@mastra/cloudflare-d1 0.1.6-alpha.4 → 0.1.6-alpha.5

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.
@@ -2,6 +2,7 @@ import type { D1Database as D1Database_2 } from '@cloudflare/workers-types';
2
2
  import type { EvalRow } from '@mastra/core/storage';
3
3
  import { MastraStorage } from '@mastra/core/storage';
4
4
  import type { MessageType } from '@mastra/core/memory';
5
+ import type { MessageType as MessageType_2 } from '@mastra/core';
5
6
  import type { StorageColumn } from '@mastra/core/storage';
6
7
  import type { StorageGetMessagesArg } from '@mastra/core/storage';
7
8
  import type { StorageThreadType } from '@mastra/core/memory';
@@ -11,7 +12,9 @@ import type { WorkflowRuns } from '@mastra/core/storage';
11
12
  import type { WorkflowRunState } from '@mastra/core/workflows';
12
13
  import type { WorkflowRunState as WorkflowRunState_2 } from '@mastra/core';
13
14
 
14
- export declare const createSampleMessage: (threadId: string) => any;
15
+ export declare const checkWorkflowSnapshot: (snapshot: WorkflowRunState_2 | string, stepId: string, status: string) => void;
16
+
17
+ export declare const createSampleMessage: (threadId: string) => MessageType_2;
15
18
 
16
19
  export declare const createSampleThread: () => {
17
20
  id: string;
@@ -52,7 +55,11 @@ export declare const createSampleTrace: (name: string, scope?: string, attribute
52
55
  createdAt: string;
53
56
  };
54
57
 
55
- export declare const createSampleWorkflowSnapshot: (threadId: string) => WorkflowRunState_2;
58
+ export declare const createSampleWorkflowSnapshot: (threadId: string, status: string, createdAt?: Date) => {
59
+ snapshot: WorkflowRunState_2;
60
+ runId: string;
61
+ stepId: string;
62
+ };
56
63
 
57
64
  export declare function createSqlBuilder(): SqlBuilder;
58
65
 
@@ -162,14 +169,17 @@ declare class D1Store extends MastraStorage {
162
169
  attributes?: Record<string, string>;
163
170
  }): Promise<Record<string, any>[]>;
164
171
  getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;
165
- getWorkflowRuns(_args?: {
172
+ private parseWorkflowRun;
173
+ private hasColumn;
174
+ getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId, }?: {
166
175
  workflowName?: string;
167
176
  fromDate?: Date;
168
177
  toDate?: Date;
169
178
  limit?: number;
170
179
  offset?: number;
180
+ resourceId?: string;
171
181
  }): Promise<WorkflowRuns>;
