shogun-core 1.2.7 → 1.2.8

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.
Files changed (67) hide show
  1. package/README.md +0 -1
  2. package/dist/browser/shogun-core.js +1 -1
  3. package/dist/browser/shogun-core.js.LICENSE.txt +2 -0
  4. package/dist/browser/shogun-core.light.js +1 -1
  5. package/dist/browser/shogun-core.vendors.light.js +1 -1
  6. package/dist/core.js +31 -71
  7. package/dist/gundb/{instance.js → gunInstance.js} +135 -115
  8. package/dist/gundb/index.js +3 -20
  9. package/dist/plugins/index.js +23 -1
  10. package/dist/plugins/nostr/index.js +1 -0
  11. package/dist/plugins/nostr/nostrChain.js +128 -0
  12. package/dist/plugins/nostr/nostrConnector.js +42 -7
  13. package/dist/plugins/nostr/nostrConnectorPlugin.js +157 -1
  14. package/dist/plugins/nostr/nostrSigner.js +343 -0
  15. package/dist/plugins/oauth/index.js +13 -0
  16. package/dist/plugins/oauth/oauthChain.js +161 -0
  17. package/dist/plugins/oauth/oauthConnector.js +542 -0
  18. package/dist/plugins/oauth/oauthPlugin.js +302 -0
  19. package/dist/plugins/oauth/types.js +2 -0
  20. package/dist/plugins/web3/index.js +1 -0
  21. package/dist/plugins/web3/web3Chain.js +77 -2
  22. package/dist/plugins/web3/web3Connector.js +159 -37
  23. package/dist/plugins/web3/web3ConnectorPlugin.js +157 -1
  24. package/dist/plugins/web3/web3Signer.js +268 -0
  25. package/dist/plugins/webauthn/webauthnChain.js +78 -0
  26. package/dist/plugins/webauthn/webauthnPlugin.js +154 -1
  27. package/dist/plugins/webauthn/webauthnSigner.js +318 -0
  28. package/dist/storage/storage.js +0 -8
  29. package/dist/types/core.d.ts +10 -34
  30. package/dist/types/gundb/gun-es/gun-es.d.ts +1 -0
  31. package/dist/types/gundb/{instance.d.ts → gunInstance.d.ts} +2 -2
  32. package/dist/types/gundb/index.d.ts +1 -4
  33. package/dist/types/plugins/index.d.ts +4 -0
  34. package/dist/types/plugins/nostr/index.d.ts +1 -0
  35. package/dist/types/plugins/nostr/nostrConnector.d.ts +3 -2
  36. package/dist/types/plugins/nostr/nostrConnectorPlugin.d.ts +82 -0
  37. package/dist/types/plugins/nostr/nostrSigner.d.ts +104 -0
  38. package/dist/types/plugins/oauth/index.d.ts +4 -0
  39. package/dist/types/plugins/oauth/oauthChain.d.ts +2 -0
  40. package/dist/types/plugins/oauth/oauthConnector.d.ts +100 -0
  41. package/dist/types/plugins/oauth/oauthPlugin.d.ts +89 -0
  42. package/dist/types/plugins/oauth/types.d.ts +106 -0
  43. package/dist/types/plugins/web3/index.d.ts +1 -0
  44. package/dist/types/plugins/web3/types.d.ts +1 -0
  45. package/dist/types/plugins/web3/web3Connector.d.ts +8 -2
  46. package/dist/types/plugins/web3/web3ConnectorPlugin.d.ts +82 -0
  47. package/dist/types/plugins/web3/web3Signer.d.ts +93 -0
  48. package/dist/types/plugins/webauthn/webauthnPlugin.d.ts +81 -0
  49. package/dist/types/plugins/webauthn/webauthnSigner.d.ts +90 -0
  50. package/dist/types/shogun.js +1 -28
  51. package/dist/types/types/events.d.ts +2 -2
  52. package/dist/types/types/shogun.d.ts +13 -49
  53. package/package.json +2 -1
  54. package/dist/browser.js +0 -107
  55. package/dist/contracts/base.js +0 -152
  56. package/dist/contracts/entryPoint.js +0 -407
  57. package/dist/contracts/index.js +0 -47
  58. package/dist/contracts/registry.js +0 -259
  59. package/dist/contracts/relay.js +0 -494
  60. package/dist/contracts/utils.js +0 -582
  61. package/dist/types/browser.d.ts +0 -27
  62. package/dist/types/contracts/base.d.ts +0 -82
  63. package/dist/types/contracts/entryPoint.d.ts +0 -138
  64. package/dist/types/contracts/index.d.ts +0 -17
  65. package/dist/types/contracts/registry.d.ts +0 -97
  66. package/dist/types/contracts/relay.d.ts +0 -165
  67. package/dist/types/contracts/utils.d.ts +0 -173
