@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.mjs CHANGED
@@ -549,9 +549,11 @@ var BookmarkDataSchema = z3.object({
549
549
  updated_at: z3.string().optional()
550
550
  });
551
551
  var BookmarksRequestPayloadSchema = z3.object({
552
- operation: z3.enum(["create", "update", "delete", "getAll", "getOne"]),
552
+ operation: z3.enum(["create", "update", "delete", "getAll", "getOne", "getByUser", "getByThread"]),
553
553
  data: z3.object({
554
554
  id: z3.number().optional(),
555
+ userId: z3.number().optional(),
556
+ threadId: z3.string().optional(),
555
557
  uiblock: z3.any().optional()
556
558
  }).optional()
557
559
  });
@@ -1379,7 +1381,7 @@ async function cleanupUserStorage() {
1379
1381
  }
1380
1382
 
1381
1383
  // src/auth/validator.ts
1382
- function validateUser(credentials) {
1384
+ async function validateUser(credentials, collections) {
1383
1385
  const { username, email, password } = credentials;
1384
1386
  const identifier = username || email;
1385
1387
  logger.debug("[validateUser] Starting user validation");
@@ -1391,7 +1393,39 @@ function validateUser(credentials) {
1391
1393
  error: "Username or email and password are required"
1392
1394
  };
1393
1395
  }
1394
- logger.debug(`[validateUser] Looking up user by identifier: ${identifier}`);
1396
+ if (collections && collections["users"] && collections["users"]["authenticate"]) {
1397
+ logger.debug(`[validateUser] Attempting database authentication for: ${identifier}`);
1398
+ try {
1399
+ const dbResult = await collections["users"]["authenticate"]({
1400
+ identifier,
1401
+ password
1402
+ });
1403
+ logger.info("[validateUser] Database authentication attempt completed", dbResult);
1404
+ if (dbResult && dbResult.success && dbResult.data) {
1405
+ logger.info(`[validateUser] \u2713 User authenticated via database: ${dbResult.data.username}`);
1406
+ return {
1407
+ success: true,
1408
+ data: dbResult.data.username,
1409
+ username: dbResult.data.username,
1410
+ userId: dbResult.data.id
1411
+ };
1412
+ } else {
1413
+ logger.debug(`[validateUser] Database auth failed for ${identifier}: ${dbResult?.error || "Invalid credentials"}`);
1414
+ if (dbResult && dbResult.error === "Invalid credentials") {
1415
+ return {
1416
+ success: false,
1417
+ error: "Invalid credentials"
1418
+ };
1419
+ }
1420
+ }
1421
+ } catch (error) {
1422
+ const errorMsg = error instanceof Error ? error.message : String(error);
1423
+ logger.debug(`[validateUser] Database lookup error: ${errorMsg}, falling back to file storage`);
1424
+ }
1425
+ } else {
1426
+ logger.debug("[validateUser] No users collection available, using file storage only");
1427
+ }
1428
+ logger.info(`[validateUser] Attempting file-based validation for: ${identifier}`);
1395
1429
  const user = findUserByUsernameOrEmail(identifier);
1396
1430
  if (!user) {
1397
1431
  logger.warn(`[validateUser] Validation failed: User not found - ${identifier}`);
@@ -1400,7 +1434,7 @@ function validateUser(credentials) {
1400
1434
  error: "Invalid username or email"
1401
1435
  };
1402
1436
  }
1403
- logger.debug(`[validateUser] User found: ${user.username}, verifying password`);
1437
+ logger.debug(`[validateUser] User found in file storage: ${user.username}, verifying password`);
1404
1438
  const hashedPassword = hashPassword(user.password);
1405
1439
  if (hashedPassword !== password) {
1406
1440
  logger.warn(`[validateUser] Validation failed: Invalid password for user - ${user.username}`);
@@ -1410,19 +1444,18 @@ function validateUser(credentials) {
1410
1444
  error: "Invalid password"
1411
1445
  };
1412
1446
  }
1413
- logger.info(`[validateUser] \u2713 User validated successfully: ${user.username}`);
1414
- logger.debug(`[validateUser] Returning user data for: ${user.username}`);
1447
+ logger.info(`[validateUser] \u2713 User validated via file storage: ${user.username}`);
1415
1448
  return {
1416
1449
  success: true,
1417
1450
  data: user.username,
1418
1451
  username: user.username
1419
1452
  };
1420
1453
  }
