@mastra/cloudflare-d1 0.0.0-pgvector-index-fix-20250905222058 → 0.0.0-playground-studio-cloud-20251031080052

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,8 +1,9 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, LegacyEvalsStorage, TABLE_EVALS, serializeDate, TracesStorage, TABLE_TRACES, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit, safelyParseJSON } from '@mastra/core/storage';
2
+ import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, LegacyEvalsStorage, TABLE_EVALS, serializeDate, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit, safelyParseJSON } from '@mastra/core/storage';
3
3
  import Cloudflare from 'cloudflare';
4
4
  import { parseSqlIdentifier } from '@mastra/core/utils';
5
5
  import { MessageList } from '@mastra/core/agent';
6
+ import { saveScorePayloadSchema } from '@mastra/core/scores';
6
7
 
7
8
  // src/storage/index.ts
8
9
  var SqlBuilder = class {
@@ -241,16 +242,6 @@ function isArrayOfRecords(value) {
241
242
  }
242
243
  function deserializeValue(value, type) {
243
244
  if (value === null || value === void 0) return null;
244
- if (type === "date" && typeof value === "string") {
245
- return new Date(value);
246
- }
247
- if (type === "jsonb" && typeof value === "string") {
248
- try {
249
- return JSON.parse(value);
250
- } catch {
251
- return value;
252
- }
253
- }
254
245
  if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
255
246
  try {
256
247
  return JSON.parse(value);
@@ -1609,12 +1600,25 @@ var ScoresStorageD1 = class extends ScoresStorage {
1609
1600
  }
1610
1601
  }
1611
1602
  async saveScore(score) {
1603
+ let parsedScore;
1604
+ try {
1605
+ parsedScore = saveScorePayloadSchema.parse(score);
1606
+ } catch (error) {
1607
+ throw new MastraError(
1608
+ {
1609
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1610
+ domain: ErrorDomain.STORAGE,
1611
+ category: ErrorCategory.USER,
1612
+ details: { scoreId: score.id }
1613
+ },
1614
+ error
1615
+ );
1616
+ }
1612
1617
  try {
1613
1618
  const id = crypto.randomUUID();
1614
1619
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1615
- const { input, ...rest } = score;
1616
1620
  const serializedRecord = {};
1617
- for (const [key, value] of Object.entries(rest)) {
1621
+ for (const [key, value] of Object.entries(parsedScore)) {
1618
1622
  if (value !== null && value !== void 0) {
1619
1623
  if (typeof value === "object") {
1620
1624
  serializedRecord[key] = JSON.stringify(value);
@@ -1626,7 +1630,6 @@ var ScoresStorageD1 = class extends ScoresStorage {
1626
1630
  }
1627
1631
  }
1628
1632
  serializedRecord.id = id;
1629
- serializedRecord.input = JSON.stringify(input);
1630
1633
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1631
1634
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1632
1635
  const columns = Object.keys(serializedRecord);
@@ -1802,128 +1805,53 @@ var ScoresStorageD1 = class extends ScoresStorage {
1802
1805
  );
1803
1806
  }
1804
1807
  }
1805
- };
1806
- function isArrayOfRecords2(value) {
1807
- return value && Array.isArray(value) && value.length > 0;
1808
- }
1809
- var TracesStorageD1 = class extends TracesStorage {
1810
- operations;
1811
- constructor({ operations }) {
1812
- super();
1813
- this.operations = operations;
1814
- }
1815
- async getTraces(args) {
1816
- const paginatedArgs = {
1817
- name: args.name,
1818
- scope: args.scope,
1819
- page: args.page,
1820
- perPage: args.perPage,
1821
- attributes: args.attributes,
1822
- filters: args.filters,
1823
- dateRange: args.fromDate || args.toDate ? {
1824
- start: args.fromDate,
1825
- end: args.toDate
1826
- } : void 0
1827
- };
1828
- try {
1829
- const result = await this.getTracesPaginated(paginatedArgs);
1830
- return result.traces;
1831
- } catch (error) {
1832
- throw new MastraError(
1833
- {
1834
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1835
- domain: ErrorDomain.STORAGE,
1836
- category: ErrorCategory.THIRD_PARTY,
1837
- text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1838
- details: {
1839
- name: args.name ?? "",
1840
- scope: args.scope ?? ""
1841
- }
1842
- },
1843
- error
1844
- );
1845
- }
1846
- }
1847
- async getTracesPaginated(args) {
1848
- const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
1849
- const fromDate = dateRange?.start;
1850
- const toDate = dateRange?.end;
1851
- const fullTableName = this.operations.getTableName(TABLE_TRACES);
1808
+ async getScoresBySpan({
1809
+ traceId,
1810
+ spanId,
1811
+ pagination
1812
+ }) {
1852
1813
  try {
1853
- const dataQuery = createSqlBuilder().select("*").from(fullTableName).where("1=1");
1854
- const countQuery = createSqlBuilder().count().from(fullTableName).where("1=1");
1855
- if (name) {
1856
- dataQuery.andWhere("name LIKE ?", `%${name}%`);
1857
- countQuery.andWhere("name LIKE ?", `%${name}%`);
1858
- }
1859
- if (scope) {
1860
- dataQuery.andWhere("scope = ?", scope);
1861
- countQuery.andWhere("scope = ?", scope);
1862
- }
1863
- if (attributes && Object.keys(attributes).length > 0) {
1864
- for (const [key, value] of Object.entries(attributes)) {
1865
- dataQuery.jsonLike("attributes", key, value);
1866
- countQuery.jsonLike("attributes", key, value);
1867
- }
1868
- }
1869
- if (fromDate) {
1870
- const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
1871
- dataQuery.andWhere("createdAt >= ?", fromDateStr);
1872
- countQuery.andWhere("createdAt >= ?", fromDateStr);
1873
- }
1874
- if (toDate) {
1875
- const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
1876
- dataQuery.andWhere("createdAt <= ?", toDateStr);
1877
- countQuery.andWhere("createdAt <= ?", toDateStr);
1878
- }
1879
- const allDataResult = await this.operations.executeQuery(
1880
- createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1881
- );
1882
- console.log("allDataResult", allDataResult);
1814
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1815
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1883
1816
  const countResult = await this.operations.executeQuery(countQuery.build());
1884
- const total = Number(countResult?.[0]?.count ?? 0);
1885
- dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
1886
- const results = await this.operations.executeQuery(dataQuery.build());
1887
- const traces = isArrayOfRecords2(results) ? results.map(
1888
- (trace) => ({
1889
- ...trace,
1890
- attributes: deserializeValue(trace.attributes, "jsonb"),
1891
- status: deserializeValue(trace.status, "jsonb"),
1892
- events: deserializeValue(trace.events, "jsonb"),
1893
- links: deserializeValue(trace.links, "jsonb"),
1894
- other: deserializeValue(trace.other, "jsonb")
1895
- })
1896
- ) : [];
1817
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1818
+ if (total === 0) {
1819
+ return {
1820
+ pagination: {
1821
+ total: 0,
1822
+ page: pagination.page,
1823
+ perPage: pagination.perPage,
1824
+ hasMore: false
1825
+ },
1826
+ scores: []
1827
+ };
1828
+ }
1829
+ const limit = pagination.perPage + 1;
1830
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
1831
+ const { sql, params } = selectQuery.build();
1832
+ const results = await this.operations.executeQuery({ sql, params });
1833
+ const rows = Array.isArray(results) ? results : [];
1834
+ const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
1897
1835
  return {
1898
- traces,
1899
- total,
1900
- page,
1901
- perPage,
1902
- hasMore: page * perPage + traces.length < total
1836
+ pagination: {
1837
+ total,
1838
+ page: pagination.page,
1839
+ perPage: pagination.perPage,
1840
+ hasMore: rows.length > pagination.perPage
1841
+ },
1842
+ scores
1903
1843
  };
1904
1844
  } catch (error) {
1905
- const mastraError = new MastraError(
1845
+ throw new MastraError(
1906
1846
  {
1907
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_PAGINATED_ERROR",
1847
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1908
1848
  domain: ErrorDomain.STORAGE,
1909
- category: ErrorCategory.THIRD_PARTY,
1910
- text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1911
- details: { name: name ?? "", scope: scope ?? "" }
1849
+ category: ErrorCategory.THIRD_PARTY
1912
1850
  },
1913
1851
  error
1914
1852
  );
1915
- this.logger?.error(mastraError.toString());
1916
- this.logger?.trackException(mastraError);
1917
- return { traces: [], total: 0, page, perPage, hasMore: false };
1918
1853
  }
1919
1854
  }
1920
- async batchTraceInsert({ records }) {
1921
- this.logger.debug("Batch inserting traces", { count: records.length });
1922
- await this.operations.batchInsert({
1923
- tableName: TABLE_TRACES,
1924
- records
1925
- });
1926
- }
1927
1855
  };
1928
1856
  var WorkflowsStorageD1 = class extends WorkflowsStorage {
1929
1857
  operations;
@@ -1950,6 +1878,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1950
1878
  async persistWorkflowSnapshot({
1951
1879
  workflowName,
1952
1880
  runId,
1881
+ resourceId,
1953
1882
  snapshot
1954
1883
  }) {
1955
1884
  const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
@@ -1960,11 +1889,13 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1960
1889
  });
1961
1890
  const persisting = currentSnapshot ? {
1962
1891
  ...currentSnapshot,
1892
+ resourceId,
1963
1893
  snapshot: JSON.stringify(snapshot),
1964
1894
  updatedAt: now
1965
1895
  } : {
1966
1896
  workflow_name: workflowName,
1967
1897
  run_id: runId,
1898
+ resourceId,
1968
1899
  snapshot,
1969
1900
  createdAt: now,
1970
1901
  updatedAt: now
@@ -2206,9 +2137,6 @@ var D1Store = class extends MastraStorage {
2206
2137
  const legacyEvals = new LegacyEvalsStorageD1({
2207
2138
  operations
2208
2139
  });
2209
- const traces = new TracesStorageD1({
2210
- operations
2211
- });
2212
2140
  const workflows = new WorkflowsStorageD1({
2213
2141
  operations
2214
2142
  });
@@ -2219,7 +2147,6 @@ var D1Store = class extends MastraStorage {
2219
2147
  operations,
2220
2148
  scores,
2221
2149
  legacyEvals,
2222
- traces,
2223
2150
  workflows,
2224
2151
  memory
2225
2152
  };
@@ -2230,7 +2157,8 @@ var D1Store = class extends MastraStorage {
2230
2157
  resourceWorkingMemory: true,
2231
2158
  hasColumn: true,
2232
2159
  createTable: true,
2233
- deleteMessages: false
2160
+ deleteMessages: false,
2161
+ getScoresBySpan: true
2234
2162
  };
2235
2163
  }
2236
2164
  async createTable({
@@ -2334,9 +2262,10 @@ var D1Store = class extends MastraStorage {
2334
2262
  async persistWorkflowSnapshot({
2335
2263
  workflowName,
2336
2264
  runId,
2265
+ resourceId,
2337
2266
  snapshot
2338
2267
  }) {
2339
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2268
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2340
2269
  }
2341
2270
  async loadWorkflowSnapshot(params) {
2342
2271
  return this.stores.workflows.loadWorkflowSnapshot(params);
@@ -2365,15 +2294,6 @@ var D1Store = class extends MastraStorage {
2365
2294
  async batchInsert({ tableName, records }) {
2366
2295
  return this.stores.operations.batchInsert({ tableName, records });
2367
2296
  }
2368
- /**
2369
- * @deprecated use getTracesPaginated instead
2370
- */
2371
- async getTraces(args) {
2372
- return this.stores.traces.getTraces(args);
2373
- }
2374
- async getTracesPaginated(args) {
2375
- return this.stores.traces.getTracesPaginated(args);
2376
- }
2377
2297
  /**
2378
2298
  * @deprecated use getEvals instead
2379
2299
  */
@@ -2431,6 +2351,13 @@ var D1Store = class extends MastraStorage {
2431
2351
  }) {
2432
2352
  return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2433
2353
  }
2354
+ async getScoresBySpan({
2355
+ traceId,
2356
+ spanId,
2357
+ pagination
2358
+ }) {
2359
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2360
+ }
2434
2361
  /**
2435
2362
  * Close the database connection
2436
2363
  * No explicit cleanup needed for D1 in either REST or Workers Binding mode