package/dist/core.js CHANGED
@@ -13,11 +13,8 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
13
13
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
16
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.ShogunCore = exports.ShogunEventEmitter = exports.ShogunStorage = exports.Webauthn = exports.Web3Connector = exports.derive = exports.GunDB = exports.RelayVerifier = void 0;
17
+ exports.ShogunCore = exports.ShogunEventEmitter = exports.ShogunStorage = exports.Gun = exports.SEA = void 0;
21
18
  const gundb_1 = require("./gundb");
22
19
  const rxjs_integration_1 = require("./gundb/rxjs-integration");
23
20
  const eventEmitter_1 = require("./utils/eventEmitter");
@@ -28,28 +25,15 @@ const shogun_1 = require("./types/shogun");
28
25
  const webauthnPlugin_1 = require("./plugins/webauthn/webauthnPlugin");
29
26
  const web3ConnectorPlugin_1 = require("./plugins/web3/web3ConnectorPlugin");
30
27
  const nostrConnectorPlugin_1 = require("./plugins/nostr/nostrConnectorPlugin");
31
- const gun_1 = __importDefault(require("gun"));
32
- require("gun/sea");
33
- var utils_1 = require("./contracts/utils");
34
- Object.defineProperty(exports, "RelayVerifier", { enumerable: true, get: function () { return utils_1.RelayVerifier; } });
28
+ const oauthPlugin_1 = require("./plugins/oauth/oauthPlugin");
29
+ const gun_es_1 = require("./gundb/gun-es/gun-es");
30
+ Object.defineProperty(exports, "Gun", { enumerable: true, get: function () { return gun_es_1.Gun; } });
31
+ Object.defineProperty(exports, "SEA", { enumerable: true, get: function () { return gun_es_1.SEA; } });
35
32
  __exportStar(require("./utils/errorHandler"), exports);
33
+ __exportStar(require("./gundb"), exports);
36
34
  __exportStar(require("./gundb/rxjs-integration"), exports);
37
35
  __exportStar(require("./plugins"), exports);
38
- __exportStar(require("./contracts/entryPoint"), exports);
39
- __exportStar(require("./contracts/utils"), exports);
40
- __exportStar(require("./contracts/registry"), exports);
41
- __exportStar(require("./contracts/relay"), exports);
42
- // Export all types
43
36
  __exportStar(require("./types/shogun"), exports);
44
- // Export classes
45
- var gundb_2 = require("./gundb");
46
- Object.defineProperty(exports, "GunDB", { enumerable: true, get: function () { return gundb_2.GunDB; } });
47
- var gundb_3 = require("./gundb");
48
- Object.defineProperty(exports, "derive", { enumerable: true, get: function () { return gundb_3.derive; } });
49
- var web3Connector_1 = require("./plugins/web3/web3Connector");
50
- Object.defineProperty(exports, "Web3Connector", { enumerable: true, get: function () { return web3Connector_1.Web3Connector; } });
51
- var webauthn_1 = require("./plugins/webauthn/webauthn");
52
- Object.defineProperty(exports, "Webauthn", { enumerable: true, get: function () { return webauthn_1.Webauthn; } });
53
37
  var storage_2 = require("./storage/storage");
54
38
  Object.defineProperty(exports, "ShogunStorage", { enumerable: true, get: function () { return storage_2.ShogunStorage; } });
55
39
  var events_1 = require("./types/events");