1421
- function authenticateAndStoreWsId(credentials, wsId) {
1454
+ async function authenticateAndStoreWsId(credentials, wsId, collections) {
1422
1455
  const identifier = credentials.username || credentials.email;
1423
1456
  logger.debug("[authenticateAndStoreWsId] Starting authentication and WebSocket ID storage");
1424
1457
  logger.debug("[authenticateAndStoreWsId] Validating user credentials");
1425
- const validationResult = validateUser(credentials);
1458
+ const validationResult = await validateUser(credentials, collections);
1426
1459
  if (!validationResult.success) {
1427
1460
  logger.warn(`[authenticateAndStoreWsId] User validation failed for: ${identifier}`);
1428
1461
  return validationResult;
@@ -1434,7 +1467,7 @@ function authenticateAndStoreWsId(credentials, wsId) {
1434
1467
  logger.debug(`[authenticateAndStoreWsId] WebSocket ID ${wsId} associated with user ${username}`);
1435
1468
  return validationResult;
1436
1469
  }
1437
- function verifyAuthToken(authToken) {
1470
+ async function verifyAuthToken(authToken, collections) {
1438
1471
  try {
1439
1472
  logger.debug("[verifyAuthToken] Starting token verification");
1440
1473
  logger.debug("[verifyAuthToken] Decoding base64 token");
@@ -1444,7 +1477,7 @@ function verifyAuthToken(authToken) {
1444
1477
  logger.debug("[verifyAuthToken] Token decoded and parsed successfully");
1445
1478
  logger.debug(`[verifyAuthToken] Token contains username: ${credentials.username ? "\u2713" : "\u2717"}`);
1446
1479
  logger.debug("[verifyAuthToken] Validating credentials from token");
1447
- const result = validateUser(credentials);
1480
+ const result = await validateUser(credentials, collections);
1448
1481
  if (result.success) {
1449
1482
  logger.info(`[verifyAuthToken] \u2713 Token verified successfully for user: ${credentials.username || "unknown"}`);
1450
1483
  } else {
@@ -1463,7 +1496,7 @@ function verifyAuthToken(authToken) {
1463
1496
  }
1464
1497
 
1465
1498
  // src/handlers/auth-login-requests.ts
1466
- async function handleAuthLoginRequest(data, sendMessage) {
1499
+ async function handleAuthLoginRequest(data, collections, sendMessage) {
1467
1500
  try {
1468
1501
  logger.debug("[AUTH_LOGIN_REQ] Parsing incoming auth login request");
1469
1502
  const authRequest = AuthLoginRequestMessageSchema.parse(data);
@@ -1522,12 +1555,12 @@ async function handleAuthLoginRequest(data, sendMessage) {
1522
1555
  }, sendMessage, wsId);
1523
1556
  return;
1524
1557
  }
1525
- logger.info(`[AUTH_LOGIN_REQ ${id}] Credentials validated, authenticating user: ${identifier}`);
1526
- logger.debug(`[AUTH_LOGIN_REQ ${id}] WebSocket ID: ${wsId}`);
1558
+ logger.info(`[AUTH_LOGIN_REQ ${id}] Credentials validated, authenticating user: ${identifier} username: ${username} email: ${email} password: ${password}`);
1527
1559
  logger.debug(`[AUTH_LOGIN_REQ ${id}] Calling authenticateAndStoreWsId for user: ${identifier}`);
1528
- const authResult = authenticateAndStoreWsId(
1560
+ const authResult = await authenticateAndStoreWsId(
1529
1561
  { username, email, password },
1530
- wsId
1562
+ wsId,
1563
+ collections
1531
1564
  );
1532
1565
  logger.info(`[AUTH_LOGIN_REQ ${id}] Authentication result for ${identifier}: ${authResult.success ? "success" : "failed"}`);
1533
1566
  if (!authResult.success) {
@@ -1579,7 +1612,7 @@ function sendDataResponse2(id, res, sendMessage, clientId) {
1579
1612
  }
1580
1613
 
1581
1614
  // src/handlers/auth-verify-request.ts
1582
- async function handleAuthVerifyRequest(data, sendMessage) {
1615
+ async function handleAuthVerifyRequest(data, collections, sendMessage) {
1583
1616
  try {
1584
1617
  logger.debug("[AUTH_VERIFY_REQ] Parsing incoming auth verify request");
1585
1618
  const authRequest = AuthVerifyRequestMessageSchema.parse(data);
@@ -1609,7 +1642,7 @@ async function handleAuthVerifyRequest(data, sendMessage) {
1609
1642
  logger.debug(`[AUTH_VERIFY_REQ ${id}] WebSocket ID: ${wsId}`);
1610
1643
  logger.debug(`[AUTH_VERIFY_REQ ${id}] Calling verifyAuthToken`);
1611
1644
  const startTime = Date.now();
1612
- const authResult = verifyAuthToken(token);
1645
+ const authResult = await verifyAuthToken(token, collections);
1613
1646
  const verificationTime = Date.now() - startTime;
1614
1647
  logger.info(`[AUTH_VERIFY_REQ ${id}] Token verification completed in ${verificationTime}ms - ${authResult.success ? "valid" : "invalid"}`);
1615
1648
  if (!authResult.success) {
@@ -3659,13 +3692,13 @@ var BaseLLM = class {
3659
3692
  */
3660
3693
  async adaptUIBlockParameters(currentUserPrompt, originalUserPrompt, matchedUIBlock, apiKey, logCollector) {
3661
3694
  try {
3662
- if (!matchedUIBlock || !matchedUIBlock.generatedComponentMetadata) {
3695
+ const component = matchedUIBlock?.generatedComponentMetadata || matchedUIBlock?.component;
3696
+ if (!matchedUIBlock || !component) {
3663
3697
  return {
3664
3698
  success: false,
3665
3699
  explanation: "No component found in matched UI block"
3666
3700
  };
3667
3701
  }
3668
- const component = matchedUIBlock.generatedComponentMetadata;
3669
3702
  const schemaDoc = schema.generateSchemaDocumentation();
3670
3703
  const prompts = await promptLoader.loadPrompts("adapt-ui-block-params", {
3671
3704
  ORIGINAL_USER_PROMPT: originalUserPrompt,
@@ -4770,6 +4803,15 @@ var UILogCollector = class {
4770
4803
  };
4771
4804
 
4772
4805
  // src/utils/conversation-saver.ts
4806
+ function transformUIBlockForDB(uiblock, userPrompt, uiBlockId) {
4807
+ const component = uiblock?.generatedComponentMetadata && Object.keys(uiblock.generatedComponentMetadata).length > 0 ? uiblock.generatedComponentMetadata : null;
4808
+ return {
4809
+ id: uiBlockId || uiblock?.id || "",
4810
+ component,
4811
+ analysis: uiblock?.textResponse || null,
4812
+ user_prompt: userPrompt || uiblock?.userQuestion || ""
4813
+ };
4814
+ }
4773
4815
  async function saveConversation(params) {
4774
4816
  const { userId, userPrompt, uiblock, uiBlockId, threadId, collections } = params;
4775
4817
  if (!userId) {
@@ -4824,10 +4866,12 @@ async function saveConversation(params) {
4824
4866
  error: `Invalid userId: ${userId} (not a valid number)`
4825
4867
  };
4826
4868
  }
4869
+ const dbUIBlock = transformUIBlockForDB(uiblock, userPrompt, uiBlockId);
4870
+ logger.debug(`[CONVERSATION_SAVER] Transformed UIBlock for DB: ${JSON.stringify(dbUIBlock)}`);
4827
4871
  const saveResult = await collections["user-conversations"]["create"]({
4828
4872
  userId: userIdNumber,
4829
4873
  userPrompt,
4830
- uiblock,
4874
+ uiblock: dbUIBlock,
4831
4875
  threadId
4832
4876
  });
4833
4877
  if (!saveResult?.success) {
@@ -4844,7 +4888,8 @@ async function saveConversation(params) {
4844
4888
  const embedResult = await collections["conversation-history"]["embed"]({
4845
4889
  uiBlockId,
4846
4890
  userPrompt,
4847
- uiBlock: uiblock,
4891
+ uiBlock: dbUIBlock,
4892
+ // Use the transformed UIBlock
4848
4893
  userId: userIdNumber
4849
4894
  });
4850
4895
  if (embedResult?.success) {
@@ -6144,13 +6189,15 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6144
6189
  const { id, payload, from } = request;
6145
6190
  const { operation, data: requestData } = payload;
6146
6191
  const bookmarkId = requestData?.id;
6192
+ const userId = requestData?.userId;
6193
+ const threadId = requestData?.threadId;
6147
6194
  const uiblock = requestData?.uiblock;
6148
6195
  switch (operation) {
6149
6196
  case "create":
6150
- await handleCreate4(id, uiblock, executeCollection, sendMessage, from.id);
6197
+ await handleCreate4(id, userId, threadId, uiblock, executeCollection, sendMessage, from.id);
6151
6198
  break;
6152
6199
  case "update":
6153
- await handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMessage, from.id);
6200
+ await handleUpdate4(id, bookmarkId, threadId, uiblock, executeCollection, sendMessage, from.id);
6154
6201
  break;
6155
6202
  case "delete":
6156
6203
  await handleDelete4(id, bookmarkId, executeCollection, sendMessage, from.id);
@@ -6161,6 +6208,12 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6161
6208
  case "getOne":
6162
6209
  await handleGetOne4(id, bookmarkId, executeCollection, sendMessage, from.id);
6163
6210
  break;
6211
+ case "getByUser":
6212
+ await handleGetByUser(id, userId, threadId, executeCollection, sendMessage, from.id);
6213
+ break;
6214
+ case "getByThread":
6215
+ await handleGetByThread(id, threadId, executeCollection, sendMessage, from.id);
6216
+ break;
6164
6217
  default:
6165
6218
  sendResponse6(id, {
6166
6219
  success: false,
@@ -6175,7 +6228,14 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6175
6228
  }, sendMessage);
6176
6229
  }
6177
6230
  }
6178
- async function handleCreate4(id, uiblock, executeCollection, sendMessage, clientId) {
6231
+ async function handleCreate4(id, userId, threadId, uiblock, executeCollection, sendMessage, clientId) {
6232
+ if (!userId) {
6233
+ sendResponse6(id, {
6234
+ success: false,
6235
+ error: "userId is required"
6236
+ }, sendMessage, clientId);
6237
+ return;
6238
+ }
6179
6239
  if (!uiblock) {
6180
6240
  sendResponse6(id, {
6181
6241
  success: false,
@@ -6184,7 +6244,7 @@ async function handleCreate4(id, uiblock, executeCollection, sendMessage, client
6184
6244
  return;
6185
6245
  }
6186
6246
  try {
6187
- const result = await executeCollection("bookmarks", "create", { uiblock });
6247
+ const result = await executeCollection("bookmarks", "create", { userId, threadId, uiblock });
6188
6248
  sendResponse6(id, {
6189
6249
  success: true,
6190
6250
  data: result.data,
@@ -6198,7 +6258,7 @@ async function handleCreate4(id, uiblock, executeCollection, sendMessage, client
6198
6258
  }, sendMessage, clientId);
6199
6259
  }
6200
6260
  }
6201
- async function handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMessage, clientId) {
6261
+ async function handleUpdate4(id, bookmarkId, threadId, uiblock, executeCollection, sendMessage, clientId) {
6202
6262
  if (!bookmarkId) {
6203
6263
  sendResponse6(id, {
6204
6264
  success: false,
@@ -6214,7 +6274,7 @@ async function handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMes
6214
6274
  return;
6215
6275
  }
6216
6276
  try {
6217
- const result = await executeCollection("bookmarks", "update", { id: bookmarkId, uiblock });
6277
+ const result = await executeCollection("bookmarks", "update", { id: bookmarkId, threadId, uiblock });
6218
6278
  sendResponse6(id, {
6219
6279
  success: true,
6220
6280
  data: result.data,
@@ -6291,6 +6351,54 @@ async function handleGetOne4(id, bookmarkId, executeCollection, sendMessage, cli
6291
6351
  }, sendMessage, clientId);
6292
6352
  }
6293
6353
  }
6354
+ async function handleGetByUser(id, userId, threadId, executeCollection, sendMessage, clientId) {
6355
+ if (!userId) {
6356
+ sendResponse6(id, {
6357
+ success: false,
6358
+ error: "userId is required"
6359
+ }, sendMessage, clientId);
6360
+ return;
6361
+ }
6362
+ try {
6363
+ const result = await executeCollection("bookmarks", "getByUser", { userId, threadId });
6364
+ sendResponse6(id, {
6365
+ success: true,
6366
+ data: result.data,
6367
+ count: result.count,
6368
+ message: `Retrieved ${result.count} bookmarks for user ${userId}`
6369
+ }, sendMessage, clientId);
6370
+ logger.info(`Retrieved bookmarks for user ${userId} (count: ${result.count})`);
6371
+ } catch (error) {
6372
+ sendResponse6(id, {
6373
+ success: false,
6374
+ error: error instanceof Error ? error.message : "Failed to get bookmarks by user"
6375
+ }, sendMessage, clientId);
6376
+ }
6377
+ }
6378
+ async function handleGetByThread(id, threadId, executeCollection, sendMessage, clientId) {
6379
+ if (!threadId) {
6380
+ sendResponse6(id, {
6381
+ success: false,
6382
+ error: "threadId is required"
6383
+ }, sendMessage, clientId);
6384
+ return;
6385
+ }
6386
+ try {
6387
+ const result = await executeCollection("bookmarks", "getByThread", { threadId });
6388
+ sendResponse6(id, {
6389
+ success: true,
6390
+ data: result.data,
6391
+ count: result.count,
6392
+ message: `Retrieved ${result.count} bookmarks for thread ${threadId}`
6393
+ }, sendMessage, clientId);
6394
+ logger.info(`Retrieved bookmarks for thread ${threadId} (count: ${result.count})`);
6395
+ } catch (error) {
6396
+ sendResponse6(id, {
6397
+ success: false,
6398
+ error: error instanceof Error ? error.message : "Failed to get bookmarks by thread"
6399
+ }, sendMessage, clientId);
6400
+ }
6401
+ }
6294
6402
  function sendResponse6(id, res, sendMessage, clientId) {
6295
6403
  const response = {
6296
6404
  id: id || "unknown",
@@ -7277,12 +7385,12 @@ var SuperatomSDK = class {
7277
7385
  });
7278
7386
  break;
7279
7387
  case "AUTH_LOGIN_REQ":
7280
- handleAuthLoginRequest(parsed, (msg) => this.send(msg)).catch((error) => {
7388
+ handleAuthLoginRequest(parsed, this.collections, (msg) => this.send(msg)).catch((error) => {
7281
7389
  logger.error("Failed to handle auth login request:", error);
7282
7390
  });
7283
7391
  break;
7284
7392
  case "AUTH_VERIFY_REQ":
7285
- handleAuthVerifyRequest(parsed, (msg) => this.send(msg)).catch((error) => {
7393
+ handleAuthVerifyRequest(parsed, this.collections, (msg) => this.send(msg)).catch((error) => {
7286
7394
  logger.error("Failed to handle auth verify request:", error);
7287
7395
  });
7288
7396
  break;