172
- getWorkflowRunById(_args: {
182
+ getWorkflowRunById({ runId, workflowName, }: {
173
183
  runId: string;
174
184
  workflowName?: string;
175
185
  }): Promise<WorkflowRun | null>;
@@ -231,6 +241,7 @@ export declare class SqlBuilder {
231
241
  orderBy(column: string, direction?: 'ASC' | 'DESC'): SqlBuilder;
232
242
  limit(count: number): SqlBuilder;
233
243
  offset(count: number): SqlBuilder;
244
+ count(): SqlBuilder;
234
245
  /**
235
246
  * Insert a row, or update specific columns on conflict (upsert).
236
247
  * @param table Table name
@@ -2,6 +2,7 @@ import type { D1Database as D1Database_2 } from '@cloudflare/workers-types';
2
2
  import type { EvalRow } from '@mastra/core/storage';
3
3
  import { MastraStorage } from '@mastra/core/storage';
4
4
  import type { MessageType } from '@mastra/core/memory';
5
+ import type { MessageType as MessageType_2 } from '@mastra/core';
5
6
  import type { StorageColumn } from '@mastra/core/storage';
6
7
  import type { StorageGetMessagesArg } from '@mastra/core/storage';
7
8
  import type { StorageThreadType } from '@mastra/core/memory';
@@ -11,7 +12,9 @@ import type { WorkflowRuns } from '@mastra/core/storage';
11
12
  import type { WorkflowRunState } from '@mastra/core/workflows';
12
13
  import type { WorkflowRunState as WorkflowRunState_2 } from '@mastra/core';
13
14
 
14
- export declare const createSampleMessage: (threadId: string) => any;
15
+ export declare const checkWorkflowSnapshot: (snapshot: WorkflowRunState_2 | string, stepId: string, status: string) => void;
16
+
17
+ export declare const createSampleMessage: (threadId: string) => MessageType_2;
15
18
 
16
19
  export declare const createSampleThread: () => {
17
20
  id: string;
@@ -52,7 +55,11 @@ export declare const createSampleTrace: (name: string, scope?: string, attribute
52
55
  createdAt: string;
53
56
  };
54
57
 
55
- export declare const createSampleWorkflowSnapshot: (threadId: string) => WorkflowRunState_2;
58
+ export declare const createSampleWorkflowSnapshot: (threadId: string, status: string, createdAt?: Date) => {
59
+ snapshot: WorkflowRunState_2;
60
+ runId: string;
61
+ stepId: string;
62
+ };
56
63
 
57
64
  export declare function createSqlBuilder(): SqlBuilder;
58
65
 
@@ -162,14 +169,17 @@ declare class D1Store extends MastraStorage {
162
169
  attributes?: Record<string, string>;
163
170
  }): Promise<Record<string, any>[]>;
164
171
  getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;
165
- getWorkflowRuns(_args?: {
172
+ private parseWorkflowRun;
173
+ private hasColumn;
174
+ getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId, }?: {
166
175
  workflowName?: string;
167
176
  fromDate?: Date;
168
177
  toDate?: Date;
169
178
  limit?: number;
170
179
  offset?: number;
180
+ resourceId?: string;
171
181
  }): Promise<WorkflowRuns>;
172
- getWorkflowRunById(_args: {
182
+ getWorkflowRunById({ runId, workflowName, }: {
173
183
  runId: string;
174
184
  workflowName?: string;
175
185
  }): Promise<WorkflowRun | null>;
@@ -231,6 +241,7 @@ export declare class SqlBuilder {
231
241
  orderBy(column: string, direction?: 'ASC' | 'DESC'): SqlBuilder;
232
242
  limit(count: number): SqlBuilder;
233
243
  offset(count: number): SqlBuilder;
244
+ count(): SqlBuilder;
234
245
  /**
235
246
  * Insert a row, or update specific columns on conflict (upsert).
236
247
  * @param table Table name
package/dist/index.cjs CHANGED
@@ -74,6 +74,10 @@ var SqlBuilder = class {
74
74
  this.params.push(count);
75
75
  return this;
76
76
  }
77
+ count() {
78
+ this.sql += "SELECT COUNT(*) AS count";
79
+ return this;
80
+ }
77
81
  /**
78
82
  * Insert a row, or update specific columns on conflict (upsert).
79
83
  * @param table Table name
@@ -496,7 +500,8 @@ var D1Store = class extends storage.MastraStorage {
496
500
  try {
497
501
  await this.executeQuery({ sql, params });
498
502
  } catch (error) {
499
- this.logger.error(`Error inserting into ${fullTableName}:`, { error });
503
+ const message = error instanceof Error ? error.message : String(error);
504
+ this.logger.error(`Error inserting into ${fullTableName}:`, { message });
500
505
  throw new Error(`Failed to insert into ${fullTableName}: ${error}`);
501
506
  }
502
507
  }
@@ -594,7 +599,8 @@ var D1Store = class extends storage.MastraStorage {
594
599
  await this.executeQuery({ sql, params });
595
600
  return thread;
596
601
  } catch (error) {
597
- this.logger.error(`Error saving thread to ${fullTableName}:`, { error });
602
+ const message = error instanceof Error ? error.message : String(error);
603
+ this.logger.error(`Error saving thread to ${fullTableName}:`, { message });
598
604
  throw error;
599
605
  }
600
606
  }
@@ -628,7 +634,8 @@ var D1Store = class extends storage.MastraStorage {
628
634
  updatedAt: /* @__PURE__ */ new Date()
629
635
  };
630
636
  } catch (error) {
631
- this.logger.error("Error updating thread:", { error });
637
+ const message = error instanceof Error ? error.message : String(error);
638
+ this.logger.error("Error updating thread:", { message });
632
639
  throw error;
633
640
  }
634
641
  }
@@ -929,11 +936,107 @@ var D1Store = class extends storage.MastraStorage {
929
936
  return [];
930
937
  }
931
938
  }