@@ -58,7 +42,7 @@ Object.defineProperty(exports, "ShogunEventEmitter", { enumerable: true, get: fu
58
42
  * Main ShogunCore class - implements the IShogunCore interface
59
43
  *
60
44
  * This is the primary entry point for the Shogun SDK, providing access to:
61
- * - Decentralized database (GunDB)
45
+ * - Decentralized database (GunInstance)
62
46
  * - Authentication methods (traditional, WebAuthn, MetaMask)
63
47
  * - Plugin system for extensibility
64
48
  * - RxJS integration for reactive programming
@@ -66,44 +50,32 @@ Object.defineProperty(exports, "ShogunEventEmitter", { enumerable: true, get: fu
66
50
  * @since 2.0.0
67
51
  */
68
52
  class ShogunCore {
69
- /** Current API version - used for deprecation warnings and migration guidance */
70
53
  static API_VERSION = "2.0.0";
71
- /** Gun database instance - access through gundb.gun for consistency */
72
54
  _gun;
73
- /** Gun user instance */
74
55
  _user = null;
75
- /** GunDB wrapper - the primary interface for Gun operations */
76
56
  gundb;
77
- /** Storage implementation */
78
57
  storage;
79
- /** Event emitter for SDK events */
80
58
  eventEmitter;
81
- /** Ethereum provider */
82
59
  provider;
83
- /** SDK configuration */
84
60
  config;
85
- /** RxJS integration */
86
61
  rx;
87
- /** Plugin registry */
88
62
  plugins = new Map();
89
- /** Current authentication method */
90
63
  currentAuthMethod;
91
64
  /**
92
65
  * Initialize the Shogun SDK
93
66
  * @param config - SDK Configuration object
94
67
  * @description Creates a new instance of ShogunCore with the provided configuration.
95
- * Initializes all required components including storage, event emitter, GunDB connection,
68
+ * Initializes all required components including storage, event emitter, GunInstance connection,
96
69
  * and plugin system.
97
70
  */
98
71
  constructor(config) {
99
- (0, logger_1.log)("Initializing ShogunSDK");
72
+ (0, logger_1.log)("Initializing Shogun");
100
73
  this.config = config;
74
+ this.storage = new storage_1.ShogunStorage();
75
+ this.eventEmitter = new eventEmitter_1.EventEmitter();
101
76
  if (config.logging) {
102
77
  (0, logger_1.configureLogging)(config.logging);
103
- (0, logger_1.log)("Logging configured with custom settings");
104
78
  }
105
- this.storage = new storage_1.ShogunStorage();
106
- this.eventEmitter = new eventEmitter_1.EventEmitter();
107
79
  errorHandler_1.ErrorHandler.addListener((error) => {
108
80
  this.eventEmitter.emit("error", {
109
81
  action: error.code,
@@ -111,39 +83,28 @@ class ShogunCore {
111
83
  type: error.type,
112
84
  });
113
85
  });
114
- (0, logger_1.log)("Creating Gun instance...");
115
86
  try {
116
87
  if (config.gunInstance) {
117
- (0, logger_1.log)("Using provided Gun instance");
118
- // Validate the provided instance
119
88
  this._gun = config.gunInstance;
120
89
  }
121
90
  else {
122
- (0, logger_1.log)(`Creating new Gun instance with peers: ${JSON.stringify(config.peers)}`);
123
- // Use the factory to create a properly configured Gun instance
124
- this._gun = (0, gun_1.default)(config.peers || []);
91
+ this._gun = (0, gun_es_1.Gun)(config.peers || []);
125
92
  }
126
- (0, logger_1.log)(`Gun instance created and validated successfully`);
127
93
  }
128
94
  catch (error) {
129
95
  (0, logger_1.logError)("Error creating Gun instance:", error);
130
96
  throw new Error(`Failed to create Gun instance: ${error}`);
131
97
  }
132
- // Then initialize GunDB with the Gun instance
133
- (0, logger_1.log)("Initializing GunDB...");
134
98
  try {
135
- this.gundb = new gundb_1.GunDB(this._gun, config.scope || "");
99
+ this.gundb = new gundb_1.GunInstance(this._gun, config.scope || "");
136
100
  this._gun = this.gundb.gun;
137
- (0, logger_1.log)("GunDB initialized successfully");
138
101
  }
139
102
  catch (error) {
140
- (0, logger_1.logError)("Error initializing GunDB:", error);
141
- throw new Error(`Failed to initialize GunDB: ${error}`);
103
+ (0, logger_1.logError)("Error initializing GunInstance:", error);
104
+ throw new Error(`Failed to initialize GunInstance: ${error}`);
142
105
  }
143
- (0, logger_1.log)("Initialized Gun instance");
144
106
  try {
145
107
  this._user = this._gun.user().recall({ sessionStorage: true });
146
- (0, logger_1.log)("Gun user initialized successfully");
147
108
  }
148
109
  catch (error) {
149
110
  (0, logger_1.logError)("Error initializing Gun user:", error);
@@ -156,14 +117,13 @@ class ShogunCore {
156
117
  for (const plugin of config.plugins.autoRegister) {
157
118
  try {
158
119
  this.register(plugin);
159
- (0, logger_1.log)(`Auto-registered plugin: ${plugin.name}`);
160
120
  }
161
121
  catch (error) {
162
122
  (0, logger_1.logError)(`Failed to auto-register plugin ${plugin.name}:`, error);
163
123
  }
164
124
  }
165
125
  }
166
- (0, logger_1.log)("ShogunSDK initialized!");
126
+ (0, logger_1.log)("ShogunSDK initialized! 🚀");
167
127
  }
168
128
  /**
169
129
  * Access to the Gun instance
@@ -204,6 +164,19 @@ class ShogunCore {
204
164
  this.register(nostrConnectorPlugin);
205
165
  (0, logger_1.log)("NostrConnector plugin registered");
206
166
  }
167
+ // Register OAuth plugin if enabled
168
+ if (config.oauth?.enabled) {
169
+ const oauthPlugin = new oauthPlugin_1.OAuthPlugin();
170
+ oauthPlugin._category = shogun_1.PluginCategory.Authentication;
171
+ // Configure the plugin with provider settings from config
172
+ if (config.oauth.providers) {
173
+ oauthPlugin.configure({
174
+ providers: config.oauth.providers,
175
+ });
176
+ }
177
+ this.register(oauthPlugin);
178
+ (0, logger_1.log)("OAuth plugin registered with providers:", config.oauth.providers);
179
+ }
207
180
  }
208
181
  catch (error) {
209
182
  (0, logger_1.logError)("Error registering builtin plugins:", error);
@@ -286,7 +259,6 @@ class ShogunCore {
286
259
  return this.getPlugin(shogun_1.CorePlugins.Nostr);
287
260
  case "password":
288
261
  default:
289
- // Default authentication is provided by the core class
290
262
  return {
291
263
  login: (username, password) => {
292
264
  this.login(username, password);
@@ -332,7 +304,7 @@ class ShogunCore {
332
304
  /**
333
305
  * Check if user is logged in
334
306
  * @returns {boolean} True if user is logged in, false otherwise
335
- * @description Verifies authentication status by checking GunDB login state
307
+ * @description Verifies authentication status by checking GunInstance login state
336
308
  * and presence of authentication credentials in storage
337
309
  */
338
310
  isLoggedIn() {
@@ -340,7 +312,7 @@ class ShogunCore {
340
312
  }
341
313
  /**
342
314
  * Perform user logout
343
- * @description Logs out the current user from GunDB and emits logout event.
315
+ * @description Logs out the current user from GunInstance and emits logout event.
344
316
  * If user is not authenticated, the logout operation is ignored.
345
317
  */
346
318
  logout() {
@@ -354,7 +326,6 @@ class ShogunCore {
354
326
  (0, logger_1.log)("Logout completed successfully");
355
327
  }
356
328
  catch (error) {
357
- // Use centralized error handler
358
329
  errorHandler_1.ErrorHandler.handle(errorHandler_1.ErrorType.AUTHENTICATION, "LOGOUT_FAILED", error instanceof Error ? error.message : "Error during logout", error);
359
330
  }
360
331
  }
@@ -377,14 +348,11 @@ class ShogunCore {
377
348
  error: "Username and password are required",
378
349
  };
379
350
  }
380
- // Set authentication method to password only if not already set by a plugin
381
351
  if (!this.currentAuthMethod) {
382
352
  this.currentAuthMethod = "password";
383
353
  (0, logger_1.log)("Authentication method set to default: password");
384
354
  }
385
- // Timeout after a configurable interval (default 15 seconds)
386
355
  const timeoutDuration = this.config?.timeouts?.login ?? 15000;
387
- // Use a Promise with timeout for the login operation
388
356
  const loginPromiseWithTimeout = new Promise(async (resolve) => {
389
357
  const timeoutId = setTimeout(() => {
390
358
  resolve({
@@ -393,7 +361,6 @@ class ShogunCore {
393
361
  });
394
362
  }, timeoutDuration);
395
363
  try {
396
- // Use the GunDB login method instead of reimplementing it here
397
364
  const loginResult = await this.gundb.login(username, password);
398
365
  clearTimeout(timeoutId);
399
366
  if (!loginResult.success) {
@@ -403,7 +370,6 @@ class ShogunCore {
403
370
  });
404
371
  }
405
372
  else {
406
- // First resolve the success result
407
373
  resolve({
408
374
  success: true,
409
375
  userPub: loginResult.userPub,
@@ -424,8 +390,6 @@ class ShogunCore {
424
390
  this.eventEmitter.emit("auth:login", {
425
391
  userPub: result.userPub ?? "",
426
392
  });
427
- // Automatically initialize wallet after successful login
428
- // Only for traditional password authentication
429
393
  (0, logger_1.log)(`Current auth method before wallet check: ${this.currentAuthMethod}`);
430
394
  }
431
395
  return result;
@@ -485,25 +449,21 @@ class ShogunCore {
485
449
  });
486
450
  }, timeoutDuration);
487
451
  try {
488
- // Use the GunDB signUp method instead of reimplementing it here
489
452
  const result = await this.gundb.signUp(username, password);
490
453
  clearTimeout(timeoutId);
491
454
  if (result.success) {
492
- // Emit a debug event to monitor the flow
493
455
  this.eventEmitter.emit("debug", {
494
456
  action: "signup_complete",
495
457
  username,
496
458
  userPub: result.userPub,
497
459
  timestamp: Date.now(),
498
460
  });
499
- // Emit the signup event
500
461
  this.eventEmitter.emit("auth:signup", {
501
462
  userPub: result.userPub ?? "",
502
463
  username,
503
464
  });
504
465
  }
505
466
  else {
506
- // Emit a debug event to monitor the flow in case of failure
507
467
  this.eventEmitter.emit("debug", {
508
468
  action: "signup_failed",
509
469
  username,
@@ -42,7 +42,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
42
42
  return (mod && mod.__esModule) ? mod : { "default": mod };
43
43
  };
44
44
  Object.defineProperty(exports, "__esModule", { value: true });
45
- exports.GunDB = void 0;
45
+ exports.GunInstance = void 0;
46
46
  const logger_1 = require("../utils/logger");
47
47
  const errorHandler_1 = require("../utils/errorHandler");
48
48
  const rxjs_integration_1 = require("./rxjs-integration");
@@ -50,7 +50,7 @@ const GunErrors = __importStar(require("./errors"));
50
50
  const crypto = __importStar(require("./crypto"));
51
51
  const utils = __importStar(require("./utils"));
52
52
  const derive_1 = __importDefault(require("./derive"));
53
- class GunDB {
53
+ class GunInstance {
54
54
  gun;
55
55
  user = null;
56
56
  crypto;
@@ -78,6 +78,14 @@ class GunDB {
78
78
  throw new Error(`Gun instance is invalid: gun.on is not a function. Received gun.on type: ${typeof gun.on}`);
79
79
  }
80
80
  this.gun = gun;
81
+ if (typeof window !== "undefined") {
82
+ window.ShogunDB = this;
83
+ window.ShogunGun = gun;
84
+ }
85
+ else if (typeof global !== "undefined") {
86
+ global.ShogunDB = this;
87
+ global.ShogunGun = gun;
88
+ }
81
89
  try {
82
90
  this.user = this.gun.user().recall({ sessionStorage: true });
83
91
  }
@@ -86,7 +94,6 @@ class GunDB {
86
94
  throw new Error(`Failed to initialize Gun user: ${error}`);
87
95
  }
88
96
  this.subscribeToAuthEvents();
89
- // bind crypto and utils
90
97
  this.crypto = crypto;
91
98
  this.utils = utils;
92
99
  this.node = this.gun.get(appScope);
@@ -380,17 +387,84 @@ class GunDB {
380
387
  (0, logger_1.log)(err);
381
388
  return { success: false, error: err };
382
389
  }
383
- // Check if username already exists in our tracking system
384
- (0, logger_1.log)(`Checking if username ${username} already exists in tracking system...`);
385
- const existingUser = await this.checkUsernameExists(username);
386
- if (existingUser) {
387
- (0, logger_1.log)(`Username ${username} already exists in tracking system with pub: ${existingUser.pub}`);
390
+ // First, try to authenticate with Gun's native system to check if user exists
391
+ (0, logger_1.log)(`Checking if user ${username} exists in Gun's native system...`);
392
+ const authTestResult = await new Promise((resolve) => {
393
+ this.gun.user().auth(username, password, (ack) => {
394
+ if (ack.err) {
395
+ // User doesn't exist or password is wrong - this is expected for new users
396
+ resolve({ exists: false, error: ack.err });
397
+ }
398
+ else {
399
+ // User exists and password is correct
400
+ resolve({ exists: true, userPub: this.gun.user().is?.pub });
401
+ }
402
+ });
403
+ });
404
+ if (authTestResult.exists) {
405
+ (0, logger_1.log)(`User ${username} already exists and password is correct, syncing with tracking system...`);
406
+ // User exists and can authenticate, sync with tracking system
407
+ const userPub = authTestResult.userPub;
408
+ // Check if user exists in our tracking system
409
+ const existingUser = await this.checkUsernameExists(username);
410
+ if (!existingUser) {
411
+ (0, logger_1.log)(`User ${username} not in tracking system, adding them...`);
412
+ // Add user to our tracking system
413
+ const userMetadata = {
414
+ username: username,
415
+ pub: userPub,
416
+ createdAt: Date.now(),
417
+ lastLogin: Date.now(),
418
+ };
419
+ // Save user metadata
420
+ await new Promise((resolve) => {
421
+ this.gun.get(userPub).put(userMetadata, (ack) => {
422
+ if (ack.err) {
423
+ (0, logger_1.logError)(`Warning: Failed to save user metadata: ${ack.err}`);
424
+ }
425
+ else {
426
+ (0, logger_1.log)(`User metadata saved for: ${username}`);
427
+ }
428
+ resolve();
429
+ });
430
+ });
431
+ // Add to users collection
432
+ await new Promise((resolve) => {
433
+ this.gun.get("users").set(this.gun.get(userPub), (ack) => {
434
+ if (ack.err) {
435
+ (0, logger_1.logError)(`Warning: Failed to add user to collection: ${ack.err}`);
436
+ }
437
+ else {
438
+ (0, logger_1.log)(`User added to collection: ${username}`);
439
+ }
440
+ resolve();
441
+ });
442
+ });
443
+ // Create username mapping
444
+ await new Promise((resolve) => {
445
+ this.gun
446
+ .get("usernames")
447
+ .get(username)
448
+ .put(userPub, (ack) => {
449
+ if (ack.err) {
450
+ (0, logger_1.logError)(`Warning: Could not create username mapping: ${ack.err}`);
451
+ }
452
+ else {
453
+ (0, logger_1.log)(`Username mapping created: ${username} -> ${userPub}`);
454
+ }
455
+ resolve();
456
+ });
457
+ });
458
+ }
388
459
  return {
389
- success: false,
390
- error: `User already created!`,
460
+ success: true,
461
+ userPub: userPub,
462
+ username: username,
463
+ message: "User already exists and was synced with tracking system",
391
464
  };
392
465
  }
393
- // Attempt to create user directly with Gun.js
466
+ // User doesn't exist, attempt to create new user
467
+ (0, logger_1.log)(`Creating new user: ${username}`);
394
468
  const createResult = await new Promise((resolve) => {
395
469
  this.gun.user().create(username, password, (ack) => {
396
470
  if (ack.err) {
@@ -404,145 +478,91 @@ class GunDB {
404
478
  });
405
479
  });
406
480
  if (!createResult.success) {
407
- // If Gun.js creation fails with "User already created", try login instead
408
- if (createResult.error &&
409
- createResult.error.includes("User already created")) {
410
- (0, logger_1.log)(`User ${username} already exists in Gun.js, attempting login...`);
411
- try {
412
- const loginResult = await this.login(username, password);
413
- if (loginResult.success) {
414
- (0, logger_1.log)(`Login successful after failed registration for: ${username}`);
415
- return {
416
- success: true,
417
- userPub: loginResult.userPub,
418
- username: loginResult.username,
419
- };
420
- }
421
- else {
422
- return {
423
- success: false,
424
- error: `User already created!`,
425
- };
426
- }
481
+ return createResult;
482
+ }
483
+ // User created successfully, now authenticate to get the userPub
484
+ const authResult = await new Promise((resolve) => {
485
+ this.gun.user().auth(username, password, (ack) => {
486
+ if (ack.err) {
487
+ (0, logger_1.logError)(`Authentication after creation failed: ${ack.err}`);
488
+ resolve({ success: false, error: ack.err });
427
489
  }
428
- catch (loginError) {
429
- (0, logger_1.logError)(`Login after failed registration error: ${loginError}`);
430
- return {
431
- success: false,
432
- error: `User already created!`,
433
- };
490
+ else {
491
+ resolve({ success: true, userPub: this.gun.user().is?.pub });
434
492
  }
435
- }
436
- return createResult;
493
+ });
494
+ });
495
+ if (!authResult.success) {
496
+ return {
497
+ success: false,
498
+ error: "User created but authentication failed",
499
+ };
437
500
  }
438
- // Store user metadata with improved safety and wait for confirmation
501
+ const userPub = authResult.userPub;
502
+ (0, logger_1.log)(`User authentication successful after creation: ${username} (${userPub})`);
503
+ // Add to tracking system
504
+ const userMetadata = {
505
+ username: username,
506
+ pub: userPub,
507
+ createdAt: Date.now(),
508
+ lastLogin: Date.now(),
509
+ };
510
+ // Save user metadata (best effort)
439
511
  try {
440
- const userNode = this.gun.get(createResult.pub);
441
- const userMetadata = {
442
- username: username,
443
- pub: createResult.pub,
444
- createdAt: Date.now(),
445
- };
446
- // Save user metadata
447
- await new Promise((resolve, reject) => {
448
- userNode.put(userMetadata, (ack) => {
512
+ await new Promise((resolve) => {
513
+ this.gun.get(userPub).put(userMetadata, (ack) => {
449
514
  if (ack.err) {
450
515
  (0, logger_1.logError)(`Warning: Failed to save user metadata: ${ack.err}`);
451
- resolve(); // Don't fail registration for this
452
516
  }
453
517
  else {
454
518
  (0, logger_1.log)(`User metadata saved for: ${username}`);
455
- resolve();
456
519
  }
520
+ resolve();
457
521
  });
458
522
  });
459
- // Add to users collection and wait for confirmation
460
- await new Promise((resolve, reject) => {
461
- this.gun.get("users").set(userNode, (ack) => {
523
+ // Add to users collection
524
+ await new Promise((resolve) => {
525
+ this.gun.get("users").set(this.gun.get(userPub), (ack) => {
462
526
  if (ack.err) {
463
527
  (0, logger_1.logError)(`Warning: Failed to add user to collection: ${ack.err}`);
464
- resolve(); // Don't fail registration for this
465
528
  }
466
529
  else {
467
530
  (0, logger_1.log)(`User added to collection: ${username}`);
468
- resolve();
469
531
  }
532
+ resolve();
470
533
  });
471
534
  });
472
- // Create a username -> pub mapping for faster lookups
473
- await new Promise((resolve, reject) => {
535
+ // Create username mapping
536
+ await new Promise((resolve) => {
474
537
  this.gun
475
538
  .get("usernames")
476
539
  .get(username)
477
- .put(createResult.pub, (ack) => {
540
+ .put(userPub, (ack) => {
478
541
  if (ack.err) {
479
542
  (0, logger_1.logError)(`Warning: Could not create username mapping: ${ack.err}`);
480
- resolve(); // Don't fail registration for this
481
543
  }
482
544
  else {
483
- (0, logger_1.log)(`Username mapping created: ${username} -> ${createResult.pub}`);
484
- resolve();
545
+ (0, logger_1.log)(`Username mapping created: ${username} -> ${userPub}`);
485
546
  }
547
+ resolve();
486
548
  });
487
549
  });
488
550
  }
489
- catch (metadataError) {
490
- (0, logger_1.logError)(`Warning: Could not store user metadata: ${metadataError}`);
491
- // Continue with login attempt even if metadata storage fails
492
- }
493
- // Login after creation with retry mechanism
494
- (0, logger_1.log)(`Attempting login after registration for: ${username}`);
495
- let loginAttempts = 0;
496
- const maxAttempts = 3;
497
- while (loginAttempts < maxAttempts) {
498
- try {
499
- const loginResult = await this.login(username, password);
500
- if (loginResult.success) {
501
- (0, logger_1.log)(`Login after registration successful for: ${username}`);
502
- return {
503
- success: true,
504
- userPub: loginResult.userPub,
505
- username: loginResult.username,
506
- };
507
- }
508
- else {
509
- loginAttempts++;
510
- if (loginAttempts < maxAttempts) {
511
- (0, logger_1.log)(`Login attempt ${loginAttempts} failed, retrying...`);
512
- await new Promise((resolve) => setTimeout(resolve, 1000 * loginAttempts));
513
- }
514
- else {
515
- (0, logger_1.logError)(`Login after registration failed after ${maxAttempts} attempts: ${loginResult.error}`);
516
- return {
517
- success: false,
518
- error: `Registration completed but login failed: ${loginResult.error}`,
519
- };
520
- }
521
- }
522
- }
523
- catch (loginError) {
524
- loginAttempts++;
525
- if (loginAttempts >= maxAttempts) {
526
- (0, logger_1.logError)(`Exception during post-registration login: ${loginError}`);
527
- return {
528
- success: false,
529
- error: "Exception during post-registration login",
530
- };
531
- }
532
- await new Promise((resolve) => setTimeout(resolve, 1000 * loginAttempts));
533
- }
551
+ catch (trackingError) {
552
+ (0, logger_1.logError)(`Warning: Could not update tracking system: ${trackingError}`);
553
+ // Don't fail signup for tracking errors
534
554
  }
555
+ this._savePair();
535
556
  return {
536
- success: false,
537
- error: "Failed to login after registration",
557
+ success: true,
558
+ userPub,
559
+ username,
560
+ message: "User created successfully",
538
561
  };
539
562
  }
540
563
  catch (error) {
541
- (0, logger_1.logError)(`Unexpected error during registration flow: ${error}`);
542
- return {
543
- success: false,
544
- error: `Unexpected error during registration: ${error}`,
545
- };
564
+ (0, logger_1.logError)(`Exception during signup for ${username}: ${error}`);
565
+ return { success: false, error: String(error) };
546
566
  }
547
567
  }
548
568
  /**
@@ -1086,4 +1106,4 @@ class GunDB {
1086
1106
  // Errors
1087
1107
  static Errors = GunErrors;
1088
1108
  }
1089
- exports.GunDB = GunDB;
1109
+ exports.GunInstance = GunInstance;
@@ -1,26 +1,9 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.app_scoped = exports.getArrayFromIndexedObject = exports.getIndexedObjectFromArray = exports.qs = exports.getSet = exports.getUUID = exports.getTargetPub = exports.getPub = exports.getId = exports.derive = exports.SEA = exports.Gun = exports.GunDB = void 0;
3
+ exports.SEA = exports.Gun = exports.GunInstance = void 0;
7
4
  // Export the main class
8
- var instance_1 = require("./instance");
9
- Object.defineProperty(exports, "GunDB", { enumerable: true, get: function () { return instance_1.GunDB; } });
5
+ var gunInstance_1 = require("./gunInstance");
6
+ Object.defineProperty(exports, "GunInstance", { enumerable: true, get: function () { return gunInstance_1.GunInstance; } });
10
7
  var gun_es_1 = require("./gun-es/gun-es");
11
8
  Object.defineProperty(exports, "Gun", { enumerable: true, get: function () { return gun_es_1.Gun; } });
12
9
  Object.defineProperty(exports, "SEA", { enumerable: true, get: function () { return gun_es_1.SEA; } });
13
- // Export derive functionality
14
- var derive_1 = require("./derive");
15
- Object.defineProperty(exports, "derive", { enumerable: true, get: function () { return __importDefault(derive_1).default; } });
16
- // Export utils
17
- var utils_1 = require("./utils");
18
- Object.defineProperty(exports, "getId", { enumerable: true, get: function () { return utils_1.getId; } });
19
- Object.defineProperty(exports, "getPub", { enumerable: true, get: function () { return utils_1.getPub; } });
20
- Object.defineProperty(exports, "getTargetPub", { enumerable: true, get: function () { return utils_1.getTargetPub; } });
21
- Object.defineProperty(exports, "getUUID", { enumerable: true, get: function () { return utils_1.getUUID; } });
22
- Object.defineProperty(exports, "getSet", { enumerable: true, get: function () { return utils_1.getSet; } });
23
- Object.defineProperty(exports, "qs", { enumerable: true, get: function () { return utils_1.qs; } });
24
- Object.defineProperty(exports, "getIndexedObjectFromArray", { enumerable: true, get: function () { return utils_1.getIndexedObjectFromArray; } });
25
- Object.defineProperty(exports, "getArrayFromIndexedObject", { enumerable: true, get: function () { return utils_1.getArrayFromIndexedObject; } });
26
- Object.defineProperty(exports, "app_scoped", { enumerable: true, get: function () { return utils_1.app_scoped; } });