@rushdb/javascript-sdk 3.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/api/api.d.ts +45 -5
- package/dist/direct/capabilities.d.ts +2 -1
- package/dist/direct/engine.d.ts +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.mjs +6 -6
- package/dist/index.node.mjs +3 -3
- package/dist/sdk/types.d.ts +2 -2
- package/dist/types/value.d.ts +99 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -178,7 +178,7 @@ The SDK works with RushDB in one of two ways:
|
|
|
178
178
|
|
|
179
179
|
| | RushDB Cloud | Self-hosted RushDB engine (direct mode) |
|
|
180
180
|
| --- | --- | --- |
|
|
181
|
-
| What you run | nothing: the managed service at [app.rushdb.com](https://app.rushdb.com) | one `
|
|
181
|
+
| What you run | nothing: the managed service at [app.rushdb.com](https://app.rushdb.com) | one `rushdb` binary, on your own infrastructure |
|
|
182
182
|
| Connect with | an API key | the engine URL and the engine token |
|
|
183
183
|
|
|
184
184
|
The engine is what you can self-host. RushDB Cloud runs that engine for you and adds the dashboard,
|
|
@@ -209,10 +209,11 @@ What each offers:
|
|
|
209
209
|
| External vector indexes; vector and hybrid search with a `queryVector` you supply | ✓ | ✓ |
|
|
210
210
|
| Raw openCypher (`query.raw`; the engine needs `--languages cypher`) | ✓ | ✓ |
|
|
211
211
|
| Schema (`ai.getSchema`, `ai.getSchemaMarkdown`) | ✓ | ✓ |
|
|
212
|
+
| Catalog lookups: `ai.searchValues` (a value across every property, also near spellings), `ai.getSchemaSummary`, `ai.resolveNames`, and value search in `properties.values` (`query`, `match`, `domainOnMiss`) | ✓ | ✓ |
|
|
212
213
|
| Transactions | ✓ | record creates, updates, sets, deletes by id, attaches and imports are staged; other writes refuse a transaction |
|
|
213
214
|
| Managed embeddings: managed indexes, `records.vectorSearch` by text `query` | ✓ | — |
|
|
214
215
|
| Natural-language search (`ai.search`) | ✓ | — |
|
|
215
|
-
| Relationship-pattern suggestions (`relationships.patterns.*`) | ✓ | — |
|
|
216
|
+
| Relationship-pattern suggestions (`relationships.patterns.*`) and join suggestions (`ai.getJoinCandidates`) | ✓ | — |
|
|
216
217
|
| Project settings (`settings.get`), dashboard, projects, team access, MCP over HTTP with OAuth | ✓ | — |
|
|
217
218
|
|
|
218
219
|
In direct mode a Cloud-only method throws `CloudOnlyError` (with `method` and `reason`) before
|
package/dist/api/api.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { DirectEngine } from '../direct/engine.js';
|
|
|
3
3
|
import type { DBRecordCreationOptions, DBRecordTarget, Relation, RelationDetachOptions, RelationDirection, RelationOptions, RelationTarget } from '../sdk/record.js';
|
|
4
4
|
import { DBRecordInstance, DBRecordsArrayInstance } from '../sdk/record.js';
|
|
5
5
|
import type { SDKConfig } from '../sdk/types.js';
|
|
6
|
-
import type { FlatObject, InferSchemaTypesWrite, MaybeArray, OrderDirection, Property, PropertyDraft, PropertyValuesData, Schema, RelationshipSearchQuery, SearchQuery, Where } from '../types/index.js';
|
|
6
|
+
import type { FlatObject, InferSchemaTypesWrite, MaybeArray, OrderDirection, Property, PropertyDraft, JoinCandidate, NameSuggestion, PropertyValuesData, PropertyValuesSearch, Schema, SchemaSummaryLabel, SearchValuesParams, ValueMatchesData, RelationshipSearchQuery, SearchQuery, Where } from '../types/index.js';
|
|
7
7
|
import type { ApiResponse } from './types.js';
|
|
8
8
|
import type { CreateEmbeddingIndexParams, DeleteRelationshipPatternOptions, EmbeddingIndex, EmbeddingIndexStats, RelationshipPatternListResponse, SmartSearchOptions, UpsertEmbeddingVectorsParams, UpsertEmbeddingVectorsResult, CreateTextIndexParams, TextIndex, TextSearchParams, VectorEntry, VectorSearchParams } from './types.js';
|
|
9
9
|
import { createFetcher } from '../network/index.js';
|
|
@@ -13,7 +13,7 @@ export declare class RestAPI {
|
|
|
13
13
|
options: SDKConfig['options'];
|
|
14
14
|
logger: SDKConfig['logger'];
|
|
15
15
|
/**
|
|
16
|
-
* Direct engine transport (standalone `
|
|
16
|
+
* Direct engine transport (standalone `rushdb`) when `direct` mode is set.
|
|
17
17
|
* In direct mode every request is answered from the engine; nothing is sent
|
|
18
18
|
* to RushDB Cloud.
|
|
19
19
|
*/
|
|
@@ -409,14 +409,16 @@ export declare class RestAPI {
|
|
|
409
409
|
* Retrieves values for a specific property
|
|
410
410
|
* @param id - The unique identifier of the property
|
|
411
411
|
* @param searchQuery - Query parameters to filter properties
|
|
412
|
-
* @param searchQuery.query -
|
|
412
|
+
* @param searchQuery.query - Keep the values whose text matches (`match`: contains,
|
|
413
|
+
* prefix, exact, or similar for near spellings); the values then rank by record
|
|
414
|
+
* count and come with `counts`. `domainOnMiss: n` lists every value of a property
|
|
415
|
+
* holding at most `n` when nothing matches (`searchMissed: true`).
|
|
413
416
|
* @param transaction - Optional transaction for atomic operations
|
|
414
417
|
* @returns Promise with the API response containing the property and its values
|
|
415
418
|
*/
|
|
416
419
|
values: (id: string, searchQuery?: SearchQuery & {
|
|
417
|
-
query?: string;
|
|
418
420
|
orderBy?: OrderDirection;
|
|
419
|
-
}, transaction?: Transaction | string) => Promise<ApiResponse<{
|
|
421
|
+
} & PropertyValuesSearch, transaction?: Transaction | string) => Promise<ApiResponse<{
|
|
420
422
|
metadata?: string;
|
|
421
423
|
name: string;
|
|
422
424
|
type: import("../types/value.js").PropertyType;
|
|
@@ -530,6 +532,44 @@ export declare class RestAPI {
|
|
|
530
532
|
};
|
|
531
533
|
private textIndexRequest;
|
|
532
534
|
ai: {
|
|
535
|
+
/**
|
|
536
|
+
* Stored values matching a text across every property, with the label and property
|
|
537
|
+
* holding each and its record count. Maps a word in a question to the value the data
|
|
538
|
+
* actually stores (`"positive"` → `KCT = "+"` once combined with `getSchemaSummary`).
|
|
539
|
+
* `match: 'similar'` finds near spellings (`spiderman` → `Spider-Man`).
|
|
540
|
+
* @param params - The search text, match mode, labels to search and a limit.
|
|
541
|
+
*/
|
|
542
|
+
searchValues: (params: SearchValuesParams) => Promise<ApiResponse<ValueMatchesData>>;
|
|
543
|
+
/**
|
|
544
|
+
* Every label with its properties in one read, from the live catalog: types, record
|
|
545
|
+
* and exact distinct counts, numeric and date ranges, the values of properties that
|
|
546
|
+
* hold few (`fewValues`, default 10), and relationship shapes.
|
|
547
|
+
* @param params - Optional `labels` to summarize and `fewValues`.
|
|
548
|
+
*/
|
|
549
|
+
getSchemaSummary: (params?: {
|
|
550
|
+
labels?: Array<string>;
|
|
551
|
+
fewValues?: number;
|
|
552
|
+
}) => Promise<ApiResponse<SchemaSummaryLabel[]>>;
|
|
553
|
+
/**
|
|
554
|
+
* Labels and properties spelled like a name, ignoring case, separators and plural
|
|
555
|
+
* endings: the answer to "no such label or property" (`patients.birthdate` →
|
|
556
|
+
* `Patient.Birthday`).
|
|
557
|
+
* @param params - The name (`text`, optionally `Label.property`) and a limit.
|
|
558
|
+
*/
|
|
559
|
+
resolveNames: (params: {
|
|
560
|
+
text: string;
|
|
561
|
+
limit?: number;
|
|
562
|
+
}) => Promise<ApiResponse<NameSuggestion[]>>;
|
|
563
|
+
/**
|
|
564
|
+
* Properties that look like references to another label's key, found from property
|
|
565
|
+
* names and exact value containment (no language model), each with its evidence.
|
|
566
|
+
* RushDB Cloud only: in direct mode it throws `CloudOnlyError`.
|
|
567
|
+
* @param params - Optional `labels` the candidates must touch and `minConfidence` (default 0.5).
|
|
568
|
+
*/
|
|
569
|
+
getJoinCandidates: (params?: {
|
|
570
|
+
labels?: Array<string>;
|
|
571
|
+
minConfidence?: number;
|
|
572
|
+
}) => Promise<ApiResponse<JoinCandidate[]>>;
|
|
533
573
|
/**
|
|
534
574
|
* Returns the full graph schema as structured JSON.
|
|
535
575
|
* Each item contains the label name, record count, properties with value ranges/samples,
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
* the direct-mode router refuses these with `CloudOnlyError`, the MCP server
|
|
4
4
|
* hides the tools built on them, and the docs mark them.
|
|
5
5
|
*
|
|
6
|
-
* Everything else the SDK offers runs against a standalone `
|
|
6
|
+
* Everything else the SDK offers runs against a standalone `rushdb` too.
|
|
7
7
|
*/
|
|
8
8
|
export declare const CLOUD_ONLY_METHODS: {
|
|
9
9
|
readonly 'ai.search': "natural-language search turns the prompt into a query with an LLM";
|
|
10
|
+
readonly 'ai.getJoinCandidates': "join suggestions are computed by the platform (its heuristics over the engine's value overlap)";
|
|
10
11
|
readonly 'relationships.patterns.list': "relationship-pattern suggestions are produced and stored by the platform";
|
|
11
12
|
readonly 'relationships.patterns.analyze': "relationship-pattern suggestions are produced and stored by the platform";
|
|
12
13
|
readonly 'relationships.patterns.approve': "relationship-pattern suggestions are produced and stored by the platform";
|
package/dist/direct/engine.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export type ProtocolResponse = {
|
|
|
21
21
|
};
|
|
22
22
|
/**
|
|
23
23
|
* Direct engine transport: executes protocol operations against a standalone
|
|
24
|
-
* `
|
|
24
|
+
* `rushdb` (`/protocol/v1/execute`) over HTTP. This is the SDK's "direct
|
|
25
25
|
* mode" — no RushDB Cloud. `scope` is the tenant on a multitenant engine
|
|
26
26
|
* (`X-RushDB-Tenant`); auth is the engine token.
|
|
27
27
|
*/
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var $t=Object.create;var ue=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,Bt=Object.prototype.hasOwnProperty;var vt=(t,e)=>{for(var r in e)ue(t,r,{get:e[r],enumerable:!0})},ze=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ct(e))!Bt.call(t,n)&&n!==r&&ue(t,n,{get:()=>e[n],enumerable:!(s=_t(e,n))||s.enumerable});return t};var Xe=(t,e,r)=>(r=t!=null?$t(kt(t)):{},ze(e||!t||!t.__esModule?ue(r,"default",{value:t,enumerable:!0}):r,t)),Lt=t=>ze(ue({},"__esModule",{value:!0}),t);var ar={};vt(ar,{CLOUD_ONLY_FORMS:()=>pe,CLOUD_ONLY_METHODS:()=>le,CloudOnlyError:()=>J,DBRecordInstance:()=>T,DBRecordsArrayInstance:()=>$,DirectModeError:()=>ne,EmptyTargetError:()=>k,HttpClient:()=>B,HttpClientResponse:()=>ge,Model:()=>He,NonUniqueResultError:()=>ce,RestAPI:()=>X,RushDB:()=>x,Transaction:()=>j,UniquenessError:()=>L,default:()=>sr,idToDate:()=>Be,idToTimestamp:()=>Se,initSDK:()=>Fe,isCloudOnlyMethod:()=>st,mergeDefaultsWithPayload:()=>de,parseConfig:()=>Ce,pickUniqFieldsFromRecord:()=>fe,pickUniqFieldsFromRecords:()=>_e,validateInteger:()=>ke});module.exports=Lt(ar);var B=class t{makeRequest(e,{headers:r,method:s,protocol:n,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(t.TIMEOUT_ERROR_CODE);return e.code=t.TIMEOUT_ERROR_CODE,e}};B.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];B.TIMEOUT_ERROR_CODE="ETIMEDOUT";var me=class{constructor(e,r){this._statusCode=e,this._headers=r}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},ge=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 Ee=Xe(require("http"),1),Oe=Xe(require("https"),1);var jt="string",Ut="datetime",Mt="boolean",Vt="number",Ze=[jt,Ut,Mt,Vt];var tt=Ee.default||Ee,rt=Oe.default||Oe,Nt=new tt.Agent({keepAlive:!0}),Ft=new rt.Agent({keepAlive:!0}),ye=class extends B{constructor(e){super(),this._agent=e}makeRequest(e,{headers:r,method:s,protocol:n,requestData:a,timeout:o}){let i=new URL(e),d=n==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Nt:Ft),new Promise((l,p)=>{let h=(d?tt:rt).request({agent:c,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:r,host:i.hostname,method:s,path:i.pathname+i.search,port:i.port});h.setTimeout(o!=null?o:8e4,()=>{h.destroy(B.makeTimeoutError())}),h.on("response",u=>{l(new Pe(u))}),h.on("error",u=>{p(u)}),h.once("socket",u=>{let y=a?JSON.stringify(a):"";u.connecting?u.once(d?"connect":"secureConnect",()=>{h.write(y),h.end()}):(h.write(y),h.end())})})}},Pe=class extends me{constructor(e){super(e.statusCode,e.headers||{}),this._res=e}getRawResponse(){return this._res}toStream(e){return this._res.once("end",()=>e()),this._res}toJSON(){return new Promise((e,r)=>{let s="";this._res.setEncoding("utf8"),this._res.on("data",n=>{s+=n}),this._res.once("end",()=>{try{e(JSON.parse(s))}catch(n){r(n)}})})}};var I=t=>typeof t=="object"&&Array.isArray(t)&&t!==null,P=t=>t!==null&&Object.prototype.toString.call(t)==="[object Object]",ee=t=>P(t)&&Object.keys(t).length===0,Ae=t=>typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null;function Ht(t,e){let r={...t};return e.forEach(s=>{delete r[s]}),r}var te=t=>P(t)?Ht(t,["__label","__id","__proptypes"]):t,Y=t=>I(t)?t.map(Y):P(t)?Object.fromEntries(Object.entries(t).filter(([e,r])=>r!==void 0).map(([e,r])=>[e,Y(r)])):t,qe=t=>I(t)?t.every(Ae):Ae(t),re=t=>P(t)&&Object.values(t).every(qe),Qt=t=>P(t)||I(t)&&!t.every(Ae),nt=t=>{if(I(t)||!P(t))return!0;let e=Object.values(t);return e.length===0?!0:e.some(r=>!Qt(r))},v=t=>typeof t=="string",A=t=>{if(typeof t=="string"){if(t.toLowerCase()==="true")return!0;if(t.toLowerCase()==="false")return!1}return I(t)&&t.length===0||P(t)&&Object.keys(t).length===0?!1:!!t};var $e=["httpClient","timeout","host","port","protocol","url","logger","options","direct","engineUrl","scope"];var L=class t extends Error{constructor(e,r){super(`Record with label "${e}" and properties ${JSON.stringify(r)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,t.prototype)}},k=class t extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,t.prototype)}},ce=class t extends Error{constructor(e,r){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(r)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,t.prototype)}},J=class t extends Error{constructor(r,s){super(`${r} requires RushDB Cloud: ${s}. It is not available in direct mode.`);this.method=r;this.reason=s;this.code="CLOUD_ONLY";this.name="CloudOnlyError",Object.setPrototypeOf(this,t.prototype)}},ne=class t extends Error{constructor(r){super(r);this.code="DIRECT_MODE_UNSUPPORTED";this.name="DirectModeError",Object.setPrototypeOf(this,t.prototype)}};var de=async(t,e)=>{let r=Object.entries(t).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(r)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},fe=(t,e)=>Object.entries(e).filter(([r])=>{var s;return(s=t[r])==null?void 0:s.unique}).reduce((r,[s,n])=>(s in t&&(r[s]=n),r),{}),_e=(t,e,r)=>{let s={},n=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[o])=>(a[o]=!0,a),{});return t.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in n)if(s[o]){if(s[o].includes(i))throw new L(r,{[o]:i});s[o]=[...s[o],i]}else s[o]=[i]})}),s},Ce=t=>{if(!t)return{};if(!P(t))throw new Error("Config must be an object");if(Object.keys(t).filter(r=>!$e.includes(r)).length>0)throw new Error(`Config object may only contain the following: ${$e.join(", ")}`);return t};function ke(t,e,r){if(!Number.isInteger(e)){if(r!==void 0)return r;throw new Error(`${t} must be an integer`)}return e}function Se(t){let e=t.split("-"),r=e[0]+e[1].slice(0,4);return parseInt(r,16)}function Be(t){return new Date(Se(t))}var T=class{constructor(e={}){this.data=e}get exists(){return A(this.data.__id)&&A(this.data.__label)}get id(){if(!A(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}get label(){if(!A(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}get proptypes(){if(!A(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}get date(){try{return Be(this.id)}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}get timestamp(){try{return Se(this.id)}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or invalid.")}}get score(){return this.data.__score}async delete(e){if(!A(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await x.getInstance().records.deleteById(this.id,e)}async update(e,r){if(!A(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return x.getInstance().records.update({label:this.label,target:this.id,data:e},r)}async set(e,r){if(!A(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return x.getInstance().records.set({label:this.label,target:this.id,data:e},r)}async attach(e,r,s){if(!A(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return x.getInstance().records.attach({source:this.id,target:e,options:r},s)}async detach(e,r,s){if(!A(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return x.getInstance().records.detach({source:this.id,target:e,options:r},s)}},$=class{constructor(e=[],r=0,s,n){this.data=e,this.total=r,this.searchQuery=s,this.warnings=n}async deleteAll(e){let r=this.data.map(n=>n.id);return r.length?await x.getInstance().records.deleteById(r,e):{success:!0}}async next(e){var i,d;if(!this.searchQuery)throw new Error("DBRecordsArrayInstance: Cannot paginate \u2014 no searchQuery was provided.");let r=(i=this.searchQuery.skip)!=null?i:0,s=(d=this.searchQuery.limit)!=null?d:100,n={...this.searchQuery,skip:r+s},o=await x.getInstance().records.find(n,void 0);return e!=null&&e.preserveData?(this.data=[...this.data,...o.data],this.total=o.total,this.searchQuery=n,this):o}exportCsv(){if(!this.data.length)return"";let e=new Set(["__id","__label","__proptypes"]),r=Object.keys(this.data[0].data).filter(a=>!e.has(a)),s=a=>{let o=a==null?"":String(a);return o.includes(",")||o.includes('"')||o.includes(`
|
|
2
2
|
`)?`"${o.replace(/"/g,'""')}"`:o},n=this.data.map(a=>r.map(o=>s(a.data[o])).join(","));return[r.join(","),...n].join(`
|
|
3
|
-
`)}async setProperties(e,r){let n=x.getInstance();for(let a=0;a<this.data.length;a+=100){let o=this.data.slice(a,a+100);await Promise.all(o.map(i=>n.records.update({target:i.id,label:i.data.__label,data:e},r)))}}};var Re=class{constructor(e){this.baseUrl=e.engineUrl.replace(/\/$/,""),this.token=e.token,this.httpClient=e.httpClient,this.scope=e.scope}async execute(e){var i,d;let r={protocolVersion:1,...this.scope?{context:{scope:this.scope}}:{},operation:e},s={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`};this.scope&&(s["X-RushDB-Tenant"]=this.scope);let n=await this.httpClient.makeRequest(`${this.baseUrl}/protocol/v1/execute`,{method:"POST",headers:s,requestData:r}),a=n.getStatusCode(),o=await n.toJSON().catch(()=>{});if(a>=400||o!=null&&o.error||!(o!=null&&o.response)){let c=(d=(i=o==null?void 0:o.error)==null?void 0:i.message)!=null?d:"engine request failed",
|
|
3
|
+
`)}async setProperties(e,r){let n=x.getInstance();for(let a=0;a<this.data.length;a+=100){let o=this.data.slice(a,a+100);await Promise.all(o.map(i=>n.records.update({target:i.id,label:i.data.__label,data:e},r)))}}};var Re=class{constructor(e){this.baseUrl=e.engineUrl.replace(/\/$/,""),this.token=e.token,this.httpClient=e.httpClient,this.scope=e.scope}async execute(e){var i,d;let r={protocolVersion:1,...this.scope?{context:{scope:this.scope}}:{},operation:e},s={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`};this.scope&&(s["X-RushDB-Tenant"]=this.scope);let n=await this.httpClient.makeRequest(`${this.baseUrl}/protocol/v1/execute`,{method:"POST",headers:s,requestData:r}),a=n.getStatusCode(),o=await n.toJSON().catch(()=>{});if(a>=400||o!=null&&o.error||!(o!=null&&o.response)){let c=(d=(i=o==null?void 0:o.error)==null?void 0:i.message)!=null?d:"engine request failed",l=new Error(`${a} ${c}`);throw l.status=a,l.body=o,l}return o.response}};var le={"ai.search":"natural-language search turns the prompt into a query with an LLM","ai.getJoinCandidates":"join suggestions are computed by the platform (its heuristics over the engine's value overlap)","relationships.patterns.list":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.analyze":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.approve":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.ignore":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.delete":"relationship-pattern suggestions are produced and stored by the platform","settings.get":"project settings belong to the platform"},pe={"records.vectorSearch":"a text `query` is embedded with the managed embedding model; in direct mode pass `queryVector`","ai.indexes.create":"a managed index is filled by the managed embedding model; in direct mode create an external index (`external: true`) and supply vectors"},st=t=>Object.prototype.hasOwnProperty.call(le,t);var ve=async(t,e,r)=>{var p,h,u,y,S,E,_,M,V,K,oe,N,F,W,ie,Qe,Ke,We,Ye,Je;let[s,n]=await Promise.all([t.execute({kind:"describe",describe:{kind:"schema",query:{labels:[],predicate:{},offset:0}}}),t.execute({kind:"describe",describe:{kind:"vectorIndexes"}})]),a=(p=s.schema)!=null?p:{labels:[],properties:[],relationships:[]},o=new Map;for(let m of(h=a.properties)!=null?h:[]){let D=(u=m.label)!=null?u:"";if(!D)continue;let b={id:String(m.id),name:String(m.name),type:String((y=m.type)!=null?y:"string"),recordsCount:Number((S=m.recordsCount)!=null?S:0),isArray:(E=m.isArray)!=null?E:void 0};if(b.type==="boolean")b.values=["true","false"];else if(b.type==="string"){let qt=((_=m.sampleValues)!=null?_:[]).filter(Ge=>Ge!=null).map(String);b.values=[...new Set(qt)].slice(0,10)}m.min!==void 0&&m.min!==null&&(b.min=b.type==="number"?Number(m.min):String(m.min)),m.max!==void 0&&m.max!==null&&(b.max=b.type==="number"?Number(m.max):String(m.max));let Z=(M=o.get(D))!=null?M:[];Z.push(b),o.set(D,Z)}let i=((V=a.labels)!=null?V:[]).map(m=>{var D,b;return{label:m.name,count:Number((D=m.recordsCount)!=null?D:0),properties:(b=o.get(m.name))!=null?b:[],relationships:[]}}),d=new Map(i.map(m=>[m.label,m])),c=(m,D)=>{let b=d.get(m);b&&!b.relationships.some(Z=>Z.direction===D.direction&&Z.label===D.label&&Z.type===D.type)&&b.relationships.push(D)};for(let m of(K=a.relationships)!=null?K:[]){let D=(oe=m.properties)!=null&&oe.length?m.properties:void 0;c(m.sourceLabel,{label:m.targetLabel,type:m.type,direction:"out",count:m.count,properties:D}),m.sourceLabel!==m.targetLabel&&c(m.targetLabel,{label:m.sourceLabel,type:m.type,direction:"in",count:m.count,properties:D})}let l=new Map;for(let m of((N=n.indexes)!=null?N:[]).map(r)){let D=`${m.label}|${m.propertyName}`,b=(F=l.get(D))!=null?F:[];b.push({id:String((W=m.id)!=null?W:""),name:String((ie=m.name)!=null?ie:""),sourceType:String((Qe=m.sourceType)!=null?Qe:"external"),similarityFunction:String((Ke=m.similarityFunction)!=null?Ke:"cosine"),dimensions:Number((We=m.dimensions)!=null?We:0),status:String((Ye=m.status)!=null?Ye:"pending"),modelKey:String((Je=m.modelKey)!=null?Je:"")}),l.set(D,b)}for(let m of i){m.relationships.sort((D,b)=>`${D.direction}|${D.label}|${D.type}`.localeCompare(`${b.direction}|${b.label}|${b.type}`));for(let D of m.properties){let b=l.get(`${m.label}|${D.name}`);b!=null&&b.length&&(D.vectorIndexes=b)}}return i.sort((m,D)=>D.count-m.count),e!=null&&e.length?i.filter(m=>e.includes(m.label)):i},at=t=>{var i,d;let e=c=>String(c).replace(/\|/g,"\\|").replace(/`/g,"\\`"),n=c=>c.length>48?c.slice(0,48)+"\u2026":c,a=c=>{let l=(c.type||"").toLowerCase();if(l==="number"||l==="datetime")return c.min!==void 0&&c.max!==void 0?`\`${c.min}\`..\`${c.max}\``:"\u2014";if(Array.isArray(c.values)&&c.values.length>0){let p=c.values.slice(0,5),h=c.values.length>5?` (+${c.values.length-5} more)`:"";return p.map(u=>`\`${e(n(String(u)))}\``).join(", ")+h}return"\u2014"},o=`# Graph Schema
|
|
4
4
|
|
|
5
5
|
## Labels
|
|
6
6
|
|
|
@@ -8,20 +8,20 @@
|
|
|
8
8
|
|-------|------:|
|
|
9
9
|
`;for(let c of t)o+=`| \`${e(c.label)}\` | ${c.count} |
|
|
10
10
|
`;o+=`
|
|
11
|
-
`;for(let c of t){let
|
|
11
|
+
`;for(let c of t){let l=c.count===1?"record":"records";if(o+=`---
|
|
12
12
|
|
|
13
|
-
## \`${e(c.label)}\` (${c.count} ${
|
|
13
|
+
## \`${e(c.label)}\` (${c.count} ${l})
|
|
14
14
|
|
|
15
15
|
`,c.properties.length>0){o+=`### Properties
|
|
16
16
|
|
|
17
17
|
`,o+=`| Property | Type | Values / Range | Semantic Search |
|
|
18
18
|
|----------|------|----------------|-----------------|
|
|
19
|
-
`;for(let
|
|
19
|
+
`;for(let p of c.properties){let h=(i=p.vectorIndexes)!=null&&i.length?p.vectorIndexes.map(y=>`\`${y.name}\` (${y.sourceType}, ${y.similarityFunction}, ${y.dimensions}d) [${y.status}]`).join(", "):"\u2014",u=p.isArray?`${p.type}[]`:p.type;o+=`| \`${e(p.name)}\` | ${e(u)} | ${a(p)} | ${h} |
|
|
20
20
|
`}o+=`
|
|
21
21
|
`}if(c.relationships.length>0){o+=`### Relationships
|
|
22
22
|
|
|
23
23
|
`,o+=`| Traversal | Count | Edge Properties |
|
|
24
24
|
|-----------|------:|-----------------|
|
|
25
|
-
`;for(let
|
|
25
|
+
`;for(let p of c.relationships){let h=(d=p.properties)!=null&&d.length?p.properties.map(S=>`\`${e(S.name)}:${e(S.type)}\``).join(", "):"\u2014",u=p.direction==="out"?`(${c.label})-[:${p.type}]->(${p.label})`:`(${c.label})<-[:${p.type}]-(${p.label})`,y=typeof p.count=="number"?String(p.count):"\u2014";o+=`| \`${e(u)}\` | ${y} | ${h} |
|
|
26
26
|
`}o+=`
|
|
27
|
-
`}}return o.trim()};var f=(t,e={})=>({success:!0,data:t,...e}),q=(t,e)=>{let r=new Error(`${t} ${e}`);return r.status=t,r.body={statusCode:t,message:e},r},G=t=>async()=>{throw new Y(t,pe[t])},H=(t,e)=>{if(t)throw new ne(`${e} inside a transaction is not supported in direct mode: the engine stages record creates, updates, deletes, links and imports. Run it outside the transaction.`)},ut="__RUSHDB__RELATION__DEFAULT__",z=(t,e,r)=>t.execute({kind:"transaction",transaction:{kind:"stage",transactionId:e,mutation:r}}),je=async(t,e,r)=>{var n;let{record:s}=await z(t,e,{kind:"getRecord",record:{id:r}});return{...(n=s==null?void 0:s.properties)!=null?n:{},__id:r,__label:s==null?void 0:s.__label,__proptypes:{}}},mt=(t,e)=>{t&&Array.isArray(e)&&e.length>0&&H(t,"A write with inline vectors")},be=t=>{var r,s;if(!t)return t;let e={...(r=t.properties)!=null?r:{}};return e.__id=t.id,e.__label=t.label,e.__proptypes=(s=t.propertyTypes)!=null?s:{},t.score!==void 0&&(e.__score=t.score),e},De=t=>(t!=null?t:[]).map(e=>be(e)),Ue=t=>t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:Array.isArray(t.properties)?Object.fromEntries(t.properties.map(e=>[e.name,e.value])):t.properties&&typeof t.properties=="object"?t.properties:{},Kt=t=>t==null||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?"desc":typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).map(([e,r])=>[e==="__id"?"id":e,r])),se=(t={})=>{var s,n,a,o,i,d;let e=(s=t.pagination)!=null?s:{},r={labels:(n=t.labels)!=null?n:[],predicate:(a=t.where)!=null?a:{},select:t.select,order:Kt(t.orderBy),offset:(i=(o=t.skip)!=null?o:e.skip)!=null?i:0,limit:(d=t.limit)!=null?d:e.limit};return Array.isArray(t.groupBy)&&t.groupBy.length>0&&(r.groupBy=t.groupBy),r},xe=t=>t==null||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0,Ve=async(t,e)=>(await t.execute({kind:"query",query:{kind:"record",id:e}})).record,gt=async(t,e)=>{var s,n,a;let r=await t.execute({kind:"query",query:{kind:"records",query:se(e)}});return r.kind==="rows"?{data:(s=r.rows)!=null?s:[],total:(n=r.total)!=null?n:0}:{data:De(r.records),total:(a=r.total)!=null?a:0}},ae=async t=>{var e;return(e=(await t.execute({kind:"describe",describe:{kind:"vectorIndexes"}})).indexes)!=null?e:[]},Me=async t=>{var e;return(e=(await t.execute({kind:"describe",describe:{kind:"indexes"}})).indexes)!=null?e:[]},he=t=>{var r;let e=Number((r=t.dimensions)!=null?r:0);return{id:t.name,name:t.name,label:t.label,propertyName:t.property,vectorPropertyName:`_emb_external_${t.similarity}_${e}`,similarityFunction:t.similarity,dimensions:e,sourceType:"external",status:t.status}},yt=t=>{var e,r;return{name:t.name,label:t.label,property:t.property,consistency:(e=t.consistency)!=null?e:"eventual",status:t.state,pending:(r=t.pending)!=null?r:0}},Ne=async t=>(await Me(t)).filter(e=>e.kind==="text").map(yt),ft=64,St=t=>t.join(".").slice(0,ft).replace(/[.:-]+$/,""),Te=t=>t.replace(/[^A-Za-z0-9_-]/g,"-"),ve=(t,e)=>{if(!e.has(t))return t;for(let r=2;;r++){let s=`-${r}`,n=t.slice(0,ft-s.length)+s;if(!e.has(n))return n}},ot=({label:t,property:e})=>St([Te(t),e==="*"?"all":Te(e),"text"]),Wt=(t,e,r)=>St([Te(t.label),Te(t.propertyName),"external",String(e),r]).replace(/^emb__/,"emb_"),Ie=async(t,e,r,s)=>{if(!Array.isArray(e)||e.length===0)return[];let n=s!=null?s:await ae(t);return e.map(a=>{if(typeof(a==null?void 0:a.index)=="string")return a;if(!r)throw q(422,"inline vectors require a record label to select their index");let o=Array.isArray(a.vector)?a.vector.length:void 0,i=n.filter(d=>d.label===r&&d.property===a.propertyName&&(a.similarityFunction===void 0||d.similarity===a.similarityFunction)&&(o===void 0||Number(d.dimensions)===o));if(i.length!==1)throw q(i.length===0?404:422,i.length===0?`No vector index matches label "${r}", property "${a.propertyName}"`:`${i.length} vector indexes match label "${r}", property "${a.propertyName}"; name one with \`index\``);return{...a,index:i[0].name}})},Yt=async(t,e,r)=>{let s=Array.isArray(e)?e:[e],n=i=>Array.isArray(i==null?void 0:i.$vectors)&&i.$vectors.length>0;if(!s.some(n))return e;let a=await ae(t),o=await Promise.all(s.map(async i=>n(i)?{...i,$vectors:await Ie(t,i.$vectors,r,a)}:i));return Array.isArray(e)?o:o[0]},Gt=()=>{var s;let t=new Uint8Array(16);if(typeof((s=globalThis.crypto)==null?void 0:s.getRandomValues)=="function")globalThis.crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);let e=Date.now();for(let n=0;n<6;n++)t[n]=Math.floor(e/2**(8*(5-n)))&255;t[6]=t[6]&15|112,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},zt=async({body:t,engine:e,txId:r})=>{var i,d,c,p,l,h;let s=!!((i=t.options)!=null&&i.mergeStrategy)||Array.isArray((d=t.options)==null?void 0:d.mergeBy),n=Ue(t);if(r){s&&H(r,"An upsert"),mt(r,t.vectors);let u=Gt();return await z(e,r,{kind:"createRecord",label:t.label,id:u,properties:n,options:(c=t.options)!=null?c:{}}),f(await je(e,r,u))}let a=s?{...t.options,mergeBy:(l=(p=t.options)==null?void 0:p.mergeBy)!=null?l:[]}:(h=t.options)!=null?h:{},o=await e.execute({kind:"mutate",mutation:{kind:"putRecord",mode:"create",label:t.label,properties:n,vectors:await Ie(e,t.vectors,t.label),options:a}});return f(be(o.record))},it=t=>async({body:e,params:[r],engine:s,txId:n})=>{var d,c;let a=typeof e.label=="string"&&e.label?e.label:void 0;if(n){if(mt(n,e.vectors),a){let p=await je(s,n,r);p.__label&&p.__label!==a&&await z(s,n,{kind:"retypeRecord",record:{id:r},fromLabel:p.__label,toLabel:a})}return await z(s,n,{kind:"updateRecord",record:{id:r},properties:Ue(e),replace:t==="replace"}),f(await je(s,n,r))}let o=a;if(a||(d=e.vectors)!=null&&d.length){let p=await Ve(s,r);a&&(p!=null&&p.label)&&p.label!==a&&await s.execute({kind:"mutate",mutation:{kind:"retypeRecord",id:r,fromLabel:p.label,toLabel:a}}),o=a!=null?a:p==null?void 0:p.label}let i=await s.execute({kind:"mutate",mutation:{kind:"putRecord",mode:t,id:r,properties:Ue(e),vectors:await Ie(s,e.vectors,o),options:(c=e.options)!=null?c:{}}});return f(be(i.record))},Jt=async(t,e,r)=>{var o;if(!e)return r;let s;try{s=(o=await Ve(t,e))==null?void 0:o.label}catch(i){if((i==null?void 0:i.status)===404)return;throw i}let n={[s]:{$id:e}},a=r.where;return{...r,where:xe(a)?n:{$and:[a,n]}}},ct=async({body:t,params:[e],engine:r})=>{let s=await Jt(r,e,t);if(!s)return f([],{total:0});let{data:n,total:a}=await gt(r,s);return f(n,{total:a})},dt=(t,e,r)=>e?z(t,e,{kind:"ingest",ingest:r}):t.execute({kind:"ingest",ingest:r}),pt=(t,e)=>{var r,s;return e&&((r=t.records)!=null&&r.length)?f(De(t.records)):f({message:"Records have been successfully imported",count:Number((s=t.count)!=null?s:0)})},Xt=["delimiter","header","skipEmptyLines","dynamicTyping","quoteChar","escapeChar","newline"],lt=t=>{var e,r,s,n,a,o,i,d,c,p,l,h;return{relationType:(e=t.type)!=null?e:ut,direction:String((r=t.direction)!=null?r:"").toLowerCase()==="in"?"in":"out",allowCartesian:(s=t.manyToMany)!=null?s:!1,properties:(n=t.properties)!=null?n:{},source:{label:(a=t.source)==null?void 0:a.label,property:(o=t.source)==null?void 0:o.key,predicate:(d=(i=t.source)==null?void 0:i.where)!=null?d:{}},target:{label:(c=t.target)==null?void 0:c.label,property:(p=t.target)==null?void 0:p.key,predicate:(h=(l=t.target)==null?void 0:l.where)!=null?h:{}}}},we=t=>Array.isArray(t)?t:[t],Zt=t=>{var r,s;let e=new Map;for(let n of t){let a=e.get(n.id);if(a){a.recordsCount+=Number((r=n.recordsCount)!=null?r:0),a.isArray||(a.isArray=n.isArray===!0);continue}e.set(n.id,{id:n.id,name:n.name,type:n.type,recordsCount:Number((s=n.recordsCount)!=null?s:0),isArray:n.isArray===!0})}return Array.from(e.values(),({isArray:n,...a})=>({...a,metadata:JSON.stringify({cardinality:n?"OrderedMany":"Single",nullability:"Nullable"})}))},Rt=async(t,e={})=>{var s;let r=await t.execute({kind:"describe",describe:{kind:"properties",query:se(e),...xe(e.where)?{detail:"catalog"}:{}}});return Zt((s=r.properties)!=null?s:[])},ht=async(t,e)=>{var s;let r=(await Rt(t)).find(n=>n.name===e||n.id===e);return r&&{...r,id:(s=r.id)!=null?s:r.name}},wt=async(t,e,r)=>{var a,o;if(typeof e.query!="string"||e.query.trim()==="")throw q(422,"text.query is required");let s=await Ne(t),n;if(e.index!==void 0){if(n=s.find(i=>i.name===e.index),!n)throw q(404,`No text index named "${e.index}"`)}else{let i=r[0];if(!i)throw q(422,"Name a text index with `index`, or give `labels`");let d=s.filter(c=>c.label===i&&c.status==="ready"&&(e.property===void 0||c.property===e.property));if(d.length===0)throw q(404,`No ready text index on label "${i}"`);if(d.length>1)throw q(422,`Label "${i}" has several text indexes (${d.map(c=>c.name).join(", ")}); name one with \`index\``);n=d[0]}return{index:n.name,label:n.label,query:e.query,allTerms:(a=e.allTerms)!=null?a:!1,phrase:(o=e.phrase)!=null?o:!1}},er=async({body:t,engine:e})=>{var l,h,u,g,S,P,$,M,N,Q,oe;let r=(l=t.queryVector)!=null?l:[];if(r.length===0)throw new Y("records.vectorSearch",le["records.vectorSearch"]);let s=await ae(e),n;if(typeof t.index=="string"){if(n=s.find(V=>V.name===t.index),!n)throw q(404,`No vector index named "${t.index}"`)}else{let V=((h=t.labels)!=null?h:[])[0],F=s.filter(K=>{var ie;return K.label===V&&K.property===t.propertyName&&(t.similarityFunction===void 0||K.similarity===t.similarityFunction)&&Number(K.dimensions)===((ie=t.dimensions)!=null?ie:r.length)});if(F.length!==1)throw q(F.length===0?404:422,F.length===0?`No vector index matches label "${V}", property "${t.propertyName}"`:`${F.length} vector indexes match label "${V}", property "${t.propertyName}"; name one with \`index\``);n=F[0]}let a=(u=t.labels)!=null&&u.length?t.labels:[n.label],o={property:n.property,vector:r,similarity:(g=n.similarity)!=null?g:"cosine",index:n.name,mode:t.mode,ef:t.ef,scoreThreshold:t.scoreThreshold},i=t.text?await wt(e,{...t.text,query:(S=t.text.query)!=null?S:t.query},a):void 0,d=i?{kind:"hybrid",query:{labels:a,predicate:(P=t.where)!=null?P:{},vector:{...o,weight:t.weight,prefetchLimit:t.prefetchLimit},text:{index:i.index,query:i.query,allTerms:i.allTerms,phrase:i.phrase,weight:t.text.weight,prefetchLimit:t.text.prefetchLimit},fusion:t.fusion,rrfK:t.rrfK,offset:($=t.skip)!=null?$:0,limit:(M=t.limit)!=null?M:10}}:{kind:"vector",query:{...o,labels:a,predicate:(N=t.where)!=null?N:{},offset:(Q=t.skip)!=null?Q:0,limit:(oe=t.limit)!=null?oe:10}},c=await e.execute({kind:"query",query:d}),p=De(c.records);return f(p,{total:p.length,meta:{vectorSearch:c.vectorSearch,textSearch:c.textSearch,fusion:c.fusion}})},O="([^/]+)",xt=[{method:"GET",pattern:new RegExp(`^/records/${O}$`),handle:async({params:[t],engine:e})=>f(be(await Ve(e,t)))},{method:"POST",pattern:/^\/records$/,handle:zt},{method:"PATCH",pattern:new RegExp(`^/records/${O}$`),handle:it("merge")},{method:"PUT",pattern:new RegExp(`^/records/${O}$`),handle:it("replace")},{method:"DELETE",pattern:new RegExp(`^/records/${O}$`),handle:async({params:[t],engine:e,txId:r})=>(r?await z(e,r,{kind:"deleteRecord",record:{id:t}}):await e.execute({kind:"mutate",mutation:{kind:"deleteRecord",id:t}}),f({message:"Record deleted"}))},{method:"POST",pattern:/^\/records\/delete$/,handle:async({body:t,engine:e,txId:r})=>{var n;H(r,"records.delete");let s=await e.execute({kind:"mutate",mutation:{kind:"deleteRecords",query:se(t)}});return f({message:`${(n=s.affected)!=null?n:0} records deleted`})}},{method:"POST",pattern:/^\/records\/search$/,handle:ct},{method:"POST",pattern:new RegExp(`^/records/${O}/search$`),handle:ct},{method:"POST",pattern:/^\/records\/import\/json$/,handle:async({body:t,engine:e,txId:r})=>{var n,a;let s=await dt(e,r,{kind:"documents",label:t.label,documents:await Yt(e,t.data,t.label),options:(n=t.options)!=null?n:{}});return pt(s,(a=t.options)==null?void 0:a.returnResult)}},{method:"POST",pattern:/^\/records\/import\/csv$/,handle:async({body:t,engine:e,txId:r})=>{var i,d,c,p,l,h,u;let s=(i=t.vectors)!=null&&i.length?await ae(e):[],n=await Promise.all(((d=t.vectors)!=null?d:[]).map(g=>Ie(e,g,t.label,s))),a=Object.fromEntries(Object.entries((c=t.parseConfig)!=null?c:{}).filter(([g])=>Xt.includes(g))),o=await dt(e,r,{kind:"csv",label:t.label,data:(p=t.data)!=null?p:"",parseConfig:a,options:(l=t.options)!=null?l:{},vectors:n});return Number((h=o.count)!=null?h:0)===0?f(!0):pt(o,(u=t.options)==null?void 0:u.returnResult)}},{method:"POST",pattern:/^\/records\/export\/csv$/,handle:async({body:t,engine:e})=>{let r=await e.execute({kind:"query",query:{kind:"exportCsv",query:se({labels:t.labels,where:t.where,orderBy:t.orderBy,skip:typeof t.skip=="number"?t.skip:0,limit:typeof t.limit=="number"?t.limit:100})}});return f({fileContent:r.content,dateTime:new Date().toISOString()})}},{method:"POST",pattern:new RegExp(`^/relationships/${O}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var o,i,d,c;let n=(o=t.type)!=null?o:ut,a=String((i=t.direction)!=null?i:"").toLowerCase()==="in";if(s)for(let p of we(t.targetIds))await z(r,s,{kind:"createRelationship",relationType:n,source:{id:a?p:e},target:{id:a?e:p},properties:(d=t.properties)!=null?d:{}});else await r.execute({kind:"mutate",mutation:{kind:"linkRecordsById",command:{relationType:n,direction:a?"in":"out",sourceIds:[e],targetIds:we(t.targetIds),properties:(c=t.properties)!=null?c:{}}}});return f({message:`Relations to Record ${e} have been successfully created`})}},{method:"PUT",pattern:new RegExp(`^/relationships/${O}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var a;H(s,"records.detach");let n=String((a=t.direction)!=null?a:"").toLowerCase();return await r.execute({kind:"mutate",mutation:{kind:"unlinkRecordsById",command:{relationTypes:we(t.typeOrTypes).filter(Boolean),...n==="in"||n==="out"?{direction:n}:{},sourceIds:[e],targetIds:we(t.targetIds)}}}),f({message:`Relations to Record ${e} have been successfully deleted`})}},{method:"POST",pattern:/^\/relationships\/create-many$/,handle:async({body:t,engine:e,txId:r})=>(H(r,"relationships.createMany"),await e.execute({kind:"mutate",mutation:{kind:"linkRecords",command:lt(t)}}),f({message:"Relations have been successfully created"}))},{method:"POST",pattern:/^\/relationships\/delete-many$/,handle:async({body:t,engine:e,txId:r})=>(H(r,"relationships.deleteMany"),await e.execute({kind:"mutate",mutation:{kind:"unlinkRecords",command:lt(t)}}),f({message:"Relations have been successfully deleted"}))},{method:"POST",pattern:/^\/relationships\/search$/,handle:async({body:t,engine:e})=>{var s,n,a,o,i,d,c,p,l,h,u;let r=await e.execute({kind:"query",query:{kind:"relationships",query:{sourceLabels:(n=(s=t.source)==null?void 0:s.labels)!=null?n:[],targetLabels:(o=(a=t.target)==null?void 0:a.labels)!=null?o:[],relationType:(i=t.where)==null?void 0:i.type,predicate:Object.fromEntries(Object.entries((d=t.where)!=null?d:{}).filter(([g])=>g!=="type")),sourcePredicate:xe((c=t.source)==null?void 0:c.where)?void 0:t.source.where,targetPredicate:xe((p=t.target)==null?void 0:p.where)?void 0:t.target.where,offset:(l=t.skip)!=null?l:0,limit:t.limit}}});return f((h=r.relationships)!=null?h:[],{total:(u=r.total)!=null?u:0})}},{method:"GET",pattern:/^\/relationships\/patterns$/,handle:G("relationships.patterns.list")},{method:"POST",pattern:/^\/relationships\/patterns\/analyze$/,handle:G("relationships.patterns.analyze")},{method:"POST",pattern:new RegExp(`^/relationships/patterns/${O}/approve$`),handle:G("relationships.patterns.approve")},{method:"POST",pattern:new RegExp(`^/relationships/patterns/${O}/ignore$`),handle:G("relationships.patterns.ignore")},{method:"DELETE",pattern:new RegExp(`^/relationships/patterns/${O}$`),handle:G("relationships.patterns.delete")},{method:"POST",pattern:/^\/properties\/search$/,handle:async({body:t,engine:e})=>{var r,s;return f(await Rt(e,{labels:(r=t.labels)!=null?r:[],where:(s=t.where)!=null?s:{}}))}},{method:"GET",pattern:new RegExp(`^/properties/${O}$`),handle:async({params:[t],engine:e})=>{let r=await ht(e,t);if(!r)throw q(404,`property \`${t}\` does not exist`);return f(r)}},{method:"DELETE",pattern:new RegExp(`^/properties/${O}$`),handle:async({params:[t],engine:e,txId:r})=>{H(r,"properties.delete");let s=await ht(e,t);if(!s)throw q(404,`property \`${t}\` does not exist`);return await e.execute({kind:"mutate",mutation:{kind:"deleteProperty",name:s.name}}),f({message:`Property (${t}) has been successfully deleted.`})}},{method:"POST",pattern:new RegExp(`^/properties/${O}/values$`),handle:async({body:t,params:[e],engine:r})=>{var n,a,o;let s=await r.execute({kind:"query",query:{kind:"propertyValues",property:e,query:se({labels:(n=t.labels)!=null?n:[],where:(a=t.where)!=null?a:{}})}});return f({values:(o=s.values)!=null?o:[]})}},{method:"POST",pattern:/^\/labels\/search$/,handle:async({body:t,engine:e})=>{var n;let r=await e.execute({kind:"describe",describe:{kind:"labels",query:se(t)}}),s={};for(let a of(n=r.labels)!=null?n:[])s[a]=(await gt(e,{...t,labels:[a],skip:0,limit:1})).total;return f(s)}},{method:"POST",pattern:/^\/tx$/,handle:async({body:t,engine:e})=>{var s;let r=await e.execute({kind:"transaction",transaction:{kind:"begin",ttlMs:t.ttl,autocommit:(s=t.autocommit)!=null?s:!1}});return f({id:r.transactionId})}},{method:"GET",pattern:new RegExp(`^/tx/${O}$`),handle:async({params:[t]})=>f({id:t})},{method:"POST",pattern:new RegExp(`^/tx/${O}/commit$`),handle:async({params:[t],engine:e})=>{var s;let r=await e.execute({kind:"transaction",transaction:{kind:"commit",transactionId:t}});if(r.status!=="committed")throw q(409,`Transaction commit failed: ${(s=r.reason)!=null?s:r.status}`);return f({message:`Transaction (${t}) has been successfully committed.`})}},{method:"POST",pattern:new RegExp(`^/tx/${O}/rollback$`),handle:async({params:[t],engine:e})=>(await e.execute({kind:"transaction",transaction:{kind:"rollback",transactionId:t}}),f({message:`Transaction (${t}) has been rolled back.`}))},{method:"POST",pattern:/^\/query\/raw$/,handle:async({body:t,engine:e,txId:r})=>{var n,a;H(r,"query.raw");let s=await e.execute({kind:"query",query:{kind:"statement",language:"cypher",statement:t.query,parameters:(n=t.params)!=null?n:null}});return f({records:(a=s.rows)!=null?a:[]})}},{method:"GET",pattern:/^\/text-indexes$/,handle:async({engine:t})=>f(await Ne(t))},{method:"POST",pattern:/^\/text-indexes$/,handle:async({body:t,engine:e})=>{var n,a;let r=new Set((await Me(e)).map(o=>String(o.name)));if(t.name!==void 0&&r.has(t.name))throw q(409,`An index named "${t.name}" already exists`);let s=await e.execute({kind:"index",index:{kind:"create",definition:{name:(n=t.name)!=null?n:ve(ot(t),r),label:t.label,property:t.property,kind:"text",consistency:(a=t.consistency)!=null?a:"eventual"}}});return f(yt(s.index))}},{method:"POST",pattern:/^\/text-indexes\/name-suggestion$/,handle:async({body:t,engine:e})=>{let r=new Set((await Me(e)).map(s=>String(s.name)));return f({name:ve(ot(t),r)})}},{method:"DELETE",pattern:new RegExp(`^/text-indexes/${O}$`),handle:async({params:[t],engine:e})=>{let r=decodeURIComponent(t);if(!(await Ne(e)).some(s=>s.name===r))throw q(404,`No text index named "${r}"`);return await e.execute({kind:"index",index:{kind:"drop",name:r}}),f({deleted:!0})}},{method:"POST",pattern:/^\/search\/text$/,handle:async({body:t,engine:e})=>{var a,o,i,d,c,p,l;if(typeof t.query!="string"||t.query.trim()==="")throw q(422,"query is required");let r=await wt(e,t,(a=t.labels)!=null?a:[]),s=await e.execute({kind:"query",query:{kind:"hybrid",query:{labels:(o=t.labels)!=null&&o.length?t.labels:[r.label],predicate:(i=t.where)!=null?i:{},text:{index:r.index,query:r.query,allTerms:r.allTerms,phrase:r.phrase},offset:(d=t.skip)!=null?d:0,limit:(c=t.limit)!=null?c:10}}}),n=De(s.records);return f(n,{total:(l=(p=s.textSearch)==null?void 0:p.matches)!=null?l:n.length,meta:{textSearch:s.textSearch}})}},{method:"POST",pattern:/^\/ai\/schema$/,handle:async({body:t,engine:e})=>f(await Le(e,t.labels,he))},{method:"POST",pattern:/^\/ai\/schema\/md$/,handle:async({body:t,engine:e})=>f(at(await Le(e,t.labels,he)))},{method:"POST",pattern:/^\/ai\/search-query$/,handle:G("ai.search")},{method:"POST",pattern:/^\/ai\/search$/,handle:er},{method:"GET",pattern:/^\/ai\/indexes$/,handle:async({engine:t})=>f((await ae(t)).map(he))},{method:"POST",pattern:/^\/ai\/indexes$/,handle:async({body:t,engine:e})=>{var d,c;if(t.sourceType!=="external")throw new Y("ai.indexes.create",le["ai.indexes.create"]);let r=Number(t.dimensions);if(!Number.isInteger(r)||r<1||r>4096)throw q(422,"dimensions must be an integer between 1 and 4096");let s=(d=t.similarityFunction)!=null?d:"cosine",n=await ae(e),a=n.find(p=>p.label===t.label&&p.property===t.propertyName&&p.similarity===s&&Number(p.dimensions)===r);if(a)throw q(409,`An embedding index for label "${t.label}", property "${t.propertyName}", sourceType "external", similarityFunction "${s}", and dimensions ${r} already exists ("${a.name}")`);let o=new Set(n.map(p=>String(p.name)));if(t.name!==void 0&&o.has(t.name))throw q(409,`An embedding index named "${t.name}" already exists`);let i=await e.execute({kind:"index",index:{kind:"createVector",definition:{label:t.label,property:t.propertyName,dimensions:r,similarity:s,name:(c=t.name)!=null?c:ve(Wt(t,r,s),o)}}});return f(he(i.index))}},{method:"DELETE",pattern:new RegExp(`^/ai/indexes/${O}$`),handle:async({params:[t],engine:e})=>(await e.execute({kind:"index",index:{kind:"dropVector",name:decodeURIComponent(t)}}),f({deleted:!0,queued:!1}))},{method:"GET",pattern:new RegExp(`^/ai/indexes/${O}/stats$`),handle:async({params:[t],engine:e})=>{var s,n;let r=await e.execute({kind:"describe",describe:{kind:"vectorIndex",name:decodeURIComponent(t)}});return f({...r.stats,index:he((n=(s=r.stats)==null?void 0:s.index)!=null?n:{})})}},{method:"POST",pattern:new RegExp(`^/ai/indexes/${O}/vectors/upsert$`),handle:async({body:t,params:[e],engine:r})=>{var n;let s=await r.execute({kind:"index",index:{kind:"upsertVectors",name:decodeURIComponent(e),items:(n=t.items)!=null?n:[]}});return f({updated:s.updated,requested:s.requested})}},{method:"GET",pattern:/^\/sdk\/settings$/,handle:G("settings.get")}],Or=xt.map(t=>`${t.method} ${t.pattern.source}`),Tt=t=>async(e,{method:r="GET",headers:s,requestData:n})=>{var c;let a=new URL(String(e),"http://direct"),o=xt.filter(p=>p.method===r&&p.pattern.test(a.pathname)).sort((p,l)=>p.pattern.source.split("(").length-l.pattern.source.split("(").length)[0];if(!o)throw new ne(`${r} ${a.pathname} has no direct-mode mapping`);let i=((c=o.pattern.exec(a.pathname))!=null?c:[]).slice(1),d=s==null?void 0:s["x-transaction-id"];return await o.handle({body:n!=null?n:{},params:i,query:a.searchParams,txId:d,engine:t})};var tr={"Content-Type":"application/json"},bt=({httpClient:t,token:e,url:r})=>async(s,{headers:n,...a})=>{var p;let o=await t.makeRequest(`${r}${s}`,{credentials:"omit",headers:Object.assign({...tr,...n},typeof e<"u"?{Authorization:`Bearer ${e}`}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();let i="",d;try{let l=await o.toJSON();d=l;let h=(p=l==null?void 0:l.message)!=null?p:l==null?void 0:l.error;Array.isArray(h)?i=h.join("; "):typeof h=="string"&&(i=h)}catch{}let c=new Error(i?`${o.getStatusCode()} ${i}`:`${o.getStatusCode()}`);throw c.status=o.getStatusCode(),c.body=d,c};var j=class{constructor(e){this.id=e}async rollback(){return await x.getInstance().tx.rollback(this.id)}async commit(){return await x.getInstance().tx.commit(this.id)}};var Dt="api.rushdb.com";var It="https",Et="/api/v1";var w=t=>t?{"x-transaction-id":t}:void 0,nr=t=>L(t)||t instanceof j,R=t=>nr(t)?t instanceof j?t.id:t:void 0,Pt=t=>/^[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(t),C=t=>{if(L(t)&&Pt(t))return t;if(t instanceof T&&t.data)return t.data.__id;if(E(t)&&"__id"in t&&Pt(t.__id))return t.__id},J=t=>!(!E(t)||E(t)&&"name"in t&&!L(t.name)||E(t)&&"type"in t&&(!L(t.type)||!Ze.includes(t.type))||!("value"in t)||!qe(t.value)||"metadata"in t&&!L(t.metadata)||"valueSeparator"in t&&!L(t.valueSeparator)),Ot=t=>{let e=It,r=Dt,s=443,n=Et;if("url"in t){let o=new URL(t.url);e=o.protocol.replace(":",""),r=o.hostname,s=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in t&&"port"in t&&"protocol"in t&&(e=t.protocol.replace(":",""),r=t.host,s=t.port),n&&!n.startsWith("/")&&(n="/"+n);let a="";return e==="http"&&s===80||e==="https"&&s===443||(a=":"+s),`${e}://${r}${a}${n}`},y=(t=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r="";for(let s=0;s<t;s++){let n=Math.floor(Math.random()*e.length);r+=e[n]}return r};var X=class{constructor(e,r){this.records={attach:async({source:e,target:r,options:s},n)=>{var l,h;let a=R(n),i=`/relationships/${C(e)}`,d={headers:Object.assign({},w(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(r,"Attach"),...(s==null?void 0:s.type)&&{type:s.type},...(s==null?void 0:s.direction)&&{direction:s.direction},...(s==null?void 0:s.properties)&&{properties:s.properties}}},c=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},detach:async({source:e,target:r,options:s},n)=>{var l,h;let a=R(n),i=`/relationships/${C(e)}`,d={headers:Object.assign({},w(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(r,"Detach"),...(s==null?void 0:s.typeOrTypes)&&{typeOrTypes:s.typeOrTypes},...(s==null?void 0:s.direction)&&{direction:s.direction}}},c=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},create:async({label:e,data:r,options:s,vectors:n},a)=>{var h,u;let o=R(a),i="/records",d={headers:Object.assign({},w(o)),method:"POST",requestData:{}},c=typeof this.logger=="function"?y():"",p=te(W(r));if(I(p)&&p.every(J))d.requestData={label:e,properties:p,options:s,...(n==null?void 0:n.length)&&{vectors:n}};else if(re(p))d.requestData={label:e,data:p,options:s,...(n==null?void 0:n.length)&&{vectors:n}};else throw E(p)?new Error("Provided data is not a flat object. Consider using the `importJson` method for nested objects or arrays of nested objects, or use `createMany` for arrays of flat objects."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d});let l=await this.fetcher(i,d);return(u=this.logger)==null||u.call(this,{requestId:c,path:i,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new T(l.data):new T},createMany:async(e,r)=>{var h,u,g;let s=I(e.data)?e.data:[e.data];if(!s.every(S=>re(S)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=e.vectors?I(e.vectors[0])?e.vectors:[e.vectors]:void 0;if(a&&a.length>s.length)throw new Error(`records.createMany: vectors length (${a.length}) exceeds the number of data rows (${s.length}).`);let o=a!=null&&a.length?s.map((S,P)=>{var $;return($=a[P])!=null&&$.length?{...S,$vectors:a[P]}:S}):s,i=R(r),d="/records/import/json",c={headers:Object.assign({},w(i)),method:"POST",requestData:{label:e.label,data:o,options:e.options}},p=typeof this.logger=="function"?y():"";(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let S=I(l.data)?(g=l.data)==null?void 0:g.map(P=>new T(P)):[];return new _(S,l.total)}return new _([])},importJson:async(e,r)=>{var h,u,g;let{data:s,options:n}=e,{label:a}=e,o=s;if(!a){let S=E(s)&&!I(s)?te(s):s;if(nt(S))throw new Error("records.importJson: Missing `label`. Provide `label` for top-level arrays or objects with primitive top-level properties, or pass a container object whose top-level values are objects or arrays, e.g. { ITEM: [...], USER: [...] }.")}let i=R(r),d="/records/import/json",c={headers:Object.assign({},w(i)),method:"POST",requestData:{label:a,data:o,options:n}},p=typeof this.logger=="function"?y():"";(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let S=I(l.data)?(g=l.data)==null?void 0:g.map(P=>new T(P)):[];return new _(S,l.total)}return new _([])},importCsv:async(e,r)=>{var d,c;let s=R(r),n="/records/import/csv",a={headers:Object.assign({},w(s)),method:"POST",requestData:e},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let p=I(i.data)?i.data.map(l=>new T(l)):[];return new _(p,i.total)}return new _([])},delete:async(e,r)=>{var d,c,p;if(ee(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new k("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let s=R(r),n="/records/delete",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteById:async(e,r)=>{var c,p;let s=R(r),n=I(e),a=n?"/records/delete":`/records/${e}`,o={headers:Object.assign({},w(s)),method:n?"POST":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d},export:async(e,r)=>{var d,c;let s=R(r),n="/records/export/csv",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,r)=>{var l,h;let{id:s,...n}=e,a=R(r),o=s?`/records/${s}/search`:"/records/search",i={headers:Object.assign({},w(a)),method:"POST",requestData:n!=null?n:{}},d=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:c.data});let p=c.data.map(u=>new T(u));return new _(p,c.total,e)},vectorSearch:async(e,r)=>{var p,l,h,u,g,S,P;let s=R(r),n="/ai/search",a={method:"POST",headers:Object.assign({},w(s)),requestData:e},o=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=((h=i.data)!=null?h:[]).map($=>new T($)),c=new _(d,(u=i.total)!=null?u:0);return c.vectorSearch=(g=i.meta)==null?void 0:g.vectorSearch,c.textSearch=(S=i.meta)==null?void 0:S.textSearch,c.fusion=(P=i.meta)==null?void 0:P.fusion,c},textSearch:async(e,r)=>{var p,l,h,u,g;let s=R(r),n="/search/text",a={method:"POST",headers:Object.assign({},w(s)),requestData:e},o=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=((h=i.data)!=null?h:[]).map(S=>new T(S)),c=new _(d,(u=i.total)!=null?u:0);return c.textSearch=(g=i.meta)==null?void 0:g.textSearch,c},findById:async(e,r)=>{var d,c;let s=R(r),n=I(e)?"/records/search":`/records/${e}`,a={headers:Object.assign({},w(s)),method:I(e)?"POST":"GET",requestData:I(e)?{where:{$id:{$in:e}},limit:e.length}:void 0},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),I(e)){let p=i.data.map(l=>new T(l));return new _(p,i.total)}else return new T(i.data)},findOne:async(e,r)=>{var c,p;let s=R(r),n="/records/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data});let[d]=i.data;return new T(d)},findUniq:async(e,r)=>{var c,p;let s=R(r),n="/records/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new ce(i.total,e);let[d]=i.data;return new T(d)},set:async({target:e,label:r,data:s,options:n,vectors:a},o)=>{var g,S;let i=R(o),c=`/records/${C(e)}`,p={headers:Object.assign({},w(i)),method:"PUT",requestData:{}},l=typeof this.logger=="function"?y():"",h=te(W(s));if(I(h)&&h.every(J))p.requestData={label:r,properties:h,...(a==null?void 0:a.length)&&{vectors:a}};else if(re(h))p.requestData={label:r,data:h,options:n,...(a==null?void 0:a.length)&&{vectors:a}};else throw E(h)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(g=this.logger)==null||g.call(this,{requestId:l,path:c,...p});let u=await this.fetcher(c,p);return(S=this.logger)==null||S.call(this,{requestId:l,path:c,...p,responseData:u.data}),u!=null&&u.success&&(u!=null&&u.data)?new T(u.data):new T},update:async({target:e,label:r,data:s,options:n},a)=>{var u,g;let o=C(e),i=R(a),d=`/records/${o}`,c={headers:Object.assign({},w(i)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?y():"",l=te(W(s));if(I(l)&&l.every(J))c.requestData={label:r,properties:l};else if(re(l))c.requestData={label:r,data:l,options:n};else throw E(l)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(u=this.logger)==null||u.call(this,{requestId:p,path:d,...c});let h=await this.fetcher(d,c);return(g=this.logger)==null||g.call(this,{requestId:p,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new T(h.data):new T},upsert:async({label:e,data:r,options:s,vectors:n},a)=>{var u,g,S;let o=R(a),i="/records",d={headers:Object.assign({},w(o)),method:"POST",requestData:{}},c=typeof this.logger=="function"?y():"",p=te(W(r)),l={...s,mergeBy:(u=s==null?void 0:s.mergeBy)!=null?u:[]};if(I(p)&&p.every(J))d.requestData={label:e,properties:p,options:l,...(n==null?void 0:n.length)&&{vectors:n}};else if(re(p))d.requestData={label:e,data:p,options:l,...(n==null?void 0:n.length)&&{vectors:n}};else throw E(p)?new Error("Provided data is not a flat object. Upsert supports flat objects or property drafts array."):new Error("Provided data is not valid.");(g=this.logger)==null||g.call(this,{requestId:c,path:i,...d});let h=await this.fetcher(i,d);return(S=this.logger)==null||S.call(this,{requestId:c,path:i,...d,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new T(h.data):new T}};this.relationships={patterns:{list:async()=>{var a,o;let e="/relationships/patterns",r={method:"GET",headers:{}},s=typeof this.logger=="function"?y():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},analyze:async()=>{var a,o;let e="/relationships/patterns/analyze",r={method:"POST",headers:{},requestData:{}},s=typeof this.logger=="function"?y():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},approve:async e=>{var o,i;let r=`/relationships/patterns/${encodeURIComponent(e)}/approve`,s={method:"POST",headers:{},requestData:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},ignore:async e=>{var o,i;let r=`/relationships/patterns/${encodeURIComponent(e)}/ignore`,s={method:"POST",headers:{},requestData:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},delete:async(e,r)=>{var d,c;let s=r!=null&&r.deleteExisting?"?deleteExisting=true":"",n=`/relationships/patterns/${encodeURIComponent(e)}${s}`,a={method:"DELETE",headers:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}},createMany:async(e,r)=>{var d,c;let s=R(r),n="/relationships/create-many",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteMany:async(e,r)=>{var d,c;let s=R(r),n="/relationships/delete-many",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e={},r)=>{var d,c;let s=R(r),n="/relationships/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.properties={delete:async(e,r)=>{var d,c;let s=R(r),n=`/properties/${e}`,a={headers:Object.assign({},w(s)),method:"DELETE"},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,r)=>{var d,c;let s=R(r),n="/properties/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},findById:async(e,r)=>{var d,c;let s=R(r),n=`/properties/${e}`,a={headers:Object.assign({},w(s)),method:"GET"},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},values:async(e,r,s)=>{var c,p;let n=R(s),a=`/properties/${e}/values`,o={headers:Object.assign({},w(n)),method:"POST",requestData:r!=null?r:{}},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.labels={find:async(e,r)=>{var d,c;let s=R(r),n="/labels/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let r="/tx",s={method:"POST",requestData:E(e)?e:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),new j(a.data.id)},commit:async e=>{var i,d;let s=`/tx/${R(e)}/commit`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o},get:async e=>{var i,d;let s=`/tx/${R(e)}`,n={method:"GET"},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),new j(o.data.id)},rollback:async e=>{var i,d;let s=`/tx/${R(e)}/rollback`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",r={method:"GET"},s=typeof this.logger=="function"?y():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n}};this.query={raw:async({query:e,params:r},s)=>{var c,p;let n=R(s),a="/query/raw",o={headers:Object.assign({},w(n)),method:"POST",requestData:{query:e,params:r}},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.textIndexes={find:async()=>this.textIndexRequest("/text-indexes","GET"),create:async e=>this.textIndexRequest("/text-indexes","POST",e),suggestName:async e=>this.textIndexRequest("/text-indexes/name-suggestion","POST",e),delete:async e=>this.textIndexRequest(`/text-indexes/${encodeURIComponent(e)}`,"DELETE")};this.ai={getSchema:async(e,r)=>{var d,c;let s=R(r),n="/ai/schema",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},getSchemaMarkdown:async(e,r)=>{var d,c;let s=R(r),n="/ai/schema/md",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},indexes:{find:async()=>{var a,o;let e="/ai/indexes",r={method:"GET",headers:{}},s=typeof this.logger=="function"?y():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},create:async e=>{var c,p;let r="/ai/indexes",{external:s,...n}=e,a=s===!0?{...n,sourceType:"external"}:n,o={method:"POST",headers:{},requestData:a},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:r,...o});let d=await this.fetcher(r,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:r,...o,responseData:d.data}),d},upsertVectors:async(e,r)=>{var i,d;let s=`/ai/indexes/${e}/vectors/upsert`,n={method:"POST",headers:{},requestData:r},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o},delete:async e=>{var o,i;let r=`/ai/indexes/${e}`,s={method:"DELETE",headers:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},stats:async e=>{var o,i;let r=`/ai/indexes/${e}/stats`,s={method:"GET",headers:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a}},search:async(e,r)=>{var g,S,P,$,M,N;let s=R(r==null?void 0:r.transaction),n="/ai/search-query",a={method:"POST",headers:Object.assign({},w(s)),requestData:{prompt:e,currentQuery:r==null?void 0:r.currentQuery}},o=typeof this.logger=="function"?y():"";(g=this.logger)==null||g.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(S=this.logger)==null||S.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=i.data.searchQuery,c="/records/search",p={method:"POST",headers:Object.assign({},w(s)),requestData:d!=null?d:{}},l=typeof this.logger=="function"?y():"";(P=this.logger)==null||P.call(this,{requestId:l,path:c,...p});let h=await this.fetcher(c,p);($=this.logger)==null||$.call(this,{requestId:l,path:c,...p,responseData:h.data});let u=((M=h.data)!=null?M:[]).map(Q=>new T(Q));return new _(u,(N=h.total)!=null?N:0,d,i.data.warnings)}};if(this.fetcher=null,r!=null&&r.direct){if(!r.engineUrl)throw new Error("Direct mode requires `engineUrl`, the standalone engine base URL.");if(!r.httpClient)throw new Error("Direct mode requires an HTTP client; import the SDK from its Node or browser entry.");this.direct=new Re({engineUrl:r.engineUrl,token:e!=null?e:"",httpClient:r.httpClient,scope:r.scope}),this.fetcher=Tt(this.direct)}else if(r!=null&&r.httpClient){let s=Ot(r);this.fetcher=bt({httpClient:r.httpClient,token:e,url:s})}r!=null&&r.options&&(this.options=r==null?void 0:r.options),r!=null&&r.logger&&(this.logger=r==null?void 0:r.logger)}_extractTargetIds(e,r){var s;if(e instanceof T){let n=C(e);if(!n)throw new k(`${r} error: Target id is empty`);return[n]}if(I(e)&&e.every(n=>n instanceof T)){let n=e.map(C).filter(A);if(!n.length)throw new k(`${r} error: Target ids are empty`);return n}if(e instanceof _){let n=(s=e.data)==null?void 0:s.map(C).filter(A);if(!(n!=null&&n.length))throw new k(`${r} error: Target ids are empty`);return n}if(E(e)&&"__id"in e)return[e.__id];if(I(e)&&e.every(n=>E(n)&&"__id"in n)){let n=e.map(C).filter(A);if(!n.length)throw new k(`${r} error: Target ids are empty`);return n}return I(e)?e:L(e)?[e]:[]}async textIndexRequest(e,r,s){var i,d;let n={method:r,headers:{},...s===void 0?{}:{requestData:s}},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:e,...n});let o=await this.fetcher(e,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:e,...n,responseData:o.data}),o}};var At,U=class U extends X{constructor(e,r){var a,o;let s=e!=null?e:typeof process<"u"?(a=process.env)==null?void 0:a.RUSHDB_API_KEY:void 0,n=Ce(r);super(s,{...n,httpClient:(o=n.httpClient)!=null?o:At}),U.instance=this,this.initializeSync(s,n)}initializeSync(e,r){U.state={initialized:!0,debug:!1,timeout:ke("timeout",r==null?void 0:r.timeout,8e4),token:e,direct:(r==null?void 0:r.direct)===!0,engineUrl:r==null?void 0:r.engineUrl}}static getInstance(){if(U.instance)return U.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return A(U.instance)}toDBRecordInstance(e){return new T(e)}};U.instance=null,U.state={initialized:!1,debug:!1,timeout:8e4};var x=U,Fe=t=>{At=t};var He=class{constructor(e,r,s){this.label=e,this.schema=r,this.config=s!=null?s:{}}getLabel(){return this.label}async toDBRecordInstance(e){try{return x.getInstance().toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,r){let s=e!=null?e:{};return x.getInstance().records.find({...s,labels:[this.label]},r)}async findOne(e,r){let s=e!=null?e:{};return x.getInstance().records.findOne({...s,labels:[this.label]},r)}async findById(e,r){return this.findOne({where:{$id:e}},r)}async findUniq(e,r){let s=e!=null?e:{};return x.getInstance().records.findUniq({...s,labels:[this.label]},r)}async create(e,r,s){var d,c;let n=await de(this.schema,e),a=fe(this.schema,n),o=A(a),i=x.getInstance();if(o){let p=r!=null?r:await i.tx.begin(),l=await this.find({where:a},p),h=typeof r<"u";if(!((d=l==null?void 0:l.data)!=null&&d.length)){let g=await i.records.create({label:this.label,data:n},p);return h||await p.commit(),g}else switch((c=s==null?void 0:s.onConflict)!=null?c:"throw"){case"upsert":{let S=l.data[0],P=await i.records.set({target:S.id,label:this.label,data:n},p);return h||await p.commit(),P}case"skip":return h||await p.commit(),null;default:throw h||await p.commit(),new v(this.label,a)}}return await i.records.create({label:this.label,data:n},r)}async attach({source:e,target:r,options:s},n){return await x.getInstance().records.attach({source:e,target:r,options:s},n)}async detach({source:e,target:r,options:s},n){return await x.getInstance().records.detach({source:e,target:r,options:s},n)}async validateTargetLabel(e,r){let s=C(e);if(!s)return;let a=await x.getInstance().records.findById(s,r);if(!a)throw new Error(`Record with id "${s}" not found.`);if(a.data.__label!==this.label)throw new TypeError(`Target record label "${a.data.__label}" does not match model label "${this.label}".`)}async handleSetOrUpdate(e,r,s,n){var d,c;if(this.config.validateTargetLabel&&await this.validateTargetLabel(e,n),I(r)&&r.every(J))return await x.getInstance().records[s]({label:this.label,target:e,data:r},n);let a=x.getInstance(),o=await de(this.schema,r),i=fe(this.schema,o);if(!ee(i)){let p=n!=null?n:await a.tx.begin(),l=await this.find({where:i},p),h=typeof n<"u";if(!((d=l==null?void 0:l.data)!=null&&d.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id)===C(e)){let g=await a.records[s]({target:e,label:this.label,data:o},p);return h||await p.commit(),g}else throw h||await p.commit(),new v(this.label,i)}return await a.records[s]({label:this.label,target:e,data:o},n)}async set(e,r,s){return await this.handleSetOrUpdate(e,r,"set",s)}async update(e,r,s){return await this.handleSetOrUpdate(e,r,"update",s)}async createMany(e,r){var o;let s=x.getInstance(),n=typeof r<"u",a=r!=null?r:await s.tx.begin();try{let i=await Promise.all(e.map(async p=>await de(this.schema,p))),d=$e(i,this.schema,this.label);if(!ee(d)){let p=Object.entries(d).map(([h,u])=>({[h]:{$in:u}})),l=await this.find({where:{$or:p}},a);if((o=l==null?void 0:l.data)!=null&&o.length)throw new v(this.label,Object.keys(d))}let c=await s.records.createMany({label:this.label,data:i},a);return n||await a.commit(),c}catch(i){throw n||await a.rollback(),i}}async delete(e,r){if(ee(e.where))throw new k(`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 x.getInstance().records.delete({...e,labels:[this.label]},r)}async deleteById(e,r){return await x.getInstance().records.deleteById(e,r)}};Fe(new ye);var sr=x;0&&(module.exports={CLOUD_ONLY_FORMS,CLOUD_ONLY_METHODS,CloudOnlyError,DBRecordInstance,DBRecordsArrayInstance,DirectModeError,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,isCloudOnlyMethod,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
|
|
27
|
+
`}}return o.trim()};var f=(t,e={})=>({success:!0,data:t,...e}),q=(t,e)=>{let r=new Error(`${t} ${e}`);return r.status=t,r.body={statusCode:t,message:e},r},H=t=>async()=>{throw new J(t,le[t])},Q=(t,e)=>{if(t)throw new ne(`${e} inside a transaction is not supported in direct mode: the engine stages record creates, updates, deletes, links and imports. Run it outside the transaction.`)},ut="__RUSHDB__RELATION__DEFAULT__",G=(t,e,r)=>t.execute({kind:"transaction",transaction:{kind:"stage",transactionId:e,mutation:r}}),je=async(t,e,r)=>{var n;let{record:s}=await G(t,e,{kind:"getRecord",record:{id:r}});return{...(n=s==null?void 0:s.properties)!=null?n:{},__id:r,__label:s==null?void 0:s.__label,__proptypes:{}}},mt=(t,e)=>{t&&Array.isArray(e)&&e.length>0&&Q(t,"A write with inline vectors")},be=t=>{var r,s;if(!t)return t;let e={...(r=t.properties)!=null?r:{}};return e.__id=t.id,e.__label=t.label,e.__proptypes=(s=t.propertyTypes)!=null?s:{},t.score!==void 0&&(e.__score=t.score),e},De=t=>(t!=null?t:[]).map(e=>be(e)),Ue=t=>t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:Array.isArray(t.properties)?Object.fromEntries(t.properties.map(e=>[e.name,e.value])):t.properties&&typeof t.properties=="object"?t.properties:{},Kt=t=>t==null||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?"desc":typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).map(([e,r])=>[e==="__id"?"id":e,r])),se=(t={})=>{var s,n,a,o,i,d;let e=(s=t.pagination)!=null?s:{},r={labels:(n=t.labels)!=null?n:[],predicate:(a=t.where)!=null?a:{},select:t.select,order:Kt(t.orderBy),offset:(i=(o=t.skip)!=null?o:e.skip)!=null?i:0,limit:(d=t.limit)!=null?d:e.limit};return Array.isArray(t.groupBy)&&t.groupBy.length>0&&(r.groupBy=t.groupBy),r},xe=t=>t==null||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0,Ne=async(t,e)=>(await t.execute({kind:"query",query:{kind:"record",id:e}})).record,gt=async(t,e)=>{var s,n,a;let r=await t.execute({kind:"query",query:{kind:"records",query:se(e)}});return r.kind==="rows"?{data:(s=r.rows)!=null?s:[],total:(n=r.total)!=null?n:0}:{data:De(r.records),total:(a=r.total)!=null?a:0}},ae=async t=>{var e;return(e=(await t.execute({kind:"describe",describe:{kind:"vectorIndexes"}})).indexes)!=null?e:[]},Me=async t=>{var e;return(e=(await t.execute({kind:"describe",describe:{kind:"indexes"}})).indexes)!=null?e:[]},he=t=>{var r;let e=Number((r=t.dimensions)!=null?r:0);return{id:t.name,name:t.name,label:t.label,propertyName:t.property,vectorPropertyName:`_emb_external_${t.similarity}_${e}`,similarityFunction:t.similarity,dimensions:e,sourceType:"external",status:t.status}},yt=t=>{var e,r;return{name:t.name,label:t.label,property:t.property,consistency:(e=t.consistency)!=null?e:"eventual",status:t.state,pending:(r=t.pending)!=null?r:0}},Ve=async t=>(await Me(t)).filter(e=>e.kind==="text").map(yt),ft=64,St=t=>t.join(".").slice(0,ft).replace(/[.:-]+$/,""),Te=t=>t.replace(/[^A-Za-z0-9_-]/g,"-"),Le=(t,e)=>{if(!e.has(t))return t;for(let r=2;;r++){let s=`-${r}`,n=t.slice(0,ft-s.length)+s;if(!e.has(n))return n}},ot=({label:t,property:e})=>St([Te(t),e==="*"?"all":Te(e),"text"]),Wt=(t,e,r)=>St([Te(t.label),Te(t.propertyName),"external",String(e),r]).replace(/^emb__/,"emb_"),Ie=async(t,e,r,s)=>{if(!Array.isArray(e)||e.length===0)return[];let n=s!=null?s:await ae(t);return e.map(a=>{if(typeof(a==null?void 0:a.index)=="string")return a;if(!r)throw q(422,"inline vectors require a record label to select their index");let o=Array.isArray(a.vector)?a.vector.length:void 0,i=n.filter(d=>d.label===r&&d.property===a.propertyName&&(a.similarityFunction===void 0||d.similarity===a.similarityFunction)&&(o===void 0||Number(d.dimensions)===o));if(i.length!==1)throw q(i.length===0?404:422,i.length===0?`No vector index matches label "${r}", property "${a.propertyName}"`:`${i.length} vector indexes match label "${r}", property "${a.propertyName}"; name one with \`index\``);return{...a,index:i[0].name}})},Yt=async(t,e,r)=>{let s=Array.isArray(e)?e:[e],n=i=>Array.isArray(i==null?void 0:i.$vectors)&&i.$vectors.length>0;if(!s.some(n))return e;let a=await ae(t),o=await Promise.all(s.map(async i=>n(i)?{...i,$vectors:await Ie(t,i.$vectors,r,a)}:i));return Array.isArray(e)?o:o[0]},Jt=()=>{var s;let t=new Uint8Array(16);if(typeof((s=globalThis.crypto)==null?void 0:s.getRandomValues)=="function")globalThis.crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);let e=Date.now();for(let n=0;n<6;n++)t[n]=Math.floor(e/2**(8*(5-n)))&255;t[6]=t[6]&15|112,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},Gt=async({body:t,engine:e,txId:r})=>{var i,d,c,l,p,h;let s=!!((i=t.options)!=null&&i.mergeStrategy)||Array.isArray((d=t.options)==null?void 0:d.mergeBy),n=Ue(t);if(r){s&&Q(r,"An upsert"),mt(r,t.vectors);let u=Jt();return await G(e,r,{kind:"createRecord",label:t.label,id:u,properties:n,options:(c=t.options)!=null?c:{}}),f(await je(e,r,u))}let a=s?{...t.options,mergeBy:(p=(l=t.options)==null?void 0:l.mergeBy)!=null?p:[]}:(h=t.options)!=null?h:{},o=await e.execute({kind:"mutate",mutation:{kind:"putRecord",mode:"create",label:t.label,properties:n,vectors:await Ie(e,t.vectors,t.label),options:a}});return f(be(o.record))},it=t=>async({body:e,params:[r],engine:s,txId:n})=>{var d,c;let a=typeof e.label=="string"&&e.label?e.label:void 0;if(n){if(mt(n,e.vectors),a){let l=await je(s,n,r);l.__label&&l.__label!==a&&await G(s,n,{kind:"retypeRecord",record:{id:r},fromLabel:l.__label,toLabel:a})}return await G(s,n,{kind:"updateRecord",record:{id:r},properties:Ue(e),replace:t==="replace"}),f(await je(s,n,r))}let o=a;if(a||(d=e.vectors)!=null&&d.length){let l=await Ne(s,r);a&&(l!=null&&l.label)&&l.label!==a&&await s.execute({kind:"mutate",mutation:{kind:"retypeRecord",id:r,fromLabel:l.label,toLabel:a}}),o=a!=null?a:l==null?void 0:l.label}let i=await s.execute({kind:"mutate",mutation:{kind:"putRecord",mode:t,id:r,properties:Ue(e),vectors:await Ie(s,e.vectors,o),options:(c=e.options)!=null?c:{}}});return f(be(i.record))},zt=async(t,e,r)=>{var o;if(!e)return r;let s;try{s=(o=await Ne(t,e))==null?void 0:o.label}catch(i){if((i==null?void 0:i.status)===404)return;throw i}let n={[s]:{$id:e}},a=r.where;return{...r,where:xe(a)?n:{$and:[a,n]}}},ct=async({body:t,params:[e],engine:r})=>{let s=await zt(r,e,t);if(!s)return f([],{total:0});let{data:n,total:a}=await gt(r,s);return f(n,{total:a})},dt=(t,e,r)=>e?G(t,e,{kind:"ingest",ingest:r}):t.execute({kind:"ingest",ingest:r}),lt=(t,e)=>{var r,s;return e&&((r=t.records)!=null&&r.length)?f(De(t.records)):f({message:"Records have been successfully imported",count:Number((s=t.count)!=null?s:0)})},Xt=["delimiter","header","skipEmptyLines","dynamicTyping","quoteChar","escapeChar","newline"],pt=t=>{var e,r,s,n,a,o,i,d,c,l,p,h;return{relationType:(e=t.type)!=null?e:ut,direction:String((r=t.direction)!=null?r:"").toLowerCase()==="in"?"in":"out",allowCartesian:(s=t.manyToMany)!=null?s:!1,properties:(n=t.properties)!=null?n:{},source:{label:(a=t.source)==null?void 0:a.label,property:(o=t.source)==null?void 0:o.key,predicate:(d=(i=t.source)==null?void 0:i.where)!=null?d:{}},target:{label:(c=t.target)==null?void 0:c.label,property:(l=t.target)==null?void 0:l.key,predicate:(h=(p=t.target)==null?void 0:p.where)!=null?h:{}}}},we=t=>Array.isArray(t)?t:[t],Zt=t=>{var r,s;let e=new Map;for(let n of t){let a=e.get(n.id);if(a){a.recordsCount+=Number((r=n.recordsCount)!=null?r:0),a.isArray||(a.isArray=n.isArray===!0);continue}e.set(n.id,{id:n.id,name:n.name,type:n.type,recordsCount:Number((s=n.recordsCount)!=null?s:0),isArray:n.isArray===!0})}return Array.from(e.values(),({isArray:n,...a})=>({...a,metadata:JSON.stringify({cardinality:n?"OrderedMany":"Single",nullability:"Nullable"})}))},Rt=async(t,e={})=>{var s;let r=await t.execute({kind:"describe",describe:{kind:"properties",query:se(e),...xe(e.where)?{detail:"catalog"}:{}}});return Zt((s=r.properties)!=null?s:[])},ht=async(t,e)=>{var s;let r=(await Rt(t)).find(n=>n.name===e||n.id===e);return r&&{...r,id:(s=r.id)!=null?s:r.name}},wt=async(t,e,r)=>{var a,o;if(typeof e.query!="string"||e.query.trim()==="")throw q(422,"text.query is required");let s=await Ve(t),n;if(e.index!==void 0){if(n=s.find(i=>i.name===e.index),!n)throw q(404,`No text index named "${e.index}"`)}else{let i=r[0];if(!i)throw q(422,"Name a text index with `index`, or give `labels`");let d=s.filter(c=>c.label===i&&c.status==="ready"&&(e.property===void 0||c.property===e.property));if(d.length===0)throw q(404,`No ready text index on label "${i}"`);if(d.length>1)throw q(422,`Label "${i}" has several text indexes (${d.map(c=>c.name).join(", ")}); name one with \`index\``);n=d[0]}return{index:n.name,label:n.label,query:e.query,allTerms:(a=e.allTerms)!=null?a:!1,phrase:(o=e.phrase)!=null?o:!1}},er=async({body:t,engine:e})=>{var p,h,u,y,S,E,_,M,V,K,oe;let r=(p=t.queryVector)!=null?p:[];if(r.length===0)throw new J("records.vectorSearch",pe["records.vectorSearch"]);let s=await ae(e),n;if(typeof t.index=="string"){if(n=s.find(N=>N.name===t.index),!n)throw q(404,`No vector index named "${t.index}"`)}else{let N=((h=t.labels)!=null?h:[])[0],F=s.filter(W=>{var ie;return W.label===N&&W.property===t.propertyName&&(t.similarityFunction===void 0||W.similarity===t.similarityFunction)&&Number(W.dimensions)===((ie=t.dimensions)!=null?ie:r.length)});if(F.length!==1)throw q(F.length===0?404:422,F.length===0?`No vector index matches label "${N}", property "${t.propertyName}"`:`${F.length} vector indexes match label "${N}", property "${t.propertyName}"; name one with \`index\``);n=F[0]}let a=(u=t.labels)!=null&&u.length?t.labels:[n.label],o={property:n.property,vector:r,similarity:(y=n.similarity)!=null?y:"cosine",index:n.name,mode:t.mode,ef:t.ef,scoreThreshold:t.scoreThreshold},i=t.text?await wt(e,{...t.text,query:(S=t.text.query)!=null?S:t.query},a):void 0,d=i?{kind:"hybrid",query:{labels:a,predicate:(E=t.where)!=null?E:{},vector:{...o,weight:t.weight,prefetchLimit:t.prefetchLimit},text:{index:i.index,query:i.query,allTerms:i.allTerms,phrase:i.phrase,weight:t.text.weight,prefetchLimit:t.text.prefetchLimit},fusion:t.fusion,rrfK:t.rrfK,offset:(_=t.skip)!=null?_:0,limit:(M=t.limit)!=null?M:10}}:{kind:"vector",query:{...o,labels:a,predicate:(V=t.where)!=null?V:{},offset:(K=t.skip)!=null?K:0,limit:(oe=t.limit)!=null?oe:10}},c=await e.execute({kind:"query",query:d}),l=De(c.records);return f(l,{total:l.length,meta:{vectorSearch:c.vectorSearch,textSearch:c.textSearch,fusion:c.fusion}})},O="([^/]+)",xt=[{method:"GET",pattern:new RegExp(`^/records/${O}$`),handle:async({params:[t],engine:e})=>f(be(await Ne(e,t)))},{method:"POST",pattern:/^\/records$/,handle:Gt},{method:"PATCH",pattern:new RegExp(`^/records/${O}$`),handle:it("merge")},{method:"PUT",pattern:new RegExp(`^/records/${O}$`),handle:it("replace")},{method:"DELETE",pattern:new RegExp(`^/records/${O}$`),handle:async({params:[t],engine:e,txId:r})=>(r?await G(e,r,{kind:"deleteRecord",record:{id:t}}):await e.execute({kind:"mutate",mutation:{kind:"deleteRecord",id:t}}),f({message:"Record deleted"}))},{method:"POST",pattern:/^\/records\/delete$/,handle:async({body:t,engine:e,txId:r})=>{var n;Q(r,"records.delete");let s=await e.execute({kind:"mutate",mutation:{kind:"deleteRecords",query:se(t)}});return f({message:`${(n=s.affected)!=null?n:0} records deleted`})}},{method:"POST",pattern:/^\/records\/search$/,handle:ct},{method:"POST",pattern:new RegExp(`^/records/${O}/search$`),handle:ct},{method:"POST",pattern:/^\/records\/import\/json$/,handle:async({body:t,engine:e,txId:r})=>{var n,a;let s=await dt(e,r,{kind:"documents",label:t.label,documents:await Yt(e,t.data,t.label),options:(n=t.options)!=null?n:{}});return lt(s,(a=t.options)==null?void 0:a.returnResult)}},{method:"POST",pattern:/^\/records\/import\/csv$/,handle:async({body:t,engine:e,txId:r})=>{var i,d,c,l,p,h,u;let s=(i=t.vectors)!=null&&i.length?await ae(e):[],n=await Promise.all(((d=t.vectors)!=null?d:[]).map(y=>Ie(e,y,t.label,s))),a=Object.fromEntries(Object.entries((c=t.parseConfig)!=null?c:{}).filter(([y])=>Xt.includes(y))),o=await dt(e,r,{kind:"csv",label:t.label,data:(l=t.data)!=null?l:"",parseConfig:a,options:(p=t.options)!=null?p:{},vectors:n});return Number((h=o.count)!=null?h:0)===0?f(!0):lt(o,(u=t.options)==null?void 0:u.returnResult)}},{method:"POST",pattern:/^\/records\/export\/csv$/,handle:async({body:t,engine:e})=>{let r=await e.execute({kind:"query",query:{kind:"exportCsv",query:se({labels:t.labels,where:t.where,orderBy:t.orderBy,skip:typeof t.skip=="number"?t.skip:0,limit:typeof t.limit=="number"?t.limit:100})}});return f({fileContent:r.content,dateTime:new Date().toISOString()})}},{method:"POST",pattern:new RegExp(`^/relationships/${O}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var o,i,d,c;let n=(o=t.type)!=null?o:ut,a=String((i=t.direction)!=null?i:"").toLowerCase()==="in";if(s)for(let l of we(t.targetIds))await G(r,s,{kind:"createRelationship",relationType:n,source:{id:a?l:e},target:{id:a?e:l},properties:(d=t.properties)!=null?d:{}});else await r.execute({kind:"mutate",mutation:{kind:"linkRecordsById",command:{relationType:n,direction:a?"in":"out",sourceIds:[e],targetIds:we(t.targetIds),properties:(c=t.properties)!=null?c:{}}}});return f({message:`Relations to Record ${e} have been successfully created`})}},{method:"PUT",pattern:new RegExp(`^/relationships/${O}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var a;Q(s,"records.detach");let n=String((a=t.direction)!=null?a:"").toLowerCase();return await r.execute({kind:"mutate",mutation:{kind:"unlinkRecordsById",command:{relationTypes:we(t.typeOrTypes).filter(Boolean),...n==="in"||n==="out"?{direction:n}:{},sourceIds:[e],targetIds:we(t.targetIds)}}}),f({message:`Relations to Record ${e} have been successfully deleted`})}},{method:"POST",pattern:/^\/relationships\/create-many$/,handle:async({body:t,engine:e,txId:r})=>(Q(r,"relationships.createMany"),await e.execute({kind:"mutate",mutation:{kind:"linkRecords",command:pt(t)}}),f({message:"Relations have been successfully created"}))},{method:"POST",pattern:/^\/relationships\/delete-many$/,handle:async({body:t,engine:e,txId:r})=>(Q(r,"relationships.deleteMany"),await e.execute({kind:"mutate",mutation:{kind:"unlinkRecords",command:pt(t)}}),f({message:"Relations have been successfully deleted"}))},{method:"POST",pattern:/^\/relationships\/search$/,handle:async({body:t,engine:e})=>{var s,n,a,o,i,d,c,l,p,h,u;let r=await e.execute({kind:"query",query:{kind:"relationships",query:{sourceLabels:(n=(s=t.source)==null?void 0:s.labels)!=null?n:[],targetLabels:(o=(a=t.target)==null?void 0:a.labels)!=null?o:[],relationType:(i=t.where)==null?void 0:i.type,predicate:Object.fromEntries(Object.entries((d=t.where)!=null?d:{}).filter(([y])=>y!=="type")),sourcePredicate:xe((c=t.source)==null?void 0:c.where)?void 0:t.source.where,targetPredicate:xe((l=t.target)==null?void 0:l.where)?void 0:t.target.where,offset:(p=t.skip)!=null?p:0,limit:t.limit}}});return f((h=r.relationships)!=null?h:[],{total:(u=r.total)!=null?u:0})}},{method:"GET",pattern:/^\/relationships\/patterns$/,handle:H("relationships.patterns.list")},{method:"POST",pattern:/^\/relationships\/patterns\/analyze$/,handle:H("relationships.patterns.analyze")},{method:"POST",pattern:new RegExp(`^/relationships/patterns/${O}/approve$`),handle:H("relationships.patterns.approve")},{method:"POST",pattern:new RegExp(`^/relationships/patterns/${O}/ignore$`),handle:H("relationships.patterns.ignore")},{method:"DELETE",pattern:new RegExp(`^/relationships/patterns/${O}$`),handle:H("relationships.patterns.delete")},{method:"POST",pattern:/^\/properties\/search$/,handle:async({body:t,engine:e})=>{var r,s;return f(await Rt(e,{labels:(r=t.labels)!=null?r:[],where:(s=t.where)!=null?s:{}}))}},{method:"GET",pattern:new RegExp(`^/properties/${O}$`),handle:async({params:[t],engine:e})=>{let r=await ht(e,t);if(!r)throw q(404,`property \`${t}\` does not exist`);return f(r)}},{method:"DELETE",pattern:new RegExp(`^/properties/${O}$`),handle:async({params:[t],engine:e,txId:r})=>{Q(r,"properties.delete");let s=await ht(e,t);if(!s)throw q(404,`property \`${t}\` does not exist`);return await e.execute({kind:"mutate",mutation:{kind:"deleteProperty",name:s.name}}),f({message:`Property (${t}) has been successfully deleted.`})}},{method:"POST",pattern:new RegExp(`^/properties/${O}/values$`),handle:async({body:t,params:[e],engine:r})=>{var a,o,i,d,c,l;let s=!!t.query||!!t.limit,n=await r.execute({kind:"query",query:{kind:"propertyValues",property:e,query:se({labels:(a=t.labels)!=null?a:[],where:(o=t.where)!=null?o:{}}),...s?{mode:"topK",limit:(i=t.limit)!=null?i:100}:{},...t.query?{search:{text:t.query,match:(d=t.match)!=null?d:"contains",...t.domainOnMiss?{domainOnMiss:t.domainOnMiss}:{},...t.minSimilarity!==void 0?{minSimilarity:t.minSimilarity}:{}}}:{}}});return f({values:(c=n.values)!=null?c:[],...(l=n.counts)!=null&&l.length?{counts:n.counts}:{},...s&&n.distinctCount!==void 0?{distinctCount:n.distinctCount}:{},...n.searchMissed?{searchMissed:!0}:{}})}},{method:"POST",pattern:/^\/labels\/search$/,handle:async({body:t,engine:e})=>{var n;let r=await e.execute({kind:"describe",describe:{kind:"labels",query:se(t)}}),s={};for(let a of(n=r.labels)!=null?n:[])s[a]=(await gt(e,{...t,labels:[a],skip:0,limit:1})).total;return f(s)}},{method:"POST",pattern:/^\/tx$/,handle:async({body:t,engine:e})=>{var s;let r=await e.execute({kind:"transaction",transaction:{kind:"begin",ttlMs:t.ttl,autocommit:(s=t.autocommit)!=null?s:!1}});return f({id:r.transactionId})}},{method:"GET",pattern:new RegExp(`^/tx/${O}$`),handle:async({params:[t]})=>f({id:t})},{method:"POST",pattern:new RegExp(`^/tx/${O}/commit$`),handle:async({params:[t],engine:e})=>{var s;let r=await e.execute({kind:"transaction",transaction:{kind:"commit",transactionId:t}});if(r.status!=="committed")throw q(409,`Transaction commit failed: ${(s=r.reason)!=null?s:r.status}`);return f({message:`Transaction (${t}) has been successfully committed.`})}},{method:"POST",pattern:new RegExp(`^/tx/${O}/rollback$`),handle:async({params:[t],engine:e})=>(await e.execute({kind:"transaction",transaction:{kind:"rollback",transactionId:t}}),f({message:`Transaction (${t}) has been rolled back.`}))},{method:"POST",pattern:/^\/query\/raw$/,handle:async({body:t,engine:e,txId:r})=>{var n,a;Q(r,"query.raw");let s=await e.execute({kind:"query",query:{kind:"statement",language:"cypher",statement:t.query,parameters:(n=t.params)!=null?n:null}});return f({records:(a=s.rows)!=null?a:[]})}},{method:"GET",pattern:/^\/text-indexes$/,handle:async({engine:t})=>f(await Ve(t))},{method:"POST",pattern:/^\/text-indexes$/,handle:async({body:t,engine:e})=>{var n,a;let r=new Set((await Me(e)).map(o=>String(o.name)));if(t.name!==void 0&&r.has(t.name))throw q(409,`An index named "${t.name}" already exists`);let s=await e.execute({kind:"index",index:{kind:"create",definition:{name:(n=t.name)!=null?n:Le(ot(t),r),label:t.label,property:t.property,kind:"text",consistency:(a=t.consistency)!=null?a:"eventual"}}});return f(yt(s.index))}},{method:"POST",pattern:/^\/text-indexes\/name-suggestion$/,handle:async({body:t,engine:e})=>{let r=new Set((await Me(e)).map(s=>String(s.name)));return f({name:Le(ot(t),r)})}},{method:"DELETE",pattern:new RegExp(`^/text-indexes/${O}$`),handle:async({params:[t],engine:e})=>{let r=decodeURIComponent(t);if(!(await Ve(e)).some(s=>s.name===r))throw q(404,`No text index named "${r}"`);return await e.execute({kind:"index",index:{kind:"drop",name:r}}),f({deleted:!0})}},{method:"POST",pattern:/^\/search\/text$/,handle:async({body:t,engine:e})=>{var a,o,i,d,c,l,p;if(typeof t.query!="string"||t.query.trim()==="")throw q(422,"query is required");let r=await wt(e,t,(a=t.labels)!=null?a:[]),s=await e.execute({kind:"query",query:{kind:"hybrid",query:{labels:(o=t.labels)!=null&&o.length?t.labels:[r.label],predicate:(i=t.where)!=null?i:{},text:{index:r.index,query:r.query,allTerms:r.allTerms,phrase:r.phrase},offset:(d=t.skip)!=null?d:0,limit:(c=t.limit)!=null?c:10}}}),n=De(s.records);return f(n,{total:(p=(l=s.textSearch)==null?void 0:l.matches)!=null?p:n.length,meta:{textSearch:s.textSearch}})}},{method:"POST",pattern:/^\/ai\/schema$/,handle:async({body:t,engine:e})=>f(await ve(e,t.labels,he))},{method:"POST",pattern:/^\/ai\/schema\/md$/,handle:async({body:t,engine:e})=>f(at(await ve(e,t.labels,he)))},{method:"POST",pattern:/^\/ai\/search-query$/,handle:H("ai.search")},{method:"POST",pattern:/^\/ai\/search$/,handle:er},{method:"GET",pattern:/^\/ai\/indexes$/,handle:async({engine:t})=>f((await ae(t)).map(he))},{method:"POST",pattern:/^\/ai\/indexes$/,handle:async({body:t,engine:e})=>{var d,c;if(t.sourceType!=="external")throw new J("ai.indexes.create",pe["ai.indexes.create"]);let r=Number(t.dimensions);if(!Number.isInteger(r)||r<1||r>4096)throw q(422,"dimensions must be an integer between 1 and 4096");let s=(d=t.similarityFunction)!=null?d:"cosine",n=await ae(e),a=n.find(l=>l.label===t.label&&l.property===t.propertyName&&l.similarity===s&&Number(l.dimensions)===r);if(a)throw q(409,`An embedding index for label "${t.label}", property "${t.propertyName}", sourceType "external", similarityFunction "${s}", and dimensions ${r} already exists ("${a.name}")`);let o=new Set(n.map(l=>String(l.name)));if(t.name!==void 0&&o.has(t.name))throw q(409,`An embedding index named "${t.name}" already exists`);let i=await e.execute({kind:"index",index:{kind:"createVector",definition:{label:t.label,property:t.propertyName,dimensions:r,similarity:s,name:(c=t.name)!=null?c:Le(Wt(t,r,s),o)}}});return f(he(i.index))}},{method:"DELETE",pattern:new RegExp(`^/ai/indexes/${O}$`),handle:async({params:[t],engine:e})=>(await e.execute({kind:"index",index:{kind:"dropVector",name:decodeURIComponent(t)}}),f({deleted:!0,queued:!1}))},{method:"GET",pattern:new RegExp(`^/ai/indexes/${O}/stats$`),handle:async({params:[t],engine:e})=>{var s,n;let r=await e.execute({kind:"describe",describe:{kind:"vectorIndex",name:decodeURIComponent(t)}});return f({...r.stats,index:he((n=(s=r.stats)==null?void 0:s.index)!=null?n:{})})}},{method:"POST",pattern:new RegExp(`^/ai/indexes/${O}/vectors/upsert$`),handle:async({body:t,params:[e],engine:r})=>{var n;let s=await r.execute({kind:"index",index:{kind:"upsertVectors",name:decodeURIComponent(e),items:(n=t.items)!=null?n:[]}});return f({updated:s.updated,requested:s.requested})}},{method:"POST",pattern:/^\/ai\/values\/search$/,handle:async({body:t,engine:e})=>{var s,n,a,o;let r=await e.execute({kind:"query",query:{kind:"searchValues",search:{text:t.text,match:(s=t.match)!=null?s:"contains",...t.caseSensitive?{caseSensitive:!0}:{},...t.minSimilarity!==void 0?{minSimilarity:t.minSimilarity}:{}},...(n=t.labels)!=null&&n.length?{labels:t.labels}:{},...t.limit?{limit:t.limit}:{}}});return f({matches:(a=r.matches)!=null?a:[],total:(o=r.total)!=null?o:0,...r.skipped?{skipped:r.skipped}:{}})}},{method:"POST",pattern:/^\/ai\/schema\/summary$/,handle:async({body:t,engine:e})=>{var s,n;let r=await e.execute({kind:"describe",describe:{kind:"schemaSummary",...(s=t.labels)!=null&&s.length?{labels:t.labels}:{},...t.fewValues!==void 0?{fewValues:t.fewValues}:{}}});return f((n=r.labels)!=null?n:[])}},{method:"POST",pattern:/^\/ai\/schema\/names$/,handle:async({body:t,engine:e})=>{var s;let r=await e.execute({kind:"describe",describe:{kind:"names",text:t.text,...t.limit?{limit:t.limit}:{}}});return f((s=r.names)!=null?s:[])}},{method:"POST",pattern:/^\/ai\/schema\/join-candidates$/,handle:H("ai.getJoinCandidates")},{method:"GET",pattern:/^\/sdk\/settings$/,handle:H("settings.get")}],Or=xt.map(t=>`${t.method} ${t.pattern.source}`),Tt=t=>async(e,{method:r="GET",headers:s,requestData:n})=>{var c;let a=new URL(String(e),"http://direct"),o=xt.filter(l=>l.method===r&&l.pattern.test(a.pathname)).sort((l,p)=>l.pattern.source.split("(").length-p.pattern.source.split("(").length)[0];if(!o)throw new ne(`${r} ${a.pathname} has no direct-mode mapping`);let i=((c=o.pattern.exec(a.pathname))!=null?c:[]).slice(1),d=s==null?void 0:s["x-transaction-id"];return await o.handle({body:n!=null?n:{},params:i,query:a.searchParams,txId:d,engine:t})};var tr={"Content-Type":"application/json"},bt=({httpClient:t,token:e,url:r})=>async(s,{headers:n,...a})=>{var l;let o=await t.makeRequest(`${r}${s}`,{credentials:"omit",headers:Object.assign({...tr,...n},typeof e<"u"?{Authorization:`Bearer ${e}`}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();let i="",d;try{let p=await o.toJSON();d=p;let h=(l=p==null?void 0:p.message)!=null?l:p==null?void 0:p.error;Array.isArray(h)?i=h.join("; "):typeof h=="string"&&(i=h)}catch{}let c=new Error(i?`${o.getStatusCode()} ${i}`:`${o.getStatusCode()}`);throw c.status=o.getStatusCode(),c.body=d,c};var j=class{constructor(e){this.id=e}async rollback(){return await x.getInstance().tx.rollback(this.id)}async commit(){return await x.getInstance().tx.commit(this.id)}};var Dt="api.rushdb.com";var It="https",Pt="/api/v1";var w=t=>t?{"x-transaction-id":t}:void 0,nr=t=>v(t)||t instanceof j,R=t=>nr(t)?t instanceof j?t.id:t:void 0,Et=t=>/^[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(t),C=t=>{if(v(t)&&Et(t))return t;if(t instanceof T&&t.data)return t.data.__id;if(P(t)&&"__id"in t&&Et(t.__id))return t.__id},z=t=>!(!P(t)||P(t)&&"name"in t&&!v(t.name)||P(t)&&"type"in t&&(!v(t.type)||!Ze.includes(t.type))||!("value"in t)||!qe(t.value)||"metadata"in t&&!v(t.metadata)||"valueSeparator"in t&&!v(t.valueSeparator)),Ot=t=>{let e=It,r=Dt,s=443,n=Pt;if("url"in t){let o=new URL(t.url);e=o.protocol.replace(":",""),r=o.hostname,s=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in t&&"port"in t&&"protocol"in t&&(e=t.protocol.replace(":",""),r=t.host,s=t.port),n&&!n.startsWith("/")&&(n="/"+n);let a="";return e==="http"&&s===80||e==="https"&&s===443||(a=":"+s),`${e}://${r}${a}${n}`},g=(t=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r="";for(let s=0;s<t;s++){let n=Math.floor(Math.random()*e.length);r+=e[n]}return r};var X=class{constructor(e,r){this.records={attach:async({source:e,target:r,options:s},n)=>{var p,h;let a=R(n),i=`/relationships/${C(e)}`,d={headers:Object.assign({},w(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(r,"Attach"),...(s==null?void 0:s.type)&&{type:s.type},...(s==null?void 0:s.direction)&&{direction:s.direction},...(s==null?void 0:s.properties)&&{properties:s.properties}}},c=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:c,path:i,...d});let l=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:l.data}),l},detach:async({source:e,target:r,options:s},n)=>{var p,h;let a=R(n),i=`/relationships/${C(e)}`,d={headers:Object.assign({},w(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(r,"Detach"),...(s==null?void 0:s.typeOrTypes)&&{typeOrTypes:s.typeOrTypes},...(s==null?void 0:s.direction)&&{direction:s.direction}}},c=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:c,path:i,...d});let l=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:l.data}),l},create:async({label:e,data:r,options:s,vectors:n},a)=>{var h,u;let o=R(a),i="/records",d={headers:Object.assign({},w(o)),method:"POST",requestData:{}},c=typeof this.logger=="function"?g():"",l=te(Y(r));if(I(l)&&l.every(z))d.requestData={label:e,properties:l,options:s,...(n==null?void 0:n.length)&&{vectors:n}};else if(re(l))d.requestData={label:e,data:l,options:s,...(n==null?void 0:n.length)&&{vectors:n}};else throw P(l)?new Error("Provided data is not a flat object. Consider using the `importJson` method for nested objects or arrays of nested objects, or use `createMany` for arrays of flat objects."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(u=this.logger)==null||u.call(this,{requestId:c,path:i,...d,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new T(p.data):new T},createMany:async(e,r)=>{var h,u,y;let s=I(e.data)?e.data:[e.data];if(!s.every(S=>re(S)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=e.vectors?I(e.vectors[0])?e.vectors:[e.vectors]:void 0;if(a&&a.length>s.length)throw new Error(`records.createMany: vectors length (${a.length}) exceeds the number of data rows (${s.length}).`);let o=a!=null&&a.length?s.map((S,E)=>{var _;return(_=a[E])!=null&&_.length?{...S,$vectors:a[E]}:S}):s,i=R(r),d="/records/import/json",c={headers:Object.assign({},w(i)),method:"POST",requestData:{label:e.label,data:o,options:e.options}},l=typeof this.logger=="function"?g():"";(h=this.logger)==null||h.call(this,{requestId:l,path:d,...c});let p=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:l,path:d,...c,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)){let S=I(p.data)?(y=p.data)==null?void 0:y.map(E=>new T(E)):[];return new $(S,p.total)}return new $([])},importJson:async(e,r)=>{var h,u,y;let{data:s,options:n}=e,{label:a}=e,o=s;if(!a){let S=P(s)&&!I(s)?te(s):s;if(nt(S))throw new Error("records.importJson: Missing `label`. Provide `label` for top-level arrays or objects with primitive top-level properties, or pass a container object whose top-level values are objects or arrays, e.g. { ITEM: [...], USER: [...] }.")}let i=R(r),d="/records/import/json",c={headers:Object.assign({},w(i)),method:"POST",requestData:{label:a,data:o,options:n}},l=typeof this.logger=="function"?g():"";(h=this.logger)==null||h.call(this,{requestId:l,path:d,...c});let p=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:l,path:d,...c,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)){let S=I(p.data)?(y=p.data)==null?void 0:y.map(E=>new T(E)):[];return new $(S,p.total)}return new $([])},importCsv:async(e,r)=>{var d,c;let s=R(r),n="/records/import/csv",a={headers:Object.assign({},w(s)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let l=I(i.data)?i.data.map(p=>new T(p)):[];return new $(l,i.total)}return new $([])},delete:async(e,r)=>{var d,c,l;if(ee(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new k("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let s=R(r),n="/records/delete",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteById:async(e,r)=>{var c,l;let s=R(r),n=I(e),a=n?"/records/delete":`/records/${e}`,o={headers:Object.assign({},w(s)),method:n?"POST":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d},export:async(e,r)=>{var d,c;let s=R(r),n="/records/export/csv",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,r)=>{var p,h;let{id:s,...n}=e,a=R(r),o=s?`/records/${s}/search`:"/records/search",i={headers:Object.assign({},w(a)),method:"POST",requestData:n!=null?n:{}},d=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:c.data});let l=c.data.map(u=>new T(u));return new $(l,c.total,e)},vectorSearch:async(e,r)=>{var l,p,h,u,y,S,E;let s=R(r),n="/ai/search",a={method:"POST",headers:Object.assign({},w(s)),requestData:e},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=((h=i.data)!=null?h:[]).map(_=>new T(_)),c=new $(d,(u=i.total)!=null?u:0);return c.vectorSearch=(y=i.meta)==null?void 0:y.vectorSearch,c.textSearch=(S=i.meta)==null?void 0:S.textSearch,c.fusion=(E=i.meta)==null?void 0:E.fusion,c},textSearch:async(e,r)=>{var l,p,h,u,y;let s=R(r),n="/search/text",a={method:"POST",headers:Object.assign({},w(s)),requestData:e},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=((h=i.data)!=null?h:[]).map(S=>new T(S)),c=new $(d,(u=i.total)!=null?u:0);return c.textSearch=(y=i.meta)==null?void 0:y.textSearch,c},findById:async(e,r)=>{var d,c;let s=R(r),n=I(e)?"/records/search":`/records/${e}`,a={headers:Object.assign({},w(s)),method:I(e)?"POST":"GET",requestData:I(e)?{where:{$id:{$in:e}},limit:e.length}:void 0},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),I(e)){let l=i.data.map(p=>new T(p));return new $(l,i.total)}else return new T(i.data)},findOne:async(e,r)=>{var c,l;let s=R(r),n="/records/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data});let[d]=i.data;return new T(d)},findUniq:async(e,r)=>{var c,l;let s=R(r),n="/records/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new ce(i.total,e);let[d]=i.data;return new T(d)},set:async({target:e,label:r,data:s,options:n,vectors:a},o)=>{var y,S;let i=R(o),c=`/records/${C(e)}`,l={headers:Object.assign({},w(i)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?g():"",h=te(Y(s));if(I(h)&&h.every(z))l.requestData={label:r,properties:h,...(a==null?void 0:a.length)&&{vectors:a}};else if(re(h))l.requestData={label:r,data:h,options:n,...(a==null?void 0:a.length)&&{vectors:a}};else throw P(h)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:p,path:c,...l});let u=await this.fetcher(c,l);return(S=this.logger)==null||S.call(this,{requestId:p,path:c,...l,responseData:u.data}),u!=null&&u.success&&(u!=null&&u.data)?new T(u.data):new T},update:async({target:e,label:r,data:s,options:n},a)=>{var u,y;let o=C(e),i=R(a),d=`/records/${o}`,c={headers:Object.assign({},w(i)),method:"PATCH",requestData:{}},l=typeof this.logger=="function"?g():"",p=te(Y(s));if(I(p)&&p.every(z))c.requestData={label:r,properties:p};else if(re(p))c.requestData={label:r,data:p,options:n};else throw P(p)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(u=this.logger)==null||u.call(this,{requestId:l,path:d,...c});let h=await this.fetcher(d,c);return(y=this.logger)==null||y.call(this,{requestId:l,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new T(h.data):new T},upsert:async({label:e,data:r,options:s,vectors:n},a)=>{var u,y,S;let o=R(a),i="/records",d={headers:Object.assign({},w(o)),method:"POST",requestData:{}},c=typeof this.logger=="function"?g():"",l=te(Y(r)),p={...s,mergeBy:(u=s==null?void 0:s.mergeBy)!=null?u:[]};if(I(l)&&l.every(z))d.requestData={label:e,properties:l,options:p,...(n==null?void 0:n.length)&&{vectors:n}};else if(re(l))d.requestData={label:e,data:l,options:p,...(n==null?void 0:n.length)&&{vectors:n}};else throw P(l)?new Error("Provided data is not a flat object. Upsert supports flat objects or property drafts array."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:c,path:i,...d});let h=await this.fetcher(i,d);return(S=this.logger)==null||S.call(this,{requestId:c,path:i,...d,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new T(h.data):new T}};this.relationships={patterns:{list:async()=>{var a,o;let e="/relationships/patterns",r={method:"GET",headers:{}},s=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},analyze:async()=>{var a,o;let e="/relationships/patterns/analyze",r={method:"POST",headers:{},requestData:{}},s=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},approve:async e=>{var o,i;let r=`/relationships/patterns/${encodeURIComponent(e)}/approve`,s={method:"POST",headers:{},requestData:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},ignore:async e=>{var o,i;let r=`/relationships/patterns/${encodeURIComponent(e)}/ignore`,s={method:"POST",headers:{},requestData:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},delete:async(e,r)=>{var d,c;let s=r!=null&&r.deleteExisting?"?deleteExisting=true":"",n=`/relationships/patterns/${encodeURIComponent(e)}${s}`,a={method:"DELETE",headers:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}},createMany:async(e,r)=>{var d,c;let s=R(r),n="/relationships/create-many",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteMany:async(e,r)=>{var d,c;let s=R(r),n="/relationships/delete-many",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e={},r)=>{var d,c;let s=R(r),n="/relationships/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.properties={delete:async(e,r)=>{var d,c;let s=R(r),n=`/properties/${e}`,a={headers:Object.assign({},w(s)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,r)=>{var d,c;let s=R(r),n="/properties/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},findById:async(e,r)=>{var d,c;let s=R(r),n=`/properties/${e}`,a={headers:Object.assign({},w(s)),method:"GET"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},values:async(e,r,s)=>{var c,l;let n=R(s),a=`/properties/${e}/values`,o={headers:Object.assign({},w(n)),method:"POST",requestData:r!=null?r:{}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.labels={find:async(e,r)=>{var d,c;let s=R(r),n="/labels/search",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let r="/tx",s={method:"POST",requestData:P(e)?e:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),new j(a.data.id)},commit:async e=>{var i,d;let s=`/tx/${R(e)}/commit`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o},get:async e=>{var i,d;let s=`/tx/${R(e)}`,n={method:"GET"},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),new j(o.data.id)},rollback:async e=>{var i,d;let s=`/tx/${R(e)}/rollback`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",r={method:"GET"},s=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n}};this.query={raw:async({query:e,params:r},s)=>{var c,l;let n=R(s),a="/query/raw",o={headers:Object.assign({},w(n)),method:"POST",requestData:{query:e,params:r}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.textIndexes={find:async()=>this.textIndexRequest("/text-indexes","GET"),create:async e=>this.textIndexRequest("/text-indexes","POST",e),suggestName:async e=>this.textIndexRequest("/text-indexes/name-suggestion","POST",e),delete:async e=>this.textIndexRequest(`/text-indexes/${encodeURIComponent(e)}`,"DELETE")};this.ai={searchValues:async e=>{var o,i;let r="/ai/values/search",s={headers:{},method:"POST",requestData:e},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getSchemaSummary:async e=>{var o,i;let r="/ai/schema/summary",s={headers:{},method:"POST",requestData:e!=null?e:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},resolveNames:async e=>{var o,i;let r="/ai/schema/names",s={headers:{},method:"POST",requestData:e},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getJoinCandidates:async e=>{var o,i;let r="/ai/schema/join-candidates",s={headers:{},method:"POST",requestData:e!=null?e:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getSchema:async(e,r)=>{var d,c;let s=R(r),n="/ai/schema",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},getSchemaMarkdown:async(e,r)=>{var d,c;let s=R(r),n="/ai/schema/md",a={headers:Object.assign({},w(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},indexes:{find:async()=>{var a,o;let e="/ai/indexes",r={method:"GET",headers:{}},s=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},create:async e=>{var c,l;let r="/ai/indexes",{external:s,...n}=e,a=s===!0?{...n,sourceType:"external"}:n,o={method:"POST",headers:{},requestData:a},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:r,...o});let d=await this.fetcher(r,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:r,...o,responseData:d.data}),d},upsertVectors:async(e,r)=>{var i,d;let s=`/ai/indexes/${e}/vectors/upsert`,n={method:"POST",headers:{},requestData:r},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o},delete:async e=>{var o,i;let r=`/ai/indexes/${e}`,s={method:"DELETE",headers:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},stats:async e=>{var o,i;let r=`/ai/indexes/${e}/stats`,s={method:"GET",headers:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a}},search:async(e,r)=>{var y,S,E,_,M,V;let s=R(r==null?void 0:r.transaction),n="/ai/search-query",a={method:"POST",headers:Object.assign({},w(s)),requestData:{prompt:e,currentQuery:r==null?void 0:r.currentQuery}},o=typeof this.logger=="function"?g():"";(y=this.logger)==null||y.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(S=this.logger)==null||S.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=i.data.searchQuery,c="/records/search",l={method:"POST",headers:Object.assign({},w(s)),requestData:d!=null?d:{}},p=typeof this.logger=="function"?g():"";(E=this.logger)==null||E.call(this,{requestId:p,path:c,...l});let h=await this.fetcher(c,l);(_=this.logger)==null||_.call(this,{requestId:p,path:c,...l,responseData:h.data});let u=((M=h.data)!=null?M:[]).map(K=>new T(K));return new $(u,(V=h.total)!=null?V:0,d,i.data.warnings)}};if(this.fetcher=null,r!=null&&r.direct){if(!r.engineUrl)throw new Error("Direct mode requires `engineUrl`, the standalone engine base URL.");if(!r.httpClient)throw new Error("Direct mode requires an HTTP client; import the SDK from its Node or browser entry.");this.direct=new Re({engineUrl:r.engineUrl,token:e!=null?e:"",httpClient:r.httpClient,scope:r.scope}),this.fetcher=Tt(this.direct)}else if(r!=null&&r.httpClient){let s=Ot(r);this.fetcher=bt({httpClient:r.httpClient,token:e,url:s})}r!=null&&r.options&&(this.options=r==null?void 0:r.options),r!=null&&r.logger&&(this.logger=r==null?void 0:r.logger)}_extractTargetIds(e,r){var s;if(e instanceof T){let n=C(e);if(!n)throw new k(`${r} error: Target id is empty`);return[n]}if(I(e)&&e.every(n=>n instanceof T)){let n=e.map(C).filter(A);if(!n.length)throw new k(`${r} error: Target ids are empty`);return n}if(e instanceof $){let n=(s=e.data)==null?void 0:s.map(C).filter(A);if(!(n!=null&&n.length))throw new k(`${r} error: Target ids are empty`);return n}if(P(e)&&"__id"in e)return[e.__id];if(I(e)&&e.every(n=>P(n)&&"__id"in n)){let n=e.map(C).filter(A);if(!n.length)throw new k(`${r} error: Target ids are empty`);return n}return I(e)?e:v(e)?[e]:[]}async textIndexRequest(e,r,s){var i,d;let n={method:r,headers:{},...s===void 0?{}:{requestData:s}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:e,...n});let o=await this.fetcher(e,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:e,...n,responseData:o.data}),o}};var At,U=class U extends X{constructor(e,r){var a,o;let s=e!=null?e:typeof process<"u"?(a=process.env)==null?void 0:a.RUSHDB_API_KEY:void 0,n=Ce(r);super(s,{...n,httpClient:(o=n.httpClient)!=null?o:At}),U.instance=this,this.initializeSync(s,n)}initializeSync(e,r){U.state={initialized:!0,debug:!1,timeout:ke("timeout",r==null?void 0:r.timeout,8e4),token:e,direct:(r==null?void 0:r.direct)===!0,engineUrl:r==null?void 0:r.engineUrl}}static getInstance(){if(U.instance)return U.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return A(U.instance)}toDBRecordInstance(e){return new T(e)}};U.instance=null,U.state={initialized:!1,debug:!1,timeout:8e4};var x=U,Fe=t=>{At=t};var He=class{constructor(e,r,s){this.label=e,this.schema=r,this.config=s!=null?s:{}}getLabel(){return this.label}async toDBRecordInstance(e){try{return x.getInstance().toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,r){let s=e!=null?e:{};return x.getInstance().records.find({...s,labels:[this.label]},r)}async findOne(e,r){let s=e!=null?e:{};return x.getInstance().records.findOne({...s,labels:[this.label]},r)}async findById(e,r){return this.findOne({where:{$id:e}},r)}async findUniq(e,r){let s=e!=null?e:{};return x.getInstance().records.findUniq({...s,labels:[this.label]},r)}async create(e,r,s){var d,c;let n=await de(this.schema,e),a=fe(this.schema,n),o=A(a),i=x.getInstance();if(o){let l=r!=null?r:await i.tx.begin(),p=await this.find({where:a},l),h=typeof r<"u";if(!((d=p==null?void 0:p.data)!=null&&d.length)){let y=await i.records.create({label:this.label,data:n},l);return h||await l.commit(),y}else switch((c=s==null?void 0:s.onConflict)!=null?c:"throw"){case"upsert":{let S=p.data[0],E=await i.records.set({target:S.id,label:this.label,data:n},l);return h||await l.commit(),E}case"skip":return h||await l.commit(),null;default:throw h||await l.commit(),new L(this.label,a)}}return await i.records.create({label:this.label,data:n},r)}async attach({source:e,target:r,options:s},n){return await x.getInstance().records.attach({source:e,target:r,options:s},n)}async detach({source:e,target:r,options:s},n){return await x.getInstance().records.detach({source:e,target:r,options:s},n)}async validateTargetLabel(e,r){let s=C(e);if(!s)return;let a=await x.getInstance().records.findById(s,r);if(!a)throw new Error(`Record with id "${s}" not found.`);if(a.data.__label!==this.label)throw new TypeError(`Target record label "${a.data.__label}" does not match model label "${this.label}".`)}async handleSetOrUpdate(e,r,s,n){var d,c;if(this.config.validateTargetLabel&&await this.validateTargetLabel(e,n),I(r)&&r.every(z))return await x.getInstance().records[s]({label:this.label,target:e,data:r},n);let a=x.getInstance(),o=await de(this.schema,r),i=fe(this.schema,o);if(!ee(i)){let l=n!=null?n:await a.tx.begin(),p=await this.find({where:i},l),h=typeof n<"u";if(!((d=p==null?void 0:p.data)!=null&&d.length)||p.data.length===1&&((c=p.data[0])==null?void 0:c.id)===C(e)){let y=await a.records[s]({target:e,label:this.label,data:o},l);return h||await l.commit(),y}else throw h||await l.commit(),new L(this.label,i)}return await a.records[s]({label:this.label,target:e,data:o},n)}async set(e,r,s){return await this.handleSetOrUpdate(e,r,"set",s)}async update(e,r,s){return await this.handleSetOrUpdate(e,r,"update",s)}async createMany(e,r){var o;let s=x.getInstance(),n=typeof r<"u",a=r!=null?r:await s.tx.begin();try{let i=await Promise.all(e.map(async l=>await de(this.schema,l))),d=_e(i,this.schema,this.label);if(!ee(d)){let l=Object.entries(d).map(([h,u])=>({[h]:{$in:u}})),p=await this.find({where:{$or:l}},a);if((o=p==null?void 0:p.data)!=null&&o.length)throw new L(this.label,Object.keys(d))}let c=await s.records.createMany({label:this.label,data:i},a);return n||await a.commit(),c}catch(i){throw n||await a.rollback(),i}}async delete(e,r){if(ee(e.where))throw new k(`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 x.getInstance().records.delete({...e,labels:[this.label]},r)}async deleteById(e,r){return await x.getInstance().records.deleteById(e,r)}};Fe(new ye);var sr=x;0&&(module.exports={CLOUD_ONLY_FORMS,CLOUD_ONLY_METHODS,CloudOnlyError,DBRecordInstance,DBRecordsArrayInstance,DirectModeError,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,isCloudOnlyMethod,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
|