@axonbase/sdk 0.1.1

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 AxonBase
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 ADDED
@@ -0,0 +1,65 @@
1
+ # AxonBase SDK Node.js/TypeScript
2
+
3
+ Cliente WebSocket JSON-RPC do AxonBase para Node.js/TypeScript.
4
+
5
+ ## Instalação
6
+
7
+ ```bash
8
+ npm install @axonbase/sdk
9
+ ```
10
+
11
+ ## Uso básico
12
+
13
+ ```ts
14
+ import { Axon } from "@axonbase/sdk";
15
+
16
+ const axon = await Axon.connect("ws://127.0.0.1:8000/rpc/ws");
17
+ await axon.use("test", "dev");
18
+
19
+ // Consulta AxonQL
20
+ const rows = await axon.query("SELECT * FROM person WHERE age >= 18");
21
+
22
+ // CRUD via RPC
23
+ await axon.create("person", { name: "Ana", age: 30 });
24
+ await axon.update("person", { age: 31 });
25
+ await axon.delete("person");
26
+
27
+ // Live query
28
+ const id = await axon.live("person", (liveId, action, result) => {
29
+ console.log(action, result);
30
+ });
31
+ await axon.kill(id);
32
+
33
+ // Fechar conexão
34
+ axon.close();
35
+ ```
36
+
37
+ ## Funcionalidades
38
+
39
+ - Handshake hello com protocolo versionado
40
+ - Todos os métodos RPC: `ping`, `use`, `query`, `signin`, `signup`, `authenticate`, `invalidate`, `version`
41
+ - CRUD: `select`, `create`, `insert`, `update`, `upsert`, `delete`, `relate`
42
+ - Variáveis de sessão: `let`, `unset`
43
+ - Transações: `begin`, `commit`, `cancel`
44
+ - Key-Value: `kvGet`, `kvSet`, `kvDel`, `kvScan`
45
+ - Live queries: `live`, `kill`
46
+ - Reconexão automática e tratamento de `NOT_LEADER`
47
+ - `vars` tipados (datetime, duration, decimal, bytes, uuid, record, table)
48
+
49
+ ## Configuração
50
+
51
+ ```ts
52
+ const axon = new Axon("ws://127.0.0.1:8000/rpc/ws", {
53
+ timeout: 30_000, // timeout RPC (ms)
54
+ reconnect: true, // reconectar automaticamente
55
+ reconnectInterval: 1_000, // intervalo entre tentativas
56
+ maxReconnectAttempts: 10, // máximo de tentativas
57
+ });
58
+ ```
59
+
60
+ ## Testes
61
+
62
+ ```bash
63
+ # Requer servidor AxonBase rodando
64
+ AXON_URL=ws://127.0.0.1:8000/rpc/ws npm test
65
+ ```
@@ -0,0 +1,92 @@
1
+ import WebSocket from "ws";
2
+ import { HelloFrame, CertificateChallenge, CertificateCompletion, KvEntry } from "./protocol.js";
3
+ export type LiveHandler = (id: string, action: "CREATE" | "UPDATE" | "DELETE", result: unknown) => void;
4
+ export interface AxonOptions {
5
+ /** Timeout padrão para chamadas RPC (ms). */
6
+ timeout?: number;
7
+ /** Reconectar automaticamente ao cair. */
8
+ reconnect?: boolean;
9
+ /** Intervalo entre tentativas de reconexão (ms). */
10
+ reconnectInterval?: number;
11
+ /** Máximo de tentativas de reconexão. */
12
+ maxReconnectAttempts?: number;
13
+ /** TLS and WebSocket client options, including mTLS certificates. */
14
+ tls?: WebSocket.ClientOptions;
15
+ }
16
+ /**
17
+ * Cliente AxonBase para Node.js/TypeScript.
18
+ *
19
+ * ```ts
20
+ * const axon = await Axon.connect("ws://127.0.0.1:8000/rpc/ws");
21
+ * await axon.use("test", "dev");
22
+ * const result = await axon.query("SELECT * FROM person");
23
+ * axon.close();
24
+ * ```
25
+ */
26
+ export declare class Axon {
27
+ private ws;
28
+ private url;
29
+ private readonly options;
30
+ private nextId;
31
+ private readonly pending;
32
+ private readonly liveHandlers;
33
+ private handshakeReceived;
34
+ private _namespace;
35
+ private _database;
36
+ private _auth;
37
+ private hello;
38
+ private openPromise;
39
+ private openResolve;
40
+ private closed;
41
+ constructor(url: string, options?: AxonOptions);
42
+ /** Conecta e aguarda o handshake hello. */
43
+ static connect(url: string, options?: AxonOptions): Promise<Axon>;
44
+ private open;
45
+ private onOpen;
46
+ private onMessage;
47
+ private onClose;
48
+ private reconnectLoop;
49
+ private call;
50
+ private callRpc;
51
+ /**
52
+ * Reconecta o WebSocket a um novo URL, preservando sessão, auth e live queries.
53
+ */
54
+ private reconnectTo;
55
+ private callRaw;
56
+ ping(): Promise<boolean>;
57
+ use(ns: string, db: string): Promise<{
58
+ namespace: string;
59
+ database: string;
60
+ }>;
61
+ query(sql: string, vars?: Record<string, unknown>): Promise<unknown>;
62
+ signin(user: string, pass: string, access?: string): Promise<string>;
63
+ authenticate(token: string): Promise<void>;
64
+ signup(user: string, pass: string): Promise<string>;
65
+ invalidate(): Promise<void>;
66
+ certificateBegin(store: string): Promise<CertificateChallenge>;
67
+ certificateComplete(completion: CertificateCompletion): Promise<string>;
68
+ version(): Promise<string>;
69
+ select(what: string): Promise<unknown>;
70
+ create(what: string, data: Record<string, unknown>): Promise<unknown>;
71
+ update(what: string, data: Record<string, unknown>): Promise<unknown>;
72
+ upsert(what: string, data: Record<string, unknown>): Promise<unknown>;
73
+ delete(what: string): Promise<unknown>;
74
+ insert(table: string, data: Record<string, unknown>): Promise<unknown>;
75
+ relate(from: string, kind: string, to: string, data?: Record<string, unknown>): Promise<unknown>;
76
+ letVar(name: string, value: unknown): Promise<void>;
77
+ unset(name: string): Promise<void>;
78
+ begin(): Promise<void>;
79
+ commit(): Promise<void>;
80
+ cancel(): Promise<void>;
81
+ kvGet(ns: string, db: string, key: string): Promise<unknown>;
82
+ kvSet(ns: string, db: string, key: string, value: unknown, ttl?: number): Promise<unknown>;
83
+ kvDel(ns: string, db: string, key: string): Promise<boolean>;
84
+ kvScan(ns: string, db: string, prefix: string): Promise<KvEntry[]>;
85
+ live(table: string, handler: LiveHandler, diff?: boolean): Promise<string>;
86
+ kill(id: string): Promise<boolean>;
87
+ get namespace(): string;
88
+ get database(): string;
89
+ get isConnected(): boolean;
90
+ get helloInfo(): HelloFrame["hello"] | null;
91
+ close(): void;
92
+ }
package/dist/client.js ADDED
@@ -0,0 +1,389 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Axon = void 0;
7
+ const ws_1 = __importDefault(require("ws"));
8
+ const protocol_js_1 = require("./protocol.js");
9
+ const errors_js_1 = require("./errors.js");
10
+ const codec_js_1 = require("./codec.js");
11
+ /**
12
+ * Cliente AxonBase para Node.js/TypeScript.
13
+ *
14
+ * ```ts
15
+ * const axon = await Axon.connect("ws://127.0.0.1:8000/rpc/ws");
16
+ * await axon.use("test", "dev");
17
+ * const result = await axon.query("SELECT * FROM person");
18
+ * axon.close();
19
+ * ```
20
+ */
21
+ class Axon {
22
+ ws = null;
23
+ url;
24
+ options;
25
+ nextId = 1;
26
+ pending = new Map();
27
+ liveHandlers = new Map();
28
+ handshakeReceived = false;
29
+ _namespace = "";
30
+ _database = "";
31
+ _auth = null;
32
+ hello = null;
33
+ openPromise = null;
34
+ openResolve = null;
35
+ closed = false;
36
+ constructor(url, options) {
37
+ this.url = url;
38
+ this.options = {
39
+ timeout: 30_000,
40
+ reconnect: true,
41
+ reconnectInterval: 1_000,
42
+ maxReconnectAttempts: 10,
43
+ ...options,
44
+ };
45
+ }
46
+ // ------------------------------------------------------------------
47
+ // Conexão
48
+ // ------------------------------------------------------------------
49
+ /** Conecta e aguarda o handshake hello. */
50
+ static async connect(url, options) {
51
+ const axon = new Axon(url, options);
52
+ await axon.open();
53
+ return axon;
54
+ }
55
+ async open() {
56
+ if (this.openPromise)
57
+ return this.openPromise;
58
+ this.openPromise = new Promise((resolve, reject) => {
59
+ this.openResolve = resolve;
60
+ try {
61
+ this.ws = new ws_1.default(this.url, this.options.tls);
62
+ this.ws.on("open", () => this.onOpen());
63
+ this.ws.on("message", (data) => this.onMessage(data.toString()));
64
+ this.ws.on("close", () => this.onClose());
65
+ this.ws.on("error", (err) => {
66
+ if (!this.handshakeReceived)
67
+ reject(err);
68
+ });
69
+ }
70
+ catch (err) {
71
+ reject(err);
72
+ }
73
+ });
74
+ return this.openPromise;
75
+ }
76
+ onOpen() {
77
+ // o handshake hello chega como primeiro frame
78
+ }
79
+ onMessage(text) {
80
+ let parsed;
81
+ try {
82
+ parsed = JSON.parse(text);
83
+ }
84
+ catch {
85
+ return;
86
+ }
87
+ // Handshake hello
88
+ if (!this.handshakeReceived && isHello(parsed)) {
89
+ this.hello = parsed.hello;
90
+ this.handshakeReceived = true;
91
+ if (this.openResolve) {
92
+ this.openResolve();
93
+ this.openResolve = null;
94
+ }
95
+ return;
96
+ }
97
+ // Notificação live
98
+ if (isNotification(parsed)) {
99
+ const n = parsed.notification;
100
+ const handler = this.liveHandlers.get(n.id);
101
+ if (handler) {
102
+ handler(n.id, n.action, n.result);
103
+ }
104
+ return;
105
+ }
106
+ // Resposta RPC
107
+ const rpc = parsed;
108
+ if (rpc.id != null) {
109
+ const pending = this.pending.get(rpc.id);
110
+ if (pending) {
111
+ clearTimeout(pending.timer);
112
+ this.pending.delete(rpc.id);
113
+ pending.resolve(rpc);
114
+ }
115
+ }
116
+ }
117
+ onClose() {
118
+ for (const [, pending] of this.pending) {
119
+ clearTimeout(pending.timer);
120
+ pending.reject(new errors_js_1.AxonSdkError("conexão fechada"));
121
+ }
122
+ this.pending.clear();
123
+ this.ws = null;
124
+ this.handshakeReceived = false;
125
+ this.openPromise = null;
126
+ // Reconexão automática
127
+ if (!this.closed && this.options.reconnect) {
128
+ this.reconnectLoop();
129
+ }
130
+ }
131
+ async reconnectLoop(attempt = 0) {
132
+ if (attempt >= this.options.maxReconnectAttempts)
133
+ return;
134
+ await sleep(this.options.reconnectInterval);
135
+ try {
136
+ await this.open();
137
+ // Re-registrar live queries
138
+ for (const [id] of this.liveHandlers) {
139
+ try {
140
+ await this.call("live", [id, false]);
141
+ }
142
+ catch {
143
+ // A subscription expirou; remover
144
+ this.liveHandlers.delete(id);
145
+ }
146
+ }
147
+ }
148
+ catch {
149
+ await this.reconnectLoop(attempt + 1);
150
+ }
151
+ }
152
+ // ------------------------------------------------------------------
153
+ // Chamada RPC
154
+ // ------------------------------------------------------------------
155
+ async call(method, params) {
156
+ if (!this.ws || this.ws.readyState !== ws_1.default.OPEN) {
157
+ throw new errors_js_1.AxonSdkError("conexão não aberta");
158
+ }
159
+ const id = this.nextId++;
160
+ const request = { id, method, params: params.map(codec_js_1.encodeTyped), version: protocol_js_1.PROTOCOL_VERSION };
161
+ const text = JSON.stringify(request);
162
+ return new Promise((resolve, reject) => {
163
+ const timer = setTimeout(() => {
164
+ this.pending.delete(id);
165
+ reject(new errors_js_1.AxonSdkError(`timeout em ${method}`));
166
+ }, this.options.timeout);
167
+ this.pending.set(id, { resolve: (r) => resolve(r.result), reject, timer });
168
+ this.ws.send(text, (err) => {
169
+ if (err) {
170
+ clearTimeout(timer);
171
+ this.pending.delete(id);
172
+ reject(err);
173
+ }
174
+ });
175
+ }).then((result) => {
176
+ return result;
177
+ }, (err) => {
178
+ throw err;
179
+ });
180
+ }
181
+ async callRpc(method, params) {
182
+ const maxRetries = this.options.reconnect ? 3 : 1;
183
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
184
+ try {
185
+ const response = await this.callRaw(method, params);
186
+ if (response.error) {
187
+ throw (0, errors_js_1.fromRpcError)(response.error);
188
+ }
189
+ return response.result;
190
+ }
191
+ catch (err) {
192
+ if (err instanceof errors_js_1.NotLeaderError && err.leaderAddress && attempt < maxRetries - 1) {
193
+ // Reconectar no líder automaticamente
194
+ const newUrl = this.url.startsWith("ws://") ? `ws://${err.leaderAddress}/rpc/ws` : `wss://${err.leaderAddress}/rpc/ws`;
195
+ await this.reconnectTo(newUrl);
196
+ continue;
197
+ }
198
+ throw err;
199
+ }
200
+ }
201
+ throw new errors_js_1.AxonSdkError("falha após tentativas de reconexão");
202
+ }
203
+ /**
204
+ * Reconecta o WebSocket a um novo URL, preservando sessão, auth e live queries.
205
+ */
206
+ async reconnectTo(newUrl) {
207
+ if (this.ws) {
208
+ try {
209
+ this.ws.close();
210
+ }
211
+ catch { /* ignorar */ }
212
+ this.ws = null;
213
+ }
214
+ this.handshakeReceived = false;
215
+ this.hello = null;
216
+ this.openPromise = null;
217
+ this.openResolve = null;
218
+ this.url = newUrl;
219
+ await this.open();
220
+ if (this._namespace) {
221
+ await this.callRaw("use", [this._namespace, this._database]);
222
+ }
223
+ if (this._auth) {
224
+ await this.callRaw("authenticate", [this._auth]);
225
+ }
226
+ }
227
+ async callRaw(method, params) {
228
+ if (!this.ws || this.ws.readyState !== ws_1.default.OPEN) {
229
+ throw new errors_js_1.AxonSdkError("conexão não aberta");
230
+ }
231
+ const id = this.nextId++;
232
+ const request = { id, method, params: params.map(codec_js_1.encodeTyped), version: protocol_js_1.PROTOCOL_VERSION };
233
+ const text = JSON.stringify(request);
234
+ return new Promise((resolve, reject) => {
235
+ const timer = setTimeout(() => {
236
+ this.pending.delete(id);
237
+ reject(new errors_js_1.AxonSdkError(`timeout em ${method}`));
238
+ }, this.options.timeout);
239
+ this.pending.set(id, { resolve, reject, timer });
240
+ this.ws.send(text, (err) => {
241
+ if (err) {
242
+ clearTimeout(timer);
243
+ this.pending.delete(id);
244
+ reject(err);
245
+ }
246
+ });
247
+ });
248
+ }
249
+ // ------------------------------------------------------------------
250
+ // Métodos RPC
251
+ // ------------------------------------------------------------------
252
+ async ping() {
253
+ return (await this.callRpc("ping", []));
254
+ }
255
+ async use(ns, db) {
256
+ const result = await this.callRpc("use", [ns, db]);
257
+ this._namespace = result.namespace;
258
+ this._database = result.database;
259
+ return result;
260
+ }
261
+ async query(sql, vars) {
262
+ const params = vars ? [sql, vars] : [sql];
263
+ return this.callRpc("query", params);
264
+ }
265
+ async signin(user, pass, access) {
266
+ const cred = { user, pass };
267
+ if (access)
268
+ cred.access = access;
269
+ const token = await this.callRpc("signin", [cred]);
270
+ this._auth = token;
271
+ return token;
272
+ }
273
+ async authenticate(token) {
274
+ await this.callRpc("authenticate", [token]);
275
+ this._auth = token;
276
+ }
277
+ async signup(user, pass) {
278
+ const token = await this.callRpc("signup", [{ user, pass }]);
279
+ this._auth = token;
280
+ return token;
281
+ }
282
+ async invalidate() {
283
+ await this.callRpc("invalidate", []);
284
+ this._auth = null;
285
+ }
286
+ async certificateBegin(store) {
287
+ return (await this.callRpc("certificate.begin", [{ store }]));
288
+ }
289
+ async certificateComplete(completion) {
290
+ return (await this.callRpc("certificate.complete", [completion]));
291
+ }
292
+ async version() {
293
+ return (await this.callRpc("version", []));
294
+ }
295
+ // CRUD helpers via RPC
296
+ async select(what) {
297
+ return this.callRpc("select", [what]);
298
+ }
299
+ async create(what, data) {
300
+ return this.callRpc("create", [what, data]);
301
+ }
302
+ async update(what, data) {
303
+ return this.callRpc("update", [what, data]);
304
+ }
305
+ async upsert(what, data) {
306
+ return this.callRpc("upsert", [what, data]);
307
+ }
308
+ async delete(what) {
309
+ return this.callRpc("delete", [what]);
310
+ }
311
+ async insert(table, data) {
312
+ return this.callRpc("insert", [table, data]);
313
+ }
314
+ async relate(from, kind, to, data) {
315
+ return this.callRpc("relate", [from, kind, to, data ?? {}]);
316
+ }
317
+ // Variáveis de sessão
318
+ async letVar(name, value) {
319
+ const cleanName = name.startsWith("$") ? name.slice(1) : name;
320
+ await this.callRaw("let", [cleanName, value]);
321
+ }
322
+ async unset(name) {
323
+ const cleanName = name.startsWith("$") ? name.slice(1) : name;
324
+ await this.callRaw("unset", [cleanName]);
325
+ }
326
+ // Transações
327
+ async begin() {
328
+ await this.callRpc("begin", []);
329
+ }
330
+ async commit() {
331
+ await this.callRpc("commit", []);
332
+ }
333
+ async cancel() {
334
+ await this.callRpc("cancel", []);
335
+ }
336
+ // Key-Value
337
+ async kvGet(ns, db, key) {
338
+ return this.callRpc("kv_get", [ns, db, key]);
339
+ }
340
+ async kvSet(ns, db, key, value, ttl) {
341
+ return this.callRpc("kv_set", [ns, db, key, value, ttl ?? null]);
342
+ }
343
+ async kvDel(ns, db, key) {
344
+ return (await this.callRpc("kv_del", [ns, db, key]));
345
+ }
346
+ async kvScan(ns, db, prefix) {
347
+ return (await this.callRpc("kv_scan", [ns, db, prefix]));
348
+ }
349
+ // Live queries
350
+ async live(table, handler, diff) {
351
+ const id = await this.callRpc("live", [table, diff ?? false]);
352
+ this.liveHandlers.set(id, handler);
353
+ return id;
354
+ }
355
+ async kill(id) {
356
+ const ok = await this.callRpc("kill", [id]);
357
+ if (ok)
358
+ this.liveHandlers.delete(id);
359
+ return ok;
360
+ }
361
+ // ------------------------------------------------------------------
362
+ // Getters
363
+ // ------------------------------------------------------------------
364
+ get namespace() { return this._namespace; }
365
+ get database() { return this._database; }
366
+ get isConnected() { return this.ws?.readyState === ws_1.default.OPEN; }
367
+ get helloInfo() { return this.hello; }
368
+ // ------------------------------------------------------------------
369
+ // Encerramento
370
+ // ------------------------------------------------------------------
371
+ close() {
372
+ this.closed = true;
373
+ this.liveHandlers.clear();
374
+ if (this.ws) {
375
+ this.ws.close();
376
+ this.ws = null;
377
+ }
378
+ }
379
+ }
380
+ exports.Axon = Axon;
381
+ function isHello(v) {
382
+ return typeof v === "object" && v !== null && "hello" in v;
383
+ }
384
+ function isNotification(v) {
385
+ return typeof v === "object" && v !== null && "notification" in v;
386
+ }
387
+ function sleep(ms) {
388
+ return new Promise((resolve) => setTimeout(resolve, ms));
389
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Codec de valores tipados do AxonBase.
3
+ *
4
+ * No wire JSON, tipos especiais são representados por objetos marcados:
5
+ * `{"$decimal":"..."}`, `{"$bytes":"base64"}`, `{"$datetime":"ISO8601"}`,
6
+ * `{"$duration":"1h"}`, `{"$record":"tabela:chave"}`, `{"$uuid":"..."}`,
7
+ * `{"$table":"nome"}`.
8
+ */
9
+ export type AxonValue = null | boolean | number | string | AxonValue[] | {
10
+ [key: string]: AxonValue;
11
+ } | TypedValue;
12
+ export type TypedValue = {
13
+ $decimal: string;
14
+ } | {
15
+ $bytes: string;
16
+ } | {
17
+ $datetime: string;
18
+ } | {
19
+ $duration: string;
20
+ } | {
21
+ $record: string;
22
+ } | {
23
+ $uuid: string;
24
+ } | {
25
+ $table: string;
26
+ };
27
+ /** Verifica se um valor é um objeto marcado com tipo. */
28
+ export declare function isTypedValue(v: unknown): v is TypedValue;
29
+ /** Converte um valor tipado de volta para string de apresentação, para uso em logs. */
30
+ export declare function typedValueToString(v: TypedValue): string;
31
+ /** Envolve um valor AxonQL em envelope marcado, se necessário, para preservar o tipo. */
32
+ export declare function encodeTyped(value: unknown): AxonValue;
package/dist/codec.js ADDED
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isTypedValue = isTypedValue;
4
+ exports.typedValueToString = typedValueToString;
5
+ exports.encodeTyped = encodeTyped;
6
+ /** Verifica se um valor é um objeto marcado com tipo. */
7
+ function isTypedValue(v) {
8
+ if (typeof v !== "object" || v === null)
9
+ return false;
10
+ const keys = Object.keys(v);
11
+ if (keys.length !== 1)
12
+ return false;
13
+ const key = keys[0];
14
+ return ["$decimal", "$bytes", "$datetime", "$duration", "$record", "$uuid", "$table"].includes(key);
15
+ }
16
+ /** Converte um valor tipado de volta para string de apresentação, para uso em logs. */
17
+ function typedValueToString(v) {
18
+ const key = Object.keys(v)[0];
19
+ const value = v[key];
20
+ return `${key}=${value}`;
21
+ }
22
+ /** Envolve um valor AxonQL em envelope marcado, se necessário, para preservar o tipo. */
23
+ function encodeTyped(value) {
24
+ if (value === null || value === undefined)
25
+ return null;
26
+ if (typeof value === "boolean" || typeof value === "number")
27
+ return value;
28
+ if (typeof value === "string")
29
+ return value;
30
+ if (Array.isArray(value))
31
+ return value.map(encodeTyped);
32
+ if (typeof value === "object") {
33
+ const obj = value;
34
+ // Se já é um valor marcado, retorna como está
35
+ if (isTypedValue(obj))
36
+ return obj;
37
+ const result = {};
38
+ for (const [k, v] of Object.entries(obj)) {
39
+ result[k] = encodeTyped(v);
40
+ }
41
+ return result;
42
+ }
43
+ return String(value);
44
+ }
@@ -0,0 +1,29 @@
1
+ /** Erros específicos do SDK Axon. */
2
+ export declare class AxonSdkError extends Error {
3
+ readonly code?: number | undefined;
4
+ constructor(message: string, code?: number | undefined);
5
+ }
6
+ export declare class NotLeaderError extends AxonSdkError {
7
+ readonly leader: string;
8
+ readonly leaderAddress: string;
9
+ constructor(message: string, leader: string, leaderAddress: string);
10
+ }
11
+ export declare class NoQuorumError extends AxonSdkError {
12
+ constructor(message: string);
13
+ }
14
+ export declare class RateLimitError extends AxonSdkError {
15
+ constructor(message: string);
16
+ }
17
+ export declare class ProtocolMismatchError extends AxonSdkError {
18
+ readonly protocol: number;
19
+ readonly serverVersion: string;
20
+ constructor(message: string, protocol: number, serverVersion: string);
21
+ }
22
+ export declare class AuthError extends AxonSdkError {
23
+ constructor(message: string);
24
+ }
25
+ export declare class ConflictError extends AxonSdkError {
26
+ constructor(message: string);
27
+ }
28
+ export declare function fromRpcError(err: AxonError): AxonSdkError;
29
+ import { AxonError } from "./protocol.js";
package/dist/errors.js ADDED
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConflictError = exports.AuthError = exports.ProtocolMismatchError = exports.RateLimitError = exports.NoQuorumError = exports.NotLeaderError = exports.AxonSdkError = void 0;
4
+ exports.fromRpcError = fromRpcError;
5
+ /** Erros específicos do SDK Axon. */
6
+ class AxonSdkError extends Error {
7
+ code;
8
+ constructor(message, code) {
9
+ super(message);
10
+ this.code = code;
11
+ this.name = "AxonSdkError";
12
+ }
13
+ }
14
+ exports.AxonSdkError = AxonSdkError;
15
+ class NotLeaderError extends AxonSdkError {
16
+ leader;
17
+ leaderAddress;
18
+ constructor(message, leader, leaderAddress) {
19
+ super(message, -32010);
20
+ this.leader = leader;
21
+ this.leaderAddress = leaderAddress;
22
+ this.name = "NotLeaderError";
23
+ }
24
+ }
25
+ exports.NotLeaderError = NotLeaderError;
26
+ class NoQuorumError extends AxonSdkError {
27
+ constructor(message) {
28
+ super(message, -32011);
29
+ this.name = "NoQuorumError";
30
+ }
31
+ }
32
+ exports.NoQuorumError = NoQuorumError;
33
+ class RateLimitError extends AxonSdkError {
34
+ constructor(message) {
35
+ super(message, -32029);
36
+ this.name = "RateLimitError";
37
+ }
38
+ }
39
+ exports.RateLimitError = RateLimitError;
40
+ class ProtocolMismatchError extends AxonSdkError {
41
+ protocol;
42
+ serverVersion;
43
+ constructor(message, protocol, serverVersion) {
44
+ super(message, -32600);
45
+ this.protocol = protocol;
46
+ this.serverVersion = serverVersion;
47
+ this.name = "ProtocolMismatchError";
48
+ }
49
+ }
50
+ exports.ProtocolMismatchError = ProtocolMismatchError;
51
+ class AuthError extends AxonSdkError {
52
+ constructor(message) {
53
+ super(message, -32002);
54
+ this.name = "AuthError";
55
+ }
56
+ }
57
+ exports.AuthError = AuthError;
58
+ class ConflictError extends AxonSdkError {
59
+ constructor(message) {
60
+ super(message, -32009);
61
+ this.name = "ConflictError";
62
+ }
63
+ }
64
+ exports.ConflictError = ConflictError;
65
+ function fromRpcError(err) {
66
+ switch (err.code) {
67
+ case -32010: return new NotLeaderError(err.message, err.leader ?? "", err.leader_address ?? "");
68
+ case -32011: return new NoQuorumError(err.message);
69
+ case -32029: return new RateLimitError(err.message);
70
+ case -32002: return new AuthError(err.message);
71
+ case -32009: return new ConflictError(err.message);
72
+ default: return new AxonSdkError(err.message, err.code);
73
+ }
74
+ }
@@ -0,0 +1,10 @@
1
+ /** AxonBase SDK para Node.js/TypeScript. */
2
+ export { Axon } from "./client.js";
3
+ export { SagaTransaction } from "./saga.js";
4
+ export { SagaParticipantTransaction } from "./saga-participant.js";
5
+ export type { AxonOptions, LiveHandler } from "./client.js";
6
+ export type { AxonValue, TypedValue } from "./codec.js";
7
+ export { encodeTyped, isTypedValue, typedValueToString } from "./codec.js";
8
+ export { AxonSdkError, NotLeaderError, NoQuorumError, RateLimitError, ProtocolMismatchError, AuthError, ConflictError, fromRpcError, } from "./errors.js";
9
+ export { PROTOCOL_VERSION, METHODS, ERR_PARSE, ERR_INVALID_REQ, ERR_METHOD_NOT_FOUND, ERR_INVALID_PARAMS, ERR_INTERNAL, ERR_AUTH, ERR_RUNTIME, ERR_TXN_CONFLICT, ERR_NOT_LEADER, ERR_NO_QUORUM, ERR_RATE_LIMIT, } from "./protocol.js";
10
+ export type { Method, AxonError, HelloFrame, NotificationFrame, KvEntry, Status, CertificateChallenge, CertificateCompletion, } from "./protocol.js";
package/dist/index.js ADDED
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ERR_RATE_LIMIT = exports.ERR_NO_QUORUM = exports.ERR_NOT_LEADER = exports.ERR_TXN_CONFLICT = exports.ERR_RUNTIME = exports.ERR_AUTH = exports.ERR_INTERNAL = exports.ERR_INVALID_PARAMS = exports.ERR_METHOD_NOT_FOUND = exports.ERR_INVALID_REQ = exports.ERR_PARSE = exports.METHODS = exports.PROTOCOL_VERSION = exports.fromRpcError = exports.ConflictError = exports.AuthError = exports.ProtocolMismatchError = exports.RateLimitError = exports.NoQuorumError = exports.NotLeaderError = exports.AxonSdkError = exports.typedValueToString = exports.isTypedValue = exports.encodeTyped = exports.SagaParticipantTransaction = exports.SagaTransaction = exports.Axon = void 0;
4
+ /** AxonBase SDK para Node.js/TypeScript. */
5
+ var client_js_1 = require("./client.js");
6
+ Object.defineProperty(exports, "Axon", { enumerable: true, get: function () { return client_js_1.Axon; } });
7
+ var saga_js_1 = require("./saga.js");
8
+ Object.defineProperty(exports, "SagaTransaction", { enumerable: true, get: function () { return saga_js_1.SagaTransaction; } });
9
+ var saga_participant_js_1 = require("./saga-participant.js");
10
+ Object.defineProperty(exports, "SagaParticipantTransaction", { enumerable: true, get: function () { return saga_participant_js_1.SagaParticipantTransaction; } });
11
+ var codec_js_1 = require("./codec.js");
12
+ Object.defineProperty(exports, "encodeTyped", { enumerable: true, get: function () { return codec_js_1.encodeTyped; } });
13
+ Object.defineProperty(exports, "isTypedValue", { enumerable: true, get: function () { return codec_js_1.isTypedValue; } });
14
+ Object.defineProperty(exports, "typedValueToString", { enumerable: true, get: function () { return codec_js_1.typedValueToString; } });
15
+ var errors_js_1 = require("./errors.js");
16
+ Object.defineProperty(exports, "AxonSdkError", { enumerable: true, get: function () { return errors_js_1.AxonSdkError; } });
17
+ Object.defineProperty(exports, "NotLeaderError", { enumerable: true, get: function () { return errors_js_1.NotLeaderError; } });
18
+ Object.defineProperty(exports, "NoQuorumError", { enumerable: true, get: function () { return errors_js_1.NoQuorumError; } });
19
+ Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_js_1.RateLimitError; } });
20
+ Object.defineProperty(exports, "ProtocolMismatchError", { enumerable: true, get: function () { return errors_js_1.ProtocolMismatchError; } });
21
+ Object.defineProperty(exports, "AuthError", { enumerable: true, get: function () { return errors_js_1.AuthError; } });
22
+ Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return errors_js_1.ConflictError; } });
23
+ Object.defineProperty(exports, "fromRpcError", { enumerable: true, get: function () { return errors_js_1.fromRpcError; } });
24
+ var protocol_js_1 = require("./protocol.js");
25
+ Object.defineProperty(exports, "PROTOCOL_VERSION", { enumerable: true, get: function () { return protocol_js_1.PROTOCOL_VERSION; } });
26
+ Object.defineProperty(exports, "METHODS", { enumerable: true, get: function () { return protocol_js_1.METHODS; } });
27
+ Object.defineProperty(exports, "ERR_PARSE", { enumerable: true, get: function () { return protocol_js_1.ERR_PARSE; } });
28
+ Object.defineProperty(exports, "ERR_INVALID_REQ", { enumerable: true, get: function () { return protocol_js_1.ERR_INVALID_REQ; } });
29
+ Object.defineProperty(exports, "ERR_METHOD_NOT_FOUND", { enumerable: true, get: function () { return protocol_js_1.ERR_METHOD_NOT_FOUND; } });
30
+ Object.defineProperty(exports, "ERR_INVALID_PARAMS", { enumerable: true, get: function () { return protocol_js_1.ERR_INVALID_PARAMS; } });
31
+ Object.defineProperty(exports, "ERR_INTERNAL", { enumerable: true, get: function () { return protocol_js_1.ERR_INTERNAL; } });
32
+ Object.defineProperty(exports, "ERR_AUTH", { enumerable: true, get: function () { return protocol_js_1.ERR_AUTH; } });
33
+ Object.defineProperty(exports, "ERR_RUNTIME", { enumerable: true, get: function () { return protocol_js_1.ERR_RUNTIME; } });
34
+ Object.defineProperty(exports, "ERR_TXN_CONFLICT", { enumerable: true, get: function () { return protocol_js_1.ERR_TXN_CONFLICT; } });
35
+ Object.defineProperty(exports, "ERR_NOT_LEADER", { enumerable: true, get: function () { return protocol_js_1.ERR_NOT_LEADER; } });
36
+ Object.defineProperty(exports, "ERR_NO_QUORUM", { enumerable: true, get: function () { return protocol_js_1.ERR_NO_QUORUM; } });
37
+ Object.defineProperty(exports, "ERR_RATE_LIMIT", { enumerable: true, get: function () { return protocol_js_1.ERR_RATE_LIMIT; } });
@@ -0,0 +1,2 @@
1
+ export { Migrator } from "./migrator.js";
2
+ export type { MigrationRecord, MigrationFile, MigrationHook } from "./migrator.js";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Migrator = void 0;
4
+ var migrator_js_1 = require("./migrator.js");
5
+ Object.defineProperty(exports, "Migrator", { enumerable: true, get: function () { return migrator_js_1.Migrator; } });
@@ -0,0 +1,31 @@
1
+ import { Axon } from "../client.js";
2
+ export interface MigrationRecord {
3
+ version: string;
4
+ name: string;
5
+ checksum: string;
6
+ applied_at: string;
7
+ }
8
+ export interface MigrationFile {
9
+ version: string;
10
+ name: string;
11
+ path: string;
12
+ checksum: string;
13
+ }
14
+ export type MigrationHook = (migration: MigrationFile) => void | Promise<void>;
15
+ export declare class Migrator {
16
+ private axon;
17
+ private table;
18
+ private beforeHooks;
19
+ private afterHooks;
20
+ constructor(axon: Axon, table?: string);
21
+ onBefore(hook: MigrationHook): void;
22
+ onAfter(hook: MigrationHook): void;
23
+ ensureTable(): Promise<void>;
24
+ applied(): Promise<MigrationRecord[]>;
25
+ load(path: string): MigrationFile[];
26
+ status(path: string): Promise<{
27
+ pending: MigrationFile[];
28
+ applied: MigrationRecord[];
29
+ }>;
30
+ up(path: string): Promise<MigrationRecord[]>;
31
+ }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Migrator = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_fs_1 = require("node:fs");
6
+ const node_path_1 = require("node:path");
7
+ const DEFAULT_TABLE = "_migration";
8
+ const CREATE_TABLE_SQL = `
9
+ DEFINE TABLE _migration SCHEMAFULL;
10
+ DEFINE FIELD version ON TABLE _migration TYPE string;
11
+ DEFINE FIELD name ON TABLE _migration TYPE string;
12
+ DEFINE FIELD checksum ON TABLE _migration TYPE string;
13
+ DEFINE FIELD applied_at ON TABLE _migration TYPE datetime DEFAULT time::now();
14
+ `;
15
+ class Migrator {
16
+ axon;
17
+ table;
18
+ beforeHooks = [];
19
+ afterHooks = [];
20
+ constructor(axon, table) {
21
+ this.axon = axon;
22
+ this.table = table ?? DEFAULT_TABLE;
23
+ }
24
+ onBefore(hook) {
25
+ this.beforeHooks.push(hook);
26
+ }
27
+ onAfter(hook) {
28
+ this.afterHooks.push(hook);
29
+ }
30
+ async ensureTable() {
31
+ await this.axon.query(CREATE_TABLE_SQL);
32
+ }
33
+ async applied() {
34
+ const result = await this.axon.query(`SELECT version, name, checksum, applied_at FROM ${this.table} ORDER BY version ASC`);
35
+ return result ?? [];
36
+ }
37
+ load(path) {
38
+ const resolved = (0, node_path_1.resolve)(path);
39
+ const stat = (0, node_fs_1.statSync)(resolved);
40
+ if (stat.isFile()) {
41
+ if (!resolved.endsWith(".axql")) {
42
+ throw new Error(`not an .axql file: ${resolved}`);
43
+ }
44
+ return [parseFile(resolved)];
45
+ }
46
+ const entries = (0, node_fs_1.readdirSync)(resolved)
47
+ .filter((f) => f.endsWith(".axql"))
48
+ .sort();
49
+ return entries.map((f) => parseFile((0, node_path_1.join)(resolved, f)));
50
+ }
51
+ async status(path) {
52
+ const files = this.load(path);
53
+ const applied = await this.applied();
54
+ const appliedVersions = new Set(applied.map((r) => r.version));
55
+ const pending = files.filter((f) => !appliedVersions.has(f.version));
56
+ return { pending, applied };
57
+ }
58
+ async up(path) {
59
+ const { pending } = await this.status(path);
60
+ const completed = [];
61
+ for (const migration of pending) {
62
+ for (const hook of this.beforeHooks) {
63
+ await hook(migration);
64
+ }
65
+ const sql = (0, node_fs_1.readFileSync)(migration.path, "utf-8");
66
+ await this.axon.query(sql);
67
+ const dateStr = new Date().toISOString();
68
+ const result = await this.axon.query(`UPSERT ${this.table}:v_${migration.version} CONTENT { version: $v, name: $n, checksum: $c, applied_at: time::now() }`, {
69
+ v: migration.version,
70
+ n: migration.name,
71
+ c: migration.checksum,
72
+ });
73
+ for (const hook of this.afterHooks) {
74
+ await hook(migration);
75
+ }
76
+ completed.push({
77
+ version: migration.version,
78
+ name: migration.name,
79
+ checksum: migration.checksum,
80
+ applied_at: dateStr,
81
+ });
82
+ }
83
+ return completed;
84
+ }
85
+ }
86
+ exports.Migrator = Migrator;
87
+ function parseFile(filePath) {
88
+ const basename = filePath.split("/").pop() ?? filePath;
89
+ const name = basename.endsWith(".axql") ? basename.slice(0, -5) : basename;
90
+ const version = name.includes("_") ? name.substring(0, name.indexOf("_")) : name;
91
+ const content = (0, node_fs_1.readFileSync)(filePath);
92
+ const checksum = (0, node_crypto_1.createHash)("sha256").update(content).digest("hex");
93
+ return { version, name, path: filePath, checksum };
94
+ }
@@ -0,0 +1,82 @@
1
+ /** AxonBase protocol constants. */
2
+ export declare const PROTOCOL_VERSION = 1;
3
+ export declare const SERVER_VERSION = "0.1.0-SNAPSHOT";
4
+ export declare const METHODS: readonly ["ping", "use", "query", "signin", "authenticate", "live", "kill", "version", "begin", "commit", "cancel", "kv_get", "kv_set", "kv_del", "kv_scan", "let", "set", "unset", "select", "create", "insert", "update", "upsert", "delete", "relate", "signup", "invalidate", "certificate.begin", "certificate.complete"];
5
+ export type Method = typeof METHODS[number];
6
+ export declare const ERR_PARSE = -32700;
7
+ export declare const ERR_INVALID_REQ = -32600;
8
+ export declare const ERR_METHOD_NOT_FOUND = -32601;
9
+ export declare const ERR_INVALID_PARAMS = -32602;
10
+ export declare const ERR_INTERNAL = -32000;
11
+ export declare const ERR_AUTH = -32002;
12
+ export declare const ERR_RUNTIME = -32003;
13
+ export declare const ERR_TXN_CONFLICT = -32009;
14
+ export declare const ERR_NOT_LEADER = -32010;
15
+ export declare const ERR_NO_QUORUM = -32011;
16
+ export declare const ERR_RATE_LIMIT = -32029;
17
+ export declare const PROTOCOL_MISMATCH = -32600;
18
+ export interface AxonError {
19
+ code: number;
20
+ message: string;
21
+ kind?: string;
22
+ leader?: string;
23
+ leader_address?: string;
24
+ protocol?: number;
25
+ version?: string;
26
+ }
27
+ export interface HelloFrame {
28
+ hello: {
29
+ protocol: number;
30
+ server: string;
31
+ methods: string[];
32
+ };
33
+ }
34
+ export interface NotificationFrame {
35
+ notification: {
36
+ id: string;
37
+ action: "CREATE" | "UPDATE" | "DELETE";
38
+ result: unknown;
39
+ };
40
+ }
41
+ export interface RpcRequest {
42
+ id: number;
43
+ method: string;
44
+ params: unknown[];
45
+ version?: number;
46
+ }
47
+ export interface RpcResponse {
48
+ id: number | null;
49
+ result?: unknown;
50
+ error?: AxonError;
51
+ }
52
+ export interface Status {
53
+ node_id: string;
54
+ cluster_id: string;
55
+ role: string;
56
+ leader: string;
57
+ leader_address: string;
58
+ term: number;
59
+ commit_index: number;
60
+ active: number;
61
+ members: number;
62
+ quorum: number;
63
+ ready: boolean;
64
+ }
65
+ export interface KvEntry {
66
+ key: string;
67
+ value: unknown;
68
+ ttl?: number;
69
+ }
70
+ export interface CertificateChallenge {
71
+ id: string;
72
+ challenge: string;
73
+ expires_at: string;
74
+ }
75
+ export interface CertificateCompletion {
76
+ id: string;
77
+ challenge: string;
78
+ store: string;
79
+ user: string;
80
+ chain: string[];
81
+ signature: string;
82
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROTOCOL_MISMATCH = exports.ERR_RATE_LIMIT = exports.ERR_NO_QUORUM = exports.ERR_NOT_LEADER = exports.ERR_TXN_CONFLICT = exports.ERR_RUNTIME = exports.ERR_AUTH = exports.ERR_INTERNAL = exports.ERR_INVALID_PARAMS = exports.ERR_METHOD_NOT_FOUND = exports.ERR_INVALID_REQ = exports.ERR_PARSE = exports.METHODS = exports.SERVER_VERSION = exports.PROTOCOL_VERSION = void 0;
4
+ /** AxonBase protocol constants. */
5
+ exports.PROTOCOL_VERSION = 1;
6
+ exports.SERVER_VERSION = "0.1.0-SNAPSHOT";
7
+ exports.METHODS = [
8
+ "ping", "use", "query", "signin", "authenticate", "live", "kill", "version",
9
+ "begin", "commit", "cancel",
10
+ "kv_get", "kv_set", "kv_del", "kv_scan",
11
+ "let", "set", "unset", "select", "create", "insert", "update", "upsert", "delete", "relate",
12
+ "signup", "invalidate", "certificate.begin", "certificate.complete",
13
+ ];
14
+ /* Códigos de erro */
15
+ exports.ERR_PARSE = -32700;
16
+ exports.ERR_INVALID_REQ = -32600;
17
+ exports.ERR_METHOD_NOT_FOUND = -32601;
18
+ exports.ERR_INVALID_PARAMS = -32602;
19
+ exports.ERR_INTERNAL = -32000;
20
+ exports.ERR_AUTH = -32002;
21
+ exports.ERR_RUNTIME = -32003;
22
+ exports.ERR_TXN_CONFLICT = -32009;
23
+ exports.ERR_NOT_LEADER = -32010;
24
+ exports.ERR_NO_QUORUM = -32011;
25
+ exports.ERR_RATE_LIMIT = -32029;
26
+ exports.PROTOCOL_MISMATCH = -32600; // com kind="PROTOCOL_MISMATCH"
@@ -0,0 +1,16 @@
1
+ import { Axon } from "./client.js";
2
+ /** Joins an active Saga while controlling only this client's local transaction. */
3
+ export declare class SagaParticipantTransaction {
4
+ private readonly axon;
5
+ readonly correlationId: string;
6
+ private begun;
7
+ private finished;
8
+ constructor(axon: Axon, correlationId: string);
9
+ get isBegun(): boolean;
10
+ get isFinished(): boolean;
11
+ begin(): Promise<void>;
12
+ step(axonql: string): Promise<unknown>;
13
+ commit(): Promise<void>;
14
+ rollback(): Promise<void>;
15
+ private assertActive;
16
+ }
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SagaParticipantTransaction = void 0;
4
+ const errors_js_1 = require("./errors.js");
5
+ /** Joins an active Saga while controlling only this client's local transaction. */
6
+ class SagaParticipantTransaction {
7
+ axon;
8
+ correlationId;
9
+ begun = false;
10
+ finished = false;
11
+ constructor(axon, correlationId) {
12
+ this.axon = axon;
13
+ this.correlationId = correlationId;
14
+ }
15
+ get isBegun() { return this.begun; }
16
+ get isFinished() { return this.finished; }
17
+ async begin() {
18
+ if (this.begun)
19
+ throw new errors_js_1.AxonSdkError(`Transaction already begun: ${this.correlationId}`);
20
+ await this.axon.begin();
21
+ try {
22
+ await this.axon.letVar("saga_corr", this.correlationId);
23
+ this.begun = true;
24
+ }
25
+ catch (error) {
26
+ try {
27
+ await this.axon.cancel();
28
+ }
29
+ catch { /* preserve the setup error */ }
30
+ throw error;
31
+ }
32
+ }
33
+ async step(axonql) {
34
+ this.assertActive();
35
+ return this.axon.query(axonql);
36
+ }
37
+ async commit() {
38
+ this.assertActive();
39
+ await this.axon.commit();
40
+ this.finished = true;
41
+ }
42
+ async rollback() {
43
+ if (!this.begun || this.finished)
44
+ return;
45
+ await this.axon.cancel();
46
+ this.finished = true;
47
+ }
48
+ assertActive() {
49
+ if (!this.begun)
50
+ throw new errors_js_1.AxonSdkError("Transaction not begun");
51
+ if (this.finished)
52
+ throw new errors_js_1.AxonSdkError("Transaction already finished");
53
+ }
54
+ }
55
+ exports.SagaParticipantTransaction = SagaParticipantTransaction;
package/dist/saga.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { Axon } from "./client.js";
2
+ /** Client-side helper for an AxonBase distributed saga. */
3
+ export declare class SagaTransaction {
4
+ private readonly axon;
5
+ readonly sagaName: string;
6
+ readonly correlationId: string;
7
+ private begun;
8
+ private finished;
9
+ constructor(axon: Axon, sagaName: string, correlationId: string);
10
+ get isBegun(): boolean;
11
+ get isFinished(): boolean;
12
+ begin(): Promise<void>;
13
+ step(axonql: string): Promise<unknown>;
14
+ commit(): Promise<void>;
15
+ rollback(): Promise<void>;
16
+ describe(): Promise<unknown>;
17
+ private assertActive;
18
+ }
package/dist/saga.js ADDED
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SagaTransaction = void 0;
4
+ const errors_js_1 = require("./errors.js");
5
+ /** Client-side helper for an AxonBase distributed saga. */
6
+ class SagaTransaction {
7
+ axon;
8
+ sagaName;
9
+ correlationId;
10
+ begun = false;
11
+ finished = false;
12
+ constructor(axon, sagaName, correlationId) {
13
+ this.axon = axon;
14
+ this.sagaName = sagaName;
15
+ this.correlationId = correlationId;
16
+ }
17
+ get isBegun() { return this.begun; }
18
+ get isFinished() { return this.finished; }
19
+ async begin() {
20
+ if (this.begun)
21
+ throw new errors_js_1.AxonSdkError(`Saga already begun: ${this.correlationId}`);
22
+ const result = await this.axon.query(`BEGIN SAGA ${escapeSagaValue(this.sagaName)} WITH CORRELATION '${escapeSagaValue(this.correlationId)}'`);
23
+ if (hasStatus(result, "RUNNING")) {
24
+ this.begun = true;
25
+ return;
26
+ }
27
+ throw new errors_js_1.AxonSdkError(`Failed to begin saga: ${JSON.stringify(result)}`);
28
+ }
29
+ async step(axonql) {
30
+ this.assertActive();
31
+ await this.axon.letVar("saga_corr", this.correlationId);
32
+ return this.axon.query(axonql);
33
+ }
34
+ async commit() {
35
+ this.assertActive();
36
+ const result = await this.axon.query(`COMMIT SAGA ${escapeSagaValue(this.sagaName)} WITH CORRELATION '${escapeSagaValue(this.correlationId)}'`);
37
+ this.finished = true;
38
+ if (!hasStatus(result, "COMMITTED")) {
39
+ throw new errors_js_1.AxonSdkError(`Saga commit failed: ${JSON.stringify(result)}`);
40
+ }
41
+ }
42
+ async rollback() {
43
+ if (!this.begun || this.finished)
44
+ return;
45
+ await this.axon.query(`CANCEL SAGA ${escapeSagaValue(this.sagaName)} WITH CORRELATION '${escapeSagaValue(this.correlationId)}'`);
46
+ this.finished = true;
47
+ }
48
+ describe() {
49
+ return this.axon.query(`SHOW SAGA TRANSACTION ${escapeSagaValue(this.sagaName)} '${escapeSagaValue(this.correlationId)}'`);
50
+ }
51
+ assertActive() {
52
+ if (!this.begun)
53
+ throw new errors_js_1.AxonSdkError("Saga not begun");
54
+ if (this.finished)
55
+ throw new errors_js_1.AxonSdkError("Saga already finished");
56
+ }
57
+ }
58
+ exports.SagaTransaction = SagaTransaction;
59
+ function hasStatus(result, expected) {
60
+ return typeof result === "object" && result !== null && "status" in result
61
+ && result.status === expected;
62
+ }
63
+ function escapeSagaValue(value) {
64
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "''");
65
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@axonbase/sdk",
3
+ "version": "0.1.1",
4
+ "description": "AxonBase WebSocket JSON-RPC client for Node.js and TypeScript.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": ["dist", "LICENSE"],
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "tsx --test tests/client.test.ts tests/saga-participant.test.ts tests/saga.test.ts",
11
+ "test:integration": "tsx --test tests/integration.test.ts",
12
+ "prepublishOnly": "npm run build"
13
+ },
14
+ "dependencies": {
15
+ "ws": "^8.18.0"
16
+ },
17
+ "devDependencies": {
18
+ "@types/node": "^22.0.0",
19
+ "@types/ws": "^8.5.10",
20
+ "tsx": "^4.19.0",
21
+ "typescript": "^5.6.0"
22
+ },
23
+ "engines": {
24
+ "node": ">=18.0.0"
25
+ },
26
+ "license": "MIT",
27
+ "homepage": "https://github.com/axonbase/axonbase",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/axonbase/axonbase.git"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/axonbase/axonbase/issues"
34
+ },
35
+ "keywords": ["axonbase", "database", "websocket", "json-rpc"]
36
+ }