@tracewayapp/backend 0.2.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/traceway.ts","../src/collection-frame-store.ts","../src/typed-ring.ts","../src/metrics.ts","../src/stack-trace.ts","../src/context.ts"],"sourcesContent":["import {\n generateUUID,\n parseConnectionString,\n nowISO,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport type {\n TracewayOptions,\n ExceptionStackTrace,\n Trace,\n Span,\n} from \"@tracewayapp/core\";\nimport { CollectionFrameStore } from \"./collection-frame-store.js\";\nimport { formatErrorStackTrace } from \"./stack-trace.js\";\nimport {\n getTraceContext,\n getTraceId,\n addSpanToContext,\n type TraceContext,\n} from \"./context.js\";\nimport * as os from \"os\";\n\nlet store: CollectionFrameStore | null = null;\n\nfunction getHostname(): string {\n try {\n const hostname = os.hostname();\n const dotIdx = hostname.indexOf(\".\");\n return dotIdx >= 0 ? hostname.slice(0, dotIdx) : hostname;\n } catch {\n return \"unknown\";\n }\n}\n\nexport function init(\n connectionString: string,\n options: TracewayOptions = {},\n): void {\n if (store !== null) {\n throw new Error(\"Traceway: already initialized. Call shutdown() first.\");\n }\n\n const { token, apiUrl } = parseConnectionString(connectionString);\n\n store = new CollectionFrameStore({\n apiUrl,\n token,\n debug: options.debug ?? false,\n maxCollectionFrames: options.maxCollectionFrames ?? 12,\n collectionInterval: options.collectionInterval ?? 5000,\n uploadThrottle: options.uploadThrottle ?? 2000,\n metricsInterval: options.metricsInterval ?? 30000,\n version: options.version ?? \"\",\n serverName: options.serverName ?? getHostname(),\n sampleRate: options.sampleRate ?? 1,\n errorSampleRate: options.errorSampleRate ?? 1,\n });\n}\n\nexport function captureException(error: Error): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n captureExceptionWithAttributes(\n error,\n ctx?.attributes,\n ctx?.traceId,\n );\n}\n\nexport function captureExceptionWithAttributes(\n error: Error,\n attributes?: Record<string, string>,\n traceId?: string,\n): void {\n if (!store) return;\n // Auto-detect trace context if not explicitly provided\n const ctx = getTraceContext();\n const resolvedTraceId = traceId ?? ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: formatErrorStackTrace(error),\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: false,\n });\n}\n\nexport function captureMessage(\n msg: string,\n attributes?: Record<string, string>,\n): void {\n if (!store) return;\n // Auto-detect trace context\n const ctx = getTraceContext();\n const resolvedTraceId = ctx?.traceId ?? null;\n const resolvedAttrs = attributes ?? ctx?.attributes;\n const isTask = ctx?.isTask ?? false;\n\n store.addException({\n traceId: resolvedTraceId,\n isTask: isTask || undefined,\n stackTrace: msg,\n recordedAt: nowISO(),\n attributes: resolvedAttrs,\n isMessage: true,\n });\n}\n\nexport function captureMetric(name: string, value: number): void {\n if (!store) return;\n store.addMetric({\n name,\n value,\n recordedAt: nowISO(),\n });\n}\n\nexport function captureTrace(\n traceId: string,\n endpoint: string,\n durationMs: number,\n startedAt: Date,\n statusCode: number,\n bodySize: number,\n clientIP: string,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode,\n bodySize,\n clientIP,\n attributes,\n spans,\n });\n}\n\nexport function captureTask(\n traceId: string,\n taskName: string,\n durationMs: number,\n startedAt: Date,\n attributes?: Record<string, string>,\n spans?: Span[],\n): void {\n if (!store) return;\n store.addTrace({\n id: traceId,\n endpoint: taskName,\n duration: msToNanoseconds(durationMs),\n recordedAt: startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes,\n spans,\n isTask: true,\n });\n}\n\n/** Handle returned by startSpan for tracking span timing */\nexport interface SpanHandle {\n id: string;\n name: string;\n startTime: string;\n startedAt: number;\n}\n\n/**\n * Start a new span. If within a trace context, the span will be\n * automatically added to the trace when ended.\n */\nexport function startSpan(name: string): SpanHandle {\n const now = Date.now();\n return {\n id: generateUUID(),\n name,\n startTime: new Date(now).toISOString(),\n startedAt: now,\n };\n}\n\n/**\n * End a span and get the completed Span object.\n * If within a trace context, automatically adds the span to the trace.\n *\n * @param addToContext - If true (default), adds span to current trace context\n */\nexport function endSpan(span: SpanHandle, addToContext: boolean = true): Span {\n const durationMs = Date.now() - span.startedAt;\n const completedSpan: Span = {\n id: span.id,\n name: span.name,\n startTime: span.startTime,\n duration: msToNanoseconds(durationMs),\n };\n\n // Auto-add to trace context if available\n if (addToContext) {\n addSpanToContext(completedSpan);\n }\n\n return completedSpan;\n}\n\n/**\n * Capture the current trace context as a trace.\n * Call this at the end of a request/task to record the trace.\n *\n * @example\n * ```ts\n * // In Express middleware (after response)\n * withTraceContext({ endpoint: `${req.method} ${req.path}` }, async () => {\n * await handleRequest(req, res);\n * setTraceResponseInfo(res.statusCode, contentLength);\n * captureCurrentTrace(); // Records the trace with all spans\n * });\n * ```\n */\nexport function captureCurrentTrace(): void {\n if (!store) return;\n\n const ctx = getTraceContext();\n if (!ctx) return;\n\n const durationMs = Date.now() - ctx.startedAt.getTime();\n const isError = (ctx.statusCode ?? 0) >= 500;\n\n if (!shouldSample(isError)) return;\n\n if (ctx.isTask) {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown-task\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: 0,\n bodySize: 0,\n clientIP: \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n isTask: true,\n });\n } else {\n store.addTrace({\n id: ctx.traceId,\n endpoint: ctx.endpoint ?? \"unknown\",\n duration: msToNanoseconds(durationMs),\n recordedAt: ctx.startedAt.toISOString(),\n statusCode: ctx.statusCode ?? 0,\n bodySize: ctx.bodySize ?? 0,\n clientIP: ctx.clientIP ?? \"\",\n attributes: Object.keys(ctx.attributes).length > 0 ? ctx.attributes : undefined,\n spans: ctx.spans.length > 0 ? ctx.spans : undefined,\n });\n }\n}\n\nexport function shouldSample(isError: boolean): boolean {\n if (!store) return false;\n const rate = isError ? store.errorSampleRate : store.sampleRate;\n if (rate >= 1) return true;\n if (rate <= 0) return false;\n return Math.random() < rate;\n}\n\nexport function measureTask(\n title: string,\n fn: () => void | Promise<void>,\n): void {\n const traceId = generateUUID();\n const start = Date.now();\n const startDate = new Date(start);\n\n try {\n const result = fn();\n if (result && typeof (result as Promise<void>).then === \"function\") {\n (result as Promise<void>)\n .then(() => {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n })\n .catch((err: unknown) => {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n });\n } else {\n const durationMs = Date.now() - start;\n if (shouldSample(false)) {\n captureTask(traceId, title, durationMs, startDate);\n }\n }\n } catch (err) {\n const durationMs = Date.now() - start;\n if (shouldSample(true)) {\n captureTask(traceId, title, durationMs, startDate);\n if (err instanceof Error) {\n captureExceptionWithAttributes(err, undefined, traceId);\n }\n }\n throw err;\n }\n}\n\nexport async function shutdown(): Promise<void> {\n if (!store) return;\n const s = store;\n store = null;\n await s.shutdown();\n}\n","import * as zlib from \"zlib\";\nimport {\n nowISO,\n generateUUID,\n msToNanoseconds,\n} from \"@tracewayapp/core\";\nimport { TypedRing } from \"./typed-ring.js\";\nimport type {\n CollectionFrame,\n ExceptionStackTrace,\n MetricRecord,\n Trace,\n Span,\n ReportRequest,\n} from \"@tracewayapp/core\";\nimport { collectMetrics } from \"./metrics.js\";\n\nexport interface CollectionFrameStoreOptions {\n apiUrl: string;\n token: string;\n debug: boolean;\n maxCollectionFrames: number;\n collectionInterval: number;\n uploadThrottle: number;\n metricsInterval: number;\n version: string;\n serverName: string;\n sampleRate: number;\n errorSampleRate: number;\n}\n\nexport class CollectionFrameStore {\n private current: CollectionFrame | null = null;\n private currentSetAt: number = Date.now();\n private sendQueue: TypedRing<CollectionFrame>;\n private lastUploadStarted: number | null = null;\n\n private collectionTimer: ReturnType<typeof setInterval> | null = null;\n private metricsTimer: ReturnType<typeof setInterval> | null = null;\n\n private readonly apiUrl: string;\n private readonly token: string;\n private readonly debug: boolean;\n private readonly collectionInterval: number;\n private readonly uploadThrottle: number;\n private readonly metricsInterval: number;\n private readonly version: string;\n private readonly serverName: string;\n\n readonly sampleRate: number;\n readonly errorSampleRate: number;\n\n constructor(options: CollectionFrameStoreOptions) {\n this.apiUrl = options.apiUrl;\n this.token = options.token;\n this.debug = options.debug;\n this.collectionInterval = options.collectionInterval;\n this.uploadThrottle = options.uploadThrottle;\n this.metricsInterval = options.metricsInterval;\n this.version = options.version;\n this.serverName = options.serverName;\n this.sampleRate = options.sampleRate;\n this.errorSampleRate = options.errorSampleRate;\n this.sendQueue = new TypedRing<CollectionFrame>(\n options.maxCollectionFrames,\n );\n\n this.collectionTimer = setInterval(() => {\n this.tick();\n }, this.collectionInterval);\n if (this.collectionTimer && typeof this.collectionTimer.unref === \"function\") {\n this.collectionTimer.unref();\n }\n\n this.metricsTimer = setInterval(() => {\n this.collectSystemMetrics();\n }, this.metricsInterval);\n if (this.metricsTimer && typeof this.metricsTimer.unref === \"function\") {\n this.metricsTimer.unref();\n }\n }\n\n private tick(): void {\n if (this.current !== null) {\n if (this.currentSetAt < Date.now() - this.collectionInterval) {\n this.rotateCurrentCollectionFrame();\n this.processSendQueue();\n }\n } else if (this.sendQueue.length > 0) {\n this.processSendQueue();\n }\n }\n\n private ensureCurrent(): CollectionFrame {\n if (this.current === null) {\n this.current = { stackTraces: [], metrics: [], traces: [] };\n this.currentSetAt = Date.now();\n }\n return this.current;\n }\n\n addException(exception: ExceptionStackTrace): void {\n this.ensureCurrent().stackTraces.push(exception);\n }\n\n addMetric(metric: MetricRecord): void {\n this.ensureCurrent().metrics.push(metric);\n }\n\n addTrace(trace: Trace): void {\n this.ensureCurrent().traces.push(trace);\n }\n\n private rotateCurrentCollectionFrame(): void {\n if (this.current !== null) {\n this.sendQueue.push(this.current);\n this.current = null;\n }\n }\n\n private processSendQueue(): void {\n if (\n this.lastUploadStarted === null ||\n this.lastUploadStarted < Date.now() - this.uploadThrottle\n ) {\n this.lastUploadStarted = Date.now();\n const frames = this.sendQueue.readAll();\n if (frames.length > 0) {\n this.triggerUpload(frames);\n }\n }\n }\n\n private triggerUpload(framesToSend: CollectionFrame[]): void {\n const payload: ReportRequest = {\n collectionFrames: framesToSend,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n let jsonData: string;\n try {\n jsonData = JSON.stringify(payload);\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to serialize frames:\", err);\n }\n return;\n }\n\n let gzipped: Uint8Array;\n try {\n gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to gzip:\", err);\n }\n return;\n }\n\n fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n })\n .then((resp) => {\n if (resp.status === 200) {\n this.sendQueue.remove(framesToSend);\n } else if (this.debug) {\n console.error(`Traceway: upload returned status ${resp.status}`);\n }\n })\n .catch((err) => {\n if (this.debug) {\n console.error(\"Traceway: upload failed:\", err);\n }\n });\n }\n\n private collectSystemMetrics(): void {\n try {\n const metrics = collectMetrics();\n for (const metric of metrics) {\n this.addMetric(metric);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: failed to collect metrics:\", err);\n }\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.collectionTimer !== null) {\n clearInterval(this.collectionTimer);\n this.collectionTimer = null;\n }\n if (this.metricsTimer !== null) {\n clearInterval(this.metricsTimer);\n this.metricsTimer = null;\n }\n\n this.rotateCurrentCollectionFrame();\n\n const frames = this.sendQueue.readAll();\n if (frames.length === 0) return;\n\n const payload: ReportRequest = {\n collectionFrames: frames,\n appVersion: this.version,\n serverName: this.serverName,\n };\n\n try {\n const jsonData = JSON.stringify(payload);\n const gzipped = new Uint8Array(zlib.gzipSync(Buffer.from(jsonData)));\n\n const resp = await fetch(this.apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Encoding\": \"gzip\",\n Authorization: `Bearer ${this.token}`,\n },\n body: gzipped as unknown as BodyInit,\n });\n\n if (resp.status === 200) {\n this.sendQueue.remove(frames);\n }\n } catch (err) {\n if (this.debug) {\n console.error(\"Traceway: shutdown upload failed:\", err);\n }\n }\n }\n}\n","export class TypedRing<T> {\n private arr: (T | null)[];\n private head: number = 0;\n private _capacity: number;\n private _len: number = 0;\n\n constructor(capacity: number) {\n this._capacity = capacity;\n this.arr = new Array<T | null>(capacity).fill(null);\n }\n\n get length(): number {\n return this._len;\n }\n\n get capacity(): number {\n return this._capacity;\n }\n\n push(val: T): void {\n this.arr[this.head] = val;\n this.head = (this.head + 1) % this._capacity;\n if (this._len < this._capacity) {\n this._len += 1;\n }\n }\n\n readAll(): T[] {\n const result: T[] = [];\n for (let i = 0; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n result.push(this.arr[idx] as T);\n }\n return result;\n }\n\n clear(): void {\n for (let i = 0; i < this.arr.length; i++) {\n this.arr[i] = null;\n }\n this.head = 0;\n this._len = 0;\n }\n\n remove(vals: T[]): number {\n if (vals.length === 0) return 0;\n\n const toRemove = new Set<T>(vals);\n let writeIdx = 0;\n let removed = 0;\n\n for (let i = 0; i < this._len; i++) {\n const readIdx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n if (toRemove.has(this.arr[readIdx] as T)) {\n removed++;\n } else {\n if (writeIdx !== i) {\n const destIdx =\n (this.head - this._len + writeIdx + this._capacity) %\n this._capacity;\n this.arr[destIdx] = this.arr[readIdx];\n }\n writeIdx++;\n }\n }\n\n for (let i = writeIdx; i < this._len; i++) {\n const idx =\n (this.head - this._len + i + this._capacity) % this._capacity;\n this.arr[idx] = null;\n }\n\n this._len = writeIdx;\n this.head = (this.head - removed + this._capacity) % this._capacity;\n\n return removed;\n }\n}\n","import * as os from \"os\";\nimport { METRIC_MEM_USED, METRIC_MEM_TOTAL, METRIC_CPU_USED_PCNT } from \"@tracewayapp/core\";\nimport type { MetricRecord } from \"@tracewayapp/core\";\nimport { nowISO } from \"@tracewayapp/core\";\n\nlet prevCpuUsage: NodeJS.CpuUsage | null = null;\nlet prevCpuTime: number | null = null;\n\nexport function collectMetrics(): MetricRecord[] {\n const metrics: MetricRecord[] = [];\n const recordedAt = nowISO();\n\n const mem = process.memoryUsage();\n metrics.push({\n name: METRIC_MEM_USED,\n value: Math.round((mem.rss / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const totalMem = os.totalmem();\n metrics.push({\n name: METRIC_MEM_TOTAL,\n value: Math.round((totalMem / 1024 / 1024) * 100) / 100,\n recordedAt,\n });\n\n const currentCpuUsage = process.cpuUsage();\n const currentTime = Date.now();\n if (prevCpuUsage !== null && prevCpuTime !== null) {\n const elapsedMs = currentTime - prevCpuTime;\n if (elapsedMs > 0) {\n const userDelta = currentCpuUsage.user - prevCpuUsage.user;\n const systemDelta = currentCpuUsage.system - prevCpuUsage.system;\n const totalDeltaMs = (userDelta + systemDelta) / 1000;\n const cpuCount = os.cpus().length || 1;\n const cpuPercent = (totalDeltaMs / elapsedMs / cpuCount) * 100;\n metrics.push({\n name: METRIC_CPU_USED_PCNT,\n value: Math.round(cpuPercent * 100) / 100,\n recordedAt,\n });\n }\n }\n prevCpuUsage = currentCpuUsage;\n prevCpuTime = currentTime;\n\n return metrics;\n}\n\nexport function resetCpuTracking(): void {\n prevCpuUsage = null;\n prevCpuTime = null;\n}\n","export function formatErrorStackTrace(error: Error): string {\n const lines: string[] = [];\n\n const typeName = error.constructor.name || \"Error\";\n lines.push(`${typeName}: ${error.message}`);\n\n if (error.stack) {\n const stackLines = error.stack.split(\"\\n\");\n for (const line of stackLines) {\n const match = line.match(/^\\s+at\\s+(.+?)\\s+\\((.+):(\\d+):\\d+\\)$/);\n if (match) {\n const funcName = shortenFunctionName(match[1]);\n const file = shortenFilePath(match[2]);\n const lineNum = match[3];\n lines.push(`${funcName}()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchNoParens = line.match(/^\\s+at\\s+(.+):(\\d+):\\d+$/);\n if (matchNoParens) {\n const file = shortenFilePath(matchNoParens[1]);\n const lineNum = matchNoParens[2];\n lines.push(`<anonymous>()`);\n lines.push(` ${file}:${lineNum}`);\n continue;\n }\n\n const matchFnOnly = line.match(/^\\s+at\\s+(.+)$/);\n if (matchFnOnly) {\n const funcName = shortenFunctionName(matchFnOnly[1]);\n lines.push(`${funcName}()`);\n lines.push(` <unknown>:0`);\n }\n }\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nfunction shortenFunctionName(fn: string): string {\n const slashIdx = fn.lastIndexOf(\"/\");\n if (slashIdx >= 0) {\n fn = fn.slice(slashIdx + 1);\n }\n const dotIdx = fn.indexOf(\".\");\n if (dotIdx >= 0) {\n fn = fn.slice(dotIdx + 1);\n }\n return fn;\n}\n\nfunction shortenFilePath(filePath: string): string {\n const parts = filePath.split(\"/\");\n return parts[parts.length - 1];\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport { generateUUID } from \"@tracewayapp/core\";\nimport type { Span } from \"@tracewayapp/core\";\n\n/**\n * Trace context stored in AsyncLocalStorage.\n * Automatically propagates through async operations.\n */\nexport interface TraceContext {\n /** Unique trace identifier (UUID v4) */\n traceId: string;\n /** Whether this is a background task (vs HTTP request) */\n isTask: boolean;\n /** When the trace started */\n startedAt: Date;\n /** Collected spans within this trace */\n spans: Span[];\n /** Key-value attributes for this trace */\n attributes: Record<string, string>;\n /** For HTTP traces: endpoint like \"GET /api/users\" */\n endpoint?: string;\n /** For HTTP traces: response status code */\n statusCode?: number;\n /** For HTTP traces: response body size */\n bodySize?: number;\n /** For HTTP traces: client IP address */\n clientIP?: string;\n}\n\n/**\n * Options for creating a new trace context.\n */\nexport interface TraceContextOptions {\n /** Custom trace ID (auto-generated if not provided) */\n traceId?: string;\n /** Mark as background task instead of HTTP trace */\n isTask?: boolean;\n /** Initial attributes */\n attributes?: Record<string, string>;\n /** HTTP endpoint (e.g., \"GET /api/users\") */\n endpoint?: string;\n /** Client IP address */\n clientIP?: string;\n}\n\n// The AsyncLocalStorage instance for trace context\nconst asyncLocalStorage = new AsyncLocalStorage<TraceContext>();\n\n/**\n * Get the current trace context, if any.\n * Returns undefined if not within a trace context.\n */\nexport function getTraceContext(): TraceContext | undefined {\n return asyncLocalStorage.getStore();\n}\n\n/**\n * Get the current trace ID, if within a trace context.\n */\nexport function getTraceId(): string | undefined {\n return asyncLocalStorage.getStore()?.traceId;\n}\n\n/**\n * Check if currently within a trace context.\n */\nexport function hasTraceContext(): boolean {\n return asyncLocalStorage.getStore() !== undefined;\n}\n\n/**\n * Run a function within a new trace context.\n * All async operations within will have access to this context.\n *\n * @example\n * ```ts\n * // HTTP request handler\n * withTraceContext({ endpoint: \"GET /api/users\", clientIP: req.ip }, async () => {\n * const users = await db.query(\"SELECT * FROM users\");\n * captureException(new Error(\"oops\")); // Auto-linked to trace\n * return users;\n * });\n *\n * // Background task\n * withTraceContext({ isTask: true, endpoint: \"process-emails\" }, async () => {\n * await processEmails();\n * });\n * ```\n */\nexport function withTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T,\n): T {\n const context: TraceContext = {\n traceId: options.traceId ?? generateUUID(),\n isTask: options.isTask ?? false,\n startedAt: new Date(),\n spans: [],\n attributes: options.attributes ?? {},\n endpoint: options.endpoint,\n clientIP: options.clientIP,\n };\n return asyncLocalStorage.run(context, fn);\n}\n\n/**\n * Run a function within a trace context, automatically capturing the trace on completion.\n * This is a convenience wrapper that handles timing and capture automatically.\n *\n * @example\n * ```ts\n * // In Express middleware\n * app.use((req, res, next) => {\n * runWithTraceContext(\n * {\n * endpoint: `${req.method} ${req.path}`,\n * clientIP: req.ip,\n * attributes: { userId: req.user?.id },\n * },\n * async () => {\n * await next();\n * // Status code and body size set via setTraceResponseInfo()\n * },\n * { captureOnEnd: true }\n * );\n * });\n * ```\n */\nexport function runWithTraceContext<T>(\n options: TraceContextOptions,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return withTraceContext(options, fn);\n}\n\n/**\n * Add a completed span to the current trace context.\n * No-op if not within a trace context.\n */\nexport function addSpanToContext(span: Span): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.spans.push(span);\n }\n}\n\n/**\n * Set an attribute on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttribute(key: string, value: string): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.attributes[key] = value;\n }\n}\n\n/**\n * Set multiple attributes on the current trace context.\n * No-op if not within a trace context.\n */\nexport function setTraceAttributes(attributes: Record<string, string>): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n Object.assign(ctx.attributes, attributes);\n }\n}\n\n/**\n * Set HTTP response info on the current trace context.\n * Used by framework adapters after the response is sent.\n */\nexport function setTraceResponseInfo(\n statusCode: number,\n bodySize?: number,\n): void {\n const ctx = asyncLocalStorage.getStore();\n if (ctx) {\n ctx.statusCode = statusCode;\n ctx.bodySize = bodySize;\n }\n}\n\n/**\n * Get all spans from the current trace context.\n * Returns empty array if not within a trace context.\n */\nexport function getTraceSpans(): Span[] {\n return asyncLocalStorage.getStore()?.spans ?? [];\n}\n\n/**\n * Get the duration in milliseconds since the trace started.\n * Returns 0 if not within a trace context.\n */\nexport function getTraceDuration(): number {\n const ctx = asyncLocalStorage.getStore();\n if (!ctx) return 0;\n return Date.now() - ctx.startedAt.getTime();\n}\n\n/**\n * Fork the current trace context for a sub-operation.\n * Useful for parallel operations that should have isolated spans.\n * Returns undefined if not within a trace context.\n */\nexport function forkTraceContext<T>(fn: () => T): T | undefined {\n const parentCtx = asyncLocalStorage.getStore();\n if (!parentCtx) return undefined;\n\n const forkedContext: TraceContext = {\n ...parentCtx,\n spans: [], // Forked context gets its own spans\n attributes: { ...parentCtx.attributes },\n };\n\n return asyncLocalStorage.run(forkedContext, () => {\n const result = fn();\n // Merge spans back to parent after completion\n parentCtx.spans.push(...forkedContext.spans);\n return result;\n });\n}\n\n// Export the AsyncLocalStorage instance for advanced use cases\nexport { asyncLocalStorage as traceContextStorage };\n"],"mappings":";AAAA;AAAA,EACE,gBAAAA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA;AAAA,OACK;;;ACLP,YAAY,UAAU;;;ACAf,IAAM,YAAN,MAAmB;AAAA,EAChB;AAAA,EACA,OAAe;AAAA,EACf;AAAA,EACA,OAAe;AAAA,EAEvB,YAAY,UAAkB;AAC5B,SAAK,YAAY;AACjB,SAAK,MAAM,IAAI,MAAgB,QAAQ,EAAE,KAAK,IAAI;AAAA,EACpD;AAAA,EAEA,IAAI,SAAiB;AACnB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,WAAmB;AACrB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,KAAK,KAAc;AACjB,SAAK,IAAI,KAAK,IAAI,IAAI;AACtB,SAAK,QAAQ,KAAK,OAAO,KAAK,KAAK;AACnC,QAAI,KAAK,OAAO,KAAK,WAAW;AAC9B,WAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA,EAEA,UAAe;AACb,UAAM,SAAc,CAAC;AACrB,aAAS,IAAI,GAAG,IAAI,KAAK,MAAM,KAAK;AAClC,YAAM,OACH,KAAK,OAAO,KAAK,OAAO,IAAI,KAAK,aAAa,KAAK;AACtD,aAAO,KAAK,KAAK,IAAI,GAAG,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AC,OACE,KAAK,MAAM;AACV,cAAM,aAAa,KAAK,IAAI,IAAI;AAChC,YAAI,aAAa,KAAK,GAAG;AACvB,sBAAY,SAAS,OAAO,YAAY,SAAS;AAAA,QACnD;AAAA,MACF,CAAC,EACA,MAAM,CAAC,QAAiB;AACvB,cAAM,aAAa,KAAK,IAAI,IAAI;AAChC,YAAI,aAAa,IAAI,GAAG;AACtB,sBAAY,SAAS,OAAO,YAAY,SAAS;AACjD,cAAI,eAAe,OAAO;AACxB,2CAA+B,KAAK,QAAW,OAAO;AAAA,UACxD;AAAA,QACF;AACA,cAAM;AAAA,MACR,CAAC;AAAA,IACL,OAAO;AACL,YAAM,aAAa,KAAK,IAAI,IAAI;AAChC,UAAI,aAAa,KAAK,GAAG;AACvB,oBAAY,SAAS,OAAO,YAAY,SAAS;AAAA,MACnD;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,UAAM,aAAa,KAAK,IAAI,IAAI;AAChC,QAAI,aAAa,IAAI,GAAG;AACtB,kBAAY,SAAS,OAAO,YAAY,SAAS;AACjD,UAAI,eAAe,OAAO;AACxB,uCAA+B,KAAK,QAAW,OAAO;AAAA,MACxD;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACF;AAEA,eAAsB,WAA0B;AAC9C,MAAI,CAAC,MAAO;AACZ,QAAM,IAAI;AACV,UAAQ;AACR,QAAM,EAAE,SAAS;AACnB;","names":["generateUUID","nowISO","os","hostname","nowISO","generateUUID"]}
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@tracewayapp/backend",
3
+ "version": "0.2.0",
4
+ "description": "Traceway SDK for Node.js backends",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "scripts": {
22
+ "build": "tsup",
23
+ "dev": "tsup --watch"
24
+ },
25
+ "dependencies": {
26
+ "@tracewayapp/core": "0.2.0"
27
+ }
28
+ }