@mastra/mssql 0.0.0-main-test-05-11-2025-2-20251106053353 → 0.0.0-main-test-2-20251127211532

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -156,6 +156,18 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
156
156
  }
157
157
  async listThreadsByResourceId(args) {
158
158
  const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
159
+ if (page < 0) {
160
+ throw new error.MastraError({
161
+ id: "MASTRA_STORAGE_MSSQL_STORE_INVALID_PAGE",
162
+ domain: error.ErrorDomain.STORAGE,
163
+ category: error.ErrorCategory.USER,
164
+ text: "Page number must be non-negative",
165
+ details: {
166
+ resourceId,
167
+ page
168
+ }
169
+ });
170
+ }
159
171
  const perPage = storage.normalizePerPage(perPageInput, 100);
160
172
  const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
161
173
  const { field, direction } = this.parseOrderBy(orderBy);
@@ -511,43 +523,59 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
511
523
  new Error("threadId must be a non-empty string")
512
524
  );
513
525
  }
526
+ if (page < 0) {
527
+ throw new error.MastraError({
528
+ id: "MASTRA_STORAGE_MSSQL_STORE_INVALID_PAGE",
529
+ domain: error.ErrorDomain.STORAGE,
530
+ category: error.ErrorCategory.USER,
531
+ text: "Page number must be non-negative",
532
+ details: {
533
+ threadId,
534
+ page
535
+ }
536
+ });
537
+ }
514
538
  const perPage = storage.normalizePerPage(perPageInput, 40);
515
539
  const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
