@mastra/cloudflare-d1 0.0.0-trigger-playground-ui-package-20250506151043 → 0.0.0-update-stores-peerDeps-20250723031338

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,9 +1,10 @@
1
- import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_TRACES, TABLE_EVALS } from '@mastra/core/storage';
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 } from '@mastra/core/storage';
2
3
  import Cloudflare from 'cloudflare';
4
+ import { parseSqlIdentifier } from '@mastra/core/utils';
5
+ import { MessageList } from '@mastra/core/agent';
3
6
 
4
7
  // src/storage/index.ts
5
-
6
- // src/storage/sql-builder.ts
7
8
  var SqlBuilder = class {
8
9
  sql = "";
9
10
  params = [];
@@ -13,12 +14,15 @@ var SqlBuilder = class {
13
14
  if (!columns || Array.isArray(columns) && columns.length === 0) {
14
15
  this.sql = "SELECT *";
15
16
  } else {
16
- this.sql = `SELECT ${Array.isArray(columns) ? columns.join(", ") : columns}`;
17
+ const cols = Array.isArray(columns) ? columns : [columns];
18
+ const parsedCols = cols.map((col) => parseSelectIdentifier(col));
19
+ this.sql = `SELECT ${parsedCols.join(", ")}`;
17
20
  }
18
21
  return this;
19
22
  }
20
23
  from(table) {
21
- this.sql += ` FROM ${table}`;
24
+ const parsedTableName = parseSqlIdentifier(table, "table name");
25
+ this.sql += ` FROM ${parsedTableName}`;
22
26
  return this;
23
27
  }
24
28
  /**
@@ -55,7 +59,11 @@ var SqlBuilder = class {
55
59
  return this;
56
60
  }
57
61
  orderBy(column, direction = "ASC") {
58
- this.sql += ` ORDER BY ${column} ${direction}`;
62
+ const parsedColumn = parseSqlIdentifier(column, "column name");
63
+ if (!["ASC", "DESC"].includes(direction)) {
64
+ throw new Error(`Invalid sort direction: ${direction}`);
65
+ }
66
+ this.sql += ` ORDER BY ${parsedColumn} ${direction}`;
59
67
  return this;
60
68
  }
61
69
  limit(count) {
@@ -81,27 +89,33 @@ var SqlBuilder = class {
81
89
  * @param updateMap Object mapping columns to update to their new value (e.g. { name: 'excluded.name' })
82
90
  */
83
91
  insert(table, columns, values, conflictColumns, updateMap) {
84
- const placeholders = columns.map(() => "?").join(", ");
92
+ const parsedTableName = parseSqlIdentifier(table, "table name");
93
+ const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
94
+ const placeholders = parsedColumns.map(() => "?").join(", ");
85
95
  if (conflictColumns && updateMap) {
96
+ const parsedConflictColumns = conflictColumns.map((col) => parseSqlIdentifier(col, "column name"));
86
97
  const updateClause = Object.entries(updateMap).map(([col, expr]) => `${col} = ${expr}`).join(", ");
87
- this.sql = `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${conflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
98
+ this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${parsedConflictColumns.join(", ")}) DO UPDATE SET ${updateClause}`;
88
99
  this.params.push(...values);
89
100
  return this;
90
101
  }
91
- this.sql = `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${placeholders})`;
102
+ this.sql = `INSERT INTO ${parsedTableName} (${parsedColumns.join(", ")}) VALUES (${placeholders})`;
92
103
  this.params.push(...values);
93
104
  return this;
94
105
  }
95
106
  // Update operations
96
107
  update(table, columns, values) {
97
- const setClause = columns.map((col) => `${col} = ?`).join(", ");
98
- this.sql = `UPDATE ${table} SET ${setClause}`;
108
+ const parsedTableName = parseSqlIdentifier(table, "table name");
109
+ const parsedColumns = columns.map((col) => parseSqlIdentifier(col, "column name"));
110
+ const setClause = parsedColumns.map((col) => `${col} = ?`).join(", ");
111
+ this.sql = `UPDATE ${parsedTableName} SET ${setClause}`;
99
112
  this.params.push(...values);
100
113
  return this;
101
114
  }
102
115
  // Delete operations
103
116
  delete(table) {
104
- this.sql = `DELETE FROM ${table}`;
117
+ const parsedTableName = parseSqlIdentifier(table, "table name");
118
+ this.sql = `DELETE FROM ${parsedTableName}`;
105
119
  return this;
106
120
  }
107
121
  /**
@@ -112,9 +126,16 @@ var SqlBuilder = class {
112
126
  * @returns The builder instance
113
127
  */
114
128
  createTable(table, columnDefinitions, tableConstraints) {
115
- const columns = columnDefinitions.join(", ");
129
+ const parsedTableName = parseSqlIdentifier(table, "table name");
130
+ const parsedColumnDefinitions = columnDefinitions.map((def) => {
131
+ const colName = def.split(/\s+/)[0];
132
+ if (!colName) throw new Error("Empty column name in definition");
133
+ parseSqlIdentifier(colName, "column name");
134
+ return def;
135
+ });
136
+ const columns = parsedColumnDefinitions.join(", ");
116
137
  const constraints = tableConstraints && tableConstraints.length > 0 ? ", " + tableConstraints.join(", ") : "";
117
- this.sql = `CREATE TABLE IF NOT EXISTS ${table} (${columns}${constraints})`;
138
+ this.sql = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (${columns}${constraints})`;
118
139
  return this;
119
140
  }
120
141
  /**
@@ -137,13 +158,10 @@ var SqlBuilder = class {
137
158
  * @returns The builder instance
138
159
  */
139
160
  createIndex(indexName, tableName, columnName, indexType = "") {
140
- this.sql = `CREATE ${indexType ? indexType + " " : ""}INDEX IF NOT EXISTS ${indexName} ON ${tableName}(${columnName})`;
141
- return this;
142
- }
143
- // Raw SQL with params
144
- raw(sql, ...params) {
145
- this.sql = sql;
146
- this.params.push(...params);
161
+ const parsedIndexName = parseSqlIdentifier(indexName, "index name");
162
+ const parsedTableName = parseSqlIdentifier(tableName, "table name");
163
+ const parsedColumnName = parseSqlIdentifier(columnName, "column name");
164
+ this.sql = `CREATE ${indexType ? indexType + " " : ""}INDEX IF NOT EXISTS ${parsedIndexName} ON ${parsedTableName}(${parsedColumnName})`;
147
165
  return this;
148
166
  }
149
167
  /**
@@ -153,11 +171,12 @@ var SqlBuilder = class {
153
171
  * @param exact If true, will not add % wildcards
154
172
  */
155
173
  like(column, value, exact = false) {
174
+ const parsedColumnName = parseSqlIdentifier(column, "column name");
156
175
  const likeValue = exact ? value : `%${value}%`;
157
176
  if (this.whereAdded) {
158
- this.sql += ` AND ${column} LIKE ?`;
177
+ this.sql += ` AND ${parsedColumnName} LIKE ?`;
159
178
  } else {
160
- this.sql += ` WHERE ${column} LIKE ?`;
179
+ this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
161
180
  this.whereAdded = true;
162
181
  }
163
182
  this.params.push(likeValue);
@@ -170,11 +189,13 @@ var SqlBuilder = class {
170
189
  * @param value The value to match
171
190
  */
172
191
  jsonLike(column, key, value) {
173
- const jsonPattern = `%"${key}":"${value}"%`;
192
+ const parsedColumnName = parseSqlIdentifier(column, "column name");
193
+ const parsedKey = parseSqlIdentifier(key, "key name");
194
+ const jsonPattern = `%"${parsedKey}":"${value}"%`;
174
195
  if (this.whereAdded) {
175
- this.sql += ` AND ${column} LIKE ?`;
196
+ this.sql += ` AND ${parsedColumnName} LIKE ?`;
176
197
  } else {
177
- this.sql += ` WHERE ${column} LIKE ?`;
198
+ this.sql += ` WHERE ${parsedColumnName} LIKE ?`;
178
199
  this.whereAdded = true;
179
200
  }
180
201
  this.params.push(jsonPattern);
@@ -204,380 +225,426 @@ var SqlBuilder = class {
204
225
  function createSqlBuilder() {
205
226
  return new SqlBuilder();
206
227
  }
228
+ var SQL_IDENTIFIER_PATTERN = /^[a-zA-Z0-9_]+(\s+AS\s+[a-zA-Z0-9_]+)?$/;
229
+ function parseSelectIdentifier(column) {
230
+ if (column !== "*" && !SQL_IDENTIFIER_PATTERN.test(column)) {
231
+ throw new Error(
232
+ `Invalid column name: "${column}". Must be "*" or a valid identifier (letters, numbers, underscores), optionally with "AS alias".`
233
+ );
234
+ }
235
+ return column;
236
+ }
207
237
 
208
- // src/storage/index.ts
238
+ // src/storage/domains/utils.ts
209
239
  function isArrayOfRecords(value) {
210
240
  return value && Array.isArray(value) && value.length > 0;
211
241
  }
212
- var D1Store = class extends MastraStorage {
213
- client;
214
- accountId;
215
- databaseId;
216
- binding;
217
- // D1Database binding
218
- tablePrefix;
219
- /**
220
- * Creates a new D1Store instance
221
- * @param config Configuration for D1 access (either REST API or Workers Binding API)
222
- */
223
- constructor(config) {
224
- super({ name: "D1" });
225
- this.tablePrefix = config.tablePrefix || "";
226
- if ("binding" in config) {
227
- if (!config.binding) {
228
- throw new Error("D1 binding is required when using Workers Binding API");
229
- }
230
- this.binding = config.binding;
231
- this.logger.info("Using D1 Workers Binding API");
232
- } else {
233
- if (!config.accountId || !config.databaseId || !config.apiToken) {
234
- throw new Error("accountId, databaseId, and apiToken are required when using REST API");
235
- }
236
- this.accountId = config.accountId;
237
- this.databaseId = config.databaseId;
238
- this.client = new Cloudflare({
239
- apiToken: config.apiToken
240
- });
241
- this.logger.info("Using D1 REST API");
242
- }
243
- }
244
- // Helper method to get the full table name with prefix
245
- getTableName(tableName) {
246
- return `${this.tablePrefix}${tableName}`;
242
+ function deserializeValue(value, type) {
243
+ if (value === null || value === void 0) return null;
244
+ if (type === "date" && typeof value === "string") {
245
+ return new Date(value);
247
246
  }
248
- formatSqlParams(params) {
249
- return params.map((p) => p === void 0 || p === null ? null : p);
250
- }
251
- // Helper method to create SQL indexes for better query performance
252
- async createIndexIfNotExists(tableName, columnName, indexType = "") {
253
- const fullTableName = this.getTableName(tableName);
254
- const indexName = `idx_${tableName}_${columnName}`;
247
+ if (type === "jsonb" && typeof value === "string") {
255
248
  try {
256
- const checkQuery = createSqlBuilder().checkIndexExists(indexName, fullTableName);
257
- const { sql: checkSql, params: checkParams } = checkQuery.build();
258
- const indexExists = await this.executeQuery({
259
- sql: checkSql,
260
- params: checkParams,
261
- first: true
262
- });
263
- if (!indexExists) {
264
- const createQuery = createSqlBuilder().createIndex(indexName, fullTableName, columnName, indexType);
265
- const { sql: createSql, params: createParams } = createQuery.build();
266
- await this.executeQuery({ sql: createSql, params: createParams });
267
- this.logger.debug(`Created index ${indexName} on ${fullTableName}(${columnName})`);
268
- }
269
- } catch (error) {
270
- this.logger.error(`Error creating index on ${fullTableName}(${columnName}):`, {
271
- message: error instanceof Error ? error.message : String(error)
272
- });
249
+ return JSON.parse(value);
250
+ } catch {
251
+ return value;
273
252
  }
274
253
  }
275
- async executeWorkersBindingQuery({
276
- sql,
277
- params = [],
278
- first = false
279
- }) {
280
- if (!this.binding) {
281
- throw new Error("Workers binding is not configured");
282
- }
254
+ if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
283
255
  try {
284
- const statement = this.binding.prepare(sql);
285
- const formattedParams = this.formatSqlParams(params);
286
- let result;
287
- if (formattedParams.length > 0) {
288
- if (first) {
289
- result = await statement.bind(...formattedParams).first();
290
- if (!result) return null;
291
- return result;
292
- } else {
293
- result = await statement.bind(...formattedParams).all();
294
- const results = result.results || [];
295
- if (result.meta) {
296
- this.logger.debug("Query metadata", { meta: result.meta });
297
- }
298
- return results;
299
- }
300
- } else {
301
- if (first) {
302
- result = await statement.first();
303
- if (!result) return null;
304
- return result;
305
- } else {
306
- result = await statement.all();
307
- const results = result.results || [];
308
- if (result.meta) {
309
- this.logger.debug("Query metadata", { meta: result.meta });
310
- }
311
- return results;
312
- }
313
- }
314
- } catch (workerError) {
315
- this.logger.error("Workers Binding API error", {
316
- message: workerError instanceof Error ? workerError.message : String(workerError),
317
- sql
318
- });
319
- throw new Error(`D1 Workers API error: ${workerError.message}`);
256
+ return JSON.parse(value);
257
+ } catch {
258
+ return value;
320
259
  }
321
260
  }
322
- async executeRestQuery({
323
- sql,
324
- params = [],
325
- first = false
326
- }) {
327
- if (!this.client || !this.accountId || !this.databaseId) {
328
- throw new Error("Missing required REST API configuration");
261
+ return value;
262
+ }
263
+
264
+ // src/storage/domains/legacy-evals/index.ts
265
+ var LegacyEvalsStorageD1 = class extends LegacyEvalsStorage {
266
+ operations;
267
+ constructor({ operations }) {
268
+ super();
269
+ this.operations = operations;
270
+ }
271
+ async getEvals(options) {
272
+ const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
273
+ const fullTableName = this.operations.getTableName(TABLE_EVALS);
274
+ const conditions = [];
275
+ const queryParams = [];
276
+ if (agentName) {
277
+ conditions.push(`agent_name = ?`);
278
+ queryParams.push(agentName);
329
279
  }
280
+ if (type === "test") {
281
+ conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
282
+ } else if (type === "live") {
283
+ conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
284
+ }
285
+ if (dateRange?.start) {
286
+ conditions.push(`created_at >= ?`);
287
+ queryParams.push(serializeDate(dateRange.start));
288
+ }
289
+ if (dateRange?.end) {
290
+ conditions.push(`created_at <= ?`);
291
+ queryParams.push(serializeDate(dateRange.end));
292
+ }
293
+ const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
294
+ if (conditions.length > 0) {
295
+ countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
296
+ }
297
+ const { sql: countSql, params: countParams } = countQueryBuilder.build();
330
298
  try {
331
- const response = await this.client.d1.database.query(this.databaseId, {
332
- account_id: this.accountId,
333
- sql,
334
- params: this.formatSqlParams(params)
299
+ const countResult = await this.operations.executeQuery({
300
+ sql: countSql,
301
+ params: countParams,
302
+ first: true
335
303
  });
336
- const result = response.result || [];
337
- const results = result.flatMap((r) => r.results || []);
338
- if (first) {
339
- const firstResult = isArrayOfRecords(results) && results.length > 0 ? results[0] : null;
340
- if (!firstResult) return null;
341
- return firstResult;
304
+ const total = Number(countResult?.count || 0);
305
+ const currentOffset = page * perPage;
306
+ if (total === 0) {
307
+ return {
308
+ evals: [],
309
+ total: 0,
310
+ page,
311
+ perPage,
312
+ hasMore: false
313
+ };
314
+ }
315
+ const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
316
+ if (conditions.length > 0) {
317
+ dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
342
318
  }
343
- return results;
344
- } catch (restError) {
345
- this.logger.error("REST API error", {
346
- message: restError instanceof Error ? restError.message : String(restError),
347
- sql
319
+ dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
320
+ const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
321
+ const rows = await this.operations.executeQuery({
322
+ sql: dataSql,
323
+ params: dataParams
324
+ });
325
+ const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
326
+ const result = deserializeValue(row.result);
327
+ const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
328
+ if (!result || typeof result !== "object" || !("score" in result)) {
329
+ throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
330
+ }
331
+ return {
332
+ input: row.input,
333
+ output: row.output,
334
+ result,
335
+ agentName: row.agent_name,
336
+ metricName: row.metric_name,
337
+ instructions: row.instructions,
338
+ testInfo,
339
+ globalRunId: row.global_run_id,
340
+ runId: row.run_id,
341
+ createdAt: row.created_at
342
+ };
348
343
  });
349
- throw new Error(`D1 REST API error: ${restError.message}`);
344
+ const hasMore = currentOffset + evals.length < total;
345
+ return {
346
+ evals,
347
+ total,
348
+ page,
349
+ perPage,
350
+ hasMore
351
+ };
352
+ } catch (error) {
353
+ throw new MastraError(
354
+ {
355
+ id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
356
+ domain: ErrorDomain.STORAGE,
357
+ category: ErrorCategory.THIRD_PARTY,
358
+ text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
359
+ details: { agentName: agentName ?? "", type: type ?? "" }
360
+ },
361
+ error
362
+ );
350
363
  }
351
364
  }
352
365
  /**
353
- * Execute a SQL query against the D1 database
354
- * @param options Query options including SQL, parameters, and whether to return only the first result
355
- * @returns Query results as an array or a single object if first=true
366
+ * @deprecated use getEvals instead
356
367
  */
357
- async executeQuery(options) {
358
- const { sql, params = [], first = false } = options;
368
+ async getEvalsByAgentName(agentName, type) {
369
+ const fullTableName = this.operations.getTableName(TABLE_EVALS);
359
370
  try {
360
- this.logger.debug("Executing SQL query", { sql, params, first });
361
- if (this.binding) {
362
- return this.executeWorkersBindingQuery({ sql, params, first });
363
- } else if (this.client && this.accountId && this.databaseId) {
364
- return this.executeRestQuery({ sql, params, first });
365
- } else {
366
- throw new Error("No valid D1 configuration provided");
371
+ let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
372
+ if (type === "test") {
373
+ query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
374
+ } else if (type === "live") {
375
+ query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
367
376
  }
377
+ query.orderBy("created_at", "DESC");
378
+ const { sql, params } = query.build();
379
+ const results = await this.operations.executeQuery({ sql, params });
380
+ return isArrayOfRecords(results) ? results.map((row) => {
381
+ const result = deserializeValue(row.result);
382
+ const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
383
+ return {
384
+ input: row.input || "",
385
+ output: row.output || "",
386
+ result,
387
+ agentName: row.agent_name || "",
388
+ metricName: row.metric_name || "",
389
+ instructions: row.instructions || "",
390
+ runId: row.run_id || "",
391
+ globalRunId: row.global_run_id || "",
392
+ createdAt: row.created_at || "",
393
+ testInfo
394
+ };
395
+ }) : [];
368
396
  } catch (error) {
369
- this.logger.error("Error executing SQL query", {
370
- message: error instanceof Error ? error.message : String(error),
371
- sql,
372
- params,
373
- first
374
- });
375
- throw new Error(`D1 query error: ${error.message}`);
376
- }
377
- }
378
- // Helper to convert storage type to SQL type
379
- getSqlType(type) {
380
- switch (type) {
381
- case "text":
382
- return "TEXT";
383
- case "timestamp":
384
- return "TIMESTAMP";
385
- case "integer":
386
- return "INTEGER";
387
- case "bigint":
388
- return "INTEGER";
389
- // SQLite doesn't have a separate BIGINT type
390
- case "jsonb":
391
- return "TEXT";
392
- // Store JSON as TEXT in SQLite
393
- default:
394
- return "TEXT";
395
- }
396
- }
397
- ensureDate(date) {
398
- if (!date) return void 0;
399
- return date instanceof Date ? date : new Date(date);
400
- }
401
- serializeDate(date) {
402
- if (!date) return void 0;
403
- const dateObj = this.ensureDate(date);
404
- return dateObj?.toISOString();
405
- }
406
- // Helper to serialize objects to JSON strings
407
- serializeValue(value) {
408
- if (value === null || value === void 0) return null;
409
- if (value instanceof Date) {
410
- return this.serializeDate(value);
411
- }
412
- if (typeof value === "object") {
413
- return JSON.stringify(value);
397
+ const mastraError = new MastraError(
398
+ {
399
+ id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
400
+ domain: ErrorDomain.STORAGE,
401
+ category: ErrorCategory.THIRD_PARTY,
402
+ text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
403
+ details: { agentName }
404
+ },
405
+ error
406
+ );
407
+ this.logger?.error(mastraError.toString());
408
+ this.logger?.trackException(mastraError);
409
+ return [];
414
410
  }
415
- return value;
416
411
  }
417
- // Helper to deserialize JSON strings to objects
418
- deserializeValue(value, type) {
419
- if (value === null || value === void 0) return null;
420
- if (type === "date" && typeof value === "string") {
421
- return new Date(value);
422
- }
423
- if (type === "jsonb" && typeof value === "string") {
424
- try {
425
- return JSON.parse(value);
426
- } catch {
427
- return value;
428
- }
429
- }
430
- if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
431
- try {
432
- return JSON.parse(value);
433
- } catch {
434
- return value;
435
- }
436
- }
437
- return value;
412
+ };
413
+ var MemoryStorageD1 = class extends MemoryStorage {
414
+ operations;
415
+ constructor({ operations }) {
416
+ super();
417
+ this.operations = operations;
438
418
  }
439
- async createTable({
440
- tableName,
441
- schema
442
- }) {
443
- const fullTableName = this.getTableName(tableName);
444
- const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
445
- const type = this.getSqlType(colDef.type);
446
- const nullable = colDef.nullable === false ? "NOT NULL" : "";
447
- const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
448
- return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
419
+ async getResourceById({ resourceId }) {
420
+ const resource = await this.operations.load({
421
+ tableName: TABLE_RESOURCES,
422
+ keys: { id: resourceId }
449
423
  });
450
- const tableConstraints = [];
451
- if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
452
- tableConstraints.push("UNIQUE (workflow_name, run_id)");
453
- }
454
- const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
455
- const { sql, params } = query.build();
456
- try {
457
- await this.executeQuery({ sql, params });
458
- this.logger.debug(`Created table ${fullTableName}`);
459
- } catch (error) {
460
- this.logger.error(`Error creating table ${fullTableName}:`, {
461
- message: error instanceof Error ? error.message : String(error)
462
- });
463
- throw new Error(`Failed to create table ${fullTableName}: ${error}`);
464
- }
465
- }
466
- async clearTable({ tableName }) {
467
- const fullTableName = this.getTableName(tableName);
424
+ if (!resource) return null;
468
425
  try {
469
- const query = createSqlBuilder().delete(fullTableName);
470
- const { sql, params } = query.build();
471
- await this.executeQuery({ sql, params });
472
- this.logger.debug(`Cleared table ${fullTableName}`);
426
+ return {
427
+ ...resource,
428
+ createdAt: ensureDate(resource.createdAt),
429
+ updatedAt: ensureDate(resource.updatedAt),
430
+ metadata: typeof resource.metadata === "string" ? JSON.parse(resource.metadata || "{}") : resource.metadata
431
+ };
473
432
  } catch (error) {
474
- this.logger.error(`Error clearing table ${fullTableName}:`, {
475
- message: error instanceof Error ? error.message : String(error)
476
- });
477
- throw new Error(`Failed to clear table ${fullTableName}: ${error}`);
478
- }
479
- }
480
- async processRecord(record) {
481
- const processedRecord = {};
482
- for (const [key, value] of Object.entries(record)) {
483
- processedRecord[key] = this.serializeValue(value);
433
+ const mastraError = new MastraError(
434
+ {
435
+ id: "CLOUDFLARE_D1_STORAGE_GET_RESOURCE_BY_ID_ERROR",
436
+ domain: ErrorDomain.STORAGE,
437
+ category: ErrorCategory.THIRD_PARTY,
438
+ text: `Error processing resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
439
+ details: { resourceId }
440
+ },
441
+ error
442
+ );
443
+ this.logger?.error(mastraError.toString());
444
+ this.logger?.trackException(mastraError);
445
+ return null;
484
446
  }
