@rushdb/javascript-sdk 1.11.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api/api.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import type { HttpClient } from '../network/HttpClient.js';
2
- import type { DBRecordCreationOptions, DBRecordTarget, Relation, RelationDetachOptions, RelationOptions, RelationTarget } from '../sdk/record.js';
2
+ import type { DBRecordCreationOptions, DBRecordTarget, Relation, RelationDetachOptions, RelationDirection, RelationOptions, RelationTarget } from '../sdk/record.js';
3
3
  import { DBRecordInstance, DBRecordsArrayInstance } from '../sdk/record.js';
4
4
  import type { SDKConfig } from '../sdk/types.js';
5
- import type { AnyObject, InferSchemaTypesWrite, MaybeArray, OrderDirection, Property, PropertyDraft, PropertyValuesData, Schema, SearchQuery } from '../types/index.js';
5
+ import type { AnyObject, InferSchemaTypesWrite, MaybeArray, OrderDirection, Property, PropertyDraft, PropertyValuesData, Schema, SearchQuery, Where } from '../types/index.js';
6
6
  import type { ApiResponse } from './types.js';
7
7
  import { createFetcher } from '../network/index.js';
8
8
  import { Transaction } from '../sdk/transaction.js';
@@ -177,6 +177,49 @@ export declare class RestAPI {
177
177
  * API methods for managing relations between records
178
178
  */
179
179
  relationships: {
180
+ /**
181
+ * Creates many relationships by matching source and target records by keys
182
+ * @param data - Configuration of source/target match and relation details
183
+ * @param transaction - Optional transaction for atomic operations
184
+ * @returns Promise with the API response message
185
+ */
186
+ createMany: (data: {
187
+ source: {
188
+ label: string;
189
+ key?: string;
190
+ where?: Where;
191
+ };
192
+ target: {
193
+ label: string;
194
+ key?: string;
195
+ where?: Where;
196
+ };
197
+ type?: string;
198
+ direction?: RelationDirection;
199
+ manyToMany?: boolean;
200
+ }, transaction?: Transaction | string) => Promise<ApiResponse<{
201
+ message: string;
202
+ }>>;
203
+ /**
204
+ * Deletes many relationships by matching source and target records by keys or by manyToMany filter
205
+ */
206
+ deleteMany: (data: {
207
+ source: {
208
+ label: string;
209
+ key?: string;
210
+ where?: Where;
211
+ };
212
+ target: {
213
+ label: string;
214
+ key?: string;
215
+ where?: Where;
216
+ };
217
+ type?: string;
218
+ direction?: RelationDirection;
219
+ manyToMany?: boolean;
220
+ }, transaction?: Transaction | string) => Promise<ApiResponse<{
221
+ message: string;
222
+ }>>;
180
223
  /**
181
224
  * Searches for relations matching the query criteria
182
225
  * @param searchQuery - Query to identify relations
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Se=Object.create;var H=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var be=(s,e)=>{for(var t in e)H(s,t,{get:e[t],enumerable:!0})},ne=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Te(e))!we.call(s,r)&&r!==t&&H(s,r,{get:()=>e[r],enumerable:!(n=Re(e,r))||n.enumerable});return s};var se=(s,e,t)=>(t=s!=null?Se(De(s)):{},ne(e||!s||!s.__esModule?H(t,"default",{value:s,enumerable:!0}):t,s)),Ie=s=>ne(H({},"__esModule",{value:!0}),s);var Me={};be(Me,{DBRecordInstance:()=>g,DBRecordsArrayInstance:()=>A,EmptyTargetError:()=>w,HttpClient:()=>O,HttpClientResponse:()=>v,Model:()=>re,NonUniqueResultError:()=>k,RestAPI:()=>_,RushDB:()=>D,Transaction:()=>B,UniquenessError:()=>E,default:()=>He,extractMixedPropertiesFromToken:()=>ee,idToDate:()=>Z,idToTimestamp:()=>K,initSDK:()=>te,mergeDefaultsWithPayload:()=>U,parseConfig:()=>G,pickUniqFieldsFromRecord:()=>N,pickUniqFieldsFromRecords:()=>J,validateInteger:()=>X});module.exports=Ie(Me);var O=class s{makeRequest(e,{headers:t,method:n,protocol:r,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(s.TIMEOUT_ERROR_CODE);return e.code=s.TIMEOUT_ERROR_CODE,e}};O.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];O.TIMEOUT_ERROR_CODE="ETIMEDOUT";var M=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},v=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var V=se(require("http"),1),Y=se(require("https"),1);var xe="string",Oe="datetime",Pe="boolean",Ee="number",Ae="null",Be="vector",ae=[xe,Oe,Pe,Ee,Ae,Be];var ie=V.default||V,ce=Y.default||Y,_e=new ie.Agent({keepAlive:!0}),Ce=new ce.Agent({keepAlive:!0}),F=class extends O{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:n,protocol:r,requestData:a,timeout:o}){let i=new URL(e),c=r==="http"||i.protocol==="http:",d=this._agent;return d||(d=c?_e:Ce),new Promise((p,h)=>{let l=(c?ie:ce).request({agent:d,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:n,path:i.pathname+i.search,port:i.port});l.setTimeout(o!=null?o:8e4,()=>{l.destroy(O.makeTimeoutError())}),l.on("response",m=>{p(new W(m))}),l.on("error",m=>{h(m)}),l.once("socket",m=>{let I=a?JSON.stringify(a):"";m.connecting?m.once(c?"connect":"secureConnect",()=>{l.write(I),l.end()}):(l.write(I),l.end())})})}},W=class extends M{constructor(e){super(e.statusCode,e.headers||{}),this._res=e}getRawResponse(){return this._res}toStream(e){return this._res.once("end",()=>e()),this._res}toJSON(){return new Promise((e,t)=>{let n="";this._res.setEncoding("utf8"),this._res.on("data",r=>{n+=r}),this._res.once("end",()=>{try{e(JSON.parse(n))}catch(r){t(r)}})})}};var R=s=>typeof s=="object"&&Array.isArray(s)&&s!==null,S=s=>s!==null&&Object.prototype.toString.call(s)==="[object Object]",q=s=>S(s)&&Object.keys(s).length===0,de=s=>typeof s=="number"||typeof s=="string"||typeof s=="boolean"||s===null;function qe(s,e){let t={...s};return e.forEach(n=>{delete t[n]}),t}var L=s=>S(s)?qe(s,["__label","__id","__proptypes"]):s,C=s=>R(s)?s.map(C):S(s)?Object.fromEntries(Object.entries(s).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,C(t)])):s,Q=s=>R(s)?s.every(de):de(s),$=s=>S(s)&&Object.values(s).every(Q),P=s=>typeof s=="string",T=s=>{if(typeof s=="string"){if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1}return R(s)&&s.length===0||S(s)&&Object.keys(s).length===0?!1:!!s};var z=["httpClient","timeout","host","port","protocol","url","logger","options"],pe={initial:"in",extended:"ex",fullFeatured:"ff"};var E=class s extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,s.prototype)}},w=class s extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,s.prototype)}},k=class s extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,s.prototype)}};var U=async(s,e)=>{let t=Object.entries(s).map(async([a,o])=>o.default&&typeof o.default<"u"&&typeof e[a]>"u"?{key:a,value:typeof o.default=="function"?await o.default():o.default}:{key:a,value:void 0});return{...(await Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},N=(s,e)=>Object.entries(e).filter(([t])=>{var n;return(n=s[t])==null?void 0:n.uniq}).reduce((t,[n,r])=>(n in s&&(t[n]=r),t),{}),J=(s,e,t)=>{let n={},r=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[o])=>(a[o]=!0,a),{});return s.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in r)if(n[o]){if(n[o].includes(i))throw new E(t,{[o]:i});n[o]=[...n[o],i]}else n[o]=[i]})}),n},G=s=>{if(!s)return{};if(!S(s))throw new Error("Config must be an object");if(Object.keys(s).filter(t=>!z.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${z.join(", ")}`);return s};function X(s,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${s} must be an integer`)}return e}function K(s){let e=s.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function Z(s){return new Date(K(s))}function ee(s){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=s.match(e);if(!t)return[null,s];let[,n,r,a]=t,i=Object.entries(pe).find(([l,m])=>m===n)[0],[c,d,p]=r.split("");return[{...{customDB:c==="1",managedDB:d==="1",selfHosted:p==="1",planType:i}},a]}var g=class{constructor(e={}){this.data=e}exists(){return T(this.data.__id)&&T(this.data.__label)}id(){if(!T(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!T(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!T(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return Z(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return K(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!T(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await D.init().records.deleteById(this.id(),e)}async update(e,t){if(!T(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return D.init().records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!T(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return D.init().records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,n){if(!T(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return D.init().records.attach({source:this.id(),target:e,options:t},n)}async detach(e,t,n){if(!T(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return D.init().records.detach({source:this.id(),target:e,options:t},n)}},A=class{constructor(e=[],t=0,n){this.data=e,this.total=t,this.searchQuery=n}};var je={"Content-Type":"application/json"},le=({httpClient:s,token:e,url:t})=>async(n,{headers:r,...a})=>{let o=await s.makeRequest(`${t}${n}`,{credentials:"omit",headers:Object.assign({...je,...r},typeof e<"u"?{token:e}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();throw new Error(`${o.getStatusCode()}`)};var B=class{constructor(e){this.id=e}async rollback(){return await D.init().tx.rollback(this.id)}async commit(){return await D.init().tx.commit(this.id)}};var he="api.rushdb.com";var ue="https",ye="/api/v1";var f=s=>s?{"x-transaction-id":s}:void 0,Ue=s=>P(s)||s instanceof B,y=s=>Ue(s)?s instanceof B?s.id:s:void 0,ge=s=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(s),b=s=>{if(P(s)&&ge(s))return s;if(s instanceof g&&s.data)return s.data.__id;if(S(s)&&"__id"in s&&ge(s.__id))return s.__id},j=s=>!(!S(s)||S(s)&&"name"in s&&!P(s.name)||S(s)&&"type"in s&&(!P(s.type)||!ae.includes(s.type))||!("value"in s)||!Q(s.value)||"metadata"in s&&!P(s.metadata)||"valueSeparator"in s&&!P(s.valueSeparator)),fe=s=>{let e=ue,t=he,n=443,r=ye;if("url"in s){let o=new URL(s.url);e=o.protocol.replace(":",""),t=o.hostname,n=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in s&&"port"in s&&"protocol"in s&&(e=s.protocol.replace(":",""),t=s.host,n=s.port),r&&!r.startsWith("/")&&(r="/"+r);let a="";return e==="http"&&n===80||e==="https"&&n===443||(a=":"+n),`${e}://${t}${a}${r}`},u=(s=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let n=0;n<s;n++){let r=Math.floor(Math.random()*e.length);t+=e[r]}return t};var _=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:n},r)=>{var h,l;let a=y(r),i=`/relationships/${b(e)}`,c={headers:Object.assign({},f(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(n==null?void 0:n.type)&&{type:n.type},...(n==null?void 0:n.direction)&&{direction:n.direction}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},detach:async({source:e,target:t,options:n},r)=>{var h,l;let a=y(r),i=`/relationships/${b(e)}`,c={headers:Object.assign({},f(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(n==null?void 0:n.typeOrTypes)&&{typeOrTypes:n.typeOrTypes},...(n==null?void 0:n.direction)&&{direction:n.direction}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},create:async({label:e,data:t,options:n},r)=>{var h,l;let a=y(r),o="/records",i={headers:Object.assign({},f(a)),method:"POST",requestData:{}},c=typeof this.logger=="function"?u():"",d=L(C(t));if(R(d)&&d.every(j))i.requestData={label:e,properties:d};else if($(d))i.requestData={label:e,data:d,options:n};else throw S(d)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let p=await this.fetcher(o,i);return(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new g(p.data):new g},createMany:async(e,t)=>{var c,d,p;let n=y(t),r="/records/import/json",a={headers:Object.assign({},f(n)),method:"POST",requestData:e},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let h=R(i.data)?(p=i.data)==null?void 0:p.map(l=>new g(l)):[];return new A(h,i.total)}return new A([])},delete:async(e,t)=>{var c,d,p;if(q(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new w("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let n=y(t),r="/records/delete",a={headers:Object.assign({},f(n)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},deleteById:async(e,t)=>{var d,p;let n=y(t),r=R(e),a=r?"/records/delete":`/records/${e}`,o={headers:Object.assign({},f(n)),method:r?"POST":"DELETE",requestData:r?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c},export:async(e,t)=>{var c,d;let n=y(t),r="/records/export/csv",a={headers:Object.assign({},f(n)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},find:async(e,t)=>{var h,l;let{id:n,...r}=e,a=y(t),o=n?`/records/${n}/search`:"/records/search",i={headers:Object.assign({},f(a)),method:"POST",requestData:r!=null?r:{}},c=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:d.data});let p=d.data.map(m=>new g(m));return new A(p,d.total,e)},findById:async(e,t)=>{var c,d;let n=y(t),r=R(e)?"/records":`/records/${e}`,a={headers:Object.assign({},f(n)),method:R(e)?"POST":"GET",requestData:R(e)?{ids:e}:void 0},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),R(e)){let p=i.data.map(h=>new g(h));return new A(p,i.total)}else return new g(i.data)},findOne:async(e,t)=>{var d,p;let n=y(t),r="/records/search",a={headers:Object.assign({},f(n)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);(p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data});let[c]=i.data;return new g(c)},findUniq:async(e,t)=>{var d,p;let n=y(t),r="/records/search",a={headers:Object.assign({},f(n)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new k(i.total,e);let[c]=i.data;return new g(c)},set:async({target:e,label:t,data:n,options:r},a)=>{var m,I;let o=y(a),c=`/records/${b(e)}`,d={headers:Object.assign({},f(o)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(n));if(R(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:r};else throw S(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(m=this.logger)==null||m.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(I=this.logger)==null||I.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new g(l.data):new g},update:async({target:e,label:t,data:n,options:r},a)=>{var m,I;let o=y(a),c=`/records/${b(e)}`,d={headers:Object.assign({},f(o)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(n));if(R(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:r};else throw S(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(m=this.logger)==null||m.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(I=this.logger)==null||I.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new g(l.data):new g}};this.relationships={find:async(e,t)=>{var p,h;let n=y(t),r=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&r.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&r.append("skip",e.skip.toString());let o=`/relationships/search${r.toString()?"?"+r.toString():""}`,i={headers:Object.assign({},f(n)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);return(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i,responseData:d.data}),d}};this.properties={delete:async(e,t)=>{var c,d;let n=y(t),r=`/properties/${e}`,a={headers:Object.assign({},f(n)),method:"DELETE"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},find:async(e,t)=>{var c,d;let n=y(t),r="/properties/search",a={headers:Object.assign({},f(n)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},findById:async(e,t)=>{var c,d;let n=y(t),r=`/properties/${e}`,a={headers:Object.assign({},f(n)),method:"GET"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},values:async(e,t,n)=>{var d,p;let r=y(n),a=`/properties/${e}/values`,o={headers:Object.assign({},f(r)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c}};this.labels={find:async(e,t)=>{var c,d;let n=y(t),r="/labels/search",a={headers:Object.assign({},f(n)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let t="/tx",n={method:"POST",requestData:S(e)&&"ttl"in e?e:{}},r=typeof this.logger=="function"?u():"";(o=this.logger)==null||o.call(this,{requestId:r,path:t,...n});let a=await this.fetcher(t,n);return(i=this.logger)==null||i.call(this,{requestId:r,path:t,...n,responseData:a.data}),new B(a.data.id)},commit:async e=>{var i,c;let n=`/tx/${y(e)}/commit`,r={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:n,...r});let o=await this.fetcher(n,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:n,...r,responseData:o.data}),o},get:async e=>{var i,c;let n=`/tx/${y(e)}`,r={method:"GET"},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:n,...r});let o=await this.fetcher(n,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:n,...r,responseData:o.data}),new B(o.data.id)},rollback:async e=>{var i,c;let n=`/tx/${y(e)}/rollback`,r={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:n,...r});let o=await this.fetcher(n,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:n,...r,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",t={method:"GET"},n=typeof this.logger=="function"?u():"";(a=this.logger)==null||a.call(this,{requestId:n,path:e,...t});let r=await this.fetcher(e,t);return(o=this.logger)==null||o.call(this,{requestId:n,path:e,...t,responseData:r.data}),r}};if(this.fetcher=null,t!=null&&t.httpClient){let n=fe(t);this.fetcher=le({httpClient:t.httpClient,token:e,url:n})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var n;if(e instanceof g){let r=b(e);if(!r)throw new w(`${t} error: Target id is empty`);return[r]}if(R(e)&&e.every(r=>r instanceof g)){let r=e.map(b).filter(T);if(!r.length)throw new w(`${t} error: Target ids are empty`);return r}if(e instanceof A){let r=(n=e.data)==null?void 0:n.map(b).filter(T);if(!(r!=null&&r.length))throw new w(`${t} error: Target ids are empty`);return r}if(S(e)&&"__id"in e)return[e.__id];if(R(e)&&e.every(r=>S(r)&&"__id"in r)){let r=e.map(b).filter(T);if(!r.length)throw new w(`${t} error: Target ids are empty`);return r}return R(e)?e:P(e)?[e]:[]}};var me,x=class x extends _{constructor(e,t){var a;let n=G(t);super(e,{...n,httpClient:(a=n.httpClient)!=null?a:me}),x.instance=this;let[r]=ee(e!=null?e:"");this.initializeSync(r,e,n)}initializeSync(e,t,n){let r=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;x.state={initialized:!0,debug:!1,timeout:X("timeout",n==null?void 0:n.timeout,8e4),token:t,...r&&{serverSettings:r}}}static init(){if(x.instance)return x.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return x.instance}static isInitialized(){return x.instance!==null}toDBRecordInstance(e){return new g(e)}};x.instance=null,x.state={initialized:!1,debug:!1,timeout:8e4};var D=x,te=s=>{me=s};var re=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}async getRushDBInstance(){if(D.getInstance())return D.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}async toDBRecordInstance(e){try{return(await this.getRushDBInstance()).toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,t){let n=e!=null?e:{};return(await this.getRushDBInstance()).records.find({...n,labels:[this.label]},t)}async findOne(e,t){let n=e!=null?e:{};return(await this.getRushDBInstance()).records.findOne({...n,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){let n=e!=null?e:{};return(await this.getRushDBInstance()).records.findUniq({...n,labels:[this.label]},t)}async create(e,t){var i;let n=await U(this.schema,e),r=N(this.schema,n),a=T(r),o=await this.getRushDBInstance();if(a){let c=t!=null?t:await o.tx.begin(),d=await this.find({where:r},c),p=typeof t<"u";if(!((i=d==null?void 0:d.data)!=null&&i.length)){let l=await o.records.create({label:this.label,data:n},c);return p||await c.commit(),l}else throw p||await c.commit(),new E(this.label,r)}return await o.records.create({label:this.label,data:n},t)}async attach({source:e,target:t,options:n},r){return await(await this.getRushDBInstance()).records.attach({source:e,target:t,options:n},r)}async detach({source:e,target:t,options:n},r){return await(await this.getRushDBInstance()).records.detach({source:e,target:t,options:n},r)}async handleSetOrUpdate(e,t,n,r){var c,d;if(R(t)&&t.every(j))throw new Error(`Model.${n} with Array<PropertyDraft> as payload is not implemented yet.`);let a=await this.getRushDBInstance(),o=await U(this.schema,t),i=N(this.schema,o);if(!q(i)){let p=r!=null?r:await a.tx.begin(),h=await this.find({where:i},p),l=typeof r<"u";if(!((c=h==null?void 0:h.data)!=null&&c.length)||h.data.length===1&&((d=h.data[0])==null?void 0:d.id())===b(e)){let I=await a.records[n]({target:e,label:this.label,data:o},p);return l||await p.commit(),I}else throw l||await p.commit(),new E(this.label,i)}return await a.records[n]({label:this.label,target:e,data:o},r)}async set(e,t,n){return await this.handleSetOrUpdate(e,t,"set",n)}async update(e,t,n){return await this.handleSetOrUpdate(e,t,"update",n)}async createMany(e,t){var o;let n=await this.getRushDBInstance(),r=typeof t<"u",a=t!=null?t:await n.tx.begin();try{let i=await Promise.all(e.map(async p=>await U(this.schema,p))),c=J(i,this.schema,this.label);if(!q(c)){let p=Object.entries(c).map(([l,m])=>({[l]:{$in:m}})),h=await this.find({where:{$or:p}},a);if((o=h==null?void 0:h.data)!=null&&o.length)throw new E(this.label,Object.keys(c))}let d=await n.records.createMany({label:this.label,data:i},a);return r||await a.commit(),d}catch(i){throw r||await a.rollback(),i}}async delete(e,t){if(q(e.where))throw new w(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return await(await this.getRushDBInstance()).records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await(await this.getRushDBInstance()).records.deleteById(e,t)}};te(new F);var He=D;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,extractMixedPropertiesFromToken,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
1
+ "use strict";var Se=Object.create;var M=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var be=(n,e)=>{for(var t in e)M(n,t,{get:e[t],enumerable:!0})},se=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Te(e))!we.call(n,r)&&r!==t&&M(n,r,{get:()=>e[r],enumerable:!(s=Re(e,r))||s.enumerable});return n};var ne=(n,e,t)=>(t=n!=null?Se(De(n)):{},se(e||!n||!n.__esModule?M(t,"default",{value:n,enumerable:!0}):t,n)),Ie=n=>se(M({},"__esModule",{value:!0}),n);var He={};be(He,{DBRecordInstance:()=>y,DBRecordsArrayInstance:()=>A,EmptyTargetError:()=>w,HttpClient:()=>O,HttpClientResponse:()=>v,Model:()=>re,NonUniqueResultError:()=>k,RestAPI:()=>_,RushDB:()=>D,Transaction:()=>B,UniquenessError:()=>E,default:()=>Me,extractMixedPropertiesFromToken:()=>ee,idToDate:()=>Z,idToTimestamp:()=>W,initSDK:()=>te,mergeDefaultsWithPayload:()=>U,parseConfig:()=>G,pickUniqFieldsFromRecord:()=>N,pickUniqFieldsFromRecords:()=>J,validateInteger:()=>X});module.exports=Ie(He);var O=class n{makeRequest(e,{headers:t,method:s,protocol:r,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};O.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];O.TIMEOUT_ERROR_CODE="ETIMEDOUT";var H=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},v=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var V=ne(require("http"),1),Y=ne(require("https"),1);var xe="string",Oe="datetime",Pe="boolean",Ee="number",Ae="null",Be="vector",ae=[xe,Oe,Pe,Ee,Ae,Be];var ie=V.default||V,ce=Y.default||Y,_e=new ie.Agent({keepAlive:!0}),Ce=new ce.Agent({keepAlive:!0}),F=class extends O{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:s,protocol:r,requestData:a,timeout:o}){let i=new URL(e),c=r==="http"||i.protocol==="http:",d=this._agent;return d||(d=c?_e:Ce),new Promise((p,h)=>{let l=(c?ie:ce).request({agent:d,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:s,path:i.pathname+i.search,port:i.port});l.setTimeout(o!=null?o:8e4,()=>{l.destroy(O.makeTimeoutError())}),l.on("response",m=>{p(new K(m))}),l.on("error",m=>{h(m)}),l.once("socket",m=>{let I=a?JSON.stringify(a):"";m.connecting?m.once(c?"connect":"secureConnect",()=>{l.write(I),l.end()}):(l.write(I),l.end())})})}},K=class extends H{constructor(e){super(e.statusCode,e.headers||{}),this._res=e}getRawResponse(){return this._res}toStream(e){return this._res.once("end",()=>e()),this._res}toJSON(){return new Promise((e,t)=>{let s="";this._res.setEncoding("utf8"),this._res.on("data",r=>{s+=r}),this._res.once("end",()=>{try{e(JSON.parse(s))}catch(r){t(r)}})})}};var R=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,S=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",q=n=>S(n)&&Object.keys(n).length===0,de=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function qe(n,e){let t={...n};return e.forEach(s=>{delete t[s]}),t}var L=n=>S(n)?qe(n,["__label","__id","__proptypes"]):n,C=n=>R(n)?n.map(C):S(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,C(t)])):n,Q=n=>R(n)?n.every(de):de(n),$=n=>S(n)&&Object.values(n).every(Q),P=n=>typeof n=="string",T=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return R(n)&&n.length===0||S(n)&&Object.keys(n).length===0?!1:!!n};var z=["httpClient","timeout","host","port","protocol","url","logger","options"],pe={initial:"in",extended:"ex",fullFeatured:"ff"};var E=class n extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,n.prototype)}},w=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},k=class n extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,n.prototype)}};var U=async(n,e)=>{let t=Object.entries(n).map(async([a,o])=>o.default&&typeof o.default<"u"&&typeof e[a]>"u"?{key:a,value:typeof o.default=="function"?await o.default():o.default}:{key:a,value:void 0});return{...(await Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},N=(n,e)=>Object.entries(e).filter(([t])=>{var s;return(s=n[t])==null?void 0:s.uniq}).reduce((t,[s,r])=>(s in n&&(t[s]=r),t),{}),J=(n,e,t)=>{let s={},r=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[o])=>(a[o]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in r)if(s[o]){if(s[o].includes(i))throw new E(t,{[o]:i});s[o]=[...s[o],i]}else s[o]=[i]})}),s},G=n=>{if(!n)return{};if(!S(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!z.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${z.join(", ")}`);return n};function X(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function W(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function Z(n){return new Date(W(n))}function ee(n){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=n.match(e);if(!t)return[null,n];let[,s,r,a]=t,i=Object.entries(pe).find(([l,m])=>m===s)[0],[c,d,p]=r.split("");return[{...{customDB:c==="1",managedDB:d==="1",selfHosted:p==="1",planType:i}},a]}var y=class{constructor(e={}){this.data=e}exists(){return T(this.data.__id)&&T(this.data.__label)}id(){if(!T(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!T(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!T(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return Z(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return W(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!T(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await D.init().records.deleteById(this.id(),e)}async update(e,t){if(!T(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return D.init().records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!T(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return D.init().records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,s){if(!T(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return D.init().records.attach({source:this.id(),target:e,options:t},s)}async detach(e,t,s){if(!T(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return D.init().records.detach({source:this.id(),target:e,options:t},s)}},A=class{constructor(e=[],t=0,s){this.data=e,this.total=t,this.searchQuery=s}};var je={"Content-Type":"application/json"},le=({httpClient:n,token:e,url:t})=>async(s,{headers:r,...a})=>{let o=await n.makeRequest(`${t}${s}`,{credentials:"omit",headers:Object.assign({...je,...r},typeof e<"u"?{token:e}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();throw new Error(`${o.getStatusCode()}`)};var B=class{constructor(e){this.id=e}async rollback(){return await D.init().tx.rollback(this.id)}async commit(){return await D.init().tx.commit(this.id)}};var he="api.rushdb.com";var ue="https",ge="/api/v1";var f=n=>n?{"x-transaction-id":n}:void 0,Ue=n=>P(n)||n instanceof B,g=n=>Ue(n)?n instanceof B?n.id:n:void 0,ye=n=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(n),b=n=>{if(P(n)&&ye(n))return n;if(n instanceof y&&n.data)return n.data.__id;if(S(n)&&"__id"in n&&ye(n.__id))return n.__id},j=n=>!(!S(n)||S(n)&&"name"in n&&!P(n.name)||S(n)&&"type"in n&&(!P(n.type)||!ae.includes(n.type))||!("value"in n)||!Q(n.value)||"metadata"in n&&!P(n.metadata)||"valueSeparator"in n&&!P(n.valueSeparator)),fe=n=>{let e=ue,t=he,s=443,r=ge;if("url"in n){let o=new URL(n.url);e=o.protocol.replace(":",""),t=o.hostname,s=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,s=n.port),r&&!r.startsWith("/")&&(r="/"+r);let a="";return e==="http"&&s===80||e==="https"&&s===443||(a=":"+s),`${e}://${t}${a}${r}`},u=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let s=0;s<n;s++){let r=Math.floor(Math.random()*e.length);t+=e[r]}return t};var _=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:s},r)=>{var h,l;let a=g(r),i=`/relationships/${b(e)}`,c={headers:Object.assign({},f(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(s==null?void 0:s.type)&&{type:s.type},...(s==null?void 0:s.direction)&&{direction:s.direction}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},detach:async({source:e,target:t,options:s},r)=>{var h,l;let a=g(r),i=`/relationships/${b(e)}`,c={headers:Object.assign({},f(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(s==null?void 0:s.typeOrTypes)&&{typeOrTypes:s.typeOrTypes},...(s==null?void 0:s.direction)&&{direction:s.direction}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},create:async({label:e,data:t,options:s},r)=>{var h,l;let a=g(r),o="/records",i={headers:Object.assign({},f(a)),method:"POST",requestData:{}},c=typeof this.logger=="function"?u():"",d=L(C(t));if(R(d)&&d.every(j))i.requestData={label:e,properties:d};else if($(d))i.requestData={label:e,data:d,options:s};else throw S(d)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let p=await this.fetcher(o,i);return(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new y(p.data):new y},createMany:async(e,t)=>{var c,d,p;let s=g(t),r="/records/import/json",a={headers:Object.assign({},f(s)),method:"POST",requestData:e},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let h=R(i.data)?(p=i.data)==null?void 0:p.map(l=>new y(l)):[];return new A(h,i.total)}return new A([])},delete:async(e,t)=>{var c,d,p;if(q(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new w("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let s=g(t),r="/records/delete",a={headers:Object.assign({},f(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},deleteById:async(e,t)=>{var d,p;let s=g(t),r=R(e),a=r?"/records/delete":`/records/${e}`,o={headers:Object.assign({},f(s)),method:r?"POST":"DELETE",requestData:r?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c},export:async(e,t)=>{var c,d;let s=g(t),r="/records/export/csv",a={headers:Object.assign({},f(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},find:async(e,t)=>{var h,l;let{id:s,...r}=e,a=g(t),o=s?`/records/${s}/search`:"/records/search",i={headers:Object.assign({},f(a)),method:"POST",requestData:r!=null?r:{}},c=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:d.data});let p=d.data.map(m=>new y(m));return new A(p,d.total,e)},findById:async(e,t)=>{var c,d;let s=g(t),r=R(e)?"/records":`/records/${e}`,a={headers:Object.assign({},f(s)),method:R(e)?"POST":"GET",requestData:R(e)?{ids:e}:void 0},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),R(e)){let p=i.data.map(h=>new y(h));return new A(p,i.total)}else return new y(i.data)},findOne:async(e,t)=>{var d,p;let s=g(t),r="/records/search",a={headers:Object.assign({},f(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);(p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data});let[c]=i.data;return new y(c)},findUniq:async(e,t)=>{var d,p;let s=g(t),r="/records/search",a={headers:Object.assign({},f(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new k(i.total,e);let[c]=i.data;return new y(c)},set:async({target:e,label:t,data:s,options:r},a)=>{var m,I;let o=g(a),c=`/records/${b(e)}`,d={headers:Object.assign({},f(o)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(s));if(R(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:r};else throw S(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(m=this.logger)==null||m.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(I=this.logger)==null||I.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new y(l.data):new y},update:async({target:e,label:t,data:s,options:r},a)=>{var m,I;let o=g(a),c=`/records/${b(e)}`,d={headers:Object.assign({},f(o)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(s));if(R(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:r};else throw S(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(m=this.logger)==null||m.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(I=this.logger)==null||I.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new y(l.data):new y}};this.relationships={createMany:async(e,t)=>{var c,d;let s=g(t),r="/relationships/create-many",a={headers:Object.assign({},f(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},deleteMany:async(e,t)=>{var c,d;let s=g(t),r="/relationships/delete-many",a={headers:Object.assign({},f(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},find:async(e,t)=>{var p,h;let s=g(t),r=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&r.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&r.append("skip",e.skip.toString());let o=`/relationships/search${r.toString()?"?"+r.toString():""}`,i={headers:Object.assign({},f(s)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);return(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i,responseData:d.data}),d}};this.properties={delete:async(e,t)=>{var c,d;let s=g(t),r=`/properties/${e}`,a={headers:Object.assign({},f(s)),method:"DELETE"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},find:async(e,t)=>{var c,d;let s=g(t),r="/properties/search",a={headers:Object.assign({},f(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},findById:async(e,t)=>{var c,d;let s=g(t),r=`/properties/${e}`,a={headers:Object.assign({},f(s)),method:"GET"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},values:async(e,t,s)=>{var d,p;let r=g(s),a=`/properties/${e}/values`,o={headers:Object.assign({},f(r)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c}};this.labels={find:async(e,t)=>{var c,d;let s=g(t),r="/labels/search",a={headers:Object.assign({},f(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let t="/tx",s={method:"POST",requestData:S(e)&&"ttl"in e?e:{}},r=typeof this.logger=="function"?u():"";(o=this.logger)==null||o.call(this,{requestId:r,path:t,...s});let a=await this.fetcher(t,s);return(i=this.logger)==null||i.call(this,{requestId:r,path:t,...s,responseData:a.data}),new B(a.data.id)},commit:async e=>{var i,c;let s=`/tx/${g(e)}/commit`,r={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...r});let o=await this.fetcher(s,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...r,responseData:o.data}),o},get:async e=>{var i,c;let s=`/tx/${g(e)}`,r={method:"GET"},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...r});let o=await this.fetcher(s,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...r,responseData:o.data}),new B(o.data.id)},rollback:async e=>{var i,c;let s=`/tx/${g(e)}/rollback`,r={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...r});let o=await this.fetcher(s,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...r,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",t={method:"GET"},s=typeof this.logger=="function"?u():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...t});let r=await this.fetcher(e,t);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...t,responseData:r.data}),r}};if(this.fetcher=null,t!=null&&t.httpClient){let s=fe(t);this.fetcher=le({httpClient:t.httpClient,token:e,url:s})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var s;if(e instanceof y){let r=b(e);if(!r)throw new w(`${t} error: Target id is empty`);return[r]}if(R(e)&&e.every(r=>r instanceof y)){let r=e.map(b).filter(T);if(!r.length)throw new w(`${t} error: Target ids are empty`);return r}if(e instanceof A){let r=(s=e.data)==null?void 0:s.map(b).filter(T);if(!(r!=null&&r.length))throw new w(`${t} error: Target ids are empty`);return r}if(S(e)&&"__id"in e)return[e.__id];if(R(e)&&e.every(r=>S(r)&&"__id"in r)){let r=e.map(b).filter(T);if(!r.length)throw new w(`${t} error: Target ids are empty`);return r}return R(e)?e:P(e)?[e]:[]}};var me,x=class x extends _{constructor(e,t){var a;let s=G(t);super(e,{...s,httpClient:(a=s.httpClient)!=null?a:me}),x.instance=this;let[r]=ee(e!=null?e:"");this.initializeSync(r,e,s)}initializeSync(e,t,s){let r=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;x.state={initialized:!0,debug:!1,timeout:X("timeout",s==null?void 0:s.timeout,8e4),token:t,...r&&{serverSettings:r}}}static init(){if(x.instance)return x.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return x.instance}static isInitialized(){return x.instance!==null}toDBRecordInstance(e){return new y(e)}};x.instance=null,x.state={initialized:!1,debug:!1,timeout:8e4};var D=x,te=n=>{me=n};var re=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}async getRushDBInstance(){if(D.getInstance())return D.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}async toDBRecordInstance(e){try{return(await this.getRushDBInstance()).toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,t){let s=e!=null?e:{};return(await this.getRushDBInstance()).records.find({...s,labels:[this.label]},t)}async findOne(e,t){let s=e!=null?e:{};return(await this.getRushDBInstance()).records.findOne({...s,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){let s=e!=null?e:{};return(await this.getRushDBInstance()).records.findUniq({...s,labels:[this.label]},t)}async create(e,t){var i;let s=await U(this.schema,e),r=N(this.schema,s),a=T(r),o=await this.getRushDBInstance();if(a){let c=t!=null?t:await o.tx.begin(),d=await this.find({where:r},c),p=typeof t<"u";if(!((i=d==null?void 0:d.data)!=null&&i.length)){let l=await o.records.create({label:this.label,data:s},c);return p||await c.commit(),l}else throw p||await c.commit(),new E(this.label,r)}return await o.records.create({label:this.label,data:s},t)}async attach({source:e,target:t,options:s},r){return await(await this.getRushDBInstance()).records.attach({source:e,target:t,options:s},r)}async detach({source:e,target:t,options:s},r){return await(await this.getRushDBInstance()).records.detach({source:e,target:t,options:s},r)}async handleSetOrUpdate(e,t,s,r){var c,d;if(R(t)&&t.every(j))throw new Error(`Model.${s} with Array<PropertyDraft> as payload is not implemented yet.`);let a=await this.getRushDBInstance(),o=await U(this.schema,t),i=N(this.schema,o);if(!q(i)){let p=r!=null?r:await a.tx.begin(),h=await this.find({where:i},p),l=typeof r<"u";if(!((c=h==null?void 0:h.data)!=null&&c.length)||h.data.length===1&&((d=h.data[0])==null?void 0:d.id())===b(e)){let I=await a.records[s]({target:e,label:this.label,data:o},p);return l||await p.commit(),I}else throw l||await p.commit(),new E(this.label,i)}return await a.records[s]({label:this.label,target:e,data:o},r)}async set(e,t,s){return await this.handleSetOrUpdate(e,t,"set",s)}async update(e,t,s){return await this.handleSetOrUpdate(e,t,"update",s)}async createMany(e,t){var o;let s=await this.getRushDBInstance(),r=typeof t<"u",a=t!=null?t:await s.tx.begin();try{let i=await Promise.all(e.map(async p=>await U(this.schema,p))),c=J(i,this.schema,this.label);if(!q(c)){let p=Object.entries(c).map(([l,m])=>({[l]:{$in:m}})),h=await this.find({where:{$or:p}},a);if((o=h==null?void 0:h.data)!=null&&o.length)throw new E(this.label,Object.keys(c))}let d=await s.records.createMany({label:this.label,data:i},a);return r||await a.commit(),d}catch(i){throw r||await a.rollback(),i}}async delete(e,t){if(q(e.where))throw new w(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return await(await this.getRushDBInstance()).records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await(await this.getRushDBInstance()).records.deleteById(e,t)}};te(new F);var Me=D;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,extractMixedPropertiesFromToken,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var De=Object.defineProperty,be=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var ee=(s,e,t)=>e in s?De(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,p=(s,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(s,t,e[t]);if(M)for(var t of M(e))re.call(e,t)&&ee(s,t,e[t]);return s},y=(s,e)=>be(s,we(e));var $=(s,e)=>{var t={};for(var r in s)te.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&M)for(var r of M(s))e.indexOf(r)<0&&re.call(s,r)&&(t[r]=s[r]);return t};var h=(s,e,t)=>new Promise((r,n)=>{var a=c=>{try{o(t.next(c))}catch(d){n(d)}},i=c=>{try{o(t.throw(c))}catch(d){n(d)}},o=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,i);o((t=t.apply(s,e)).next())});var Ie="string",xe="datetime",Oe="boolean",Pe="number",Ee="null",Ae="vector",se=[Ie,xe,Oe,Pe,Ee,Ae];var P=class s{makeRequest(e,{headers:t,method:r,protocol:n,requestData:a,timeout:i}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(s.TIMEOUT_ERROR_CODE);return e.code=s.TIMEOUT_ERROR_CODE,e}};P.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];P.TIMEOUT_ERROR_CODE="ETIMEDOUT";var L=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},Q=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var N=class s extends P{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=s.makeFetchWithAbortTimeout(e):this._fetchFn=s.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,n)=>{let a,i=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(P.makeTimeoutError())},n)}),o=e(t,r);return Promise.race([o,i]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,n)=>h(this,null,function*(){let a=new AbortController,i=setTimeout(()=>{i=null,a.abort(P.makeTimeoutError())},n);try{return yield e(t,y(p({},r),{signal:a.signal}))}catch(o){throw o.name==="AbortError"?P.makeTimeoutError():o}finally{i&&clearTimeout(i)}})}makeRequest(o,c){return h(this,arguments,function*(e,{headers:t,method:r,protocol:n,requestData:a,timeout:i}){let d=r=="POST"||r=="PUT"||r=="PATCH",l=JSON.stringify(a)||(d?"":void 0),u=yield this._fetchFn(e,{body:l,headers:t,method:r},i!=null?i:8e4);return new z(u)})}},z=class s extends L{constructor(e){super(e.status,s._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let t={};for(let r of e){if(!Array.isArray(r)||r.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");t[r[0]]=r[1]}return t}};var w=s=>typeof s=="object"&&Array.isArray(s)&&s!==null,b=s=>s!==null&&Object.prototype.toString.call(s)==="[object Object]",k=s=>b(s)&&Object.keys(s).length===0,ae=s=>typeof s=="number"||typeof s=="string"||typeof s=="boolean"||s===null;function Be(s,e){let t=p({},s);return e.forEach(r=>{delete t[r]}),t}var W=s=>b(s)?Be(s,["__label","__id","__proptypes"]):s,j=s=>w(s)?s.map(j):b(s)?Object.fromEntries(Object.entries(s).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,j(t)])):s,J=s=>w(s)?s.every(ae):ae(s),K=s=>b(s)&&Object.values(s).every(J),B=s=>typeof s=="string",I=s=>{if(typeof s=="string"){if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1}return w(s)&&s.length===0||b(s)&&Object.keys(s).length===0?!1:!!s};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],oe={initial:"in",extended:"ex",fullFeatured:"ff"};var _=class s extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,s.prototype)}},E=class s extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,s.prototype)}},V=class s extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,s.prototype)}};var Y=(s,e)=>h(void 0,null,function*(){let t=Object.entries(s).map(o=>h(void 0,[o],function*([a,i]){return i.default&&typeof i.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof i.default=="function"?yield i.default():i.default}:{key:a,value:void 0}})),n=(yield Promise.all(t)).reduce((a,{key:i,value:o})=>(o!==void 0&&(a[i]=o),a),{});return p(p({},n),e)}),Z=(s,e)=>Object.entries(e).filter(([t])=>{var r;return(r=s[t])==null?void 0:r.uniq}).reduce((t,[r,n])=>(r in s&&(t[r]=n),t),{}),ie=(s,e,t)=>{let r={},n=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[i])=>(a[i]=!0,a),{});return s.forEach(a=>{Object.entries(a).forEach(([i,o])=>{if(i in n)if(r[i]){if(r[i].includes(o))throw new _(t,{[i]:o});r[i]=[...r[i],o]}else r[i]=[o]})}),r},ce=s=>{if(!s)return{};if(!b(s))throw new Error("Config must be an object");if(Object.keys(s).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return s};function de(s,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${s} must be an integer`)}return e}function X(s){let e=s.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function pe(s){return new Date(X(s))}function le(s){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=s.match(e);if(!t)return[null,s];let[,r,n,a]=t,o=Object.entries(oe).find(([m,f])=>f===r)[0],[c,d,l]=n.split("");return[p({},{customDB:c==="1",managedDB:d==="1",selfHosted:l==="1",planType:o}),a]}var T=class{constructor(e={}){this.data=e}exists(){return I(this.data.__id)&&I(this.data.__label)}id(){if(!I(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!I(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!I(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return pe(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return X(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield x.init().records.deleteById(this.id(),e)})}update(e,t){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return x.init().records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return x.init().records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return x.init().records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return x.init().records.detach({source:this.id(),target:e,options:t},r)})}},C=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var _e={"Content-Type":"application/json"},he=({httpClient:s,token:e,url:t})=>(r,i)=>h(void 0,null,function*(){var o=i,{headers:n}=o,a=$(o,["headers"]);let c=yield s.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},_e),n),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var q=class{constructor(e){this.id=e}rollback(){return h(this,null,function*(){return yield x.init().tx.rollback(this.id)})}commit(){return h(this,null,function*(){return yield x.init().tx.commit(this.id)})}};var ue="api.rushdb.com";var ye="https",me="/api/v1";var D=s=>s?{"x-transaction-id":s}:void 0,qe=s=>B(s)||s instanceof q,R=s=>qe(s)?s instanceof q?s.id:s:void 0,fe=s=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(s),O=s=>{if(B(s)&&fe(s))return s;if(s instanceof T&&s.data)return s.data.__id;if(b(s)&&"__id"in s&&fe(s.__id))return s.__id},U=s=>!(!b(s)||b(s)&&"name"in s&&!B(s.name)||b(s)&&"type"in s&&(!B(s.type)||!se.includes(s.type))||!("value"in s)||!J(s.value)||"metadata"in s&&!B(s.metadata)||"valueSeparator"in s&&!B(s.valueSeparator)),ge=s=>{let e=ye,t=ue,r=443,n=me;if("url"in s){let i=new URL(s.url);e=i.protocol.replace(":",""),t=i.hostname,r=parseInt(i.port||(e==="http"?"80":e==="https"?"443":""))}"host"in s&&"port"in s&&"protocol"in s&&(e=s.protocol.replace(":",""),t=s.host,r=s.port),n&&!n.startsWith("/")&&(n="/"+n);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${n}`},S=(s=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t};var H=class{constructor(e,t){this.records={attach:(a,i)=>h(this,[a,i],function*({source:e,target:t,options:r},n){var f,g;let o=R(n),d=`/relationships/${O(e)}`,l={headers:Object.assign({},D(o)),method:"POST",requestData:p(p({targetIds:this._extractTargetIds(t,"Attach")},(r==null?void 0:r.type)&&{type:r.type}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(f=this.logger)==null||f.call(this,p({requestId:u,path:d},l));let m=yield this.fetcher(d,l);return(g=this.logger)==null||g.call(this,y(p({requestId:u,path:d},l),{responseData:m.data})),m}),detach:(a,i)=>h(this,[a,i],function*({source:e,target:t,options:r},n){var f,g;let o=R(n),d=`/relationships/${O(e)}`,l={headers:Object.assign({},D(o)),method:"PUT",requestData:p(p({targetIds:this._extractTargetIds(t,"Detach")},(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(f=this.logger)==null||f.call(this,p({requestId:u,path:d},l));let m=yield this.fetcher(d,l);return(g=this.logger)==null||g.call(this,y(p({requestId:u,path:d},l),{responseData:m.data})),m}),create:(a,i)=>h(this,[a,i],function*({label:e,data:t,options:r},n){var f,g;let o=R(n),c="/records",d={headers:Object.assign({},D(o)),method:"POST",requestData:{}},l=typeof this.logger=="function"?S():"",u=W(j(t));if(w(u)&&u.every(U))d.requestData={label:e,properties:u};else if(K(u))d.requestData={label:e,data:u,options:r};else throw b(u)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(f=this.logger)==null||f.call(this,p({requestId:l,path:c},d));let m=yield this.fetcher(c,d);return(g=this.logger)==null||g.call(this,y(p({requestId:l,path:c},d),{responseData:m.data})),m!=null&&m.success&&(m!=null&&m.data)?new T(m.data):new T}),createMany:(e,t)=>h(this,null,function*(){var c,d,l;let r=R(t),n="/records/import/json",a={headers:Object.assign({},D(r)),method:"POST",requestData:e},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o!=null&&o.success&&(o!=null&&o.data)){let u=w(o.data)?(l=o.data)==null?void 0:l.map(m=>new T(m)):[];return new C(u,o.total)}return new C([])}),delete:(e,t)=>h(this,null,function*(){var c,d,l;if(k(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new E("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=R(t),n="/records/delete",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(l=this.logger)==null||l.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),deleteById:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),n=w(e),a=n?"/records/delete":`/records/${e}`,i={headers:Object.assign({},D(r)),method:n?"POST":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:e}}}:void 0},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:a},i));let c=yield this.fetcher(a,i);return(l=this.logger)==null||l.call(this,y(p({requestId:o,path:a},i),{responseData:c.data})),c}),export:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n="/records/export/csv",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),find:(e,t)=>h(this,null,function*(){var m,f;let u=e,{id:r}=u,n=$(u,["id"]),a=R(t),i=r?`/records/${r}/search`:"/records/search",o={headers:Object.assign({},D(a)),method:"POST",requestData:n!=null?n:{}},c=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:c,path:i},o));let d=yield this.fetcher(i,o);(f=this.logger)==null||f.call(this,y(p({requestId:c,path:i},o),{responseData:d.data}));let l=d.data.map(g=>new T(g));return new C(l,d.total,e)}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n=w(e)?"/records":`/records/${e}`,a={headers:Object.assign({},D(r)),method:w(e)?"POST":"GET",requestData:w(e)?{ids:e}:void 0},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),w(e)){let l=o.data.map(u=>new T(u));return new C(l,o.total)}else return new T(o.data)}),findOne:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),n="/records/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);(l=this.logger)==null||l.call(this,y(p({requestId:i,path:n},a),{responseData:o.data}));let[c]=o.data;return new T(c)}),findUniq:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),n="/records/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);if((l=this.logger)==null||l.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),typeof o.total!="undefined"&&o.total>1)throw new V(o.total,e);let[c]=o.data;return new T(c)}),set:(i,o)=>h(this,[i,o],function*({target:e,label:t,data:r,options:n},a){var F,v;let c=R(a),l=`/records/${O(e)}`,u={headers:Object.assign({},D(c)),method:"PUT",requestData:{}},m=typeof this.logger=="function"?S():"",f=W(j(r));if(w(f)&&f.every(U))u.requestData={label:t,properties:f};else if(K(f))u.requestData={label:t,data:f,options:n};else throw b(f)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(F=this.logger)==null||F.call(this,p({requestId:m,path:l},u));let g=yield this.fetcher(l,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:l},u),{responseData:g.data})),g!=null&&g.success&&(g!=null&&g.data)?new T(g.data):new T}),update:(i,o)=>h(this,[i,o],function*({target:e,label:t,data:r,options:n},a){var F,v;let c=R(a),l=`/records/${O(e)}`,u={headers:Object.assign({},D(c)),method:"PATCH",requestData:{}},m=typeof this.logger=="function"?S():"",f=W(j(r));if(w(f)&&f.every(U))u.requestData={label:t,properties:f};else if(K(f))u.requestData={label:t,data:f,options:n};else throw b(f)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(F=this.logger)==null||F.call(this,p({requestId:m,path:l},u));let g=yield this.fetcher(l,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:l},u),{responseData:g.data})),g!=null&&g.success&&(g!=null&&g.data)?new T(g.data):new T})};this.relationships={find:(e,t)=>h(this,null,function*(){var l,u;let r=R(t),n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&n.append("skip",e.skip.toString());let i=`/relationships/search${n.toString()?"?"+n.toString():""}`,o={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?S():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:i},o));let d=yield this.fetcher(i,o);return(u=this.logger)==null||u.call(this,y(p({requestId:c,path:i},o),{responseData:d.data})),d})};this.properties={delete:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n=`/properties/${e}`,a={headers:Object.assign({},D(r)),method:"DELETE"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),find:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n="/properties/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n=`/properties/${e}`,a={headers:Object.assign({},D(r)),method:"GET"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),values:(e,t,r)=>h(this,null,function*(){var d,l;let n=R(r),a=`/properties/${e}/values`,i={headers:Object.assign({},D(n)),method:"POST",requestData:t!=null?t:{}},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:a},i));let c=yield this.fetcher(a,i);return(l=this.logger)==null||l.call(this,y(p({requestId:o,path:a},i),{responseData:c.data})),c})};this.labels={find:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n="/labels/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o})};this.tx={begin:e=>h(this,null,function*(){var i,o;let t="/tx",r={method:"POST",requestData:b(e)&&"ttl"in e?e:{}},n=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,p({requestId:n,path:t},r));let a=yield this.fetcher(t,r);return(o=this.logger)==null||o.call(this,y(p({requestId:n,path:t},r),{responseData:a.data})),new q(a.data.id)}),commit:e=>h(this,null,function*(){var o,c;let r=`/tx/${R(e)}/commit`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},n));let i=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:i.data})),i}),get:e=>h(this,null,function*(){var o,c;let r=`/tx/${R(e)}`,n={method:"GET"},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},n));let i=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:i.data})),new q(i.data.id)}),rollback:e=>h(this,null,function*(){var o,c;let r=`/tx/${R(e)}/rollback`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},n));let i=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:i.data})),i})};this.settings={get:()=>h(this,null,function*(){var a,i;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:r,path:e},t));let n=yield this.fetcher(e,t);return(i=this.logger)==null||i.call(this,y(p({requestId:r,path:e},t),{responseData:n.data})),n})};if(this.fetcher=null,t!=null&&t.httpClient){let r=ge(t);this.fetcher=he({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof T){let n=O(e);if(!n)throw new E(`${t} error: Target id is empty`);return[n]}if(w(e)&&e.every(n=>n instanceof T)){let n=e.map(O).filter(I);if(!n.length)throw new E(`${t} error: Target ids are empty`);return n}if(e instanceof C){let n=(r=e.data)==null?void 0:r.map(O).filter(I);if(!(n!=null&&n.length))throw new E(`${t} error: Target ids are empty`);return n}if(b(e)&&"__id"in e)return[e.__id];if(w(e)&&e.every(n=>b(n)&&"__id"in n)){let n=e.map(O).filter(I);if(!n.length)throw new E(`${t} error: Target ids are empty`);return n}return w(e)?e:B(e)?[e]:[]}};var Se,A=class A extends H{constructor(e,t){var a;let r=ce(t);super(e,y(p({},r),{httpClient:(a=r.httpClient)!=null?a:Se})),A.instance=this;let[n]=le(e!=null?e:"");this.initializeSync(n,e,r)}initializeSync(e,t,r){let n=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;A.state=p({initialized:!0,debug:!1,timeout:de("timeout",r==null?void 0:r.timeout,8e4),token:t},n&&{serverSettings:n})}static init(){if(A.instance)return A.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return A.instance}static isInitialized(){return A.instance!==null}toDBRecordInstance(e){return new T(e)}};A.instance=null,A.state={initialized:!1,debug:!1,timeout:8e4};var x=A,Re=s=>{Se=s};var Te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}getRushDBInstance(){return h(this,null,function*(){if(x.getInstance())return x.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')})}toDBRecordInstance(e){return h(this,null,function*(){try{return(yield this.getRushDBInstance()).toDBRecordInstance(e)}catch(t){throw new Error("No RushDB instance was provided during model initialization.")}})}find(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.find(y(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findOne(y(p({},r),{labels:[this.label]}),t)})}findById(e,t){return h(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findUniq(y(p({},r),{labels:[this.label]}),t)})}create(e,t){return h(this,null,function*(){var o;let r=yield Y(this.schema,e),n=Z(this.schema,r),a=I(n),i=yield this.getRushDBInstance();if(a){let c=t!=null?t:yield i.tx.begin(),d=yield this.find({where:n},c),l=typeof t!="undefined";if(!((o=d==null?void 0:d.data)!=null&&o.length)){let m=yield i.records.create({label:this.label,data:r},c);return l||(yield c.commit()),m}else throw l||(yield c.commit()),new _(this.label,n)}return yield i.records.create({label:this.label,data:r},t)})}attach(a,i){return h(this,arguments,function*({source:e,target:t,options:r},n){return yield(yield this.getRushDBInstance()).records.attach({source:e,target:t,options:r},n)})}detach(a,i){return h(this,arguments,function*({source:e,target:t,options:r},n){return yield(yield this.getRushDBInstance()).records.detach({source:e,target:t,options:r},n)})}handleSetOrUpdate(e,t,r,n){return h(this,null,function*(){var c,d;if(w(t)&&t.every(U))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=yield this.getRushDBInstance(),i=yield Y(this.schema,t),o=Z(this.schema,i);if(!k(o)){let l=n!=null?n:yield a.tx.begin(),u=yield this.find({where:o},l),m=typeof n!="undefined";if(!((c=u==null?void 0:u.data)!=null&&c.length)||u.data.length===1&&((d=u.data[0])==null?void 0:d.id())===O(e)){let g=yield a.records[r]({target:e,label:this.label,data:i},l);return m||(yield l.commit()),g}else throw m||(yield l.commit()),new _(this.label,o)}return yield a.records[r]({label:this.label,target:e,data:i},n)})}set(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return h(this,null,function*(){var i;let r=yield this.getRushDBInstance(),n=typeof t!="undefined",a=t!=null?t:yield r.tx.begin();try{let o=yield Promise.all(e.map(l=>h(this,null,function*(){return yield Y(this.schema,l)}))),c=ie(o,this.schema,this.label);if(!k(c)){let l=Object.entries(c).map(([m,f])=>({[m]:{$in:f}})),u=yield this.find({where:{$or:l}},a);if((i=u==null?void 0:u.data)!=null&&i.length)throw new _(this.label,Object.keys(c))}let d=yield r.records.createMany({label:this.label,data:o},a);return n||(yield a.commit()),d}catch(o){throw n||(yield a.rollback()),o}})}delete(e,t){return h(this,null,function*(){if(k(e.where))throw new E(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return yield(yield this.getRushDBInstance()).records.delete(y(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return h(this,null,function*(){return yield(yield this.getRushDBInstance()).records.deleteById(e,t)})}};Re(new N);var Ft=x;export{T as DBRecordInstance,C as DBRecordsArrayInstance,E as EmptyTargetError,P as HttpClient,Q as HttpClientResponse,Te as Model,V as NonUniqueResultError,H as RestAPI,x as RushDB,q as Transaction,_ as UniquenessError,Ft as default,le as extractMixedPropertiesFromToken,pe as idToDate,X as idToTimestamp,Re as initSDK,Y as mergeDefaultsWithPayload,ce as parseConfig,Z as pickUniqFieldsFromRecord,ie as pickUniqFieldsFromRecords,de as validateInteger};
1
+ var De=Object.defineProperty,be=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var ee=(n,e,t)=>e in n?De(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(n,t,e[t]);if(M)for(var t of M(e))re.call(e,t)&&ee(n,t,e[t]);return n},y=(n,e)=>be(n,we(e));var $=(n,e)=>{var t={};for(var r in n)te.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&M)for(var r of M(n))e.indexOf(r)<0&&re.call(n,r)&&(t[r]=n[r]);return t};var l=(n,e,t)=>new Promise((r,s)=>{var a=c=>{try{o(t.next(c))}catch(d){s(d)}},i=c=>{try{o(t.throw(c))}catch(d){s(d)}},o=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,i);o((t=t.apply(n,e)).next())});var Ie="string",xe="datetime",Oe="boolean",Pe="number",Ee="null",Ae="vector",se=[Ie,xe,Oe,Pe,Ee,Ae];var P=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:i}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};P.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];P.TIMEOUT_ERROR_CODE="ETIMEDOUT";var L=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},Q=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var W=class n 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=n.makeFetchWithAbortTimeout(e):this._fetchFn=n.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,s)=>{let a,i=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(P.makeTimeoutError())},s)}),o=e(t,r);return Promise.race([o,i]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>l(this,null,function*(){let a=new AbortController,i=setTimeout(()=>{i=null,a.abort(P.makeTimeoutError())},s);try{return yield e(t,y(p({},r),{signal:a.signal}))}catch(o){throw o.name==="AbortError"?P.makeTimeoutError():o}finally{i&&clearTimeout(i)}})}makeRequest(o,c){return l(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:a,timeout:i}){let d=r=="POST"||r=="PUT"||r=="PATCH",h=JSON.stringify(a)||(d?"":void 0),u=yield this._fetchFn(e,{body:h,headers:t,method:r},i!=null?i:8e4);return new z(u)})}},z=class n extends L{constructor(e){super(e.status,n._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let t={};for(let r of e){if(!Array.isArray(r)||r.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");t[r[0]]=r[1]}return t}};var w=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,b=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",k=n=>b(n)&&Object.keys(n).length===0,ae=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function Be(n,e){let t=p({},n);return e.forEach(r=>{delete t[r]}),t}var N=n=>b(n)?Be(n,["__label","__id","__proptypes"]):n,j=n=>w(n)?n.map(j):b(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,j(t)])):n,J=n=>w(n)?n.every(ae):ae(n),K=n=>b(n)&&Object.values(n).every(J),B=n=>typeof n=="string",I=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return w(n)&&n.length===0||b(n)&&Object.keys(n).length===0?!1:!!n};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],oe={initial:"in",extended:"ex",fullFeatured:"ff"};var _=class n extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,n.prototype)}},E=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},V=class n extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,n.prototype)}};var Y=(n,e)=>l(void 0,null,function*(){let t=Object.entries(n).map(o=>l(void 0,[o],function*([a,i]){return i.default&&typeof i.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof i.default=="function"?yield i.default():i.default}:{key:a,value:void 0}})),s=(yield Promise.all(t)).reduce((a,{key:i,value:o})=>(o!==void 0&&(a[i]=o),a),{});return p(p({},s),e)}),Z=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.uniq}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),ie=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[i])=>(a[i]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([i,o])=>{if(i in s)if(r[i]){if(r[i].includes(o))throw new _(t,{[i]:o});r[i]=[...r[i],o]}else r[i]=[o]})}),r},ce=n=>{if(!n)return{};if(!b(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return n};function de(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function X(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function pe(n){return new Date(X(n))}function le(n){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=n.match(e);if(!t)return[null,n];let[,r,s,a]=t,o=Object.entries(oe).find(([m,g])=>g===r)[0],[c,d,h]=s.split("");return[p({},{customDB:c==="1",managedDB:d==="1",selfHosted:h==="1",planType:o}),a]}var D=class{constructor(e={}){this.data=e}exists(){return I(this.data.__id)&&I(this.data.__label)}id(){if(!I(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!I(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!I(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return pe(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return X(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return l(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield x.init().records.deleteById(this.id(),e)})}update(e,t){return l(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return x.init().records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return l(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return x.init().records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return l(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return x.init().records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return l(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return x.init().records.detach({source:this.id(),target:e,options:t},r)})}},C=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var _e={"Content-Type":"application/json"},he=({httpClient:n,token:e,url:t})=>(r,i)=>l(void 0,null,function*(){var o=i,{headers:s}=o,a=$(o,["headers"]);let c=yield n.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},_e),s),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var q=class{constructor(e){this.id=e}rollback(){return l(this,null,function*(){return yield x.init().tx.rollback(this.id)})}commit(){return l(this,null,function*(){return yield x.init().tx.commit(this.id)})}};var ue="api.rushdb.com";var ye="https",me="/api/v1";var T=n=>n?{"x-transaction-id":n}:void 0,qe=n=>B(n)||n instanceof q,R=n=>qe(n)?n instanceof q?n.id:n:void 0,ge=n=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(n),O=n=>{if(B(n)&&ge(n))return n;if(n instanceof D&&n.data)return n.data.__id;if(b(n)&&"__id"in n&&ge(n.__id))return n.__id},U=n=>!(!b(n)||b(n)&&"name"in n&&!B(n.name)||b(n)&&"type"in n&&(!B(n.type)||!se.includes(n.type))||!("value"in n)||!J(n.value)||"metadata"in n&&!B(n.metadata)||"valueSeparator"in n&&!B(n.valueSeparator)),fe=n=>{let e=ye,t=ue,r=443,s=me;if("url"in n){let i=new URL(n.url);e=i.protocol.replace(":",""),t=i.hostname,r=parseInt(i.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,r=n.port),s&&!s.startsWith("/")&&(s="/"+s);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${s}`},S=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++){let s=Math.floor(Math.random()*e.length);t+=e[s]}return t};var H=class{constructor(e,t){this.records={attach:(a,i)=>l(this,[a,i],function*({source:e,target:t,options:r},s){var g,f;let o=R(s),d=`/relationships/${O(e)}`,h={headers:Object.assign({},T(o)),method:"POST",requestData:p(p({targetIds:this._extractTargetIds(t,"Attach")},(r==null?void 0:r.type)&&{type:r.type}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(g=this.logger)==null||g.call(this,p({requestId:u,path:d},h));let m=yield this.fetcher(d,h);return(f=this.logger)==null||f.call(this,y(p({requestId:u,path:d},h),{responseData:m.data})),m}),detach:(a,i)=>l(this,[a,i],function*({source:e,target:t,options:r},s){var g,f;let o=R(s),d=`/relationships/${O(e)}`,h={headers:Object.assign({},T(o)),method:"PUT",requestData:p(p({targetIds:this._extractTargetIds(t,"Detach")},(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(g=this.logger)==null||g.call(this,p({requestId:u,path:d},h));let m=yield this.fetcher(d,h);return(f=this.logger)==null||f.call(this,y(p({requestId:u,path:d},h),{responseData:m.data})),m}),create:(a,i)=>l(this,[a,i],function*({label:e,data:t,options:r},s){var g,f;let o=R(s),c="/records",d={headers:Object.assign({},T(o)),method:"POST",requestData:{}},h=typeof this.logger=="function"?S():"",u=N(j(t));if(w(u)&&u.every(U))d.requestData={label:e,properties:u};else if(K(u))d.requestData={label:e,data:u,options:r};else throw b(u)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(g=this.logger)==null||g.call(this,p({requestId:h,path:c},d));let m=yield this.fetcher(c,d);return(f=this.logger)==null||f.call(this,y(p({requestId:h,path:c},d),{responseData:m.data})),m!=null&&m.success&&(m!=null&&m.data)?new D(m.data):new D}),createMany:(e,t)=>l(this,null,function*(){var c,d,h;let r=R(t),s="/records/import/json",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o!=null&&o.success&&(o!=null&&o.data)){let u=w(o.data)?(h=o.data)==null?void 0:h.map(m=>new D(m)):[];return new C(u,o.total)}return new C([])}),delete:(e,t)=>l(this,null,function*(){var c,d,h;if(k(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new E("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=R(t),s="/records/delete",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(h=this.logger)==null||h.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o}),deleteById:(e,t)=>l(this,null,function*(){var d,h;let r=R(t),s=w(e),a=s?"/records/delete":`/records/${e}`,i={headers:Object.assign({},T(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:a},i));let c=yield this.fetcher(a,i);return(h=this.logger)==null||h.call(this,y(p({requestId:o,path:a},i),{responseData:c.data})),c}),export:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),s="/records/export/csv",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>l(this,null,function*(){var m,g;let u=e,{id:r}=u,s=$(u,["id"]),a=R(t),i=r?`/records/${r}/search`:"/records/search",o={headers:Object.assign({},T(a)),method:"POST",requestData:s!=null?s:{}},c=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:c,path:i},o));let d=yield this.fetcher(i,o);(g=this.logger)==null||g.call(this,y(p({requestId:c,path:i},o),{responseData:d.data}));let h=d.data.map(f=>new D(f));return new C(h,d.total,e)}),findById:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),s=w(e)?"/records":`/records/${e}`,a={headers:Object.assign({},T(r)),method:w(e)?"POST":"GET",requestData:w(e)?{ids:e}:void 0},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),w(e)){let h=o.data.map(u=>new D(u));return new C(h,o.total)}else return new D(o.data)}),findOne:(e,t)=>l(this,null,function*(){var d,h;let r=R(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);(h=this.logger)==null||h.call(this,y(p({requestId:i,path:s},a),{responseData:o.data}));let[c]=o.data;return new D(c)}),findUniq:(e,t)=>l(this,null,function*(){var d,h;let r=R(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((h=this.logger)==null||h.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),typeof o.total!="undefined"&&o.total>1)throw new V(o.total,e);let[c]=o.data;return new D(c)}),set:(i,o)=>l(this,[i,o],function*({target:e,label:t,data:r,options:s},a){var F,v;let c=R(a),h=`/records/${O(e)}`,u={headers:Object.assign({},T(c)),method:"PUT",requestData:{}},m=typeof this.logger=="function"?S():"",g=N(j(r));if(w(g)&&g.every(U))u.requestData={label:t,properties:g};else if(K(g))u.requestData={label:t,data:g,options:s};else throw b(g)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(F=this.logger)==null||F.call(this,p({requestId:m,path:h},u));let f=yield this.fetcher(h,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:h},u),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D}),update:(i,o)=>l(this,[i,o],function*({target:e,label:t,data:r,options:s},a){var F,v;let c=R(a),h=`/records/${O(e)}`,u={headers:Object.assign({},T(c)),method:"PATCH",requestData:{}},m=typeof this.logger=="function"?S():"",g=N(j(r));if(w(g)&&g.every(U))u.requestData={label:t,properties:g};else if(K(g))u.requestData={label:t,data:g,options:s};else throw b(g)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(F=this.logger)==null||F.call(this,p({requestId:m,path:h},u));let f=yield this.fetcher(h,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:h},u),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D})};this.relationships={createMany:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),s="/relationships/create-many",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o}),deleteMany:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),s="/relationships/delete-many",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>l(this,null,function*(){var h,u;let r=R(t),s=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&s.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&s.append("skip",e.skip.toString());let i=`/relationships/search${s.toString()?"?"+s.toString():""}`,o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?S():"";(h=this.logger)==null||h.call(this,p({requestId:c,path:i},o));let d=yield this.fetcher(i,o);return(u=this.logger)==null||u.call(this,y(p({requestId:c,path:i},o),{responseData:d.data})),d})};this.properties={delete:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"DELETE"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),s="/properties/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o}),findById:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"GET"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o}),values:(e,t,r)=>l(this,null,function*(){var d,h;let s=R(r),a=`/properties/${e}/values`,i={headers:Object.assign({},T(s)),method:"POST",requestData:t!=null?t:{}},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:a},i));let c=yield this.fetcher(a,i);return(h=this.logger)==null||h.call(this,y(p({requestId:o,path:a},i),{responseData:c.data})),c})};this.labels={find:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),s="/labels/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},a),{responseData:o.data})),o})};this.tx={begin:e=>l(this,null,function*(){var i,o;let t="/tx",r={method:"POST",requestData:b(e)&&"ttl"in e?e:{}},s=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,p({requestId:s,path:t},r));let a=yield this.fetcher(t,r);return(o=this.logger)==null||o.call(this,y(p({requestId:s,path:t},r),{responseData:a.data})),new q(a.data.id)}),commit:e=>l(this,null,function*(){var o,c;let r=`/tx/${R(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},s),{responseData:i.data})),i}),get:e=>l(this,null,function*(){var o,c;let r=`/tx/${R(e)}`,s={method:"GET"},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},s),{responseData:i.data})),new q(i.data.id)}),rollback:e=>l(this,null,function*(){var o,c;let r=`/tx/${R(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},s),{responseData:i.data})),i})};this.settings={get:()=>l(this,null,function*(){var a,i;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:r,path:e},t));let s=yield this.fetcher(e,t);return(i=this.logger)==null||i.call(this,y(p({requestId:r,path:e},t),{responseData:s.data})),s})};if(this.fetcher=null,t!=null&&t.httpClient){let r=fe(t);this.fetcher=he({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof D){let s=O(e);if(!s)throw new E(`${t} error: Target id is empty`);return[s]}if(w(e)&&e.every(s=>s instanceof D)){let s=e.map(O).filter(I);if(!s.length)throw new E(`${t} error: Target ids are empty`);return s}if(e instanceof C){let s=(r=e.data)==null?void 0:r.map(O).filter(I);if(!(s!=null&&s.length))throw new E(`${t} error: Target ids are empty`);return s}if(b(e)&&"__id"in e)return[e.__id];if(w(e)&&e.every(s=>b(s)&&"__id"in s)){let s=e.map(O).filter(I);if(!s.length)throw new E(`${t} error: Target ids are empty`);return s}return w(e)?e:B(e)?[e]:[]}};var Se,A=class A extends H{constructor(e,t){var a;let r=ce(t);super(e,y(p({},r),{httpClient:(a=r.httpClient)!=null?a:Se})),A.instance=this;let[s]=le(e!=null?e:"");this.initializeSync(s,e,r)}initializeSync(e,t,r){let s=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;A.state=p({initialized:!0,debug:!1,timeout:de("timeout",r==null?void 0:r.timeout,8e4),token:t},s&&{serverSettings:s})}static init(){if(A.instance)return A.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return A.instance}static isInitialized(){return A.instance!==null}toDBRecordInstance(e){return new D(e)}};A.instance=null,A.state={initialized:!1,debug:!1,timeout:8e4};var x=A,Re=n=>{Se=n};var Te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}getRushDBInstance(){return l(this,null,function*(){if(x.getInstance())return x.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')})}toDBRecordInstance(e){return l(this,null,function*(){try{return(yield this.getRushDBInstance()).toDBRecordInstance(e)}catch(t){throw new Error("No RushDB instance was provided during model initialization.")}})}find(e,t){return l(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.find(y(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return l(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findOne(y(p({},r),{labels:[this.label]}),t)})}findById(e,t){return l(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return l(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findUniq(y(p({},r),{labels:[this.label]}),t)})}create(e,t){return l(this,null,function*(){var o;let r=yield Y(this.schema,e),s=Z(this.schema,r),a=I(s),i=yield this.getRushDBInstance();if(a){let c=t!=null?t:yield i.tx.begin(),d=yield this.find({where:s},c),h=typeof t!="undefined";if(!((o=d==null?void 0:d.data)!=null&&o.length)){let m=yield i.records.create({label:this.label,data:r},c);return h||(yield c.commit()),m}else throw h||(yield c.commit()),new _(this.label,s)}return yield i.records.create({label:this.label,data:r},t)})}attach(a,i){return l(this,arguments,function*({source:e,target:t,options:r},s){return yield(yield this.getRushDBInstance()).records.attach({source:e,target:t,options:r},s)})}detach(a,i){return l(this,arguments,function*({source:e,target:t,options:r},s){return yield(yield this.getRushDBInstance()).records.detach({source:e,target:t,options:r},s)})}handleSetOrUpdate(e,t,r,s){return l(this,null,function*(){var c,d;if(w(t)&&t.every(U))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=yield this.getRushDBInstance(),i=yield Y(this.schema,t),o=Z(this.schema,i);if(!k(o)){let h=s!=null?s:yield a.tx.begin(),u=yield this.find({where:o},h),m=typeof s!="undefined";if(!((c=u==null?void 0:u.data)!=null&&c.length)||u.data.length===1&&((d=u.data[0])==null?void 0:d.id())===O(e)){let f=yield a.records[r]({target:e,label:this.label,data:i},h);return m||(yield h.commit()),f}else throw m||(yield h.commit()),new _(this.label,o)}return yield a.records[r]({label:this.label,target:e,data:i},s)})}set(e,t,r){return l(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return l(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return l(this,null,function*(){var i;let r=yield this.getRushDBInstance(),s=typeof t!="undefined",a=t!=null?t:yield r.tx.begin();try{let o=yield Promise.all(e.map(h=>l(this,null,function*(){return yield Y(this.schema,h)}))),c=ie(o,this.schema,this.label);if(!k(c)){let h=Object.entries(c).map(([m,g])=>({[m]:{$in:g}})),u=yield this.find({where:{$or:h}},a);if((i=u==null?void 0:u.data)!=null&&i.length)throw new _(this.label,Object.keys(c))}let d=yield r.records.createMany({label:this.label,data:o},a);return s||(yield a.commit()),d}catch(o){throw s||(yield a.rollback()),o}})}delete(e,t){return l(this,null,function*(){if(k(e.where))throw new E(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return yield(yield this.getRushDBInstance()).records.delete(y(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return l(this,null,function*(){return yield(yield this.getRushDBInstance()).records.deleteById(e,t)})}};Re(new W);var Ft=x;export{D as DBRecordInstance,C as DBRecordsArrayInstance,E as EmptyTargetError,P as HttpClient,Q as HttpClientResponse,Te as Model,V as NonUniqueResultError,H as RestAPI,x as RushDB,q as Transaction,_ as UniquenessError,Ft as default,le as extractMixedPropertiesFromToken,pe as idToDate,X as idToTimestamp,Re as initSDK,Y as mergeDefaultsWithPayload,ce as parseConfig,Z as pickUniqFieldsFromRecord,ie as pickUniqFieldsFromRecords,de as validateInteger};
package/package.json CHANGED
@@ -33,7 +33,7 @@
33
33
  "rushdb"
34
34
  ],
35
35
  "license": "Apache-2.0",
36
- "version": "1.11.1",
36
+ "version": "1.12.0",
37
37
  "type": "module",
38
38
  "files": [
39
39
  "dist"
@@ -41,7 +41,9 @@
41
41
  "main": "./dist/index.cjs",
42
42
  "module": "./dist/index.mjs",
43
43
  "types": "./dist/index.worker.d.ts",
44
- "devDependencies": {},
44
+ "devDependencies": {
45
+ "dotenv": "^16.0.3"
46
+ },
45
47
  "peerDependencies": {},
46
48
  "sideEffects": false,
47
49
  "publishConfig": {