@mastra/cloudflare 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.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_EVALS, TABLE_SCORERS, TABLE_TRACES, StoreOperations, serializeDate, ensureDate, LegacyEvalsStorage, WorkflowsStorage, TracesStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ScoresStorage } from '@mastra/core/storage';
2
+ import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_EVALS, TABLE_SCORERS, TABLE_TRACES, StoreOperations, serializeDate, ensureDate, LegacyEvalsStorage, WorkflowsStorage, TracesStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ScoresStorage, safelyParseJSON } from '@mastra/core/storage';
3
3
  import Cloudflare from 'cloudflare';
4
4
  import { MessageList } from '@mastra/core/agent';
5
+ import { saveScorePayloadSchema } from '@mastra/core/scores';
5
6
 
6
7
  // src/storage/index.ts
7
8
  var LegacyEvalsStorageCloudflare = class extends LegacyEvalsStorage {
@@ -463,9 +464,9 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
463
464
  const messageMigrationTasks = [];
464
465
  for (const message of validatedMessages) {
465
466
  const existingMessage = await this.findMessageInAnyThread(message.id);
466
- console.log(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
467
+ console.info(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
467
468
  if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
468
- console.log(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
469
+ console.info(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
469
470
  messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
470
471
  }
471
472
  }
@@ -494,7 +495,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
494
495
  ...cleanMessage,
495
496
  createdAt: serializeDate(cleanMessage.createdAt)
496
497
  };
497
- console.log(`Saving message ${message.id} with content:`, {
498
+ console.info(`Saving message ${message.id} with content:`, {
498
499
  content: serializedMessage.content,
499
500
  contentType: typeof serializedMessage.content,
500
501
  isArray: Array.isArray(serializedMessage.content)
@@ -590,13 +591,14 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
590
591
  );
591
592
  }
592
593
  async getRecentMessages(threadId, limit, messageIds) {
594
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
593
595
  if (limit <= 0) return;
594
596
  try {
595
597
  const threadMessagesKey = this.getThreadMessagesKey(threadId);
596
598
  const latestIds = await this.getLastN(threadMessagesKey, limit);
597
599
  latestIds.forEach((id) => messageIds.add(id));
598
600
  } catch {
599
- console.log(`No message order found for thread ${threadId}, skipping latest messages`);
601
+ console.info(`No message order found for thread ${threadId}, skipping latest messages`);
600
602
  }
601
603
  }
602
604
  async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
@@ -627,7 +629,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
627
629
  const data = await this.operations.getKV(TABLE_MESSAGES, key);
628
630
  if (!data) return null;
629
631
  const parsed = typeof data === "string" ? JSON.parse(data) : data;
630
- console.log(`Retrieved message ${id} from thread ${threadId} with content:`, {
632
+ console.info(`Retrieved message ${id} from thread ${threadId} with content:`, {
631
633
  content: parsed.content,
632
634
  contentType: typeof parsed.content,
633
635
  isArray: Array.isArray(parsed.content)
@@ -648,15 +650,14 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
648
650
  selectBy,
649
651
  format
650
652
  }) {
651
- console.log(`getMessages called with format: ${format}, threadId: ${threadId}`);
652
- if (!threadId) throw new Error("threadId is required");
653
+ console.info(`getMessages called with format: ${format}, threadId: ${threadId}`);
653
654
  const actualFormat = format || "v1";
654
- console.log(`Using format: ${actualFormat}`);
655
- if (!threadId) throw new Error("threadId is required");
655
+ console.info(`Using format: ${actualFormat}`);
656
656
  const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
657
657
  const messageIds = /* @__PURE__ */ new Set();
658
658
  if (limit === 0 && !selectBy?.include?.length) return [];
659
659
  try {
660
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
660
661
  await Promise.all([
661
662
  selectBy?.include?.length ? this.getIncludedMessagesWithContext(threadId, selectBy.include, messageIds) : Promise.resolve(),
662
663
  limit > 0 ? this.getRecentMessages(threadId, limit, messageIds) : Promise.resolve()
@@ -701,7 +702,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
701
702
  createdAt: ensureDate(message.createdAt)
702
703
  }));
703
704
  if (actualFormat === `v1`) {
704
- console.log(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
705
+ console.info(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
705
706
  return prepared.map((msg) => ({
706
707
  ...msg,
707
708
  createdAt: new Date(msg.createdAt)
@@ -717,7 +718,43 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
717
718
  category: ErrorCategory.THIRD_PARTY,
718
719
  text: `Error retrieving messages for thread ${threadId}`,
719
720
  details: {
720
- threadId
721
+ threadId,
722
+ resourceId: resourceId ?? ""
723
+ }
724
+ },
725
+ error
726
+ );
727
+ this.logger?.trackException(mastraError);
728
+ this.logger?.error(mastraError.toString());
729
+ return [];
730
+ }
731
+ }
732
+ async getMessagesById({
733
+ messageIds,
734
+ format
735
+ }) {
736
+ if (messageIds.length === 0) return [];
737
+ try {
738
+ const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
739
+ (result) => !!result
740
+ );
741
+ const prepared = messages.map(({ _index, ...message }) => ({
742
+ ...message,
743
+ ...message.type !== `v2` && { type: message.type },
744
+ createdAt: ensureDate(message.createdAt)
745
+ }));
746
+ const list = new MessageList().add(prepared, "memory");
747
+ if (format === `v1`) return list.get.all.v1();
748
+ return list.get.all.v2();
749
+ } catch (error) {
750
+ const mastraError = new MastraError(
751
+ {
752
+ id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
753
+ domain: ErrorDomain.STORAGE,
754
+ category: ErrorCategory.THIRD_PARTY,
755
+ text: `Error retrieving messages by ID`,
756
+ details: {
757
+ messageIds: JSON.stringify(messageIds)
721
758
  }
722
759
  },
723
760
  error
@@ -728,9 +765,10 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
728
765
  }
729
766
  }
730
767
  async getMessagesPaginated(args) {
768
+ const { threadId, resourceId, selectBy, format = "v1" } = args;
769
+ const { page = 0, perPage = 100 } = selectBy?.pagination || {};
731
770
  try {
732
- const { threadId, selectBy, format = "v1" } = args;
733
- const { page = 0, perPage = 100 } = selectBy?.pagination || {};
771
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
734
772
  const messages = format === "v2" ? await this.getMessages({ threadId, selectBy, format: "v2" }) : await this.getMessages({ threadId, selectBy, format: "v1" });
735
773
  let filteredMessages = messages;
736
774
  if (selectBy?.pagination?.dateRange) {
@@ -753,15 +791,22 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
753
791
  messages: paginatedMessages
754
792
  };
755
793
  } catch (error) {
756
- throw new MastraError(
794
+ const mastraError = new MastraError(
757
795
  {
758
796
  id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
759
797
  domain: ErrorDomain.STORAGE,
760
798
  category: ErrorCategory.THIRD_PARTY,
761
- text: "Failed to get messages with pagination"
799
+ text: "Failed to get messages with pagination",
800
+ details: {
801
+ threadId,
802
+ resourceId: resourceId ?? ""
803
+ }
762
804
  },
763
805
  error
764
806
  );
807
+ this.logger?.trackException?.(mastraError);
808
+ this.logger?.error?.(mastraError.toString());
809
+ return { messages: [], total: 0, page, perPage: perPage || 40, hasMore: false };
765
810
  }
766
811
  }
767
812
  async updateMessages(args) {
@@ -1529,18 +1574,17 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1529
1574
  }
1530
1575
  };
1531
1576
  function transformScoreRow(row) {
1532
- let input = void 0;
1533
- if (row.input) {
1534
- try {
1535
- input = JSON.parse(row.input);
1536
- } catch {
1537
- input = row.input;
1538
- }
1539
- }
1540
- return {
1541
- ...row,
1542
- input
1543
- };
1577
+ const deserialized = { ...row };
1578
+ deserialized.input = safelyParseJSON(row.input);
1579
+ deserialized.output = safelyParseJSON(row.output);
1580
+ deserialized.scorer = safelyParseJSON(row.scorer);
1581
+ deserialized.preprocessStepResult = safelyParseJSON(row.preprocessStepResult);
1582
+ deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
1583
+ deserialized.metadata = safelyParseJSON(row.metadata);
1584
+ deserialized.additionalContext = safelyParseJSON(row.additionalContext);
1585
+ deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
1586
+ deserialized.entity = safelyParseJSON(row.entity);
1587
+ return deserialized;
1544
1588
  }
1545
1589
  var ScoresStorageCloudflare = class extends ScoresStorage {
1546
1590
  operations;
@@ -1571,10 +1615,24 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1571
1615
  }
1572
1616
  }
1573
1617
  async saveScore(score) {
1618
+ let parsedScore;
1574
1619
  try {
1575
- const { input, ...rest } = score;
1620
+ parsedScore = saveScorePayloadSchema.parse(score);
1621
+ } catch (error) {
1622
+ throw new MastraError(
1623
+ {
1624
+ id: "CLOUDFLARE_STORAGE_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1625
+ domain: ErrorDomain.STORAGE,
1626
+ category: ErrorCategory.USER,
1627
+ details: { scoreId: score.id }
1628
+ },
1629
+ error
1630
+ );
1631
+ }
1632
+ try {
1633
+ const id = crypto.randomUUID();
1576
1634
  const serializedRecord = {};
1577
- for (const [key, value] of Object.entries(rest)) {
1635
+ for (const [key, value] of Object.entries(parsedScore)) {
1578
1636
  if (value !== null && value !== void 0) {
1579
1637
  if (typeof value === "object") {
1580
1638
  serializedRecord[key] = JSON.stringify(value);
@@ -1585,12 +1643,12 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1585
1643
  serializedRecord[key] = null;
1586
1644
  }
1587
1645
  }
1588
- serializedRecord.input = JSON.stringify(input);
1646
+ serializedRecord.id = id;
1589
1647
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1590
1648
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1591
1649
  await this.operations.putKV({
1592
1650
  tableName: TABLE_SCORERS,
1593
- key: score.id,
1651
+ key: id,
1594
1652
  value: serializedRecord
1595
1653
  });
1596
1654
  const scoreFromDb = await this.getScoreById({ id: score.id });
@@ -1612,6 +1670,9 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1612
1670
  }
1613
1671
  async getScoresByScorerId({
1614
1672
  scorerId,
1673
+ entityId,
1674
+ entityType,
1675
+ source,
1615
1676
  pagination
1616
1677
  }) {
1617
1678
  try {
@@ -1619,6 +1680,15 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1619
1680
  const scores = [];
1620
1681
  for (const { name: key } of keys) {
1621
1682
  const score = await this.operations.getKV(TABLE_SCORERS, key);
1683
+ if (entityId && score.entityId !== entityId) {
1684
+ continue;
1685
+ }
1686
+ if (entityType && score.entityType !== entityType) {
1687
+ continue;
1688
+ }
1689
+ if (source && score.source !== source) {
1690
+ continue;
1691
+ }
1622
1692
  if (score && score.scorerId === scorerId) {
1623
1693
  scores.push(transformScoreRow(score));
1624
1694
  }
@@ -1749,6 +1819,50 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1749
1819
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1750
1820
  }
1751
1821
  }
1822
+ async getScoresBySpan({
1823
+ traceId,
1824
+ spanId,
1825
+ pagination
1826
+ }) {
1827
+ try {
1828
+ const keys = await this.operations.listKV(TABLE_SCORERS);
1829
+ const scores = [];
1830
+ for (const { name: key } of keys) {
1831
+ const score = await this.operations.getKV(TABLE_SCORERS, key);
1832
+ if (score && score.traceId === traceId && score.spanId === spanId) {
1833
+ scores.push(transformScoreRow(score));
1834
+ }
1835
+ }
1836
+ scores.sort((a, b) => {
1837
+ const dateA = new Date(a.createdAt || 0).getTime();
1838
+ const dateB = new Date(b.createdAt || 0).getTime();
1839
+ return dateB - dateA;
1840
+ });
1841
+ const total = scores.length;
1842
+ const start = pagination.page * pagination.perPage;
1843
+ const end = start + pagination.perPage;
1844
+ const pagedScores = scores.slice(start, end);
1845
+ return {
1846
+ pagination: {
1847
+ total,
1848
+ page: pagination.page,
1849
+ perPage: pagination.perPage,
1850
+ hasMore: end < total
1851
+ },
1852
+ scores: pagedScores
1853
+ };
1854
+ } catch (error) {
1855
+ throw new MastraError(
1856
+ {
1857
+ id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1858
+ domain: ErrorDomain.STORAGE,
1859
+ category: ErrorCategory.THIRD_PARTY,
1860
+ text: `Failed to get scores by span: traceId=${traceId}, spanId=${spanId}`
1861
+ },
1862
+ error
1863
+ );
1864
+ }
1865
+ }
1752
1866
  };
1753
1867
  var TracesStorageCloudflare = class extends TracesStorage {
1754
1868
  operations;
@@ -1882,15 +1996,32 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1882
1996
  throw new Error("Invalid workflow snapshot parameters");
1883
1997
  }
1884
1998
  }
1999
+ updateWorkflowResults({
2000
+ // workflowName,
2001
+ // runId,
2002
+ // stepId,
2003
+ // result,
2004
+ // runtimeContext,
2005
+ }) {
2006
+ throw new Error("Method not implemented.");
2007
+ }
2008
+ updateWorkflowState({
2009
+ // workflowName,
2010
+ // runId,
2011
+ // opts,
2012
+ }) {
2013
+ throw new Error("Method not implemented.");
2014
+ }
1885
2015
  async persistWorkflowSnapshot(params) {
1886
2016
  try {
1887
- const { workflowName, runId, snapshot } = params;
2017
+ const { workflowName, runId, resourceId, snapshot } = params;
1888
2018
  await this.operations.putKV({
1889
2019
  tableName: TABLE_WORKFLOW_SNAPSHOT,
1890
2020
  key: this.operations.getKey(TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId }),
1891
2021
  value: {
1892
2022
  workflow_name: workflowName,
1893
2023
  run_id: runId,
2024
+ resourceId,
1894
2025
  snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
1895
2026
  createdAt: /* @__PURE__ */ new Date(),
1896
2027
  updatedAt: /* @__PURE__ */ new Date()
@@ -2122,6 +2253,11 @@ var CloudflareStore = class extends MastraStorage {
2122
2253
  throw new Error("apiToken is required for REST API");
2123
2254
  }
2124
2255
  }
2256
+ get supports() {
2257
+ const supports = super.supports;
2258
+ supports.getScoresBySpan = true;
2259
+ return supports;
2260
+ }
2125
2261
  constructor(config) {
2126
2262
  super({ name: "Cloudflare" });
2127
2263
  try {
@@ -2233,6 +2369,28 @@ var CloudflareStore = class extends MastraStorage {
2233
2369
  }) {
2234
2370
  return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2235
2371
  }
2372
+ async updateWorkflowResults({
2373
+ workflowName,
2374
+ runId,
2375
+ stepId,
2376
+ result,
2377
+ runtimeContext
2378
+ }) {
2379
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2380
+ }
2381
+ async updateWorkflowState({
2382
+ workflowName,
2383
+ runId,
2384
+ opts
2385
+ }) {
2386
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2387
+ }
2388
+ async getMessagesById({
2389
+ messageIds,
2390
+ format
2391
+ }) {
2392
+ return this.stores.memory.getMessagesById({ messageIds, format });
2393
+ }
2236
2394
  async persistWorkflowSnapshot(params) {
2237
2395
  return this.stores.workflows.persistWorkflowSnapshot(params);
2238
2396
  }
@@ -2323,9 +2481,19 @@ var CloudflareStore = class extends MastraStorage {
2323
2481
  }
2324
2482
  async getScoresByScorerId({
2325
2483
  scorerId,
2484
+ entityId,
2485
+ entityType,
2486
+ source,
2487
+ pagination
2488
+ }) {
2489
+ return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2490
+ }
2491
+ async getScoresBySpan({
2492
+ traceId,
2493
+ spanId,
2326
2494
  pagination
2327
2495
  }) {
2328
- return this.stores.scores.getScoresByScorerId({ scorerId, pagination });
2496
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2329
2497
  }
2330
2498
  async getResourceById({ resourceId }) {
2331
2499
  return this.stores.memory.getResourceById({ resourceId });
@@ -2345,3 +2513,5 @@ var CloudflareStore = class extends MastraStorage {
2345
2513
  };
2346
2514
 
2347
2515
  export { CloudflareStore };
2516
+ //# sourceMappingURL=index.js.map
2517
+ //# sourceMappingURL=index.js.map