samyama-sdk 0.6.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import type { QueryResult, ServerStatus, ClientOptions, GraphSchema, CsvImportResult, JsonImportResult } from "./types";
1
+ import type { QueryResult, ServerStatus, ClientOptions, GraphSchema, SampleRequest, SampleResult, CsvImportResult, JsonImportResult } from "./types.js";
2
2
  /**
3
3
  * Client for the Samyama Graph Database.
4
4
  *
@@ -31,27 +31,33 @@ export declare class SamyamaClient {
31
31
  */
32
32
  static connectHttp(url?: string): SamyamaClient;
33
33
  /** Execute a read-write Cypher query */
34
- query(cypher: string, _graph?: string): Promise<QueryResult>;
34
+ query(cypher: string, graph?: string): Promise<QueryResult>;
35
35
  /** Execute a read-only Cypher query */
36
- queryReadonly(cypher: string, _graph?: string): Promise<QueryResult>;
36
+ queryReadonly(cypher: string, graph?: string): Promise<QueryResult>;
37
37
  /**
38
38
  * Return the EXPLAIN plan for a Cypher query without executing it.
39
39
  * Returns the plan as text rows in the QueryResult records.
40
40
  */
41
- explain(cypher: string): Promise<QueryResult>;
41
+ explain(cypher: string, graph?: string): Promise<QueryResult>;
42
42
  /**
43
43
  * Execute a Cypher query with PROFILE instrumentation.
44
44
  * Returns plan text with actual row counts and timing per operator.
45
45
  */
46
- profile(cypher: string): Promise<QueryResult>;
46
+ profile(cypher: string, graph?: string): Promise<QueryResult>;
47
47
  /** Delete a graph (executes MATCH (n) DELETE n) */
48
- deleteGraph(_graph?: string): Promise<void>;
48
+ deleteGraph(graph?: string): Promise<void>;
49
49
  /** List graphs (OSS: always returns ["default"]) */
50
50
  listGraphs(): Promise<string[]>;
51
51
  /** Get server status */
52
52
  status(): Promise<ServerStatus>;
53
53
  /** Get graph schema (node types, edge types, indexes, constraints, statistics) */
54
54
  schema(): Promise<GraphSchema>;
55
+ /**
56
+ * Sample a subgraph for visualization.
57
+ * Returns a proportionally sampled set of nodes and edges.
58
+ * @param options - max_nodes (default 200), labels filter, graph/tenant name
59
+ */
60
+ sample(options?: SampleRequest): Promise<SampleResult>;
55
61
  /**
56
62
  * Import nodes from CSV content.
57
63
  * @param csvContent - Raw CSV string (first row = headers)
@@ -68,6 +74,14 @@ export declare class SamyamaClient {
68
74
  * @param nodes - Array of objects, each becoming a node
69
75
  */
70
76
  importJson(label: string, nodes: Record<string, unknown>[]): Promise<JsonImportResult>;
77
+ /**
78
+ * Does the server answer, and does it call itself healthy?
79
+ *
80
+ * Returns false rather than throwing: "is it up" is a question whose negative
81
+ * answer is not exceptional, and `ping()` below throws, which makes it
82
+ * awkward inside a readiness loop.
83
+ */
84
+ healthy(): Promise<boolean>;
71
85
  /** Ping the server */
72
86
  ping(): Promise<string>;
73
87
  }
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SamyamaClient = void 0;
4
- const http_client_1 = require("./http-client");
1
+ import { HttpTransport } from "./http-client.js";
5
2
  const DEFAULT_URL = "http://localhost:8080";
6
3
  /**
7
4
  * Client for the Samyama Graph Database.
@@ -26,10 +23,14 @@ const DEFAULT_URL = "http://localhost:8080";
26
23
  * const profile = await client.profile("MATCH (n:Person) RETURN n");
27
24
  * ```
28
25
  */
