@mastra/loggers 1.3.9-alpha.1 → 1.3.9

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.
@@ -3,7 +3,7 @@ name: mastra-loggers
3
3
  description: Documentation for @mastra/loggers. Use when working with @mastra/loggers APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/loggers"
6
- version: "1.3.9-alpha.1"
6
+ version: "1.3.9"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.3.9-alpha.1",
2
+ "version": "1.3.9",
3
3
  "package": "@mastra/loggers",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -147,9 +147,9 @@ Re-drives every orphaned `running` durable-agent run across all registered durab
147
147
 
148
148
  Requires persistent storage. With an in-memory store, there's nothing to recover after a process restart.
149
149
 
150
- Agents and their runs are attempted serially. Each built-in `recoverActiveRuns()` attempt waits up to 30 seconds in total for `recover()` setup and settlement of the whole recovered workflow, then traversal can continue to later runs and agents. This isn't an overall recovery deadline: discovery and overridden custom recovery methods aren't bounded by this budget.
150
+ Recovery processes up to five agents concurrently, with up to five run waits per agent, independently of `recovery.workflowConcurrency`. Each built-in `recoverActiveRuns()` attempt waits up to 30 seconds in total for `recover()` setup and settlement of the whole recovered workflow, then frees its slot for another run. These limits bound waiting, not live executions. This isn't an overall recovery deadline: discovery and overridden custom recovery methods aren't bounded by this budget.
151
151
 
152
- A timed-out attempt continues in the background. Its outcome is `status: 'skipped'` with `reason: 'recovery-timeout'` and no `retryAt`. It contributes only to `skipped`, not `recovered`, `succeeded`, or `failed`, and Mastra doesn't automatically retry it. Late settlement doesn't change the returned counts.
152
+ A timed-out attempt continues in the background. Its outcome is `status: 'skipped'` with `reason: 'recovery-timeout'` and a future `retryAt`. It contributes only to `skipped`, not `recovered`, `succeeded`, or `failed`. Mastra schedules re-checks automatically. While the original attempt is pending, re-checks defer without starting another execution. After it settles, recovery checks the persisted snapshot and ownership before retrying; finished or suspended runs aren't restarted. Late settlement doesn't change the returned counts.
153
153
 
154
154
  When shutdown begins, recovery stops dispatching new agents and runs. The recovery traversal and original attempts, including timed-out setup or execution, participate in the same shared shutdown drain as active executions. A recovery wait timeout doesn't cancel the attempt or give it a separate shutdown drain window.
155
155
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["LoggerTransport","#queryLogs","MastraError","ErrorDomain","ErrorCategory","normalizePagination"],"sources":["../../src/file/index.ts"],"sourcesContent":["import type { WriteStream } from 'node:fs';\nimport { createReadStream, createWriteStream, existsSync, statSync } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\nexport class FileTransport extends LoggerTransport {\n path: string;\n fileStream: WriteStream;\n constructor({ path }: { path: string }) {\n super({ objectMode: true });\n this.path = path;\n\n if (!existsSync(this.path)) {\n throw new Error('File path does not exist');\n }\n\n if (!statSync(this.path).isFile()) {\n throw new Error(`File path must point to a file: ${this.path}`);\n }\n\n this.fileStream = createWriteStream(this.path, { flags: 'a' });\n // Without a listener, the file stream's 'error' event would crash the process.\n // Write failures already reach the transport through the write callback, so only\n // forward errors that have not destroyed the transport yet (e.g. open failures).\n this.fileStream.on('error', error => {\n if (!this.destroyed) this.destroy(error);\n });\n }\n\n _transform(chunk: any, _encoding: string, callback: (error: Error | null, chunk?: any) => void) {\n try {\n this.fileStream.write(chunk, error => {\n if (error) callback(error);\n else callback(null, chunk);\n });\n } catch (error) {\n callback(error as Error);\n }\n }\n\n _flush(callback: Function) {\n // End the file stream when transform stream ends\n this.fileStream.end(() => {\n callback();\n });\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n // Clean up resources\n _destroy(error: Error, callback: Function) {\n if (this.fileStream) {\n this.fileStream.destroy(error);\n }\n callback(error);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(params?.page, params?.perPage);\n try {\n return await this.#queryLogs(params || {});\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path },\n },\n error,\n );\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(page, perPage);\n try {\n return await this.#queryLogs({ runId, fromDate, toDate, logLevel, filters, page, perPage });\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_BY_RUN_ID_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path, runId },\n },\n error,\n );\n }\n }\n\n /**\n * Streams the log file line by line, counting every matching record but\n * retaining only the requested page (or all matches when pagination is off).\n */\n async #queryLogs({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults = true,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId?: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }) {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n const filterEntries = Object.entries(filters ?? {});\n\n const logs: BaseLogMessage[] = [];\n let total = 0;\n\n const lines = createInterface({ input: createReadStream(this.path, 'utf8'), crlfDelay: Infinity });\n for await (const line of lines) {\n if (!line.trim()) continue;\n\n let log: any;\n try {\n log = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (log === null || typeof log !== 'object') continue;\n if (runId !== undefined && log.runId !== runId) continue;\n if (!filterEntries.every(([key, value]) => log[key] === value)) continue;\n if (logLevel && log.level !== logLevel) continue;\n if (fromDate && !(new Date(log.time).getTime() >= fromDate.getTime())) continue;\n if (toDate && !(new Date(log.time).getTime() <= toDate.getTime())) continue;\n\n if (!returnPaginationResults || (total >= start && total < end)) {\n logs.push(log);\n }\n total++;\n }\n\n if (!returnPaginationResults) {\n return { logs, total, page, perPage: total, hasMore: false };\n }\n\n return { logs, total, page, perPage, hasMore: end < total };\n }\n}\n"],"mappings":";;;;;;;AAQA,IAAa,gBAAb,cAAmCA,oBAAAA,gBAAgB;CACjD;CACA;CACA,YAAY,EAAE,QAA0B;EACtC,MAAM,EAAE,YAAY,KAAK,CAAC;EAC1B,KAAK,OAAO;EAEZ,IAAI,EAAA,GAAA,GAAA,WAAA,CAAY,KAAK,IAAI,GACvB,MAAM,IAAI,MAAM,0BAA0B;EAG5C,IAAI,EAAA,GAAA,GAAA,SAAA,CAAU,KAAK,IAAI,CAAC,CAAC,OAAO,GAC9B,MAAM,IAAI,MAAM,mCAAmC,KAAK,MAAM;EAGhE,KAAK,cAAA,GAAA,GAAA,kBAAA,CAA+B,KAAK,MAAM,EAAE,OAAO,IAAI,CAAC;EAI7D,KAAK,WAAW,GAAG,UAAS,UAAS;GACnC,IAAI,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK;EACzC,CAAC;CACH;CAEA,WAAW,OAAY,WAAmB,UAAsD;EAC9F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ream","MastraError","ErrorDomain","ErrorCategory","normalizePagination","createInterface","createReadStream"],"sources":["../../src/file/index.ts"],"sourcesContent":["import type { WriteStream } from 'node:fs';\nimport { createReadStream, createWriteStream, existsSync, statSync } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\nexport class FileTransport extends LoggerTransport {\n path: string;\n fileStream: WriteStream;\n constructor({ path }: { path: string }) {\n super({ objectMode: true });\n this.path = path;\n\n if (!existsSync(this.path)) {\n throw new Error('File path does not exist');\n }\n\n if (!statSync(this.path).isFile()) {\n throw new Error(`File path must point to a file: ${this.path}`);\n }\n\n this.fileStream = createWriteStream(this.path, { flags: 'a' });\n // Without a listener, the file stream's 'error' event would crash the process.\n // Write failures already reach the transport through the write callback, so only\n // forward errors that have not destroyed the transport yet (e.g. open failures).\n this.fileStream.on('error', error => {\n if (!this.destroyed) this.destroy(error);\n });\n }\n\n _transform(chunk: any, _encoding: string, callback: (error: Error | null, chunk?: any) => void) {\n try {\n this.fileStream.write(chunk, error => {\n if (error) callback(error);\n else callback(null, chunk);\n });\n } catch (error) {\n callback(error as Error);\n }\n }\n\n _flush(callback: Function) {\n // End the file stream when transform stream ends\n this.fileStream.end(() => {\n callback();\n });\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n // Clean up resources\n _destroy(error: Error, callback: Function) {\n if (this.fileStream) {\n this.fileStream.destroy(error);\n }\n callback(error);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(params?.page, params?.perPage);\n try {\n return await this.#queryLogs(params || {});\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path },\n },\n error,\n );\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(page, perPage);\n try {\n return await this.#queryLogs({ runId, fromDate, toDate, logLevel, filters, page, perPage });\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_BY_RUN_ID_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path, runId },\n },\n error,\n );\n }\n }\n\n /**\n * Streams the log file line by line, counting every matching record but\n * retaining only the requested page (or all matches when pagination is off).\n */\n async #queryLogs({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults = true,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId?: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }) {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n const filterEntries = Object.entries(filters ?? {});\n\n const logs: BaseLogMessage[] = [];\n let total = 0;\n\n const lines = createInterface({ input: createReadStream(this.path, 'utf8'), crlfDelay: Infinity });\n for await (const line of lines) {\n if (!line.trim()) continue;\n\n let log: any;\n try {\n log = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (log === null || typeof log !== 'object') continue;\n if (runId !== undefined && log.runId !== runId) continue;\n if (!filterEntries.every(([key, value]) => log[key] === value)) continue;\n if (logLevel && log.level !== logLevel) continue;\n if (fromDate && !(new Date(log.time).getTime() >= fromDate.getTime())) continue;\n if (toDate && !(new Date(log.time).getTime() <= toDate.getTime())) continue;\n\n if (!returnPaginationResults || (total >= start && total < end)) {\n logs.push(log);\n }\n total++;\n }\n\n if (!returnPaginationResults) {\n return { logs, total, page, perPage: total, hasMore: false };\n }\n\n return { logs, total, page, perPage, hasMore: end < total };\n }\n}\n"],"mappings":";;;;;;;AAQA,IAAa,gBAAb,cAAmCA,oBAAAA,gBAAgB;CACjD;CACA;CACA,YAAY,EAAE,QAA0B;EACtC,MAAM,EAAE,YAAY,KAAK,CAAC;EAC1B,KAAK,OAAO;EAEZ,IAAI,EAAA,GAACC,GAAAA,WAAAA,CAAW,KAAK,IAAI,GACvB,MAAM,IAAI,MAAM,0BAA0B;EAG5C,IAAI,EAAA,GAACC,GAAAA,SAAAA,CAAS,KAAK,IAAI,CAAC,CAAC,OAAO,GAC9B,MAAM,IAAI,MAAM,mCAAmC,KAAK,MAAM;EAGhE,KAAK,cAAA,GAAaC,GAAAA,kBAAAA,CAAkB,KAAK,MAAM,EAAE,OAAO,IAAI,CAAC;EAI7D,KAAK,WAAW,GAAG,UAAS,UAAS;GACnC,IAAI,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK;EACzC,CAAC;CACH;CAEA,WAAW,OAAY,WAAmB,UAAsD;EAC9F,IAAI;GACF,KAAK,WAAW,MAAM,QAAO,UAAS;IACpC,IAAI,OAAO,SAAS,KAAK;SACpB,SAAS,MAAM,KAAK;GAC3B,CAAC;EACH,SAAS,OAAO;GACd,SAAS,KAAc;EACzB;CACF;CAEA,OAAO,UAAoB;EAEzB,KAAK,WAAW,UAAU;GACxB,SAAS;EACX,CAAC;CAC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AAC,CAAC;EAElD,MAAM,OAAyB,CAAC;EAChC,IAAI,QAAQ;EAEZ,MAAM,SAAA,GAAQC,SAAAA,gBAAAA,CAAgB;GAAE,QAAA,GAAOC,GAAAA,iBAAAA,CAAiB,KAAK,MAAM,MAAM;GAAG,WAAW;EAAS,CAAC;EACjG,WAAW,MAAM,QAAQ,OAAO;GAC9B,IAAI,CAAC,KAAK,KAAK,GAAG;GAElB,IAAI;GACJ,IAAI;IACF,MAAM,KAAK,MAAM,IAAI;GACvB,QAAQ;IACN;GACF;GAEA,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;GAC7C,IAAI,UAAU,KAAA,KAAa,IAAI,UAAU,OAAO;GAChD,IAAI,CAAC,cAAc,OAAO,CAAC,KAAK,WAAW,IAAI,SAAS,KAAK,GAAG;GAChE,IAAI,YAAY,IAAI,UAAU,UAAU;GACxC,IAAI,YAAY,EAAE,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,QAAQ,IAAI;GACvE,IAAI,UAAU,EAAE,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,QAAQ,IAAI;GAEnE,IAAI,CAAC,2BAA4B,SAAS,SAAS,QAAQ,KACzD,KAAK,KAAK,GAAG;GAEf;EACF;EAEA,IAAI,CAAC,yBACH,OAAO;GAAE;GAAM;GAAO;GAAM,SAAS;GAAO,SAAS;EAAM;EAG7D,OAAO;GAAE;GAAM;GAAO;GAAM;GAAS,SAAS,MAAM;EAAM;CAC5D;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#queryLogs"],"sources":["../../src/file/index.ts"],"sourcesContent":["import type { WriteStream } from 'node:fs';\nimport { createReadStream, createWriteStream, existsSync, statSync } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\nexport class FileTransport extends LoggerTransport {\n path: string;\n fileStream: WriteStream;\n constructor({ path }: { path: string }) {\n super({ objectMode: true });\n this.path = path;\n\n if (!existsSync(this.path)) {\n throw new Error('File path does not exist');\n }\n\n if (!statSync(this.path).isFile()) {\n throw new Error(`File path must point to a file: ${this.path}`);\n }\n\n this.fileStream = createWriteStream(this.path, { flags: 'a' });\n // Without a listener, the file stream's 'error' event would crash the process.\n // Write failures already reach the transport through the write callback, so only\n // forward errors that have not destroyed the transport yet (e.g. open failures).\n this.fileStream.on('error', error => {\n if (!this.destroyed) this.destroy(error);\n });\n }\n\n _transform(chunk: any, _encoding: string, callback: (error: Error | null, chunk?: any) => void) {\n try {\n this.fileStream.write(chunk, error => {\n if (error) callback(error);\n else callback(null, chunk);\n });\n } catch (error) {\n callback(error as Error);\n }\n }\n\n _flush(callback: Function) {\n // End the file stream when transform stream ends\n this.fileStream.end(() => {\n callback();\n });\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n // Clean up resources\n _destroy(error: Error, callback: Function) {\n if (this.fileStream) {\n this.fileStream.destroy(error);\n }\n callback(error);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(params?.page, params?.perPage);\n try {\n return await this.#queryLogs(params || {});\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path },\n },\n error,\n );\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(page, perPage);\n try {\n return await this.#queryLogs({ runId, fromDate, toDate, logLevel, filters, page, perPage });\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_BY_RUN_ID_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path, runId },\n },\n error,\n );\n }\n }\n\n /**\n * Streams the log file line by line, counting every matching record but\n * retaining only the requested page (or all matches when pagination is off).\n */\n async #queryLogs({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults = true,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId?: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }) {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n const filterEntries = Object.entries(filters ?? {});\n\n const logs: BaseLogMessage[] = [];\n let total = 0;\n\n const lines = createInterface({ input: createReadStream(this.path, 'utf8'), crlfDelay: Infinity });\n for await (const line of lines) {\n if (!line.trim()) continue;\n\n let log: any;\n try {\n log = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (log === null || typeof log !== 'object') continue;\n if (runId !== undefined && log.runId !== runId) continue;\n if (!filterEntries.every(([key, value]) => log[key] === value)) continue;\n if (logLevel && log.level !== logLevel) continue;\n if (fromDate && !(new Date(log.time).getTime() >= fromDate.getTime())) continue;\n if (toDate && !(new Date(log.time).getTime() <= toDate.getTime())) continue;\n\n if (!returnPaginationResults || (total >= start && total < end)) {\n logs.push(log);\n }\n total++;\n }\n\n if (!returnPaginationResults) {\n return { logs, total, page, perPage: total, hasMore: false };\n }\n\n return { logs, total, page, perPage, hasMore: end < total };\n }\n}\n"],"mappings":";;;;;;AAQA,IAAa,gBAAb,cAAmC,gBAAgB;CACjD;CACA;CACA,YAAY,EAAE,QAA0B;EACtC,MAAM,EAAE,YAAY,KAAK,CAAC;EAC1B,KAAK,OAAO;EAEZ,IAAI,CAAC,WAAW,KAAK,IAAI,GACvB,MAAM,IAAI,MAAM,0BAA0B;EAG5C,IAAI,CAAC,SAAS,KAAK,IAAI,CAAC,CAAC,OAAO,GAC9B,MAAM,IAAI,MAAM,mCAAmC,KAAK,MAAM;EAGhE,KAAK,aAAa,kBAAkB,KAAK,MAAM,EAAE,OAAO,IAAI,CAAC;EAI7D,KAAK,WAAW,GAAG,UAAS,UAAS;GACnC,IAAI,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK;EACzC,CAAC;CACH;CAEA,WAAW,OAAY,WAAmB,UAAsD;EAC9F,IAAI;GACF,KAAK,WAAW,MAAM,QAAO,UAAS;IACpC,IAAI,OAAO,SAAS,KAAK;SACpB,SAAS,MAAM,KAAK;GAC3B,CAAC;EACH,SAAS,OAAO;GACd,SAAS,KAAc;EACzB;CACF;CAEA,OAAO,UAAoB;EAEzB,KAAK,WAAW,UAAU;GACxB,SAAS;EACX,CAAC;CACH;CAEA,OAAO,OAAY,UAAmB,UAAoD;EACxF,IAAI,OAAO,aAAa,YAAY;GAClC,KAAK,WAAW,OAAO,YAAY,QAAQ,QAAQ;GACnD,OAAO;EACT;EAEA,KAAK,WAAW,OAAO,YAAY,SAAS,UAAwB;GAClE,IAAI,OAAO,QAAQ,MAAM,6BAA6B,KAAK;EAC7D,CAAC;EACD,OAAO;CACT;CAGA,SAAS,OAAc,UAAoB;EACzC,IAAI,KAAK,YACP,KAAK,WAAW,QAAQ,KAAK;EAE/B,SAAS,KAAK;CAChB;CAEA,M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AK,WAAW,IAAI,SAAS,KAAK,GAAG;GAChE,IAAI,YAAY,IAAI,UAAU,UAAU;GACxC,IAAI,YAAY,EAAE,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,QAAQ,IAAI;GACvE,IAAI,UAAU,EAAE,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,QAAQ,IAAI;GAEnE,IAAI,CAAC,2BAA4B,SAAS,SAAS,QAAQ,KACzD,KAAK,KAAK,GAAG;GAEf;EACF;EAEA,IAAI,CAAC,yBACH,OAAO;GAAE;GAAM;GAAO;GAAM,SAAS;GAAO,SAAS;EAAM;EAG7D,OAAO;GAAE;GAAM;GAAO;GAAM;GAAS,SAAS,MAAM;EAAM;CAC5D;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/file/index.ts"],"sourcesContent":["import type { WriteStream } from 'node:fs';\nimport { createReadStream, createWriteStream, existsSync, statSync } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\nexport class FileTransport extends LoggerTransport {\n path: string;\n fileStream: WriteStream;\n constructor({ path }: { path: string }) {\n super({ objectMode: true });\n this.path = path;\n\n if (!existsSync(this.path)) {\n throw new Error('File path does not exist');\n }\n\n if (!statSync(this.path).isFile()) {\n throw new Error(`File path must point to a file: ${this.path}`);\n }\n\n this.fileStream = createWriteStream(this.path, { flags: 'a' });\n // Without a listener, the file stream's 'error' event would crash the process.\n // Write failures already reach the transport through the write callback, so only\n // forward errors that have not destroyed the transport yet (e.g. open failures).\n this.fileStream.on('error', error => {\n if (!this.destroyed) this.destroy(error);\n });\n }\n\n _transform(chunk: any, _encoding: string, callback: (error: Error | null, chunk?: any) => void) {\n try {\n this.fileStream.write(chunk, error => {\n if (error) callback(error);\n else callback(null, chunk);\n });\n } catch (error) {\n callback(error as Error);\n }\n }\n\n _flush(callback: Function) {\n // End the file stream when transform stream ends\n this.fileStream.end(() => {\n callback();\n });\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n // Clean up resources\n _destroy(error: Error, callback: Function) {\n if (this.fileStream) {\n this.fileStream.destroy(error);\n }\n callback(error);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(params?.page, params?.perPage);\n try {\n return await this.#queryLogs(params || {});\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path },\n },\n error,\n );\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(page, perPage);\n try {\n return await this.#queryLogs({ runId, fromDate, toDate, logLevel, filters, page, perPage });\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_BY_RUN_ID_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path, runId },\n },\n error,\n );\n }\n }\n\n /**\n * Streams the log file line by line, counting every matching record but\n * retaining only the requested page (or all matches when pagination is off).\n */\n async #queryLogs({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults = true,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId?: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }) {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n const filterEntries = Object.entries(filters ?? {});\n\n const logs: BaseLogMessage[] = [];\n let total = 0;\n\n const lines = createInterface({ input: createReadStream(this.path, 'utf8'), crlfDelay: Infinity });\n for await (const line of lines) {\n if (!line.trim()) continue;\n\n let log: any;\n try {\n log = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (log === null || typeof log !== 'object') continue;\n if (runId !== undefined && log.runId !== runId) continue;\n if (!filterEntries.every(([key, value]) => log[key] === value)) continue;\n if (logLevel && log.level !== logLevel) continue;\n if (fromDate && !(new Date(log.time).getTime() >= fromDate.getTime())) continue;\n if (toDate && !(new Date(log.time).getTime() <= toDate.getTime())) continue;\n\n if (!returnPaginationResults || (total >= start && total < end)) {\n logs.push(log);\n }\n total++;\n }\n\n if (!returnPaginationResults) {\n return { logs, total, page, perPage: total, hasMore: false };\n }\n\n return { logs, total, page, perPage, hasMore: end < total };\n }\n}\n"],"mappings":";;;;;;AAQA,IAAa,gBAAb,cAAmC,gBAAgB;CACjD;CACA;CACA,YAAY,EAAE,QAA0B;EACtC,MAAM,EAAE,YAAY,KAAK,CAAC;EAC1B,KAAK,OAAO;EAEZ,IAAI,CAAC,WAAW,KAAK,IAAI,GACvB,MAAM,IAAI,MAAM,0BAA0B;EAG5C,IAAI,CAAC,SAAS,KAAK,IAAI,CAAC,CAAC,OAAO,GAC9B,MAAM,IAAI,MAAM,mCAAmC,KAAK,MAAM;EAGhE,KAAK,aAAa,kBAAkB,KAAK,MA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@ -59,6 +59,11 @@ var HttpTransport = class extends _mastra_core_logger.LoggerTransport {
59
59
  this.logBuffer = [];