485
- return processedRecord;
486
447
  }
487
- async insert({ tableName, record }) {
488
- const fullTableName = this.getTableName(tableName);
489
- const processedRecord = await this.processRecord(record);
448
+ async saveResource({ resource }) {
449
+ const fullTableName = this.operations.getTableName(TABLE_RESOURCES);
450
+ const resourceToSave = {
451
+ id: resource.id,
452
+ workingMemory: resource.workingMemory,
453
+ metadata: resource.metadata ? JSON.stringify(resource.metadata) : null,
454
+ createdAt: resource.createdAt,
455
+ updatedAt: resource.updatedAt
456
+ };
457
+ const processedRecord = await this.operations.processRecord(resourceToSave);
490
458
  const columns = Object.keys(processedRecord);
491
459
  const values = Object.values(processedRecord);
492
- const query = createSqlBuilder().insert(fullTableName, columns, values);
460
+ const updateMap = {
461
+ workingMemory: "excluded.workingMemory",
462
+ metadata: "excluded.metadata",
463
+ createdAt: "excluded.createdAt",
464
+ updatedAt: "excluded.updatedAt"
465
+ };
466
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
493
467
  const { sql, params } = query.build();
494
468
  try {
495
- await this.executeQuery({ sql, params });
469
+ await this.operations.executeQuery({ sql, params });
470
+ return resource;
496
471
  } catch (error) {
497
- const message = error instanceof Error ? error.message : String(error);
498
- this.logger.error(`Error inserting into ${fullTableName}:`, { message });
499
- throw new Error(`Failed to insert into ${fullTableName}: ${error}`);
472
+ throw new MastraError(
473
+ {
474
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_RESOURCE_ERROR",
475
+ domain: ErrorDomain.STORAGE,
476
+ category: ErrorCategory.THIRD_PARTY,
477
+ text: `Failed to save resource to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
478
+ details: { resourceId: resource.id }
479
+ },
480
+ error
481
+ );
500
482
  }
501
483
  }
502
- async load({ tableName, keys }) {
503
- const fullTableName = this.getTableName(tableName);
504
- const query = createSqlBuilder().select("*").from(fullTableName);
505
- let firstKey = true;
506
- for (const [key, value] of Object.entries(keys)) {
507
- if (firstKey) {
508
- query.where(`${key} = ?`, value);
509
- firstKey = false;
510
- } else {
511
- query.andWhere(`${key} = ?`, value);
512
- }
484
+ async updateResource({
485
+ resourceId,
486
+ workingMemory,
487
+ metadata
488
+ }) {
489
+ const existingResource = await this.getResourceById({ resourceId });
490
+ if (!existingResource) {
491
+ const newResource = {
492
+ id: resourceId,
493
+ workingMemory,
494
+ metadata: metadata || {},
495
+ createdAt: /* @__PURE__ */ new Date(),
496
+ updatedAt: /* @__PURE__ */ new Date()
497
+ };
498
+ return this.saveResource({ resource: newResource });
513
499
  }
514
- query.limit(1);
500
+ const updatedAt = /* @__PURE__ */ new Date();
501
+ const updatedResource = {
502
+ ...existingResource,
503
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
504
+ metadata: {
505
+ ...existingResource.metadata,
506
+ ...metadata
507
+ },
508
+ updatedAt
509
+ };
510
+ const fullTableName = this.operations.getTableName(TABLE_RESOURCES);
511
+ const columns = ["workingMemory", "metadata", "updatedAt"];
512
+ const values = [updatedResource.workingMemory, JSON.stringify(updatedResource.metadata), updatedAt.toISOString()];
513
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
515
514
  const { sql, params } = query.build();
516
515
  try {
517
- const result = await this.executeQuery({ sql, params, first: true });
518
- if (!result) return null;
519
- const processedResult = {};
520
- for (const [key, value] of Object.entries(result)) {
521
- processedResult[key] = this.deserializeValue(value);
522
- }
523
- return processedResult;
516
+ await this.operations.executeQuery({ sql, params });
517
+ return updatedResource;
524
518
  } catch (error) {
525
- this.logger.error(`Error loading from ${fullTableName}:`, {
526
- message: error instanceof Error ? error.message : String(error)
527
- });
528
- return null;
519
+ throw new MastraError(
520
+ {
521
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_RESOURCE_ERROR",
522
+ domain: ErrorDomain.STORAGE,
523
+ category: ErrorCategory.THIRD_PARTY,
524
+ text: `Failed to update resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
525
+ details: { resourceId }
526
+ },
527
+ error
528
+ );
529
529
  }
530
530
  }
531
531
  async getThreadById({ threadId }) {
532
- const thread = await this.load({
532
+ const thread = await this.operations.load({
533
533
  tableName: TABLE_THREADS,
534
534
  keys: { id: threadId }
535
535
  });
536
536
  if (!thread) return null;
537
+ console.log("thread", thread);
537
538
  try {
538
539
  return {
539
540
  ...thread,
540
- createdAt: this.ensureDate(thread.createdAt),
541
- updatedAt: this.ensureDate(thread.updatedAt),
541
+ createdAt: ensureDate(thread.createdAt),
542
+ updatedAt: ensureDate(thread.updatedAt),
542
543
  metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
543
544
  };
544
545
  } catch (error) {
545
- this.logger.error(`Error processing thread ${threadId}:`, {
546
- message: error instanceof Error ? error.message : String(error)
547
- });
546
+ const mastraError = new MastraError(
547
+ {
548
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
549
+ domain: ErrorDomain.STORAGE,
550
+ category: ErrorCategory.THIRD_PARTY,
551
+ text: `Error processing thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
552
+ details: { threadId }
553
+ },
554
+ error
555
+ );
556
+ this.logger?.error(mastraError.toString());
557
+ this.logger?.trackException(mastraError);
548
558
  return null;
549
559
  }
550
560
  }
561
+ /**
562
+ * @deprecated use getThreadsByResourceIdPaginated instead
563
+ */
551
564
  async getThreadsByResourceId({ resourceId }) {
552
- const fullTableName = this.getTableName(TABLE_THREADS);
565
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
553
566
  try {
554
567
  const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
555
568
  const { sql, params } = query.build();
556
- const results = await this.executeQuery({ sql, params });
569
+ const results = await this.operations.executeQuery({ sql, params });
557
570
  return (isArrayOfRecords(results) ? results : []).map((thread) => ({
558
571
  ...thread,
559
- createdAt: this.ensureDate(thread.createdAt),
560
- updatedAt: this.ensureDate(thread.updatedAt),
572
+ createdAt: ensureDate(thread.createdAt),
573
+ updatedAt: ensureDate(thread.updatedAt),
561
574
  metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
562
575
  }));
563
576
  } catch (error) {
564
- this.logger.error(`Error getting threads by resourceId ${resourceId}:`, {
565
- message: error instanceof Error ? error.message : String(error)
566
- });
577
+ const mastraError = new MastraError(
578
+ {
579
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
580
+ domain: ErrorDomain.STORAGE,
581
+ category: ErrorCategory.THIRD_PARTY,
582
+ text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
583
+ details: { resourceId }
584
+ },
585
+ error
586
+ );
587
+ this.logger?.error(mastraError.toString());
588
+ this.logger?.trackException(mastraError);
567
589
  return [];
568
590
  }
569
591
  }
592
+ async getThreadsByResourceIdPaginated(args) {
593
+ const { resourceId, page, perPage } = args;
594
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
595
+ const mapRowToStorageThreadType = (row) => ({
596
+ ...row,
597
+ createdAt: ensureDate(row.createdAt),
598
+ updatedAt: ensureDate(row.updatedAt),
599
+ metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
600
+ });
601
+ try {
602
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
603
+ const countResult = await this.operations.executeQuery(countQuery.build());
604
+ const total = Number(countResult?.[0]?.count ?? 0);
605
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
606
+ const results = await this.operations.executeQuery(selectQuery.build());
607
+ const threads = results.map(mapRowToStorageThreadType);
608
+ return {
609
+ threads,
610
+ total,
611
+ page,
612
+ perPage,
613
+ hasMore: page * perPage + threads.length < total
614
+ };
615
+ } catch (error) {
616
+ const mastraError = new MastraError(
617
+ {
618
+ id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
619
+ domain: ErrorDomain.STORAGE,
620
+ category: ErrorCategory.THIRD_PARTY,
621
+ text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
622
+ details: { resourceId }
623
+ },
624
+ error
625
+ );
626
+ this.logger?.error(mastraError.toString());
627
+ this.logger?.trackException(mastraError);
628
+ return {
629
+ threads: [],
630
+ total: 0,
631
+ page,
632
+ perPage,
633
+ hasMore: false
634
+ };
635
+ }
636
+ }
570
637
  async saveThread({ thread }) {
571
- const fullTableName = this.getTableName(TABLE_THREADS);
638
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
572
639
  const threadToSave = {
573
640
  id: thread.id,
574
641
  resourceId: thread.resourceId,
575
642
  title: thread.title,
576
643
  metadata: thread.metadata ? JSON.stringify(thread.metadata) : null,
577
- createdAt: thread.createdAt,
578
- updatedAt: thread.updatedAt
644
+ createdAt: thread.createdAt.toISOString(),
645
+ updatedAt: thread.updatedAt.toISOString()
579
646
  };
580
- const processedRecord = await this.processRecord(threadToSave);
647
+ const processedRecord = await this.operations.processRecord(threadToSave);
581
648
  const columns = Object.keys(processedRecord);
582
649
  const values = Object.values(processedRecord);
583
650
  const updateMap = {
@@ -590,12 +657,19 @@ var D1Store = class extends MastraStorage {
590
657
  const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
591
658
  const { sql, params } = query.build();
592
659
  try {
593
- await this.executeQuery({ sql, params });
660
+ await this.operations.executeQuery({ sql, params });
594
661
  return thread;
595
662
  } catch (error) {
596
- const message = error instanceof Error ? error.message : String(error);
597
- this.logger.error(`Error saving thread to ${fullTableName}:`, { message });
598
- throw error;
663
+ throw new MastraError(
664
+ {
665
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
666
+ domain: ErrorDomain.STORAGE,
667
+ category: ErrorCategory.THIRD_PARTY,
668
+ text: `Failed to save thread to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
669
+ details: { threadId: thread.id }
670
+ },
671
+ error
672
+ );
599
673
  }
600
674
  }
601
675
  async updateThread({
@@ -604,20 +678,21 @@ var D1Store = class extends MastraStorage {
604
678
  metadata
605
679
  }) {
606
680
  const thread = await this.getThreadById({ threadId: id });
607
- if (!thread) {
608
- throw new Error(`Thread ${id} not found`);
609
- }
610
- const fullTableName = this.getTableName(TABLE_THREADS);
611
- const mergedMetadata = {
612
- ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
613
- ...metadata
614
- };
615
- const columns = ["title", "metadata", "updatedAt"];
616
- const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
617
- const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
618
- const { sql, params } = query.build();
619
681
  try {
620
- await this.executeQuery({ sql, params });
682
+ if (!thread) {
683
+ throw new Error(`Thread ${id} not found`);
684
+ }
685
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
686
+ const mergedMetadata = {
687
+ ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
688
+ ...metadata
689
+ };
690
+ const updatedAt = /* @__PURE__ */ new Date();
691
+ const columns = ["title", "metadata", "updatedAt"];
692
+ const values = [title, JSON.stringify(mergedMetadata), updatedAt.toISOString()];
693
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
694
+ const { sql, params } = query.build();
695
+ await this.operations.executeQuery({ sql, params });
621
696
  return {
622
697
  ...thread,
623
698
  title,
@@ -625,41 +700,64 @@ var D1Store = class extends MastraStorage {
625
700
  ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
626
701
  ...metadata
627
702
  },
628
- updatedAt: /* @__PURE__ */ new Date()
703
+ updatedAt
629
704
  };
630
705
  } catch (error) {
631
- const message = error instanceof Error ? error.message : String(error);
632
- this.logger.error("Error updating thread:", { message });
633
- throw error;
706
+ throw new MastraError(
707
+ {
708
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
709
+ domain: ErrorDomain.STORAGE,
710
+ category: ErrorCategory.THIRD_PARTY,
711
+ text: `Failed to update thread ${id}: ${error instanceof Error ? error.message : String(error)}`,
712
+ details: { threadId: id }
713
+ },
714
+ error
715
+ );
634
716
  }
635
717
  }
636
718
  async deleteThread({ threadId }) {
637
- const fullTableName = this.getTableName(TABLE_THREADS);
719
+ const fullTableName = this.operations.getTableName(TABLE_THREADS);
638
720
  try {
639
721
  const deleteThreadQuery = createSqlBuilder().delete(fullTableName).where("id = ?", threadId);
640
722
  const { sql: threadSql, params: threadParams } = deleteThreadQuery.build();
641
- await this.executeQuery({ sql: threadSql, params: threadParams });
642
- const messagesTableName = this.getTableName(TABLE_MESSAGES);
723
+ await this.operations.executeQuery({ sql: threadSql, params: threadParams });
724
+ const messagesTableName = this.operations.getTableName(TABLE_MESSAGES);
643
725
  const deleteMessagesQuery = createSqlBuilder().delete(messagesTableName).where("thread_id = ?", threadId);
644
726
  const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
645
- await this.executeQuery({ sql: messagesSql, params: messagesParams });
727
+ await this.operations.executeQuery({ sql: messagesSql, params: messagesParams });
646
728
  } catch (error) {
647
- this.logger.error(`Error deleting thread ${threadId}:`, {
648
- message: error instanceof Error ? error.message : String(error)
649
- });
650
- throw new Error(`Failed to delete thread ${threadId}: ${error}`);
729
+ throw new MastraError(
730
+ {
731
+ id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
732
+ domain: ErrorDomain.STORAGE,
733
+ category: ErrorCategory.THIRD_PARTY,
734
+ text: `Failed to delete thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
735
+ details: { threadId }
736
+ },
737
+ error
738
+ );
651
739
  }
652
740
  }
653
- // Thread and message management methods
654
- async saveMessages({ messages }) {
741
+ async saveMessages(args) {
742
+ const { messages, format = "v1" } = args;
655
743
  if (messages.length === 0) return [];
656
744
  try {
657
745
  const now = /* @__PURE__ */ new Date();
746
+ const threadId = messages[0]?.threadId;
658
747
  for (const [i, message] of messages.entries()) {
659
748
  if (!message.id) throw new Error(`Message at index ${i} missing id`);
660
- if (!message.threadId) throw new Error(`Message at index ${i} missing threadId`);
661
- if (!message.content) throw new Error(`Message at index ${i} missing content`);
662
- if (!message.role) throw new Error(`Message at index ${i} missing role`);
749
+ if (!message.threadId) {
750
+ throw new Error(`Message at index ${i} missing threadId`);
751
+ }
752
+ if (!message.content) {
753
+ throw new Error(`Message at index ${i} missing content`);
754
+ }
755
+ if (!message.role) {
756
+ throw new Error(`Message at index ${i} missing role`);
757
+ }
758
+ if (!message.resourceId) {
759
+ throw new Error(`Message at index ${i} missing resourceId`);
760
+ }
663
761
  const thread = await this.getThreadById({ threadId: message.threadId });
664
762
  if (!thread) {
665
763
  throw new Error(`Thread ${message.threadId} not found`);
@@ -673,74 +771,119 @@ var D1Store = class extends MastraStorage {
673
771
  content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
674
772
  createdAt: createdAt.toISOString(),
675
773
  role: message.role,
676
- type: message.type
774
+ type: message.type || "v2",
775
+ resourceId: message.resourceId
677
776
  };
678
777
  });
679
- await this.batchInsert({
680
- tableName: TABLE_MESSAGES,
681
- records: messagesToInsert
682
- });
778
+ await Promise.all([
779
+ this.operations.batchUpsert({
780
+ tableName: TABLE_MESSAGES,
781
+ records: messagesToInsert
782
+ }),
783
+ // Update thread's updatedAt timestamp
784
+ this.operations.executeQuery({
785
+ sql: `UPDATE ${this.operations.getTableName(TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
786
+ params: [now.toISOString(), threadId]
787
+ })
788
+ ]);
683
789
  this.logger.debug(`Saved ${messages.length} messages`);
684
- return messages;
790
+ const list = new MessageList().add(messages, "memory");
791
+ if (format === `v2`) return list.get.all.v2();
792
+ return list.get.all.v1();
685
793
  } catch (error) {
686
- this.logger.error("Error saving messages:", { message: error instanceof Error ? error.message : String(error) });
687
- throw error;
794
+ throw new MastraError(
795
+ {
796
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
797
+ domain: ErrorDomain.STORAGE,
798
+ category: ErrorCategory.THIRD_PARTY,
799
+ text: `Failed to save messages: ${error instanceof Error ? error.message : String(error)}`
800
+ },
801
+ error
802
+ );
688
803
  }
689
804
  }
690
- async getMessages({ threadId, selectBy }) {
691
- const fullTableName = this.getTableName(TABLE_MESSAGES);
692
- const limit = typeof selectBy?.last === "number" ? selectBy.last : 40;
693
- const include = selectBy?.include || [];
694
- const messages = [];
695
- try {
696
- if (include.length) {
697
- const prevMax = Math.max(...include.map((i) => i.withPreviousMessages || 0));
698
- const nextMax = Math.max(...include.map((i) => i.withNextMessages || 0));
699
- const includeIds = include.map((i) => i.id);
700
- const sql2 = `
701
- WITH ordered_messages AS (
702
- SELECT
703
- *,
704
- ROW_NUMBER() OVER (ORDER BY createdAt DESC) AS row_num
705
- FROM ${fullTableName}
706
- WHERE thread_id = ?
707
- )
708
- SELECT
709
- m.id,
710
- m.content,
711
- m.role,
712
- m.type,
713
- m.createdAt,
714
- m.thread_id AS "threadId"
715
- FROM ordered_messages m
716
- WHERE m.id IN (${includeIds.map(() => "?").join(",")})
717
- OR EXISTS (
718
- SELECT 1 FROM ordered_messages target
719
- WHERE target.id IN (${includeIds.map(() => "?").join(",")})
720
- AND (
721
- (m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
722
- OR
723
- (m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
724
- )
725
- )
726
- ORDER BY m.createdAt DESC
727
- `;
728
- const params2 = [
729
- threadId,
730
- ...includeIds,
731
- // for m.id IN (...)
732
- ...includeIds,
733
- // for target.id IN (...)
734
- prevMax,
735
- nextMax
736
- ];
737
- const includeResult = await this.executeQuery({ sql: sql2, params: params2 });
738
- if (Array.isArray(includeResult)) messages.push(...includeResult);
739
- }
805
+ async _getIncludedMessages(threadId, selectBy) {
806
+ const include = selectBy?.include;
807
+ if (!include) return null;
808
+ const unionQueries = [];
809
+ const params = [];
810
+ let paramIdx = 1;
811
+ for (const inc of include) {
812
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
813
+ const searchId = inc.threadId || threadId;
814
+ unionQueries.push(`
815
+ SELECT * FROM (
816
+ WITH ordered_messages AS (
817
+ SELECT
818
+ *,
819
+ ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
820
+ FROM ${this.operations.getTableName(TABLE_MESSAGES)}
821
+ WHERE thread_id = ?
822
+ )
823
+ SELECT
824
+ m.id,
825
+ m.content,
826
+ m.role,
827
+ m.type,
828
+ m.createdAt,
829
+ m.thread_id AS threadId,
830
+ m.resourceId
831
+ FROM ordered_messages m
832
+ WHERE m.id = ?
833
+ OR EXISTS (
834
+ SELECT 1 FROM ordered_messages target
835
+ WHERE target.id = ?
836
+ AND (
837
+ (m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
838
+ OR
839
+ (m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
840
+ )
841
+ )
842
+ ) AS query_${paramIdx}
843
+ `);
844
+ params.push(searchId, id, id, withNextMessages, withPreviousMessages);
845
+ paramIdx++;
846
+ }
847
+ const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
848
+ const messages = await this.operations.executeQuery({ sql: finalQuery, params });
849
+ if (!Array.isArray(messages)) {
850
+ return [];
851
+ }
852
+ const processedMessages = messages.map((message) => {
853
+ const processedMsg = {};
854
+ for (const [key, value] of Object.entries(message)) {
855
+ if (key === `type` && value === `v2`) continue;
856
+ processedMsg[key] = deserializeValue(value);
857
+ }
858
+ return processedMsg;
859
+ });
860
+ return processedMessages;
861
+ }
862
+ async getMessages({
863
+ threadId,
864
+ selectBy,
865
+ format
866
+ }) {
867
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
868
+ const limit = resolveMessageLimit({
869
+ last: selectBy?.last,
870
+ defaultLimit: 40
871
+ });
872
+ const include = selectBy?.include || [];
873
+ const messages = [];
874
+ try {
875
+ if (include.length) {
876
+ const includeResult = await this._getIncludedMessages(threadId, selectBy);
877
+ if (Array.isArray(includeResult)) messages.push(...includeResult);
878
+ }
740
879
  const excludeIds = messages.map((m) => m.id);
741
- let query = createSqlBuilder().select(["id", "content", "role", "type", '"createdAt"', 'thread_id AS "threadId"']).from(fullTableName).where("thread_id = ?", threadId).andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds).orderBy("createdAt", "DESC").limit(limit);
880
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
881
+ if (excludeIds.length > 0) {
882
+ query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
883
+ }
884
+ query.orderBy("createdAt", "DESC").limit(limit);
742
885
  const { sql, params } = query.build();
743
- const result = await this.executeQuery({ sql, params });
886
+ const result = await this.operations.executeQuery({ sql, params });
744
887
  if (Array.isArray(result)) messages.push(...result);
745
888
  messages.sort((a, b) => {
746
889
  const aRecord = a;
@@ -752,28 +895,982 @@ var D1Store = class extends MastraStorage {
752
895
  const processedMessages = messages.map((message) => {
753
896
  const processedMsg = {};
754
897
  for (const [key, value] of Object.entries(message)) {
755
- processedMsg[key] = this.deserializeValue(value);
898
+ if (key === `type` && value === `v2`) continue;
899
+ processedMsg[key] = deserializeValue(value);
900
+ }
901
+ return processedMsg;
902
+ });
903
+ this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
904
+ const list = new MessageList().add(processedMessages, "memory");
905
+ if (format === `v2`) return list.get.all.v2();
906
+ return list.get.all.v1();
907
+ } catch (error) {
908
+ const mastraError = new MastraError(
909
+ {
910
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
911
+ domain: ErrorDomain.STORAGE,
912
+ category: ErrorCategory.THIRD_PARTY,
913
+ text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
914
+ details: { threadId }
915
+ },
916
+ error
917
+ );
918
+ this.logger?.error(mastraError.toString());
919
+ this.logger?.trackException(mastraError);
920
+ throw mastraError;
921
+ }
922
+ }
923
+ async getMessagesPaginated({
924
+ threadId,
925
+ selectBy,
926
+ format
927
+ }) {
928
+ const { dateRange, page = 0, perPage: perPageInput } = selectBy?.pagination || {};
929
+ const { start: fromDate, end: toDate } = dateRange || {};
930
+ const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
931
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
932
+ const messages = [];
933
+ try {
934
+ if (selectBy?.include?.length) {
935
+ const includeResult = await this._getIncludedMessages(threadId, selectBy);
936
+ if (Array.isArray(includeResult)) messages.push(...includeResult);
937
+ }
938
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
939
+ if (fromDate) {
940
+ countQuery.andWhere("createdAt >= ?", serializeDate(fromDate));
941
+ }
942
+ if (toDate) {
943
+ countQuery.andWhere("createdAt <= ?", serializeDate(toDate));
944
+ }
945
+ const countResult = await this.operations.executeQuery(countQuery.build());
946
+ const total = Number(countResult[0]?.count ?? 0);
947
+ if (total === 0 && messages.length === 0) {
948
+ return {
949
+ messages: [],
950
+ total: 0,
951
+ page,
952
+ perPage,
953
+ hasMore: false
954
+ };
955
+ }
956
+ const excludeIds = messages.map((m) => m.id);
957
+ const excludeCondition = excludeIds.length > 0 ? `AND id NOT IN (${excludeIds.map(() => "?").join(",")})` : "";
958
+ let query;
959
+ let queryParams = [threadId];
960
+ if (fromDate) {
961
+ queryParams.push(serializeDate(fromDate));
962
+ }
963
+ if (toDate) {
964
+ queryParams.push(serializeDate(toDate));
965
+ }
966
+ if (excludeIds.length > 0) {
967
+ queryParams.push(...excludeIds);
968
+ }
969
+ if (selectBy?.last && selectBy.last > 0) {
970
+ query = `
971
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
972
+ FROM ${fullTableName}
973
+ WHERE thread_id = ?
974
+ ${fromDate ? "AND createdAt >= ?" : ""}
975
+ ${toDate ? "AND createdAt <= ?" : ""}
976
+ ${excludeCondition}
977
+ ORDER BY createdAt DESC
978
+ LIMIT ?
979
+ `;
980
+ queryParams.push(selectBy.last);
981
+ } else {
982
+ query = `
983
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
984
+ FROM ${fullTableName}
985
+ WHERE thread_id = ?
986
+ ${fromDate ? "AND createdAt >= ?" : ""}
987
+ ${toDate ? "AND createdAt <= ?" : ""}
988
+ ${excludeCondition}
989
+ ORDER BY createdAt DESC
990
+ LIMIT ? OFFSET ?
991
+ `;
992
+ queryParams.push(perPage, page * perPage);
993
+ }
994
+ const results = await this.operations.executeQuery({ sql: query, params: queryParams });
995
+ const processedMessages = results.map((message) => {
996
+ const processedMsg = {};
997
+ for (const [key, value] of Object.entries(message)) {
998
+ if (key === `type` && value === `v2`) continue;
999
+ processedMsg[key] = deserializeValue(value);
1000
+ }
1001
+ return processedMsg;
1002
+ });
1003
+ if (selectBy?.last) {
1004
+ processedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1005
+ }
1006
+ const list = new MessageList().add(processedMessages, "memory");
1007
+ messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
1008
+ return {
1009
+ messages,
1010
+ total,
1011
+ page,
1012
+ perPage,
1013
+ hasMore: selectBy?.last ? false : page * perPage + messages.length < total
1014
+ };
1015
+ } catch (error) {
1016
+ const mastraError = new MastraError(
1017
+ {
1018
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
1019
+ domain: ErrorDomain.STORAGE,
1020
+ category: ErrorCategory.THIRD_PARTY,
1021
+ text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1022
+ details: { threadId }
1023
+ },
1024
+ error
1025
+ );
1026
+ this.logger?.error(mastraError.toString());
1027
+ this.logger?.trackException(mastraError);
1028
+ return {
1029
+ messages: [],
1030
+ total: 0,
1031
+ page,
1032
+ perPage,
1033
+ hasMore: false
1034
+ };
1035
+ }
1036
+ }
1037
+ async updateMessages(args) {
1038
+ const { messages } = args;
1039
+ this.logger.debug("Updating messages", { count: messages.length });
1040
+ if (!messages.length) {
1041
+ return [];
1042
+ }
1043
+ const messageIds = messages.map((m) => m.id);
1044
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
1045
+ const threadsTableName = this.operations.getTableName(TABLE_THREADS);
1046
+ try {
1047
+ const placeholders = messageIds.map(() => "?").join(",");
1048
+ const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${placeholders})`;
1049
+ const existingMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
1050
+ if (existingMessages.length === 0) {
1051
+ return [];
1052
+ }
1053
+ const parsedExistingMessages = existingMessages.map((msg) => {
1054
+ if (typeof msg.content === "string") {
1055
+ try {
1056
+ msg.content = JSON.parse(msg.content);
1057
+ } catch {
1058
+ }
1059
+ }
1060
+ return msg;
1061
+ });
1062
+ const threadIdsToUpdate = /* @__PURE__ */ new Set();
1063
+ const updateQueries = [];
1064
+ for (const existingMessage of parsedExistingMessages) {
1065
+ const updatePayload = messages.find((m) => m.id === existingMessage.id);
1066
+ if (!updatePayload) continue;
1067
+ const { id, ...fieldsToUpdate } = updatePayload;
1068
+ if (Object.keys(fieldsToUpdate).length === 0) continue;
1069
+ threadIdsToUpdate.add(existingMessage.threadId);
1070
+ if ("threadId" in updatePayload && updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
1071
+ threadIdsToUpdate.add(updatePayload.threadId);
1072
+ }
1073
+ const setClauses = [];
1074
+ const values = [];
1075
+ const updatableFields = { ...fieldsToUpdate };
1076
+ if (updatableFields.content) {
1077
+ const existingContent = existingMessage.content || {};
1078
+ const newContent = {
1079
+ ...existingContent,
1080
+ ...updatableFields.content,
1081
+ // Deep merge metadata if it exists on both
1082
+ ...existingContent?.metadata && updatableFields.content.metadata ? {
1083
+ metadata: {
1084
+ ...existingContent.metadata,
1085
+ ...updatableFields.content.metadata
1086
+ }
1087
+ } : {}
1088
+ };
1089
+ setClauses.push(`content = ?`);
1090
+ values.push(JSON.stringify(newContent));
1091
+ delete updatableFields.content;
1092
+ }
1093
+ for (const key in updatableFields) {
1094
+ if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
1095
+ const dbColumn = key === "threadId" ? "thread_id" : key;
1096
+ setClauses.push(`${dbColumn} = ?`);
1097
+ values.push(updatableFields[key]);
1098
+ }
1099
+ }
1100
+ if (setClauses.length > 0) {
1101
+ values.push(id);
1102
+ const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?`;
1103
+ updateQueries.push({ sql: updateQuery, params: values });
1104
+ }
1105
+ }
1106
+ for (const query of updateQueries) {
1107
+ await this.operations.executeQuery(query);
1108
+ }
1109
+ if (threadIdsToUpdate.size > 0) {
1110
+ const threadPlaceholders = Array.from(threadIdsToUpdate).map(() => "?").join(",");
1111
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadPlaceholders})`;
1112
+ const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...Array.from(threadIdsToUpdate)];
1113
+ await this.operations.executeQuery({ sql: threadUpdateQuery, params: threadUpdateParams });
1114
+ }
1115
+ const updatedMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
1116
+ return updatedMessages.map((message) => {
1117
+ if (typeof message.content === "string") {
1118
+ try {
1119
+ message.content = JSON.parse(message.content);
1120
+ } catch {
1121
+ }
1122
+ }
1123
+ return message;
1124
+ });
1125
+ } catch (error) {
1126
+ throw new MastraError(
1127
+ {
1128
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_MESSAGES_FAILED",
1129
+ domain: ErrorDomain.STORAGE,
1130
+ category: ErrorCategory.THIRD_PARTY,
1131
+ details: { count: messages.length }
1132
+ },
1133
+ error
1134
+ );
1135
+ }
1136
+ }
1137
+ };
1138
+ var StoreOperationsD1 = class extends StoreOperations {
1139
+ client;
1140
+ binding;
1141
+ tablePrefix;
1142
+ constructor(config) {
1143
+ super();
1144
+ this.client = config.client;
1145
+ this.binding = config.binding;
1146
+ this.tablePrefix = config.tablePrefix || "";
1147
+ }
1148
+ async hasColumn(table, column) {
1149
+ const fullTableName = table.startsWith(this.tablePrefix) ? table : `${this.tablePrefix}${table}`;
1150
+ const sql = `PRAGMA table_info(${fullTableName});`;
1151
+ const result = await this.executeQuery({ sql, params: [] });
1152
+ if (!result || !Array.isArray(result)) return false;
1153
+ return result.some((col) => col.name === column || col.name === column.toLowerCase());
1154
+ }
1155
+ getTableName(tableName) {
1156
+ return `${this.tablePrefix}${tableName}`;
1157
+ }
1158
+ formatSqlParams(params) {
1159
+ return params.map((p) => p === void 0 || p === null ? null : p);
1160
+ }
1161
+ async executeWorkersBindingQuery({
1162
+ sql,
1163
+ params = [],
1164
+ first = false
1165
+ }) {
1166
+ if (!this.binding) {
1167
+ throw new Error("Workers binding is not configured");
1168
+ }
1169
+ try {
1170
+ const statement = this.binding.prepare(sql);
1171
+ const formattedParams = this.formatSqlParams(params);
1172
+ let result;
1173
+ if (formattedParams.length > 0) {
1174
+ if (first) {
1175
+ result = await statement.bind(...formattedParams).first();
1176
+ if (!result) return null;
1177
+ return result;
1178
+ } else {
1179
+ result = await statement.bind(...formattedParams).all();
1180
+ const results = result.results || [];
1181
+ return results;
1182
+ }
1183
+ } else {
1184
+ if (first) {
1185
+ result = await statement.first();
1186
+ if (!result) return null;
1187
+ return result;
1188
+ } else {
1189
+ result = await statement.all();
1190
+ const results = result.results || [];
1191
+ return results;
1192
+ }
1193
+ }
1194
+ } catch (error) {
1195
+ throw new MastraError(
1196
+ {
1197
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_WORKERS_BINDING_QUERY_FAILED",
1198
+ domain: ErrorDomain.STORAGE,
1199
+ category: ErrorCategory.THIRD_PARTY,
1200
+ details: { sql }
1201
+ },
1202
+ error
1203
+ );
1204
+ }
1205
+ }
1206
+ async executeRestQuery({
1207
+ sql,
1208
+ params = [],
1209
+ first = false
1210
+ }) {
1211
+ if (!this.client) {
1212
+ throw new Error("D1 client is not configured");
1213
+ }
1214
+ try {
1215
+ const formattedParams = this.formatSqlParams(params);
1216
+ const response = await this.client.query({
1217
+ sql,
1218
+ params: formattedParams
1219
+ });
1220
+ if (!response.result) {
1221
+ return first ? null : [];
1222
+ }
1223
+ if (first) {
1224
+ return response.result[0] || null;
1225
+ }
1226
+ return response.result;
1227
+ } catch (error) {
1228
+ throw new MastraError(
1229
+ {
1230
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_REST_QUERY_FAILED",
1231
+ domain: ErrorDomain.STORAGE,
1232
+ category: ErrorCategory.THIRD_PARTY,
1233
+ details: { sql }
1234
+ },
1235
+ error
1236
+ );
1237
+ }
1238
+ }
1239
+ async executeQuery(options) {
1240
+ if (this.binding) {
1241
+ return this.executeWorkersBindingQuery(options);
1242
+ } else if (this.client) {
1243
+ return this.executeRestQuery(options);
1244
+ } else {
1245
+ throw new Error("Neither binding nor client is configured");
1246
+ }
1247
+ }
1248
+ async getTableColumns(tableName) {
1249
+ try {
1250
+ const sql = `PRAGMA table_info(${tableName})`;
1251
+ const result = await this.executeQuery({ sql });
1252
+ if (!result || !Array.isArray(result)) {
1253
+ return [];
1254
+ }
1255
+ return result.map((row) => ({
1256
+ name: row.name,
1257
+ type: row.type
1258
+ }));
1259
+ } catch (error) {
1260
+ this.logger.warn(`Failed to get table columns for ${tableName}:`, error);
1261
+ return [];
1262
+ }
1263
+ }
1264
+ serializeValue(value) {
1265
+ if (value === null || value === void 0) {
1266
+ return null;
1267
+ }
1268
+ if (value instanceof Date) {
1269
+ return value.toISOString();
1270
+ }
1271
+ if (typeof value === "object") {
1272
+ return JSON.stringify(value);
1273
+ }
1274
+ return value;
1275
+ }
1276
+ getSqlType(type) {
1277
+ switch (type) {
1278
+ case "bigint":
1279
+ return "INTEGER";
1280
+ // SQLite uses INTEGER for all integer sizes
1281
+ case "jsonb":
1282
+ return "TEXT";
1283
+ // Store JSON as TEXT in SQLite
1284
+ default:
1285
+ return super.getSqlType(type);
1286
+ }
1287
+ }
1288
+ async createTable({
1289
+ tableName,
1290
+ schema
1291
+ }) {
1292
+ try {
1293
+ const fullTableName = this.getTableName(tableName);
1294
+ const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
1295
+ const type = this.getSqlType(colDef.type);
1296
+ const nullable = colDef.nullable === false ? "NOT NULL" : "";
1297
+ const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
1298
+ return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
1299
+ });
1300
+ const tableConstraints = [];
1301
+ if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
1302
+ tableConstraints.push("UNIQUE (workflow_name, run_id)");
1303
+ }
1304
+ const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
1305
+ const { sql, params } = query.build();
1306
+ await this.executeQuery({ sql, params });
1307
+ this.logger.debug(`Created table ${fullTableName}`);
1308
+ } catch (error) {
1309
+ throw new MastraError(
1310
+ {
1311
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_CREATE_TABLE_FAILED",
1312
+ domain: ErrorDomain.STORAGE,
1313
+ category: ErrorCategory.THIRD_PARTY,
1314
+ details: { tableName }
1315
+ },
1316
+ error
1317
+ );
1318
+ }
1319
+ }
1320
+ async clearTable({ tableName }) {
1321
+ try {
1322
+ const fullTableName = this.getTableName(tableName);
1323
+ const query = createSqlBuilder().delete(fullTableName);
1324
+ const { sql, params } = query.build();
1325
+ await this.executeQuery({ sql, params });
1326
+ this.logger.debug(`Cleared table ${fullTableName}`);
1327
+ } catch (error) {
1328
+ throw new MastraError(
1329
+ {
1330
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_CLEAR_TABLE_FAILED",
1331
+ domain: ErrorDomain.STORAGE,
1332
+ category: ErrorCategory.THIRD_PARTY,
1333
+ details: { tableName }
1334
+ },
1335
+ error
1336
+ );
1337
+ }
1338
+ }
1339
+ async dropTable({ tableName }) {
1340
+ try {
1341
+ const fullTableName = this.getTableName(tableName);
1342
+ const sql = `DROP TABLE IF EXISTS ${fullTableName}`;
1343
+ await this.executeQuery({ sql });
1344
+ this.logger.debug(`Dropped table ${fullTableName}`);
1345
+ } catch (error) {
1346
+ throw new MastraError(
1347
+ {
1348
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_DROP_TABLE_FAILED",
1349
+ domain: ErrorDomain.STORAGE,
1350
+ category: ErrorCategory.THIRD_PARTY,
1351
+ details: { tableName }
1352
+ },
1353
+ error
1354
+ );
1355
+ }
1356
+ }
1357
+ async alterTable(args) {
1358
+ try {
1359
+ const fullTableName = this.getTableName(args.tableName);
1360
+ const existingColumns = await this.getTableColumns(fullTableName);
1361
+ const existingColumnNames = new Set(existingColumns.map((col) => col.name));
1362
+ for (const [columnName, column] of Object.entries(args.schema)) {
1363
+ if (!existingColumnNames.has(columnName) && args.ifNotExists.includes(columnName)) {
1364
+ const sqlType = this.getSqlType(column.type);
1365
+ const defaultValue = this.getDefaultValue(column.type);
1366
+ const sql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${defaultValue}`;
1367
+ await this.executeQuery({ sql });
1368
+ this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
1369
+ }
1370
+ }
1371
+ } catch (error) {
1372
+ throw new MastraError(
1373
+ {
1374
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_ALTER_TABLE_FAILED",
1375
+ domain: ErrorDomain.STORAGE,
1376
+ category: ErrorCategory.THIRD_PARTY,
1377
+ details: { tableName: args.tableName }
1378
+ },
1379
+ error
1380
+ );
1381
+ }
1382
+ }
1383
+ async insert({ tableName, record }) {
1384
+ try {
1385
+ const fullTableName = this.getTableName(tableName);
1386
+ const processedRecord = await this.processRecord(record);
1387
+ const columns = Object.keys(processedRecord);
1388
+ const values = Object.values(processedRecord);
1389
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1390
+ const { sql, params } = query.build();
1391
+ await this.executeQuery({ sql, params });
1392
+ } catch (error) {
1393
+ throw new MastraError(
1394
+ {
1395
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_INSERT_FAILED",
1396
+ domain: ErrorDomain.STORAGE,
1397
+ category: ErrorCategory.THIRD_PARTY,
1398
+ details: { tableName }
1399
+ },
1400
+ error
1401
+ );
1402
+ }
1403
+ }
1404
+ async batchInsert({ tableName, records }) {
1405
+ try {
1406
+ if (records.length === 0) return;
1407
+ const fullTableName = this.getTableName(tableName);
1408
+ const processedRecords = await Promise.all(records.map((record) => this.processRecord(record)));
1409
+ const columns = Object.keys(processedRecords[0] || {});
1410
+ for (const record of processedRecords) {
1411
+ const values = Object.values(record);
1412
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1413
+ const { sql, params } = query.build();
1414
+ await this.executeQuery({ sql, params });
1415
+ }
1416
+ } catch (error) {
1417
+ throw new MastraError(
1418
+ {
1419
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_BATCH_INSERT_FAILED",
1420
+ domain: ErrorDomain.STORAGE,
1421
+ category: ErrorCategory.THIRD_PARTY,
1422
+ details: { tableName }
1423
+ },
1424
+ error
1425
+ );
1426
+ }
1427
+ }
1428
+ async load({ tableName, keys }) {
1429
+ try {
1430
+ const fullTableName = this.getTableName(tableName);
1431
+ const query = createSqlBuilder().select("*").from(fullTableName);
1432
+ let firstKey = true;
1433
+ for (const [key, value] of Object.entries(keys)) {
1434
+ if (firstKey) {
1435
+ query.where(`${key} = ?`, value);
1436
+ firstKey = false;
1437
+ } else {
1438
+ query.andWhere(`${key} = ?`, value);
1439
+ }
1440
+ }
1441
+ query.limit(1);
1442
+ const { sql, params } = query.build();
1443
+ const result = await this.executeQuery({ sql, params, first: true });
1444
+ if (!result) {
1445
+ return null;
1446
+ }
1447
+ const deserializedResult = {};
1448
+ for (const [key, value] of Object.entries(result)) {
1449
+ deserializedResult[key] = deserializeValue(value);
1450
+ }
1451
+ return deserializedResult;
1452
+ } catch (error) {
1453
+ throw new MastraError(
1454
+ {
1455
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_LOAD_FAILED",
1456
+ domain: ErrorDomain.STORAGE,
1457
+ category: ErrorCategory.THIRD_PARTY,
1458
+ details: { tableName }
1459
+ },
1460
+ error
1461
+ );
1462
+ }
1463
+ }
1464
+ async processRecord(record) {
1465
+ const processed = {};
1466
+ for (const [key, value] of Object.entries(record)) {
1467
+ processed[key] = this.serializeValue(value);
1468
+ }
1469
+ return processed;
1470
+ }
1471
+ /**
1472
+ * Upsert multiple records in a batch operation
1473
+ * @param tableName The table to insert into
1474
+ * @param records The records to insert
1475
+ */
1476
+ async batchUpsert({ tableName, records }) {
1477
+ if (records.length === 0) return;
1478
+ const fullTableName = this.getTableName(tableName);
1479
+ try {
1480
+ const batchSize = 50;
1481
+ for (let i = 0; i < records.length; i += batchSize) {
1482
+ const batch = records.slice(i, i + batchSize);
1483
+ const recordsToInsert = batch;
1484
+ if (recordsToInsert.length > 0) {
1485
+ const firstRecord = recordsToInsert[0];
1486
+ const columns = Object.keys(firstRecord || {});
1487
+ for (const record of recordsToInsert) {
1488
+ const values = columns.map((col) => {
1489
+ if (!record) return null;
1490
+ const value = typeof col === "string" ? record[col] : null;
1491
+ return this.serializeValue(value);
1492
+ });
1493
+ const recordToUpsert = columns.reduce(
1494
+ (acc, col) => {
1495
+ if (col !== "createdAt") acc[col] = `excluded.${col}`;
1496
+ return acc;
1497
+ },
1498
+ {}
1499
+ );
1500
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert);
1501
+ const { sql, params } = query.build();
1502
+ await this.executeQuery({ sql, params });
1503
+ }
1504
+ }
1505
+ this.logger.debug(
1506
+ `Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
1507
+ );
1508
+ }
1509
+ this.logger.debug(`Successfully batch upserted ${records.length} records into ${tableName}`);
1510
+ } catch (error) {
1511
+ throw new MastraError(
1512
+ {
1513
+ id: "CLOUDFLARE_D1_STORAGE_BATCH_UPSERT_ERROR",
1514
+ domain: ErrorDomain.STORAGE,
1515
+ category: ErrorCategory.THIRD_PARTY,
1516
+ text: `Failed to batch upsert into ${tableName}: ${error instanceof Error ? error.message : String(error)}`,
1517
+ details: { tableName }
1518
+ },
1519
+ error
1520
+ );
1521
+ }
1522
+ }
1523
+ };
1524
+ function transformScoreRow(row) {
1525
+ let input = void 0;
1526
+ if (row.input) {
1527
+ try {
1528
+ input = JSON.parse(row.input);
1529
+ } catch {
1530
+ input = row.input;
1531
+ }
1532
+ }
1533
+ return {
1534
+ ...row,
1535
+ input,
1536
+ createdAt: row.createdAtZ || row.createdAt,
1537
+ updatedAt: row.updatedAtZ || row.updatedAt
1538
+ };
1539
+ }
1540
+ var ScoresStorageD1 = class extends ScoresStorage {
1541
+ operations;
1542
+ constructor({ operations }) {
1543
+ super();
1544
+ this.operations = operations;
1545
+ }
1546
+ async getScoreById({ id }) {
1547
+ try {
1548
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1549
+ const query = createSqlBuilder().select("*").from(fullTableName).where("id = ?", id);
1550
+ const { sql, params } = query.build();
1551
+ const result = await this.operations.executeQuery({ sql, params, first: true });
1552
+ if (!result) {
1553
+ return null;
1554
+ }
1555
+ return transformScoreRow(result);
1556
+ } catch (error) {
1557
+ throw new MastraError(
1558
+ {
1559
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORE_BY_ID_FAILED",
1560
+ domain: ErrorDomain.STORAGE,
1561
+ category: ErrorCategory.THIRD_PARTY
1562
+ },
1563
+ error
1564
+ );
1565
+ }
1566
+ }
1567
+ async saveScore(score) {
1568
+ try {
1569
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1570
+ const { input, ...rest } = score;
1571
+ const serializedRecord = {};
1572
+ for (const [key, value] of Object.entries(rest)) {
1573
+ if (value !== null && value !== void 0) {
1574
+ if (typeof value === "object") {
1575
+ serializedRecord[key] = JSON.stringify(value);
1576
+ } else {
1577
+ serializedRecord[key] = value;
1578
+ }
1579
+ } else {
1580
+ serializedRecord[key] = null;
1581
+ }
1582
+ }
1583
+ serializedRecord.input = JSON.stringify(input);
1584
+ serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1585
+ serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1586
+ const columns = Object.keys(serializedRecord);
1587
+ const values = Object.values(serializedRecord);
1588
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1589
+ const { sql, params } = query.build();
1590
+ await this.operations.executeQuery({ sql, params });
1591
+ const scoreFromDb = await this.getScoreById({ id: score.id });
1592
+ return { score: scoreFromDb };
1593
+ } catch (error) {
1594
+ throw new MastraError(
1595
+ {
1596
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED",
1597
+ domain: ErrorDomain.STORAGE,
1598
+ category: ErrorCategory.THIRD_PARTY
1599
+ },
1600
+ error
1601
+ );
1602
+ }
1603
+ }
1604
+ async getScoresByScorerId({
1605
+ scorerId,
1606
+ pagination
1607
+ }) {
1608
+ try {
1609
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1610
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1611
+ const countResult = await this.operations.executeQuery(countQuery.build());
1612
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1613
+ if (total === 0) {
1614
+ return {
1615
+ pagination: {
1616
+ total: 0,
1617
+ page: pagination.page,
1618
+ perPage: pagination.perPage,
1619
+ hasMore: false
1620
+ },
1621
+ scores: []
1622
+ };
1623
+ }
1624
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1625
+ const { sql, params } = selectQuery.build();
1626
+ const results = await this.operations.executeQuery({ sql, params });
1627
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1628
+ return {
1629
+ pagination: {
1630
+ total,
1631
+ page: pagination.page,
1632
+ perPage: pagination.perPage,
1633
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1634
+ },
1635
+ scores
1636
+ };
1637
+ } catch (error) {
1638
+ throw new MastraError(
1639
+ {
1640
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
1641
+ domain: ErrorDomain.STORAGE,
1642
+ category: ErrorCategory.THIRD_PARTY
1643
+ },
1644
+ error
1645
+ );
1646
+ }
1647
+ }
1648
+ async getScoresByRunId({
1649
+ runId,
1650
+ pagination
1651
+ }) {
1652
+ try {
1653
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1654
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
1655
+ const countResult = await this.operations.executeQuery(countQuery.build());
1656
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1657
+ if (total === 0) {
1658
+ return {
1659
+ pagination: {
1660
+ total: 0,
1661
+ page: pagination.page,
1662
+ perPage: pagination.perPage,
1663
+ hasMore: false
1664
+ },
1665
+ scores: []
1666
+ };
1667
+ }
1668
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1669
+ const { sql, params } = selectQuery.build();
1670
+ const results = await this.operations.executeQuery({ sql, params });
1671
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1672
+ return {
1673
+ pagination: {
1674
+ total,
1675
+ page: pagination.page,
1676
+ perPage: pagination.perPage,
1677
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1678
+ },
1679
+ scores
1680
+ };
1681
+ } catch (error) {
1682
+ throw new MastraError(
1683
+ {
1684
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
1685
+ domain: ErrorDomain.STORAGE,
1686
+ category: ErrorCategory.THIRD_PARTY
1687
+ },
1688
+ error
1689
+ );
1690
+ }
1691
+ }
1692
+ async getScoresByEntityId({
1693
+ entityId,
1694
+ entityType,
1695
+ pagination
1696
+ }) {
1697
+ try {
1698
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1699
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
1700
+ const countResult = await this.operations.executeQuery(countQuery.build());
1701
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1702
+ if (total === 0) {
1703
+ return {
1704
+ pagination: {
1705
+ total: 0,
1706
+ page: pagination.page,
1707
+ perPage: pagination.perPage,
1708
+ hasMore: false
1709
+ },
1710
+ scores: []
1711
+ };
1712
+ }
1713
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1714
+ const { sql, params } = selectQuery.build();
1715
+ const results = await this.operations.executeQuery({ sql, params });
1716
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1717
+ return {
1718
+ pagination: {
1719
+ total,
1720
+ page: pagination.page,
1721
+ perPage: pagination.perPage,
1722
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1723
+ },
1724
+ scores
1725
+ };
1726
+ } catch (error) {
1727
+ throw new MastraError(
1728
+ {
1729
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
1730
+ domain: ErrorDomain.STORAGE,
1731
+ category: ErrorCategory.THIRD_PARTY
1732
+ },
1733
+ error
1734
+ );
1735
+ }
1736
+ }
1737
+ };
1738
+ function isArrayOfRecords2(value) {
1739
+ return value && Array.isArray(value) && value.length > 0;
1740
+ }
1741
+ var TracesStorageD1 = class extends TracesStorage {
1742
+ operations;
1743
+ constructor({ operations }) {
1744
+ super();
1745
+ this.operations = operations;
1746
+ }
1747
+ async getTraces(args) {
1748
+ const paginatedArgs = {
1749
+ name: args.name,
1750
+ scope: args.scope,
1751
+ page: args.page,
1752
+ perPage: args.perPage,
1753
+ attributes: args.attributes,
1754
+ filters: args.filters,
1755
+ dateRange: args.fromDate || args.toDate ? {
1756
+ start: args.fromDate,
1757
+ end: args.toDate
1758
+ } : void 0
1759
+ };
1760
+ try {
1761
+ const result = await this.getTracesPaginated(paginatedArgs);
1762
+ return result.traces;
1763
+ } catch (error) {
1764
+ throw new MastraError(
1765
+ {
1766
+ id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1767
+ domain: ErrorDomain.STORAGE,
1768
+ category: ErrorCategory.THIRD_PARTY,
1769
+ text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1770
+ details: {
1771
+ name: args.name ?? "",
1772
+ scope: args.scope ?? ""
1773
+ }
1774
+ },
1775
+ error
1776
+ );
1777
+ }
1778
+ }
1779
+ async getTracesPaginated(args) {
1780
+ const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
1781
+ const fromDate = dateRange?.start;
1782
+ const toDate = dateRange?.end;
1783
+ const fullTableName = this.operations.getTableName(TABLE_TRACES);
1784
+ try {
1785
+ const dataQuery = createSqlBuilder().select("*").from(fullTableName).where("1=1");
1786
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("1=1");
1787
+ if (name) {
1788
+ dataQuery.andWhere("name LIKE ?", `%${name}%`);
1789
+ countQuery.andWhere("name LIKE ?", `%${name}%`);
1790
+ }
1791
+ if (scope) {
1792
+ dataQuery.andWhere("scope = ?", scope);
1793
+ countQuery.andWhere("scope = ?", scope);
1794
+ }
1795
+ if (attributes && Object.keys(attributes).length > 0) {
1796
+ for (const [key, value] of Object.entries(attributes)) {
1797
+ dataQuery.jsonLike("attributes", key, value);
1798
+ countQuery.jsonLike("attributes", key, value);
756
1799
  }
757
- return processedMsg;
758
- });
759
- this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
760
- return processedMessages;
1800
+ }
1801
+ if (fromDate) {
1802
+ const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
1803
+ dataQuery.andWhere("createdAt >= ?", fromDateStr);
1804
+ countQuery.andWhere("createdAt >= ?", fromDateStr);
1805
+ }
1806
+ if (toDate) {
1807
+ const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
1808
+ dataQuery.andWhere("createdAt <= ?", toDateStr);
1809
+ countQuery.andWhere("createdAt <= ?", toDateStr);
1810
+ }
1811
+ const allDataResult = await this.operations.executeQuery(
1812
+ createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1813
+ );
1814
+ console.log("allDataResult", allDataResult);
1815
+ const countResult = await this.operations.executeQuery(countQuery.build());
1816
+ const total = Number(countResult?.[0]?.count ?? 0);
1817
+ dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
1818
+ const results = await this.operations.executeQuery(dataQuery.build());
1819
+ const traces = isArrayOfRecords2(results) ? results.map(
1820
+ (trace) => ({
1821
+ ...trace,
1822
+ attributes: deserializeValue(trace.attributes, "jsonb"),
1823
+ status: deserializeValue(trace.status, "jsonb"),
1824
+ events: deserializeValue(trace.events, "jsonb"),
1825
+ links: deserializeValue(trace.links, "jsonb"),
1826
+ other: deserializeValue(trace.other, "jsonb")
1827
+ })
1828
+ ) : [];
1829
+ return {
1830
+ traces,
1831
+ total,
1832
+ page,
1833
+ perPage,
1834
+ hasMore: page * perPage + traces.length < total
1835
+ };
761
1836
  } catch (error) {
762
- this.logger.error("Error retrieving messages for thread", {
763
- threadId,
764
- message: error instanceof Error ? error.message : String(error)
765
- });
766
- return [];
1837
+ const mastraError = new MastraError(
1838
+ {
1839
+ id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_PAGINATED_ERROR",
1840
+ domain: ErrorDomain.STORAGE,
1841
+ category: ErrorCategory.THIRD_PARTY,
1842
+ text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1843
+ details: { name: name ?? "", scope: scope ?? "" }
1844
+ },
1845
+ error
1846
+ );
1847
+ this.logger?.error(mastraError.toString());
1848
+ this.logger?.trackException(mastraError);
1849
+ return { traces: [], total: 0, page, perPage, hasMore: false };
767
1850
  }
768
1851
  }
1852
+ async batchTraceInsert({ records }) {
1853
+ this.logger.debug("Batch inserting traces", { count: records.length });
1854
+ await this.operations.batchInsert({
1855
+ tableName: TABLE_TRACES,
1856
+ records
1857
+ });
1858
+ }
1859
+ };
1860
+ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1861
+ operations;
1862
+ constructor({ operations }) {
1863
+ super();
1864
+ this.operations = operations;
1865
+ }
769
1866
  async persistWorkflowSnapshot({
770
1867
  workflowName,
771
1868
  runId,
772
1869
  snapshot
773
1870
  }) {
774
- const fullTableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1871
+ const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
775
1872
  const now = (/* @__PURE__ */ new Date()).toISOString();
776
- const currentSnapshot = await this.load({
1873
+ const currentSnapshot = await this.operations.load({
777
1874
  tableName: TABLE_WORKFLOW_SNAPSHOT,
778
1875
  keys: { workflow_name: workflowName, run_id: runId }
779
1876
  });
@@ -788,7 +1885,7 @@ var D1Store = class extends MastraStorage {
788
1885
  createdAt: now,
789
1886
  updatedAt: now
790
1887
  };
791
- const processedRecord = await this.processRecord(persisting);
1888
+ const processedRecord = await this.operations.processRecord(persisting);
792
1889
  const columns = Object.keys(processedRecord);
793
1890
  const values = Object.values(processedRecord);
794
1891
  const updateMap = {
@@ -799,143 +1896,43 @@ var D1Store = class extends MastraStorage {
799
1896
  const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap);
800
1897
  const { sql, params } = query.build();
801
1898
  try {
802
- await this.executeQuery({ sql, params });
1899
+ await this.operations.executeQuery({ sql, params });
803
1900
  } catch (error) {
804
- this.logger.error("Error persisting workflow snapshot:", {
805
- message: error instanceof Error ? error.message : String(error)
806
- });
807
- throw error;
1901
+ throw new MastraError(
1902
+ {
1903
+ id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
1904
+ domain: ErrorDomain.STORAGE,
1905
+ category: ErrorCategory.THIRD_PARTY,
1906
+ text: `Failed to persist workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
1907
+ details: { workflowName, runId }
1908
+ },
1909
+ error
1910
+ );
808
1911
  }
809
1912
  }
810
1913
  async loadWorkflowSnapshot(params) {
811
1914
  const { workflowName, runId } = params;
812
1915
  this.logger.debug("Loading workflow snapshot", { workflowName, runId });
813
- const d = await this.load({
814
- tableName: TABLE_WORKFLOW_SNAPSHOT,
815
- keys: {
816
- workflow_name: workflowName,
817
- run_id: runId
818
- }
819
- });
820
- return d ? d.snapshot : null;
821
- }
822
- /**
823
- * Insert multiple records in a batch operation
824
- * @param tableName The table to insert into
825
- * @param records The records to insert
826
- */
827
- async batchInsert({ tableName, records }) {
828
- if (records.length === 0) return;
829
- const fullTableName = this.getTableName(tableName);
830
1916
  try {
831
- const batchSize = 50;
832
- for (let i = 0; i < records.length; i += batchSize) {
833
- const batch = records.slice(i, i + batchSize);
834
- const recordsToInsert = batch;
835
- if (recordsToInsert.length > 0) {
836
- const firstRecord = recordsToInsert[0];
837
- const columns = Object.keys(firstRecord || {});
838
- for (const record of recordsToInsert) {
839
- const values = columns.map((col) => {
840
- if (!record) return null;
841
- const value = typeof col === "string" ? record[col] : null;
842
- return this.serializeValue(value);
843
- });
844
- const query = createSqlBuilder().insert(fullTableName, columns, values);
845
- const { sql, params } = query.build();
846
- await this.executeQuery({ sql, params });
847
- }
1917
+ const d = await this.operations.load({
1918
+ tableName: TABLE_WORKFLOW_SNAPSHOT,
1919
+ keys: {
1920
+ workflow_name: workflowName,
1921
+ run_id: runId
848
1922
  }
849
- this.logger.debug(
850
- `Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
851
- );
852
- }
853
- this.logger.debug(`Successfully batch inserted ${records.length} records into ${tableName}`);
854
- } catch (error) {
855
- this.logger.error(`Error batch inserting into ${tableName}:`, {
856
- message: error instanceof Error ? error.message : String(error)
857
1923
  });
858
- throw new Error(`Failed to batch insert into ${tableName}: ${error}`);
859
- }
860
- }
861
- async getTraces({
862
- name,
863
- scope,
864
- page,
865
- perPage,
866
- attributes,
867
- fromDate,
868
- toDate
869
- }) {
870
- const fullTableName = this.getTableName(TABLE_TRACES);
871
- try {
872
- const query = createSqlBuilder().select("*").from(fullTableName).where("1=1");
873
- if (name) {
874
- query.andWhere("name LIKE ?", `%${name}%`);
875
- }
876
- if (scope) {
877
- query.andWhere("scope = ?", scope);
878
- }
879
- if (attributes && Object.keys(attributes).length > 0) {
880
- for (const [key, value] of Object.entries(attributes)) {
881
- query.jsonLike("attributes", key, value);
882
- }
883
- }
884
- if (fromDate) {
885
- query.andWhere("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
886
- }
887
- if (toDate) {
888
- query.andWhere("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
889
- }
890
- query.orderBy("startTime", "DESC").limit(perPage).offset((page - 1) * perPage);
891
- const { sql, params } = query.build();
892
- const results = await this.executeQuery({ sql, params });
893
- return isArrayOfRecords(results) ? results.map((trace) => ({
894
- ...trace,
895
- attributes: this.deserializeValue(trace.attributes, "jsonb"),
896
- status: this.deserializeValue(trace.status, "jsonb"),
897
- events: this.deserializeValue(trace.events, "jsonb"),
898
- links: this.deserializeValue(trace.links, "jsonb"),
899
- other: this.deserializeValue(trace.other, "jsonb")
900
- })) : [];
901
- } catch (error) {
902
- this.logger.error("Error getting traces:", { message: error instanceof Error ? error.message : String(error) });
903
- return [];
904
- }
905
- }
906
- async getEvalsByAgentName(agentName, type) {
907
- const fullTableName = this.getTableName(TABLE_EVALS);
908
- try {
909
- let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
910
- if (type === "test") {
911
- query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
912
- } else if (type === "live") {
913
- query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
914
- }
915
- query.orderBy("created_at", "DESC");
916
- const { sql, params } = query.build();
917
- const results = await this.executeQuery({ sql, params });
918
- return isArrayOfRecords(results) ? results.map((row) => {
919
- const result = this.deserializeValue(row.result);
920
- const testInfo = row.test_info ? this.deserializeValue(row.test_info) : void 0;
921
- return {
922
- input: row.input || "",
923
- output: row.output || "",
924
- result,
925
- agentName: row.agent_name || "",
926
- metricName: row.metric_name || "",
927
- instructions: row.instructions || "",
928
- runId: row.run_id || "",
929
- globalRunId: row.global_run_id || "",
930
- createdAt: row.created_at || "",
931
- testInfo
932
- };
933
- }) : [];
1924
+ return d ? d.snapshot : null;
934
1925
  } catch (error) {
935
- this.logger.error(`Error getting evals for agent ${agentName}:`, {
936
- message: error instanceof Error ? error.message : String(error)
937
- });
938
- return [];
1926
+ throw new MastraError(
1927
+ {
1928
+ id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
1929
+ domain: ErrorDomain.STORAGE,
1930
+ category: ErrorCategory.THIRD_PARTY,
1931
+ text: `Failed to load workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
1932
+ details: { workflowName, runId }
1933
+ },
1934
+ error
1935
+ );
939
1936
  }
940
1937
  }
941
1938
  parseWorkflowRun(row) {
@@ -951,17 +1948,11 @@ var D1Store = class extends MastraStorage {
951
1948
  workflowName: row.workflow_name,
952
1949
  runId: row.run_id,
953
1950
  snapshot: parsedSnapshot,
954
- createdAt: this.ensureDate(row.createdAt),
955
- updatedAt: this.ensureDate(row.updatedAt),
1951
+ createdAt: ensureDate(row.createdAt),
1952
+ updatedAt: ensureDate(row.updatedAt),
956
1953
  resourceId: row.resourceId
957
1954
  };
958
1955
  }
959
- async hasColumn(table, column) {
960
- const sql = `PRAGMA table_info(${table});`;
961
- const result = await this.executeQuery({ sql, params: [] });
962
- if (!result || !Array.isArray(result)) return false;
963
- return result.some((col) => col.name === column || col.name === column.toLowerCase());
964
- }
965
1956
  async getWorkflowRuns({
966
1957
  workflowName,
967
1958
  fromDate,
@@ -970,13 +1961,13 @@ var D1Store = class extends MastraStorage {
970
1961
  offset,
971
1962
  resourceId
972
1963
  } = {}) {
973
- const fullTableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1964
+ const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
974
1965
  try {
975
1966
  const builder = createSqlBuilder().select().from(fullTableName);
976
1967
  const countBuilder = createSqlBuilder().count().from(fullTableName);
977
1968
  if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
978
1969
  if (resourceId) {
979
- const hasResourceId = await this.hasColumn(fullTableName, "resourceId");
1970
+ const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
980
1971
  if (hasResourceId) {
981
1972
  builder.whereAnd("resourceId = ?", resourceId);
982
1973
  countBuilder.whereAnd("resourceId = ?", resourceId);
@@ -999,24 +1990,37 @@ var D1Store = class extends MastraStorage {
999
1990
  let total = 0;
1000
1991
  if (limit !== void 0 && offset !== void 0) {
1001
1992
  const { sql: countSql, params: countParams } = countBuilder.build();
1002
- const countResult = await this.executeQuery({ sql: countSql, params: countParams, first: true });
1993
+ const countResult = await this.operations.executeQuery({
1994
+ sql: countSql,
1995
+ params: countParams,
1996
+ first: true
1997
+ });
1003
1998
  total = Number(countResult?.count ?? 0);
1004
1999
  }
1005
- const results = await this.executeQuery({ sql, params });
2000
+ const results = await this.operations.executeQuery({ sql, params });
1006
2001
  const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
1007
2002
  return { runs, total: total || runs.length };
1008
2003
  } catch (error) {
1009
- this.logger.error("Error getting workflow runs:", {
1010
- message: error instanceof Error ? error.message : String(error)
1011
- });
1012
- throw error;
2004
+ throw new MastraError(
2005
+ {
2006
+ id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
2007
+ domain: ErrorDomain.STORAGE,
2008
+ category: ErrorCategory.THIRD_PARTY,
2009
+ text: `Failed to retrieve workflow runs: ${error instanceof Error ? error.message : String(error)}`,
2010
+ details: {
2011
+ workflowName: workflowName ?? "",
2012
+ resourceId: resourceId ?? ""
2013
+ }
2014
+ },
2015
+ error
2016
+ );
1013
2017
  }
1014
2018
  }
1015
2019
  async getWorkflowRunById({
1016
2020
  runId,
1017
2021
  workflowName
1018
2022
  }) {
1019
- const fullTableName = this.getTableName(TABLE_WORKFLOW_SNAPSHOT);
2023
+ const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1020
2024
  try {
1021
2025
  const conditions = [];
1022
2026
  const params = [];
@@ -1030,15 +2034,292 @@ var D1Store = class extends MastraStorage {
1030
2034
  }
1031
2035
  const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
1032
2036
  const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
1033
- const result = await this.executeQuery({ sql, params, first: true });
2037
+ const result = await this.operations.executeQuery({ sql, params, first: true });
1034
2038
  if (!result) return null;
1035
2039
  return this.parseWorkflowRun(result);
1036
2040
  } catch (error) {
1037
- this.logger.error("Error getting workflow run by ID:", {
1038
- message: error instanceof Error ? error.message : String(error)
1039
- });
1040
- throw error;
2041
+ throw new MastraError(
2042
+ {
2043
+ id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
2044
+ domain: ErrorDomain.STORAGE,
2045
+ category: ErrorCategory.THIRD_PARTY,
2046
+ text: `Failed to retrieve workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
2047
+ details: { runId, workflowName: workflowName ?? "" }
2048
+ },
2049
+ error
2050
+ );
2051
+ }
2052
+ }
2053
+ };
2054
+
2055
+ // src/storage/index.ts
2056
+ var D1Store = class extends MastraStorage {
2057
+ client;
2058
+ binding;
2059
+ // D1Database binding
2060
+ tablePrefix;
2061
+ stores;
2062
+ /**
2063
+ * Creates a new D1Store instance
2064
+ * @param config Configuration for D1 access (either REST API or Workers Binding API)
2065
+ */
2066
+ constructor(config) {
2067
+ try {
2068
+ super({ name: "D1" });
2069
+ if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
2070
+ throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
2071
+ }
2072
+ this.tablePrefix = config.tablePrefix || "";
2073
+ if ("binding" in config) {
2074
+ if (!config.binding) {
2075
+ throw new Error("D1 binding is required when using Workers Binding API");
2076
+ }
2077
+ this.binding = config.binding;
2078
+ this.logger.info("Using D1 Workers Binding API");
2079
+ } else if ("client" in config) {
2080
+ if (!config.client) {
2081
+ throw new Error("D1 client is required when using D1ClientConfig");
2082
+ }
2083
+ this.client = config.client;
2084
+ this.logger.info("Using D1 Client");
2085
+ } else {
2086
+ if (!config.accountId || !config.databaseId || !config.apiToken) {
2087
+ throw new Error("accountId, databaseId, and apiToken are required when using REST API");
2088
+ }
2089
+ const cfClient = new Cloudflare({
2090
+ apiToken: config.apiToken
2091
+ });
2092
+ this.client = {
2093
+ query: ({ sql, params }) => {
2094
+ return cfClient.d1.database.query(config.databaseId, {
2095
+ account_id: config.accountId,
2096
+ sql,
2097
+ params
2098
+ });
2099
+ }
2100
+ };
2101
+ this.logger.info("Using D1 REST API");
2102
+ }
2103
+ } catch (error) {
2104
+ throw new MastraError(
2105
+ {
2106
+ id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
2107
+ domain: ErrorDomain.STORAGE,
2108
+ category: ErrorCategory.SYSTEM,
2109
+ text: "Error initializing D1Store"
2110
+ },
2111
+ error
2112
+ );
1041
2113
  }
2114
+ const operations = new StoreOperationsD1({
2115
+ client: this.client,
2116
+ binding: this.binding,
2117
+ tablePrefix: this.tablePrefix
2118
+ });
2119
+ const scores = new ScoresStorageD1({
2120
+ operations
2121
+ });
2122
+ const legacyEvals = new LegacyEvalsStorageD1({
2123
+ operations
2124
+ });
2125
+ const traces = new TracesStorageD1({
2126
+ operations
2127
+ });
2128
+ const workflows = new WorkflowsStorageD1({
2129
+ operations
2130
+ });
2131
+ const memory = new MemoryStorageD1({
2132
+ operations
2133
+ });
2134
+ this.stores = {
2135
+ operations,
2136
+ scores,
2137
+ legacyEvals,
2138
+ traces,
2139
+ workflows,
2140
+ memory
2141
+ };
2142
+ }
2143
+ get supports() {
2144
+ return {
2145
+ selectByIncludeResourceScope: true,
2146
+ resourceWorkingMemory: true,
2147
+ hasColumn: true,
2148
+ createTable: true
2149
+ };
2150
+ }
2151
+ async createTable({
2152
+ tableName,
2153
+ schema
2154
+ }) {
2155
+ return this.stores.operations.createTable({ tableName, schema });
2156
+ }
2157
+ /**
2158
+ * Alters table schema to add columns if they don't exist
2159
+ * @param tableName Name of the table
2160
+ * @param schema Schema of the table
2161
+ * @param ifNotExists Array of column names to add if they don't exist
2162
+ */
2163
+ async alterTable({
2164
+ tableName,
2165
+ schema,
2166
+ ifNotExists
2167
+ }) {
2168
+ return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
2169
+ }
2170
+ async clearTable({ tableName }) {
2171
+ return this.stores.operations.clearTable({ tableName });
2172
+ }
2173
+ async dropTable({ tableName }) {
2174
+ return this.stores.operations.dropTable({ tableName });
2175
+ }
2176
+ async hasColumn(table, column) {
2177
+ return this.stores.operations.hasColumn(table, column);
2178
+ }
2179
+ async insert({ tableName, record }) {
2180
+ return this.stores.operations.insert({ tableName, record });
2181
+ }
2182
+ async load({ tableName, keys }) {
2183
+ return this.stores.operations.load({ tableName, keys });
2184
+ }
2185
+ async getThreadById({ threadId }) {
2186
+ return this.stores.memory.getThreadById({ threadId });
2187
+ }
2188
+ /**
2189
+ * @deprecated use getThreadsByResourceIdPaginated instead
2190
+ */
2191
+ async getThreadsByResourceId({ resourceId }) {
2192
+ return this.stores.memory.getThreadsByResourceId({ resourceId });
2193
+ }
2194
+ async getThreadsByResourceIdPaginated(args) {
2195
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
2196
+ }
2197
+ async saveThread({ thread }) {
2198
+ return this.stores.memory.saveThread({ thread });
2199
+ }
2200
+ async updateThread({
2201
+ id,
2202
+ title,
2203
+ metadata
2204
+ }) {
2205
+ return this.stores.memory.updateThread({ id, title, metadata });
2206
+ }
2207
+ async deleteThread({ threadId }) {
2208
+ return this.stores.memory.deleteThread({ threadId });
2209
+ }
2210
+ async saveMessages(args) {
2211
+ return this.stores.memory.saveMessages(args);
2212
+ }
2213
+ async getMessages({
2214
+ threadId,
2215
+ selectBy,
2216
+ format
2217
+ }) {
2218
+ return this.stores.memory.getMessages({ threadId, selectBy, format });
2219
+ }
2220
+ async getMessagesPaginated({
2221
+ threadId,
2222
+ selectBy,
2223
+ format
2224
+ }) {
2225
+ return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2226
+ }
2227
+ async persistWorkflowSnapshot({
2228
+ workflowName,
2229
+ runId,
2230
+ snapshot
2231
+ }) {
2232
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2233
+ }
2234
+ async loadWorkflowSnapshot(params) {
2235
+ return this.stores.workflows.loadWorkflowSnapshot(params);
2236
+ }
2237
+ async getWorkflowRuns({
2238
+ workflowName,
2239
+ fromDate,
2240
+ toDate,
2241
+ limit,
2242
+ offset,
2243
+ resourceId
2244
+ } = {}) {
2245
+ return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2246
+ }
2247
+ async getWorkflowRunById({
2248
+ runId,
2249
+ workflowName
2250
+ }) {
2251
+ return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2252
+ }
2253
+ /**
2254
+ * Insert multiple records in a batch operation
2255
+ * @param tableName The table to insert into
2256
+ * @param records The records to insert
2257
+ */
2258
+ async batchInsert({ tableName, records }) {
2259
+ return this.stores.operations.batchInsert({ tableName, records });
2260
+ }
2261
+ /**
2262
+ * @deprecated use getTracesPaginated instead
2263
+ */
2264
+ async getTraces(args) {
2265
+ return this.stores.traces.getTraces(args);
2266
+ }
2267
+ async getTracesPaginated(args) {
2268
+ return this.stores.traces.getTracesPaginated(args);
2269
+ }
2270
+ /**
2271
+ * @deprecated use getEvals instead
2272
+ */
2273
+ async getEvalsByAgentName(agentName, type) {
2274
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2275
+ }
2276
+ async getEvals(options) {
2277
+ return this.stores.legacyEvals.getEvals(options);
2278
+ }
2279
+ async updateMessages(_args) {
2280
+ return this.stores.memory.updateMessages(_args);
2281
+ }
2282
+ async getResourceById({ resourceId }) {
2283
+ return this.stores.memory.getResourceById({ resourceId });
2284
+ }
2285
+ async saveResource({ resource }) {
2286
+ return this.stores.memory.saveResource({ resource });
2287
+ }
2288
+ async updateResource({
2289
+ resourceId,
2290
+ workingMemory,
2291
+ metadata
2292
+ }) {
2293
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
2294
+ }
2295
+ async getScoreById({ id: _id }) {
2296
+ return this.stores.scores.getScoreById({ id: _id });
2297
+ }
2298
+ async saveScore(_score) {
2299
+ return this.stores.scores.saveScore(_score);
2300
+ }
2301
+ async getScoresByRunId({
2302
+ runId: _runId,
2303
+ pagination: _pagination
2304
+ }) {
2305
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2306
+ }
2307
+ async getScoresByEntityId({
2308
+ entityId: _entityId,
2309
+ entityType: _entityType,
2310
+ pagination: _pagination
2311
+ }) {
2312
+ return this.stores.scores.getScoresByEntityId({
2313
+ entityId: _entityId,
2314
+ entityType: _entityType,
2315
+ pagination: _pagination
2316
+ });
2317
+ }
2318
+ async getScoresByScorerId({
2319
+ scorerId: _scorerId,
2320
+ pagination: _pagination
2321
+ }) {
2322
+ return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
1042
2323
  }
1043
2324
  /**
1044
2325
  * Close the database connection