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