@mastra/cloudflare-d1 0.0.0-update-stores-peerDeps-20250723031338 → 0.0.0-usechat-duplicate-20251016110554

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
@@ -5,6 +5,7 @@ var storage = require('@mastra/core/storage');
5
5
  var Cloudflare = require('cloudflare');
6
6
  var utils = require('@mastra/core/utils');
7
7
  var agent = require('@mastra/core/agent');
8
+ var scores = require('@mastra/core/scores');
8
9
 
9
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
11
 
@@ -540,7 +541,6 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
540
541
  keys: { id: threadId }
541
542
  });
542
543
  if (!thread) return null;
543
- console.log("thread", thread);
544
544
  try {
545
545
  return {
546
546
  ...thread,
@@ -809,6 +809,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
809
809
  }
810
810
  }
811
811
  async _getIncludedMessages(threadId, selectBy) {
812
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
812
813
  const include = selectBy?.include;
813
814
  if (!include) return null;
814
815
  const unionQueries = [];
@@ -867,17 +868,19 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
867
868
  }
868
869
  async getMessages({
869
870
  threadId,
871
+ resourceId,
870
872
  selectBy,
871
873
  format
872
874
  }) {
873
- const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
874
- const limit = storage.resolveMessageLimit({
875
- last: selectBy?.last,
876
- defaultLimit: 40
877
- });
878
- const include = selectBy?.include || [];
879
- const messages = [];
880
875
  try {
876
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
877
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
878
+ const limit = storage.resolveMessageLimit({
879
+ last: selectBy?.last,
880
+ defaultLimit: 40
881
+ });
882
+ const include = selectBy?.include || [];
883
+ const messages = [];
881
884
  if (include.length) {
882
885
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
883
886
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -917,7 +920,48 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
917
920
  domain: error.ErrorDomain.STORAGE,
918
921
  category: error.ErrorCategory.THIRD_PARTY,
919
922
  text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
920
- details: { threadId }
923
+ details: { threadId, resourceId: resourceId ?? "" }
924
+ },
925
+ error$1
926
+ );
927
+ this.logger?.error(mastraError.toString());
928
+ this.logger?.trackException(mastraError);
929
+ throw mastraError;
930
+ }
931
+ }
932
+ async getMessagesById({
933
+ messageIds,
934
+ format
935
+ }) {
936
+ if (messageIds.length === 0) return [];
937
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
938
+ const messages = [];
939
+ try {
940
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
941
+ query.orderBy("createdAt", "DESC");
942
+ const { sql, params } = query.build();
943
+ const result = await this.operations.executeQuery({ sql, params });
944
+ if (Array.isArray(result)) messages.push(...result);
945
+ const processedMessages = messages.map((message) => {
946
+ const processedMsg = {};
947
+ for (const [key, value] of Object.entries(message)) {
948
+ if (key === `type` && value === `v2`) continue;
949
+ processedMsg[key] = deserializeValue(value);
950
+ }
951
+ return processedMsg;
952
+ });
953
+ this.logger.debug(`Retrieved ${messages.length} messages`);
954
+ const list = new agent.MessageList().add(processedMessages, "memory");
955
+ if (format === `v1`) return list.get.all.v1();
956
+ return list.get.all.v2();
957
+ } catch (error$1) {
958
+ const mastraError = new error.MastraError(
959
+ {
960
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
961
+ domain: error.ErrorDomain.STORAGE,
962
+ category: error.ErrorCategory.THIRD_PARTY,
963
+ text: `Failed to retrieve messages by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
964
+ details: { messageIds: JSON.stringify(messageIds) }
921
965
  },
922
966
  error$1
923
967
  );
@@ -928,6 +972,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
928
972
  }
929
973
  async getMessagesPaginated({
930
974
  threadId,
975
+ resourceId,
931
976
  selectBy,
932
977
  format
933
978
  }) {
@@ -937,6 +982,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
937
982
  const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
938
983
  const messages = [];
939
984
  try {
985
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
940
986
  if (selectBy?.include?.length) {
941
987
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
942
988
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -1025,7 +1071,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
1025
1071
  domain: error.ErrorDomain.STORAGE,
1026
1072
  category: error.ErrorCategory.THIRD_PARTY,
1027
1073
  text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1028
- details: { threadId }
1074
+ details: { threadId, resourceId: resourceId ?? "" }
1029
1075
  },
1030
1076
  error$1
1031
1077
  );
@@ -1223,13 +1269,12 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1223
1269
  sql,
1224
1270
  params: formattedParams
1225
1271
  });
1226
- if (!response.result) {
1227
- return first ? null : [];
1228
- }
1272
+ const result = response.result || [];
1273
+ const results = result.flatMap((r) => r.results || []);
1229
1274
  if (first) {
1230
- return response.result[0] || null;
1275
+ return results[0] || null;
1231
1276
  }
1232
- return response.result;
1277
+ return results;
1233
1278
  } catch (error$1) {
1234
1279
  throw new error.MastraError(
1235
1280
  {
@@ -1444,6 +1489,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1444
1489
  query.andWhere(`${key} = ?`, value);
1445
1490
  }
1446
1491
  }
1492
+ query.orderBy("createdAt", "DESC");
1447
1493
  query.limit(1);
1448
1494
  const { sql, params } = query.build();
1449
1495
  const result = await this.executeQuery({ sql, params, first: true });
@@ -1528,20 +1574,19 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1528
1574
  }
1529
1575
  };
1530
1576
  function transformScoreRow(row) {
1531
- let input = void 0;
1532
- if (row.input) {
1533
- try {
1534
- input = JSON.parse(row.input);
1535
- } catch {
1536
- input = row.input;
1537
- }
1538
- }
1539
- return {
1540
- ...row,
1541
- input,
1542
- createdAt: row.createdAtZ || row.createdAt,
1543
- updatedAt: row.updatedAtZ || row.updatedAt
1544
- };
1577
+ const deserialized = { ...row };
1578
+ deserialized.input = storage.safelyParseJSON(row.input);
1579
+ deserialized.output = storage.safelyParseJSON(row.output);
1580
+ deserialized.scorer = storage.safelyParseJSON(row.scorer);
1581
+ deserialized.preprocessStepResult = storage.safelyParseJSON(row.preprocessStepResult);
1582
+ deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1583
+ deserialized.metadata = storage.safelyParseJSON(row.metadata);
1584
+ deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1585
+ deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1586
+ deserialized.entity = storage.safelyParseJSON(row.entity);
1587
+ deserialized.createdAt = row.createdAtZ || row.createdAt;
1588
+ deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
1589
+ return deserialized;
1545
1590
  }
1546
1591
  var ScoresStorageD1 = class extends storage.ScoresStorage {
1547
1592
  operations;
@@ -1571,11 +1616,25 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1571
1616
  }
1572
1617
  }
1573
1618
  async saveScore(score) {
1619
+ let parsedScore;
1620
+ try {
1621
+ parsedScore = scores.saveScorePayloadSchema.parse(score);
1622
+ } catch (error$1) {
1623
+ throw new error.MastraError(
1624
+ {
1625
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1626
+ domain: error.ErrorDomain.STORAGE,
1627
+ category: error.ErrorCategory.USER,
1628
+ details: { scoreId: score.id }
1629
+ },
1630
+ error$1
1631
+ );
1632
+ }
1574
1633
  try {
1634
+ const id = crypto.randomUUID();
1575
1635
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1576
- const { input, ...rest } = score;
1577
1636
  const serializedRecord = {};
1578
- for (const [key, value] of Object.entries(rest)) {
1637
+ for (const [key, value] of Object.entries(parsedScore)) {
1579
1638
  if (value !== null && value !== void 0) {
1580
1639
  if (typeof value === "object") {
1581
1640
  serializedRecord[key] = JSON.stringify(value);
@@ -1586,7 +1645,7 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1586
1645
  serializedRecord[key] = null;
1587
1646
  }
1588
1647
  }
1589
- serializedRecord.input = JSON.stringify(input);
1648
+ serializedRecord.id = id;
1590
1649
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1591
1650
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1592
1651
  const columns = Object.keys(serializedRecord);
@@ -1594,7 +1653,7 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1594
1653
  const query = createSqlBuilder().insert(fullTableName, columns, values);
1595
1654
  const { sql, params } = query.build();
1596
1655
  await this.operations.executeQuery({ sql, params });
1597
- const scoreFromDb = await this.getScoreById({ id: score.id });
1656
+ const scoreFromDb = await this.getScoreById({ id });
1598
1657
  return { score: scoreFromDb };
1599
1658
  } catch (error$1) {
1600
1659
  throw new error.MastraError(
@@ -1609,11 +1668,23 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1609
1668
  }
1610
1669
  async getScoresByScorerId({
1611
1670
  scorerId,
1671
+ entityId,
1672
+ entityType,
1673
+ source,
1612
1674
  pagination
1613
1675
  }) {
1614
1676
  try {
1615
1677
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1616
1678
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1679
+ if (entityId) {
1680
+ countQuery.andWhere("entityId = ?", entityId);
1681
+ }
1682
+ if (entityType) {
1683
+ countQuery.andWhere("entityType = ?", entityType);
1684
+ }
1685
+ if (source) {
1686
+ countQuery.andWhere("source = ?", source);
1687
+ }
1617
1688
  const countResult = await this.operations.executeQuery(countQuery.build());
1618
1689
  const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1619
1690
  if (total === 0) {
@@ -1627,7 +1698,17 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1627
1698
  scores: []
1628
1699
  };
1629
1700
  }
1630
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1701
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1702
+ if (entityId) {
1703
+ selectQuery.andWhere("entityId = ?", entityId);
1704
+ }
1705
+ if (entityType) {
1706
+ selectQuery.andWhere("entityType = ?", entityType);
1707
+ }
1708
+ if (source) {
1709
+ selectQuery.andWhere("source = ?", source);
1710
+ }
1711
+ selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1631
1712
  const { sql, params } = selectQuery.build();
1632
1713
  const results = await this.operations.executeQuery({ sql, params });
1633
1714
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
@@ -1740,6 +1821,53 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1740
1821
  );
1741
1822
  }
1742
1823
  }
1824
+ async getScoresBySpan({
1825
+ traceId,
1826
+ spanId,
1827
+ pagination
1828
+ }) {
1829
+ try {
1830
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1831
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1832
+ const countResult = await this.operations.executeQuery(countQuery.build());
1833
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1834
+ if (total === 0) {
1835
+ return {
1836
+ pagination: {
1837
+ total: 0,
1838
+ page: pagination.page,
1839
+ perPage: pagination.perPage,
1840
+ hasMore: false
1841
+ },
1842
+ scores: []
1843
+ };
1844
+ }
1845
+ const limit = pagination.perPage + 1;
1846
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
1847
+ const { sql, params } = selectQuery.build();
1848
+ const results = await this.operations.executeQuery({ sql, params });
1849
+ const rows = Array.isArray(results) ? results : [];
1850
+ const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
1851
+ return {
1852
+ pagination: {
1853
+ total,
1854
+ page: pagination.page,
1855
+ perPage: pagination.perPage,
1856
+ hasMore: rows.length > pagination.perPage
1857
+ },
1858
+ scores
1859
+ };
1860
+ } catch (error$1) {
1861
+ throw new error.MastraError(
1862
+ {
1863
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1864
+ domain: error.ErrorDomain.STORAGE,
1865
+ category: error.ErrorCategory.THIRD_PARTY
1866
+ },
1867
+ error$1
1868
+ );
1869
+ }
1870
+ }
1743
1871
  };
1744
1872
  function isArrayOfRecords2(value) {
1745
1873
  return value && Array.isArray(value) && value.length > 0;
@@ -1817,7 +1945,7 @@ var TracesStorageD1 = class extends storage.TracesStorage {
1817
1945
  const allDataResult = await this.operations.executeQuery(
1818
1946
  createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1819
1947
  );
1820
- console.log("allDataResult", allDataResult);
1948
+ console.info("allDataResult", allDataResult);
1821
1949
  const countResult = await this.operations.executeQuery(countQuery.build());
1822
1950
  const total = Number(countResult?.[0]?.count ?? 0);
1823
1951
  dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
@@ -1869,9 +1997,26 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1869
1997
  super();
1870
1998
  this.operations = operations;
1871
1999
  }
2000
+ updateWorkflowResults({
2001
+ // workflowName,
2002
+ // runId,
2003
+ // stepId,
2004
+ // result,
2005
+ // runtimeContext,
2006
+ }) {
2007
+ throw new Error("Method not implemented.");
2008
+ }
2009
+ updateWorkflowState({
2010
+ // workflowName,
2011
+ // runId,
2012
+ // opts,
2013
+ }) {
2014
+ throw new Error("Method not implemented.");
2015
+ }
1872
2016
  async persistWorkflowSnapshot({
1873
2017
  workflowName,
1874
2018
  runId,
2019
+ resourceId,
1875
2020
  snapshot
1876
2021
  }) {
1877
2022
  const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
@@ -1882,11 +2027,13 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1882
2027
  });
1883
2028
  const persisting = currentSnapshot ? {
1884
2029
  ...currentSnapshot,
2030
+ resourceId,
1885
2031
  snapshot: JSON.stringify(snapshot),
1886
2032
  updatedAt: now
1887
2033
  } : {
1888
2034
  workflow_name: workflowName,
1889
2035
  run_id: runId,
2036
+ resourceId,
1890
2037
  snapshot,
1891
2038
  createdAt: now,
1892
2039
  updatedAt: now
@@ -2151,7 +2298,9 @@ var D1Store = class extends storage.MastraStorage {
2151
2298
  selectByIncludeResourceScope: true,
2152
2299
  resourceWorkingMemory: true,
2153
2300
  hasColumn: true,
2154
- createTable: true
2301
+ createTable: true,
2302
+ deleteMessages: false,
2303
+ getScoresBySpan: true
2155
2304
  };
2156
2305
  }
2157
2306
  async createTable({
@@ -2223,6 +2372,12 @@ var D1Store = class extends storage.MastraStorage {
2223
2372
  }) {
2224
2373
  return this.stores.memory.getMessages({ threadId, selectBy, format });
2225
2374
  }
2375
+ async getMessagesById({
2376
+ messageIds,
2377
+ format
2378
+ }) {
2379
+ return this.stores.memory.getMessagesById({ messageIds, format });
2380
+ }
2226
2381
  async getMessagesPaginated({
2227
2382
  threadId,
2228
2383
  selectBy,
@@ -2230,12 +2385,29 @@ var D1Store = class extends storage.MastraStorage {
2230
2385
  }) {
2231
2386
  return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2232
2387
  }
2388
+ async updateWorkflowResults({
2389
+ workflowName,
2390
+ runId,
2391
+ stepId,
2392
+ result,
2393
+ runtimeContext
2394
+ }) {
2395
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2396
+ }
2397
+ async updateWorkflowState({
2398
+ workflowName,
2399
+ runId,
2400
+ opts
2401
+ }) {
2402
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2403
+ }
2233
2404
  async persistWorkflowSnapshot({
2234
2405
  workflowName,
2235
2406
  runId,
2407
+ resourceId,
2236
2408
  snapshot
2237
2409
  }) {
2238
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2410
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2239
2411
  }
2240
2412
  async loadWorkflowSnapshot(params) {
2241
2413
  return this.stores.workflows.loadWorkflowSnapshot(params);
@@ -2322,10 +2494,20 @@ var D1Store = class extends storage.MastraStorage {
2322
2494
  });
2323
2495
  }
2324
2496
  async getScoresByScorerId({
2325
- scorerId: _scorerId,
2326
- pagination: _pagination
2497
+ scorerId,
2498
+ pagination,
2499
+ entityId,
2500
+ entityType,
2501
+ source
2502
+ }) {
2503
+ return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2504
+ }
2505
+ async getScoresBySpan({
2506
+ traceId,
2507
+ spanId,
2508
+ pagination
2327
2509
  }) {
2328
- return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2510
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2329
2511
  }
2330
2512
  /**
2331
2513
  * Close the database connection
@@ -2337,3 +2519,5 @@ var D1Store = class extends storage.MastraStorage {
2337
2519
  };
2338
2520
 
2339
2521
  exports.D1Store = D1Store;
2522
+ //# sourceMappingURL=index.cjs.map
2523
+ //# sourceMappingURL=index.cjs.map