516
540
  try {
517
541
  const { field, direction } = this.parseOrderBy(orderBy, "ASC");
518
- const orderByStatement = `ORDER BY [${field}] ${direction}`;
519
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
542
+ const orderByStatement = `ORDER BY [${field}] ${direction}, [seq_id] ${direction}`;
520
543
  const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
521
- const conditions = ["[thread_id] = @threadId"];
522
- const request = this.pool.request();
523
- request.input("threadId", threadId);
524
- if (resourceId) {
525
- conditions.push("[resourceId] = @resourceId");
526
- request.input("resourceId", resourceId);
527
- }
528
- if (filter?.dateRange?.start) {
529
- conditions.push("[createdAt] >= @fromDate");
530
- request.input("fromDate", filter.dateRange.start);
531
- }
532
- if (filter?.dateRange?.end) {
533
- conditions.push("[createdAt] <= @toDate");
534
- request.input("toDate", filter.dateRange.end);
535
- }
536
- const whereClause = `WHERE ${conditions.join(" AND ")}`;
537
- const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
538
- const countResult = await request.query(countQuery);
544
+ const baseQuery = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId FROM ${tableName}`;
545
+ const filters = {
546
+ thread_id: threadId,
547
+ ...resourceId ? { resourceId } : {},
548
+ ...buildDateRangeFilter(filter?.dateRange, "createdAt")
549
+ };
550
+ const { sql: actualWhereClause = "", params: whereParams } = prepareWhereClause(
551
+ filters);
552
+ const bindWhereParams = (req) => {
553
+ Object.entries(whereParams).forEach(([paramName, paramValue]) => req.input(paramName, paramValue));
554
+ };
555
+ const countRequest = this.pool.request();
556
+ bindWhereParams(countRequest);
557
+ const countResult = await countRequest.query(`SELECT COUNT(*) as total FROM ${tableName}${actualWhereClause}`);
539
558
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
540
- const limitValue = perPageInput === false ? total : perPage;
541
- const dataQuery = `${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
542
- request.input("offset", offset);
543
- if (limitValue > 2147483647) {
544
- request.input("limit", sql2__default.default.BigInt, limitValue);
545
- } else {
546
- request.input("limit", limitValue);
547
- }
548
- const rowsResult = await request.query(dataQuery);
549
- const rows = rowsResult.recordset || [];
550
- const messages = [...rows];
559
+ const fetchBaseMessages = async () => {
560
+ const request = this.pool.request();
561
+ bindWhereParams(request);
562
+ if (perPageInput === false) {
563
+ const result2 = await request.query(`${baseQuery}${actualWhereClause} ${orderByStatement}`);
564
+ return result2.recordset || [];
565
+ }
566
+ request.input("offset", offset);
567
+ request.input("limit", perPage > 2147483647 ? sql2__default.default.BigInt : sql2__default.default.Int, perPage);
568
+ const result = await request.query(
569
+ `${baseQuery}${actualWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`
570
+ );
571
+ return result.recordset || [];
572
+ };
573
+ const baseRows = perPage === 0 ? [] : await fetchBaseMessages();
574
+ const messages = [...baseRows];
575
+ const seqById = /* @__PURE__ */ new Map();
576
+ messages.forEach((msg) => {
577
+ if (typeof msg.seq_id === "number") seqById.set(msg.id, msg.seq_id);
578
+ });
551
579
  if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
552
580
  return {
553
581
  messages: [],
@@ -557,28 +585,33 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
557
585
  hasMore: false
558
586
  };
559
587
  }
560
- const messageIds = new Set(messages.map((m) => m.id));
561
- if (include && include.length > 0) {
588
+ if (include?.length) {
589
+ const messageIds = new Set(messages.map((m) => m.id));
562
590
  const includeMessages = await this._getIncludedMessages({ threadId, include });
563
- if (includeMessages) {
564
- for (const includeMsg of includeMessages) {
565
- if (!messageIds.has(includeMsg.id)) {
566
- messages.push(includeMsg);
567
- messageIds.add(includeMsg.id);
568
- }
591
+ includeMessages?.forEach((msg) => {
592
+ if (!messageIds.has(msg.id)) {
593
+ messages.push(msg);
594
+ messageIds.add(msg.id);
595
+ if (typeof msg.seq_id === "number") seqById.set(msg.id, msg.seq_id);
569
596
  }
570
- }
597
+ });
571
598
  }
572
599
  const parsed = this._parseAndFormatMessages(messages, "v2");
573
- let finalMessages = parsed;
574
- finalMessages = finalMessages.sort((a, b) => {
575
- const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
576
- const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
577
- return direction === "ASC" ? aValue - bValue : bValue - aValue;
600
+ const mult = direction === "ASC" ? 1 : -1;
601
+ const finalMessages = parsed.sort((a, b) => {
602
+ const aVal = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
603
+ const bVal = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
604
+ if (aVal == null || bVal == null) {
605
+ return aVal == null && bVal == null ? a.id.localeCompare(b.id) : aVal == null ? 1 : -1;
606
+ }
607
+ const diff = (typeof aVal === "number" && typeof bVal === "number" ? aVal - bVal : String(aVal).localeCompare(String(bVal))) * mult;
608
+ if (diff !== 0) return diff;
609
+ const seqA = seqById.get(a.id);
610
+ const seqB = seqById.get(b.id);
611
+ return seqA != null && seqB != null ? (seqA - seqB) * mult : a.id.localeCompare(b.id);
578
612
  });
579
- const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
580
- const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
581
- const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
613
+ const returnedThreadMessageCount = finalMessages.filter((m) => m.threadId === threadId).length;
614
+ const hasMore = perPageInput !== false && returnedThreadMessageCount < total && offset + perPage < total;
582
615
  return {
583
616
  messages: finalMessages,
584
617
  total,
@@ -1685,6 +1718,20 @@ ${columns}
1685
1718
  return value ? 1 : 0;
1686
1719
  }
1687
1720
  if (columnSchema?.type === "jsonb") {
1721
+ if (typeof value === "string") {
1722
+ const trimmed = value.trim();
1723
+ if (trimmed.length > 0) {
1724
+ try {
1725
+ JSON.parse(trimmed);
1726
+ return trimmed;
1727
+ } catch {
1728
+ }
1729
+ }
1730
+ return JSON.stringify(value);
1731
+ }
1732
+ if (typeof value === "bigint") {
1733
+ return value.toString();
1734
+ }
1688
1735
  return JSON.stringify(value);
1689
1736
  }
1690
1737
  if (typeof value === "object") {
@@ -2225,8 +2272,8 @@ function transformScoreRow(row) {
2225
2272
  additionalContext: storage.safelyParseJSON(row.additionalContext),
2226
2273
  requestContext: storage.safelyParseJSON(row.requestContext),
2227
2274
  entity: storage.safelyParseJSON(row.entity),
2228
- createdAt: row.createdAt,
2229
- updatedAt: row.updatedAt
2275
+ createdAt: new Date(row.createdAt),
2276
+ updatedAt: new Date(row.updatedAt)
2230
2277
  };
2231
2278
  }
2232
2279
  var ScoresMSSQL = class extends storage.ScoresStorage {
@@ -2630,13 +2677,14 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2630
2677
  snapshot = {
2631
2678
  context: {},
2632
2679
  activePaths: [],
2680
+ activeStepsPath: {},
2633
2681
  timestamp: Date.now(),
2634
2682
  suspendedPaths: {},
2635
2683
  resumeLabels: {},
2636
2684
  serializedStepGraph: [],
2685
+ status: "pending",
2637
2686
  value: {},
2638
2687
  waitingPaths: {},
2639
- status: "pending",
2640
2688
  runId,
2641
2689
  requestContext: {}
2642
2690
  };
@@ -2866,7 +2914,8 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2866
2914
  toDate,
2867
2915
  page,
2868
2916
  perPage,
2869
- resourceId
2917
+ resourceId,
2918
+ status
2870
2919
  } = {}) {
2871
2920
  try {
2872
2921
  const conditions = [];
@@ -2875,6 +2924,10 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2875
2924
  conditions.push(`[workflow_name] = @workflowName`);
2876
2925
  paramMap["workflowName"] = workflowName;
2877
2926
  }
2927
+ if (status) {
2928
+ conditions.push(`JSON_VALUE([snapshot], '$.status') = @status`);
2929
+ paramMap["status"] = status;
2930
+ }
2878
2931
  if (resourceId) {
2879
2932
  const hasResourceId = await this.operations.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
2880
2933
  if (hasResourceId) {
@@ -3143,15 +3196,8 @@ var MSSQLStore = class extends storage.MastraStorage {
3143
3196
  }) {
3144
3197
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3145
3198
  }
3146
- async listWorkflowRuns({
3147
- workflowName,
3148
- fromDate,
3149
- toDate,
3150
- perPage,
3151
- page,
3152
- resourceId
3153
- } = {}) {
3154
- return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
3199
+ async listWorkflowRuns(args = {}) {
3200
+ return this.stores.workflows.listWorkflowRuns(args);
3155
3201
  }
3156
3202
  async getWorkflowRunById({
3157
3203
  runId,