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