29
- class SamyamaClient {
26
+ export class SamyamaClient {
30
27
  constructor(options) {
31
28
  const url = options?.url ?? DEFAULT_URL;
32
- this.http = new http_client_1.HttpTransport(url);
29
+ this.http = new HttpTransport(url, {
30
+ timeoutMs: options?.timeoutMs,
31
+ maxRetries: options?.maxRetries,
32
+ retryBaseDelayMs: options?.retryBaseDelayMs,
33
+ });
33
34
  }
34
35
  /**
35
36
  * Connect to a Samyama server via HTTP.
@@ -39,36 +40,36 @@ class SamyamaClient {
39
40
  return new SamyamaClient({ url });
40
41
  }
41
42
  /** Execute a read-write Cypher query */
42
- async query(cypher, _graph = "default") {
43
- return this.http.query(cypher);
43
+ async query(cypher, graph = "default") {
44
+ return this.http.query(cypher, graph);
44
45
  }
45
46
  /** Execute a read-only Cypher query */
46
- async queryReadonly(cypher, _graph = "default") {
47
- return this.http.query(cypher);
47
+ async queryReadonly(cypher, graph = "default") {
48
+ return this.http.query(cypher, graph);
48
49
  }
49
50
  /**
50
51
  * Return the EXPLAIN plan for a Cypher query without executing it.
51
52
  * Returns the plan as text rows in the QueryResult records.
52
53
  */
53
- async explain(cypher) {
54
+ async explain(cypher, graph = "default") {
54
55
  const prefixed = cypher.trimStart().toUpperCase().startsWith("EXPLAIN")
55
56
  ? cypher
56
57
  : `EXPLAIN ${cypher}`;
57
- return this.http.query(prefixed);
58
+ return this.http.query(prefixed, graph);
58
59
  }
59
60
  /**
60
61
  * Execute a Cypher query with PROFILE instrumentation.
61
62
  * Returns plan text with actual row counts and timing per operator.
62
63
  */
63
- async profile(cypher) {
64
+ async profile(cypher, graph = "default") {
64
65
  const prefixed = cypher.trimStart().toUpperCase().startsWith("PROFILE")
65
66
  ? cypher
66
67
  : `PROFILE ${cypher}`;
67
- return this.http.query(prefixed);
68
+ return this.http.query(prefixed, graph);
68
69
  }
69
70
  /** Delete a graph (executes MATCH (n) DELETE n) */
70
- async deleteGraph(_graph = "default") {
71
- await this.http.query("MATCH (n) DELETE n");
71
+ async deleteGraph(graph = "default") {
72
+ await this.http.query("MATCH (n) DELETE n", graph);
72
73
  }
73
74
  /** List graphs (OSS: always returns ["default"]) */
74
75
  async listGraphs() {
@@ -82,6 +83,14 @@ class SamyamaClient {
82
83
  async schema() {
83
84
  return this.http.schema();
84
85
  }
86
+ /**
87
+ * Sample a subgraph for visualization.
88
+ * Returns a proportionally sampled set of nodes and edges.
89
+ * @param options - max_nodes (default 200), labels filter, graph/tenant name
90
+ */
91
+ async sample(options = {}) {
92
+ return this.http.post("/api/sample", options);
93
+ }
85
94
  /**
86
95
  * Import nodes from CSV content.
87
96
  * @param csvContent - Raw CSV string (first row = headers)
@@ -99,6 +108,16 @@ class SamyamaClient {
99
108
  async importJson(label, nodes) {
100
109
  return this.http.importJson(label, nodes);
101
110
  }
111
+ /**
112
+ * Does the server answer, and does it call itself healthy?
113
+ *
114
+ * Returns false rather than throwing: "is it up" is a question whose negative
115
+ * answer is not exceptional, and `ping()` below throws, which makes it
116
+ * awkward inside a readiness loop.
117
+ */
118
+ async healthy() {
119
+ return this.http.healthy();
120
+ }
102
121
  /** Ping the server */
103
122
  async ping() {
104
123
  const s = await this.status();
@@ -108,4 +127,3 @@ class SamyamaClient {
108
127
  throw new Error(`Server unhealthy: ${s.status}`);
109
128
  }
110
129
  }
111
- exports.SamyamaClient = SamyamaClient;
@@ -1,22 +1,82 @@
1
- import type { QueryResult, ServerStatus, GraphSchema, CsvImportResult, JsonImportResult } from "./types";
1
+ import type { QueryResult, ServerStatus, GraphSchema, CsvImportResult, JsonImportResult } from "./types.js";
2
+ /**
3
+ * How the transport treats the network (API-06).
4
+ *
5
+ * Every field has a default, and the defaults are the point. Every call used to
6
+ * be a bare `fetch` with no `signal`, and `fetch` has **no timeout**: a server
7
+ * that accepts the connection and then stops talking leaves the promise pending
8
+ * for as long as the process lives (samyama-graph#1326).
9
+ */
10
+ export interface ConnectionOptions {
11
+ /** Deadline for a whole request, in milliseconds. */
12
+ timeoutMs?: number;
13
+ /** How many times a retryable failure is retried. 0 disables retry. */
14
+ maxRetries?: number;
15
+ /**
16
+ * Delay before the first retry, doubled each attempt.
17
+ *
18
+ * Constant-delay retry is deliberately not what this does: it is what turns
19
+ * one slow server into a thundering herd of clients waking together.
20
+ */
21
+ retryBaseDelayMs?: number;
22
+ }
23
+ /** Per-call overrides. `signal` lets a caller cancel. */
24
+ export interface RequestOptions {
25
+ /** Caller's cancellation signal, combined with the timeout. */
26
+ signal?: AbortSignal;
27
+ /** Override the transport's timeout for this call. */
28
+ timeoutMs?: number;
29
+ }
2
30
  /**
3
31
  * HTTP transport for the Samyama SDK.
4
32
  * Uses the native `fetch` API (works in Node.js 18+ and browsers).
5
33
  */
6
34
  export declare class HttpTransport {
7
35
  private baseUrl;
8
- constructor(baseUrl: string);
36
+ private options;
37
+ constructor(baseUrl: string, options?: ConnectionOptions);
38
+ /** The settings this transport was built with. */
39
+ get connectionOptions(): Required<ConnectionOptions>;
40
+ /**
41
+ * Is this failure worth retrying?
42
+ *
43
+ * A timeout or a connection failure, and nothing else. An HTTP error is the
44
+ * server answering; repeating a request it has already refused achieves
45
+ * nothing, and blindly repeating a write is how one duplicate becomes
46
+ * several. A caller's own `AbortSignal` firing is never retried — the caller
47
+ * asked to stop.
48
+ */
49
+ private static retryable;
50
+ /**
51
+ * Every request goes through here.
52
+ *
53
+ * One place, not fifteen: the missing timeout was missing at six separate
54
+ * `fetch` call sites, so fixing one of them fixed one of them.
55
+ */
56
+ private request;
57
+ /** Throw the server's error message, or the status if it sent none. */
58
+ private static fail;
59
+ private json;
9
60
  /** Execute a Cypher query via POST /api/query */
10
- query(cypher: string): Promise<QueryResult>;
61
+ query(cypher: string, graph?: string, opts?: RequestOptions): Promise<QueryResult>;
11
62
  /** Get server status via GET /api/status */
12
- status(): Promise<ServerStatus>;
63
+ status(opts?: RequestOptions): Promise<ServerStatus>;
64
+ /**
65
+ * Health check: does the server answer, and does it call itself healthy?
66
+ *
67
+ * Returns false rather than throwing, because "is it up" is a question whose
68
+ * negative answer is not exceptional.
69
+ */
70
+ healthy(opts?: RequestOptions): Promise<boolean>;
13
71
  /** Get graph schema via GET /api/schema */
14
- schema(): Promise<GraphSchema>;
72
+ schema(opts?: RequestOptions): Promise<GraphSchema>;
73
+ /** Generic POST request returning typed JSON response */
74
+ post<T>(path: string, body: unknown, opts?: RequestOptions): Promise<T>;
15
75
  /** Import nodes from CSV via POST /api/import/csv (multipart) */
16
76
  importCsv(csvContent: string, label: string, options?: {
17
77
  idColumn?: string;
18
78
  delimiter?: string;
19
- }): Promise<CsvImportResult>;
79
+ }, opts?: RequestOptions): Promise<CsvImportResult>;
20
80
  /** Import nodes from JSON via POST /api/import/json */
21
- importJson(label: string, nodes: Record<string, unknown>[]): Promise<JsonImportResult>;
81
+ importJson(label: string, nodes: Record<string, unknown>[], opts?: RequestOptions): Promise<JsonImportResult>;
22
82
  }
@@ -1,50 +1,123 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpTransport = void 0;
1
+ const DEFAULTS = {
2
+ timeoutMs: 30000,
3
+ maxRetries: 2,
4
+ retryBaseDelayMs: 100,
5
+ };
6
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4
7
  /**
5
8
  * HTTP transport for the Samyama SDK.
6
9
  * Uses the native `fetch` API (works in Node.js 18+ and browsers).
7
10
  */
8
- class HttpTransport {
9
- constructor(baseUrl) {
11
+ export class HttpTransport {
12
+ constructor(baseUrl, options = {}) {
10
13
  this.baseUrl = baseUrl.replace(/\/+$/, "");
14
+ this.options = { ...DEFAULTS, ...options };
15
+ }
16
+ /** The settings this transport was built with. */
17
+ get connectionOptions() {
18
+ return { ...this.options };
19
+ }
20
+ /**
21
+ * Is this failure worth retrying?
22
+ *
23
+ * A timeout or a connection failure, and nothing else. An HTTP error is the
24
+ * server answering; repeating a request it has already refused achieves
25
+ * nothing, and blindly repeating a write is how one duplicate becomes
26
+ * several. A caller's own `AbortSignal` firing is never retried — the caller
27
+ * asked to stop.
28
+ */
29
+ static retryable(err, callerSignal) {
30
+ if (callerSignal?.aborted)
31
+ return false;
32
+ if (err instanceof DOMException && err.name === "TimeoutError")
33
+ return true;
34
+ if (err instanceof DOMException && err.name === "AbortError")
35
+ return true;
36
+ return err instanceof TypeError; // fetch's network-failure shape
37
+ }
38
+ /**
39
+ * Every request goes through here.
40
+ *
41
+ * One place, not fifteen: the missing timeout was missing at six separate
42
+ * `fetch` call sites, so fixing one of them fixed one of them.
43
+ */
44
+ async request(path, init, opts = {}) {
45
+ const timeoutMs = opts.timeoutMs ?? this.options.timeoutMs;
46
+ let delay = this.options.retryBaseDelayMs;
47
+ for (let attempt = 0;; attempt++) {
48
+ // A fresh timeout per attempt, and the caller's signal combined with it,
49
+ // so cancellation wins over a retry that is still waiting.
50
+ const signals = [AbortSignal.timeout(timeoutMs)];
51
+ if (opts.signal)
52
+ signals.push(opts.signal);
53
+ const signal = signals.length === 1 ? signals[0] : AbortSignal.any(signals);
54
+ try {
55
+ return await fetch(`${this.baseUrl}${path}`, { ...init, signal });
56
+ }
57
+ catch (err) {
58
+ if (attempt >= this.options.maxRetries ||
59
+ !HttpTransport.retryable(err, opts.signal)) {
60
+ throw err;
61
+ }
62
+ await sleep(delay);
63
+ delay *= 2;
64
+ }
65
+ }
66
+ }
67
+ /** Throw the server's error message, or the status if it sent none. */
68
+ static async fail(response) {
69
+ const body = (await response.json().catch(() => ({
70
+ error: `HTTP ${response.status}`,
71
+ })));
72
+ throw new Error(body.error || `HTTP ${response.status}`);
73
+ }
74
+ async json(path, init, opts) {
75
+ const response = await this.request(path, init, opts);
76
+ if (!response.ok)
77
+ return HttpTransport.fail(response);
78
+ return (await response.json());
11
79
  }
12
80
  /** Execute a Cypher query via POST /api/query */
13
- async query(cypher) {
14
- const response = await fetch(`${this.baseUrl}/api/query`, {
81
+ async query(cypher, graph = "default", opts) {
82
+ return this.json("/api/query", {
15
83
  method: "POST",
16
84
  headers: { "Content-Type": "application/json" },
17
- body: JSON.stringify({ query: cypher }),
18
- });
19
- if (!response.ok) {
20
- const body = (await response.json().catch(() => ({
21
- error: `HTTP ${response.status}`,
22
- })));
23
- throw new Error(body.error || `HTTP ${response.status}`);
24
- }
25
- return (await response.json());
85
+ body: JSON.stringify({ query: cypher, graph }),
86
+ }, opts);
26
87
  }
27
88
  /** Get server status via GET /api/status */
28
- async status() {
29
- const response = await fetch(`${this.baseUrl}/api/status`);
30
- if (!response.ok) {
31
- throw new Error(`Status endpoint returned ${response.status}`);
89
+ async status(opts) {
90
+ return this.json("/api/status", {}, opts);
91
+ }
92
+ /**
93
+ * Health check: does the server answer, and does it call itself healthy?
94
+ *
95
+ * Returns false rather than throwing, because "is it up" is a question whose
96
+ * negative answer is not exceptional.
97
+ */
98
+ async healthy(opts) {
99
+ try {
100
+ const s = await this.status(opts);
101
+ return s.status === "healthy";
102
+ }
103
+ catch {
104
+ return false;
32
105
  }
33
- return (await response.json());
34
106
  }
35
107
  /** Get graph schema via GET /api/schema */
36
- async schema() {
37
- const response = await fetch(`${this.baseUrl}/api/schema`);
38
- if (!response.ok) {
39
- const body = (await response.json().catch(() => ({
40
- error: `HTTP ${response.status}`,
41
- })));
42
- throw new Error(body.error || `HTTP ${response.status}`);
43
- }
44
- return (await response.json());
108
+ async schema(opts) {
109
+ return this.json("/api/schema", {}, opts);
110
+ }
111
+ /** Generic POST request returning typed JSON response */
112
+ async post(path, body, opts) {
113
+ return this.json(path, {
114
+ method: "POST",
115
+ headers: { "Content-Type": "application/json" },
116
+ body: JSON.stringify(body),
117
+ }, opts);
45
118
  }
46
119
  /** Import nodes from CSV via POST /api/import/csv (multipart) */
47
- async importCsv(csvContent, label, options) {
120
+ async importCsv(csvContent, label, options, opts) {
48
121
  const formData = new FormData();
49
122
  const blob = new Blob([csvContent], { type: "text/csv" });
50
123
  formData.append("file", blob, "import.csv");
@@ -53,32 +126,14 @@ class HttpTransport {
53
126
  formData.append("id_column", options.idColumn);
54
127
  if (options?.delimiter)
55
128
  formData.append("delimiter", options.delimiter);
56
- const response = await fetch(`${this.baseUrl}/api/import/csv`, {
57
- method: "POST",
58
- body: formData,
59
- });
60
- if (!response.ok) {
61
- const body = (await response.json().catch(() => ({
62
- error: `HTTP ${response.status}`,
63
- })));
64
- throw new Error(body.error || `HTTP ${response.status}`);
65
- }
66
- return (await response.json());
129
+ return this.json("/api/import/csv", { method: "POST", body: formData }, opts);
67
130
  }
68
131
  /** Import nodes from JSON via POST /api/import/json */
69
- async importJson(label, nodes) {
70
- const response = await fetch(`${this.baseUrl}/api/import/json`, {
132
+ async importJson(label, nodes, opts) {
133
+ return this.json("/api/import/json", {
71
134
  method: "POST",
72
135
  headers: { "Content-Type": "application/json" },
73
136
  body: JSON.stringify({ label, nodes }),
74
- });
75
- if (!response.ok) {
76
- const body = (await response.json().catch(() => ({
77
- error: `HTTP ${response.status}`,
78
- })));
79
- throw new Error(body.error || `HTTP ${response.status}`);
80
- }
81
- return (await response.json());
137
+ }, opts);
82
138
  }
83
139
  }
84
- exports.HttpTransport = HttpTransport;
@@ -1,3 +1,4 @@
1
- export { SamyamaClient } from "./client";
2
- export { HttpTransport } from "./http-client";
3
- export type { SdkNode, SdkEdge, QueryResult, ServerStatus, ErrorResponse, ClientOptions, GraphSchema, NodeType, EdgeType, IndexInfo, ConstraintInfo, CsvImportResult, JsonImportResult, } from "./types";
1
+ export { SamyamaClient } from "./client.js";
2
+ export { HttpTransport } from "./http-client.js";
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";
package/dist/src/index.js CHANGED
@@ -1,7 +1,2 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpTransport = exports.SamyamaClient = void 0;
4
- var client_1 = require("./client");
5
- Object.defineProperty(exports, "SamyamaClient", { enumerable: true, get: function () { return client_1.SamyamaClient; } });
6
- var http_client_1 = require("./http-client");
7
- Object.defineProperty(exports, "HttpTransport", { enumerable: true, get: function () { return http_client_1.HttpTransport; } });
1
+ export { SamyamaClient } from "./client.js";
2
+ export { HttpTransport } from "./http-client.js";
@@ -70,6 +70,39 @@ export interface GraphSchema {
70
70
  avg_out_degree: number;
71
71
  };
72
72
  }
73
+ /** Request for subgraph sampling (POST /api/sample) */
74
+ export interface SampleRequest {
75
+ /** Maximum nodes to return (default: 200, max: 1000) */
76
+ max_nodes?: number;
77
+ /** Only include these node labels (empty = all) */
78
+ labels?: string[];
79
+ /** Tenant/graph name */
80
+ graph?: string;
81
+ }
82
+ /** A sampled node for visualization */
83
+ export interface SampleNode {
84
+ id: number;
85
+ label: string;
86
+ name: string;
87
+ properties: Record<string, unknown>;
88
+ }
89
+ /** A sampled edge for visualization */
90
+ export interface SampleEdge {
91
+ id: number;
92
+ source: number;
93
+ target: number;
94
+ type: string;
95
+ properties: Record<string, unknown>;
96
+ }
97
+ /** Result of subgraph sampling */
98
+ export interface SampleResult {
99
+ nodes: SampleNode[];
100
+ edges: SampleEdge[];
101
+ total_nodes: number;
102
+ total_edges: number;
103
+ sampled_nodes: number;
104
+ sampled_edges: number;
105
+ }
73
106
  /** Result of CSV import */
74
107
  export interface CsvImportResult {
75
108
  status: string;
@@ -87,4 +120,10 @@ export interface JsonImportResult {
87
120
  export interface ClientOptions {
88
121
  /** Base URL for HTTP transport (default: http://localhost:8080) */
89
122
  url?: string;
123
+ /** Request deadline in milliseconds (default: 30000). */
124
+ timeoutMs?: number;
125
+ /** Retries for a timeout or connection failure (default: 2). */
126
+ maxRetries?: number;
127
+ /** Delay before the first retry, doubled each attempt (default: 100). */
128
+ retryBaseDelayMs?: number;
90
129
  }
package/dist/src/types.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
package/package.json CHANGED
@@ -1,8 +1,10 @@
1
1
  {
2
2
  "name": "samyama-sdk",
3
- "version": "0.6.1",
3
+ "version": "1.9.0",
4
4
  "description": "TypeScript SDK for the Samyama Graph Database",
5
+ "type": "module",
5
6
  "main": "dist/src/index.js",
7
+ "module": "dist/src/index.js",
6
8
  "types": "dist/src/index.d.ts",
7
9
  "files": [
8
10
  "dist/src/**/*.js",