samyama-sdk 1.10.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,6 +36,8 @@ Or the factory, when the URL is all you need:
36
36
 
37
37
  ```ts
38
38
  const client = SamyamaClient.connectHttp("http://localhost:8080");
39
+ // or, with connection settings:
40
+ const quick = SamyamaClient.connectHttp("http://localhost:8080", { timeoutMs: 5000 });
39
41
  ```
40
42
 
41
43
  ## First query
@@ -88,7 +90,7 @@ npm install && npm run build && npm test
88
90
 
89
91
  ## More
90
92
 
91
- - [`docs/SDK_API_CLI_ARCHITECTURE.md`](https://github.com/samyama-ai/samyama-graph/blob/main/docs/SDK_API_CLI_ARCHITECTURE.md)
93
+ - [`docs/SDK-API-CLI-ARCHITECTURE.md`](https://github.com/samyama-ai/samyama-graph/blob/main/docs/SDK-API-CLI-ARCHITECTURE.md)
92
94
  — how the SDKs, the HTTP API and the CLI fit together.
93
95
  - [`sdk/README.md`](https://github.com/samyama-ai/samyama-graph/blob/main/sdk/README.md)
94
96
  — the other two SDKs (Python, Rust).
@@ -28,12 +28,37 @@ export declare class SamyamaClient {
28
28
  /**
29
29
  * Connect to a Samyama server via HTTP.
30
30
  * Factory method for a more readable API.
31
+ *
32
+ * `options` takes the same connection settings as the constructor
33
+ * (`timeoutMs`, `maxRetries`, `retryBaseDelayMs`). Leaving them out keeps
34
+ * the defaults, which include a 30 s request deadline (#1326).
31
35
  */
32
- static connectHttp(url?: string): SamyamaClient;
36
+ static connectHttp(url?: string, options?: Omit<ClientOptions, "url">): SamyamaClient;
33
37
  /** Execute a read-write Cypher query */
34
38
  query(cypher: string, graph?: string): Promise<QueryResult>;
35
- /** Execute a read-only Cypher query */
39
+ /**
40
+ * Execute a read-only Cypher query. The server refuses it, before it runs,
41
+ * if it writes (#1628).
42
+ */
36
43
  queryReadonly(cypher: string, graph?: string): Promise<QueryResult>;
44
+ /**
45
+ * Stream a read query's rows as they are produced, each an object keyed by
46
+ * column (#1632). Stop early with `break`; the server stops with you.
47
+ *
48
+ * ```ts
49
+ * for await (const row of client.queryStream("MATCH (n) RETURN n.name AS name")) {
50
+ * console.log(row.name);
51
+ * }
52
+ * ```
53
+ */
54
+ queryStream(cypher: string, graph?: string, opts?: {
55
+ signal?: AbortSignal;
56
+ }): AsyncGenerator<Record<string, unknown>, void, undefined>;
57
+ /**
58
+ * Translate a natural-language question into read-only Cypher on the server.
59
+ * Returns the query without running it; pass it to `queryReadonly`.
60
+ */
61
+ nlq(question: string): Promise<string>;
37
62
  /**
38
63
  * Return the EXPLAIN plan for a Cypher query without executing it.
39
64
  * Returns the plan as text rows in the QueryResult records.
@@ -35,17 +35,44 @@ export class SamyamaClient {
35
35
  /**
36
36
  * Connect to a Samyama server via HTTP.
37
37
  * Factory method for a more readable API.
38
+ *
39
+ * `options` takes the same connection settings as the constructor
40
+ * (`timeoutMs`, `maxRetries`, `retryBaseDelayMs`). Leaving them out keeps
41
+ * the defaults, which include a 30 s request deadline (#1326).
38
42
  */
39
- static connectHttp(url = DEFAULT_URL) {
40
- return new SamyamaClient({ url });
43
+ static connectHttp(url = DEFAULT_URL, options) {
44
+ return new SamyamaClient({ ...options, url });
41
45
  }
42
46
  /** Execute a read-write Cypher query */
43
47
  async query(cypher, graph = "default") {
44
48
  return this.http.query(cypher, graph);
45
49
  }
46
- /** Execute a read-only Cypher query */
50
+ /**
51
+ * Execute a read-only Cypher query. The server refuses it, before it runs,
52
+ * if it writes (#1628).
53
+ */
47
54
  async queryReadonly(cypher, graph = "default") {
48
- return this.http.query(cypher, graph);
55
+ return this.http.query(cypher, graph, { readOnly: true });
56
+ }
57
+ /**
58
+ * Stream a read query's rows as they are produced, each an object keyed by
59
+ * column (#1632). Stop early with `break`; the server stops with you.
60
+ *
61
+ * ```ts
62
+ * for await (const row of client.queryStream("MATCH (n) RETURN n.name AS name")) {
63
+ * console.log(row.name);
64
+ * }
65
+ * ```
66
+ */
67
+ queryStream(cypher, graph = "default", opts) {
68
+ return this.http.queryStream(cypher, graph, opts);
69
+ }
70
+ /**
71
+ * Translate a natural-language question into read-only Cypher on the server.
72
+ * Returns the query without running it; pass it to `queryReadonly`.
73
+ */
74
+ async nlq(question) {
75
+ return this.http.nlq(question);
49
76
  }
50
77
  /**
51
78
  * Return the EXPLAIN plan for a Cypher query without executing it.
@@ -58,7 +58,36 @@ export declare class HttpTransport {
58
58
  private static fail;
59
59
  private json;
60
60
  /** Execute a Cypher query via POST /api/query */
61
- query(cypher: string, graph?: string, opts?: RequestOptions): Promise<QueryResult>;
61
+ query(cypher: string, graph?: string, opts?: RequestOptions & {
62
+ readOnly?: boolean;
63
+ }): Promise<QueryResult>;
64
+ /**
65
+ * Stream a read query's rows as the server produces them (API-07, #1632).
66
+ *
67
+ * Sends `Accept: application/x-ndjson` and reads the body incrementally, so
68
+ * a large result is never held whole on either end. Each row is an object
69
+ * keyed by column. Stopping early (`break` out of `for await`) cancels the
70
+ * body, which closes the connection and stops the server producing rows.
71
+ *
72
+ * The stream ends with the server's trailer: `{"done": true}` ends it,
73
+ * `{"error": ...}` throws, and a body that ends with no trailer throws too,
74
+ * since that is a result cut off rather than a complete one (#1554). The
75
+ * request is sent `read_only`, so a write is refused before it runs.
76
+ *
77
+ * The transport's timeout bounds the wait for the response, not the stream:
78
+ * a long result that keeps arriving is not cut off.
79
+ */
80
+ queryStream(cypher: string, graph?: string, opts?: {
81
+ signal?: AbortSignal;
82
+ }): AsyncGenerator<Record<string, unknown>, void, undefined>;
83
+ /**
84
+ * Translate a natural-language question into Cypher via POST /api/nlq.
85
+ *
86
+ * Returns the generated query without running it; pass it to `query` for
87
+ * results. The server chooses the LLM provider (`NLQ_PROVIDER`) and refuses
88
+ * any generated query that writes, which rejects with the server's message.
89
+ */
90
+ nlq(question: string, opts?: RequestOptions): Promise<string>;
62
91
  /** Get server status via GET /api/status */
63
92
  status(opts?: RequestOptions): Promise<ServerStatus>;
64
93
  /**
@@ -11,7 +11,12 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
11
11
  export class HttpTransport {
12
12
  constructor(baseUrl, options = {}) {
13
13
  this.baseUrl = baseUrl.replace(/\/+$/, "");
14
- this.options = { ...DEFAULTS, ...options };
14
+ // An option passed as `undefined` means "not set", but a spread copies it
15
+ // over the default all the same. `SamyamaClient` forwards every option it
16
+ // was not given as `undefined`, so every client built without a
17
+ // `timeoutMs` had no deadline at all and every call threw (#1595).
18
+ const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== undefined));
19
+ this.options = { ...DEFAULTS, ...given };
15
20
  }
16
21
  /** The settings this transport was built with. */
17
22
  get connectionOptions() {
@@ -79,12 +84,129 @@ export class HttpTransport {
79
84
  }
80
85
  /** Execute a Cypher query via POST /api/query */
81
86
  async query(cypher, graph = "default", opts) {
87
+ // `read_only` makes the server refuse a write before it runs (#1628);
88
+ // only sent when asked, so a plain query's body is what it always was.
89
+ const body = { query: cypher, graph };
90
+ if (opts?.readOnly)
91
+ body.read_only = true;
82
92
  return this.json("/api/query", {
83
93
  method: "POST",
84
94
  headers: { "Content-Type": "application/json" },
85
- body: JSON.stringify({ query: cypher, graph }),
95
+ body: JSON.stringify(body),
86
96
  }, opts);
87
97
  }
98
+ /**
99
+ * Stream a read query's rows as the server produces them (API-07, #1632).
100
+ *
101
+ * Sends `Accept: application/x-ndjson` and reads the body incrementally, so
102
+ * a large result is never held whole on either end. Each row is an object
103
+ * keyed by column. Stopping early (`break` out of `for await`) cancels the
104
+ * body, which closes the connection and stops the server producing rows.
105
+ *
106
+ * The stream ends with the server's trailer: `{"done": true}` ends it,
107
+ * `{"error": ...}` throws, and a body that ends with no trailer throws too,
108
+ * since that is a result cut off rather than a complete one (#1554). The
109
+ * request is sent `read_only`, so a write is refused before it runs.
110
+ *
111
+ * The transport's timeout bounds the wait for the response, not the stream:
112
+ * a long result that keeps arriving is not cut off.
113
+ */
114
+ async *queryStream(cypher, graph = "default", opts = {}) {
115
+ const controller = new AbortController();
116
+ const onAbort = () => controller.abort(opts.signal?.reason);
117
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
118
+ const deadline = setTimeout(() => controller.abort(new DOMException("timed out", "TimeoutError")), this.options.timeoutMs);
119
+ let response;
120
+ try {
121
+ response = await fetch(`${this.baseUrl}/api/query`, {
122
+ method: "POST",
123
+ headers: {
124
+ "Content-Type": "application/json",
125
+ Accept: "application/x-ndjson",
126
+ },
127
+ body: JSON.stringify({ query: cypher, graph, read_only: true }),
128
+ signal: controller.signal,
129
+ });
130
+ }
131
+ finally {
132
+ clearTimeout(deadline);
133
+ }
134
+ if (!response.ok)
135
+ return HttpTransport.fail(response);
136
+ if (!response.body)
137
+ throw new Error("the stream response has no body");
138
+ const reader = response.body.getReader();
139
+ const decoder = new TextDecoder();
140
+ let buffered = "";
141
+ let columns;
142
+ let finished = false;
143
+ try {
144
+ for (;;) {
145
+ let nl;
146
+ while ((nl = buffered.indexOf("\n")) >= 0) {
147
+ const text = buffered.slice(0, nl).trim();
148
+ buffered = buffered.slice(nl + 1);
149
+ if (!text)
150
+ continue;
151
+ const line = JSON.parse(text);
152
+ if (columns === undefined) {
153
+ if (!Array.isArray(line.columns)) {
154
+ throw new Error(`the stream's first line is not a header: ${text}`);
155
+ }
156
+ columns = line.columns;
157
+ }
158
+ else if (Array.isArray(line.row)) {
159
+ const row = {};
160
+ line.row.forEach((v, i) => (row[columns[i]] = v));
161
+ yield row;
162
+ }
163
+ else if (line.done === true) {
164
+ finished = true;
165
+ return;
166
+ }
167
+ else if ("error" in line) {
168
+ finished = true;
169
+ throw new Error(String(line.error));
170
+ }
171
+ else {
172
+ throw new Error(`unexpected line in the stream: ${text}`);
173
+ }
174
+ }
175
+ const { value, done } = await reader.read();
176
+ if (done)
177
+ break;
178
+ buffered += decoder.decode(value, { stream: true });
179
+ }
180
+ throw new Error("the stream ended without a trailer; the result is incomplete");
181
+ }
182
+ finally {
183
+ opts.signal?.removeEventListener("abort", onAbort);
184
+ if (!finished) {
185
+ // An early stop, or an error: release the connection so the server
186
+ // stops producing rows nobody will read.
187
+ await reader.cancel().catch(() => undefined);
188
+ }
189
+ }
190
+ }
191
+ /**
192
+ * Translate a natural-language question into Cypher via POST /api/nlq.
193
+ *
194
+ * Returns the generated query without running it; pass it to `query` for
195
+ * results. The server chooses the LLM provider (`NLQ_PROVIDER`) and refuses
196
+ * any generated query that writes, which rejects with the server's message.
197
+ */
198
+ async nlq(question, opts) {
199
+ const body = { question };
200
+ const response = await this.json("/api/nlq", {
201
+ method: "POST",
202
+ headers: { "Content-Type": "application/json" },
203
+ body: JSON.stringify(body),
204
+ }, opts);
205
+ if (typeof response.cypher !== "string") {
206
+ throw new Error("/api/nlq response has no `cypher` string");
207
+ }
208
+ return response.cypher;
209
+ }
88
210
  /** Get server status via GET /api/status */
89
211
  async status(opts) {
90
212
  return this.json("/api/status", {}, opts);
@@ -119,13 +241,15 @@ export class HttpTransport {
119
241
  /** Import nodes from CSV via POST /api/import/csv (multipart) */
120
242
  async importCsv(csvContent, label, options, opts) {
121
243
  const formData = new FormData();
122
- const blob = new Blob([csvContent], { type: "text/csv" });
123
- formData.append("file", blob, "import.csv");
244
+ // The fields before the file: the server then parses the file as it
245
+ // arrives instead of copying it to disk first (#336).
124
246
  formData.append("label", label);
125
247
  if (options?.idColumn)
126
248
  formData.append("id_column", options.idColumn);
127
249
  if (options?.delimiter)
128
250
  formData.append("delimiter", options.delimiter);
251
+ const blob = new Blob([csvContent], { type: "text/csv" });
252
+ formData.append("file", blob, "import.csv");
129
253
  return this.json("/api/import/csv", { method: "POST", body: formData }, opts);
130
254
  }
131
255
  /** Import nodes from JSON via POST /api/import/json */
@@ -1,4 +1,4 @@
1
1
  export { SamyamaClient } from "./client.js";
2
2
  export { HttpTransport } from "./http-client.js";
3
3
  export type { ConnectionOptions, RequestOptions } from "./http-client.js";
4
- export type { SdkNode, SdkEdge, QueryResult, ServerStatus, ErrorResponse, ClientOptions, GraphSchema, NodeType, EdgeType, IndexInfo, ConstraintInfo, CsvImportResult, JsonImportResult, } from "./types.js";
4
+ export type { SdkNode, SdkEdge, QueryResult, ServerStatus, ErrorResponse, NlqRequest, NlqResponse, ClientOptions, GraphSchema, NodeType, EdgeType, IndexInfo, ConstraintInfo, CsvImportResult, JsonImportResult, } from "./types.js";
@@ -28,6 +28,14 @@ export interface ServerStatus {
28
28
  edges: number;
29
29
  };
30
30
  }
31
+ /** Request body of POST /api/nlq */
32
+ export interface NlqRequest {
33
+ question: string;
34
+ }
35
+ /** Successful response of POST /api/nlq: the generated, read-only Cypher */
36
+ export interface NlqResponse {
37
+ cypher: string;
38
+ }
31
39
  /** Error response from the server */
32
40
  export interface ErrorResponse {
33
41
  error: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "samyama-sdk",
3
- "version": "1.10.0",
3
+ "version": "1.12.0",
4
4
  "description": "TypeScript SDK for the Samyama Graph Database",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",