60
60
  this.lastFlush = Date.now();
61
61
  this.flushIntervalId = setInterval(() => this.requestFlush(), this.flushInterval);
62
+ this.updateIntervalRef();
63
+ }
64
+ updateIntervalRef() {
65
+ if (this.logBuffer.length > 0 || this.flushPromise) this.flushIntervalId.ref?.();
66
+ else this.flushIntervalId.unref?.();
62
67
  }
63
68
  async makeHttpRequest(data) {
64
69
  const body = JSON.stringify({ logs: data });
@@ -114,6 +119,7 @@ var HttpTransport = class extends _mastra_core_logger.LoggerTransport {
114
119
  this.flushRequested = false;
115
120
  const flush = this.flushBatch().finally(() => {
116
121
  this.flushPromise = null;
122
+ this.updateIntervalRef();
117
123
  });
118
124
  this.flushPromise = flush;
119
125
  const continueDraining = () => {
@@ -160,6 +166,7 @@ var HttpTransport = class extends _mastra_core_logger.LoggerTransport {
160
166
  } : parsed;
161
167
  this.logBuffer.push(log);
162
168
  this.enforceBufferLimit();
169
+ this.updateIntervalRef();
163
170
  if (this.logBuffer.length >= this.batchSize) this.requestFlush();
164
171
  cb(null, chunk);
165
172
  } catch (error) {
@@ -204,6 +211,7 @@ var HttpTransport = class extends _mastra_core_logger.LoggerTransport {
204
211
  }
205
212
  clearBuffer() {
206
213
  this.logBuffer = [];
214
+ this.updateIntervalRef();
207
215
  }
208
216
  getDroppedLogCount() {
209
217
  return this.droppedLogCount;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["LoggerTransport"],"sources":["../../src/http/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\n\ninterface RetryOptions {\n maxRetries?: number;\n retryDelay?: number;\n exponentialBackoff?: boolean;\n}\n\ninterface HttpTransportOptions {\n url: string;\n method?: 'POST' | 'PUT' | 'PATCH';\n headers?: Record<string, string>;\n batchSize?: number;\n flushInterval?: number;\n timeout?: number;\n retryOptions?: RetryOptions;\n maxBufferSize?: number;\n}\n\nclass HttpResponseError extends Error {\n constructor(\n readonly status: number,\n statusText: string,\n readonly retryAfterMs: number | undefined,\n ) {\n super(`HTTP ${status}: ${statusText}`);\n }\n}\n\n// Other 4xx responses mean the request itself is wrong and will fail the same way on every retry.\nfunction isRetryableStatus(status: number): boolean {\n return status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\n// Retry-After is either delta-seconds or an HTTP date (RFC 9110). Invalid values are ignored.\nfunction parseRetryAfter(headers: Headers | undefined): number | undefined {\n const value = headers?.get('retry-after')?.trim();\n if (!value) return undefined;\n if (/^\\d+$/.test(value)) return Number(value) * 1000;\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nexport class HttpTransport extends LoggerTransport {\n private url: string;\n private method: string;\n private headers: Record<string, string>;\n private batchSize: number;\n private flushInterval: number;\n private timeout: number;\n private retryOptions: Required<RetryOptions>;\n private logBuffer: BaseLogMessage[];\n private maxBufferSize: number;\n private droppedLogCount = 0;\n private flushPromise: Promise<void> | null = null;\n private flushRequested = false;\n private lastFlush: number;\n private flushIntervalId: NodeJS.Timeout;\n\n constructor(options: HttpTransportOptions) {\n super({ objectMode: true });\n\n if (!options.url) {\n throw new Error('HTTP URL is required');\n }\n\n this.url = options.url;\n this.method = options.method || 'POST';\n this.headers = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n this.batchSize = options.batchSize ?? 100;\n this.flushInterval = options.flushInterval || 10000;\n this.timeout = options.timeout || 30000;\n this.retryOptions = {\n maxRetries: options.retryOptions?.maxRetries ?? 3,\n retryDelay: options.retryOptions?.retryDelay ?? 1000,\n exponentialBackoff: options.retryOptions?.exponentialBackoff ?? true,\n };\n\n if (!Number.isInteger(this.batchSize) || this.batchSize < 1) {\n throw new Error('HttpTransport batchSize must be a positive integer');\n }\n\n const maxBufferSize = options.maxBufferSize ?? 10_000;\n if (!Number.isInteger(maxBufferSize) || maxBufferSize < 1) {\n throw new Error('HttpTransport maxBufferSize must be a positive integer');\n }\n this.maxBufferSize = Math.max(maxBufferSize, this.batchSize);\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => this.requestFlush(), this.flushInterval);\n }\n\n private async makeHttpRequest(data: any): Promise<Response> {\n // Serialize once, outside the retry loop: serialization failures are not retryable,\n // and every retry must send the exact same payload.\n const body = JSON.stringify({ logs: data });\n return this.sendWithRetry(body);\n }\n\n private async sendWithRetry(body: string, retryCount = 0): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.url, {\n method: this.method,\n headers: this.headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new HttpResponseError(response.status, response.statusText, parseRetryAfter(response.headers));\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n\n const isPermanent = error instanceof HttpResponseError && !isRetryableStatus(error.status);\n if (!isPermanent && retryCount < this.retryOptions.maxRetries) {\n const backoff = this.retryOptions.exponentialBackoff\n ? this.retryOptions.retryDelay * Math.pow(2, retryCount)\n : this.retryOptions.retryDelay;\n // Honor the server's Retry-After, capped at the request timeout so a large value can't stall shutdown.\n const retryAfter = error instanceof HttpResponseError ? (error.retryAfterMs ?? 0) : 0;\n const delay = Math.max(backoff, Math.min(retryAfter, this.timeout));\n\n await new Promise(resolve => setTimeout(resolve, delay));\n return this.sendWithRetry(body, retryCount + 1);\n }\n\n throw error;\n }\n }\n\n private enforceBufferLimit(): void {\n const overflow = this.logBuffer.length - this.maxBufferSize;\n if (overflow <= 0) {\n return;\n }\n\n this.logBuffer.splice(0, overflow);\n if (this.droppedLogCount === 0) {\n console.warn(\n `HttpTransport: buffer exceeded maxBufferSize (${this.maxBufferSize}); dropping oldest logs. Use getDroppedLogCount() to track drops.`,\n );\n }\n this.droppedLogCount += overflow;\n }\n\n // Internal fire-and-forget flush. While a request is in flight this only records the request, so writes\n // during a slow or retrying request don't each attach another handler to the pending promise.\n private requestFlush(): void {\n if (this.flushPromise) {\n this.flushRequested = true;\n return;\n }\n this._flush().catch(err => {\n console.error('Error flushing logs to HTTP endpoint:', err);\n });\n }\n\n _flush(): Promise<void> {\n // Only one request in flight at a time, so an outage doesn't fan out into overlapping retry chains.\n if (this.flushPromise) {\n this.flushRequested = true;\n return this.flushPromise;\n }\n if (this.logBuffer.length === 0) {\n return Promise.resolve();\n }\n\n this.flushRequested = false;\n const flush = this.flushBatch().finally(() => {\n this.flushPromise = null;\n });\n this.flushPromise = flush;\n // Flushes requested while this request was in flight only got this promise back, so send their logs now,\n // and keep draining full batches. On a transient failure, wait for the next interval instead of retrying\n // straight away. A permanently rejected batch was dropped, so the logs behind it can go out now.\n const continueDraining = () => {\n if (this.logBuffer.length >= this.batchSize || (this.flushRequested && this.logBuffer.length > 0)) {\n this.requestFlush();\n }\n };\n flush.then(continueDraining, error => {\n if (error instanceof HttpResponseError && !isRetryableStatus(error.status)) {\n continueDraining();\n }\n });\n return flush;\n }\n\n private async flushBatch(): Promise<void> {\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n\n try {\n await this.makeHttpRequest(logs);\n this.lastFlush = now;\n } catch (error) {\n // The endpoint rejected this batch outright, so resending it can't succeed and would block the logs behind it.\n if (error instanceof HttpResponseError && !isRetryableStatus(error.status)) {\n this.droppedLogCount += logs.length;\n console.warn(\n `HttpTransport: endpoint rejected a batch with HTTP ${error.status}; dropping ${logs.length} logs. Use getDroppedLogCount() to track drops.`,\n );\n throw error;\n }\n\n // On a transient error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n this.enforceBufferLimit();\n throw error;\n }\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n _transform(chunk: string, _enc: string, cb: Function): void {\n try {\n // Parse the log line if it's a string\n const parsed = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present, on a copy so caller-owned (possibly frozen) records stay untouched\n const log = parsed.time === undefined || parsed.time === null ? { ...parsed, time: Date.now() } : parsed;\n\n // Add to buffer\n this.logBuffer.push(log);\n this.enforceBufferLimit();\n\n // Flush if buffer reaches batch size\n if (this.logBuffer.length >= this.batchSize) {\n this.requestFlush();\n }\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function): void {\n clearInterval(this.flushIntervalId);\n\n // Final drain. Wait out any in-flight request (ignoring its failure, since its logs are back in the buffer),\n // then keep sending until the buffer is empty. A failed request ends the drain instead of retrying forever.\n if (this.logBuffer.length > 0 || this.flushPromise) {\n const drain = async () => {\n await this.flushPromise?.catch(() => {});\n while (this.flushPromise || this.logBuffer.length > 0) {\n await (this.flushPromise ?? this._flush());\n }\n };\n\n drain()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogs: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: params?.page === 0 ? 1 : (params?.page ?? 1),\n perPage: params?.perPage ?? 100,\n hasMore: false,\n };\n }\n\n async listLogsByRunId({\n runId: _runId,\n fromDate: _fromDate,\n toDate: _toDate,\n logLevel: _logLevel,\n filters: _filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogsByRunId: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: page === 0 ? 1 : (page ?? 1),\n perPage: perPage ?? 100,\n hasMore: false,\n };\n }\n\n // Utility methods\n public getBufferedLogs(): BaseLogMessage[] {\n return [...this.logBuffer];\n }\n\n public clearBuffer(): void {\n this.logBuffer = [];\n }\n\n public getDroppedLogCount(): number {\n return this.droppedLogCount;\n }\n\n public getLastFlushTime(): number {\n return this.lastFlush;\n }\n}\n"],"mappings":";;;AAoBA,IAAM,oBAAN,cAAgC,MAAM;CAEzB;CAEA;CAHX,YACE,QACA,YACA,cACA;EACA,MAAM,QAAQ,OAAO,IAAI,YAAY;EAJ5B,KAAA,SAAA;EAEA,KAAA,eAAA;CAGX;AACF;AAGA,SAAS,kBAAkB,QAAyB;CAClD,OAAO,WAAW,OAAO,WAAW,OAAO,WAAW,OAAO,UAAU;AACzE;AAGA,SAAS,gBAAgB,SAAkD;CACzE,MAAM,QAAQ,SAAS,IAAI,aAAa,CAAC,EAAE,KAAK;CAChD,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,QAAQ,KAAK,KAAK,GAAG,OAAO,OAAO,KAAK,IAAI;CAChD,MAAM,OAAO,KAAK,MAAM,KAAK;CAC7B,OAAO,OAAO,MAAM,IAAI,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,OAAO,KAAK,IAAI,CAAC;AACvE;AAEA,IAAa,gBAAb,cAAmCA,oBAAAA,gBAAgB;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,kBAA0B;CAC1B,eAA6C;CAC7C,iBAAyB;CACzB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,KAAK,WAChC,KAAK,aAAa;GAIpB,GAAG,MAAM,KAAK;EAChB,SAAS,OAAO;GACd,GAAG,KAAK;EACV;CACF;CAEA,SAAS,KAAY,IAAoB;EACvC,cAAc,KAAK,eAAe;EAIlC,IAAI,KAAK,UAAU,SAAS,KAAK,KAAK,cAAc;GAClD,MAAM,QAAQ,YAAY;IACxB,MAAM,KAAK,cAAc,YAAY,CAAC,CAAC;IACvC,OAAO,KAAK,gBAAgB,KAAK,UAAU,SAAS,GAClD,OAAO,KAAK,gBAAgB,KAAK,OAAO;GAE5C;GAEA,MAAM,CAAC,CACJ,WAAW,GAAG,GAAG,CAAC,CAAC,CACnB,OAAM,aAAY;IACjB,QAAQ,MAAM,yBAAyB,QAAQ;IAC/C,GAAG,OAAO,QAAQ;GACpB,CAAC;EACL,OACE,GAAG,GAAG;CAEV;CAEA,MAAM,SAAS,QAcZ;EAGD,QAAQ,KACN,wGACF;EAEA,OAAO;GACL,MAAM,CAAC;GACP,OAAO;GACP,MAAM,QAAQ,SAAS,IAAI,IAAK,QAAQ,QAAQ;GAChD,SAAS,QAAQ,WAAW;GAC5B,SAAS;EACX;CACF;CAEA,MAAM,gBAAgB,EACpB,OAAO,QACP,UAAU,WACV,QAAQ,SACR,UAAU,WACV,SAAS,UACT,MACA,WAeC;EAGD,QAAQ,KACN,+GACF;EAEA,OAAO;GACL,MAAM,CAAC;GACP,OAAO;GACP,MAAM,SAAS,IAAI,IAAK,QAAQ;GAChC,SAAS,WAAW;GACpB,SAAS;EACX;CACF;CAGA,kBAA2C;EACzC,OAAO,CAAC,GAAG,KAAK,SAAS;CAC3B;CAEA,cAA2B;EACzB,KAAK,YAAY,CAAC;CACpB;CAEA,qBAAoC;EAClC,OAAO,KAAK;CACd;CAEA,mBAAkC;EAChC,OAAO,KAAK;CACd;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["LoggerTransport"],"sources":["../../src/http/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\n\ninterface RetryOptions {\n maxRetries?: number;\n retryDelay?: number;\n exponentialBackoff?: boolean;\n}\n\ninterface HttpTransportOptions {\n url: string;\n method?: 'POST' | 'PUT' | 'PATCH';\n headers?: Record<string, string>;\n batchSize?: number;\n flushInterval?: number;\n timeout?: number;\n retryOptions?: RetryOptions;\n maxBufferSize?: number;\n}\n\nclass HttpResponseError extends Error {\n constructor(\n readonly status: number,\n statusText: string,\n readonly retryAfterMs: number | undefined,\n ) {\n super(`HTTP ${status}: ${statusText}`);\n }\n}\n\n// Other 4xx responses mean the request itself is wrong and will fail the same way on every retry.\nfunction isRetryableStatus(status: number): boolean {\n return status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\n// Retry-After is either delta-seconds or an HTTP date (RFC 9110). Invalid values are ignored.\nfunction parseRetryAfter(headers: Headers | undefined): number | undefined {\n const value = headers?.get('retry-after')?.trim();\n if (!value) return undefined;\n if (/^\\d+$/.test(value)) return Number(value) * 1000;\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nexport class HttpTransport extends LoggerTransport {\n private url: string;\n private method: string;\n private headers: Record<string, string>;\n private batchSize: number;\n private flushInterval: number;\n private timeout: number;\n private retryOptions: Required<RetryOptions>;\n private logBuffer: BaseLogMessage[];\n private maxBufferSize: number;\n private droppedLogCount = 0;\n private flushPromise: Promise<void> | null = null;\n private flushRequested = false;\n private lastFlush: number;\n private flushIntervalId: NodeJS.Timeout;\n\n constructor(options: HttpTransportOptions) {\n super({ objectMode: true });\n\n if (!options.url) {\n throw new Error('HTTP URL is required');\n }\n\n this.url = options.url;\n this.method = options.method || 'POST';\n this.headers = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n this.batchSize = options.batchSize ?? 100;\n this.flushInterval = options.flushInterval || 10000;\n this.timeout = options.timeout || 30000;\n this.retryOptions = {\n maxRetries: options.retryOptions?.maxRetries ?? 3,\n retryDelay: options.retryOptions?.retryDelay ?? 1000,\n exponentialBackoff: options.retryOptions?.exponentialBackoff ?? true,\n };\n\n if (!Number.isInteger(this.batchSize) || this.batchSize < 1) {\n throw new Error('HttpTransport batchSize must be a positive integer');\n }\n\n const maxBufferSize = options.maxBufferSize ?? 10_000;\n if (!Number.isInteger(maxBufferSize) || maxBufferSize < 1) {\n throw new Error('HttpTransport maxBufferSize must be a positive integer');\n }\n this.maxBufferSize = Math.max(maxBufferSize, this.batchSize);\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => this.requestFlush(), this.flushInterval);\n this.updateIntervalRef();\n }\n\n // The interval only keeps the process alive while logs are waiting to be sent, so an idle transport\n // doesn't stop a script from exiting, but buffered logs still get delivered (or retried) first.\n // Web-standard runtimes return a numeric timer id without ref()/unref(), so those calls are optional.\n private updateIntervalRef(): void {\n if (this.logBuffer.length > 0 || this.flushPromise) {\n this.flushIntervalId.ref?.();\n } else {\n this.flushIntervalId.unref?.();\n }\n }\n\n private async makeHttpRequest(data: any): Promise<Response> {\n // Serialize once, outside the retry loop: serialization failures are not retryable,\n // and every retry must send the exact same payload.\n const body = JSON.stringify({ logs: data });\n return this.sendWithRetry(body);\n }\n\n private async sendWithRetry(body: string, retryCount = 0): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.url, {\n method: this.method,\n headers: this.headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new HttpResponseError(response.status, response.statusText, parseRetryAfter(response.headers));\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n\n const isPermanent = error instanceof HttpResponseError && !isRetryableStatus(error.status);\n if (!isPermanent && retryCount < this.retryOptions.maxRetries) {\n const backoff = this.retryOptions.exponentialBackoff\n ? this.retryOptions.retryDelay * Math.pow(2, retryCount)\n : this.retryOptions.retryDelay;\n // Honor the server's Retry-After, capped at the request timeout so a large value can't stall shutdown.\n const retryAfter = error instanceof HttpResponseError ? (error.retryAfterMs ?? 0) : 0;\n const delay = Math.max(backoff, Math.min(retryAfter, this.timeout));\n\n await new Promise(resolve => setTimeout(resolve, delay));\n return this.sendWithRetry(body, retryCount + 1);\n }\n\n throw error;\n }\n }\n\n private enforceBufferLimit(): void {\n const overflow = this.logBuffer.length - this.maxBufferSize;\n if (overflow <= 0) {\n return;\n }\n\n this.logBuffer.splice(0, overflow);\n if (this.droppedLogCount === 0) {\n console.warn(\n `HttpTransport: buffer exceeded maxBufferSize (${this.maxBufferSize}); dropping oldest logs. Use getDroppedLogCount() to track drops.`,\n );\n }\n this.droppedLogCount += overflow;\n }\n\n // Internal fire-and-forget flush. While a request is in flight this only records the request, so writes\n // during a slow or retrying request don't each attach another handler to the pending promise.\n private requestFlush(): void {\n if (this.flushPromise) {\n this.flushRequested = true;\n return;\n }\n this._flush().catch(err => {\n console.error('Error flushing logs to HTTP endpoint:', err);\n });\n }\n\n _flush(): Promise<void> {\n // Only one request in flight at a time, so an outage doesn't fan out into overlapping retry chains.\n if (this.flushPromise) {\n this.flushRequested = true;\n return this.flushPromise;\n }\n if (this.logBuffer.length === 0) {\n return Promise.resolve();\n }\n\n this.flushRequested = false;\n const flush = this.flushBatch().finally(() => {\n this.flushPromise = null;\n this.updateIntervalRef();\n });\n this.flushPromise = flush;\n // Flushes requested while this request was in flight only got this promise back, so send their logs now,\n // and keep draining full batches. On a transient failure, wait for the next interval instead of retrying\n // straight away. A permanently rejected batch was dropped, so the logs behind it can go out now.\n const continueDraining = () => {\n if (this.logBuffer.length >= this.batchSize || (this.flushRequested && this.logBuffer.length > 0)) {\n this.requestFlush();\n }\n };\n flush.then(continueDraining, error => {\n if (error instanceof HttpResponseError && !isRetryableStatus(error.status)) {\n continueDraining();\n }\n });\n return flush;\n }\n\n private async flushBatch(): Promise<void> {\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n\n try {\n await this.makeHttpRequest(logs);\n this.lastFlush = now;\n } catch (error) {\n // The endpoint rejected this batch outright, so resending it can't succeed and would block the logs behind it.\n if (error instanceof HttpResponseError && !isRetryableStatus(error.status)) {\n this.droppedLogCount += logs.length;\n console.warn(\n `HttpTransport: endpoint rejected a batch with HTTP ${error.status}; dropping ${logs.length} logs. Use getDroppedLogCount() to track drops.`,\n );\n throw error;\n }\n\n // On a transient error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n this.enforceBufferLimit();\n throw error;\n }\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n _transform(chunk: string, _enc: string, cb: Function): void {\n try {\n // Parse the log line if it's a string\n const parsed = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present, on a copy so caller-owned (possibly frozen) records stay untouched\n const log = parsed.time === undefined || parsed.time === null ? { ...parsed, time: Date.now() } : parsed;\n\n // Add to buffer\n this.logBuffer.push(log);\n this.enforceBufferLimit();\n this.updateIntervalRef();\n\n // Flush if buffer reaches batch size\n if (this.logBuffer.length >= this.batchSize) {\n this.requestFlush();\n }\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function): void {\n clearInterval(this.flushIntervalId);\n\n // Final drain. Wait out any in-flight request (ignoring its failure, since its logs are back in the buffer),\n // then keep sending until the buffer is empty. A failed request ends the drain instead of retrying forever.\n if (this.logBuffer.length > 0 || this.flushPromise) {\n const drain = async () => {\n await this.flushPromise?.catch(() => {});\n while (this.flushPromise || this.logBuffer.length > 0) {\n await (this.flushPromise ?? this._flush());\n }\n };\n\n drain()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogs: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: params?.page === 0 ? 1 : (params?.page ?? 1),\n perPage: params?.perPage ?? 100,\n hasMore: false,\n };\n }\n\n async listLogsByRunId({\n runId: _runId,\n fromDate: _fromDate,\n toDate: _toDate,\n logLevel: _logLevel,\n filters: _filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogsByRunId: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: page === 0 ? 1 : (page ?? 1),\n perPage: perPage ?? 100,\n hasMore: false,\n };\n }\n\n // Utility methods\n public getBufferedLogs(): BaseLogMessage[] {\n return [...this.logBuffer];\n }\n\n public clearBuffer(): void {\n this.logBuffer = [];\n this.updateIntervalRef();\n }\n\n public getDroppedLogCount(): number {\n return this.droppedLogCount;\n }\n\n public getLastFlushTime(): number {\n return this.lastFlush;\n }\n}\n"],"mappings":";;;AAoBA,IAAM,oBAAN,cAAgC,MAAM;CAEzB;CAEA;CAHX,YACE,QACA,YACA,cACA;EACA,MAAM,QAAQ,OAAO,IAAI,YAAY;EAJ5B,KAAA,SAAA;EAEA,KAAA,eAAA;CAGX;AACF;AAGA,SAAS,kBAAkB,QA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,SAAS,QAcZ;EAGD,QAAQ,KACN,wGACF;EAEA,OAAO;GACL,MAAM,CAAC;GACP,OAAO;GACP,MAAM,QAAQ,SAAS,IAAI,IAAK,QAAQ,QAAQ;GAChD,SAAS,QAAQ,WAAW;GAC5B,SAAS;EACX;CACF;CAEA,MAAM,gBAAgB,EACpB,OAAO,QACP,UAAU,WACV,QAAQ,SACR,UAAU,WACV,SAAS,UACT,MACA,WAeC;EAGD,QAAQ,KACN,+GACF;EAEA,OAAO;GACL,MAAM,CAAC;GACP,OAAO;GACP,MAAM,SAAS,IAAI,IAAK,QAAQ;GAChC,SAAS,WAAW;GACpB,SAAS;EACX;CACF;CAGA,kBAA2C;EACzC,OAAO,CAAC,GAAG,KAAK,SAAS;CAC3B;CAEA,cAA2B;EACzB,KAAK,YAAY,CAAC;EAClB,KAAK,kBAAkB;CACzB;CAEA,qBAAoC;EAClC,OAAO,KAAK;CACd;CAEA,mBAAkC;EAChC,OAAO,KAAK;CACd;AACF"}
@@ -31,6 +31,7 @@ export declare class HttpTransport extends LoggerTransport {
31
31
  private lastFlush;
32
32
  private flushIntervalId;
33
33
  constructor(options: HttpTransportOptions);
34
+ private updateIntervalRef;
34
35
  private makeHttpRequest;
35
36
  private sendWithRetry;
36
37
  private enforceBufferLimit;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/http/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpE,UAAU,YAAY;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,UAAU,oBAAoB;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,O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EAAE,SAAS,EACnB,OAAO,EAAE,QAAQ,EACjB,IAAI,EACJ,OAAO,GACR,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,IAAI,CAAC;QAChB,MAAM,CAAC,EAAE,IAAI,CAAC;QACd,QAAQ,CAAC,EAAE,QAAQ,CAAC;QACpB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC;QACV,IAAI,EAAE,cAAc,EAAE,CAAC;QACvB,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,OAAO,CAAC;KAClB,CAAC,CAcD;IAGM,eAAe,IAAI,cAAc,EAAE,CAEzC;IAEM,WAAW,IAAI,IAAI,CAGzB;IAEM,kBAAkB,IAAI,MAAM,CAElC;IAEM,gBAAgB,IAAI,MAAM,CAEhC;CACF"}
@@ -58,6 +58,11 @@ var HttpTransport = class extends LoggerTransport {
58
58
  this.logBuffer = [];
59
59
  this.lastFlush = Date.now();
60
60
  this.flushIntervalId = setInterval(() => this.requestFlush(), this.flushInterval);
61
+ this.updateIntervalRef();
62
+ }
63
+ updateIntervalRef() {
64
+ if (this.logBuffer.length > 0 || this.flushPromise) this.flushIntervalId.ref?.();
65
+ else this.flushIntervalId.unref?.();
61
66
  }
62
67
  async makeHttpRequest(data) {
63
68
  const body = JSON.stringify({ logs: data });
@@ -113,6 +118,7 @@ var HttpTransport = class extends LoggerTransport {
113
118
  this.flushRequested = false;
114
119
  const flush = this.flushBatch().finally(() => {
115
120
  this.flushPromise = null;
121
+ this.updateIntervalRef();
116
122
  });
117
123
  this.flushPromise = flush;
118
124
  const continueDraining = () => {
@@ -159,6 +165,7 @@ var HttpTransport = class extends LoggerTransport {
159
165
  } : parsed;
160
166
  this.logBuffer.push(log);
161
167
  this.enforceBufferLimit();
168
+ this.updateIntervalRef();
162
169
  if (this.logBuffer.length >= this.batchSize) this.requestFlush();
163
170
  cb(null, chunk);
164
171
  } catch (error) {
@@ -203,6 +210,7 @@ var HttpTransport = class extends LoggerTransport {
203
210
  }
204
211
  clearBuffer() {
205
212
  this.logBuffer = [];
213
+ this.updateIntervalRef();
206
214
  }
207
215
  getDroppedLogCount() {
208
216
  return this.droppedLogCount;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/http/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\n\ninterface RetryOptions {\n maxRetries?: number;\n retryDelay?: number;\n exponentialBackoff?: boolean;\n}\n\ninterface HttpTransportOptions {\n url: string;\n method?: 'POST' | 'PUT' | 'PATCH';\n headers?: Record<string, string>;\n batchSize?: number;\n flushInterval?: number;\n timeout?: number;\n retryOptions?: RetryOptions;\n maxBufferSize?: number;\n}\n\nclass HttpResponseError extends Error {\n constructor(\n readonly status: number,\n statusText: string,\n readonly retryAfterMs: number | undefined,\n ) {\n super(`HTTP ${status}: ${statusText}`);\n }\n}\n\n// Other 4xx responses mean the request itself is wrong and will fail the same way on every retry.\nfunction isRetryableStatus(status: number): boolean {\n return status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\n// Retry-After is either delta-seconds or an HTTP date (RFC 9110). Invalid values are ignored.\nfunction parseRetryAfter(headers: Headers | undefined): number | undefined {\n const value = headers?.get('retry-after')?.trim();\n if (!value) return undefined;\n if (/^\\d+$/.test(value)) return Number(value) * 1000;\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nexport class HttpTransport extends LoggerTransport {\n private url: string;\n private method: string;\n private headers: Record<string, string>;\n private batchSize: number;\n private flushInterval: number;\n private timeout: number;\n private retryOptions: Required<RetryOptions>;\n private logBuffer: BaseLogMessage[];\n private maxBufferSize: number;\n private droppedLogCount = 0;\n private flushPromise: Promise<void> | null = null;\n private flushRequested = false;\n private lastFlush: number;\n private flushIntervalId: NodeJS.Timeout;\n\n constructor(options: HttpTransportOptions) {\n super({ objectMode: true });\n\n if (!options.url) {\n throw new Error('HTTP URL is required');\n }\n\n this.url = options.url;\n this.method = options.method || 'POST';\n this.headers = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n this.batchSize = options.batchSize ?? 100;\n this.flushInterval = options.flushInterval || 10000;\n this.timeout = options.timeout || 30000;\n this.retryOptions = {\n maxRetries: options.retryOptions?.maxRetries ?? 3,\n retryDelay: options.retryOptions?.retryDelay ?? 1000,\n exponentialBackoff: options.retryOptions?.exponentialBackoff ?? true,\n };\n\n if (!Number.isInteger(this.batchSize) || this.batchSize < 1) {\n throw new Error('HttpTransport batchSize must be a positive integer');\n }\n\n const maxBufferSize = options.maxBufferSize ?? 10_000;\n if (!Number.isInteger(maxBufferSize) || maxBufferSize < 1) {\n throw new Error('HttpTransport maxBufferSize must be a positive integer');\n }\n this.maxBufferSize = Math.max(maxBufferSize, this.batchSize);\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => this.requestFlush(), this.flushInterval);\n }\n\n private async makeHttpRequest(data: any): Promise<Response> {\n // Serialize once, outside the retry loop: serialization failures are not retryable,\n // and every retry must send the exact same payload.\n const body = JSON.stringify({ logs: data });\n return this.sendWithRetry(body);\n }\n\n private async sendWithRetry(body: string, retryCount = 0): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.url, {\n method: this.method,\n headers: this.headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new HttpResponseError(response.status, response.statusText, parseRetryAfter(response.headers));\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n\n const isPermanent = error instanceof HttpResponseError && !isRetryableStatus(error.status);\n if (!isPermanent && retryCount < this.retryOptions.maxRetries) {\n const backoff = this.retryOptions.exponentialBackoff\n ? this.retryOptions.retryDelay * Math.pow(2, retryCount)\n : this.retryOptions.retryDelay;\n // Honor the server's Retry-After, capped at the request timeout so a large value can't stall shutdown.\n const retryAfter = error instanceof HttpResponseError ? (error.retryAfterMs ?? 0) : 0;\n const delay = Math.max(backoff, Math.min(retryAfter, this.timeout));\n\n await new Promise(resolve => setTimeout(resolve, delay));\n return this.sendWithRetry(body, retryCount + 1);\n }\n\n throw error;\n }\n }\n\n private enforceBufferLimit(): void {\n const overflow = this.logBuffer.length - this.maxBufferSize;\n if (overflow <= 0) {\n return;\n }\n\n this.logBuffer.splice(0, overflow);\n if (this.droppedLogCount === 0) {\n console.warn(\n `HttpTransport: buffer exceeded maxBufferSize (${this.maxBufferSize}); dropping oldest logs. Use getDroppedLogCount() to track drops.`,\n );\n }\n this.droppedLogCount += overflow;\n }\n\n // Internal fire-and-forget flush. While a request is in flight this only records the request, so writes\n // during a slow or retrying request don't each attach another handler to the pending promise.\n private requestFlush(): void {\n if (this.flushPromise) {\n this.flushRequested = true;\n return;\n }\n this._flush().catch(err => {\n console.error('Error flushing logs to HTTP endpoint:', err);\n });\n }\n\n _flush(): Promise<void> {\n // Only one request in flight at a time, so an outage doesn't fan out into overlapping retry chains.\n if (this.flushPromise) {\n this.flushRequested = true;\n return this.flushPromise;\n }\n if (this.logBuffer.length === 0) {\n return Promise.resolve();\n }\n\n this.flushRequested = false;\n const flush = this.flushBatch().finally(() => {\n this.flushPromise = null;\n });\n this.flushPromise = flush;\n // Flushes requested while this request was in flight only got this promise back, so send their logs now,\n // and keep draining full batches. On a transient failure, wait for the next interval instead of retrying\n // straight away. A permanently rejected batch was dropped, so the logs behind it can go out now.\n const continueDraining = () => {\n if (this.logBuffer.length >= this.batchSize || (this.flushRequested && this.logBuffer.length > 0)) {\n this.requestFlush();\n }\n };\n flush.then(continueDraining, error => {\n if (error instanceof HttpResponseError && !isRetryableStatus(error.status)) {\n continueDraining();\n }\n });\n return flush;\n }\n\n private async flushBatch(): Promise<void> {\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n\n try {\n await this.makeHttpRequest(logs);\n this.lastFlush = now;\n } catch (error) {\n // The endpoint rejected this batch outright, so resending it can't succeed and would block the logs behind it.\n if (error instanceof HttpResponseError && !isRetryableStatus(error.status)) {\n this.droppedLogCount += logs.length;\n console.warn(\n `HttpTransport: endpoint rejected a batch with HTTP ${error.status}; dropping ${logs.length} logs. Use getDroppedLogCount() to track drops.`,\n );\n throw error;\n }\n\n // On a transient error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n this.enforceBufferLimit();\n throw error;\n }\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n _transform(chunk: string, _enc: string, cb: Function): void {\n try {\n // Parse the log line if it's a string\n const parsed = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present, on a copy so caller-owned (possibly frozen) records stay untouched\n const log = parsed.time === undefined || parsed.time === null ? { ...parsed, time: Date.now() } : parsed;\n\n // Add to buffer\n this.logBuffer.push(log);\n this.enforceBufferLimit();\n\n // Flush if buffer reaches batch size\n if (this.logBuffer.length >= this.batchSize) {\n this.requestFlush();\n }\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function): void {\n clearInterval(this.flushIntervalId);\n\n // Final drain. Wait out any in-flight request (ignoring its failure, since its logs are back in the buffer),\n // then keep sending until the buffer is empty. A failed request ends the drain instead of retrying forever.\n if (this.logBuffer.length > 0 || this.flushPromise) {\n const drain = async () => {\n await this.flushPromise?.catch(() => {});\n while (this.flushPromise || this.logBuffer.length > 0) {\n await (this.flushPromise ?? this._flush());\n }\n };\n\n drain()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogs: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: params?.page === 0 ? 1 : (params?.page ?? 1),\n perPage: params?.perPage ?? 100,\n hasMore: false,\n };\n }\n\n async listLogsByRunId({\n runId: _runId,\n fromDate: _fromDate,\n toDate: _toDate,\n logLevel: _logLevel,\n filters: _filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogsByRunId: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: page === 0 ? 1 : (page ?? 1),\n perPage: perPage ?? 100,\n hasMore: false,\n };\n }\n\n // Utility methods\n public getBufferedLogs(): BaseLogMessage[] {\n return [...this.logBuffer];\n }\n\n public clearBuffer(): void {\n this.logBuffer = [];\n }\n\n public getDroppedLogCount(): number {\n return this.droppedLogCount;\n }\n\n public getLastFlushTime(): number {\n return this.lastFlush;\n }\n}\n"],"mappings":";;AAoBA,IAAM,oBAAN,cAAgC,MAAM;CAEzB;CAEA;CAHX,YACE,QACA,YACA,cACA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P,MAAM,QAAQ,SAAS,IAAI,IAAK,QAAQ,QAAQ;GAChD,SAAS,QAAQ,WAAW;GAC5B,SAAS;EACX;CACF;CAEA,MAAM,gBAAgB,EACpB,OAAO,QACP,UAAU,WACV,QAAQ,SACR,UAAU,WACV,SAAS,UACT,MACA,WAeC;EAGD,QAAQ,KACN,+GACF;EAEA,OAAO;GACL,MAAM,CAAC;GACP,OAAO;GACP,MAAM,SAAS,IAAI,IAAK,QAAQ;GAChC,SAAS,WAAW;GACpB,SAAS;EACX;CACF;CAGA,kBAA2C;EACzC,OAAO,CAAC,GAAG,KAAK,SAAS;CAC3B;CAEA,cAA2B;EACzB,KAAK,YAAY,CAAC;CACpB;CAEA,qBAAoC;EAClC,OAAO,KAAK;CACd;CAEA,mBAAkC;EAChC,OAAO,KAAK;CACd;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/http/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\n\ninterface RetryOptions {\n maxRetries?: number;\n retryDelay?: number;\n exponentialBackoff?: boolean;\n}\n\ninterface HttpTransportOptions {\n url: string;\n method?: 'POST' | 'PUT' | 'PATCH';\n headers?: Record<string, string>;\n batchSize?: number;\n flushInterval?: number;\n timeout?: number;\n retryOptions?: RetryOptions;\n maxBufferSize?: number;\n}\n\nclass HttpResponseError extends Error {\n constructor(\n readonly status: number,\n statusText: string,\n readonly retryAfterMs: number | undefined,\n ) {\n super(`HTTP ${status}: ${statusText}`);\n }\n}\n\n// Other 4xx responses mean the request itself is wrong and will fail the same way on every retry.\nfunction isRetryableStatus(status: number): boolean {\n return status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\n// Retry-After is either delta-seconds or an HTTP date (RFC 9110). Invalid values are ignored.\nfunction parseRetryAfter(headers: Headers | undefined): number | undefined {\n const value = headers?.get('retry-after')?.trim();\n if (!value) return undefined;\n if (/^\\d+$/.test(value)) return Number(value) * 1000;\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nexport class HttpTransport extends LoggerTransport {\n private url: string;\n private method: string;\n private headers: Record<string, string>;\n private batchSize: number;\n private flushInterval: number;\n private timeout: number;\n private retryOptions: Required<RetryOptions>;\n private logBuffer: BaseLogMessage[];\n private maxBufferSize: number;\n private droppedLogCount = 0;\n private flushPromise: Promise<void> | null = null;\n private flushRequested = false;\n private lastFlush: number;\n private flushIntervalId: NodeJS.Timeout;\n\n constructor(options: HttpTransportOptions) {\n super({ objectMode: true });\n\n if (!options.url) {\n throw new Error('HTTP URL is required');\n }\n\n this.url = options.url;\n this.method = options.method || 'POST';\n this.headers = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n this.batchSize = options.batchSize ?? 100;\n this.flushInterval = options.flushInterval || 10000;\n this.timeout = options.timeout || 30000;\n this.retryOptions = {\n maxRetries: options.retryOptions?.maxRetries ?? 3,\n retryDelay: options.retryOptions?.retryDelay ?? 1000,\n exponentialBackoff: options.retryOptions?.exponentialBackoff ?? true,\n };\n\n if (!Number.isInteger(this.batchSize) || this.batchSize < 1) {\n throw new Error('HttpTransport batchSize must be a positive integer');\n }\n\n const maxBufferSize = options.maxBufferSize ?? 10_000;\n if (!Number.isInteger(maxBufferSize) || maxBufferSize < 1) {\n throw new Error('HttpTransport maxBufferSize must be a positive integer');\n }\n this.maxBufferSize = Math.max(maxBufferSize, this.batchSize);\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => this.requestFlush(), this.flushInterval);\n this.updateIntervalRef();\n }\n\n // The interval only keeps the process alive while logs are waiting to be sent, so an idle transport\n // doesn't stop a script from exiting, but buffered logs still get delivered (or retried) first.\n // Web-standard runtimes return a numeric timer id without ref()/unref(), so those calls are optional.\n private updateIntervalRef(): void {\n if (this.logBuffer.length > 0 || this.flushPromise) {\n this.flushIntervalId.ref?.();\n } else {\n this.flushIntervalId.unref?.();\n }\n }\n\n private async makeHttpRequest(data: any): Promise<Response> {\n // Serialize once, outside the retry loop: serialization failures are not retryable,\n // and every retry must send the exact same payload.\n const body = JSON.stringify({ logs: data });\n return this.sendWithRetry(body);\n }\n\n private async sendWithRetry(body: string, retryCount = 0): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.url, {\n method: this.method,\n headers: this.headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new HttpResponseError(response.status, response.statusText, parseRetryAfter(response.headers));\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n\n const isPermanent = error instanceof HttpResponseError && !isRetryableStatus(error.status);\n if (!isPermanent && retryCount < this.retryOptions.maxRetries) {\n const backoff = this.retryOptions.exponentialBackoff\n ? this.retryOptions.retryDelay * Math.pow(2, retryCount)\n : this.retryOptions.retryDelay;\n // Honor the server's Retry-After, capped at the request timeout so a large value can't stall shutdown.\n const retryAfter = error instanceof HttpResponseError ? (error.retryAfterMs ?? 0) : 0;\n const delay = Math.max(backoff, Math.min(retryAfter, this.timeout));\n\n await new Promise(resolve => setTimeout(resolve, delay));\n return this.sendWithRetry(body, retryCount + 1);\n }\n\n throw error;\n }\n }\n\n private enforceBufferLimit(): void {\n const overflow = this.logBuffer.length - this.maxBufferSize;\n if (overflow <= 0) {\n return;\n }\n\n this.logBuffer.splice(0, overflow);\n if (this.droppedLogCount === 0) {\n console.warn(\n `HttpTransport: buffer exceeded maxBufferSize (${this.maxBufferSize}); dropping oldest logs. Use getDroppedLogCount() to track drops.`,\n );\n }\n this.droppedLogCount += overflow;\n }\n\n // Internal fire-and-forget flush. While a request is in flight this only records the request, so writes\n // during a slow or retrying request don't each attach another handler to the pending promise.\n private requestFlush(): void {\n if (this.flushPromise) {\n this.flushRequested = true;\n return;\n }\n this._flush().catch(err => {\n console.error('Error flushing logs to HTTP endpoint:', err);\n });\n }\n\n _flush(): Promise<void> {\n // Only one request in flight at a time, so an outage doesn't fan out into overlapping retry chains.\n if (this.flushPromise) {\n this.flushRequested = true;\n return this.flushPromise;\n }\n if (this.logBuffer.length === 0) {\n return Promise.resolve();\n }\n\n this.flushRequested = false;\n const flush = this.flushBatch().finally(() => {\n this.flushPromise = null;\n this.updateIntervalRef();\n });\n this.flushPromise = flush;\n // Flushes requested while this request was in flight only got this promise back, so send their logs now,\n // and keep draining full batches. On a transient failure, wait for the next interval instead of retrying\n // straight away. A permanently rejected batch was dropped, so the logs behind it can go out now.\n const continueDraining = () => {\n if (this.logBuffer.length >= this.batchSize || (this.flushRequested && this.logBuffer.length > 0)) {\n this.requestFlush();\n }\n };\n flush.then(continueDraining, error => {\n if (error instanceof HttpResponseError && !isRetryableStatus(error.status)) {\n continueDraining();\n }\n });\n return flush;\n }\n\n private async flushBatch(): Promise<void> {\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n\n try {\n await this.makeHttpRequest(logs);\n this.lastFlush = now;\n } catch (error) {\n // The endpoint rejected this batch outright, so resending it can't succeed and would block the logs behind it.\n if (error instanceof HttpResponseError && !isRetryableStatus(error.status)) {\n this.droppedLogCount += logs.length;\n console.warn(\n `HttpTransport: endpoint rejected a batch with HTTP ${error.status}; dropping ${logs.length} logs. Use getDroppedLogCount() to track drops.`,\n );\n throw error;\n }\n\n // On a transient error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n this.enforceBufferLimit();\n throw error;\n }\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n _transform(chunk: string, _enc: string, cb: Function): void {\n try {\n // Parse the log line if it's a string\n const parsed = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present, on a copy so caller-owned (possibly frozen) records stay untouched\n const log = parsed.time === undefined || parsed.time === null ? { ...parsed, time: Date.now() } : parsed;\n\n // Add to buffer\n this.logBuffer.push(log);\n this.enforceBufferLimit();\n this.updateIntervalRef();\n\n // Flush if buffer reaches batch size\n if (this.logBuffer.length >= this.batchSize) {\n this.requestFlush();\n }\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function): void {\n clearInterval(this.flushIntervalId);\n\n // Final drain. Wait out any in-flight request (ignoring its failure, since its logs are back in the buffer),\n // then keep sending until the buffer is empty. A failed request ends the drain instead of retrying forever.\n if (this.logBuffer.length > 0 || this.flushPromise) {\n const drain = async () => {\n await this.flushPromise?.catch(() => {});\n while (this.flushPromise || this.logBuffer.length > 0) {\n await (this.flushPromise ?? this._flush());\n }\n };\n\n drain()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogs: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: params?.page === 0 ? 1 : (params?.page ?? 1),\n perPage: params?.perPage ?? 100,\n hasMore: false,\n };\n }\n\n async listLogsByRunId({\n runId: _runId,\n fromDate: _fromDate,\n toDate: _toDate,\n logLevel: _logLevel,\n filters: _filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogsByRunId: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: page === 0 ? 1 : (page ?? 1),\n perPage: perPage ?? 100,\n hasMore: false,\n };\n }\n\n // Utility methods\n public getBufferedLogs(): BaseLogMessage[] {\n return [...this.logBuffer];\n }\n\n public clearBuffer(): void {\n this.logBuffer = [];\n this.updateIntervalRef();\n }\n\n public getDroppedLogCount(): number {\n return this.droppedLogCount;\n }\n\n public getLastFlushTime(): number {\n return this.lastFlush;\n }\n}\n"],"mappings":";;AAoBA,IAAM,oBAAN,cAAgC,MAAM;CAEzB;CAEA;CAHX,YACE,QACA,YACA,cACA;EACA,MAAM,QAAQ,OAAO,IAAI,YAAY;EAJ5B,KAAA,SAAA;EAEA,KAAA,eAAA;CAGX;AACF;AAGA,SAAS,kBAAkB,QAAyB;CAClD,OAAO,WAAW,OAAO,WAAW,OAAO,WAAW,OAAO,UAAU;AACzE;AAGA,SAAS,gBAAgB,SAAkD;CACzE,MAAM,QAAQ,SAAS,IAAI,aAAa,CAAC,EAAE,KAAK;CAChD,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,QAAQ,KAAK,KAAK,GAAG,OAAO,OAAO,KAAK,IAAI;CAChD,MAAM,OAAO,KAAK,MAAM,KAAK;CAC7B,OAAO,OAAO,MAAM,IAAI,IAAI,KAAA,IAAY,KAAK,IAAI,GAAG,OAAO,KAAK,IAAI,CAAC;AACvE;AAEA,IAAa,gBAAb,cAAmC,gBAAgB;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,kBAA0B;CAC1B,eAA6C;CAC7C,iBAAyB;CACzB;CACA;CAEA,YAAY,SAA+B;EACzC,MAAM,EAAE,YAAY,KAAK,CAAC;EAE1B,IAAI,CAAC,QAAQ,KACX,MAAM,IAAI,MAAM,sBAAsB;EAG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7 +16,7 @@ var __copyProps = (to, from, except, desc) => {
16
16
  }
17
17
  return to;
18
18
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["MastraLogger","#adapterContextRef","LogLevel","#export"],"sources":["../src/pino.ts"],"sourcesContent":["import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger';\nimport { LogLevel, MastraLogger, buildLogRecordData, exportTrackedException } from '@mastra/core/logger';\nimport pino from 'pino';\nimport pretty from 'pino-pretty';\n\ntype TransportMap = Record<string, LoggerTransport>;\n\nexport type { LogLevel } from '@mastra/core/logger';\n\nexport interface PinoLoggerOptions<CustomLevels extends string = never> {\n name?: string;\n level?: LogLevel;\n transports?: TransportMap;\n overrideDefaultTransports?: boolean;\n formatters?: pino.LoggerOptions['formatters'];\n redact?: pino.LoggerOptions['redact'];\n mixin?: pino.MixinFn<CustomLevels>;\n customLevels?: { [level in CustomLevels]: number };\n /**\n * When false, disables pino-pretty and outputs raw JSON.\n * Useful when sending logs to aggregators like Datadog,\n * Loki, or CloudWatch that expect single-line JSON per entry.\n * @default true\n */\n prettyPrint?: boolean;\n /**\n * Override the key used for the log message.\n * Defaults to Pino's built-in 'msg' key.\n * Set to 'message' for compatibility with Google Cloud Logging,\n * Elastic Common Schema (ECS), Datadog, and AWS CloudWatch.\n * @example 'message'\n */\n messageKey?: string;\n /**\n * Custom pino serializers, merged over Mastra's defaults.\n * By default the `error` key is serialized with pino's standard error\n * serializer (alongside pino's built-in `err`), so that\n * `logger.warn('...', { error })` records the message and stack rather\n * than an empty object.\n */\n serializers?: pino.LoggerOptions['serializers'];\n}\n\ninterface PinoLoggerInternalOptions<CustomLevels extends string = never> extends PinoLoggerOptions<CustomLevels> {\n /** @internal Used internally for child loggers */\n _logger?: pino.Logger<CustomLevels>;\n /** @internal Shared adapter-context ref so root and children correlate together */\n _adapterContextRef?: { current?: LoggerAdapterContext };\n}\n\n/**\n * Provides Pino-backed logging for Mastra applications.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n * import { PinoLogger } from '@mastra/loggers';\n *\n * const mastra = new Mastra({\n * logger: new PinoLogger({ name: 'my-app', level: 'info' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/loggers/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Pino logger documentation](https://mastra.ai/reference/logging/pino-logger)\n * if packaged docs are unavailable.\n */\nexport class PinoLogger<CustomLevels extends string = never> extends MastraLogger {\n protected logger: pino.Logger<CustomLevels>;\n // Mutable ref shared with child loggers: the root's mixin (which children's\n // pino instances inherit) reads through this ref, so attaching observability\n // to a child (e.g. `new Mastra({ logger: base.child({...}) })`) correlates\n // the records it actually logs through.\n #adapterContextRef: { current?: LoggerAdapterContext };\n\n constructor(options: PinoLoggerOptions<CustomLevels> = {}) {\n super(options);\n\n const internalOptions = options as PinoLoggerInternalOptions<CustomLevels>;\n this.#adapterContextRef = internalOptions._adapterContextRef ?? {};\n\n // If an existing pino logger is provided (for child loggers), use it directly\n if (internalOptions._logger) {\n this.logger = internalOptions._logger;\n return;\n }\n\n // Compose the user mixin with trace correlation. Pino mixins run\n // synchronously on every log call, so the trace fields land in the\n // native record before serialization — for ALL destinations (stdout,\n // transports, files). Trace fields win on key conflicts.\n const userMixin = options.mixin;\n const correlationMixin: pino.MixinFn<CustomLevels> = (mergeObject, level, logger) => {\n const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.correlation) return userFields;\n try {\n return { ...userFields, ...(ctx.resolveTraceFields() ?? {}) };\n } catch {\n return userFields;\n }\n };\n\n const shouldPrettyPrint = options.prettyPrint ?? true;\n let prettyStream: ReturnType<typeof pretty> | undefined = undefined;\n if (!options.overrideDefaultTransports && shouldPrettyPrint) {\n prettyStream = pretty({\n colorize: true,\n levelFirst: true,\n ignore: 'pid,hostname,component',\n colorizeObjects: true,\n translateTime: 'SYS:standard',\n singleLine: false,\n });\n }\n\n const transportsAry = [...this.getTransports().entries()];\n this.logger = pino(\n {\n name: options.name || 'app',\n level: options.level || LogLevel.INFO,\n formatters: options.formatters,\n redact: options.redact,\n mixin: correlationMixin,\n customLevels: options.customLevels,\n messageKey: options.messageKey ?? 'msg',\n // Pino applies its error serializer only to `errorKey` (default `err`).\n // Mastra logs errors as `{ error }` throughout, and an Error's `message`\n // and `stack` are non-enumerable, so without this they serialize to `{}`.\n serializers: { error: pino.stdSerializers.err, ...options.serializers },\n },\n options.overrideDefaultTransports\n ? options?.transports?.default\n : transportsAry.length === 0\n ? prettyStream // undefined when prettyPrint:false → pino native JSON\n : pino.multistream([\n ...transportsAry.map(([, transport]) => ({\n stream: transport,\n level: options.level || LogLevel.INFO,\n })),\n ...(prettyStream // only add prettyStream to multistream if it exists\n ? [{ stream: prettyStream, level: options.level || LogLevel.INFO }]\n : []),\n ]),\n );\n }\n\n /**\n * Creates a child logger with additional bound context.\n * All logs from the child logger will include the bound context.\n *\n * @param bindings - Key-value pairs to include in all logs from this child logger\n * @returns A new PinoLogger instance with the bound context\n *\n * @example\n * ```typescript\n * const baseLogger = new PinoLogger({ name: 'MyApp' });\n *\n * // Create module-scoped logger\n * const serviceLogger = baseLogger.child({ module: 'UserService' });\n * serviceLogger.info('User created', { userId: '123' });\n * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }\n *\n * // Create request-scoped logger\n * const requestLogger = baseLogger.child({ requestId: req.id });\n * requestLogger.error('Request failed', { err: error });\n * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }\n * ```\n */\n child(bindings: Record<string, unknown>): PinoLogger<CustomLevels> {\n const childPino = this.logger.child(bindings);\n const childOptions: PinoLoggerInternalOptions<CustomLevels> = {\n name: this.name,\n level: this.level,\n transports: Object.fromEntries(this.transports),\n _logger: childPino,\n _adapterContextRef: this.#adapterContextRef,\n };\n return new PinoLogger(childOptions);\n }\n\n /**\n * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables\n * native trace correlation (trace_id/span_id merged into the pino record\n * via mixin, for every destination) and observability export derived from\n * the same record. Called by Mastra during setup.\n */\n __attachObservability(ctx: LoggerAdapterContext): void {\n // Shared ref: attaching to a child also enables correlation on the root\n // mixin the child's records flow through (and vice versa).\n this.#adapterContextRef.current = ctx;\n }\n\n /**\n * The adapter context lives on the ref cell shared by the whole\n * root/child family, so re-attach detection (multi-Mastra warning) must\n * key on that cell — attaching to a child re-targets the root too.\n */\n __observabilityAttachmentKey(): object {\n return this.#adapterContextRef;\n }\n\n /**\n * Export the record derived from the same native call to observability.\n * Runs regardless of pino's level filter and never throws into the caller.\n */\n #export(level: 'debug' | 'info' | 'warn' | 'error', message: string, args: Record<string, any>): void {\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.export) return;\n try {\n // An Error passed as the args value often has no enumerable keys but\n // must still be exported (serialized by buildLogRecordData).\n const hasPayload = args instanceof Error || Object.keys(args).length > 0;\n // Trace identity travels on ExportedLog.traceId/spanId (the sink is\n // span-correlated); data stays reserved for the user payload. The mixin\n // still injects trace fields into the native pino record for stdout.\n ctx.getLogSink()?.[level](message, buildLogRecordData(hasPayload ? [args] : []));\n } catch {\n // Never let observability export break the primary logger\n }\n }\n\n debug(message: string, args: Record<string, any> = {}): void {\n this.logger.debug(args, message);\n this.#export('debug', message, args);\n }\n\n info(message: string, args: Record<string, any> = {}): void {\n this.logger.info(args, message);\n this.#export('info', message, args);\n }\n\n warn(message: string, args: Record<string, any> = {}): void {\n this.logger.warn(args, message);\n this.#export('warn', message, args);\n }\n\n error(message: string, args: Record<string, any> = {}): void {\n this.logger.error(args, message);\n this.#export('error', message, args);\n }\n\n override trackException(error: Error, metadata?: Record<string, unknown>): void {\n exportTrackedException(this.#adapterContextRef.current, error, metadata);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,aAAb,MAAa,mBAAwDA,oBAAAA,aAAa;CAChF;CAKA;CAEA,YAAY,UAA2C,CAAC,GAAG;EACzD,MAAM,OAAO;EAEb,MAAM,kBAAkB;EACxB,KAAKC,qBAAqB,gBAAgB,sBAAsB,CAAC;EAGjE,IAAI,gBAAgB,SAAS;GAC3B,KAAK,SAAS,gBAAgB;GAC9B;EACF;EAMA,MAAM,YAAY,QAAQ;EAC1B,MAAM,oBAAgD,aAAa,OAAO,WAAW;GACnF,MAAM,aAAa,YAAY,UAAU,aAAa,OAAO,MAAM,IAAI,CAAC;GACxE,MAAM,MAAM,KAAKA,mBAAmB;GACpC,IAAI,CAAC,KAAK,QAAQ,aAAa,OAAO;GACtC,IAAI;IACF,OAAO;KAAE,GAAG;KAAY,GAAI,IAAI,mBAAmB,KAAK,CAAC;IAAG;GAC9D,QAAQ;IACN,OAAO;GACT;EACF;EAEA,MAAM,oBAAoB,QAAQ,eAAe;EACjD,IAAI,eAAsD,KAAA;EAC1D,IAAI,CAAC,QAAQ,6BAA6B,mBACxC,gBAAA,GAAA,YAAA,QAAA,CAAsB;GACpB,UAAU;GACV,YAAY;GACZ,QAAQ;GACR,iBAAiB;GACjB,eAAe;GACf,YAAY;EACd,CAAC;EAGH,MAAM,gBAAgB,CAAC,GAAG,KAAK,cAAc,CAAC,CAAC,QAAQ,CAAC;EACxD,KAAK,UAAA,GAAA,KAAA,QAAA,CACH;GACE,MAAM,QAAQ,QAAQ;GACtB,OAAO,QAAQ,SAASC,oBAAAA,SAAS;GACjC,YAAY,QAAQ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C/B,KAAKE,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAKA,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAKA,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAKA,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,eAAwB,OAAc,UAA0C;EAC9E,CAAA,GAAA,oBAAA,uBAAA,CAAuB,KAAKF,mBAAmB,SAAS,OAAO,QAAQ;CACzE;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["MastraLogger","pretty","LogLevel","buildLogRecordData"],"sources":["../src/pino.ts"],"sourcesContent":["import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger';\nimport { LogLevel, MastraLogger, buildLogRecordData, exportTrackedException } from '@mastra/core/logger';\nimport pino from 'pino';\nimport pretty from 'pino-pretty';\n\ntype TransportMap = Record<string, LoggerTransport>;\n\nexport type { LogLevel } from '@mastra/core/logger';\n\nexport interface PinoLoggerOptions<CustomLevels extends string = never> {\n name?: string;\n level?: LogLevel;\n transports?: TransportMap;\n overrideDefaultTransports?: boolean;\n formatters?: pino.LoggerOptions['formatters'];\n redact?: pino.LoggerOptions['redact'];\n mixin?: pino.MixinFn<CustomLevels>;\n customLevels?: { [level in CustomLevels]: number };\n /**\n * When false, disables pino-pretty and outputs raw JSON.\n * Useful when sending logs to aggregators like Datadog,\n * Loki, or CloudWatch that expect single-line JSON per entry.\n * @default true\n */\n prettyPrint?: boolean;\n /**\n * Override the key used for the log message.\n * Defaults to Pino's built-in 'msg' key.\n * Set to 'message' for compatibility with Google Cloud Logging,\n * Elastic Common Schema (ECS), Datadog, and AWS CloudWatch.\n * @example 'message'\n */\n messageKey?: string;\n /**\n * Custom pino serializers, merged over Mastra's defaults.\n * By default the `error` key is serialized with pino's standard error\n * serializer (alongside pino's built-in `err`), so that\n * `logger.warn('...', { error })` records the message and stack rather\n * than an empty object.\n */\n serializers?: pino.LoggerOptions['serializers'];\n}\n\ninterface PinoLoggerInternalOptions<CustomLevels extends string = never> extends PinoLoggerOptions<CustomLevels> {\n /** @internal Used internally for child loggers */\n _logger?: pino.Logger<CustomLevels>;\n /** @internal Shared adapter-context ref so root and children correlate together */\n _adapterContextRef?: { current?: LoggerAdapterContext };\n}\n\n/**\n * Provides Pino-backed logging for Mastra applications.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n * import { PinoLogger } from '@mastra/loggers';\n *\n * const mastra = new Mastra({\n * logger: new PinoLogger({ name: 'my-app', level: 'info' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/loggers/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Pino logger documentation](https://mastra.ai/reference/logging/pino-logger)\n * if packaged docs are unavailable.\n */\nexport class PinoLogger<CustomLevels extends string = never> extends MastraLogger {\n protected logger: pino.Logger<CustomLevels>;\n // Mutable ref shared with child loggers: the root's mixin (which children's\n // pino instances inherit) reads through this ref, so attaching observability\n // to a child (e.g. `new Mastra({ logger: base.child({...}) })`) correlates\n // the records it actually logs through.\n #adapterContextRef: { current?: LoggerAdapterContext };\n\n constructor(options: PinoLoggerOptions<CustomLevels> = {}) {\n super(options);\n\n const internalOptions = options as PinoLoggerInternalOptions<CustomLevels>;\n this.#adapterContextRef = internalOptions._adapterContextRef ?? {};\n\n // If an existing pino logger is provided (for child loggers), use it directly\n if (internalOptions._logger) {\n this.logger = internalOptions._logger;\n return;\n }\n\n // Compose the user mixin with trace correlation. Pino mixins run\n // synchronously on every log call, so the trace fields land in the\n // native record before serialization — for ALL destinations (stdout,\n // transports, files). Trace fields win on key conflicts.\n const userMixin = options.mixin;\n const correlationMixin: pino.MixinFn<CustomLevels> = (mergeObject, level, logger) => {\n const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.correlation) return userFields;\n try {\n return { ...userFields, ...(ctx.resolveTraceFields() ?? {}) };\n } catch {\n return userFields;\n }\n };\n\n const shouldPrettyPrint = options.prettyPrint ?? true;\n let prettyStream: ReturnType<typeof pretty> | undefined = undefined;\n if (!options.overrideDefaultTransports && shouldPrettyPrint) {\n prettyStream = pretty({\n colorize: true,\n levelFirst: true,\n ignore: 'pid,hostname,component',\n colorizeObjects: true,\n translateTime: 'SYS:standard',\n singleLine: false,\n });\n }\n\n const transportsAry = [...this.getTransports().entries()];\n this.logger = pino(\n {\n name: options.name || 'app',\n level: options.level || LogLevel.INFO,\n formatters: options.formatters,\n redact: options.redact,\n mixin: correlationMixin,\n customLevels: options.customLevels,\n messageKey: options.messageKey ?? 'msg',\n // Pino applies its error serializer only to `errorKey` (default `err`).\n // Mastra logs errors as `{ error }` throughout, and an Error's `message`\n // and `stack` are non-enumerable, so without this they serialize to `{}`.\n serializers: { error: pino.stdSerializers.err, ...options.serializers },\n },\n options.overrideDefaultTransports\n ? options?.transports?.default\n : transportsAry.length === 0\n ? prettyStream // undefined when prettyPrint:false → pino native JSON\n : pino.multistream([\n ...transportsAry.map(([, transport]) => ({\n stream: transport,\n level: options.level || LogLevel.INFO,\n })),\n ...(prettyStream // only add prettyStream to multistream if it exists\n ? [{ stream: prettyStream, level: options.level || LogLevel.INFO }]\n : []),\n ]),\n );\n }\n\n /**\n * Creates a child logger with additional bound context.\n * All logs from the child logger will include the bound context.\n *\n * @param bindings - Key-value pairs to include in all logs from this child logger\n * @returns A new PinoLogger instance with the bound context\n *\n * @example\n * ```typescript\n * const baseLogger = new PinoLogger({ name: 'MyApp' });\n *\n * // Create module-scoped logger\n * const serviceLogger = baseLogger.child({ module: 'UserService' });\n * serviceLogger.info('User created', { userId: '123' });\n * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }\n *\n * // Create request-scoped logger\n * const requestLogger = baseLogger.child({ requestId: req.id });\n * requestLogger.error('Request failed', { err: error });\n * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }\n * ```\n */\n child(bindings: Record<string, unknown>): PinoLogger<CustomLevels> {\n const childPino = this.logger.child(bindings);\n const childOptions: PinoLoggerInternalOptions<CustomLevels> = {\n name: this.name,\n level: this.level,\n transports: Object.fromEntries(this.transports),\n _logger: childPino,\n _adapterContextRef: this.#adapterContextRef,\n };\n return new PinoLogger(childOptions);\n }\n\n /**\n * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables\n * native trace correlation (trace_id/span_id merged into the pino record\n * via mixin, for every destination) and observability export derived from\n * the same record. Called by Mastra during setup.\n */\n __attachObservability(ctx: LoggerAdapterContext): void {\n // Shared ref: attaching to a child also enables correlation on the root\n // mixin the child's records flow through (and vice versa).\n this.#adapterContextRef.current = ctx;\n }\n\n /**\n * The adapter context lives on the ref cell shared by the whole\n * root/child family, so re-attach detection (multi-Mastra warning) must\n * key on that cell — attaching to a child re-targets the root too.\n */\n __observabilityAttachmentKey(): object {\n return this.#adapterContextRef;\n }\n\n /**\n * Export the record derived from the same native call to observability.\n * Runs regardless of pino's level filter and never throws into the caller.\n */\n #export(level: 'debug' | 'info' | 'warn' | 'error', message: string, args: Record<string, any>): void {\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.export) return;\n try {\n // An Error passed as the args value often has no enumerable keys but\n // must still be exported (serialized by buildLogRecordData).\n const hasPayload = args instanceof Error || Object.keys(args).length > 0;\n // Trace identity travels on ExportedLog.traceId/spanId (the sink is\n // span-correlated); data stays reserved for the user payload. The mixin\n // still injects trace fields into the native pino record for stdout.\n ctx.getLogSink()?.[level](message, buildLogRecordData(hasPayload ? [args] : []));\n } catch {\n // Never let observability export break the primary logger\n }\n }\n\n debug(message: string, args: Record<string, any> = {}): void {\n this.logger.debug(args, message);\n this.#export('debug', message, args);\n }\n\n info(message: string, args: Record<string, any> = {}): void {\n this.logger.info(args, message);\n this.#export('info', message, args);\n }\n\n warn(message: string, args: Record<string, any> = {}): void {\n this.logger.warn(args, message);\n this.#export('warn', message, args);\n }\n\n error(message: string, args: Record<string, any> = {}): void {\n this.logger.error(args, message);\n this.#export('error', message, args);\n }\n\n override trackException(error: Error, metadata?: Record<string, unknown>): void {\n exportTrackedException(this.#adapterContextRef.current, error, metadata);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,aAAb,MAAa,mBAAwDA,oBAAAA,aAAa;CAChF;CAKA;CAEA,YAAY,UAA2C,CAAC,GAAG;EACzD,MAAM,OAAO;EAEb,MAAM,kBAAkB;EACxB,KAAK,qBAAqB,gBAAgB,sBAAsB,CAAC;EAGjE,IAAI,gBAAgB,SAAS;GAC3B,KAAK,SAAS,gBAAgB;GAC9B;EACF;EAMA,MAAM,YAAY,QAAQ;EAC1B,MAAM,oBAAgD,aAAa,OAAO,WAAW;GACnF,MAAM,aAAa,YAAY,UAAU,aAAa,OAAO,MAAM,IAAI,CAAC;GACxE,MAAM,MAAM,KAAK,mBAAmB;GACpC,IAAI,CAAC,KAAK,QAAQ,aAAa,OAAO;GACtC,IAAI;IACF,OAAO;KAAE,GAAG;KAAY,GAAI,IAAI,mBAAmB,KAAK,CAAC;IAAG;GAC9D,QAAQ;IACN,OAAO;GACT;EACF;EAEA,MAAM,oBAAoB,QAAQ,eAAe;EACjD,IAAI,eAAsD,KAAA;EAC1D,IAAI,CAAC,QAAQ,6BAA6B,mBACxC,gBAAA,GAAeC,YAAAA,QAAAA,CAAO;GACpB,UAAU;GACV,YAAY;GACZ,QAAQ;GACR,iBAAiB;GACjB,eAAe;GACf,YAAY;EACd,CAAC;EAGH,MAAM,gBAAgB,CAAC,G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AAA,mBAAAA,CAAmB,aAAa,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;EACjF,QAAQ,CAER;CACF;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAK,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAK,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAK,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAK,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,eAAwB,OAAc,UAA0C;EAC9E,CAAA,GAAA,oBAAA,uBAAA,CAAuB,KAAK,mBAAmB,SAAS,OAAO,QAAQ;CACzE;AACF"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#adapterContextRef","#export"],"sources":["../src/pino.ts"],"sourcesContent":["import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger';\nimport { LogLevel, MastraLogger, buildLogRecordData, exportTrackedException } from '@mastra/core/logger';\nimport pino from 'pino';\nimport pretty from 'pino-pretty';\n\ntype TransportMap = Record<string, LoggerTransport>;\n\nexport type { LogLevel } from '@mastra/core/logger';\n\nexport interface PinoLoggerOptions<CustomLevels extends string = never> {\n name?: string;\n level?: LogLevel;\n transports?: TransportMap;\n overrideDefaultTransports?: boolean;\n formatters?: pino.LoggerOptions['formatters'];\n redact?: pino.LoggerOptions['redact'];\n mixin?: pino.MixinFn<CustomLevels>;\n customLevels?: { [level in CustomLevels]: number };\n /**\n * When false, disables pino-pretty and outputs raw JSON.\n * Useful when sending logs to aggregators like Datadog,\n * Loki, or CloudWatch that expect single-line JSON per entry.\n * @default true\n */\n prettyPrint?: boolean;\n /**\n * Override the key used for the log message.\n * Defaults to Pino's built-in 'msg' key.\n * Set to 'message' for compatibility with Google Cloud Logging,\n * Elastic Common Schema (ECS), Datadog, and AWS CloudWatch.\n * @example 'message'\n */\n messageKey?: string;\n /**\n * Custom pino serializers, merged over Mastra's defaults.\n * By default the `error` key is serialized with pino's standard error\n * serializer (alongside pino's built-in `err`), so that\n * `logger.warn('...', { error })` records the message and stack rather\n * than an empty object.\n */\n serializers?: pino.LoggerOptions['serializers'];\n}\n\ninterface PinoLoggerInternalOptions<CustomLevels extends string = never> extends PinoLoggerOptions<CustomLevels> {\n /** @internal Used internally for child loggers */\n _logger?: pino.Logger<CustomLevels>;\n /** @internal Shared adapter-context ref so root and children correlate together */\n _adapterContextRef?: { current?: LoggerAdapterContext };\n}\n\n/**\n * Provides Pino-backed logging for Mastra applications.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n * import { PinoLogger } from '@mastra/loggers';\n *\n * const mastra = new Mastra({\n * logger: new PinoLogger({ name: 'my-app', level: 'info' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/loggers/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Pino logger documentation](https://mastra.ai/reference/logging/pino-logger)\n * if packaged docs are unavailable.\n */\nexport class PinoLogger<CustomLevels extends string = never> extends MastraLogger {\n protected logger: pino.Logger<CustomLevels>;\n // Mutable ref shared with child loggers: the root's mixin (which children's\n // pino instances inherit) reads through this ref, so attaching observability\n // to a child (e.g. `new Mastra({ logger: base.child({...}) })`) correlates\n // the records it actually logs through.\n #adapterContextRef: { current?: LoggerAdapterContext };\n\n constructor(options: PinoLoggerOptions<CustomLevels> = {}) {\n super(options);\n\n const internalOptions = options as PinoLoggerInternalOptions<CustomLevels>;\n this.#adapterContextRef = internalOptions._adapterContextRef ?? {};\n\n // If an existing pino logger is provided (for child loggers), use it directly\n if (internalOptions._logger) {\n this.logger = internalOptions._logger;\n return;\n }\n\n // Compose the user mixin with trace correlation. Pino mixins run\n // synchronously on every log call, so the trace fields land in the\n // native record before serialization — for ALL destinations (stdout,\n // transports, files). Trace fields win on key conflicts.\n const userMixin = options.mixin;\n const correlationMixin: pino.MixinFn<CustomLevels> = (mergeObject, level, logger) => {\n const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.correlation) return userFields;\n try {\n return { ...userFields, ...(ctx.resolveTraceFields() ?? {}) };\n } catch {\n return userFields;\n }\n };\n\n const shouldPrettyPrint = options.prettyPrint ?? true;\n let prettyStream: ReturnType<typeof pretty> | undefined = undefined;\n if (!options.overrideDefaultTransports && shouldPrettyPrint) {\n prettyStream = pretty({\n colorize: true,\n levelFirst: true,\n ignore: 'pid,hostname,component',\n colorizeObjects: true,\n translateTime: 'SYS:standard',\n singleLine: false,\n });\n }\n\n const transportsAry = [...this.getTransports().entries()];\n this.logger = pino(\n {\n name: options.name || 'app',\n level: options.level || LogLevel.INFO,\n formatters: options.formatters,\n redact: options.redact,\n mixin: correlationMixin,\n customLevels: options.customLevels,\n messageKey: options.messageKey ?? 'msg',\n // Pino applies its error serializer only to `errorKey` (default `err`).\n // Mastra logs errors as `{ error }` throughout, and an Error's `message`\n // and `stack` are non-enumerable, so without this they serialize to `{}`.\n serializers: { error: pino.stdSerializers.err, ...options.serializers },\n },\n options.overrideDefaultTransports\n ? options?.transports?.default\n : transportsAry.length === 0\n ? prettyStream // undefined when prettyPrint:false → pino native JSON\n : pino.multistream([\n ...transportsAry.map(([, transport]) => ({\n stream: transport,\n level: options.level || LogLevel.INFO,\n })),\n ...(prettyStream // only add prettyStream to multistream if it exists\n ? [{ stream: prettyStream, level: options.level || LogLevel.INFO }]\n : []),\n ]),\n );\n }\n\n /**\n * Creates a child logger with additional bound context.\n * All logs from the child logger will include the bound context.\n *\n * @param bindings - Key-value pairs to include in all logs from this child logger\n * @returns A new PinoLogger instance with the bound context\n *\n * @example\n * ```typescript\n * const baseLogger = new PinoLogger({ name: 'MyApp' });\n *\n * // Create module-scoped logger\n * const serviceLogger = baseLogger.child({ module: 'UserService' });\n * serviceLogger.info('User created', { userId: '123' });\n * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }\n *\n * // Create request-scoped logger\n * const requestLogger = baseLogger.child({ requestId: req.id });\n * requestLogger.error('Request failed', { err: error });\n * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }\n * ```\n */\n child(bindings: Record<string, unknown>): PinoLogger<CustomLevels> {\n const childPino = this.logger.child(bindings);\n const childOptions: PinoLoggerInternalOptions<CustomLevels> = {\n name: this.name,\n level: this.level,\n transports: Object.fromEntries(this.transports),\n _logger: childPino,\n _adapterContextRef: this.#adapterContextRef,\n };\n return new PinoLogger(childOptions);\n }\n\n /**\n * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables\n * native trace correlation (trace_id/span_id merged into the pino record\n * via mixin, for every destination) and observability export derived from\n * the same record. Called by Mastra during setup.\n */\n __attachObservability(ctx: LoggerAdapterContext): void {\n // Shared ref: attaching to a child also enables correlation on the root\n // mixin the child's records flow through (and vice versa).\n this.#adapterContextRef.current = ctx;\n }\n\n /**\n * The adapter context lives on the ref cell shared by the whole\n * root/child family, so re-attach detection (multi-Mastra warning) must\n * key on that cell — attaching to a child re-targets the root too.\n */\n __observabilityAttachmentKey(): object {\n return this.#adapterContextRef;\n }\n\n /**\n * Export the record derived from the same native call to observability.\n * Runs regardless of pino's level filter and never throws into the caller.\n */\n #export(level: 'debug' | 'info' | 'warn' | 'error', message: string, args: Record<string, any>): void {\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.export) return;\n try {\n // An Error passed as the args value often has no enumerable keys but\n // must still be exported (serialized by buildLogRecordData).\n const hasPayload = args instanceof Error || Object.keys(args).length > 0;\n // Trace identity travels on ExportedLog.traceId/spanId (the sink is\n // span-correlated); data stays reserved for the user payload. The mixin\n // still injects trace fields into the native pino record for stdout.\n ctx.getLogSink()?.[level](message, buildLogRecordData(hasPayload ? [args] : []));\n } catch {\n // Never let observability export break the primary logger\n }\n }\n\n debug(message: string, args: Record<string, any> = {}): void {\n this.logger.debug(args, message);\n this.#export('debug', message, args);\n }\n\n info(message: string, args: Record<string, any> = {}): void {\n this.logger.info(args, message);\n this.#export('info', message, args);\n }\n\n warn(message: string, args: Record<string, any> = {}): void {\n this.logger.warn(args, message);\n this.#export('warn', message, args);\n }\n\n error(message: string, args: Record<string, any> = {}): void {\n this.logger.error(args, message);\n this.#export('error', message, args);\n }\n\n override trackException(error: Error, metadata?: Record<string, unknown>): void {\n exportTrackedException(this.#adapterContextRef.current, error, metadata);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,aAAb,MAAa,mBAAwD,aAAa;CAChF;CAKA;CAEA,YAAY,UAA2C,CAAC,GAAG;EACzD,MAAM,OAAO;EAEb,MAAM,kBAAkB;EACxB,KAAKA,qBAAqB,gBAAgB,sBAAsB,CAAC;EAGjE,IAAI,gBAAgB,SAAS;GAC3B,KAAK,SAAS,gBAAgB;GAC9B;EACF;EAMA,MAAM,YAAY,QAAQ;EAC1B,MAAM,oBAAgD,aAAa,OAAO,WAAW;GACnF,MAAM,aAAa,YAAY,UAAU,aAAa,OAAO,MAAM,IAAI,CAAC;GACxE,MAAM,MAAM,KAAKA,mBAAmB;GACpC,IAAI,CAAC,KAAK,QAAQ,aAAa,OAAO;GACtC,IAAI;IACF,OAAO;KAAE,GAAG;KAAY,GAAI,IAAI,mBAAmB,KAAK,CAAC;IAAG;GAC9D,QAAQ;IACN,OAAO;GACT;EACF;EAEA,MAAM,oBAAoB,QAAQ,eAAe;EACjD,IAAI,eAAsD,KAAA;EAC1D,IAAI,CAAC,QAAQ,6BAA6B,mBACxC,eAAe,OAAO;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;GAIvE,IAAI,WAAW,CAAC,GAAG,MAAM,CAAC,SAAS,mBAAmB,aAAa,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;EACjF,QAAQ,CAER;CACF;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAKC,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAKA,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAKA,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAKA,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,eAAwB,OAAc,UAA0C;EAC9E,uBAAuB,KAAKD,mBAAmB,SAAS,OAAO,QAAQ;CACzE;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/pino.ts"],"sourcesContent":["import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger';\nimport { LogLevel, MastraLogger, buildLogRecordData, exportTrackedException } from '@mastra/core/logger';\nimport pino from 'pino';\nimport pretty from 'pino-pretty';\n\ntype TransportMap = Record<string, LoggerTransport>;\n\nexport type { LogLevel } from '@mastra/core/logger';\n\nexport interface PinoLoggerOptions<CustomLevels extends string = never> {\n name?: string;\n level?: LogLevel;\n transports?: TransportMap;\n overrideDefaultTransports?: boolean;\n formatters?: pino.LoggerOptions['formatters'];\n redact?: pino.LoggerOptions['redact'];\n mixin?: pino.MixinFn<CustomLevels>;\n customLevels?: { [level in CustomLevels]: number };\n /**\n * When false, disables pino-pretty and outputs raw JSON.\n * Useful when sending logs to aggregators like Datadog,\n * Loki, or CloudWatch that expect single-line JSON per entry.\n * @default true\n */\n prettyPrint?: boolean;\n /**\n * Override the key used for the log message.\n * Defaults to Pino's built-in 'msg' key.\n * Set to 'message' for compatibility with Google Cloud Logging,\n * Elastic Common Schema (ECS), Datadog, and AWS CloudWatch.\n * @example 'message'\n */\n messageKey?: string;\n /**\n * Custom pino serializers, merged over Mastra's defaults.\n * By default the `error` key is serialized with pino's standard error\n * serializer (alongside pino's built-in `err`), so that\n * `logger.warn('...', { error })` records the message and stack rather\n * than an empty object.\n */\n serializers?: pino.LoggerOptions['serializers'];\n}\n\ninterface PinoLoggerInternalOptions<CustomLevels extends string = never> extends PinoLoggerOptions<CustomLevels> {\n /** @internal Used internally for child loggers */\n _logger?: pino.Logger<CustomLevels>;\n /** @internal Shared adapter-context ref so root and children correlate together */\n _adapterContextRef?: { current?: LoggerAdapterContext };\n}\n\n/**\n * Provides Pino-backed logging for Mastra applications.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n * import { PinoLogger } from '@mastra/loggers';\n *\n * const mastra = new Mastra({\n * logger: new PinoLogger({ name: 'my-app', level: 'info' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/loggers/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Pino logger documentation](https://mastra.ai/reference/logging/pino-logger)\n * if packaged docs are unavailable.\n */\nexport class PinoLogger<CustomLevels extends string = never> extends MastraLogger {\n protected logger: pino.Logger<CustomLevels>;\n // Mutable ref shared with child loggers: the root's mixin (which children's\n // pino instances inherit) reads through this ref, so attaching observability\n // to a child (e.g. `new Mastra({ logger: base.child({...}) })`) correlates\n // the records it actually logs through.\n #adapterContextRef: { current?: LoggerAdapterContext };\n\n constructor(options: PinoLoggerOptions<CustomLevels> = {}) {\n super(options);\n\n const internalOptions = options as PinoLoggerInternalOptions<CustomLevels>;\n this.#adapterContextRef = internalOptions._adapterContextRef ?? {};\n\n // If an existing pino logger is provided (for child loggers), use it directly\n if (internalOptions._logger) {\n this.logger = internalOptions._logger;\n return;\n }\n\n // Compose the user mixin with trace correlation. Pino mixins run\n // synchronously on every log call, so the trace fields land in the\n // native record before serialization — for ALL destinations (stdout,\n // transports, files). Trace fields win on key conflicts.\n const userMixin = options.mixin;\n const correlationMixin: pino.MixinFn<CustomLevels> = (mergeObject, level, logger) => {\n const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.correlation) return userFields;\n try {\n return { ...userFields, ...(ctx.resolveTraceFields() ?? {}) };\n } catch {\n return userFields;\n }\n };\n\n const shouldPrettyPrint = options.prettyPrint ?? true;\n let prettyStream: ReturnType<typeof pretty> | undefined = undefined;\n if (!options.overrideDefaultTransports && shouldPrettyPrint) {\n prettyStream = pretty({\n colorize: true,\n levelFirst: true,\n ignore: 'pid,hostname,component',\n colorizeObjects: true,\n translateTime: 'SYS:standard',\n singleLine: false,\n });\n }\n\n const transportsAry = [...this.getTransports().entries()];\n this.logger = pino(\n {\n name: options.name || 'app',\n level: options.level || LogLevel.INFO,\n formatters: options.formatters,\n redact: options.redact,\n mixin: correlationMixin,\n customLevels: options.customLevels,\n messageKey: options.messageKey ?? 'msg',\n // Pino applies its error serializer only to `errorKey` (default `err`).\n // Mastra logs errors as `{ error }` throughout, and an Error's `message`\n // and `stack` are non-enumerable, so without this they serialize to `{}`.\n serializers: { error: pino.stdSerializers.err, ...options.serializers },\n },\n options.overrideDefaultTransports\n ? options?.transports?.default\n : transportsAry.length === 0\n ? prettyStream // undefined when prettyPrint:false → pino native JSON\n : pino.multistream([\n ...transportsAry.map(([, transport]) => ({\n stream: transport,\n level: options.level || LogLevel.INFO,\n })),\n ...(prettyStream // only add prettyStream to multistream if it exists\n ? [{ stream: prettyStream, level: options.level || LogLevel.INFO }]\n : []),\n ]),\n );\n }\n\n /**\n * Creates a child logger with additional bound context.\n * All logs from the child logger will include the bound context.\n *\n * @param bindings - Key-value pairs to include in all logs from this child logger\n * @returns A new PinoLogger instance with the bound context\n *\n * @example\n * ```typescript\n * const baseLogger = new PinoLogger({ name: 'MyApp' });\n *\n * // Create module-scoped logger\n * const serviceLogger = baseLogger.child({ module: 'UserService' });\n * serviceLogger.info('User created', { userId: '123' });\n * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }\n *\n * // Create request-scoped logger\n * const requestLogger = baseLogger.child({ requestId: req.id });\n * requestLogger.error('Request failed', { err: error });\n * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }\n * ```\n */\n child(bindings: Record<string, unknown>): PinoLogger<CustomLevels> {\n const childPino = this.logger.child(bindings);\n const childOptions: PinoLoggerInternalOptions<CustomLevels> = {\n name: this.name,\n level: this.level,\n transports: Object.fromEntries(this.transports),\n _logger: childPino,\n _adapterContextRef: this.#adapterContextRef,\n };\n return new PinoLogger(childOptions);\n }\n\n /**\n * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables\n * native trace correlation (trace_id/span_id merged into the pino record\n * via mixin, for every destination) and observability export derived from\n * the same record. Called by Mastra during setup.\n */\n __attachObservability(ctx: LoggerAdapterContext): void {\n // Shared ref: attaching to a child also enables correlation on the root\n // mixin the child's records flow through (and vice versa).\n this.#adapterContextRef.current = ctx;\n }\n\n /**\n * The adapter context lives on the ref cell shared by the whole\n * root/child family, so re-attach detection (multi-Mastra warning) must\n * key on that cell — attaching to a child re-targets the root too.\n */\n __observabilityAttachmentKey(): object {\n return this.#adapterContextRef;\n }\n\n /**\n * Export the record derived from the same native call to observability.\n * Runs regardless of pino's level filter and never throws into the caller.\n */\n #export(level: 'debug' | 'info' | 'warn' | 'error', message: string, args: Record<string, any>): void {\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.export) return;\n try {\n // An Error passed as the args value often has no enumerable keys but\n // must still be exported (serialized by buildLogRecordData).\n const hasPayload = args instanceof Error || Object.keys(args).length > 0;\n // Trace identity travels on ExportedLog.traceId/spanId (the sink is\n // span-correlated); data stays reserved for the user payload. The mixin\n // still injects trace fields into the native pino record for stdout.\n ctx.getLogSink()?.[level](message, buildLogRecordData(hasPayload ? [args] : []));\n } catch {\n // Never let observability export break the primary logger\n }\n }\n\n debug(message: string, args: Record<string, any> = {}): void {\n this.logger.debug(args, message);\n this.#export('debug', message, args);\n }\n\n info(message: string, args: Record<string, any> = {}): void {\n this.logger.info(args, message);\n this.#export('info', message, args);\n }\n\n warn(message: string, args: Record<string, any> = {}): void {\n this.logger.warn(args, message);\n this.#export('warn', message, args);\n }\n\n error(message: string, args: Record<string, any> = {}): void {\n this.logger.error(args, message);\n this.#export('error', message, args);\n }\n\n override trackException(error: Error, metadata?: Record<string, unknown>): void {\n exportTrackedException(this.#adapterContextRef.current, error, metadata);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,aAAb,MAAa,mBAAwD,aAAa;CAChF;CAKA;CAEA,YAAY,UAA2C,CAAC,GAAG;EACzD,MAAM,OAAO;EAEb,MAAM,kBAAkB;EACxB,KAAK,qBAAqB,gBAAgB,sBAAsB,CAAC;EAGjE,IAAI,gBAAgB,SAAS;GAC3B,KAAK,SAAS,gBAAgB;GAC9B;EACF;EAMA,MAAM,YAAY,QAAQ;EAC1B,MAAM,oBAAgD,aAAa,OAAO,WAAW;GACnF,MAAM,aAAa,YAAY,UAAU,aAAa,OAAO,MAAM,IAAI,CAAC;GACxE,MAAM,MAAM,KAAK,mBAAmB;GACpC,IAAI,CAAC,KAAK,QAAQ,aAAa,OAAO;GACtC,IAAI;IACF,OAAO;KAAE,GAAG;KAAY,GAAI,IAAI,mBAAmB,KAAK,CAAC;IAAG;GAC9D,QAAQ;IACN,OAAO;GACT;EACF;EAEA,MAAM,oBAAoB,QAAQ,eAAe;EACjD,IAAI,eAAsD,KAAA;EAC1D,IAAI,CAAC,QAAQ,6BAA6B,mBACxC,eAAe,OAAO;GACpB,UAAU;GACV,YAAY;GACZ,Q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AM,CAAC,SAAS,mBAAmB,aAAa,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;EACjF,QAAQ,CAER;CACF;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAK,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAK,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAK,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAK,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,eAAwB,OAAc,UAA0C;EAC9E,uBAAuB,KAAK,mBAAmB,SAAS,OAAO,QAAQ;CACzE;AACF"}
@@ -38,6 +38,11 @@ var UpstashTransport = class extends _mastra_core_logger.LoggerTransport {
38
38
  console.error("Error flushing logs to Upstash:", err);
39
39
  });
40
40
  }, this.flushInterval);
41
+ this.updateIntervalRef();
42
+ }
43
+ updateIntervalRef() {
44
+ if (this.logBuffer.length > 0 || this.flushPromise) this.flushIntervalId.ref?.();
45
+ else this.flushIntervalId.unref?.();
41
46
  }
42
47
  async executeUpstashCommands(commands) {
43
48
  const response = await fetch(`${this.upstashUrl}/pipeline`, {
@@ -57,6 +62,7 @@ var UpstashTransport = class extends _mastra_core_logger.LoggerTransport {
57
62
  if (this.logBuffer.length === 0) return Promise.resolve();
58
63
  this.flushPromise = this.flushBatch().finally(() => {
59
64
  this.flushPromise = null;
65
+ this.updateIntervalRef();
60
66
  });
61
67
  return this.flushPromise;
62
68
  }
@@ -118,6 +124,7 @@ var UpstashTransport = class extends _mastra_core_logger.LoggerTransport {
118
124
  time: Date.now()
119
125
  } : parsed;
120
126
  this.logBuffer.push(log);
127
+ this.updateIntervalRef();
121
128
  if (this.logBuffer.length >= Math.min(this.batchSize, this.maxBufferSize)) this._flush().catch((err) => {
122
129
  console.error("Error flushing logs to Upstash:", err);
123
130
  });
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["LoggerTransport","normalizePagination"],"sources":["../../src/upstash/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\n/** LTRIM failed after LPUSH succeeded: the records were written, so they are not put back in the buffer. */\nclass UpstashTrimError extends Error {\n name = 'UpstashTrimError';\n}\n\nexport class UpstashTransport extends LoggerTransport {\n upstashUrl: string;\n upstashToken: string;\n listName: string;\n maxListLength: number;\n maxBufferSize: number;\n /** Number of buffered records discarded because the buffer exceeded `maxBufferSize`. */\n droppedRecords = 0;\n batchSize: number;\n flushInterval: number;\n logBuffer: any[];\n lastFlush: number;\n flushIntervalId: NodeJS.Timeout;\n private flushPromise: Promise<void> | null = null;\n\n constructor(opts: {\n listName?: string;\n maxListLength?: number;\n /** Maximum number of records held in memory while Upstash is unreachable. Must be a positive integer. Defaults to `maxListLength`, or 10000 when `maxListLength` disables trimming. */\n maxBufferSize?: number;\n batchSize?: number;\n upstashUrl: string;\n flushInterval?: number;\n upstashToken: string;\n }) {\n super({ objectMode: true });\n\n if (!opts.upstashUrl || !opts.upstashToken) {\n throw new Error('Upstash URL and token are required');\n }\n\n this.upstashUrl = opts.upstashUrl;\n this.upstashToken = opts.upstashToken;\n this.listName = opts.listName || 'application-logs';\n this.maxListLength = opts.maxListLength || 10000;\n // A non-positive maxListLength disables LTRIM, so it cannot serve as the buffer limit.\n this.maxBufferSize = opts.maxBufferSize ?? (this.maxListLength > 0 ? this.maxListLength : 10000);\n if (!Number.isInteger(this.maxBufferSize) || this.maxBufferSize < 1) {\n throw new Error('maxBufferSize must be a positive integer');\n }\n this.batchSize = opts.batchSize || 100;\n this.flushInterval = opts.flushInterval || 10000;\n\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => {\n this._flush().catch(err => {\n console.error('Error flushing logs to Upstash:', err);\n });\n }, this.flushInterval);\n }\n\n private async executeUpstashCommands(commands: any[][]): Promise<any> {\n const response = await fetch(`${this.upstashUrl}/pipeline`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.upstashToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(commands),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to execute Upstash command: ${response.statusText}`);\n }\n\n return response.json();\n }\n\n /** Sends the next batch to Upstash. Callers share the in-flight flush instead of starting a new request. */\n _flush(): Promise<void> {\n if (this.flushPromise) {\n return this.flushPromise;\n }\n if (this.logBuffer.length === 0) {\n return Promise.resolve();\n }\n\n this.flushPromise = this.flushBatch().finally(() => {\n this.flushPromise = null;\n });\n return this.flushPromise;\n }\n\n /**\n * Pushes one batch to Upstash. If the request or the LPUSH command fails, the records return to the\n * front of the buffer. A failed LTRIM is reported without resending, since the records were already written.\n */\n private async flushBatch() {\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n const commands: any[][] = [['LPUSH', this.listName, ...logs.map(log => JSON.stringify(log))]];\n\n // Trim the list if it exceeds maxListLength (must be a separate pipeline command)\n if (this.maxListLength > 0) {\n commands.push(['LTRIM', this.listName, 0, this.maxListLength - 1]);\n }\n\n let results: any;\n try {\n results = await this.executeUpstashCommands(commands);\n // Upstash answers HTTP 200 even when a command fails, reporting { error } per command\n const pushError = Array.isArray(results) ? results[0]?.error : undefined;\n if (pushError) {\n throw new Error(`Failed to push logs to Upstash: ${pushError}`);\n }\n } catch (error) {\n // On error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n this.enforceBufferLimit();\n throw error;\n }\n\n this.lastFlush = now;\n const trimError = Array.isArray(results) ? results[1]?.error : undefined;\n if (trimError) {\n throw new UpstashTrimError(`Failed to trim Upstash log list: ${trimError}`);\n }\n }\n\n /** Drops the oldest buffered records once the buffer exceeds `maxBufferSize`. */\n private enforceBufferLimit() {\n const overflow = this.logBuffer.length - this.maxBufferSize;\n if (overflow > 0) {\n this.logBuffer.splice(0, overflow);\n this.droppedRecords += overflow;\n }\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n _transform(chunk: string, _enc: string, cb: Function) {\n try {\n // Parse the log line if it's a string\n const parsed = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present, on a copy so caller-owned (possibly frozen) records stay untouched\n const log = parsed.time === undefined || parsed.time === null ? { ...parsed, time: Date.now() } : parsed;\n\n // Add to buffer\n this.logBuffer.push(log);\n\n // Flush once a batch is ready, or earlier if the buffer limit is smaller than a batch\n if (this.logBuffer.length >= Math.min(this.batchSize, this.maxBufferSize)) {\n this._flush().catch(err => {\n console.error('Error flushing logs to Upstash:', err);\n });\n }\n\n this.enforceBufferLimit();\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function) {\n clearInterval(this.flushIntervalId);\n\n // Final flush\n if (this.logBuffer.length > 0 || this.flushPromise) {\n this.drainBuffer()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n // Wait out any in-flight request, ignoring its failure since its records are back in the buffer,\n // then keep sending until the buffer is empty. A failed request ends the drain instead of retrying forever.\n // A trim failure leaves nothing to resend, so draining continues and the first one is reported at the end.\n private async drainBuffer(): Promise<void> {\n let trimError: UpstashTrimError | undefined;\n await this.flushPromise?.catch(error => {\n if (error instanceof UpstashTrimError) trimError ??= error;\n });\n while (this.logBuffer.length > 0 || this.flushPromise) {\n try {\n await (this.flushPromise ?? this._flush());\n } catch (error) {\n if (!(error instanceof UpstashTrimError)) throw error;\n trimError ??= error;\n }\n }\n if (trimError) throw trimError;\n }\n\n private parseLogs(logs: unknown): BaseLogMessage[] {\n if (!Array.isArray(logs)) return [];\n\n return logs.flatMap((log: string) => {\n try {\n const parsedLog = JSON.parse(log);\n return parsedLog !== null && typeof parsedLog === 'object' ? [parsedLog] : [];\n } catch {\n return [];\n }\n });\n }\n\n private matchesLog(\n log: BaseLogMessage,\n {\n fromDate,\n toDate,\n logLevel,\n filters,\n runId,\n }: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n runId?: string;\n },\n ): boolean {\n if (runId !== undefined && log.runId !== runId) return false;\n if (logLevel && log.level !== logLevel) return false;\n const logTime = new Date(log.time).getTime();\n if (fromDate && !(logTime >= fromDate.getTime())) return false;\n if (toDate && !(logTime <= toDate.getTime())) return false;\n\n return !filters || Object.entries(filters).every(([key, value]) => log[key as keyof BaseLogMessage] === value);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n const { page, perPage, start, end } = normalizePagination(params?.page, params?.perPage);\n try {\n const {\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults: returnPaginationResultsInput,\n } = params || {};\n\n const returnPaginationResults = returnPaginationResultsInput ?? true;\n const hasFilters = Boolean(fromDate || toDate || logLevel || (filters && Object.keys(filters).length > 0));\n\n if (returnPaginationResults && !hasFilters) {\n const response = await this.executeUpstashCommands([\n ['LLEN', this.listName],\n ['LRANGE', this.listName, start, end - 1],\n ]);\n const total = Number(response?.[0]?.result) || 0;\n const logs = this.parseLogs(response?.[1]?.result);\n\n return {\n logs,\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n }\n\n const response = await this.executeUpstashCommands([['LRANGE', this.listName, 0, -1]]);\n const filteredLogs = this.parseLogs(response?.[0]?.result).filter(log =>\n this.matchesLog(log, { fromDate, toDate, logLevel, filters }),\n );\n\n if (!returnPaginationResults) {\n return {\n logs: filteredLogs,\n total: filteredLogs.length,\n page,\n perPage: filteredLogs.length,\n hasMore: false,\n };\n }\n\n const total = filteredLogs.length;\n\n return {\n logs: filteredLogs.slice(start, end),\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n } catch (error) {\n console.error('Error getting logs from Upstash:', error);\n return {\n logs: [],\n total: 0,\n page,\n perPage,\n hasMore: false,\n };\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n try {\n const allLogs = await this.listLogs({ fromDate, toDate, logLevel, filters, returnPaginationResults: false });\n const logs = allLogs.logs.filter(log => this.matchesLog(log, { runId }));\n const total = logs.length;\n\n return {\n logs: logs.slice(start, end),\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n } catch (error) {\n console.error('Error getting logs by runId from Upstash:', error);\n return {\n logs: [],\n total: 0,\n page,\n perPage,\n hasMore: false,\n };\n }\n }\n}\n"],"mappings":";;;;;AAKA,IAAM,mBAAN,cAA+B,MAAM;CACnC,OAAO;AACT;AAEA,IAAa,mBAAb,cAAsCA,oBAAAA,gBAAgB;CACpD;CACA;CACA;CACA;CACA;;CAEA,iBAAiB;CACjB;CACA;CACA;CACA;CACA;CACA,eAA6C;CAE7C,YAAY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;GAAQ,CAAC,CAC9D;GAEA,IAAI,CAAC,yBACH,OAAO;IACL,MAAM;IACN,OAAO,aAAa;IACpB;IACA,SAAS,aAAa;IACtB,SAAS;GACX;GAGF,MAAM,QAAQ,aAAa;GAE3B,OAAO;IACL,MAAM,aAAa,MAAM,OAAO,GAAG;IACnC;IACA;IACA;IACA,SAAS,MAAM;GACjB;EACF,SAAS,OAAO;GACd,QAAQ,MAAM,oCAAoC,KAAK;GACvD,OAAO;IACL,MAAM,CAAC;IACP,OAAO;IACP;IACA;IACA,SAAS;GACX;EACF;CACF;CAEA,MAAM,gBAAgB,EACpB,OACA,UACA,QACA,UACA,SACA,MAAM,WACN,SAAS,gBAeR;EACD,MAAM,EAAE,MAAM,SAAS,OAAO,QAAQA,mBAAAA,oBAAoB,WAAW,YAAY;EACjF,IAAI;GAEF,MAAM,QAAO,MADS,KAAK,SAAS;IAAE;IAAU;IAAQ;IAAU;IAAS,yBAAyB;GAAM,CAAC,EAAA,CACtF,KAAK,QAAO,QAAO,KAAK,WAAW,KAAK,EAAE,MAAM,CAAC,CAAC;GACvE,MAAM,QAAQ,KAAK;GAEnB,OAAO;IACL,MAAM,KAAK,MAAM,OAAO,GAAG;IAC3B;IACA;IACA;IACA,SAAS,MAAM;GACjB;EACF,SAAS,OAAO;GACd,QAAQ,MAAM,6CAA6C,KAAK;GAChE,OAAO;IACL,MAAM,CAAC;IACP,OAAO;IACP;IACA;IACA,SAAS;GACX;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["LoggerTransport","normalizePagination"],"sources":["../../src/upstash/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\n/** LTRIM failed after LPUSH succeeded: the records were written, so they are not put back in the buffer. */\nclass UpstashTrimError extends Error {\n name = 'UpstashTrimError';\n}\n\nexport class UpstashTransport extends LoggerTransport {\n upstashUrl: string;\n upstashToken: string;\n listName: string;\n maxListLength: number;\n maxBufferSize: number;\n /** Number of buffered records discarded because the buffer exceeded `maxBufferSize`. */\n droppedRecords = 0;\n batchSize: number;\n flushInterval: number;\n logBuffer: any[];\n lastFlush: number;\n flushIntervalId: NodeJS.Timeout;\n private flushPromise: Promise<void> | null = null;\n\n constructor(opts: {\n listName?: string;\n maxListLength?: number;\n /** Maximum number of records held in memory while Upstash is unreachable. Must be a positive integer. Defaults to `maxListLength`, or 10000 when `maxListLength` disables trimming. */\n maxBufferSize?: number;\n batchSize?: number;\n upstashUrl: string;\n flushInterval?: number;\n upstashToken: string;\n }) {\n super({ objectMode: true });\n\n if (!opts.upstashUrl || !opts.upstashToken) {\n throw new Error('Upstash URL and token are required');\n }\n\n this.upstashUrl = opts.upstashUrl;\n this.upstashToken = opts.upstashToken;\n this.listName = opts.listName || 'application-logs';\n this.maxListLength = opts.maxListLength || 10000;\n // A non-positive maxListLength disables LTRIM, so it cannot serve as the buffer limit.\n this.maxBufferSize = opts.maxBufferSize ?? (this.maxListLength > 0 ? this.maxListLength : 10000);\n if (!Number.isInteger(this.maxBufferSize) || this.maxBufferSize < 1) {\n throw new Error('maxBufferSize must be a positive integer');\n }\n this.batchSize = opts.batchSize || 100;\n this.flushInterval = opts.flushInterval || 10000;\n\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => {\n this._flush().catch(err => {\n console.error('Error flushing logs to Upstash:', err);\n });\n }, this.flushInterval);\n this.updateIntervalRef();\n }\n\n // The interval only keeps the process alive while records are waiting to be sent, so an idle transport\n // doesn't stop a script from exiting, but buffered records still get delivered (or retried) first.\n // Web-standard runtimes return a numeric timer id without ref()/unref(), so those calls are optional.\n private updateIntervalRef() {\n if (this.logBuffer.length > 0 || this.flushPromise) {\n this.flushIntervalId.ref?.();\n } else {\n this.flushIntervalId.unref?.();\n }\n }\n\n private async executeUpstashCommands(commands: any[][]): Promise<any> {\n const response = await fetch(`${this.upstashUrl}/pipeline`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.upstashToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(commands),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to execute Upstash command: ${response.statusText}`);\n }\n\n return response.json();\n }\n\n /** Sends the next batch to Upstash. Callers share the in-flight flush instead of starting a new request. */\n _flush(): Promise<void> {\n if (this.flushPromise) {\n return this.flushPromise;\n }\n if (this.logBuffer.length === 0) {\n return Promise.resolve();\n }\n\n this.flushPromise = this.flushBatch().finally(() => {\n this.flushPromise = null;\n this.updateIntervalRef();\n });\n return this.flushPromise;\n }\n\n /**\n * Pushes one batch to Upstash. If the request or the LPUSH command fails, the records return to the\n * front of the buffer. A failed LTRIM is reported without resending, since the records were already written.\n */\n private async flushBatch() {\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n const commands: any[][] = [['LPUSH', this.listName, ...logs.map(log => JSON.stringify(log))]];\n\n // Trim the list if it exceeds maxListLength (must be a separate pipeline command)\n if (this.maxListLength > 0) {\n commands.push(['LTRIM', this.listName, 0, this.maxListLength - 1]);\n }\n\n let results: any;\n try {\n results = await this.executeUpstashCommands(commands);\n // Upstash answers HTTP 200 even when a command fails, reporting { error } per command\n const pushError = Array.isArray(results) ? results[0]?.error : undefined;\n if (pushError) {\n throw new Error(`Failed to push logs to Upstash: ${pushError}`);\n }\n } catch (error) {\n // On error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n this.enforceBufferLimit();\n throw error;\n }\n\n this.lastFlush = now;\n const trimError = Array.isArray(results) ? results[1]?.error : undefined;\n if (trimError) {\n throw new UpstashTrimError(`Failed to trim Upstash log list: ${trimError}`);\n }\n }\n\n /** Drops the oldest buffered records once the buffer exceeds `maxBufferSize`. */\n private enforceBufferLimit() {\n const overflow = this.logBuffer.length - this.maxBufferSize;\n if (overflow > 0) {\n this.logBuffer.splice(0, overflow);\n this.droppedRecords += overflow;\n }\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n _transform(chunk: string, _enc: string, cb: Function) {\n try {\n // Parse the log line if it's a string\n const parsed = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present, on a copy so caller-owned (possibly frozen) records stay untouched\n const log = parsed.time === undefined || parsed.time === null ? { ...parsed, time: Date.now() } : parsed;\n\n // Add to buffer\n this.logBuffer.push(log);\n this.updateIntervalRef();\n\n // Flush once a batch is ready, or earlier if the buffer limit is smaller than a batch\n if (this.logBuffer.length >= Math.min(this.batchSize, this.maxBufferSize)) {\n this._flush().catch(err => {\n console.error('Error flushing logs to Upstash:', err);\n });\n }\n\n this.enforceBufferLimit();\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function) {\n clearInterval(this.flushIntervalId);\n\n // Final flush\n if (this.logBuffer.length > 0 || this.flushPromise) {\n this.drainBuffer()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n // Wait out any in-flight request, ignoring its failure since its records are back in the buffer,\n // then keep sending until the buffer is empty. A failed request ends the drain instead of retrying forever.\n // A trim failure leaves nothing to resend, so draining continues and the first one is reported at the end.\n private async drainBuffer(): Promise<void> {\n let trimError: UpstashTrimError | undefined;\n await this.flushPromise?.catch(error => {\n if (error instanceof UpstashTrimError) trimError ??= error;\n });\n while (this.logBuffer.length > 0 || this.flushPromise) {\n try {\n await (this.flushPromise ?? this._flush());\n } catch (error) {\n if (!(error instanceof UpstashTrimError)) throw error;\n trimError ??= error;\n }\n }\n if (trimError) throw trimError;\n }\n\n private parseLogs(logs: unknown): BaseLogMessage[] {\n if (!Array.isArray(logs)) return [];\n\n return logs.flatMap((log: string) => {\n try {\n const parsedLog = JSON.parse(log);\n return parsedLog !== null && typeof parsedLog === 'object' ? [parsedLog] : [];\n } catch {\n return [];\n }\n });\n }\n\n private matchesLog(\n log: BaseLogMessage,\n {\n fromDate,\n toDate,\n logLevel,\n filters,\n runId,\n }: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n runId?: string;\n },\n ): boolean {\n if (runId !== undefined && log.runId !== runId) return false;\n if (logLevel && log.level !== logLevel) return false;\n const logTime = new Date(log.time).getTime();\n if (fromDate && !(logTime >= fromDate.getTime())) return false;\n if (toDate && !(logTime <= toDate.getTime())) return false;\n\n return !filters || Object.entries(filters).every(([key, value]) => log[key as keyof BaseLogMessage] === value);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n const { page, perPage, start, end } = normalizePagination(params?.page, params?.perPage);\n try {\n const {\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults: returnPaginationResultsInput,\n } = params || {};\n\n const returnPaginationResults = returnPaginationResultsInput ?? true;\n const hasFilters = Boolean(fromDate || toDate || logLevel || (filters && Object.keys(filters).length > 0));\n\n if (returnPaginationResults && !hasFilters) {\n const response = await this.executeUpstashCommands([\n ['LLEN', this.listName],\n ['LRANGE', this.listName, start, end - 1],\n ]);\n const total = Number(response?.[0]?.result) || 0;\n const logs = this.parseLogs(response?.[1]?.result);\n\n return {\n logs,\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n }\n\n const response = await this.executeUpstashCommands([['LRANGE', this.listName, 0, -1]]);\n const filteredLogs = this.parseLogs(response?.[0]?.result).filter(log =>\n this.matchesLog(log, { fromDate, toDate, logLevel, filters }),\n );\n\n if (!returnPaginationResults) {\n return {\n logs: filteredLogs,\n total: filteredLogs.length,\n page,\n perPage: filteredLogs.length,\n hasMore: false,\n };\n }\n\n const total = filteredLogs.length;\n\n return {\n logs: filteredLogs.slice(start, end),\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n } catch (error) {\n console.error('Error getting logs from Upstash:', error);\n return {\n logs: [],\n total: 0,\n page,\n perPage,\n hasMore: false,\n };\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n try {\n const allLogs = await this.listLogs({ fromDate, toDate, logLevel, filters, returnPaginationResults: false });\n const logs = allLogs.logs.filter(log => this.matchesLog(log, { runId }));\n const total = logs.length;\n\n return {\n logs: logs.slice(start, end),\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n } catch (error) {\n console.error('Error getting logs by runId from Upstash:', error);\n return {\n logs: [],\n total: 0,\n page,\n perPage,\n hasMore: false,\n };\n }\n }\n}\n"],"mappings":";;;;;AAKA,IAAM,mBAAN,cAA+B,MAAM;CACnC,OAAO;AACT;AAEA,IAAa,mBAAb,cAAsCA,oBAAAA,gBAAgB;CACpD;CACA;CACA;CACA;CACA;;CAEA,iBAAiB;CACjB;CACA;CACA;CACA;CACA;CACA,eAA6C;CAE7C,YAAY,MAST;EACD,MAAM,EAAE,YAAY,KAAK,CAAC;EAE1B,IAAI,CAAC,KAAK,cAAc,CAAC,KAAK,cAC5B,MAAM,IAAI,MAAM,oCAAoC;EAGtD,KAAK,aAAa,KAAK;EACvB,KAAK,eAAe,KAAK;EACzB,KAAK,WAAW,KAAK,YAAY;EACjC,KAAK,gBAAgB,KAAK,iBAAi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AO;IACL,MAAM;IACN,OAAO,aAAa;IACpB;IACA,SAAS,aAAa;IACtB,SAAS;GACX;GAGF,MAAM,QAAQ,aAAa;GAE3B,OAAO;IACL,MAAM,aAAa,MAAM,OAAO,GAAG;IACnC;IACA;IACA;IACA,SAAS,MAAM;GACjB;EACF,SAAS,OAAO;GACd,QAAQ,MAAM,oCAAoC,KAAK;GACvD,OAAO;IACL,MAAM,CAAC;IACP,OAAO;IACP;IACA;IACA,SAAS;GACX;EACF;CACF;CAEA,MAAM,gBAAgB,EACpB,OACA,UACA,QACA,UACA,SACA,MAAM,WACN,SAAS,gBAeR;EACD,MAAM,EAAE,MAAM,SAAS,OAAO,QAAQA,mBAAAA,oBAAoB,WAAW,YAAY;EACjF,IAAI;GAEF,MAAM,QAAO,MADS,KAAK,SAAS;IAAE;IAAU;IAAQ;IAAU;IAAS,yBAAyB;GAAM,CAAC,EAAA,CACtF,KAAK,QAAO,QAAO,KAAK,WAAW,KAAK,EAAE,MAAM,CAAC,CAAC;GACvE,MAAM,QAAQ,KAAK;GAEnB,OAAO;IACL,MAAM,KAAK,MAAM,OAAO,GAAG;IAC3B;IACA;IACA;IACA,SAAS,MAAM;GACjB;EACF,SAAS,OAAO;GACd,QAAQ,MAAM,6CAA6C,KAAK;GAChE,OAAO;IACL,MAAM,CAAC;IACP,OAAO;IACP;IACA;IACA,SAAS;GACX;EACF;CACF;AACF"}
@@ -24,6 +24,7 @@ export declare class UpstashTransport extends LoggerTransport {
24
24
  flushInterval?: number;
25
25
  upstashToken: string;
26
26
  });
27
+ private updateIntervalRef;
27
28
  private executeUpstashCommands;
28
29
  /** Sends the next batch to Upstash. Callers share the in-flight flush instead of starting a new request. */
29
30
  _flush(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/upstash/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,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AI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,OAAO,CAAC;KAClB,CAAC,CAwBD;CACF"}
@@ -37,6 +37,11 @@ var UpstashTransport = class extends LoggerTransport {
37
37
  console.error("Error flushing logs to Upstash:", err);
38
38
  });
39
39
  }, this.flushInterval);
40
+ this.updateIntervalRef();
41
+ }
42
+ updateIntervalRef() {
43
+ if (this.logBuffer.length > 0 || this.flushPromise) this.flushIntervalId.ref?.();
44
+ else this.flushIntervalId.unref?.();
40
45
  }
41
46
  async executeUpstashCommands(commands) {
42
47
  const response = await fetch(`${this.upstashUrl}/pipeline`, {
@@ -56,6 +61,7 @@ var UpstashTransport = class extends LoggerTransport {
56
61
  if (this.logBuffer.length === 0) return Promise.resolve();
57
62
  this.flushPromise = this.flushBatch().finally(() => {
58
63
  this.flushPromise = null;
64
+ this.updateIntervalRef();
59
65
  });
60
66
  return this.flushPromise;
61
67
  }
@@ -117,6 +123,7 @@ var UpstashTransport = class extends LoggerTransport {
117
123
  time: Date.now()
118
124
  } : parsed;
119
125
  this.logBuffer.push(log);
126
+ this.updateIntervalRef();
120
127
  if (this.logBuffer.length >= Math.min(this.batchSize, this.maxBufferSize)) this._flush().catch((err) => {
121
128
  console.error("Error flushing logs to Upstash:", err);
122
129
  });
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/upstash/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\n/** LTRIM failed after LPUSH succeeded: the records were written, so they are not put back in the buffer. */\nclass UpstashTrimError extends Error {\n name = 'UpstashTrimError';\n}\n\nexport class UpstashTransport extends LoggerTransport {\n upstashUrl: string;\n upstashToken: string;\n listName: string;\n maxListLength: number;\n maxBufferSize: number;\n /** Number of buffered records discarded because the buffer exceeded `maxBufferSize`. */\n droppedRecords = 0;\n batchSize: number;\n flushInterval: number;\n logBuffer: any[];\n lastFlush: number;\n flushIntervalId: NodeJS.Timeout;\n private flushPromise: Promise<void> | null = null;\n\n constructor(opts: {\n listName?: string;\n maxListLength?: number;\n /** Maximum number of records held in memory while Upstash is unreachable. Must be a positive integer. Defaults to `maxListLength`, or 10000 when `maxListLength` disables trimming. */\n maxBufferSize?: number;\n batchSize?: number;\n upstashUrl: string;\n flushInterval?: number;\n upstashToken: string;\n }) {\n super({ objectMode: true });\n\n if (!opts.upstashUrl || !opts.upstashToken) {\n throw new Error('Upstash URL and token are required');\n }\n\n this.upstashUrl = opts.upstashUrl;\n this.upstashToken = opts.upstashToken;\n this.listName = opts.listName || 'application-logs';\n this.maxListLength = opts.maxListLength || 10000;\n // A non-positive maxListLength disables LTRIM, so it cannot serve as the buffer limit.\n this.maxBufferSize = opts.maxBufferSize ?? (this.maxListLength > 0 ? this.maxListLength : 10000);\n if (!Number.isInteger(this.maxBufferSize) || this.maxBufferSize < 1) {\n throw new Error('maxBufferSize must be a positive integer');\n }\n this.batchSize = opts.batchSize || 100;\n this.flushInterval = opts.flushInterval || 10000;\n\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => {\n this._flush().catch(err => {\n console.error('Error flushing logs to Upstash:', err);\n });\n }, this.flushInterval);\n }\n\n private async executeUpstashCommands(commands: any[][]): Promise<any> {\n const response = await fetch(`${this.upstashUrl}/pipeline`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.upstashToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(commands),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to execute Upstash command: ${response.statusText}`);\n }\n\n return response.json();\n }\n\n /** Sends the next batch to Upstash. Callers share the in-flight flush instead of starting a new request. */\n _flush(): Promise<void> {\n if (this.flushPromise) {\n return this.flushPromise;\n }\n if (this.logBuffer.length === 0) {\n return Promise.resolve();\n }\n\n this.flushPromise = this.flushBatch().finally(() => {\n this.flushPromise = null;\n });\n return this.flushPromise;\n }\n\n /**\n * Pushes one batch to Upstash. If the request or the LPUSH command fails, the records return to the\n * front of the buffer. A failed LTRIM is reported without resending, since the records were already written.\n */\n private async flushBatch() {\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n const commands: any[][] = [['LPUSH', this.listName, ...logs.map(log => JSON.stringify(log))]];\n\n // Trim the list if it exceeds maxListLength (must be a separate pipeline command)\n if (this.maxListLength > 0) {\n commands.push(['LTRIM', this.listName, 0, this.maxListLength - 1]);\n }\n\n let results: any;\n try {\n results = await this.executeUpstashCommands(commands);\n // Upstash answers HTTP 200 even when a command fails, reporting { error } per command\n const pushError = Array.isArray(results) ? results[0]?.error : undefined;\n if (pushError) {\n throw new Error(`Failed to push logs to Upstash: ${pushError}`);\n }\n } catch (error) {\n // On error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n this.enforceBufferLimit();\n throw error;\n }\n\n this.lastFlush = now;\n const trimError = Array.isArray(results) ? results[1]?.error : undefined;\n if (trimError) {\n throw new UpstashTrimError(`Failed to trim Upstash log list: ${trimError}`);\n }\n }\n\n /** Drops the oldest buffered records once the buffer exceeds `maxBufferSize`. */\n private enforceBufferLimit() {\n const overflow = this.logBuffer.length - this.maxBufferSize;\n if (overflow > 0) {\n this.logBuffer.splice(0, overflow);\n this.droppedRecords += overflow;\n }\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n _transform(chunk: string, _enc: string, cb: Function) {\n try {\n // Parse the log line if it's a string\n const parsed = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present, on a copy so caller-owned (possibly frozen) records stay untouched\n const log = parsed.time === undefined || parsed.time === null ? { ...parsed, time: Date.now() } : parsed;\n\n // Add to buffer\n this.logBuffer.push(log);\n\n // Flush once a batch is ready, or earlier if the buffer limit is smaller than a batch\n if (this.logBuffer.length >= Math.min(this.batchSize, this.maxBufferSize)) {\n this._flush().catch(err => {\n console.error('Error flushing logs to Upstash:', err);\n });\n }\n\n this.enforceBufferLimit();\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function) {\n clearInterval(this.flushIntervalId);\n\n // Final flush\n if (this.logBuffer.length > 0 || this.flushPromise) {\n this.drainBuffer()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n // Wait out any in-flight request, ignoring its failure since its records are back in the buffer,\n // then keep sending until the buffer is empty. A failed request ends the drain instead of retrying forever.\n // A trim failure leaves nothing to resend, so draining continues and the first one is reported at the end.\n private async drainBuffer(): Promise<void> {\n let trimError: UpstashTrimError | undefined;\n await this.flushPromise?.catch(error => {\n if (error instanceof UpstashTrimError) trimError ??= error;\n });\n while (this.logBuffer.length > 0 || this.flushPromise) {\n try {\n await (this.flushPromise ?? this._flush());\n } catch (error) {\n if (!(error instanceof UpstashTrimError)) throw error;\n trimError ??= error;\n }\n }\n if (trimError) throw trimError;\n }\n\n private parseLogs(logs: unknown): BaseLogMessage[] {\n if (!Array.isArray(logs)) return [];\n\n return logs.flatMap((log: string) => {\n try {\n const parsedLog = JSON.parse(log);\n return parsedLog !== null && typeof parsedLog === 'object' ? [parsedLog] : [];\n } catch {\n return [];\n }\n });\n }\n\n private matchesLog(\n log: BaseLogMessage,\n {\n fromDate,\n toDate,\n logLevel,\n filters,\n runId,\n }: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n runId?: string;\n },\n ): boolean {\n if (runId !== undefined && log.runId !== runId) return false;\n if (logLevel && log.level !== logLevel) return false;\n const logTime = new Date(log.time).getTime();\n if (fromDate && !(logTime >= fromDate.getTime())) return false;\n if (toDate && !(logTime <= toDate.getTime())) return false;\n\n return !filters || Object.entries(filters).every(([key, value]) => log[key as keyof BaseLogMessage] === value);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n const { page, perPage, start, end } = normalizePagination(params?.page, params?.perPage);\n try {\n const {\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults: returnPaginationResultsInput,\n } = params || {};\n\n const returnPaginationResults = returnPaginationResultsInput ?? true;\n const hasFilters = Boolean(fromDate || toDate || logLevel || (filters && Object.keys(filters).length > 0));\n\n if (returnPaginationResults && !hasFilters) {\n const response = await this.executeUpstashCommands([\n ['LLEN', this.listName],\n ['LRANGE', this.listName, start, end - 1],\n ]);\n const total = Number(response?.[0]?.result) || 0;\n const logs = this.parseLogs(response?.[1]?.result);\n\n return {\n logs,\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n }\n\n const response = await this.executeUpstashCommands([['LRANGE', this.listName, 0, -1]]);\n const filteredLogs = this.parseLogs(response?.[0]?.result).filter(log =>\n this.matchesLog(log, { fromDate, toDate, logLevel, filters }),\n );\n\n if (!returnPaginationResults) {\n return {\n logs: filteredLogs,\n total: filteredLogs.length,\n page,\n perPage: filteredLogs.length,\n hasMore: false,\n };\n }\n\n const total = filteredLogs.length;\n\n return {\n logs: filteredLogs.slice(start, end),\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n } catch (error) {\n console.error('Error getting logs from Upstash:', error);\n return {\n logs: [],\n total: 0,\n page,\n perPage,\n hasMore: false,\n };\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n try {\n const allLogs = await this.listLogs({ fromDate, toDate, logLevel, filters, returnPaginationResults: false });\n const logs = allLogs.logs.filter(log => this.matchesLog(log, { runId }));\n const total = logs.length;\n\n return {\n logs: logs.slice(start, end),\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n } catch (error) {\n console.error('Error getting logs by runId from Upstash:', error);\n return {\n logs: [],\n total: 0,\n page,\n perPage,\n hasMore: false,\n };\n }\n }\n}\n"],"mappings":";;;;AAKA,IAAM,mBAAN,cAA+B,MAAM;CACnC,OAAO;AACT;AAEA,IAAa,mBAAb,cAAsC,gBAAgB;CACpD;CACA;CACA;CACA;CACA;;CAEA,iBAAiB;CACjB;CACA;CACA;CACA;CACA;CACA,eAA6C;CAE7C,YAAY,MAST;EACD,MAAM,EAAE,YAAY,KAAK,CAAC;EAE1B,IAAI,CAAC,KAAK,cAAc,CAAC,KAAK,cAC5B,MAAM,IAAI,MAAM,oCAAoC;EAGtD,KAAK,aAAa,KAAK;EACvB,KAAK,eAAe,KAAK;EACzB,KAAK,WAAW,KAAK,YAAY;EACjC,KAAK,gBAAgB,KAAK,iBAAiB;EAE3C,KAAK,gBAAgB,KAAK,kBAAkB,KAAK,gBAAgB,IAAI,KAAK,gBAAgB;EAC1F,IAAI,CAAC,OAAO,UAAU,KAAK,aAAa,KAAK,KAAK,gBAAgB,GAChE,MAAM,IAAI,MAAM,0CAA0C;EAE5D,KAAK,YAAY,KAAK,aAAa;EACnC,KAAK,gBAAgB,KAAK,iBAAiB;EAE3C,KAAK,YAAY,CAAC;EAClB,KAAK,YAAY,KAAK,IAAI;EAG1B,KAAK,kBAAkB,kBAAkB;GACvC,KAAK,OAAO,CAAC,CAAC,OAAM,QAAO;IACzB,QAAQ,MAAM,mCAAmC,G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W,KAAK,EAAE,MAAM,CAAC,CAAC;GACvE,MAAM,QAAQ,KAAK;GAEnB,OAAO;IACL,MAAM,KAAK,MAAM,OAAO,GAAG;IAC3B;IACA;IACA;IACA,SAAS,MAAM;GACjB;EACF,SAAS,OAAO;GACd,QAAQ,MAAM,6CAA6C,KAAK;GAChE,OAAO;IACL,MAAM,CAAC;IACP,OAAO;IACP;IACA;IACA,SAAS;GACX;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/upstash/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\n/** LTRIM failed after LPUSH succeeded: the records were written, so they are not put back in the buffer. */\nclass UpstashTrimError extends Error {\n name = 'UpstashTrimError';\n}\n\nexport class UpstashTransport extends LoggerTransport {\n upstashUrl: string;\n upstashToken: string;\n listName: string;\n maxListLength: number;\n maxBufferSize: number;\n /** Number of buffered records discarded because the buffer exceeded `maxBufferSize`. */\n droppedRecords = 0;\n batchSize: number;\n flushInterval: number;\n logBuffer: any[];\n lastFlush: number;\n flushIntervalId: NodeJS.Timeout;\n private flushPromise: Promise<void> | null = null;\n\n constructor(opts: {\n listName?: string;\n maxListLength?: number;\n /** Maximum number of records held in memory while Upstash is unreachable. Must be a positive integer. Defaults to `maxListLength`, or 10000 when `maxListLength` disables trimming. */\n maxBufferSize?: number;\n batchSize?: number;\n upstashUrl: string;\n flushInterval?: number;\n upstashToken: string;\n }) {\n super({ objectMode: true });\n\n if (!opts.upstashUrl || !opts.upstashToken) {\n throw new Error('Upstash URL and token are required');\n }\n\n this.upstashUrl = opts.upstashUrl;\n this.upstashToken = opts.upstashToken;\n this.listName = opts.listName || 'application-logs';\n this.maxListLength = opts.maxListLength || 10000;\n // A non-positive maxListLength disables LTRIM, so it cannot serve as the buffer limit.\n this.maxBufferSize = opts.maxBufferSize ?? (this.maxListLength > 0 ? this.maxListLength : 10000);\n if (!Number.isInteger(this.maxBufferSize) || this.maxBufferSize < 1) {\n throw new Error('maxBufferSize must be a positive integer');\n }\n this.batchSize = opts.batchSize || 100;\n this.flushInterval = opts.flushInterval || 10000;\n\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => {\n this._flush().catch(err => {\n console.error('Error flushing logs to Upstash:', err);\n });\n }, this.flushInterval);\n this.updateIntervalRef();\n }\n\n // The interval only keeps the process alive while records are waiting to be sent, so an idle transport\n // doesn't stop a script from exiting, but buffered records still get delivered (or retried) first.\n // Web-standard runtimes return a numeric timer id without ref()/unref(), so those calls are optional.\n private updateIntervalRef() {\n if (this.logBuffer.length > 0 || this.flushPromise) {\n this.flushIntervalId.ref?.();\n } else {\n this.flushIntervalId.unref?.();\n }\n }\n\n private async executeUpstashCommands(commands: any[][]): Promise<any> {\n const response = await fetch(`${this.upstashUrl}/pipeline`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.upstashToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(commands),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to execute Upstash command: ${response.statusText}`);\n }\n\n return response.json();\n }\n\n /** Sends the next batch to Upstash. Callers share the in-flight flush instead of starting a new request. */\n _flush(): Promise<void> {\n if (this.flushPromise) {\n return this.flushPromise;\n }\n if (this.logBuffer.length === 0) {\n return Promise.resolve();\n }\n\n this.flushPromise = this.flushBatch().finally(() => {\n this.flushPromise = null;\n this.updateIntervalRef();\n });\n return this.flushPromise;\n }\n\n /**\n * Pushes one batch to Upstash. If the request or the LPUSH command fails, the records return to the\n * front of the buffer. A failed LTRIM is reported without resending, since the records were already written.\n */\n private async flushBatch() {\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n const commands: any[][] = [['LPUSH', this.listName, ...logs.map(log => JSON.stringify(log))]];\n\n // Trim the list if it exceeds maxListLength (must be a separate pipeline command)\n if (this.maxListLength > 0) {\n commands.push(['LTRIM', this.listName, 0, this.maxListLength - 1]);\n }\n\n let results: any;\n try {\n results = await this.executeUpstashCommands(commands);\n // Upstash answers HTTP 200 even when a command fails, reporting { error } per command\n const pushError = Array.isArray(results) ? results[0]?.error : undefined;\n if (pushError) {\n throw new Error(`Failed to push logs to Upstash: ${pushError}`);\n }\n } catch (error) {\n // On error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n this.enforceBufferLimit();\n throw error;\n }\n\n this.lastFlush = now;\n const trimError = Array.isArray(results) ? results[1]?.error : undefined;\n if (trimError) {\n throw new UpstashTrimError(`Failed to trim Upstash log list: ${trimError}`);\n }\n }\n\n /** Drops the oldest buffered records once the buffer exceeds `maxBufferSize`. */\n private enforceBufferLimit() {\n const overflow = this.logBuffer.length - this.maxBufferSize;\n if (overflow > 0) {\n this.logBuffer.splice(0, overflow);\n this.droppedRecords += overflow;\n }\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n _transform(chunk: string, _enc: string, cb: Function) {\n try {\n // Parse the log line if it's a string\n const parsed = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present, on a copy so caller-owned (possibly frozen) records stay untouched\n const log = parsed.time === undefined || parsed.time === null ? { ...parsed, time: Date.now() } : parsed;\n\n // Add to buffer\n this.logBuffer.push(log);\n this.updateIntervalRef();\n\n // Flush once a batch is ready, or earlier if the buffer limit is smaller than a batch\n if (this.logBuffer.length >= Math.min(this.batchSize, this.maxBufferSize)) {\n this._flush().catch(err => {\n console.error('Error flushing logs to Upstash:', err);\n });\n }\n\n this.enforceBufferLimit();\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function) {\n clearInterval(this.flushIntervalId);\n\n // Final flush\n if (this.logBuffer.length > 0 || this.flushPromise) {\n this.drainBuffer()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n // Wait out any in-flight request, ignoring its failure since its records are back in the buffer,\n // then keep sending until the buffer is empty. A failed request ends the drain instead of retrying forever.\n // A trim failure leaves nothing to resend, so draining continues and the first one is reported at the end.\n private async drainBuffer(): Promise<void> {\n let trimError: UpstashTrimError | undefined;\n await this.flushPromise?.catch(error => {\n if (error instanceof UpstashTrimError) trimError ??= error;\n });\n while (this.logBuffer.length > 0 || this.flushPromise) {\n try {\n await (this.flushPromise ?? this._flush());\n } catch (error) {\n if (!(error instanceof UpstashTrimError)) throw error;\n trimError ??= error;\n }\n }\n if (trimError) throw trimError;\n }\n\n private parseLogs(logs: unknown): BaseLogMessage[] {\n if (!Array.isArray(logs)) return [];\n\n return logs.flatMap((log: string) => {\n try {\n const parsedLog = JSON.parse(log);\n return parsedLog !== null && typeof parsedLog === 'object' ? [parsedLog] : [];\n } catch {\n return [];\n }\n });\n }\n\n private matchesLog(\n log: BaseLogMessage,\n {\n fromDate,\n toDate,\n logLevel,\n filters,\n runId,\n }: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n runId?: string;\n },\n ): boolean {\n if (runId !== undefined && log.runId !== runId) return false;\n if (logLevel && log.level !== logLevel) return false;\n const logTime = new Date(log.time).getTime();\n if (fromDate && !(logTime >= fromDate.getTime())) return false;\n if (toDate && !(logTime <= toDate.getTime())) return false;\n\n return !filters || Object.entries(filters).every(([key, value]) => log[key as keyof BaseLogMessage] === value);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n const { page, perPage, start, end } = normalizePagination(params?.page, params?.perPage);\n try {\n const {\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults: returnPaginationResultsInput,\n } = params || {};\n\n const returnPaginationResults = returnPaginationResultsInput ?? true;\n const hasFilters = Boolean(fromDate || toDate || logLevel || (filters && Object.keys(filters).length > 0));\n\n if (returnPaginationResults && !hasFilters) {\n const response = await this.executeUpstashCommands([\n ['LLEN', this.listName],\n ['LRANGE', this.listName, start, end - 1],\n ]);\n const total = Number(response?.[0]?.result) || 0;\n const logs = this.parseLogs(response?.[1]?.result);\n\n return {\n logs,\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n }\n\n const response = await this.executeUpstashCommands([['LRANGE', this.listName, 0, -1]]);\n const filteredLogs = this.parseLogs(response?.[0]?.result).filter(log =>\n this.matchesLog(log, { fromDate, toDate, logLevel, filters }),\n );\n\n if (!returnPaginationResults) {\n return {\n logs: filteredLogs,\n total: filteredLogs.length,\n page,\n perPage: filteredLogs.length,\n hasMore: false,\n };\n }\n\n const total = filteredLogs.length;\n\n return {\n logs: filteredLogs.slice(start, end),\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n } catch (error) {\n console.error('Error getting logs from Upstash:', error);\n return {\n logs: [],\n total: 0,\n page,\n perPage,\n hasMore: false,\n };\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n try {\n const allLogs = await this.listLogs({ fromDate, toDate, logLevel, filters, returnPaginationResults: false });\n const logs = allLogs.logs.filter(log => this.matchesLog(log, { runId }));\n const total = logs.length;\n\n return {\n logs: logs.slice(start, end),\n total,\n page,\n perPage,\n hasMore: end < total,\n };\n } catch (error) {\n console.error('Error getting logs by runId from Upstash:', error);\n return {\n logs: [],\n total: 0,\n page,\n perPage,\n hasMore: false,\n };\n }\n }\n}\n"],"mappings":";;;;AAKA,IAAM,mBAAN,cAA+B,MAAM;CACnC,OAAO;AACT;AAEA,IAAa,mBAAb,cAAsC,gBAAgB;CACpD;CACA;CACA;CACA;CACA;;CAEA,iBAAiB;CACjB;CACA;CACA;CACA;CACA;CACA,eAA6C;CAE7C,YAAY,MAST;EACD,MAAM,EAAE,YAAY,KAAK,CAAC;EAE1B,IAAI,CAAC,KAAK,cAAc,CAAC,KAAK,cAC5B,MAAM,IAAI,MAAM,oCAAoC;EAGtD,KAAK,aAAa,KAAK;EACvB,KAAK,eAAe,KAAK;EACzB,KAAK,WAAW,KAAK,YAAY;EACjC,KAAK,gBAAgB,KAAK,iBAAiB;EAE3C,KAAK,gBAAgB,KAAK,kBAAkB,KAAK,gBAAgB,IAAI,KAAK,gBAAgB;EAC1F,IAAI,CAAC,OAAO,UAAU,KAAK,aAAa,KAAK,KAAK,gBAAgB,GAChE,MAAM,IAAI,MAAM,0CAA0C;EAE5D,KAAK,YAAY,KAAK,aAAa;EACnC,KAAK,gBAAgB,KAAK,iBAAiB;EAE3C,KAAK,YAAY,CAAC;EAClB,KAAK,YAAY,KAAK,IAAI;EAG1B,KAAK,kBAAkB,kBAAkB;GACvC,KAAK,OAAO,CAAC,CAAC,OAAM,QAAO;IACzB,QAAQ,MAAM,mCAAmC,GAAG;GACtD,CAAC;EACH,GAAG,KAAK,aAAa;EACrB,KAAK,kBAAkB;CACzB;CAKA,oBAA4B;EAC1B,IAAI,KAAK,UAAU,SAAS,KAAK,KAAK,cACpC,KAAK,gBAAgB,MAAM;OAE3B,KAAK,gBAAgB,QAAQ;CAEjC;CAEA,MAAc,uBAAuB,UAAiC;EACpE,MAAM,WAAW,MAAM,MAAM,GAAG,KAAK,WAAW,YAAY;GAC1D,QA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AO,GAAG;IAC3B;IACA;IACA;IACA,SAAS,MAAM;GACjB;EACF,SAAS,OAAO;GACd,QAAQ,MAAM,6CAA6C,KAAK;GAChE,OAAO;IACL,MAAM,CAAC;IACP,OAAO;IACP;IACA;IACA,SAAS;GACX;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/loggers",
3
- "version": "1.3.9-alpha.1",
3
+ "version": "1.3.9",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [
@@ -75,9 +75,9 @@
75
75
  "tsx": "^4.23.1",
76
76
  "typescript": "^7.0.2",
77
77
  "vitest": "4.1.11",
78
- "@internal/lint": "0.0.144",
79
- "@internal/types-builder": "0.0.119",
80
- "@mastra/core": "1.79.0-alpha.4"
78
+ "@internal/lint": "0.0.145",
79
+ "@mastra/core": "1.79.0",
80
+ "@internal/types-builder": "0.0.120"
81
81
  },
82
82
  "peerDependencies": {
83
83
  "@mastra/core": ">=1.0.0-0 <2.0.0-0"