@superatomai/sdk-node 0.0.14 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -589,9 +589,11 @@ var BookmarkDataSchema = import_zod3.z.object({
589
589
  updated_at: import_zod3.z.string().optional()
590
590
  });
591
591
  var BookmarksRequestPayloadSchema = import_zod3.z.object({
592
- operation: import_zod3.z.enum(["create", "update", "delete", "getAll", "getOne"]),
592
+ operation: import_zod3.z.enum(["create", "update", "delete", "getAll", "getOne", "getByUser", "getByThread"]),
593
593
  data: import_zod3.z.object({
594
594
  id: import_zod3.z.number().optional(),
595
+ userId: import_zod3.z.number().optional(),
596
+ threadId: import_zod3.z.string().optional(),
595
597
  uiblock: import_zod3.z.any().optional()
596
598
  }).optional()
597
599
  });
@@ -1419,7 +1421,7 @@ async function cleanupUserStorage() {
1419
1421
  }
1420
1422
 
1421
1423
  // src/auth/validator.ts
1422
- function validateUser(credentials) {
1424
+ async function validateUser(credentials, collections) {
1423
1425
  const { username, email, password } = credentials;
1424
1426
  const identifier = username || email;
1425
1427
  logger.debug("[validateUser] Starting user validation");
@@ -1431,7 +1433,39 @@ function validateUser(credentials) {
1431
1433
  error: "Username or email and password are required"
1432
1434
  };
1433
1435
  }
1434
- logger.debug(`[validateUser] Looking up user by identifier: ${identifier}`);
1436
+ if (collections && collections["users"] && collections["users"]["authenticate"]) {
1437
+ logger.debug(`[validateUser] Attempting database authentication for: ${identifier}`);
1438
+ try {
1439
+ const dbResult = await collections["users"]["authenticate"]({
1440
+ identifier,
1441
+ password
1442
+ });
1443
+ logger.info("[validateUser] Database authentication attempt completed", dbResult);
1444
+ if (dbResult && dbResult.success && dbResult.data) {
1445
+ logger.info(`[validateUser] \u2713 User authenticated via database: ${dbResult.data.username}`);
1446
+ return {
1447
+ success: true,
1448
+ data: dbResult.data.username,
1449
+ username: dbResult.data.username,
1450
+ userId: dbResult.data.id
1451
+ };
1452
+ } else {
1453
+ logger.debug(`[validateUser] Database auth failed for ${identifier}: ${dbResult?.error || "Invalid credentials"}`);
1454
+ if (dbResult && dbResult.error === "Invalid credentials") {
1455
+ return {
1456
+ success: false,
1457
+ error: "Invalid credentials"
1458
+ };
1459
+ }
1460
+ }
1461
+ } catch (error) {
1462
+ const errorMsg = error instanceof Error ? error.message : String(error);
1463
+ logger.debug(`[validateUser] Database lookup error: ${errorMsg}, falling back to file storage`);
1464
+ }
1465
+ } else {
1466
+ logger.debug("[validateUser] No users collection available, using file storage only");
1467
+ }
1468
+ logger.info(`[validateUser] Attempting file-based validation for: ${identifier}`);
1435
1469
  const user = findUserByUsernameOrEmail(identifier);
1436
1470
  if (!user) {
1437
1471
  logger.warn(`[validateUser] Validation failed: User not found - ${identifier}`);
@@ -1440,7 +1474,7 @@ function validateUser(credentials) {
1440
1474
  error: "Invalid username or email"
1441
1475
  };
1442
1476
  }
1443
- logger.debug(`[validateUser] User found: ${user.username}, verifying password`);
1477
+ logger.debug(`[validateUser] User found in file storage: ${user.username}, verifying password`);
1444
1478
  const hashedPassword = hashPassword(user.password);
1445
1479
  if (hashedPassword !== password) {
1446
1480
  logger.warn(`[validateUser] Validation failed: Invalid password for user - ${user.username}`);
@@ -1450,19 +1484,18 @@ function validateUser(credentials) {
1450
1484
  error: "Invalid password"
1451
1485
  };
1452
1486
  }
1453
- logger.info(`[validateUser] \u2713 User validated successfully: ${user.username}`);
1454
- logger.debug(`[validateUser] Returning user data for: ${user.username}`);
1487
+ logger.info(`[validateUser] \u2713 User validated via file storage: ${user.username}`);
1455
1488
  return {
1456
1489
  success: true,
1457
1490
  data: user.username,
1458
1491
  username: user.username
1459
1492
  };
1460
1493
  }
