@mastra/cloudflare-d1 0.0.0-vector-sources-20250516175436 → 0.0.0-vector-query-tool-provider-options-20250828222356

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