932
- getWorkflowRuns(_args) {
933
- throw new Error("Method not implemented.");
939
+ parseWorkflowRun(row) {
940
+ let parsedSnapshot = row.snapshot;
941
+ if (typeof parsedSnapshot === "string") {
942
+ try {
943
+ parsedSnapshot = JSON.parse(row.snapshot);
944
+ } catch (e) {
945
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
946
+ }
947
+ }
948
+ return {
949
+ workflowName: row.workflow_name,
950
+ runId: row.run_id,
951
+ snapshot: parsedSnapshot,
952
+ createdAt: this.ensureDate(row.createdAt),
953
+ updatedAt: this.ensureDate(row.updatedAt),
954
+ resourceId: row.resourceId
955
+ };
956
+ }
957
+ async hasColumn(table, column) {
958
+ const sql = `PRAGMA table_info(${table});`;
959
+ const result = await this.executeQuery({ sql, params: [] });
960
+ if (!result || !Array.isArray(result)) return false;
961
+ return result.some((col) => col.name === column || col.name === column.toLowerCase());
934
962
  }
935
- async getWorkflowRunById(_args) {
936
- throw new Error("Method not implemented.");
963
+ async getWorkflowRuns({
964
+ workflowName,
965
+ fromDate,
966
+ toDate,
967
+ limit,
968
+ offset,
969
+ resourceId
970
+ } = {}) {
971
+ const fullTableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
972
+ try {
973
+ const builder = createSqlBuilder().select().from(fullTableName);
974
+ const countBuilder = createSqlBuilder().count().from(fullTableName);
975
+ if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
976
+ if (resourceId) {
977
+ const hasResourceId = await this.hasColumn(fullTableName, "resourceId");
978
+ if (hasResourceId) {
979
+ builder.whereAnd("resourceId = ?", resourceId);
980
+ countBuilder.whereAnd("resourceId = ?", resourceId);
981
+ } else {
982
+ console.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
983
+ }
984
+ }
985
+ if (fromDate) {
986
+ builder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
987
+ countBuilder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
988
+ }
989
+ if (toDate) {
990
+ builder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
991
+ countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
992
+ }
993
+ builder.orderBy("createdAt", "DESC");
994
+ if (typeof limit === "number") builder.limit(limit);
995
+ if (typeof offset === "number") builder.offset(offset);
996
+ const { sql, params } = builder.build();
997
+ let total = 0;
998
+ if (limit !== void 0 && offset !== void 0) {
999
+ const { sql: countSql, params: countParams } = countBuilder.build();
1000
+ const countResult = await this.executeQuery({ sql: countSql, params: countParams, first: true });
1001
+ total = Number(countResult?.count ?? 0);
1002
+ }
1003
+ const results = await this.executeQuery({ sql, params });
1004
+ const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
1005
+ return { runs, total: total || runs.length };
1006
+ } catch (error) {
1007
+ this.logger.error("Error getting workflow runs:", {
1008
+ message: error instanceof Error ? error.message : String(error)
1009
+ });
1010
+ throw error;
1011
+ }
1012
+ }
1013
+ async getWorkflowRunById({
1014
+ runId,
1015
+ workflowName
1016
+ }) {
1017
+ const fullTableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1018
+ try {
1019
+ const conditions = [];
1020
+ const params = [];
1021
+ if (runId) {
1022
+ conditions.push("run_id = ?");
1023
+ params.push(runId);
1024
+ }
1025
+ if (workflowName) {
1026
+ conditions.push("workflow_name = ?");
1027
+ params.push(workflowName);
1028
+ }
1029
+ const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
1030
+ const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
1031
+ const result = await this.executeQuery({ sql, params, first: true });
1032
+ if (!result) return null;
1033
+ return this.parseWorkflowRun(result);
1034
+ } catch (error) {
1035
+ this.logger.error("Error getting workflow run by ID:", {
1036
+ message: error instanceof Error ? error.message : String(error)
1037
+ });
1038
+ throw error;
1039
+ }
937
1040
  }
938
1041
  /**
939
1042
  * Close the database connection
package/dist/index.js CHANGED
@@ -68,6 +68,10 @@ var SqlBuilder = class {
68
68
  this.params.push(count);
69
69
  return this;
70
70
  }
71
+ count() {
72
+ this.sql += "SELECT COUNT(*) AS count";
73
+ return this;
74
+ }
71
75
  /**
72
76
  * Insert a row, or update specific columns on conflict (upsert).
73
77
  * @param table Table name
@@ -490,7 +494,8 @@ var D1Store = class extends MastraStorage {
490
494
  try {
491
495
  await this.executeQuery({ sql, params });
492
496
  } catch (error) {
493
- this.logger.error(`Error inserting into ${fullTableName}:`, { error });
497
+ const message = error instanceof Error ? error.message : String(error);
498
+ this.logger.error(`Error inserting into ${fullTableName}:`, { message });
494
499
  throw new Error(`Failed to insert into ${fullTableName}: ${error}`);
495
500
  }
496
501
  }
@@ -588,7 +593,8 @@ var D1Store = class extends MastraStorage {
588
593
  await this.executeQuery({ sql, params });
589
594
  return thread;
590
595
  } catch (error) {
591
- this.logger.error(`Error saving thread to ${fullTableName}:`, { error });
596
+ const message = error instanceof Error ? error.message : String(error);
597
+ this.logger.error(`Error saving thread to ${fullTableName}:`, { message });
592
598
  throw error;
593
599
  }
594
600
  }
@@ -622,7 +628,8 @@ var D1Store = class extends MastraStorage {
622
628
  updatedAt: /* @__PURE__ */ new Date()
623
629
  };
624
630
  } catch (error) {
625
- this.logger.error("Error updating thread:", { error });
631
+ const message = error instanceof Error ? error.message : String(error);
632
+ this.logger.error("Error updating thread:", { message });
626
633
  throw error;
627
634
  }