1461
- function authenticateAndStoreWsId(credentials, wsId) {
1494
+ async function authenticateAndStoreWsId(credentials, wsId, collections) {
1462
1495
  const identifier = credentials.username || credentials.email;
1463
1496
  logger.debug("[authenticateAndStoreWsId] Starting authentication and WebSocket ID storage");
1464
1497
  logger.debug("[authenticateAndStoreWsId] Validating user credentials");
1465
- const validationResult = validateUser(credentials);
1498
+ const validationResult = await validateUser(credentials, collections);
1466
1499
  if (!validationResult.success) {
1467
1500
  logger.warn(`[authenticateAndStoreWsId] User validation failed for: ${identifier}`);
1468
1501
  return validationResult;
@@ -1474,7 +1507,7 @@ function authenticateAndStoreWsId(credentials, wsId) {
1474
1507
  logger.debug(`[authenticateAndStoreWsId] WebSocket ID ${wsId} associated with user ${username}`);
1475
1508
  return validationResult;
1476
1509
  }
1477
- function verifyAuthToken(authToken) {
1510
+ async function verifyAuthToken(authToken, collections) {
1478
1511
  try {
1479
1512
  logger.debug("[verifyAuthToken] Starting token verification");
1480
1513
  logger.debug("[verifyAuthToken] Decoding base64 token");
@@ -1484,7 +1517,7 @@ function verifyAuthToken(authToken) {
1484
1517
  logger.debug("[verifyAuthToken] Token decoded and parsed successfully");
1485
1518
  logger.debug(`[verifyAuthToken] Token contains username: ${credentials.username ? "\u2713" : "\u2717"}`);
1486
1519
  logger.debug("[verifyAuthToken] Validating credentials from token");
1487
- const result = validateUser(credentials);
1520
+ const result = await validateUser(credentials, collections);
1488
1521
  if (result.success) {
1489
1522
  logger.info(`[verifyAuthToken] \u2713 Token verified successfully for user: ${credentials.username || "unknown"}`);
1490
1523
  } else {
@@ -1503,7 +1536,7 @@ function verifyAuthToken(authToken) {
1503
1536
  }
1504
1537
 
1505
1538
  // src/handlers/auth-login-requests.ts
1506
- async function handleAuthLoginRequest(data, sendMessage) {
1539
+ async function handleAuthLoginRequest(data, collections, sendMessage) {
1507
1540
  try {
1508
1541
  logger.debug("[AUTH_LOGIN_REQ] Parsing incoming auth login request");
1509
1542
  const authRequest = AuthLoginRequestMessageSchema.parse(data);
@@ -1562,12 +1595,12 @@ async function handleAuthLoginRequest(data, sendMessage) {
1562
1595
  }, sendMessage, wsId);
1563
1596
  return;
1564
1597
  }
1565
- logger.info(`[AUTH_LOGIN_REQ ${id}] Credentials validated, authenticating user: ${identifier}`);
1566
- logger.debug(`[AUTH_LOGIN_REQ ${id}] WebSocket ID: ${wsId}`);
1598
+ logger.info(`[AUTH_LOGIN_REQ ${id}] Credentials validated, authenticating user: ${identifier} username: ${username} email: ${email} password: ${password}`);
1567
1599
  logger.debug(`[AUTH_LOGIN_REQ ${id}] Calling authenticateAndStoreWsId for user: ${identifier}`);
1568
- const authResult = authenticateAndStoreWsId(
1600
+ const authResult = await authenticateAndStoreWsId(
1569
1601
  { username, email, password },
1570
- wsId
1602
+ wsId,
1603
+ collections
1571
1604
  );
1572
1605
  logger.info(`[AUTH_LOGIN_REQ ${id}] Authentication result for ${identifier}: ${authResult.success ? "success" : "failed"}`);
1573
1606
  if (!authResult.success) {
@@ -1619,7 +1652,7 @@ function sendDataResponse2(id, res, sendMessage, clientId) {
1619
1652
  }
1620
1653
 
1621
1654
  // src/handlers/auth-verify-request.ts
1622
- async function handleAuthVerifyRequest(data, sendMessage) {
1655
+ async function handleAuthVerifyRequest(data, collections, sendMessage) {
1623
1656
  try {
1624
1657
  logger.debug("[AUTH_VERIFY_REQ] Parsing incoming auth verify request");
1625
1658
  const authRequest = AuthVerifyRequestMessageSchema.parse(data);
@@ -1649,7 +1682,7 @@ async function handleAuthVerifyRequest(data, sendMessage) {
1649
1682
  logger.debug(`[AUTH_VERIFY_REQ ${id}] WebSocket ID: ${wsId}`);
1650
1683
  logger.debug(`[AUTH_VERIFY_REQ ${id}] Calling verifyAuthToken`);
1651
1684
  const startTime = Date.now();
1652
- const authResult = verifyAuthToken(token);
1685
+ const authResult = await verifyAuthToken(token, collections);
1653
1686
  const verificationTime = Date.now() - startTime;
1654
1687
  logger.info(`[AUTH_VERIFY_REQ ${id}] Token verification completed in ${verificationTime}ms - ${authResult.success ? "valid" : "invalid"}`);
1655
1688
  if (!authResult.success) {
@@ -3699,13 +3732,13 @@ var BaseLLM = class {
3699
3732
  */
3700
3733
  async adaptUIBlockParameters(currentUserPrompt, originalUserPrompt, matchedUIBlock, apiKey, logCollector) {
3701
3734
  try {
3702
- if (!matchedUIBlock || !matchedUIBlock.generatedComponentMetadata) {
3735
+ const component = matchedUIBlock?.generatedComponentMetadata || matchedUIBlock?.component;
3736
+ if (!matchedUIBlock || !component) {
3703
3737
  return {
3704
3738
  success: false,
3705
3739
  explanation: "No component found in matched UI block"
3706
3740
  };
3707
3741
  }
3708
- const component = matchedUIBlock.generatedComponentMetadata;
3709
3742
  const schemaDoc = schema.generateSchemaDocumentation();
3710
3743
  const prompts = await promptLoader.loadPrompts("adapt-ui-block-params", {
3711
3744
  ORIGINAL_USER_PROMPT: originalUserPrompt,
@@ -4810,6 +4843,15 @@ var UILogCollector = class {
4810
4843
  };
4811
4844
 
4812
4845
  // src/utils/conversation-saver.ts
4846
+ function transformUIBlockForDB(uiblock, userPrompt, uiBlockId) {
4847
+ const component = uiblock?.generatedComponentMetadata && Object.keys(uiblock.generatedComponentMetadata).length > 0 ? uiblock.generatedComponentMetadata : null;
4848
+ return {
4849
+ id: uiBlockId || uiblock?.id || "",
4850
+ component,
4851
+ analysis: uiblock?.textResponse || null,
4852
+ user_prompt: userPrompt || uiblock?.userQuestion || ""
4853
+ };
4854
+ }
4813
4855
  async function saveConversation(params) {
4814
4856
  const { userId, userPrompt, uiblock, uiBlockId, threadId, collections } = params;
4815
4857
  if (!userId) {
@@ -4864,10 +4906,12 @@ async function saveConversation(params) {
4864
4906
  error: `Invalid userId: ${userId} (not a valid number)`
4865
4907
  };
4866
4908
  }
4909
+ const dbUIBlock = transformUIBlockForDB(uiblock, userPrompt, uiBlockId);
4910
+ logger.debug(`[CONVERSATION_SAVER] Transformed UIBlock for DB: ${JSON.stringify(dbUIBlock)}`);
4867
4911
  const saveResult = await collections["user-conversations"]["create"]({
4868
4912
  userId: userIdNumber,
4869
4913
  userPrompt,
4870
- uiblock,
4914
+ uiblock: dbUIBlock,
4871
4915
  threadId
4872
4916
  });
4873
4917
  if (!saveResult?.success) {
@@ -4884,7 +4928,8 @@ async function saveConversation(params) {
4884
4928
  const embedResult = await collections["conversation-history"]["embed"]({
4885
4929
  uiBlockId,
4886
4930
  userPrompt,
4887
- uiBlock: uiblock,
4931
+ uiBlock: dbUIBlock,
4932
+ // Use the transformed UIBlock
4888
4933
  userId: userIdNumber
4889
4934
  });
4890
4935
  if (embedResult?.success) {
@@ -6184,13 +6229,15 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6184
6229
  const { id, payload, from } = request;
6185
6230
  const { operation, data: requestData } = payload;
6186
6231
  const bookmarkId = requestData?.id;
6232
+ const userId = requestData?.userId;
6233
+ const threadId = requestData?.threadId;
6187
6234
  const uiblock = requestData?.uiblock;
6188
6235
  switch (operation) {
6189
6236
  case "create":
6190
- await handleCreate4(id, uiblock, executeCollection, sendMessage, from.id);
6237
+ await handleCreate4(id, userId, threadId, uiblock, executeCollection, sendMessage, from.id);
6191
6238
  break;
6192
6239
  case "update":
6193
- await handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMessage, from.id);
6240
+ await handleUpdate4(id, bookmarkId, threadId, uiblock, executeCollection, sendMessage, from.id);
6194
6241
  break;
6195
6242
  case "delete":
6196
6243
  await handleDelete4(id, bookmarkId, executeCollection, sendMessage, from.id);
@@ -6201,6 +6248,12 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6201
6248
  case "getOne":
6202
6249
  await handleGetOne4(id, bookmarkId, executeCollection, sendMessage, from.id);
6203
6250
  break;
6251
+ case "getByUser":
6252
+ await handleGetByUser(id, userId, threadId, executeCollection, sendMessage, from.id);
6253
+ break;
6254
+ case "getByThread":
6255
+ await handleGetByThread(id, threadId, executeCollection, sendMessage, from.id);
6256
+ break;
6204
6257
  default:
6205
6258
  sendResponse6(id, {
6206
6259
  success: false,
@@ -6215,7 +6268,14 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6215
6268
  }, sendMessage);
6216
6269
  }
6217
6270
  }
6218
- async function handleCreate4(id, uiblock, executeCollection, sendMessage, clientId) {
6271
+ async function handleCreate4(id, userId, threadId, uiblock, executeCollection, sendMessage, clientId) {
6272
+ if (!userId) {
6273
+ sendResponse6(id, {
6274
+ success: false,
6275
+ error: "userId is required"
6276
+ }, sendMessage, clientId);
6277
+ return;
6278
+ }
6219
6279
  if (!uiblock) {
6220
6280
  sendResponse6(id, {
6221
6281
  success: false,
@@ -6224,7 +6284,7 @@ async function handleCreate4(id, uiblock, executeCollection, sendMessage, client
6224
6284
  return;
6225
6285
  }
6226
6286
  try {
6227
- const result = await executeCollection("bookmarks", "create", { uiblock });
6287
+ const result = await executeCollection("bookmarks", "create", { userId, threadId, uiblock });
6228
6288
  sendResponse6(id, {
6229
6289
  success: true,
6230
6290
  data: result.data,
@@ -6238,7 +6298,7 @@ async function handleCreate4(id, uiblock, executeCollection, sendMessage, client
6238
6298
  }, sendMessage, clientId);
6239
6299
  }
6240
6300
  }
6241
- async function handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMessage, clientId) {
6301
+ async function handleUpdate4(id, bookmarkId, threadId, uiblock, executeCollection, sendMessage, clientId) {
6242
6302
  if (!bookmarkId) {
6243
6303
  sendResponse6(id, {
6244
6304
  success: false,
@@ -6254,7 +6314,7 @@ async function handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMes
6254
6314
  return;
6255
6315
  }
6256
6316
  try {
6257
- const result = await executeCollection("bookmarks", "update", { id: bookmarkId, uiblock });
6317
+ const result = await executeCollection("bookmarks", "update", { id: bookmarkId, threadId, uiblock });
6258
6318
  sendResponse6(id, {
6259
6319
  success: true,
6260
6320
  data: result.data,
@@ -6331,6 +6391,54 @@ async function handleGetOne4(id, bookmarkId, executeCollection, sendMessage, cli
6331
6391
  }, sendMessage, clientId);
6332
6392
  }
6333
6393
  }
6394
+ async function handleGetByUser(id, userId, threadId, executeCollection, sendMessage, clientId) {
6395
+ if (!userId) {
6396
+ sendResponse6(id, {
6397
+ success: false,
6398
+ error: "userId is required"
6399
+ }, sendMessage, clientId);
6400
+ return;
6401
+ }
6402
+ try {
6403
+ const result = await executeCollection("bookmarks", "getByUser", { userId, threadId });
6404
+ sendResponse6(id, {
6405
+ success: true,
6406
+ data: result.data,
6407
+ count: result.count,
6408
+ message: `Retrieved ${result.count} bookmarks for user ${userId}`
6409
+ }, sendMessage, clientId);
6410
+ logger.info(`Retrieved bookmarks for user ${userId} (count: ${result.count})`);
6411
+ } catch (error) {
6412
+ sendResponse6(id, {
6413
+ success: false,
6414
+ error: error instanceof Error ? error.message : "Failed to get bookmarks by user"
6415
+ }, sendMessage, clientId);
6416
+ }
6417
+ }
6418
+ async function handleGetByThread(id, threadId, executeCollection, sendMessage, clientId) {
6419
+ if (!threadId) {
6420
+ sendResponse6(id, {
6421
+ success: false,
6422
+ error: "threadId is required"
6423
+ }, sendMessage, clientId);
6424
+ return;
6425
+ }
6426
+ try {
6427
+ const result = await executeCollection("bookmarks", "getByThread", { threadId });
6428
+ sendResponse6(id, {
6429
+ success: true,
6430
+ data: result.data,
6431
+ count: result.count,
6432
+ message: `Retrieved ${result.count} bookmarks for thread ${threadId}`
6433
+ }, sendMessage, clientId);
6434
+ logger.info(`Retrieved bookmarks for thread ${threadId} (count: ${result.count})`);
6435
+ } catch (error) {
6436
+ sendResponse6(id, {
6437
+ success: false,
6438
+ error: error instanceof Error ? error.message : "Failed to get bookmarks by thread"
6439
+ }, sendMessage, clientId);
6440
+ }
6441
+ }
6334
6442
  function sendResponse6(id, res, sendMessage, clientId) {
6335
6443
  const response = {
6336
6444
  id: id || "unknown",
@@ -7317,12 +7425,12 @@ var SuperatomSDK = class {
7317
7425
  });
7318
7426
  break;
7319
7427
  case "AUTH_LOGIN_REQ":
7320
- handleAuthLoginRequest(parsed, (msg) => this.send(msg)).catch((error) => {
7428
+ handleAuthLoginRequest(parsed, this.collections, (msg) => this.send(msg)).catch((error) => {
7321
7429
  logger.error("Failed to handle auth login request:", error);
7322
7430
  });
7323
7431
  break;
7324
7432
  case "AUTH_VERIFY_REQ":
7325
- handleAuthVerifyRequest(parsed, (msg) => this.send(msg)).catch((error) => {
7433
+ handleAuthVerifyRequest(parsed, this.collections, (msg) => this.send(msg)).catch((error) => {
7326
7434
  logger.error("Failed to handle auth verify request:", error);
7327
7435
  });
7328
7436
  break;