@canton-network/core-wallet-store-sql 1.9.0 → 1.10.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/dist/index.js CHANGED
@@ -1,977 +1,838 @@
1
- import { assertConnected, authSchema } from '@canton-network/core-wallet-auth';
2
- import { Kysely, CamelCasePlugin, SqliteDialect, PostgresDialect } from 'kysely';
3
- import Database from 'better-sqlite3';
4
- import { PartyLevelRight, UserLevelRight } from '@canton-network/core-wallet-store';
5
- import pg from 'pg';
6
- import { Umzug } from 'umzug';
7
- import { Command } from 'commander';
8
- import { pino } from 'pino';
9
-
10
- var __defProp = Object.defineProperty;
11
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
13
- var toIdp = (table) => {
14
- switch (table.type) {
15
- case "oauth": {
16
- if (!table.configUrl) {
17
- throw new Error(`Missing configUrl for oauth IdP: ${table.id}`);
18
- }
19
- return {
20
- id: table.id,
21
- type: table.type,
22
- issuer: table.issuer,
23
- configUrl: table.configUrl
24
- };
25
- }
26
- case "self_signed":
27
- return {
28
- id: table.id,
29
- type: table.type,
30
- issuer: table.issuer
31
- };
32
- }
1
+ import { assertConnected, authSchema } from "@canton-network/core-wallet-auth";
2
+ import { CamelCasePlugin, Kysely, PostgresDialect, SqliteDialect, sql } from "kysely";
3
+ import Database from "better-sqlite3";
4
+ import { PartyLevelRight, UserLevelRight } from "@canton-network/core-wallet-store";
5
+ import pg from "pg";
6
+ import { Umzug } from "umzug";
7
+ import { Command } from "commander";
8
+ import { pino } from "pino";
9
+ //#region src/schema.ts
10
+ const toIdp = (table) => {
11
+ switch (table.type) {
12
+ case "oauth":
13
+ if (!table.configUrl) throw new Error(`Missing configUrl for oauth IdP: ${table.id}`);
14
+ return {
15
+ id: table.id,
16
+ type: table.type,
17
+ issuer: table.issuer,
18
+ configUrl: table.configUrl
19
+ };
20
+ case "self_signed": return {
21
+ id: table.id,
22
+ type: table.type,
23
+ issuer: table.issuer
24
+ };
25
+ }
33
26
  };
34
- var fromIdp = (idp) => {
35
- switch (idp.type) {
36
- case "oauth":
37
- return {
38
- id: idp.id,
39
- type: idp.type,
40
- issuer: idp.issuer,
41
- configUrl: idp.configUrl
42
- };
43
- case "self_signed":
44
- return {
45
- id: idp.id,
46
- type: idp.type,
47
- issuer: idp.issuer,
48
- configUrl: void 0
49
- };
50
- }
27
+ const fromIdp = (idp) => {
28
+ switch (idp.type) {
29
+ case "oauth": return {
30
+ id: idp.id,
31
+ type: idp.type,
32
+ issuer: idp.issuer,
33
+ configUrl: idp.configUrl
34
+ };
35
+ case "self_signed": return {
36
+ id: idp.id,
37
+ type: idp.type,
38
+ issuer: idp.issuer,
39
+ configUrl: void 0
40
+ };
41
+ }
51
42
  };
52
- var toNetwork = (table) => {
53
- return {
54
- name: table.name,
55
- id: table.id,
56
- synchronizerId: table.synchronizerId ?? void 0,
57
- identityProviderId: table.identityProviderId,
58
- description: table.description,
59
- ledgerApi: {
60
- baseUrl: table.ledgerApiBaseUrl
61
- },
62
- auth: authSchema.parse(
63
- typeof table.auth === "string" ? JSON.parse(table.auth) : table.auth
64
- ),
65
- adminAuth: table.adminAuth ? authSchema.parse(
66
- typeof table.adminAuth === "string" ? JSON.parse(table.adminAuth) : table.adminAuth
67
- ) : void 0,
68
- serviceAccountAuth: table.serviceAccountAuth ? authSchema.parse(
69
- typeof table.serviceAccountAuth === "string" ? JSON.parse(table.serviceAccountAuth) : table.serviceAccountAuth
70
- ) : void 0
71
- };
43
+ const toNetwork = (table) => {
44
+ return {
45
+ name: table.name,
46
+ id: table.id,
47
+ synchronizerId: table.synchronizerId ?? void 0,
48
+ identityProviderId: table.identityProviderId,
49
+ description: table.description,
50
+ ledgerApi: { baseUrl: table.ledgerApiBaseUrl },
51
+ auth: authSchema.parse(typeof table.auth === "string" ? JSON.parse(table.auth) : table.auth),
52
+ adminAuth: table.adminAuth ? authSchema.parse(typeof table.adminAuth === "string" ? JSON.parse(table.adminAuth) : table.adminAuth) : void 0,
53
+ serviceAccountAuth: table.serviceAccountAuth ? authSchema.parse(typeof table.serviceAccountAuth === "string" ? JSON.parse(table.serviceAccountAuth) : table.serviceAccountAuth) : void 0
54
+ };
72
55
  };
73
- var fromNetwork = (network, userId) => {
74
- return {
75
- name: network.name,
76
- id: network.id,
77
- synchronizerId: network.synchronizerId ?? null,
78
- description: network.description,
79
- ledgerApiBaseUrl: network.ledgerApi.baseUrl,
80
- userId,
81
- identityProviderId: network.identityProviderId,
82
- auth: JSON.stringify(network.auth),
83
- adminAuth: network.adminAuth ? JSON.stringify(network.adminAuth) : void 0,
84
- serviceAccountAuth: network.serviceAccountAuth ? JSON.stringify(network.serviceAccountAuth) : void 0
85
- };
56
+ const fromNetwork = (network, userId) => {
57
+ return {
58
+ name: network.name,
59
+ id: network.id,
60
+ synchronizerId: network.synchronizerId ?? null,
61
+ description: network.description,
62
+ ledgerApiBaseUrl: network.ledgerApi.baseUrl,
63
+ userId,
64
+ identityProviderId: network.identityProviderId,
65
+ auth: JSON.stringify(network.auth),
66
+ adminAuth: network.adminAuth ? JSON.stringify(network.adminAuth) : void 0,
67
+ serviceAccountAuth: network.serviceAccountAuth ? JSON.stringify(network.serviceAccountAuth) : void 0
68
+ };
86
69
  };
87
- var toSession = (table) => {
88
- return {
89
- id: table.id,
90
- network: table.network,
91
- accessToken: table.accessToken,
92
- userId: table.userId
93
- };
70
+ const toSession = (table) => {
71
+ return {
72
+ id: table.id,
73
+ network: table.network,
74
+ origin: table.origin,
75
+ accessToken: table.accessToken,
76
+ userId: table.userId
77
+ };
94
78
  };
95
- var fromWallet = (wallet, userId) => {
96
- const { externalTxId, topologyTransactions, rights, ...rest } = wallet;
97
- return {
98
- ...rest,
99
- primary: wallet.primary ? 1 : 0,
100
- userId,
101
- disabled: wallet.disabled !== void 0 && wallet.disabled ? 1 : 0,
102
- reason: wallet.reason ?? null,
103
- externalTxId: externalTxId && externalTxId !== "" ? externalTxId : null,
104
- topologyTransactions: topologyTransactions && topologyTransactions !== "" ? topologyTransactions : null
105
- };
79
+ const fromWallet = (wallet, userId) => {
80
+ const { externalTxId, topologyTransactions, rights, ...rest } = wallet;
81
+ return {
82
+ ...rest,
83
+ primary: wallet.primary ? 1 : 0,
84
+ userId,
85
+ disabled: wallet.disabled !== void 0 && wallet.disabled ? 1 : 0,
86
+ reason: wallet.reason ?? null,
87
+ externalTxId: externalTxId && externalTxId !== "" ? externalTxId : null,
88
+ topologyTransactions: topologyTransactions && topologyTransactions !== "" ? topologyTransactions : null
89
+ };
106
90
  };
107
- var toWalletUpdateProperties = (params) => {
108
- const {
109
- status,
110
- externalTxId,
111
- topologyTransactions,
112
- disabled,
113
- reason,
114
- primary
115
- } = params;
116
- return {
117
- ...status !== void 0 && { status },
118
- ...externalTxId !== void 0 && { externalTxId },
119
- ...topologyTransactions !== void 0 && { topologyTransactions },
120
- ...primary !== void 0 && { primary: primary ? 1 : 0 },
121
- ...disabled !== void 0 && { disabled: disabled ? 1 : 0 },
122
- ...reason !== void 0 && { reason }
123
- };
91
+ const toWalletUpdateProperties = (params) => {
92
+ const { status, externalTxId, topologyTransactions, disabled, reason, primary } = params;
93
+ return {
94
+ ...status !== void 0 && { status },
95
+ ...externalTxId !== void 0 && { externalTxId },
96
+ ...topologyTransactions !== void 0 && { topologyTransactions },
97
+ ...primary !== void 0 && { primary: primary ? 1 : 0 },
98
+ ...disabled !== void 0 && { disabled: disabled ? 1 : 0 },
99
+ ...reason !== void 0 && { reason }
100
+ };
124
101
  };
125
- var toWalletStatus = (status) => {
126
- if (status === "allocated") return "allocated";
127
- if (status === "removed") return "removed";
128
- return "initialized";
102
+ const toWalletStatus = (status) => {
103
+ if (status === "allocated") return "allocated";
104
+ if (status === "removed") return "removed";
105
+ return "initialized";
129
106
  };
130
- var toWallet = (table) => {
131
- return {
132
- primary: Boolean(table.primary),
133
- status: toWalletStatus(table.status),
134
- partyId: table.partyId,
135
- hint: table.hint,
136
- publicKey: table.publicKey,
137
- namespace: table.namespace,
138
- networkId: table.networkId,
139
- signingProviderId: table.signingProviderId,
140
- disabled: table.disabled === 1,
141
- ...table.externalTxId !== null && {
142
- externalTxId: table.externalTxId
143
- },
144
- ...table.topologyTransactions !== null && {
145
- topologyTransactions: table.topologyTransactions
146
- },
147
- ...table.reason !== null && {
148
- reason: table.reason
149
- },
150
- rights: []
151
- };
107
+ const toWallet = (table) => {
108
+ return {
109
+ primary: Boolean(table.primary),
110
+ status: toWalletStatus(table.status),
111
+ partyId: table.partyId,
112
+ hint: table.hint,
113
+ publicKey: table.publicKey,
114
+ namespace: table.namespace,
115
+ networkId: table.networkId,
116
+ signingProviderId: table.signingProviderId,
117
+ disabled: table.disabled === 1,
118
+ ...table.externalTxId !== null && { externalTxId: table.externalTxId },
119
+ ...table.topologyTransactions !== null && { topologyTransactions: table.topologyTransactions },
120
+ ...table.reason !== null && { reason: table.reason },
121
+ rights: []
122
+ };
152
123
  };
153
- var fromPartyRight = (right) => {
154
- if (Object.values(PartyLevelRight).includes(right)) {
155
- return right;
156
- }
157
- return void 0;
124
+ const fromPartyRight = (right) => {
125
+ if (Object.values(PartyLevelRight).includes(right)) return right;
158
126
  };
159
- var fromUserRight = (right) => {
160
- if (Object.values(UserLevelRight).includes(right)) {
161
- return right;
162
- }
163
- return void 0;
127
+ const fromUserRight = (right) => {
128
+ if (Object.values(UserLevelRight).includes(right)) return right;
164
129
  };
165
- var fromTransaction = (transaction, userId, networkId) => {
166
- return {
167
- ...transaction,
168
- networkId,
169
- payload: transaction.payload ? JSON.stringify(transaction.payload) : void 0,
170
- origin: transaction.origin || null,
171
- userId,
172
- createdAt: transaction.createdAt?.toISOString() || null,
173
- signedAt: transaction.signedAt?.toISOString() || null,
174
- externalTxId: transaction.externalTxId ?? null
175
- };
130
+ const fromTransaction = (transaction, userId, networkId) => {
131
+ return {
132
+ ...transaction,
133
+ networkId,
134
+ payload: transaction.payload ? JSON.stringify(transaction.payload) : void 0,
135
+ origin: transaction.origin || null,
136
+ userId,
137
+ createdAt: transaction.createdAt?.toISOString() || null,
138
+ signedAt: transaction.signedAt?.toISOString() || null,
139
+ externalTxId: transaction.externalTxId ?? null
140
+ };
176
141
  };
177
- var toTransaction = (table) => {
178
- const result = {
179
- id: table.id,
180
- commandId: table.commandId,
181
- status: table.status,
182
- preparedTransaction: table.preparedTransaction,
183
- preparedTransactionHash: table.preparedTransactionHash,
184
- payload: table.payload ? JSON.parse(table.payload) : void 0,
185
- origin: table.origin || null,
186
- userId: table.userId,
187
- networkId: table.networkId
188
- };
189
- if (table.createdAt) {
190
- result.createdAt = new Date(table.createdAt);
191
- }
192
- if (table.signedAt) {
193
- result.signedAt = new Date(table.signedAt);
194
- }
195
- if (table.externalTxId) {
196
- result.externalTxId = table.externalTxId;
197
- }
198
- return result;
142
+ const toTransaction = (table) => {
143
+ const result = {
144
+ id: table.id,
145
+ commandId: table.commandId,
146
+ status: table.status,
147
+ preparedTransaction: table.preparedTransaction,
148
+ preparedTransactionHash: table.preparedTransactionHash,
149
+ payload: table.payload ? JSON.parse(table.payload) : void 0,
150
+ origin: table.origin || null,
151
+ userId: table.userId,
152
+ networkId: table.networkId
153
+ };
154
+ if (table.createdAt) result.createdAt = new Date(table.createdAt);
155
+ if (table.signedAt) result.signedAt = new Date(table.signedAt);
156
+ if (table.externalTxId) result.externalTxId = table.externalTxId;
157
+ return result;
199
158
  };
200
- var fromMessageRaw = (message, userId, networkId) => {
201
- if (message.userId !== userId) {
202
- throw new Error(
203
- `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`
204
- );
205
- }
206
- return {
207
- id: message.id,
208
- status: message.status,
209
- userId: message.userId,
210
- partyId: message.partyId,
211
- publicKey: message.publicKey,
212
- message: message.message,
213
- origin: message.origin || null,
214
- networkId,
215
- createdAt: message.createdAt.toISOString(),
216
- signedAt: message.signedAt?.toISOString() || null,
217
- signature: message.signature ?? null
218
- };
159
+ const fromMessageRaw = (message, userId, networkId) => {
160
+ if (message.userId !== userId) throw new Error(`MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`);
161
+ return {
162
+ id: message.id,
163
+ status: message.status,
164
+ userId: message.userId,
165
+ partyId: message.partyId,
166
+ publicKey: message.publicKey,
167
+ message: message.message,
168
+ origin: message.origin || null,
169
+ networkId,
170
+ createdAt: message.createdAt.toISOString(),
171
+ signedAt: message.signedAt?.toISOString() || null,
172
+ signature: message.signature ?? null
173
+ };
219
174
  };
220
- var toMessageRaw = (table) => {
221
- const result = {
222
- id: table.id,
223
- status: table.status,
224
- userId: table.userId,
225
- partyId: table.partyId,
226
- publicKey: table.publicKey,
227
- message: table.message,
228
- origin: table.origin || null,
229
- createdAt: new Date(table.createdAt)
230
- };
231
- if (table.signedAt) {
232
- result.signedAt = new Date(table.signedAt);
233
- }
234
- if (table.signature) {
235
- result.signature = table.signature;
236
- }
237
- return result;
175
+ const toMessageRaw = (table) => {
176
+ const result = {
177
+ id: table.id,
178
+ status: table.status,
179
+ userId: table.userId,
180
+ partyId: table.partyId,
181
+ publicKey: table.publicKey,
182
+ message: table.message,
183
+ origin: table.origin || null,
184
+ createdAt: new Date(table.createdAt)
185
+ };
186
+ if (table.signedAt) result.signedAt = new Date(table.signedAt);
187
+ if (table.signature) result.signature = table.signature;
188
+ return result;
238
189
  };
239
- var fromApiKey = (table) => {
240
- return {
241
- id: table.id,
242
- digest: table.digest,
243
- name: table.name,
244
- userId: table.userId,
245
- email: table.email,
246
- networkId: table.networkId,
247
- createdAt: new Date(table.createdAt),
248
- lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : void 0
249
- };
190
+ const fromApiKey = (table) => {
191
+ return {
192
+ id: table.id,
193
+ digest: table.digest,
194
+ name: table.name,
195
+ userId: table.userId,
196
+ email: table.email,
197
+ networkId: table.networkId,
198
+ createdAt: new Date(table.createdAt),
199
+ lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : void 0
200
+ };
250
201
  };
251
- var toApiKey = (apiKey) => {
252
- return {
253
- id: apiKey.id,
254
- digest: apiKey.digest,
255
- name: apiKey.name,
256
- userId: apiKey.userId,
257
- email: apiKey.email,
258
- networkId: apiKey.networkId,
259
- createdAt: apiKey.createdAt.toISOString(),
260
- lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null
261
- };
202
+ const toApiKey = (apiKey) => {
203
+ return {
204
+ id: apiKey.id,
205
+ digest: apiKey.digest,
206
+ name: apiKey.name,
207
+ userId: apiKey.userId,
208
+ email: apiKey.email,
209
+ networkId: apiKey.networkId,
210
+ createdAt: apiKey.createdAt.toISOString(),
211
+ lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null
212
+ };
262
213
  };
263
- var StoreSql = class _StoreSql {
264
- constructor(db, logger2, authContext) {
265
- this.db = db;
266
- this.logger = logger2;
267
- __publicField(this, "authContext");
268
- this.logger = logger2.child({ component: "StoreSql" });
269
- this.authContext = authContext;
270
- }
271
- withAuthContext(context) {
272
- return new _StoreSql(this.db, this.logger, context);
273
- }
274
- assertConnected() {
275
- return assertConnected(this.authContext).userId;
276
- }
277
- // Wallet methods
278
- async getAllWallets(filter = {}) {
279
- const userId = this.assertConnected();
280
- const { networkIds, signingProviderIds } = filter;
281
- const networkIdSet = networkIds ? new Set(networkIds) : null;
282
- const signingProviderIdSet = signingProviderIds ? new Set(signingProviderIds) : null;
283
- const wallets = await this.db.selectFrom("wallets").selectAll().where("userId", "=", userId).execute();
284
- const userPartyRights = await this.db.selectFrom("userPartyRights").selectAll().where("userId", "=", userId).execute();
285
- const rightsByWallet = /* @__PURE__ */ new Map();
286
- for (const row of userPartyRights) {
287
- const right = fromPartyRight(row.right);
288
- if (!right) continue;
289
- const key = `${row.partyId}:${row.networkId}`;
290
- const existing = rightsByWallet.get(key) ?? [];
291
- rightsByWallet.set(key, [...existing, right]);
292
- }
293
- return wallets.filter((wallet) => {
294
- const matchedNetworkIds = networkIdSet ? networkIdSet.has(wallet.networkId) : true;
295
- const matchedSigningProviderIds = signingProviderIdSet ? signingProviderIdSet.has(wallet.signingProviderId) : true;
296
- return matchedNetworkIds && matchedSigningProviderIds;
297
- }).map((table) => {
298
- const wallet = toWallet(table);
299
- const rights = rightsByWallet.get(
300
- `${table.partyId}:${table.networkId}`
301
- );
302
- return {
303
- ...wallet,
304
- rights: rights ?? []
305
- };
306
- });
307
- }
308
- async getWallets(filter = {}) {
309
- const network = await this.getCurrentNetwork();
310
- return this.getAllWallets({
311
- ...filter,
312
- networkIds: [network.id]
313
- });
314
- }
315
- async getPrimaryWallet() {
316
- const wallets = await this.getWallets();
317
- return wallets.find((w) => w.primary === true);
318
- }
319
- async setPrimaryWallet(partyId) {
320
- const network = await this.getCurrentNetwork();
321
- const userId = this.assertConnected();
322
- const wallets = await this.getWallets();
323
- if (!wallets.some((w) => w.partyId === partyId)) {
324
- throw new Error(
325
- `Wallet with partyId "${partyId}" not found in network "${network.id}"`
326
- );
327
- }
328
- const primary = wallets.find((w) => w.primary === true);
329
- await this.db.transaction().execute(async (trx) => {
330
- if (primary) {
331
- await trx.updateTable("wallets").set({ primary: 0 }).where(
332
- (eb) => eb.and([
333
- eb("partyId", "=", primary.partyId),
334
- eb("networkId", "=", network.id),
335
- eb("userId", "=", userId)
336
- ])
337
- ).execute();
338
- }
339
- await trx.updateTable("wallets").set({ primary: 1 }).where(
340
- (eb) => eb.and([
341
- eb("partyId", "=", partyId),
342
- eb("networkId", "=", network.id),
343
- eb("userId", "=", userId)
344
- ])
345
- ).execute();
346
- });
347
- }
348
- async addWallet(wallet) {
349
- this.logger.info("Adding wallet");
350
- const userId = this.assertConnected();
351
- const wallets = await this.getWallets();
352
- if (wallets.some(
353
- (w) => w.partyId === wallet.partyId && w.networkId === wallet.networkId
354
- )) {
355
- throw new Error(
356
- `Wallet with partyId "${wallet.partyId}" networkId "${wallet.networkId}" userId "${userId}" already exists`
357
- );
358
- }
359
- if (!wallet.disabled && wallet.status === "allocated" && !wallets.some((wallet2) => wallet2.primary)) {
360
- wallet.primary = true;
361
- }
362
- await this.db.transaction().execute(async (trx) => {
363
- if (wallet.primary) {
364
- await trx.updateTable("wallets").set({ primary: 0 }).where(
365
- (eb) => eb.and([
366
- eb("primary", "=", 1),
367
- eb("networkId", "=", wallet.networkId),
368
- eb("userId", "=", userId)
369
- ])
370
- ).execute();
371
- }
372
- await trx.insertInto("wallets").values(fromWallet(wallet, userId)).execute();
373
- if (wallet.rights && wallet.rights.length > 0) {
374
- await trx.insertInto("userPartyRights").values(
375
- wallet.rights.map((right) => ({
376
- userId,
377
- networkId: wallet.networkId,
378
- partyId: wallet.partyId,
379
- right
380
- }))
381
- ).execute();
382
- }
383
- });
384
- }
385
- async updateWallet(params) {
386
- const { partyId, networkId, rights } = params;
387
- this.logger.info("Updating wallet");
388
- const userId = this.assertConnected();
389
- const updates = toWalletUpdateProperties(params);
390
- const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
391
- if (Object.keys(updates).length === 0 && rights === void 0) return;
392
- await this.db.transaction().execute(async (trx) => {
393
- if (Object.keys(updates).length > 0) {
394
- await trx.updateTable("wallets").set(updates).where(
395
- (eb) => eb.and([
396
- eb("partyId", "=", partyId),
397
- eb("networkId", "=", targetNetworkId),
398
- eb("userId", "=", userId)
399
- ])
400
- ).execute();
401
- }
402
- if (rights !== void 0) {
403
- await trx.deleteFrom("userPartyRights").where(
404
- (eb) => eb.and([
405
- eb("partyId", "=", partyId),
406
- eb("networkId", "=", targetNetworkId),
407
- eb("userId", "=", userId)
408
- ])
409
- ).execute();
410
- if (rights.length > 0) {
411
- await trx.insertInto("userPartyRights").values(
412
- rights.map((right) => ({
413
- userId,
414
- networkId: targetNetworkId,
415
- partyId,
416
- right
417
- }))
418
- ).execute();
419
- }
420
- }
421
- });
422
- }
423
- async removeWallet(partyId) {
424
- this.logger.info("Removing wallet");
425
- const userId = this.assertConnected();
426
- const network = await this.getCurrentNetwork();
427
- await this.db.transaction().execute(async (trx) => {
428
- await trx.deleteFrom("wallets").where(
429
- (eb) => eb.and([
430
- eb("partyId", "=", partyId),
431
- eb("networkId", "=", network.id),
432
- eb("userId", "=", userId)
433
- ])
434
- ).execute();
435
- });
436
- }
437
- async getUserRights(networkId) {
438
- const userId = this.assertConnected();
439
- const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
440
- const rows = await this.db.selectFrom("userRights").selectAll().where(
441
- (eb) => eb.and([
442
- eb("userId", "=", userId),
443
- eb("networkId", "=", targetNetworkId)
444
- ])
445
- ).execute();
446
- return rows.map((row) => fromUserRight(row.right)).filter((right) => right !== void 0);
447
- }
448
- async setUserRights(networkId, rights) {
449
- const userId = this.assertConnected();
450
- await this.db.transaction().execute(async (trx) => {
451
- await trx.deleteFrom("userRights").where(
452
- (eb) => eb.and([
453
- eb("userId", "=", userId),
454
- eb("networkId", "=", networkId)
455
- ])
456
- ).execute();
457
- if (rights.length > 0) {
458
- await trx.insertInto("userRights").values(
459
- rights.map((right) => ({
460
- userId,
461
- networkId,
462
- right
463
- }))
464
- ).execute();
465
- }
466
- });
467
- }
468
- // Session methods
469
- async getSession() {
470
- const userId = this.assertConnected();
471
- const row = await this.db.selectFrom("sessions").selectAll().where("userId", "=", userId).executeTakeFirst();
472
- return row ? toSession(row) : void 0;
473
- }
474
- async setSession(session) {
475
- const userId = this.assertConnected();
476
- await this.db.transaction().execute(async (trx) => {
477
- const deleted = await trx.deleteFrom("sessions").where("userId", "=", userId).execute();
478
- this.logger.debug(deleted, "Deleted old session");
479
- const inserted = await trx.insertInto("sessions").values({ ...session, userId }).execute();
480
- this.logger.debug(inserted, "Inserted new session");
481
- });
482
- }
483
- async removeSession() {
484
- const userId = this.assertConnected();
485
- await this.db.deleteFrom("sessions").where("userId", "=", userId).execute();
486
- }
487
- /**
488
- * Lists all pending transactions across all users.
489
- */
490
- async listAllPendingTransactions() {
491
- const rows = await this.db.selectFrom("transactions").selectAll().where("status", "=", "pending").execute();
492
- return rows.map((row) => toTransaction(row));
493
- }
494
- // IDP methods
495
- async getIdp(idpId) {
496
- const idps = await this.listIdps();
497
- if (!idps) throw new Error("No IDPs available");
498
- const idp = idps.find((n) => n.id === idpId);
499
- if (!idp) throw new Error(`IDP "${idpId}" not found`);
500
- return idp;
501
- }
502
- async listIdps() {
503
- const query = this.db.selectFrom("idps").selectAll();
504
- const idps = await query.execute();
505
- return idps.map((table) => toIdp(table));
506
- }
507
- async updateIdp(idp) {
508
- await this.db.transaction().execute(async (trx) => {
509
- const idpEntry = fromIdp(idp);
510
- this.logger.info(idpEntry, "Updating idp table");
511
- await trx.updateTable("idps").set(idpEntry).where("id", "=", idp.id).execute();
512
- });
513
- }
514
- async addIdp(idp) {
515
- await this.db.transaction().execute(async (trx) => {
516
- const idpAlreadyExists = await trx.selectFrom("idps").selectAll().where("id", "=", idp.id).executeTakeFirst();
517
- if (idpAlreadyExists) {
518
- throw new Error(`IDP ${idp.id} already exists`);
519
- } else {
520
- await trx.insertInto("idps").values(fromIdp(idp)).execute();
521
- }
522
- });
523
- }
524
- async removeIdp(idpId) {
525
- const networks = await this.listNetworks();
526
- if (networks.some((n) => n.identityProviderId === idpId)) {
527
- throw new Error(
528
- `Cannot delete IDP ${idpId} as it is in use by existing networks`
529
- );
530
- }
531
- await this.db.transaction().execute(async (trx) => {
532
- const idp = await trx.selectFrom("idps").selectAll().where("id", "=", idpId).executeTakeFirst();
533
- if (!idp) {
534
- throw new Error(`IDP ${idpId} does not exists`);
535
- }
536
- await trx.deleteFrom("idps").where("id", "=", idpId).execute();
537
- });
538
- }
539
- // Network methods
540
- async getNetwork(networkId) {
541
- const networks = await this.listNetworks();
542
- if (!networks) throw new Error("No networks available");
543
- const network = networks.find((n) => n.id === networkId);
544
- if (!network) throw new Error(`Network "${networkId}" not found`);
545
- return network;
546
- }
547
- async getCurrentNetwork() {
548
- const session = await this.getSession();
549
- if (!session) {
550
- throw new Error("No session found");
551
- }
552
- const networkId = session.network;
553
- if (!networkId) {
554
- throw new Error("No current network set in session");
555
- }
556
- const networks = await this.listNetworks();
557
- const network = networks.find((n) => n.id === networkId);
558
- if (!network) {
559
- throw new Error(`Network "${networkId}" not found`);
560
- }
561
- return network;
562
- }
563
- async listNetworks() {
564
- let query = this.db.selectFrom("networks").selectAll();
565
- if (this.authContext) {
566
- const userId = this.assertConnected();
567
- query = query.where(
568
- (eb) => eb.or([
569
- eb("userId", "is", null),
570
- // Global networks
571
- eb("userId", "=", userId)
572
- // User-specific networks
573
- ])
574
- );
575
- } else {
576
- query = query.where("userId", "is", null);
577
- }
578
- const networks = await query.execute();
579
- return networks.map((table) => toNetwork(table));
580
- }
581
- async updateNetwork(network) {
582
- this.assertConnected();
583
- await this.db.transaction().execute(async (trx) => {
584
- const networkEntry = fromNetwork(network, void 0);
585
- this.logger.info(networkEntry, "Updating network table");
586
- await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
587
- });
588
- }
589
- async addNetwork(network) {
590
- const userId = this.authContext?.userId;
591
- const idps = await this.listIdps();
592
- const networkIdp = idps.find(
593
- (idp) => idp.id === network.identityProviderId
594
- );
595
- if (!networkIdp) {
596
- throw new Error(
597
- `Identity provider "${network.identityProviderId}" not found`
598
- );
599
- }
600
- await this.db.transaction().execute(async (trx) => {
601
- const networkAlreadyExists = await trx.selectFrom("networks").selectAll().where("id", "=", network.id).executeTakeFirst();
602
- if (networkAlreadyExists) {
603
- throw new Error(`Network ${network.id} already exists`);
604
- } else {
605
- await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
606
- }
607
- });
608
- }
609
- async removeNetwork(networkId) {
610
- const userId = this.assertConnected();
611
- await this.db.transaction().execute(async (trx) => {
612
- const network = await trx.selectFrom("networks").selectAll().where("id", "=", networkId).executeTakeFirst();
613
- if (!network) {
614
- throw new Error(`Network ${networkId} does not exists`);
615
- }
616
- if (network.userId !== userId) {
617
- throw new Error(
618
- `Network ${networkId} is not owned by user ${userId}`
619
- );
620
- }
621
- await trx.deleteFrom("networks").where("id", "=", networkId).execute();
622
- });
623
- }
624
- mergeTransactionStatusUpdate(existing, status, updates = {}) {
625
- const payload = updates.payload ?? existing.payload;
626
- const signedAt = updates.signedAt ?? existing.signedAt;
627
- const externalTxId = updates.externalTxId ?? existing.externalTxId;
628
- return {
629
- id: existing.id,
630
- commandId: existing.commandId,
631
- status,
632
- preparedTransaction: existing.preparedTransaction,
633
- preparedTransactionHash: existing.preparedTransactionHash,
634
- origin: existing.origin,
635
- ...payload !== void 0 && { payload },
636
- ...existing.createdAt !== void 0 && {
637
- createdAt: existing.createdAt
638
- },
639
- ...signedAt !== void 0 && { signedAt },
640
- ...externalTxId !== void 0 && { externalTxId }
641
- };
642
- }
643
- // Transaction methods
644
- async setTransaction(transaction) {
645
- const userId = this.assertConnected();
646
- const network = await this.getCurrentNetwork();
647
- await this.db.insertInto("transactions").values(fromTransaction(transaction, userId, network.id)).execute();
648
- }
649
- async setTransactionSigned(transactionId, signedAt, externalTxId) {
650
- await this.setTransactionStatus(transactionId, "signed", {
651
- signedAt,
652
- ...externalTxId !== void 0 && { externalTxId }
653
- });
654
- }
655
- async setTransactionStatus(transactionId, status, updates = {}) {
656
- const userId = this.assertConnected();
657
- const network = await this.getCurrentNetwork();
658
- const existing = await this.getTransaction(transactionId);
659
- if (!existing) {
660
- throw new Error(`Transaction not found with id: ${transactionId}`);
661
- }
662
- const updated = this.mergeTransactionStatusUpdate(
663
- existing,
664
- status,
665
- updates
666
- );
667
- await this.db.updateTable("transactions").set(fromTransaction(updated, userId, network.id)).where(
668
- (eb) => eb.and([
669
- eb("id", "=", transactionId),
670
- eb("userId", "=", userId),
671
- eb("networkId", "=", network.id)
672
- ])
673
- ).execute();
674
- }
675
- async getTransaction(transactionId) {
676
- const userId = this.assertConnected();
677
- const network = await this.getCurrentNetwork();
678
- const transaction = await this.db.selectFrom("transactions").selectAll().where(
679
- (eb) => eb.and([
680
- eb("id", "=", transactionId),
681
- eb("userId", "=", userId),
682
- eb("networkId", "=", network.id)
683
- ])
684
- ).executeTakeFirst();
685
- return transaction ? toTransaction(transaction) : void 0;
686
- }
687
- async getLatestTransactionByCommandId(commandId) {
688
- const userId = this.assertConnected();
689
- const network = await this.getCurrentNetwork();
690
- const transaction = await this.db.selectFrom("transactions").selectAll().where(
691
- (eb) => eb.and([
692
- eb("commandId", "=", commandId),
693
- eb("userId", "=", userId),
694
- eb("networkId", "=", network.id)
695
- ])
696
- ).orderBy("createdAt", "desc").orderBy("id", "desc").executeTakeFirst();
697
- return transaction ? toTransaction(transaction) : void 0;
698
- }
699
- async listTransactions() {
700
- const userId = this.assertConnected();
701
- const network = await this.getCurrentNetwork();
702
- const transactions = await this.db.selectFrom("transactions").selectAll().where(
703
- (eb) => eb.and([
704
- eb("userId", "=", userId),
705
- eb("networkId", "=", network.id)
706
- ])
707
- ).orderBy("createdAt", "desc").execute();
708
- return transactions.map((table) => toTransaction(table));
709
- }
710
- async removeTransaction(transactionId) {
711
- const userId = this.assertConnected();
712
- const network = await this.getCurrentNetwork();
713
- await this.db.deleteFrom("transactions").where(
714
- (eb) => eb.and([
715
- eb("id", "=", transactionId),
716
- eb("userId", "=", userId),
717
- eb("networkId", "=", network.id)
718
- ])
719
- ).execute();
720
- }
721
- mergeMessageRawStatusUpdate(existing, status, updates = {}) {
722
- const signedAt = updates.signedAt ?? existing.signedAt;
723
- const signature = updates.signature ?? existing.signature;
724
- return {
725
- ...existing,
726
- status,
727
- ...signedAt !== void 0 && { signedAt },
728
- ...signature !== void 0 && { signature }
729
- };
730
- }
731
- // Message signing request methods
732
- async setMessageRaw(message) {
733
- const userId = this.assertConnected();
734
- if (message.userId !== userId) {
735
- throw new Error(
736
- `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`
737
- );
738
- }
739
- const network = await this.getCurrentNetwork();
740
- await this.db.insertInto("messagesRaw").values(fromMessageRaw(message, userId, network.id)).execute();
741
- }
742
- async setMessageRawStatus(messageId, status, updates = {}) {
743
- const userId = this.assertConnected();
744
- const network = await this.getCurrentNetwork();
745
- const existing = await this.getMessageRaw(messageId);
746
- if (!existing) {
747
- throw new Error(`MessageRaw not found with id: ${messageId}`);
748
- }
749
- const updated = this.mergeMessageRawStatusUpdate(
750
- existing,
751
- status,
752
- updates
753
- );
754
- await this.db.updateTable("messagesRaw").set(fromMessageRaw(updated, userId, network.id)).where(
755
- (eb) => eb.and([
756
- eb("id", "=", messageId),
757
- eb("userId", "=", userId),
758
- eb("networkId", "=", network.id)
759
- ])
760
- ).execute();
761
- }
762
- async getMessageRaw(messageId) {
763
- const userId = this.assertConnected();
764
- const network = await this.getCurrentNetwork();
765
- const message = await this.db.selectFrom("messagesRaw").selectAll().where(
766
- (eb) => eb.and([
767
- eb("id", "=", messageId),
768
- eb("userId", "=", userId),
769
- eb("networkId", "=", network.id)
770
- ])
771
- ).executeTakeFirst();
772
- return message ? toMessageRaw(message) : void 0;
773
- }
774
- async listMessageRaws() {
775
- const userId = this.assertConnected();
776
- const network = await this.getCurrentNetwork();
777
- const messages = await this.db.selectFrom("messagesRaw").selectAll().where(
778
- (eb) => eb.and([
779
- eb("userId", "=", userId),
780
- eb("networkId", "=", network.id)
781
- ])
782
- ).orderBy("createdAt", "desc").orderBy("id", "desc").execute();
783
- return messages.map((m) => toMessageRaw(m));
784
- }
785
- async removeMessageRaw(messageId) {
786
- const userId = this.assertConnected();
787
- const network = await this.getCurrentNetwork();
788
- await this.db.deleteFrom("messagesRaw").where(
789
- (eb) => eb.and([
790
- eb("id", "=", messageId),
791
- eb("userId", "=", userId),
792
- eb("networkId", "=", network.id)
793
- ])
794
- ).execute();
795
- }
796
- // API keys
797
- async addApiKey(apiKey) {
798
- const userId = this.assertConnected();
799
- if (apiKey.userId !== userId) {
800
- throw new Error(
801
- `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`
802
- );
803
- }
804
- const network = await this.getCurrentNetwork();
805
- if (apiKey.networkId !== network.id) {
806
- throw new Error(
807
- `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`
808
- );
809
- }
810
- await this.db.insertInto("apiKeys").values(toApiKey(apiKey)).execute();
811
- }
812
- async listApiKeys() {
813
- const query = this.db.selectFrom("apiKeys").selectAll().orderBy("createdAt", "desc");
814
- const userId = this.assertConnected();
815
- const network = await this.getCurrentNetwork();
816
- const apiKeys = await query.where(
817
- (eb) => eb.and([
818
- eb("userId", "=", userId),
819
- eb("networkId", "=", network.id)
820
- ])
821
- ).execute();
822
- return apiKeys.map(fromApiKey);
823
- }
824
- async getApiKey(digest) {
825
- const apiKey = await this.db.selectFrom("apiKeys").selectAll().where((eb) => eb("digest", "=", digest)).executeTakeFirst();
826
- return apiKey ? fromApiKey(apiKey) : void 0;
827
- }
828
- async removeApiKey(apiKeyId) {
829
- const userId = this.assertConnected();
830
- const network = await this.getCurrentNetwork();
831
- await this.db.deleteFrom("apiKeys").where(
832
- (eb) => eb.and([
833
- eb("id", "=", apiKeyId),
834
- eb("userId", "=", userId),
835
- eb("networkId", "=", network.id)
836
- ])
837
- ).execute();
838
- }
214
+ //#endregion
215
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
216
+ function _typeof(o) {
217
+ "@babel/helpers - typeof";
218
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
219
+ return typeof o;
220
+ } : function(o) {
221
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
222
+ }, _typeof(o);
223
+ }
224
+ //#endregion
225
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
226
+ function toPrimitive(t, r) {
227
+ if ("object" != _typeof(t) || !t) return t;
228
+ var e = t[Symbol.toPrimitive];
229
+ if (void 0 !== e) {
230
+ var i = e.call(t, r || "default");
231
+ if ("object" != _typeof(i)) return i;
232
+ throw new TypeError("@@toPrimitive must return a primitive value.");
233
+ }
234
+ return ("string" === r ? String : Number)(t);
235
+ }
236
+ //#endregion
237
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
238
+ function toPropertyKey(t) {
239
+ var i = toPrimitive(t, "string");
240
+ return "symbol" == _typeof(i) ? i : i + "";
241
+ }
242
+ //#endregion
243
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
244
+ function _defineProperty(e, r, t) {
245
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
246
+ value: t,
247
+ enumerable: !0,
248
+ configurable: !0,
249
+ writable: !0
250
+ }) : e[r] = t, e;
251
+ }
252
+ //#endregion
253
+ //#region src/store-sql.ts
254
+ var StoreSql = class StoreSql {
255
+ constructor(db, logger, authContext) {
256
+ this.db = db;
257
+ this.logger = logger;
258
+ _defineProperty(this, "authContext", void 0);
259
+ this.logger = logger.child({ component: "StoreSql" });
260
+ this.authContext = authContext;
261
+ }
262
+ withAuthContext(context) {
263
+ return new StoreSql(this.db, this.logger, context);
264
+ }
265
+ assertConnected() {
266
+ return assertConnected(this.authContext).userId;
267
+ }
268
+ async getAllWallets(filter = {}) {
269
+ const userId = this.assertConnected();
270
+ const { networkIds, signingProviderIds } = filter;
271
+ const networkIdSet = networkIds ? new Set(networkIds) : null;
272
+ const signingProviderIdSet = signingProviderIds ? new Set(signingProviderIds) : null;
273
+ const wallets = await this.db.selectFrom("wallets").selectAll().where("userId", "=", userId).execute();
274
+ const userPartyRights = await this.db.selectFrom("userPartyRights").selectAll().where("userId", "=", userId).execute();
275
+ const rightsByWallet = /* @__PURE__ */ new Map();
276
+ for (const row of userPartyRights) {
277
+ const right = fromPartyRight(row.right);
278
+ if (!right) continue;
279
+ const key = `${row.partyId}:${row.networkId}`;
280
+ const existing = rightsByWallet.get(key) ?? [];
281
+ rightsByWallet.set(key, [...existing, right]);
282
+ }
283
+ return wallets.filter((wallet) => {
284
+ const matchedNetworkIds = networkIdSet ? networkIdSet.has(wallet.networkId) : true;
285
+ const matchedSigningProviderIds = signingProviderIdSet ? signingProviderIdSet.has(wallet.signingProviderId) : true;
286
+ return matchedNetworkIds && matchedSigningProviderIds;
287
+ }).map((table) => {
288
+ const wallet = toWallet(table);
289
+ const rights = rightsByWallet.get(`${table.partyId}:${table.networkId}`);
290
+ return {
291
+ ...wallet,
292
+ rights: rights ?? []
293
+ };
294
+ });
295
+ }
296
+ async getWallets(filter = {}) {
297
+ const network = await this.getCurrentNetwork();
298
+ return this.getAllWallets({
299
+ ...filter,
300
+ networkIds: [network.id]
301
+ });
302
+ }
303
+ async getPrimaryWallet() {
304
+ return (await this.getWallets()).find((w) => w.primary === true);
305
+ }
306
+ async setPrimaryWallet(partyId) {
307
+ const network = await this.getCurrentNetwork();
308
+ const userId = this.assertConnected();
309
+ const wallets = await this.getWallets();
310
+ if (!wallets.some((w) => w.partyId === partyId)) throw new Error(`Wallet with partyId "${partyId}" not found in network "${network.id}"`);
311
+ const primary = wallets.find((w) => w.primary === true);
312
+ await this.db.transaction().execute(async (trx) => {
313
+ if (primary) await trx.updateTable("wallets").set({ primary: 0 }).where((eb) => eb.and([
314
+ eb("partyId", "=", primary.partyId),
315
+ eb("networkId", "=", network.id),
316
+ eb("userId", "=", userId)
317
+ ])).execute();
318
+ await trx.updateTable("wallets").set({ primary: 1 }).where((eb) => eb.and([
319
+ eb("partyId", "=", partyId),
320
+ eb("networkId", "=", network.id),
321
+ eb("userId", "=", userId)
322
+ ])).execute();
323
+ });
324
+ }
325
+ async addWallet(wallet) {
326
+ this.logger.info("Adding wallet");
327
+ const userId = this.assertConnected();
328
+ const wallets = await this.getWallets();
329
+ if (wallets.some((w) => w.partyId === wallet.partyId && w.networkId === wallet.networkId)) throw new Error(`Wallet with partyId "${wallet.partyId}" networkId "${wallet.networkId}" userId "${userId}" already exists`);
330
+ if (!wallet.disabled && wallet.status === "allocated" && !wallets.some((wallet) => wallet.primary)) wallet.primary = true;
331
+ await this.db.transaction().execute(async (trx) => {
332
+ if (wallet.primary) await trx.updateTable("wallets").set({ primary: 0 }).where((eb) => eb.and([
333
+ eb("primary", "=", 1),
334
+ eb("networkId", "=", wallet.networkId),
335
+ eb("userId", "=", userId)
336
+ ])).execute();
337
+ await trx.insertInto("wallets").values(fromWallet(wallet, userId)).execute();
338
+ if (wallet.rights && wallet.rights.length > 0) await trx.insertInto("userPartyRights").values(wallet.rights.map((right) => ({
339
+ userId,
340
+ networkId: wallet.networkId,
341
+ partyId: wallet.partyId,
342
+ right
343
+ }))).execute();
344
+ });
345
+ }
346
+ async updateWallet(params) {
347
+ const { partyId, networkId, rights } = params;
348
+ this.logger.info("Updating wallet");
349
+ const userId = this.assertConnected();
350
+ const updates = toWalletUpdateProperties(params);
351
+ const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
352
+ if (Object.keys(updates).length === 0 && rights === void 0) return;
353
+ await this.db.transaction().execute(async (trx) => {
354
+ if (Object.keys(updates).length > 0) await trx.updateTable("wallets").set(updates).where((eb) => eb.and([
355
+ eb("partyId", "=", partyId),
356
+ eb("networkId", "=", targetNetworkId),
357
+ eb("userId", "=", userId)
358
+ ])).execute();
359
+ if (rights !== void 0) {
360
+ await trx.deleteFrom("userPartyRights").where((eb) => eb.and([
361
+ eb("partyId", "=", partyId),
362
+ eb("networkId", "=", targetNetworkId),
363
+ eb("userId", "=", userId)
364
+ ])).execute();
365
+ if (rights.length > 0) await trx.insertInto("userPartyRights").values(rights.map((right) => ({
366
+ userId,
367
+ networkId: targetNetworkId,
368
+ partyId,
369
+ right
370
+ }))).execute();
371
+ }
372
+ });
373
+ }
374
+ async removeWallet(partyId) {
375
+ this.logger.info("Removing wallet");
376
+ const userId = this.assertConnected();
377
+ const network = await this.getCurrentNetwork();
378
+ await this.db.transaction().execute(async (trx) => {
379
+ await trx.deleteFrom("wallets").where((eb) => eb.and([
380
+ eb("partyId", "=", partyId),
381
+ eb("networkId", "=", network.id),
382
+ eb("userId", "=", userId)
383
+ ])).execute();
384
+ });
385
+ }
386
+ async getUserRights(networkId) {
387
+ const userId = this.assertConnected();
388
+ const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
389
+ return (await this.db.selectFrom("userRights").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", targetNetworkId)])).execute()).map((row) => fromUserRight(row.right)).filter((right) => right !== void 0);
390
+ }
391
+ async setUserRights(networkId, rights) {
392
+ const userId = this.assertConnected();
393
+ await this.db.transaction().execute(async (trx) => {
394
+ await trx.deleteFrom("userRights").where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", networkId)])).execute();
395
+ if (rights.length > 0) await trx.insertInto("userRights").values(rights.map((right) => ({
396
+ userId,
397
+ networkId,
398
+ right
399
+ }))).execute();
400
+ });
401
+ }
402
+ async getSession(accessToken) {
403
+ const userId = this.assertConnected();
404
+ const row = await this.db.selectFrom("sessions").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("accessToken", "=", accessToken)])).executeTakeFirst();
405
+ return row ? toSession(row) : void 0;
406
+ }
407
+ async listSessions() {
408
+ const userId = this.assertConnected();
409
+ return (await this.db.selectFrom("sessions").selectAll().where("userId", "=", userId).execute()).map((row) => toSession(row));
410
+ }
411
+ async setSession(session) {
412
+ const userId = this.assertConnected();
413
+ if (!session.origin) throw new Error("Session origin is required");
414
+ await this.db.transaction().execute(async (trx) => {
415
+ const deleted = await trx.deleteFrom("sessions").where((eb) => eb.and([eb("userId", "=", userId), eb("origin", "=", session.origin)])).execute();
416
+ this.logger.debug(deleted, "Deleted old session");
417
+ const inserted = await trx.insertInto("sessions").values({
418
+ ...session,
419
+ userId
420
+ }).execute();
421
+ this.logger.debug(inserted, "Inserted new session");
422
+ });
423
+ }
424
+ async removeSession(accessToken) {
425
+ const userId = this.assertConnected();
426
+ await this.db.deleteFrom("sessions").where((eb) => eb.and([eb("userId", "=", userId), eb("accessToken", "=", accessToken)])).execute();
427
+ }
428
+ /**
429
+ * Lists all pending transactions across all users.
430
+ */
431
+ async listAllPendingTransactions() {
432
+ return (await this.db.selectFrom("transactions").selectAll().where("status", "=", "pending").execute()).map((row) => toTransaction(row));
433
+ }
434
+ async getIdp(idpId) {
435
+ const idps = await this.listIdps();
436
+ if (!idps) throw new Error("No IDPs available");
437
+ const idp = idps.find((n) => n.id === idpId);
438
+ if (!idp) throw new Error(`IDP "${idpId}" not found`);
439
+ return idp;
440
+ }
441
+ async listIdps() {
442
+ return (await this.db.selectFrom("idps").selectAll().execute()).map((table) => toIdp(table));
443
+ }
444
+ async updateIdp(idp) {
445
+ await this.db.transaction().execute(async (trx) => {
446
+ const idpEntry = fromIdp(idp);
447
+ this.logger.info(idpEntry, "Updating idp table");
448
+ await trx.updateTable("idps").set(idpEntry).where("id", "=", idp.id).execute();
449
+ });
450
+ }
451
+ async addIdp(idp) {
452
+ await this.db.transaction().execute(async (trx) => {
453
+ if (await trx.selectFrom("idps").selectAll().where("id", "=", idp.id).executeTakeFirst()) throw new Error(`IDP ${idp.id} already exists`);
454
+ else await trx.insertInto("idps").values(fromIdp(idp)).execute();
455
+ });
456
+ }
457
+ async removeIdp(idpId) {
458
+ if ((await this.listNetworks()).some((n) => n.identityProviderId === idpId)) throw new Error(`Cannot delete IDP ${idpId} as it is in use by existing networks`);
459
+ await this.db.transaction().execute(async (trx) => {
460
+ if (!await trx.selectFrom("idps").selectAll().where("id", "=", idpId).executeTakeFirst()) throw new Error(`IDP ${idpId} does not exists`);
461
+ await trx.deleteFrom("idps").where("id", "=", idpId).execute();
462
+ });
463
+ }
464
+ async getNetwork(networkId) {
465
+ const networks = await this.listNetworks();
466
+ if (!networks) throw new Error("No networks available");
467
+ const network = networks.find((n) => n.id === networkId);
468
+ if (!network) throw new Error(`Network "${networkId}" not found`);
469
+ return network;
470
+ }
471
+ async getCurrentNetwork() {
472
+ const token = this.authContext?.accessToken;
473
+ if (!token) throw new Error("No access token found in auth context");
474
+ const session = await this.getSession(token);
475
+ if (!session) throw new Error("No session found");
476
+ const networkId = session.network;
477
+ if (!networkId) throw new Error("No current network set in session");
478
+ const network = (await this.listNetworks()).find((n) => n.id === networkId);
479
+ if (!network) throw new Error(`Network "${networkId}" not found`);
480
+ return network;
481
+ }
482
+ async listNetworks() {
483
+ let query = this.db.selectFrom("networks").selectAll();
484
+ if (this.authContext) {
485
+ const userId = this.assertConnected();
486
+ query = query.where((eb) => eb.or([eb("userId", "is", null), eb("userId", "=", userId)]));
487
+ } else query = query.where("userId", "is", null);
488
+ return (await query.execute()).map((table) => toNetwork(table));
489
+ }
490
+ async updateNetwork(network) {
491
+ this.assertConnected();
492
+ await this.db.transaction().execute(async (trx) => {
493
+ const networkEntry = fromNetwork(network, void 0);
494
+ this.logger.info(networkEntry, "Updating network table");
495
+ await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
496
+ });
497
+ }
498
+ async addNetwork(network) {
499
+ const userId = this.authContext?.userId;
500
+ if (!(await this.listIdps()).find((idp) => idp.id === network.identityProviderId)) throw new Error(`Identity provider "${network.identityProviderId}" not found`);
501
+ await this.db.transaction().execute(async (trx) => {
502
+ if (await trx.selectFrom("networks").selectAll().where("id", "=", network.id).executeTakeFirst()) throw new Error(`Network ${network.id} already exists`);
503
+ else await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
504
+ });
505
+ }
506
+ async removeNetwork(networkId) {
507
+ const userId = this.assertConnected();
508
+ await this.db.transaction().execute(async (trx) => {
509
+ const network = await trx.selectFrom("networks").selectAll().where("id", "=", networkId).executeTakeFirst();
510
+ if (!network) throw new Error(`Network ${networkId} does not exists`);
511
+ if (network.userId !== userId) throw new Error(`Network ${networkId} is not owned by user ${userId}`);
512
+ await trx.deleteFrom("networks").where("id", "=", networkId).execute();
513
+ });
514
+ }
515
+ mergeTransactionStatusUpdate(existing, status, updates = {}) {
516
+ const payload = updates.payload ?? existing.payload;
517
+ const signedAt = updates.signedAt ?? existing.signedAt;
518
+ const externalTxId = updates.externalTxId ?? existing.externalTxId;
519
+ return {
520
+ id: existing.id,
521
+ commandId: existing.commandId,
522
+ status,
523
+ preparedTransaction: existing.preparedTransaction,
524
+ preparedTransactionHash: existing.preparedTransactionHash,
525
+ origin: existing.origin,
526
+ ...payload !== void 0 && { payload },
527
+ ...existing.createdAt !== void 0 && { createdAt: existing.createdAt },
528
+ ...signedAt !== void 0 && { signedAt },
529
+ ...externalTxId !== void 0 && { externalTxId }
530
+ };
531
+ }
532
+ async setTransaction(transaction) {
533
+ const userId = this.assertConnected();
534
+ const network = await this.getCurrentNetwork();
535
+ await this.db.insertInto("transactions").values(fromTransaction(transaction, userId, network.id)).execute();
536
+ }
537
+ async setTransactionSigned(transactionId, signedAt, externalTxId) {
538
+ await this.setTransactionStatus(transactionId, "signed", {
539
+ signedAt,
540
+ ...externalTxId !== void 0 && { externalTxId }
541
+ });
542
+ }
543
+ async setTransactionStatus(transactionId, status, updates = {}) {
544
+ const userId = this.assertConnected();
545
+ const network = await this.getCurrentNetwork();
546
+ const existing = await this.getTransaction(transactionId);
547
+ if (!existing) throw new Error(`Transaction not found with id: ${transactionId}`);
548
+ const updated = this.mergeTransactionStatusUpdate(existing, status, updates);
549
+ await this.db.updateTable("transactions").set(fromTransaction(updated, userId, network.id)).where((eb) => eb.and([
550
+ eb("id", "=", transactionId),
551
+ eb("userId", "=", userId),
552
+ eb("networkId", "=", network.id)
553
+ ])).execute();
554
+ }
555
+ async getTransaction(transactionId) {
556
+ const userId = this.assertConnected();
557
+ const network = await this.getCurrentNetwork();
558
+ const transaction = await this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([
559
+ eb("id", "=", transactionId),
560
+ eb("userId", "=", userId),
561
+ eb("networkId", "=", network.id)
562
+ ])).executeTakeFirst();
563
+ return transaction ? toTransaction(transaction) : void 0;
564
+ }
565
+ async getLatestTransactionByCommandId(commandId) {
566
+ const userId = this.assertConnected();
567
+ const network = await this.getCurrentNetwork();
568
+ const transaction = await this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([
569
+ eb("commandId", "=", commandId),
570
+ eb("userId", "=", userId),
571
+ eb("networkId", "=", network.id)
572
+ ])).orderBy(sql`${sql.ref("createdAt")} desc nulls last`).executeTakeFirst();
573
+ return transaction ? toTransaction(transaction) : void 0;
574
+ }
575
+ async transactionsCount() {
576
+ const userId = this.assertConnected();
577
+ const network = await this.getCurrentNetwork();
578
+ const result = await this.db.selectFrom("transactions").where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).select((eb) => eb.fn.count("id").as("count")).executeTakeFirstOrThrow();
579
+ return Number(result.count);
580
+ }
581
+ async listTransactions(options) {
582
+ const userId = this.assertConnected();
583
+ const network = await this.getCurrentNetwork();
584
+ const { cursor, limit } = options ?? {};
585
+ const lim = limit ? Math.min(limit, 100) : 100;
586
+ let query = this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).orderBy(sql`${sql.ref("createdAt")} desc nulls last`).orderBy("id", "desc").limit(lim + 1);
587
+ if (cursor) {
588
+ const split = cursor.split("::");
589
+ const dateString = split[0] === "null" ? null : split[0];
590
+ const cursorId = split[1];
591
+ query = query.where((eb) => {
592
+ if (dateString === null) return eb.and([eb("createdAt", "is", null), eb("id", "<", cursorId)]);
593
+ return eb.or([
594
+ eb("createdAt", "<", dateString),
595
+ eb.and([eb("createdAt", "=", dateString), eb("id", "<", split[1])]),
596
+ eb("createdAt", "is", null)
597
+ ]);
598
+ });
599
+ }
600
+ const txs = (await query.execute()).map((r) => toTransaction(r));
601
+ const hasNextPage = txs.length > lim;
602
+ if (hasNextPage) txs.pop();
603
+ if (txs.length === 0) return {
604
+ transactions: [],
605
+ nextCursor: null
606
+ };
607
+ const lastTx = txs[txs.length - 1];
608
+ if (lastTx === void 0) return {
609
+ transactions: txs,
610
+ nextCursor: null
611
+ };
612
+ if (lastTx.createdAt) {
613
+ const d = new Date(lastTx.createdAt).toISOString();
614
+ return {
615
+ transactions: txs,
616
+ nextCursor: hasNextPage ? `${d}::${lastTx.id}` : null
617
+ };
618
+ } else return {
619
+ transactions: txs,
620
+ nextCursor: hasNextPage ? `null::${lastTx.id}` : null
621
+ };
622
+ }
623
+ async removeTransaction(transactionId) {
624
+ const userId = this.assertConnected();
625
+ const network = await this.getCurrentNetwork();
626
+ await this.db.deleteFrom("transactions").where((eb) => eb.and([
627
+ eb("id", "=", transactionId),
628
+ eb("userId", "=", userId),
629
+ eb("networkId", "=", network.id)
630
+ ])).execute();
631
+ }
632
+ mergeMessageRawStatusUpdate(existing, status, updates = {}) {
633
+ const signedAt = updates.signedAt ?? existing.signedAt;
634
+ const signature = updates.signature ?? existing.signature;
635
+ return {
636
+ ...existing,
637
+ status,
638
+ ...signedAt !== void 0 && { signedAt },
639
+ ...signature !== void 0 && { signature }
640
+ };
641
+ }
642
+ async setMessageRaw(message) {
643
+ const userId = this.assertConnected();
644
+ if (message.userId !== userId) throw new Error(`MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`);
645
+ const network = await this.getCurrentNetwork();
646
+ await this.db.insertInto("messagesRaw").values(fromMessageRaw(message, userId, network.id)).execute();
647
+ }
648
+ async setMessageRawStatus(messageId, status, updates = {}) {
649
+ const userId = this.assertConnected();
650
+ const network = await this.getCurrentNetwork();
651
+ const existing = await this.getMessageRaw(messageId);
652
+ if (!existing) throw new Error(`MessageRaw not found with id: ${messageId}`);
653
+ const updated = this.mergeMessageRawStatusUpdate(existing, status, updates);
654
+ await this.db.updateTable("messagesRaw").set(fromMessageRaw(updated, userId, network.id)).where((eb) => eb.and([
655
+ eb("id", "=", messageId),
656
+ eb("userId", "=", userId),
657
+ eb("networkId", "=", network.id)
658
+ ])).execute();
659
+ }
660
+ async getMessageRaw(messageId) {
661
+ const userId = this.assertConnected();
662
+ const network = await this.getCurrentNetwork();
663
+ const message = await this.db.selectFrom("messagesRaw").selectAll().where((eb) => eb.and([
664
+ eb("id", "=", messageId),
665
+ eb("userId", "=", userId),
666
+ eb("networkId", "=", network.id)
667
+ ])).executeTakeFirst();
668
+ return message ? toMessageRaw(message) : void 0;
669
+ }
670
+ async listMessageRaws() {
671
+ const userId = this.assertConnected();
672
+ const network = await this.getCurrentNetwork();
673
+ return (await this.db.selectFrom("messagesRaw").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).orderBy("createdAt", "desc").orderBy("id", "desc").execute()).map((m) => toMessageRaw(m));
674
+ }
675
+ async removeMessageRaw(messageId) {
676
+ const userId = this.assertConnected();
677
+ const network = await this.getCurrentNetwork();
678
+ await this.db.deleteFrom("messagesRaw").where((eb) => eb.and([
679
+ eb("id", "=", messageId),
680
+ eb("userId", "=", userId),
681
+ eb("networkId", "=", network.id)
682
+ ])).execute();
683
+ }
684
+ async addApiKey(apiKey) {
685
+ const userId = this.assertConnected();
686
+ if (apiKey.userId !== userId) throw new Error(`ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`);
687
+ const network = await this.getCurrentNetwork();
688
+ if (apiKey.networkId !== network.id) throw new Error(`ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`);
689
+ await this.db.insertInto("apiKeys").values(toApiKey(apiKey)).execute();
690
+ }
691
+ async listApiKeys() {
692
+ const query = this.db.selectFrom("apiKeys").selectAll().orderBy("createdAt", "desc");
693
+ const userId = this.assertConnected();
694
+ const network = await this.getCurrentNetwork();
695
+ return (await query.where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).execute()).map(fromApiKey);
696
+ }
697
+ async getApiKey(digest) {
698
+ const apiKey = await this.db.selectFrom("apiKeys").selectAll().where((eb) => eb("digest", "=", digest)).executeTakeFirst();
699
+ return apiKey ? fromApiKey(apiKey) : void 0;
700
+ }
701
+ async removeApiKey(apiKeyId) {
702
+ const userId = this.assertConnected();
703
+ const network = await this.getCurrentNetwork();
704
+ await this.db.deleteFrom("apiKeys").where((eb) => eb.and([
705
+ eb("id", "=", apiKeyId),
706
+ eb("userId", "=", userId),
707
+ eb("networkId", "=", network.id)
708
+ ])).execute();
709
+ }
839
710
  };
840
- var connection = (config) => {
841
- let database;
842
- switch (config.connection.type) {
843
- case "sqlite":
844
- database = new Database(config.connection.database);
845
- database.pragma("foreign_keys = ON");
846
- return new Kysely({
847
- dialect: new SqliteDialect({
848
- database
849
- }),
850
- plugins: [new CamelCasePlugin()]
851
- });
852
- case "postgres":
853
- return new Kysely({
854
- dialect: new PostgresDialect({
855
- pool: new pg.Pool(config.connection)
856
- }),
857
- plugins: [new CamelCasePlugin()]
858
- });
859
- case "memory":
860
- database = new Database(":memory:");
861
- database.pragma("foreign_keys = ON");
862
- return new Kysely({
863
- dialect: new SqliteDialect({
864
- database
865
- }),
866
- plugins: [new CamelCasePlugin()]
867
- });
868
- }
711
+ const connection = (config) => {
712
+ let database;
713
+ switch (config.connection.type) {
714
+ case "sqlite":
715
+ database = new Database(config.connection.database);
716
+ database.pragma("foreign_keys = ON");
717
+ return new Kysely({
718
+ dialect: new SqliteDialect({ database }),
719
+ plugins: [new CamelCasePlugin()]
720
+ });
721
+ case "postgres": return new Kysely({
722
+ dialect: new PostgresDialect({ pool: new pg.Pool(config.connection) }),
723
+ plugins: [new CamelCasePlugin()]
724
+ });
725
+ case "memory":
726
+ database = new Database(":memory:");
727
+ database.pragma("foreign_keys = ON");
728
+ return new Kysely({
729
+ dialect: new SqliteDialect({ database }),
730
+ plugins: [new CamelCasePlugin()]
731
+ });
732
+ }
869
733
  };
734
+ //#endregion
735
+ //#region src/migrator.ts
870
736
  var KyselyStorage = class {
871
- constructor(db) {
872
- this.db = db;
873
- }
874
- async ensureTable() {
875
- await this.db.schema.createTable("migrations").ifNotExists().addColumn("name", "text", (col) => col.primaryKey()).addColumn("executedAt", "text", (col) => col.notNull()).execute();
876
- }
877
- async executed() {
878
- await this.ensureTable();
879
- const rows = await this.db.selectFrom("migrations").select("name").execute();
880
- return rows.map((r) => r.name);
881
- }
882
- async logMigration({ name }) {
883
- await this.ensureTable();
884
- await this.db.insertInto("migrations").values({ name, executedAt: (/* @__PURE__ */ new Date()).toISOString() }).execute();
885
- }
886
- async unlogMigration({ name }) {
887
- await this.ensureTable();
888
- await this.db.deleteFrom("migrations").where("name", "=", name).execute();
889
- }
737
+ constructor(db) {
738
+ this.db = db;
739
+ }
740
+ async ensureTable() {
741
+ await this.db.schema.createTable("migrations").ifNotExists().addColumn("name", "text", (col) => col.primaryKey()).addColumn("executedAt", "text", (col) => col.notNull()).execute();
742
+ }
743
+ async executed() {
744
+ await this.ensureTable();
745
+ return (await this.db.selectFrom("migrations").select("name").execute()).map((r) => r.name);
746
+ }
747
+ async logMigration({ name }) {
748
+ await this.ensureTable();
749
+ await this.db.insertInto("migrations").values({
750
+ name,
751
+ executedAt: (/* @__PURE__ */ new Date()).toISOString()
752
+ }).execute();
753
+ }
754
+ async unlogMigration({ name }) {
755
+ await this.ensureTable();
756
+ await this.db.deleteFrom("migrations").where("name", "=", name).execute();
757
+ }
890
758
  };
891
- var migrator = (db) => {
892
- const ext = import.meta.url.endsWith(".ts") ? "ts" : "js";
893
- const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname;
894
- return new Umzug({
895
- migrations: {
896
- glob,
897
- resolve: ({ name, path, context }) => {
898
- return {
899
- name,
900
- up: async () => {
901
- console.log(path);
902
- const { up } = await import(path);
903
- return up(context);
904
- },
905
- down: async () => {
906
- const { down } = await import(path);
907
- return down(context);
908
- }
909
- };
910
- }
911
- },
912
- context: db,
913
- storage: new KyselyStorage(db),
914
- logger: console
915
- });
759
+ const migrator = (db) => {
760
+ const ext = import.meta.url.endsWith(".ts") ? "ts" : "js";
761
+ const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname;
762
+ return new Umzug({
763
+ migrations: {
764
+ glob,
765
+ resolve: ({ name, path, context }) => {
766
+ return {
767
+ name,
768
+ up: async () => {
769
+ console.log(path);
770
+ const { up } = await import(path);
771
+ return up(context);
772
+ },
773
+ down: async () => {
774
+ const { down } = await import(path);
775
+ return down(context);
776
+ }
777
+ };
778
+ }
779
+ },
780
+ context: db,
781
+ storage: new KyselyStorage(db),
782
+ logger: console
783
+ });
916
784
  };
917
-
918
- // src/bootstrap.ts
919
- async function bootstrap(db, config, logger2) {
920
- const store = new StoreSql(db, logger2);
921
- await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
922
- await Promise.all(
923
- config.networks.map((network) => store.addNetwork(network))
924
- );
785
+ //#endregion
786
+ //#region src/bootstrap.ts
787
+ async function bootstrap(db, config, logger) {
788
+ const store = new StoreSql(db, logger);
789
+ await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
790
+ await Promise.all(config.networks.map((network) => store.addNetwork(network)));
925
791
  }
926
-
927
- // src/cli.ts
928
- var logger = pino({ name: "main", level: "debug" });
792
+ //#endregion
793
+ //#region src/cli.ts
794
+ const logger = pino({
795
+ name: "main",
796
+ level: "debug"
797
+ });
929
798
  function createCLI(config, bootstrapConfig) {
930
- const program = new Command();
931
- program.command("up").description("Run all pending migrations").action(async () => {
932
- const db = connection(config);
933
- const umzug = migrator(db);
934
- await umzug.up();
935
- await db.destroy();
936
- });
937
- program.command("down").description("Rollback last migration").action(async () => {
938
- const db = connection(config);
939
- const umzug = migrator(db);
940
- await umzug.down();
941
- await db.destroy();
942
- });
943
- program.command("status").description("Show executed and pending migrations").action(async () => {
944
- const db = connection(config);
945
- const umzug = migrator(db);
946
- const executed = await umzug.executed();
947
- const pending = await umzug.pending();
948
- console.log("Executed migrations:", executed);
949
- console.log("Pending migrations:", pending);
950
- await db.destroy();
951
- });
952
- program.command("reset").description("Rollback all migrations and reapply them").action(async () => {
953
- const db = connection(config);
954
- const umzug = migrator(db);
955
- const executed = await umzug.executed();
956
- for (const migration of executed.reverse()) {
957
- await umzug.down({ to: migration.name });
958
- }
959
- await umzug.up();
960
- await db.destroy();
961
- });
962
- program.command("bootstrap").description("Bootstrap DB from config").action(async () => {
963
- if (!bootstrapConfig) {
964
- throw new Error(
965
- "Bootstrap config (idps/networks) is required for the bootstrap command"
966
- );
967
- }
968
- const db = connection(config);
969
- await bootstrap(db, bootstrapConfig, logger);
970
- await db.destroy();
971
- });
972
- return program;
799
+ const program = new Command();
800
+ program.command("up").description("Run all pending migrations").action(async () => {
801
+ const db = connection(config);
802
+ await migrator(db).up();
803
+ await db.destroy();
804
+ });
805
+ program.command("down").description("Rollback last migration").action(async () => {
806
+ const db = connection(config);
807
+ await migrator(db).down();
808
+ await db.destroy();
809
+ });
810
+ program.command("status").description("Show executed and pending migrations").action(async () => {
811
+ const db = connection(config);
812
+ const umzug = migrator(db);
813
+ const executed = await umzug.executed();
814
+ const pending = await umzug.pending();
815
+ console.log("Executed migrations:", executed);
816
+ console.log("Pending migrations:", pending);
817
+ await db.destroy();
818
+ });
819
+ program.command("reset").description("Rollback all migrations and reapply them").action(async () => {
820
+ const db = connection(config);
821
+ const umzug = migrator(db);
822
+ const executed = await umzug.executed();
823
+ for (const migration of executed.reverse()) await umzug.down({ to: migration.name });
824
+ await umzug.up();
825
+ await db.destroy();
826
+ });
827
+ program.command("bootstrap").description("Bootstrap DB from config").action(async () => {
828
+ if (!bootstrapConfig) throw new Error("Bootstrap config (idps/networks) is required for the bootstrap command");
829
+ const db = connection(config);
830
+ await bootstrap(db, bootstrapConfig, logger);
831
+ await db.destroy();
832
+ });
833
+ return program;
973
834
  }
974
-
835
+ //#endregion
975
836
  export { StoreSql, bootstrap, connection, createCLI, migrator };
976
- //# sourceMappingURL=index.js.map
837
+
977
838
  //# sourceMappingURL=index.js.map