628
635
  }
@@ -923,11 +930,107 @@ var D1Store = class extends MastraStorage {
923
930
  return [];
924
931
  }
925
932
  }
926
- getWorkflowRuns(_args) {
927
- throw new Error("Method not implemented.");
933
+ parseWorkflowRun(row) {
934
+ let parsedSnapshot = row.snapshot;
935
+ if (typeof parsedSnapshot === "string") {
936
+ try {
937
+ parsedSnapshot = JSON.parse(row.snapshot);
938
+ } catch (e) {
939
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
940
+ }
941
+ }
942
+ return {
943
+ workflowName: row.workflow_name,
944
+ runId: row.run_id,
945
+ snapshot: parsedSnapshot,
946
+ createdAt: this.ensureDate(row.createdAt),
947
+ updatedAt: this.ensureDate(row.updatedAt),
948
+ resourceId: row.resourceId
949
+ };
950
+ }
951
+ async hasColumn(table, column) {
952
+ const sql = `PRAGMA table_info(${table});`;
953
+ const result = await this.executeQuery({ sql, params: [] });
954
+ if (!result || !Array.isArray(result)) return false;
955
+ return result.some((col) => col.name === column || col.name === column.toLowerCase());
928
956
  }
929
- async getWorkflowRunById(_args) {
930
- throw new Error("Method not implemented.");
957
+ async getWorkflowRuns({
958
+ workflowName,
959
+ fromDate,
960
+ toDate,
961
+ limit,
962
+ offset,
963
+ resourceId
964
+ } = {}) {
965
+ const fullTableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
966
+ try {
967
+ const builder = createSqlBuilder().select().from(fullTableName);
968
+ const countBuilder = createSqlBuilder().count().from(fullTableName);
969
+ if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
970
+ if (resourceId) {
971
+ const hasResourceId = await this.hasColumn(fullTableName, "resourceId");
972
+ if (hasResourceId) {
973
+ builder.whereAnd("resourceId = ?", resourceId);
974
+ countBuilder.whereAnd("resourceId = ?", resourceId);
975
+ } else {
976
+ console.warn(`[${fullTableName}] resourceId column not found. Skipping resourceId filter.`);
977
+ }
978
+ }
979
+ if (fromDate) {
980
+ builder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
981
+ countBuilder.whereAnd("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
982
+ }
983
+ if (toDate) {
984
+ builder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
985
+ countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
986
+ }
987
+ builder.orderBy("createdAt", "DESC");
988
+ if (typeof limit === "number") builder.limit(limit);
989
+ if (typeof offset === "number") builder.offset(offset);
990
+ const { sql, params } = builder.build();
991
+ let total = 0;
992
+ if (limit !== void 0 && offset !== void 0) {
993
+ const { sql: countSql, params: countParams } = countBuilder.build();
994
+ const countResult = await this.executeQuery({ sql: countSql, params: countParams, first: true });
995
+ total = Number(countResult?.count ?? 0);
996
+ }
997
+ const results = await this.executeQuery({ sql, params });
998
+ const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
999
+ return { runs, total: total || runs.length };
1000
+ } catch (error) {
1001
+ this.logger.error("Error getting workflow runs:", {
1002
+ message: error instanceof Error ? error.message : String(error)
1003
+ });
1004
+ throw error;
1005
+ }
1006
+ }
1007
+ async getWorkflowRunById({
1008
+ runId,
1009
+ workflowName
1010
+ }) {
1011
+ const fullTableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1012
+ try {
1013
+ const conditions = [];
1014
+ const params = [];
1015
+ if (runId) {
1016
+ conditions.push("run_id = ?");
1017
+ params.push(runId);
1018
+ }
1019
+ if (workflowName) {
1020
+ conditions.push("workflow_name = ?");
1021
+ params.push(workflowName);
1022
+ }
1023
+ const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
1024
+ const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
1025
+ const result = await this.executeQuery({ sql, params, first: true });
1026
+ if (!result) return null;
1027
+ return this.parseWorkflowRun(result);
1028
+ } catch (error) {
1029
+ this.logger.error("Error getting workflow run by ID:", {
1030
+ message: error instanceof Error ? error.message : String(error)
1031
+ });
1032
+ throw error;
1033
+ }
931
1034
  }
932
1035
  /**
933
1036
  * Close the database connection
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/cloudflare-d1",
3
- "version": "0.1.6-alpha.4",
3
+ "version": "0.1.6-alpha.5",
4
4
  "description": "D1 provider for Mastra - includes db storage capabilities",
5
5
  "type": "module",
6
6
  "files": [