@mastra/cloudflare-d1 0.0.0-remove-cloud-span-transform-20250425214156 → 0.0.0-remove-unused-model-providers-api-20251030210744

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