@sovaria/sdk 0.0.0-stage → 0.4.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sovaria
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,180 @@
1
- # Temporary Holding Version
1
+ # Sovaria TypeScript SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript SDK for Sovaria gateway APIs.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @sovaria/sdk
9
+ ```
10
+
11
+ Works in browsers, React Native and Node 18+ (realtime in Node needs Node 22+ or a global `WebSocket`).
12
+ Docs: <https://sovaria.in/docs/javascript-setup> · Reference: <https://sovaria.in/docs/javascript-reference>
13
+
14
+ For local workspace development:
15
+
16
+ ```bash
17
+ npm install
18
+ npm run --workspace @sovaria/sdk build
19
+ ```
20
+
21
+ ## Quick Start (an app)
22
+
23
+ Copy the project URL and anon key from the console's **Connect** panel:
24
+
25
+ ```ts
26
+ import { createClient } from '@sovaria/sdk'
27
+
28
+ const sov = createClient('https://<ref>.sovarias.in', '<anon-key>')
29
+
30
+ await sov.auth.signIn('reader@example.com', 'password') // session is saved in localStorage
31
+ const { rows } = await sov.data.sql('select id, title from books order by title')
32
+ ```
33
+
34
+ Or link the folder with the CLI (`sov link`) and build the client from `sovaria.config.json`:
35
+
36
+ ```ts
37
+ import config from './sovaria.config.json'
38
+ import { createClientFromProjectConfig } from '@sovaria/sdk'
39
+
40
+ const sov = createClientFromProjectConfig(config, { publishableKey: import.meta.env.VITE_SOVARIA_ANON_KEY })
41
+ ```
42
+
43
+ ### Sessions
44
+
45
+ In a browser the signed-in session is kept across reloads (`persistSession: false` turns it off;
46
+ `{ storage, key }` stores it elsewhere). Expired access tokens are refreshed automatically; when the
47
+ refresh token is revoked the user is signed out.
48
+
49
+ ```ts
50
+ const stop = sov.auth.onAuthStateChange((event, session) => {
51
+ // INITIAL_SESSION | SIGNED_IN | TOKEN_REFRESHED | SIGNED_OUT
52
+ })
53
+ sov.auth.getSession() // { access_token, refresh_token?, expires_at } | null
54
+ await sov.auth.signOut()
55
+ ```
56
+
57
+ ### Errors you can show to users
58
+
59
+ Every failed call throws `SovariaError`. Its `message` is written for end users ("You don't have
60
+ permission to do that.") and never contains policy names, SQL or table names. Branch on `code`;
61
+ the server's own text is in `technicalMessage` / `detail` for logs.
62
+
63
+ ```ts
64
+ import { SovariaError, userMessageFor } from '@sovaria/sdk'
65
+
66
+ try { await sov.data.sql('delete from reviews where id = $1', [id]) }
67
+ catch (e) {
68
+ if (e instanceof SovariaError && e.code === 'UNAUTHENTICATED') goToSignIn()
69
+ toast(userMessageFor(e))
70
+ console.debug(e instanceof SovariaError ? e.technicalMessage : e)
71
+ }
72
+ ```
73
+
74
+ Codes: `NETWORK_ERROR`, `UNAUTHENTICATED`, `PERMISSION_DENIED`, `NOT_FOUND`, `CONFLICT`,
75
+ `INVALID_INPUT`, `PAYLOAD_TOO_LARGE`, `RATE_LIMITED`, `PLAN_LIMIT_REACHED`, `PLAN_FEATURE_REQUIRED`,
76
+ `PLAN_QUOTA_EXHAUSTED`, `SERVICE_UNAVAILABLE`, `SERVER_ERROR`, `BAD_REQUEST`, `CONFIG_ERROR`.
77
+
78
+ ### Realtime
79
+
80
+ ```ts
81
+ const ch = sov.realtime.channel('book:42', {
82
+ onMessage: (payload) => render(payload),
83
+ onStatus: (s) => setStatus(s), // connecting | live | reconnecting | closed
84
+ })
85
+ await ch.send({ type: 'review', rating: 5 })
86
+ ch.close()
87
+ ```
88
+
89
+ ## Quick Start (operators and scripts)
90
+
91
+ ```ts
92
+ import { SovariaSDK } from '@sovaria/sdk'
93
+
94
+ const sdk = new SovariaSDK({ baseUrl: 'https://api.sovaria.in' })
95
+ await sdk.auth.consoleLogin('you@example.com', 'password')
96
+ sdk.setScope({ orgId: '<org-uuid>', projectId: '<project-uuid>' })
97
+ console.log(await sdk.system.enginesHealth())
98
+ ```
99
+
100
+ ## Supabase-Style Bootstrap (Portal Config)
101
+
102
+ ```ts
103
+ import { createClient } from '@sovaria/sdk'
104
+
105
+ const sdk = createClient({
106
+ url: 'https://api.sovaria.in',
107
+ orgId: '11111111-1111-1111-1111-111111111111',
108
+ projectId: '22222222-2222-2222-2222-222222222222',
109
+ envId: '33333333-3333-3333-3333-333333333333',
110
+ publishableKey: '<token>',
111
+ })
112
+ ```
113
+
114
+ Or bootstrap from environment variables:
115
+
116
+ ```ts
117
+ const sdk = SovariaSDK.fromEnv(process.env)
118
+ ```
119
+
120
+ Supported environment variables:
121
+ - `SOVARIA_URL` (also `NEXT_PUBLIC_SOVARIA_URL`, `VITE_SOVARIA_URL`)
122
+ - `SOVARIA_ORG_ID`
123
+ - `SOVARIA_PROJECT_ID`
124
+ - `SOVARIA_ENV_ID`
125
+ - `SOVARIA_ACCESS_TOKEN` or `SOVARIA_PUBLISHABLE_KEY` or `SOVARIA_ANON_KEY`
126
+
127
+ ## Auth lanes
128
+
129
+ | Method | Path | Lane | Session KEK |
130
+ | --- | --- | --- | --- |
131
+ | `auth.login` (**deprecated**) | `/auth/console/login` unscoped, `/auth/project/login` when scoped | compatibility | derived when `argon2_salt` + password |
132
+ | `auth.consoleLogin` / `auth.loginConsole` | `/auth/console/login` | console operator | derived when salt present |
133
+ | `auth.projectLogin` / `auth.loginProduct` | `/auth/project/login` | product user | derived when salt present |
134
+ | `auth.register` | `/auth/register` | depends on scope | derived when tokens + salt returned |
135
+ | `auth.verifyOtp` / `auth.verifyMagicLink` / `auth.oauthHandoff` | passwordless | product/console | **not** derived unless you pass `password` |
136
+ | `auth.listUsers` (**deprecated**) | warns; product-users paths | n/a | n/a |
137
+ | `auth.consoleMembers.list` | `/org/{orgId}/members` | console member admin | n/a |
138
+ | `auth.listConsoleProductUsers` | `/auth/product-users` | console operator | n/a |
139
+ | `auth.productUsers.list` | `/projects/{id}/auth/users` | project admin + `setScope` | n/a |
140
+
141
+ `auth.logout(refreshToken?)` defaults to the stored refresh token, sends Bearer,
142
+ and always clears tokens/KEK (even when HTTP logout fails). Default
143
+ `onTokenRefresh` omits `refresh_token`; use `onTokenRefreshSensitive` only if you
144
+ must persist it.
145
+
146
+ Refresh has two supported modes. Do not mix them:
147
+
148
+ - **SDK / CLI:** JSON body `{"refresh_token": "..."}`.
149
+ - **Console / browser:** empty JSON body plus the HttpOnly refresh cookie.
150
+
151
+ E2EE (`hash-wasm` 4.12.0, pinned) needs CSP `wasm-unsafe-eval` in browsers.
152
+
153
+ ## Coverage
154
+
155
+ - Axis: auth, context, graph
156
+ - Atlas-Doc: doc put/get/delete/scan
157
+ - Atlas-Rel: SQL + table lifecycle
158
+ - Pulse: stream + e2ee + websocket URL helper
159
+ - Guard: policies
160
+ - Echo: audit + simulation
161
+ - Chrono: timeline/snapshot/variance APIs
162
+ - Gateway: engines health
163
+
164
+ ## Escape Hatch
165
+
166
+ ```ts
167
+ await sdk.request('GET', '/api/v1/system/engines/health', { requiresAuth: false })
168
+ ```
169
+
170
+ ## Functions + Storage Pass-Through
171
+
172
+ ```ts
173
+ // Forge
174
+ const deployStatus = await sdk.functions.status('deploy-123')
175
+
176
+ // Vault
177
+ await sdk.storage.putJson('kv/app/settings', { theme: 'light' })
178
+ const settings = await sdk.storage.get('kv/app/settings')
179
+ await sdk.storage.delete('kv/app/settings')
180
+ ```
@@ -0,0 +1,146 @@
1
+ import type { Bucket, ColumnDefinition, DocumentGetResponse, DocumentPutResponse, DocumentScanResult, FunctionDeployResponse, FunctionInvokeResponse, NodeResponse, RealtimeCallback, RealtimeSubscription, SovariaClientOptions, StorageObject, TimelineJumpResponse, TimelineLogResponse, TokenResponse, UserProfile } from "./types.js";
2
+ /**
3
+ * Async TypeScript client for the Sovaria API Gateway.
4
+ *
5
+ * @deprecated Use {@link SovariaSDK} from `./index`. This legacy client is retained
6
+ * for in-repo tests only and is not a public package export.
7
+ *
8
+ * All requests flow through the gateway; engines are never called directly.
9
+ * Token refresh is automatic and transparent.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const sov = new SovariaClient("https://api.sovaria.in");
14
+ * await sov.auth.login("user@example.com", "password"); // deprecated; posts to /console/login
15
+ * sov.setContext("org-123", "proj-456");
16
+ *
17
+ * const rows = await sov.data.sql.query("SELECT * FROM users LIMIT 10");
18
+ * await sov.auth.logout();
19
+ * ```
20
+ */
21
+ export declare class SovariaClient {
22
+ private readonly baseUrl;
23
+ private accessToken;
24
+ private refreshToken;
25
+ private expiresAt;
26
+ private orgId;
27
+ private projectId;
28
+ private envId;
29
+ private refreshPromise;
30
+ private onTokenRefresh?;
31
+ readonly auth: AuthModule;
32
+ readonly org: OrgModule;
33
+ readonly data: DataModule;
34
+ readonly storage: StorageModule;
35
+ readonly functions: FunctionsModule;
36
+ readonly realtime: RealtimeModule;
37
+ readonly chrono: ChronoModule;
38
+ constructor(baseUrl: string, options?: SovariaClientOptions);
39
+ /**
40
+ * Bind org/project context for multi-tenant headers.
41
+ * These are injected as `X-Sovaria-Org-ID` and `X-Sovaria-Project-ID`
42
+ * on every subsequent request.
43
+ */
44
+ setContext(orgId: string, projectId: string, envId?: string): void;
45
+ clearContext(): void;
46
+ /** @internal */
47
+ _setTokens(tokens: TokenResponse): void;
48
+ /** @internal */
49
+ _clearTokens(): void;
50
+ /** @internal */
51
+ get _refreshToken(): string | null;
52
+ /** @internal */
53
+ get _isAuthenticated(): boolean;
54
+ /**
55
+ * Execute an HTTP request with automatic auth injection, token refresh, and
56
+ * exponential back-off with jitter on transient failures.
57
+ *
58
+ * @internal
59
+ */
60
+ _request<T = unknown>(method: string, path: string, options?: {
61
+ body?: unknown;
62
+ params?: Record<string, string>;
63
+ requiresAuth?: boolean;
64
+ headers?: Record<string, string>;
65
+ }): Promise<T>;
66
+ private ensureTokenFresh;
67
+ private doRefresh;
68
+ /**
69
+ * Build a WebSocket URL from the base URL, converting http(s) to ws(s).
70
+ * @internal
71
+ */
72
+ _wsUrl(path: string): string;
73
+ /** @internal */
74
+ _issueRealtimeWsTicket(channel: string): Promise<string>;
75
+ /** @internal */
76
+ get _accessToken(): string | null;
77
+ }
78
+ declare class AuthModule {
79
+ private readonly client;
80
+ constructor(client: SovariaClient);
81
+ login(email: string, password: string): Promise<TokenResponse>;
82
+ register(email: string, password: string, name: string): Promise<TokenResponse>;
83
+ logout(): Promise<void>;
84
+ me(): Promise<UserProfile>;
85
+ }
86
+ declare class OrgModule {
87
+ private readonly client;
88
+ constructor(client: SovariaClient);
89
+ list(): Promise<NodeResponse[]>;
90
+ get(id: string): Promise<NodeResponse>;
91
+ create(type: string, name: string, metadata?: Record<string, unknown>): Promise<NodeResponse>;
92
+ children(id: string): Promise<NodeResponse[]>;
93
+ }
94
+ declare class SqlSubmodule {
95
+ private readonly client;
96
+ constructor(client: SovariaClient);
97
+ createTable(tableName: string, columns: ColumnDefinition[]): Promise<Record<string, unknown>>;
98
+ query(sql: string, params?: Record<string, unknown>): Promise<Record<string, unknown>[]>;
99
+ dropTable(name: string): Promise<Record<string, unknown>>;
100
+ }
101
+ declare class DocSubmodule {
102
+ private readonly client;
103
+ constructor(client: SovariaClient);
104
+ put(collection: string, key: string, data: Record<string, unknown>): Promise<DocumentPutResponse>;
105
+ get(collection: string, key: string): Promise<DocumentGetResponse>;
106
+ scan(collection: string, filter?: Record<string, unknown>): Promise<DocumentScanResult>;
107
+ }
108
+ declare class DataModule {
109
+ readonly sql: SqlSubmodule;
110
+ readonly doc: DocSubmodule;
111
+ constructor(client: SovariaClient);
112
+ }
113
+ declare class StorageModule {
114
+ private readonly client;
115
+ constructor(client: SovariaClient);
116
+ listBuckets(): Promise<Bucket[]>;
117
+ createBucket(name: string, isPublic?: boolean): Promise<Bucket>;
118
+ listObjects(bucket: string): Promise<StorageObject[]>;
119
+ uploadObject(bucket: string, path: string, body: string | Blob | ArrayBuffer | ReadableStream, contentType?: string): Promise<StorageObject>;
120
+ deleteObject(bucket: string, path: string): Promise<void>;
121
+ }
122
+ declare class FunctionsModule {
123
+ private readonly client;
124
+ constructor(client: SovariaClient);
125
+ deploy(name: string, code: string, runtime: string, entrypoint?: string): Promise<FunctionDeployResponse>;
126
+ invoke(name: string, payload?: unknown): Promise<FunctionInvokeResponse>;
127
+ }
128
+ declare class RealtimeModule {
129
+ private readonly client;
130
+ constructor(client: SovariaClient);
131
+ /**
132
+ * Subscribe to a realtime channel via WebSocket.
133
+ *
134
+ * Uses a short-lived ticket so JWTs are never placed in WebSocket URLs.
135
+ *
136
+ * Returns a subscription handle with an `unsubscribe()` method.
137
+ */
138
+ subscribe(channel: string, callback: RealtimeCallback): RealtimeSubscription;
139
+ }
140
+ declare class ChronoModule {
141
+ private readonly client;
142
+ constructor(client: SovariaClient);
143
+ log(timelineName: string): Promise<TimelineLogResponse>;
144
+ jump(timelineName: string, targetHex: string): Promise<TimelineJumpResponse>;
145
+ }
146
+ export {};