autotel 2.25.3 → 2.25.5

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.
Files changed (68) hide show
  1. package/dist/{chunk-FXKB7EPR.cjs → chunk-A5ZUL2RZ.cjs} +5 -5
  2. package/dist/{chunk-FXKB7EPR.cjs.map → chunk-A5ZUL2RZ.cjs.map} +1 -1
  3. package/dist/{chunk-SR35DG5A.js → chunk-BBBWDIYQ.js} +27 -13
  4. package/dist/chunk-BBBWDIYQ.js.map +1 -0
  5. package/dist/{chunk-3ZLYWPMY.js → chunk-CMUM4JQI.js} +3 -3
  6. package/dist/{chunk-3ZLYWPMY.js.map → chunk-CMUM4JQI.js.map} +1 -1
  7. package/dist/{chunk-AQXPGGQK.cjs → chunk-EEJGUBWV.cjs} +5 -5
  8. package/dist/{chunk-AQXPGGQK.cjs.map → chunk-EEJGUBWV.cjs.map} +1 -1
  9. package/dist/{chunk-W4EUTSB2.cjs → chunk-HZ3FYBJG.cjs} +27 -12
  10. package/dist/chunk-HZ3FYBJG.cjs.map +1 -0
  11. package/dist/{chunk-WOWTZ4EB.cjs → chunk-I6JPSD4R.cjs} +5 -5
  12. package/dist/{chunk-WOWTZ4EB.cjs.map → chunk-I6JPSD4R.cjs.map} +1 -1
  13. package/dist/{chunk-XRKAL7WJ.cjs → chunk-JSNUWSBH.cjs} +6 -6
  14. package/dist/chunk-JSNUWSBH.cjs.map +1 -0
  15. package/dist/{chunk-OWXXS4JB.cjs → chunk-MN6PZ4AN.cjs} +7 -7
  16. package/dist/{chunk-OWXXS4JB.cjs.map → chunk-MN6PZ4AN.cjs.map} +1 -1
  17. package/dist/{chunk-JM63D22M.js → chunk-OPTGXEVN.js} +368 -349
  18. package/dist/chunk-OPTGXEVN.js.map +1 -0
  19. package/dist/{chunk-PKXD2RMI.js → chunk-QDREXAD7.js} +3 -3
  20. package/dist/{chunk-PKXD2RMI.js.map → chunk-QDREXAD7.js.map} +1 -1
  21. package/dist/{chunk-RMGSBMQF.cjs → chunk-QQLP4M6W.cjs} +372 -353
  22. package/dist/chunk-QQLP4M6W.cjs.map +1 -0
  23. package/dist/{chunk-USSL3D6L.js → chunk-S4OFEXLA.js} +6 -6
  24. package/dist/chunk-S4OFEXLA.js.map +1 -0
  25. package/dist/{chunk-VVYSQXQL.js → chunk-WYP6OOCT.js} +3 -3
  26. package/dist/{chunk-VVYSQXQL.js.map → chunk-WYP6OOCT.js.map} +1 -1
  27. package/dist/{chunk-IFKDBL65.js → chunk-XB2GITM5.js} +3 -3
  28. package/dist/{chunk-IFKDBL65.js.map → chunk-XB2GITM5.js.map} +1 -1
  29. package/dist/correlation-id.cjs +10 -9
  30. package/dist/correlation-id.d.cts +4 -1
  31. package/dist/correlation-id.d.ts +4 -1
  32. package/dist/correlation-id.js +2 -1
  33. package/dist/decorators.cjs +4 -4
  34. package/dist/decorators.js +3 -3
  35. package/dist/event.cjs +6 -5
  36. package/dist/event.js +3 -2
  37. package/dist/functional.cjs +10 -10
  38. package/dist/functional.js +3 -3
  39. package/dist/http.cjs +2 -2
  40. package/dist/http.js +1 -1
  41. package/dist/index.cjs +45 -45
  42. package/dist/index.js +10 -10
  43. package/dist/messaging.cjs +7 -7
  44. package/dist/messaging.js +4 -4
  45. package/dist/semantic-helpers.cjs +8 -8
  46. package/dist/semantic-helpers.js +4 -4
  47. package/dist/test-span-collector.cjs.map +1 -1
  48. package/dist/test-span-collector.d.cts +5 -2
  49. package/dist/test-span-collector.d.ts +5 -2
  50. package/dist/test-span-collector.js.map +1 -1
  51. package/dist/webhook.cjs +4 -4
  52. package/dist/webhook.js +3 -3
  53. package/dist/workflow-distributed.cjs +5 -5
  54. package/dist/workflow-distributed.js +3 -3
  55. package/dist/workflow.cjs +8 -8
  56. package/dist/workflow.js +4 -4
  57. package/package.json +1 -1
  58. package/src/correlation-id.ts +10 -5
  59. package/src/functional.ts +440 -420
  60. package/src/test-span-collector.ts +5 -2
  61. package/src/trace-context.test.ts +73 -0
  62. package/src/trace-context.ts +44 -12
  63. package/dist/chunk-JM63D22M.js.map +0 -1
  64. package/dist/chunk-RMGSBMQF.cjs.map +0 -1
  65. package/dist/chunk-SR35DG5A.js.map +0 -1
  66. package/dist/chunk-USSL3D6L.js.map +0 -1
  67. package/dist/chunk-W4EUTSB2.cjs.map +0 -1
  68. package/dist/chunk-XRKAL7WJ.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/semantic-helpers.ts"],"names":[],"mappings":";;;AAiLO,SAAS,SAA2C,MAAA,EAAmB;AAC5E,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,sBAAA,EAAwB,MAAA,CAAO,KAAK,CAAA;AACrD,MAAA,GAAA,CAAI,YAAA,CAAa,uBAAA,EAAyB,MAAA,CAAO,SAAA,IAAa,MAAM,CAAA;AACpE,MAAA,IAAI,OAAO,QAAA,EAAU;AACnB,QAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,MAAA,CAAO,QAAQ,CAAA;AAAA,MACnD;AACA,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;A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,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-3ZLYWPMY.js","sourcesContent":["/**\n * Semantic convention helpers for OpenTelemetry\n *\n * Pre-configured trace helpers that follow OpenTelemetry semantic conventions\n * for common operation types. Reduces boilerplate and ensures consistency.\n *\n * Based on: https://opentelemetry.io/docs/specs/semconv/\n */\n\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport type { Attributes } from '@opentelemetry/api';\n\n/**\n * Configuration for LLM (Large Language Model) operations\n *\n * Follows Gen AI semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport interface LLMConfig {\n /** Model name (e.g., 'gpt-4', 'claude-3-opus') */\n model: string;\n /** Operation type */\n operation?: 'chat' | 'completion' | 'embedding';\n /** Model provider (e.g., 'openai', 'anthropic', 'cohere') - maps to gen.ai.system */\n provider?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for database operations\n *\n * Follows DB semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/database/\n */\nexport interface DBConfig {\n /** Database system (e.g., 'postgresql', 'mongodb', 'redis') */\n system: string;\n /** Operation type (e.g., 'SELECT', 'INSERT', 'find', 'get') */\n operation?: string;\n /** Database name */\n database?: string;\n /** Collection/table name */\n collection?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for HTTP client operations\n *\n * Follows HTTP semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/http/\n */\nexport interface HTTPConfig {\n /** HTTP method (e.g., 'GET', 'POST') */\n method?: string;\n /** Target URL or URL template */\n url?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for messaging operations\n *\n * Follows Messaging semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/messaging/\n */\nexport interface MessagingConfig {\n /** Messaging system (e.g., 'kafka', 'rabbitmq', 'sqs') */\n system: string;\n /** Operation type */\n operation?: 'publish' | 'receive' | 'process';\n /** Destination name (queue/topic) */\n destination?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Trace LLM operations with Gen AI semantic conventions\n *\n * Automatically adds standard attributes for LLM operations:\n * - gen.ai.request.model\n * - gen.ai.operation.name\n * - gen.ai.system\n *\n * **Use Cases:**\n * - Chat completions\n * - Text generation\n * - Embeddings\n * - Multi-step LLM workflows\n *\n * @param config - LLM operation configuration\n * @returns Traced function factory with Gen AI attributes\n *\n * @example Chat completion with OpenAI\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import OpenAI from 'openai'\n *\n * const openai = new OpenAI()\n *\n * export const generateResponse = traceLLM({\n * model: 'gpt-4-turbo',\n * operation: 'chat',\n * provider: 'openai'\n * })(ctx => async (prompt: string) => {\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4-turbo',\n * messages: [{ role: 'user', content: prompt }]\n * })\n *\n * // Add usage metrics to span\n * ctx.setAttribute('gen.ai.usage.completion_tokens', response.usage?.completion_tokens)\n * ctx.setAttribute('gen.ai.usage.prompt_tokens', response.usage?.prompt_tokens)\n *\n * return response.choices[0].message.content\n * })\n * ```\n *\n * @example Anthropic Claude with streaming\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import Anthropic from '@anthropic-ai/sdk'\n *\n * const anthropic = new Anthropic()\n *\n * export const streamResponse = traceLLM({\n * model: 'claude-3-opus-20240229',\n * operation: 'chat',\n * provider: 'anthropic'\n * })(ctx => async function* (prompt: string) {\n * const stream = await anthropic.messages.create({\n * model: 'claude-3-opus-20240229',\n * messages: [{ role: 'user', content: prompt }],\n * stream: true,\n * max_tokens: 1024\n * })\n *\n * let totalTokens = 0\n * for await (const event of stream) {\n * if (event.type === 'content_block_delta') {\n * yield event.delta.text\n * }\n * if (event.type === 'message_stop') {\n * ctx.setAttribute('gen.ai.usage.completion_tokens', event.message.usage.output_tokens)\n * totalTokens = event.message.usage.output_tokens\n * }\n * }\n *\n * return totalTokens\n * })\n * ```\n *\n * @example Embeddings\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import { OpenAIEmbeddings } from '@langchain/openai'\n *\n * const embeddings = new OpenAIEmbeddings()\n *\n * export const embed = traceLLM({\n * model: 'text-embedding-3-small',\n * operation: 'embedding',\n * provider: 'openai'\n * })(ctx => async (text: string) => {\n * const result = await embeddings.embedQuery(text)\n * ctx.setAttribute('gen.ai.response.embedding_length', result.length)\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceLLM<TArgs extends unknown[], TReturn>(config: LLMConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('gen.ai.request.model', config.model);\n ctx.setAttribute('gen.ai.operation.name', config.operation || 'chat');\n if (config.provider) {\n ctx.setAttribute('gen.ai.system', config.provider);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace database operations with DB semantic conventions\n *\n * Automatically adds standard attributes for database operations:\n * - db.system\n * - db.operation\n * - db.name\n * - db.collection.name (for NoSQL)\n *\n * **Use Cases:**\n * - SQL queries (PostgreSQL, MySQL, SQLite)\n * - NoSQL operations (MongoDB, DynamoDB, Redis)\n * - ORM queries (Prisma, TypeORM, Drizzle)\n *\n * @param config - Database operation configuration\n * @returns Traced function factory with DB attributes\n *\n * @example PostgreSQL query\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { pool } from './db'\n *\n * export const getUser = traceDB({\n * system: 'postgresql',\n * operation: 'SELECT',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (userId: string) => {\n * const query = 'SELECT * FROM users WHERE id = $1'\n * ctx.setAttribute('db.statement', query)\n *\n * const result = await pool.query(query, [userId])\n * ctx.setAttribute('db.rows_affected', result.rowCount)\n *\n * return result.rows[0]\n * })\n * ```\n *\n * @example MongoDB with Mongoose\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { User } from './models/User'\n *\n * export const findUsers = traceDB({\n * system: 'mongodb',\n * operation: 'find',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (filter: object) => {\n * ctx.setAttribute('db.mongodb.filter', JSON.stringify(filter))\n *\n * const users = await User.find(filter).limit(100)\n * ctx.setAttribute('db.response.count', users.length)\n *\n * return users\n * })\n * ```\n *\n * @example Redis operations\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { redis } from './redis'\n *\n * export const cacheGet = traceDB({\n * system: 'redis',\n * operation: 'GET'\n * })(ctx => async (key: string) => {\n * ctx.setAttribute('db.redis.key', key)\n *\n * const value = await redis.get(key)\n * ctx.setAttribute('db.response.cache_hit', value !== null)\n *\n * return value\n * })\n * ```\n *\n * @example Prisma with detailed query info\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { prisma } from './prisma'\n *\n * export const createPost = traceDB({\n * system: 'postgresql',\n * operation: 'INSERT',\n * database: 'app_db',\n * collection: 'posts'\n * })(ctx => async (data: { title: string; content: string; authorId: string }) => {\n * ctx.setAttribute('db.prisma.model', 'Post')\n * ctx.setAttribute('db.prisma.action', 'create')\n *\n * const post = await prisma.post.create({ data })\n *\n * ctx.setAttribute('db.response.id', post.id)\n * return post\n * })\n * ```\n *\n * @public\n */\nexport function traceDB<TArgs extends unknown[], TReturn>(config: DBConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('db.system', config.system);\n if (config.operation) {\n ctx.setAttribute('db.operation', config.operation);\n }\n if (config.database) {\n ctx.setAttribute('db.name', config.database);\n }\n if (config.collection) {\n ctx.setAttribute('db.collection.name', config.collection);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace HTTP client operations with HTTP semantic conventions\n *\n * Automatically adds standard attributes for HTTP requests:\n * - http.request.method\n * - url.full\n *\n * **Use Cases:**\n * - External API calls\n * - Microservice communication\n * - Third-party integrations\n *\n * @param config - HTTP operation configuration\n * @returns Traced function factory with HTTP attributes\n *\n * @example Fetch API\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n *\n * export const fetchUser = traceHTTP({\n * method: 'GET',\n * url: 'https://api.example.com/users/:id'\n * })(ctx => async (userId: string) => {\n * const url = `https://api.example.com/users/${userId}`\n * ctx.setAttribute('url.full', url)\n *\n * const response = await fetch(url)\n * ctx.setAttribute('http.response.status_code', response.status)\n *\n * if (!response.ok) {\n * ctx.setAttribute('error', true)\n * throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n * }\n *\n * return response.json()\n * })\n * ```\n *\n * @example Axios with retry logic\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n * import axios from 'axios'\n *\n * export const sendWebhook = traceHTTP({\n * method: 'POST',\n * url: 'https://webhook.example.com/events'\n * })(ctx => async (payload: object) => {\n * let attempts = 0\n * const maxAttempts = 3\n *\n * while (attempts < maxAttempts) {\n * try {\n * attempts++\n * ctx.setAttribute('http.request.resend_count', attempts - 1)\n *\n * const response = await axios.post('https://webhook.example.com/events', payload)\n * ctx.setAttribute('http.response.status_code', response.status)\n * return response.data\n * } catch (error) {\n * if (attempts >= maxAttempts) throw error\n * await new Promise(resolve => setTimeout(resolve, 1000 * attempts))\n * }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function traceHTTP<TArgs extends unknown[], TReturn>(\n config: HTTPConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n if (config.method) {\n ctx.setAttribute('http.request.method', config.method);\n }\n if (config.url) {\n ctx.setAttribute('url.full', config.url);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace messaging operations with Messaging semantic conventions\n *\n * Automatically adds standard attributes for messaging:\n * - messaging.system\n * - messaging.operation\n * - messaging.destination.name\n *\n * **Use Cases:**\n * - Publishing messages to queues/topics\n * - Consuming messages from queues/topics\n * - Event-driven architectures\n *\n * @param config - Messaging operation configuration\n * @returns Traced function factory with Messaging attributes\n *\n * @example Publishing to Kafka\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { kafka } from './kafka'\n *\n * const producer = kafka.producer()\n *\n * export const publishEvent = traceMessaging({\n * system: 'kafka',\n * operation: 'publish',\n * destination: 'user-events'\n * })(ctx => async (event: { type: string; userId: string; data: object }) => {\n * ctx.setAttribute('messaging.message.type', event.type)\n * ctx.setAttribute('messaging.kafka.partition', 0)\n *\n * await producer.send({\n * topic: 'user-events',\n * messages: [\n * {\n * key: event.userId,\n * value: JSON.stringify(event.data)\n * }\n * ]\n * })\n *\n * ctx.setAttribute('messaging.message.id', event.userId)\n * })\n * ```\n *\n * @example Consuming from RabbitMQ\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { channel } from './rabbitmq'\n *\n * export const processOrder = traceMessaging({\n * system: 'rabbitmq',\n * operation: 'process',\n * destination: 'orders'\n * })(ctx => async (message: { orderId: string; items: object[] }) => {\n * ctx.setAttribute('messaging.message.id', message.orderId)\n * ctx.setAttribute('messaging.message.body.size', JSON.stringify(message).length)\n *\n * // Process order logic\n * const result = await processOrderInternal(message)\n *\n * ctx.setAttribute('messaging.operation.result', 'success')\n * return result\n * })\n * ```\n *\n * @example AWS SQS with batch processing\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { SQS } from '@aws-sdk/client-sqs'\n *\n * const sqs = new SQS()\n *\n * export const sendBatch = traceMessaging({\n * system: 'aws_sqs',\n * operation: 'publish',\n * destination: 'notifications-queue'\n * })(ctx => async (messages: Array<{ id: string; body: object }>) => {\n * ctx.setAttribute('messaging.batch.message_count', messages.length)\n *\n * const result = await sqs.sendMessageBatch({\n * QueueUrl: process.env.QUEUE_URL,\n * Entries: messages.map(msg => ({\n * Id: msg.id,\n * MessageBody: JSON.stringify(msg.body)\n * }))\n * })\n *\n * ctx.setAttribute('messaging.operation.success_count', result.Successful?.length || 0)\n * ctx.setAttribute('messaging.operation.failed_count', result.Failed?.length || 0)\n *\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceMessaging<TArgs extends unknown[], TReturn>(\n config: MessagingConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('messaging.system', config.system);\n if (config.operation) {\n ctx.setAttribute('messaging.operation', config.operation);\n }\n if (config.destination) {\n ctx.setAttribute('messaging.destination.name', config.destination);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/semantic-helpers.ts"],"names":[],"mappings":";;;AAiLO,SAAS,SAA2C,MAAA,EAAmB;AAC5E,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,sBAAA,EAAwB,MAAA,CAAO,KAAK,CAAA;AACrD,MAAA,GAAA,CAAI,YAAA,CAAa,uBAAA,EAAyB,MAAA,CAAO,SAAA,IAAa,MAAM,CAAA;AACpE,MAAA,IAAI,OAAO,QAAA,EAAU;AACnB,QAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,MAAA,CAAO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QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF;AAmGO,SAAS,eACd,MAAA,EACA;AACA,EAAA,OAAO,CACL,SAAA,KAC2C;AAC3C,IAAA,OAAO,KAAA,CAAsB,CAAC,GAAA,KAAQ;AAEpC,MAAA,GAAA,CAAI,YAAA,CAAa,kBAAA,EAAoB,MAAA,CAAO,MAAM,CAAA;AAClD,MAAA,IAAI,OAAO,SAAA,EAAW;AACpB,QAAA,GAAA,CAAI,YAAA,CAAa,qBAAA,EAAuB,MAAA,CAAO,SAAS,CAAA;AAAA,MAC1D;AACA,MAAA,IAAI,OAAO,WAAA,EAAa;AACtB,QAAA,GAAA,CAAI,YAAA,CAAa,4BAAA,EAA8B,MAAA,CAAO,WAAW,CAAA;AAAA,MACnE;AACA,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AAC5D,UAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAGzC,YAAA,MAAM,SAAA,GACJ,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,QAAA,IACjB,OAAO,KAAA,KAAU,SAAA,GACb,KAAA,GACA,IAAA,CAAK,UAAU,KAAK,CAAA;AAC1B,YAAA,GAAA,CAAI,YAAA,CAAa,KAAK,SAAS,CAAA;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,MAAA,OAAO,UAAU,GAAG,CAAA;AAAA,IACtB,CAAC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-CMUM4JQI.js","sourcesContent":["/**\n * Semantic convention helpers for OpenTelemetry\n *\n * Pre-configured trace helpers that follow OpenTelemetry semantic conventions\n * for common operation types. Reduces boilerplate and ensures consistency.\n *\n * Based on: https://opentelemetry.io/docs/specs/semconv/\n */\n\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport type { Attributes } from '@opentelemetry/api';\n\n/**\n * Configuration for LLM (Large Language Model) operations\n *\n * Follows Gen AI semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport interface LLMConfig {\n /** Model name (e.g., 'gpt-4', 'claude-3-opus') */\n model: string;\n /** Operation type */\n operation?: 'chat' | 'completion' | 'embedding';\n /** Model provider (e.g., 'openai', 'anthropic', 'cohere') - maps to gen.ai.system */\n provider?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for database operations\n *\n * Follows DB semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/database/\n */\nexport interface DBConfig {\n /** Database system (e.g., 'postgresql', 'mongodb', 'redis') */\n system: string;\n /** Operation type (e.g., 'SELECT', 'INSERT', 'find', 'get') */\n operation?: string;\n /** Database name */\n database?: string;\n /** Collection/table name */\n collection?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for HTTP client operations\n *\n * Follows HTTP semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/http/\n */\nexport interface HTTPConfig {\n /** HTTP method (e.g., 'GET', 'POST') */\n method?: string;\n /** Target URL or URL template */\n url?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Configuration for messaging operations\n *\n * Follows Messaging semantic conventions:\n * https://opentelemetry.io/docs/specs/semconv/messaging/\n */\nexport interface MessagingConfig {\n /** Messaging system (e.g., 'kafka', 'rabbitmq', 'sqs') */\n system: string;\n /** Operation type */\n operation?: 'publish' | 'receive' | 'process';\n /** Destination name (queue/topic) */\n destination?: string;\n /** Additional attributes to add to the span */\n attributes?: Attributes;\n}\n\n/**\n * Trace LLM operations with Gen AI semantic conventions\n *\n * Automatically adds standard attributes for LLM operations:\n * - gen.ai.request.model\n * - gen.ai.operation.name\n * - gen.ai.system\n *\n * **Use Cases:**\n * - Chat completions\n * - Text generation\n * - Embeddings\n * - Multi-step LLM workflows\n *\n * @param config - LLM operation configuration\n * @returns Traced function factory with Gen AI attributes\n *\n * @example Chat completion with OpenAI\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import OpenAI from 'openai'\n *\n * const openai = new OpenAI()\n *\n * export const generateResponse = traceLLM({\n * model: 'gpt-4-turbo',\n * operation: 'chat',\n * provider: 'openai'\n * })(ctx => async (prompt: string) => {\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4-turbo',\n * messages: [{ role: 'user', content: prompt }]\n * })\n *\n * // Add usage metrics to span\n * ctx.setAttribute('gen.ai.usage.completion_tokens', response.usage?.completion_tokens)\n * ctx.setAttribute('gen.ai.usage.prompt_tokens', response.usage?.prompt_tokens)\n *\n * return response.choices[0].message.content\n * })\n * ```\n *\n * @example Anthropic Claude with streaming\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import Anthropic from '@anthropic-ai/sdk'\n *\n * const anthropic = new Anthropic()\n *\n * export const streamResponse = traceLLM({\n * model: 'claude-3-opus-20240229',\n * operation: 'chat',\n * provider: 'anthropic'\n * })(ctx => async function* (prompt: string) {\n * const stream = await anthropic.messages.create({\n * model: 'claude-3-opus-20240229',\n * messages: [{ role: 'user', content: prompt }],\n * stream: true,\n * max_tokens: 1024\n * })\n *\n * let totalTokens = 0\n * for await (const event of stream) {\n * if (event.type === 'content_block_delta') {\n * yield event.delta.text\n * }\n * if (event.type === 'message_stop') {\n * ctx.setAttribute('gen.ai.usage.completion_tokens', event.message.usage.output_tokens)\n * totalTokens = event.message.usage.output_tokens\n * }\n * }\n *\n * return totalTokens\n * })\n * ```\n *\n * @example Embeddings\n * ```typescript\n * import { traceLLM } from 'autotel/semantic-helpers'\n * import { OpenAIEmbeddings } from '@langchain/openai'\n *\n * const embeddings = new OpenAIEmbeddings()\n *\n * export const embed = traceLLM({\n * model: 'text-embedding-3-small',\n * operation: 'embedding',\n * provider: 'openai'\n * })(ctx => async (text: string) => {\n * const result = await embeddings.embedQuery(text)\n * ctx.setAttribute('gen.ai.response.embedding_length', result.length)\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceLLM<TArgs extends unknown[], TReturn>(config: LLMConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('gen.ai.request.model', config.model);\n ctx.setAttribute('gen.ai.operation.name', config.operation || 'chat');\n if (config.provider) {\n ctx.setAttribute('gen.ai.system', config.provider);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace database operations with DB semantic conventions\n *\n * Automatically adds standard attributes for database operations:\n * - db.system\n * - db.operation\n * - db.name\n * - db.collection.name (for NoSQL)\n *\n * **Use Cases:**\n * - SQL queries (PostgreSQL, MySQL, SQLite)\n * - NoSQL operations (MongoDB, DynamoDB, Redis)\n * - ORM queries (Prisma, TypeORM, Drizzle)\n *\n * @param config - Database operation configuration\n * @returns Traced function factory with DB attributes\n *\n * @example PostgreSQL query\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { pool } from './db'\n *\n * export const getUser = traceDB({\n * system: 'postgresql',\n * operation: 'SELECT',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (userId: string) => {\n * const query = 'SELECT * FROM users WHERE id = $1'\n * ctx.setAttribute('db.statement', query)\n *\n * const result = await pool.query(query, [userId])\n * ctx.setAttribute('db.rows_affected', result.rowCount)\n *\n * return result.rows[0]\n * })\n * ```\n *\n * @example MongoDB with Mongoose\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { User } from './models/User'\n *\n * export const findUsers = traceDB({\n * system: 'mongodb',\n * operation: 'find',\n * database: 'app_db',\n * collection: 'users'\n * })(ctx => async (filter: object) => {\n * ctx.setAttribute('db.mongodb.filter', JSON.stringify(filter))\n *\n * const users = await User.find(filter).limit(100)\n * ctx.setAttribute('db.response.count', users.length)\n *\n * return users\n * })\n * ```\n *\n * @example Redis operations\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { redis } from './redis'\n *\n * export const cacheGet = traceDB({\n * system: 'redis',\n * operation: 'GET'\n * })(ctx => async (key: string) => {\n * ctx.setAttribute('db.redis.key', key)\n *\n * const value = await redis.get(key)\n * ctx.setAttribute('db.response.cache_hit', value !== null)\n *\n * return value\n * })\n * ```\n *\n * @example Prisma with detailed query info\n * ```typescript\n * import { traceDB } from 'autotel/semantic-helpers'\n * import { prisma } from './prisma'\n *\n * export const createPost = traceDB({\n * system: 'postgresql',\n * operation: 'INSERT',\n * database: 'app_db',\n * collection: 'posts'\n * })(ctx => async (data: { title: string; content: string; authorId: string }) => {\n * ctx.setAttribute('db.prisma.model', 'Post')\n * ctx.setAttribute('db.prisma.action', 'create')\n *\n * const post = await prisma.post.create({ data })\n *\n * ctx.setAttribute('db.response.id', post.id)\n * return post\n * })\n * ```\n *\n * @public\n */\nexport function traceDB<TArgs extends unknown[], TReturn>(config: DBConfig) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('db.system', config.system);\n if (config.operation) {\n ctx.setAttribute('db.operation', config.operation);\n }\n if (config.database) {\n ctx.setAttribute('db.name', config.database);\n }\n if (config.collection) {\n ctx.setAttribute('db.collection.name', config.collection);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace HTTP client operations with HTTP semantic conventions\n *\n * Automatically adds standard attributes for HTTP requests:\n * - http.request.method\n * - url.full\n *\n * **Use Cases:**\n * - External API calls\n * - Microservice communication\n * - Third-party integrations\n *\n * @param config - HTTP operation configuration\n * @returns Traced function factory with HTTP attributes\n *\n * @example Fetch API\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n *\n * export const fetchUser = traceHTTP({\n * method: 'GET',\n * url: 'https://api.example.com/users/:id'\n * })(ctx => async (userId: string) => {\n * const url = `https://api.example.com/users/${userId}`\n * ctx.setAttribute('url.full', url)\n *\n * const response = await fetch(url)\n * ctx.setAttribute('http.response.status_code', response.status)\n *\n * if (!response.ok) {\n * ctx.setAttribute('error', true)\n * throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n * }\n *\n * return response.json()\n * })\n * ```\n *\n * @example Axios with retry logic\n * ```typescript\n * import { traceHTTP } from 'autotel/semantic-helpers'\n * import axios from 'axios'\n *\n * export const sendWebhook = traceHTTP({\n * method: 'POST',\n * url: 'https://webhook.example.com/events'\n * })(ctx => async (payload: object) => {\n * let attempts = 0\n * const maxAttempts = 3\n *\n * while (attempts < maxAttempts) {\n * try {\n * attempts++\n * ctx.setAttribute('http.request.resend_count', attempts - 1)\n *\n * const response = await axios.post('https://webhook.example.com/events', payload)\n * ctx.setAttribute('http.response.status_code', response.status)\n * return response.data\n * } catch (error) {\n * if (attempts >= maxAttempts) throw error\n * await new Promise(resolve => setTimeout(resolve, 1000 * attempts))\n * }\n * }\n * })\n * ```\n *\n * @public\n */\nexport function traceHTTP<TArgs extends unknown[], TReturn>(\n config: HTTPConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n if (config.method) {\n ctx.setAttribute('http.request.method', config.method);\n }\n if (config.url) {\n ctx.setAttribute('url.full', config.url);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n\n/**\n * Trace messaging operations with Messaging semantic conventions\n *\n * Automatically adds standard attributes for messaging:\n * - messaging.system\n * - messaging.operation\n * - messaging.destination.name\n *\n * **Use Cases:**\n * - Publishing messages to queues/topics\n * - Consuming messages from queues/topics\n * - Event-driven architectures\n *\n * @param config - Messaging operation configuration\n * @returns Traced function factory with Messaging attributes\n *\n * @example Publishing to Kafka\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { kafka } from './kafka'\n *\n * const producer = kafka.producer()\n *\n * export const publishEvent = traceMessaging({\n * system: 'kafka',\n * operation: 'publish',\n * destination: 'user-events'\n * })(ctx => async (event: { type: string; userId: string; data: object }) => {\n * ctx.setAttribute('messaging.message.type', event.type)\n * ctx.setAttribute('messaging.kafka.partition', 0)\n *\n * await producer.send({\n * topic: 'user-events',\n * messages: [\n * {\n * key: event.userId,\n * value: JSON.stringify(event.data)\n * }\n * ]\n * })\n *\n * ctx.setAttribute('messaging.message.id', event.userId)\n * })\n * ```\n *\n * @example Consuming from RabbitMQ\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { channel } from './rabbitmq'\n *\n * export const processOrder = traceMessaging({\n * system: 'rabbitmq',\n * operation: 'process',\n * destination: 'orders'\n * })(ctx => async (message: { orderId: string; items: object[] }) => {\n * ctx.setAttribute('messaging.message.id', message.orderId)\n * ctx.setAttribute('messaging.message.body.size', JSON.stringify(message).length)\n *\n * // Process order logic\n * const result = await processOrderInternal(message)\n *\n * ctx.setAttribute('messaging.operation.result', 'success')\n * return result\n * })\n * ```\n *\n * @example AWS SQS with batch processing\n * ```typescript\n * import { traceMessaging } from 'autotel/semantic-helpers'\n * import { SQS } from '@aws-sdk/client-sqs'\n *\n * const sqs = new SQS()\n *\n * export const sendBatch = traceMessaging({\n * system: 'aws_sqs',\n * operation: 'publish',\n * destination: 'notifications-queue'\n * })(ctx => async (messages: Array<{ id: string; body: object }>) => {\n * ctx.setAttribute('messaging.batch.message_count', messages.length)\n *\n * const result = await sqs.sendMessageBatch({\n * QueueUrl: process.env.QUEUE_URL,\n * Entries: messages.map(msg => ({\n * Id: msg.id,\n * MessageBody: JSON.stringify(msg.body)\n * }))\n * })\n *\n * ctx.setAttribute('messaging.operation.success_count', result.Successful?.length || 0)\n * ctx.setAttribute('messaging.operation.failed_count', result.Failed?.length || 0)\n *\n * return result\n * })\n * ```\n *\n * @public\n */\nexport function traceMessaging<TArgs extends unknown[], TReturn>(\n config: MessagingConfig,\n) {\n return (\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>((ctx) => {\n // Set semantic convention attributes\n ctx.setAttribute('messaging.system', config.system);\n if (config.operation) {\n ctx.setAttribute('messaging.operation', config.operation);\n }\n if (config.destination) {\n ctx.setAttribute('messaging.destination.name', config.destination);\n }\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined && value !== null) {\n // setAttribute only accepts primitives (string | number | boolean)\n // Arrays and objects should be serialized\n const attrValue =\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ? value\n : JSON.stringify(value);\n ctx.setAttribute(key, attrValue);\n }\n }\n }\n\n // Call the user's factory to get their function and return it\n return fnFactory(ctx);\n });\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkRMGSBMQF_cjs = require('./chunk-RMGSBMQF.cjs');
3
+ var chunkQQLP4M6W_cjs = require('./chunk-QQLP4M6W.cjs');
4
4
  var chunkGML3FBOT_cjs = require('./chunk-GML3FBOT.cjs');
5
5
  var async_hooks = require('async_hooks');
6
6
 
@@ -9,7 +9,7 @@ var workflowContextStorage = new async_hooks.AsyncLocalStorage();
9
9
  function traceWorkflow(config) {
10
10
  const spanName = `workflow.${config.name}`;
11
11
  return (fnFactory) => {
12
- return chunkRMGSBMQF_cjs.trace(spanName, (baseCtx) => {
12
+ return chunkQQLP4M6W_cjs.trace(spanName, (baseCtx) => {
13
13
  return async (...args) => {
14
14
  const workflowId = typeof config.workflowId === "function" ? config.workflowId(...args) : config.workflowId;
15
15
  const ctx = createWorkflowContext(baseCtx, config.name, workflowId);
@@ -61,7 +61,7 @@ function traceWorkflow(config) {
61
61
  function traceStep(config) {
62
62
  return (fn) => {
63
63
  const spanName = `step.${config.name}`;
64
- return chunkRMGSBMQF_cjs.trace(spanName, (baseCtx) => {
64
+ return chunkQQLP4M6W_cjs.trace(spanName, (baseCtx) => {
65
65
  return async (...args) => {
66
66
  const workflowCtx = workflowContextStorage.getStore() ?? null;
67
67
  const ctx = createStepContext(baseCtx, config, workflowCtx);
@@ -339,5 +339,5 @@ exports.getCurrentWorkflowContext = getCurrentWorkflowContext;
339
339
  exports.isInWorkflow = isInWorkflow;
340
340
  exports.traceStep = traceStep;
341
341
  exports.traceWorkflow = traceWorkflow;
342
- //# sourceMappingURL=chunk-AQXPGGQK.cjs.map
343
- //# sourceMappingURL=chunk-AQXPGGQK.cjs.map
342
+ //# sourceMappingURL=chunk-EEJGUBWV.cjs.map
343
+ //# sourceMappingURL=chunk-EEJGUBWV.cjs.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AAAA,IACH;AAAA,EACF;AAGA,EAAA,IAAI,OAAO,MAAA,EAAQ;AACjB,IAAA,MAAM,SAAA,GAAY,KAAA,CAAM,OAAA,CAAQ,MAAA,CAAO,MAAM,IACzC,MAAA,CAAO,MAAA,GACP,CAAC,MAAA,CAAO,MAAM,CAAA;AAElB,IAAA,KAAA,MAAW,YAAY,SAAA,EAAW;AAChC,MAAA,MAAM,WAAA,GAAc,WAAA,CAAY,eAAA,CAAgB,QAAQ,CAAA;AACxD,MAAA,IAAI,WAAA,EAAa;AACf,QAAA,KAAA,CAAM,IAAA,CAAK;AAAA,UACT,OAAA,EAAS,WAAA;AAAA,UACT,UAAA,EAAY;AAAA,YACV,oBAAA,EAAsB,YAAA;AAAA,YACtB,oBAAA,EAAsB;AAAA;AACxB,SACD,CAAA;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAGA,EAAA,IAAI,KAAA,CAAM,SAAS,CAAA,EAAG;AACpB,IAAA,GAAA,CAAI,SAAS,KAAK,CAAA;AAAA,EACpB;AACF;AAKA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD;AAYO,SAAS,yBAAA,GAAoD;AAClE,EAAA,OAAO,sBAAA,CAAuB,UAAS,IAAK,IAAA;AAC9C;AAQO,SAAS,YAAA,GAAwB;AACtC,EAAA,OAAO,sBAAA,CAAuB,UAAS,KAAM,MAAA;AAC/C","file":"chunk-AQXPGGQK.cjs","sourcesContent":["/**\n * Workflow and Saga tracing helpers\n *\n * Provides specialized tracing for multi-step workflows and sagas with\n * automatic step linking, compensation tracking, and workflow correlation.\n *\n * @example Simple workflow\n * ```typescript\n * import { traceWorkflow, traceStep } from 'autotel/workflow';\n *\n * export const processOrder = traceWorkflow({\n * name: 'OrderFulfillment',\n * workflowId: (order) => order.id,\n * })(ctx => async (order: Order) => {\n * await validateOrder(order);\n * await chargePayment(order);\n * await shipOrder(order);\n * });\n * ```\n *\n * @example Saga with compensation\n * ```typescript\n * import { traceWorkflow, traceStep } from 'autotel/workflow';\n *\n * export const orderSaga = traceWorkflow({\n * name: 'OrderSaga',\n * workflowId: () => generateUUID(),\n * })(ctx => async (order: Order) => {\n *\n * const reserveStep = traceStep({\n * name: 'ReserveInventory',\n * compensate: async () => {\n * await releaseInventory(order.items);\n * },\n * })(async () => {\n * await inventoryService.reserve(order.items);\n * });\n * await reserveStep();\n *\n * const paymentStep = traceStep({\n * name: 'ProcessPayment',\n * linkToPrevious: true,\n * compensate: async () => {\n * await refundPayment(order.paymentId);\n * },\n * })(async () => {\n * await paymentService.charge(order);\n * });\n * await paymentStep();\n * });\n * ```\n *\n * @module\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Attributes, Link, SpanContext } from '@opentelemetry/api';\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport { getActiveSpan } from './trace-helpers';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Workflow status\n */\nexport type WorkflowStatus =\n | 'pending'\n | 'running'\n | 'completed'\n | 'failed'\n | 'compensating'\n | 'compensated'\n | 'compensation_failed';\n\n/**\n * Step status\n */\nexport type StepStatus =\n | 'pending'\n | 'running'\n | 'completed'\n | 'failed'\n | 'skipped'\n | 'compensated';\n\n/**\n * Configuration for workflow tracing\n */\nexport interface WorkflowConfig<TArgs extends unknown[] = unknown[]> {\n /** Workflow name (e.g., 'OrderFulfillment', 'UserOnboarding') */\n name: string;\n\n /**\n * Function to extract or generate workflow ID\n * Can be static string, function of args, or generator\n */\n workflowId: string | ((...args: TArgs) => string);\n\n /** Optional workflow version */\n version?: string;\n\n /** Additional attributes */\n attributes?: Attributes;\n\n /** Callback on workflow completion */\n onComplete?: (ctx: WorkflowContext, result: unknown) => void;\n\n /** Callback on workflow failure */\n onFailed?: (ctx: WorkflowContext, error: Error) => void;\n\n /** Callback on compensation start */\n onCompensating?: (ctx: WorkflowContext) => void;\n}\n\n/**\n * Configuration for workflow step tracing\n */\nexport interface StepConfig {\n /** Step name */\n name: string;\n\n /** Optional step description */\n description?: string;\n\n /** Step index (auto-assigned if not provided) */\n index?: number;\n\n /** Link to previous step span */\n linkToPrevious?: boolean;\n\n /** Link to specific step(s) by name */\n linkTo?: string | string[];\n\n /** Additional attributes */\n attributes?: Attributes;\n\n /** Compensation handler for saga rollback */\n compensate?: (error: Error) => Promise<void> | void;\n\n /** Whether this step is idempotent */\n idempotent?: boolean;\n\n /** Retry configuration */\n retry?: {\n maxAttempts: number;\n backoffMs?: number;\n };\n\n /** Callback on step completion */\n onComplete?: (ctx: StepContext) => void;\n\n /** Callback on step failure */\n onFailed?: (ctx: StepContext, error: Error) => void;\n}\n\n/**\n * Step metadata stored for linking and compensation\n */\ninterface StepMetadata {\n name: string;\n index: number;\n status: StepStatus;\n spanContext?: SpanContext;\n compensate?: (error: Error) => Promise<void> | void;\n startTime: number;\n endTime?: number;\n}\n\n/**\n * Extended trace context for workflows\n */\nexport interface WorkflowContext extends TraceContext {\n /** Get the workflow ID */\n getWorkflowId(): string;\n\n /** Get workflow name */\n getWorkflowName(): string;\n\n /** Get current workflow status */\n getStatus(): WorkflowStatus;\n\n /** Mark step as completed and store for linking */\n completeStep(stepName: string): void;\n\n /** Get previous step's span context for linking */\n getPreviousStep(stepName?: string): SpanContext | null;\n\n /** Get all completed steps */\n getCompletedSteps(): string[];\n\n /** Register a compensation handler */\n registerCompensation(\n stepName: string,\n handler: (error: Error) => Promise<void> | void,\n ): void;\n\n /** Trigger compensation for all registered steps */\n compensate(error: Error): Promise<void>;\n\n /** Record compensation result */\n recordCompensation(stepName: string, success: boolean, error?: Error): void;\n\n /** Set workflow status */\n setWorkflowStatus(status: WorkflowStatus): void;\n}\n\n/**\n * Extended trace context for workflow steps\n */\nexport interface StepContext extends TraceContext {\n /** Get step name */\n getStepName(): string;\n\n /** Get step index */\n getStepIndex(): number;\n\n /** Mark this step as completed */\n complete(): void;\n\n /** Skip this step */\n skip(reason?: string): void;\n\n /** Get workflow context */\n getWorkflowContext(): WorkflowContext | null;\n}\n\n// ============================================================================\n// Storage\n// ============================================================================\n\n// Store workflow state in a WeakMap keyed by span\nconst workflowStates = new WeakMap<\n object,\n {\n workflowId: string;\n workflowName: string;\n status: WorkflowStatus;\n steps: Map<string, StepMetadata>;\n stepCounter: number;\n compensations: Map<string, (error: Error) => Promise<void> | void>;\n }\n>();\n\n/**\n * AsyncLocalStorage for workflow context (async-safe)\n *\n * This replaces the previous module-level variable which was NOT safe for\n * concurrent workflows. AsyncLocalStorage ensures each async execution chain\n * has its own isolated workflow context.\n */\nconst workflowContextStorage = new AsyncLocalStorage<WorkflowContext>();\n\n// ============================================================================\n// Workflow Helper\n// ============================================================================\n\n/**\n * Create a traced workflow function\n *\n * Wraps business logic in a workflow span with automatic step tracking,\n * correlation via workflow ID, and compensation support.\n *\n * @param config - Workflow configuration\n * @returns Factory function that wraps your workflow logic\n *\n * @example Order fulfillment workflow\n * ```typescript\n * export const fulfillOrder = traceWorkflow({\n * name: 'OrderFulfillment',\n * workflowId: (order) => order.id,\n * version: '2.0',\n * })(ctx => async (order: Order) => {\n * ctx.setAttribute('order.total', order.total);\n *\n * await validateOrder(order);\n * await processPayment(order);\n * await fulfillItems(order);\n * await notifyCustomer(order);\n *\n * return { success: true, orderId: order.id };\n * });\n * ```\n */\nexport function traceWorkflow<TArgs extends unknown[], TReturn>(\n config: WorkflowConfig<TArgs>,\n) {\n const spanName = `workflow.${config.name}`;\n\n return (\n fnFactory: (ctx: WorkflowContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>(spanName, (baseCtx) => {\n return async (...args: TArgs) => {\n // Generate or extract workflow ID\n const workflowId =\n typeof config.workflowId === 'function'\n ? config.workflowId(...args)\n : config.workflowId;\n\n // Create workflow context\n const ctx = createWorkflowContext(baseCtx, config.name, workflowId);\n\n // Set workflow attributes\n ctx.setAttribute('workflow.name', config.name);\n ctx.setAttribute('workflow.id', workflowId);\n if (config.version) {\n ctx.setAttribute('workflow.version', config.version);\n }\n ctx.setAttribute('workflow.status', 'running');\n\n // Set custom attributes\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined) {\n ctx.setAttribute(key, value as string | number | boolean);\n }\n }\n }\n\n // Run workflow in AsyncLocalStorage context for async-safety\n // This ensures concurrent workflows have isolated contexts\n return workflowContextStorage.run(ctx, async () => {\n try {\n // Execute workflow\n const userFn = fnFactory(ctx);\n const result = await userFn(...args);\n\n // Mark as completed\n ctx.setWorkflowStatus('completed');\n config.onComplete?.(ctx, result);\n\n return result;\n } catch (error) {\n // Mark as failed\n ctx.setWorkflowStatus('failed');\n config.onFailed?.(ctx, error as Error);\n\n // Check if we have compensations to run\n const state = getWorkflowState();\n if (state && state.compensations.size > 0) {\n ctx.setWorkflowStatus('compensating');\n config.onCompensating?.(ctx);\n\n try {\n await ctx.compensate(error as Error);\n ctx.setWorkflowStatus('compensated');\n } catch (compensationError) {\n ctx.setWorkflowStatus('compensation_failed');\n ctx.setAttribute(\n 'workflow.compensation.error',\n String(compensationError),\n );\n }\n }\n\n throw error;\n }\n });\n };\n });\n };\n}\n\n/**\n * Create a traced workflow step\n *\n * Wraps step logic with automatic linking to previous steps,\n * compensation registration, and status tracking.\n *\n * @param config - Step configuration\n * @returns Factory function that wraps your step logic\n *\n * @example Step with compensation\n * ```typescript\n * const chargePayment = traceStep({\n * name: 'ChargePayment',\n * linkToPrevious: true,\n * compensate: async (error) => {\n * await paymentService.refund(paymentId);\n * },\n * })(async (amount: number) => {\n * return await paymentService.charge(amount);\n * });\n * ```\n */\nexport function traceStep<TArgs extends unknown[], TReturn>(\n config: StepConfig,\n) {\n return (\n fn: (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n const spanName = `step.${config.name}`;\n\n return trace<TArgs, TReturn>(spanName, (baseCtx) => {\n return async (...args: TArgs) => {\n // Get workflow context from AsyncLocalStorage (async-safe)\n const workflowCtx = workflowContextStorage.getStore() ?? null;\n\n // Create step context\n const ctx = createStepContext(baseCtx, config, workflowCtx);\n\n // Set step attributes\n ctx.setAttribute('workflow.step.name', config.name);\n ctx.setAttribute('workflow.step.index', ctx.getStepIndex());\n ctx.setAttribute('workflow.step.status', 'running');\n\n if (config.description) {\n ctx.setAttribute('workflow.step.description', config.description);\n }\n\n if (config.idempotent) {\n ctx.setAttribute('workflow.step.idempotent', true);\n }\n\n // Set custom attributes\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined) {\n ctx.setAttribute(key, value as string | number | boolean);\n }\n }\n }\n\n // Link to previous steps\n await addStepLinks(ctx, config, workflowCtx);\n\n // Register compensation if provided\n if (config.compensate && workflowCtx) {\n workflowCtx.registerCompensation(config.name, config.compensate);\n }\n\n // Execute with optional retry\n let lastError: Error | undefined;\n const maxAttempts = config.retry?.maxAttempts ?? 1;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n if (attempt > 1) {\n ctx.setAttribute('workflow.step.retry_attempt', attempt);\n ctx.addEvent('step_retry', {\n 'workflow.step.attempt': attempt,\n 'workflow.step.max_attempts': maxAttempts,\n });\n\n // Backoff\n if (config.retry?.backoffMs) {\n await sleep(config.retry.backoffMs * attempt);\n }\n }\n\n const result = await fn(...args);\n\n // Mark as completed\n ctx.setAttribute('workflow.step.status', 'completed');\n ctx.complete();\n config.onComplete?.(ctx);\n\n return result;\n } catch (error) {\n lastError = error as Error;\n\n if (attempt < maxAttempts) {\n ctx.addEvent('step_retry_scheduled', {\n 'workflow.step.error': String(error),\n 'workflow.step.attempt': attempt,\n });\n }\n }\n }\n\n // All attempts failed\n ctx.setAttribute('workflow.step.status', 'failed');\n ctx.setAttribute('workflow.step.error', String(lastError));\n config.onFailed?.(ctx, lastError!);\n\n throw lastError;\n };\n });\n };\n}\n\n// ============================================================================\n// Context Creation\n// ============================================================================\n\n/**\n * Create workflow-extended context\n */\nfunction createWorkflowContext(\n baseCtx: TraceContext,\n workflowName: string,\n workflowId: string,\n): WorkflowContext {\n // Initialize state\n const span = getActiveSpan();\n const state = {\n workflowId,\n workflowName,\n status: 'running' as WorkflowStatus,\n steps: new Map<string, StepMetadata>(),\n stepCounter: 0,\n compensations: new Map<string, (error: Error) => Promise<void> | void>(),\n };\n\n if (span) {\n workflowStates.set(span, state);\n }\n\n return {\n ...baseCtx,\n\n getWorkflowId(): string {\n return workflowId;\n },\n\n getWorkflowName(): string {\n return workflowName;\n },\n\n getStatus(): WorkflowStatus {\n return state.status;\n },\n\n completeStep(stepName: string): void {\n let step = state.steps.get(stepName);\n if (!step) {\n // Auto-create step entry for manually managed steps\n // (when using registerCompensation without traceStep)\n step = {\n name: stepName,\n index: state.stepCounter++,\n status: 'pending',\n startTime: Date.now(),\n };\n state.steps.set(stepName, step);\n }\n step.status = 'completed';\n step.endTime = Date.now();\n\n // Capture span context for linking\n const currentSpan = getActiveSpan();\n if (currentSpan) {\n step.spanContext = currentSpan.spanContext();\n }\n },\n\n getPreviousStep(stepName?: string): SpanContext | null {\n if (stepName) {\n const step = state.steps.get(stepName);\n return step?.spanContext ?? null;\n }\n\n // Get last completed step\n let lastStep: StepMetadata | null = null;\n for (const step of state.steps.values()) {\n if (\n step.status === 'completed' &&\n (!lastStep || step.index > lastStep.index)\n ) {\n lastStep = step;\n }\n }\n\n return lastStep?.spanContext ?? null;\n },\n\n getCompletedSteps(): string[] {\n const completed: string[] = [];\n for (const [name, step] of state.steps) {\n if (step.status === 'completed') {\n completed.push(name);\n }\n }\n return completed.toSorted(\n (a, b) =>\n (state.steps.get(a)?.index ?? 0) - (state.steps.get(b)?.index ?? 0),\n );\n },\n\n registerCompensation(\n stepName: string,\n handler: (error: Error) => Promise<void> | void,\n ): void {\n state.compensations.set(stepName, handler);\n },\n\n async compensate(error: Error): Promise<void> {\n // Execute compensations in reverse order\n const compensationOrder = [...state.compensations.entries()].toReversed();\n\n for (const [stepName, handler] of compensationOrder) {\n const step = state.steps.get(stepName);\n if (step && step.status === 'completed') {\n try {\n baseCtx.addEvent('compensation_started', {\n 'workflow.step.name': stepName,\n });\n\n await Promise.resolve(handler(error));\n\n this.recordCompensation(stepName, true);\n step.status = 'compensated';\n } catch (compensationError) {\n this.recordCompensation(\n stepName,\n false,\n compensationError as Error,\n );\n throw compensationError;\n }\n }\n }\n },\n\n recordCompensation(\n stepName: string,\n success: boolean,\n error?: Error,\n ): void {\n baseCtx.addEvent('compensation_completed', {\n 'workflow.step.name': stepName,\n 'workflow.compensation.success': success,\n ...(error && { 'workflow.compensation.error': String(error) }),\n });\n\n baseCtx.setAttribute(\n `workflow.compensation.${stepName}`,\n success ? 'success' : 'failed',\n );\n },\n\n setWorkflowStatus(status: WorkflowStatus): void {\n state.status = status;\n baseCtx.setAttribute('workflow.status', status);\n\n baseCtx.addEvent('workflow_status_changed', {\n 'workflow.status': status,\n });\n },\n };\n}\n\n/**\n * Create step-extended context\n */\nfunction createStepContext(\n baseCtx: TraceContext,\n config: StepConfig,\n workflowCtx: WorkflowContext | null,\n): StepContext {\n // Determine step index\n let stepIndex = config.index ?? 0;\n if (workflowCtx) {\n const span = getActiveSpan();\n if (span) {\n const state = workflowStates.get(span);\n if (state) {\n stepIndex = config.index ?? state.stepCounter++;\n }\n }\n }\n\n // Register step metadata\n if (workflowCtx) {\n const wfSpan = getActiveSpan();\n if (wfSpan) {\n const state = workflowStates.get(wfSpan);\n if (state) {\n state.steps.set(config.name, {\n name: config.name,\n index: stepIndex,\n status: 'running',\n startTime: Date.now(),\n compensate: config.compensate,\n });\n }\n }\n }\n\n return {\n ...baseCtx,\n\n getStepName(): string {\n return config.name;\n },\n\n getStepIndex(): number {\n return stepIndex;\n },\n\n complete(): void {\n if (workflowCtx) {\n workflowCtx.completeStep(config.name);\n }\n },\n\n skip(reason?: string): void {\n baseCtx.setAttribute('workflow.step.status', 'skipped');\n if (reason) {\n baseCtx.setAttribute('workflow.step.skip_reason', reason);\n }\n baseCtx.addEvent('step_skipped', {\n 'workflow.step.name': config.name,\n ...(reason && { 'workflow.step.skip_reason': reason }),\n });\n },\n\n getWorkflowContext(): WorkflowContext | null {\n return workflowCtx;\n },\n };\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Get workflow state from context\n */\nfunction getWorkflowState() {\n const span = getActiveSpan();\n return span ? workflowStates.get(span) : null;\n}\n\n/**\n * Add links to previous steps\n */\nasync function addStepLinks(\n ctx: StepContext,\n config: StepConfig,\n workflowCtx: WorkflowContext | null,\n): Promise<void> {\n if (!workflowCtx) return;\n\n const links: Link[] = [];\n\n // Link to previous step\n if (config.linkToPrevious) {\n const prevSpanContext = workflowCtx.getPreviousStep();\n if (prevSpanContext) {\n links.push({\n context: prevSpanContext,\n attributes: {\n 'workflow.link.type': 'sequence',\n },\n });\n }\n }\n\n // Link to specific steps\n if (config.linkTo) {\n const stepNames = Array.isArray(config.linkTo)\n ? config.linkTo\n : [config.linkTo];\n\n for (const stepName of stepNames) {\n const spanContext = workflowCtx.getPreviousStep(stepName);\n if (spanContext) {\n links.push({\n context: spanContext,\n attributes: {\n 'workflow.link.type': 'dependency',\n 'workflow.link.step': stepName,\n },\n });\n }\n }\n }\n\n // Add all links\n if (links.length > 0) {\n ctx.addLinks(links);\n }\n}\n\n/**\n * Sleep utility for retry backoff\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// ============================================================================\n// Convenience Exports\n// ============================================================================\n\n/**\n * Get current workflow context (if inside a workflow)\n *\n * Uses AsyncLocalStorage to ensure async-safety when multiple\n * workflows are running concurrently.\n */\nexport function getCurrentWorkflowContext(): WorkflowContext | null {\n return workflowContextStorage.getStore() ?? null;\n}\n\n/**\n * Check if currently executing inside a workflow\n *\n * Uses AsyncLocalStorage to ensure async-safety when multiple\n * workflows are running concurrently.\n */\nexport function isInWorkflow(): boolean {\n return workflowContextStorage.getStore() !== undef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AA,IACH;AAAA,EACF;AAGA,EAAA,IAAI,OAAO,MAAA,EAAQ;AACjB,IAAA,MAAM,SAAA,GAAY,KAAA,CAAM,OAAA,CAAQ,MAAA,CAAO,MAAM,IACzC,MAAA,CAAO,MAAA,GACP,CAAC,MAAA,CAAO,MAAM,CAAA;AAElB,IAAA,KAAA,MAAW,YAAY,SAAA,EAAW;AAChC,MAAA,MAAM,WAAA,GAAc,WAAA,CAAY,eAAA,CAAgB,QAAQ,CAAA;AACxD,MAAA,IAAI,WAAA,EAAa;AACf,QAAA,KAAA,CAAM,IAAA,CAAK;AAAA,UACT,OAAA,EAAS,WAAA;AAAA,UACT,UAAA,EAAY;AAAA,YACV,oBAAA,EAAsB,YAAA;AAAA,YACtB,oBAAA,EAAsB;AAAA;AACxB,SACD,CAAA;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAGA,EAAA,IAAI,KAAA,CAAM,SAAS,CAAA,EAAG;AACpB,IAAA,GAAA,CAAI,SAAS,KAAK,CAAA;AAAA,EACpB;AACF;AAKA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD;AAYO,SAAS,yBAAA,GAAoD;AAClE,EAAA,OAAO,sBAAA,CAAuB,UAAS,IAAK,IAAA;AAC9C;AAQO,SAAS,YAAA,GAAwB;AACtC,EAAA,OAAO,sBAAA,CAAuB,UAAS,KAAM,MAAA;AAC/C","file":"chunk-EEJGUBWV.cjs","sourcesContent":["/**\n * Workflow and Saga tracing helpers\n *\n * Provides specialized tracing for multi-step workflows and sagas with\n * automatic step linking, compensation tracking, and workflow correlation.\n *\n * @example Simple workflow\n * ```typescript\n * import { traceWorkflow, traceStep } from 'autotel/workflow';\n *\n * export const processOrder = traceWorkflow({\n * name: 'OrderFulfillment',\n * workflowId: (order) => order.id,\n * })(ctx => async (order: Order) => {\n * await validateOrder(order);\n * await chargePayment(order);\n * await shipOrder(order);\n * });\n * ```\n *\n * @example Saga with compensation\n * ```typescript\n * import { traceWorkflow, traceStep } from 'autotel/workflow';\n *\n * export const orderSaga = traceWorkflow({\n * name: 'OrderSaga',\n * workflowId: () => generateUUID(),\n * })(ctx => async (order: Order) => {\n *\n * const reserveStep = traceStep({\n * name: 'ReserveInventory',\n * compensate: async () => {\n * await releaseInventory(order.items);\n * },\n * })(async () => {\n * await inventoryService.reserve(order.items);\n * });\n * await reserveStep();\n *\n * const paymentStep = traceStep({\n * name: 'ProcessPayment',\n * linkToPrevious: true,\n * compensate: async () => {\n * await refundPayment(order.paymentId);\n * },\n * })(async () => {\n * await paymentService.charge(order);\n * });\n * await paymentStep();\n * });\n * ```\n *\n * @module\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Attributes, Link, SpanContext } from '@opentelemetry/api';\nimport { trace } from './functional';\nimport type { TraceContext } from './trace-context';\nimport { getActiveSpan } from './trace-helpers';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Workflow status\n */\nexport type WorkflowStatus =\n | 'pending'\n | 'running'\n | 'completed'\n | 'failed'\n | 'compensating'\n | 'compensated'\n | 'compensation_failed';\n\n/**\n * Step status\n */\nexport type StepStatus =\n | 'pending'\n | 'running'\n | 'completed'\n | 'failed'\n | 'skipped'\n | 'compensated';\n\n/**\n * Configuration for workflow tracing\n */\nexport interface WorkflowConfig<TArgs extends unknown[] = unknown[]> {\n /** Workflow name (e.g., 'OrderFulfillment', 'UserOnboarding') */\n name: string;\n\n /**\n * Function to extract or generate workflow ID\n * Can be static string, function of args, or generator\n */\n workflowId: string | ((...args: TArgs) => string);\n\n /** Optional workflow version */\n version?: string;\n\n /** Additional attributes */\n attributes?: Attributes;\n\n /** Callback on workflow completion */\n onComplete?: (ctx: WorkflowContext, result: unknown) => void;\n\n /** Callback on workflow failure */\n onFailed?: (ctx: WorkflowContext, error: Error) => void;\n\n /** Callback on compensation start */\n onCompensating?: (ctx: WorkflowContext) => void;\n}\n\n/**\n * Configuration for workflow step tracing\n */\nexport interface StepConfig {\n /** Step name */\n name: string;\n\n /** Optional step description */\n description?: string;\n\n /** Step index (auto-assigned if not provided) */\n index?: number;\n\n /** Link to previous step span */\n linkToPrevious?: boolean;\n\n /** Link to specific step(s) by name */\n linkTo?: string | string[];\n\n /** Additional attributes */\n attributes?: Attributes;\n\n /** Compensation handler for saga rollback */\n compensate?: (error: Error) => Promise<void> | void;\n\n /** Whether this step is idempotent */\n idempotent?: boolean;\n\n /** Retry configuration */\n retry?: {\n maxAttempts: number;\n backoffMs?: number;\n };\n\n /** Callback on step completion */\n onComplete?: (ctx: StepContext) => void;\n\n /** Callback on step failure */\n onFailed?: (ctx: StepContext, error: Error) => void;\n}\n\n/**\n * Step metadata stored for linking and compensation\n */\ninterface StepMetadata {\n name: string;\n index: number;\n status: StepStatus;\n spanContext?: SpanContext;\n compensate?: (error: Error) => Promise<void> | void;\n startTime: number;\n endTime?: number;\n}\n\n/**\n * Extended trace context for workflows\n */\nexport interface WorkflowContext extends TraceContext {\n /** Get the workflow ID */\n getWorkflowId(): string;\n\n /** Get workflow name */\n getWorkflowName(): string;\n\n /** Get current workflow status */\n getStatus(): WorkflowStatus;\n\n /** Mark step as completed and store for linking */\n completeStep(stepName: string): void;\n\n /** Get previous step's span context for linking */\n getPreviousStep(stepName?: string): SpanContext | null;\n\n /** Get all completed steps */\n getCompletedSteps(): string[];\n\n /** Register a compensation handler */\n registerCompensation(\n stepName: string,\n handler: (error: Error) => Promise<void> | void,\n ): void;\n\n /** Trigger compensation for all registered steps */\n compensate(error: Error): Promise<void>;\n\n /** Record compensation result */\n recordCompensation(stepName: string, success: boolean, error?: Error): void;\n\n /** Set workflow status */\n setWorkflowStatus(status: WorkflowStatus): void;\n}\n\n/**\n * Extended trace context for workflow steps\n */\nexport interface StepContext extends TraceContext {\n /** Get step name */\n getStepName(): string;\n\n /** Get step index */\n getStepIndex(): number;\n\n /** Mark this step as completed */\n complete(): void;\n\n /** Skip this step */\n skip(reason?: string): void;\n\n /** Get workflow context */\n getWorkflowContext(): WorkflowContext | null;\n}\n\n// ============================================================================\n// Storage\n// ============================================================================\n\n// Store workflow state in a WeakMap keyed by span\nconst workflowStates = new WeakMap<\n object,\n {\n workflowId: string;\n workflowName: string;\n status: WorkflowStatus;\n steps: Map<string, StepMetadata>;\n stepCounter: number;\n compensations: Map<string, (error: Error) => Promise<void> | void>;\n }\n>();\n\n/**\n * AsyncLocalStorage for workflow context (async-safe)\n *\n * This replaces the previous module-level variable which was NOT safe for\n * concurrent workflows. AsyncLocalStorage ensures each async execution chain\n * has its own isolated workflow context.\n */\nconst workflowContextStorage = new AsyncLocalStorage<WorkflowContext>();\n\n// ============================================================================\n// Workflow Helper\n// ============================================================================\n\n/**\n * Create a traced workflow function\n *\n * Wraps business logic in a workflow span with automatic step tracking,\n * correlation via workflow ID, and compensation support.\n *\n * @param config - Workflow configuration\n * @returns Factory function that wraps your workflow logic\n *\n * @example Order fulfillment workflow\n * ```typescript\n * export const fulfillOrder = traceWorkflow({\n * name: 'OrderFulfillment',\n * workflowId: (order) => order.id,\n * version: '2.0',\n * })(ctx => async (order: Order) => {\n * ctx.setAttribute('order.total', order.total);\n *\n * await validateOrder(order);\n * await processPayment(order);\n * await fulfillItems(order);\n * await notifyCustomer(order);\n *\n * return { success: true, orderId: order.id };\n * });\n * ```\n */\nexport function traceWorkflow<TArgs extends unknown[], TReturn>(\n config: WorkflowConfig<TArgs>,\n) {\n const spanName = `workflow.${config.name}`;\n\n return (\n fnFactory: (ctx: WorkflowContext) => (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n return trace<TArgs, TReturn>(spanName, (baseCtx) => {\n return async (...args: TArgs) => {\n // Generate or extract workflow ID\n const workflowId =\n typeof config.workflowId === 'function'\n ? config.workflowId(...args)\n : config.workflowId;\n\n // Create workflow context\n const ctx = createWorkflowContext(baseCtx, config.name, workflowId);\n\n // Set workflow attributes\n ctx.setAttribute('workflow.name', config.name);\n ctx.setAttribute('workflow.id', workflowId);\n if (config.version) {\n ctx.setAttribute('workflow.version', config.version);\n }\n ctx.setAttribute('workflow.status', 'running');\n\n // Set custom attributes\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined) {\n ctx.setAttribute(key, value as string | number | boolean);\n }\n }\n }\n\n // Run workflow in AsyncLocalStorage context for async-safety\n // This ensures concurrent workflows have isolated contexts\n return workflowContextStorage.run(ctx, async () => {\n try {\n // Execute workflow\n const userFn = fnFactory(ctx);\n const result = await userFn(...args);\n\n // Mark as completed\n ctx.setWorkflowStatus('completed');\n config.onComplete?.(ctx, result);\n\n return result;\n } catch (error) {\n // Mark as failed\n ctx.setWorkflowStatus('failed');\n config.onFailed?.(ctx, error as Error);\n\n // Check if we have compensations to run\n const state = getWorkflowState();\n if (state && state.compensations.size > 0) {\n ctx.setWorkflowStatus('compensating');\n config.onCompensating?.(ctx);\n\n try {\n await ctx.compensate(error as Error);\n ctx.setWorkflowStatus('compensated');\n } catch (compensationError) {\n ctx.setWorkflowStatus('compensation_failed');\n ctx.setAttribute(\n 'workflow.compensation.error',\n String(compensationError),\n );\n }\n }\n\n throw error;\n }\n });\n };\n });\n };\n}\n\n/**\n * Create a traced workflow step\n *\n * Wraps step logic with automatic linking to previous steps,\n * compensation registration, and status tracking.\n *\n * @param config - Step configuration\n * @returns Factory function that wraps your step logic\n *\n * @example Step with compensation\n * ```typescript\n * const chargePayment = traceStep({\n * name: 'ChargePayment',\n * linkToPrevious: true,\n * compensate: async (error) => {\n * await paymentService.refund(paymentId);\n * },\n * })(async (amount: number) => {\n * return await paymentService.charge(amount);\n * });\n * ```\n */\nexport function traceStep<TArgs extends unknown[], TReturn>(\n config: StepConfig,\n) {\n return (\n fn: (...args: TArgs) => Promise<TReturn>,\n ): ((...args: TArgs) => Promise<TReturn>) => {\n const spanName = `step.${config.name}`;\n\n return trace<TArgs, TReturn>(spanName, (baseCtx) => {\n return async (...args: TArgs) => {\n // Get workflow context from AsyncLocalStorage (async-safe)\n const workflowCtx = workflowContextStorage.getStore() ?? null;\n\n // Create step context\n const ctx = createStepContext(baseCtx, config, workflowCtx);\n\n // Set step attributes\n ctx.setAttribute('workflow.step.name', config.name);\n ctx.setAttribute('workflow.step.index', ctx.getStepIndex());\n ctx.setAttribute('workflow.step.status', 'running');\n\n if (config.description) {\n ctx.setAttribute('workflow.step.description', config.description);\n }\n\n if (config.idempotent) {\n ctx.setAttribute('workflow.step.idempotent', true);\n }\n\n // Set custom attributes\n if (config.attributes) {\n for (const [key, value] of Object.entries(config.attributes)) {\n if (value !== undefined) {\n ctx.setAttribute(key, value as string | number | boolean);\n }\n }\n }\n\n // Link to previous steps\n await addStepLinks(ctx, config, workflowCtx);\n\n // Register compensation if provided\n if (config.compensate && workflowCtx) {\n workflowCtx.registerCompensation(config.name, config.compensate);\n }\n\n // Execute with optional retry\n let lastError: Error | undefined;\n const maxAttempts = config.retry?.maxAttempts ?? 1;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n if (attempt > 1) {\n ctx.setAttribute('workflow.step.retry_attempt', attempt);\n ctx.addEvent('step_retry', {\n 'workflow.step.attempt': attempt,\n 'workflow.step.max_attempts': maxAttempts,\n });\n\n // Backoff\n if (config.retry?.backoffMs) {\n await sleep(config.retry.backoffMs * attempt);\n }\n }\n\n const result = await fn(...args);\n\n // Mark as completed\n ctx.setAttribute('workflow.step.status', 'completed');\n ctx.complete();\n config.onComplete?.(ctx);\n\n return result;\n } catch (error) {\n lastError = error as Error;\n\n if (attempt < maxAttempts) {\n ctx.addEvent('step_retry_scheduled', {\n 'workflow.step.error': String(error),\n 'workflow.step.attempt': attempt,\n });\n }\n }\n }\n\n // All attempts failed\n ctx.setAttribute('workflow.step.status', 'failed');\n ctx.setAttribute('workflow.step.error', String(lastError));\n config.onFailed?.(ctx, lastError!);\n\n throw lastError;\n };\n });\n };\n}\n\n// ============================================================================\n// Context Creation\n// ============================================================================\n\n/**\n * Create workflow-extended context\n */\nfunction createWorkflowContext(\n baseCtx: TraceContext,\n workflowName: string,\n workflowId: string,\n): WorkflowContext {\n // Initialize state\n const span = getActiveSpan();\n const state = {\n workflowId,\n workflowName,\n status: 'running' as WorkflowStatus,\n steps: new Map<string, StepMetadata>(),\n stepCounter: 0,\n compensations: new Map<string, (error: Error) => Promise<void> | void>(),\n };\n\n if (span) {\n workflowStates.set(span, state);\n }\n\n return {\n ...baseCtx,\n\n getWorkflowId(): string {\n return workflowId;\n },\n\n getWorkflowName(): string {\n return workflowName;\n },\n\n getStatus(): WorkflowStatus {\n return state.status;\n },\n\n completeStep(stepName: string): void {\n let step = state.steps.get(stepName);\n if (!step) {\n // Auto-create step entry for manually managed steps\n // (when using registerCompensation without traceStep)\n step = {\n name: stepName,\n index: state.stepCounter++,\n status: 'pending',\n startTime: Date.now(),\n };\n state.steps.set(stepName, step);\n }\n step.status = 'completed';\n step.endTime = Date.now();\n\n // Capture span context for linking\n const currentSpan = getActiveSpan();\n if (currentSpan) {\n step.spanContext = currentSpan.spanContext();\n }\n },\n\n getPreviousStep(stepName?: string): SpanContext | null {\n if (stepName) {\n const step = state.steps.get(stepName);\n return step?.spanContext ?? null;\n }\n\n // Get last completed step\n let lastStep: StepMetadata | null = null;\n for (const step of state.steps.values()) {\n if (\n step.status === 'completed' &&\n (!lastStep || step.index > lastStep.index)\n ) {\n lastStep = step;\n }\n }\n\n return lastStep?.spanContext ?? null;\n },\n\n getCompletedSteps(): string[] {\n const completed: string[] = [];\n for (const [name, step] of state.steps) {\n if (step.status === 'completed') {\n completed.push(name);\n }\n }\n return completed.toSorted(\n (a, b) =>\n (state.steps.get(a)?.index ?? 0) - (state.steps.get(b)?.index ?? 0),\n );\n },\n\n registerCompensation(\n stepName: string,\n handler: (error: Error) => Promise<void> | void,\n ): void {\n state.compensations.set(stepName, handler);\n },\n\n async compensate(error: Error): Promise<void> {\n // Execute compensations in reverse order\n const compensationOrder = [...state.compensations.entries()].toReversed();\n\n for (const [stepName, handler] of compensationOrder) {\n const step = state.steps.get(stepName);\n if (step && step.status === 'completed') {\n try {\n baseCtx.addEvent('compensation_started', {\n 'workflow.step.name': stepName,\n });\n\n await Promise.resolve(handler(error));\n\n this.recordCompensation(stepName, true);\n step.status = 'compensated';\n } catch (compensationError) {\n this.recordCompensation(\n stepName,\n false,\n compensationError as Error,\n );\n throw compensationError;\n }\n }\n }\n },\n\n recordCompensation(\n stepName: string,\n success: boolean,\n error?: Error,\n ): void {\n baseCtx.addEvent('compensation_completed', {\n 'workflow.step.name': stepName,\n 'workflow.compensation.success': success,\n ...(error && { 'workflow.compensation.error': String(error) }),\n });\n\n baseCtx.setAttribute(\n `workflow.compensation.${stepName}`,\n success ? 'success' : 'failed',\n );\n },\n\n setWorkflowStatus(status: WorkflowStatus): void {\n state.status = status;\n baseCtx.setAttribute('workflow.status', status);\n\n baseCtx.addEvent('workflow_status_changed', {\n 'workflow.status': status,\n });\n },\n };\n}\n\n/**\n * Create step-extended context\n */\nfunction createStepContext(\n baseCtx: TraceContext,\n config: StepConfig,\n workflowCtx: WorkflowContext | null,\n): StepContext {\n // Determine step index\n let stepIndex = config.index ?? 0;\n if (workflowCtx) {\n const span = getActiveSpan();\n if (span) {\n const state = workflowStates.get(span);\n if (state) {\n stepIndex = config.index ?? state.stepCounter++;\n }\n }\n }\n\n // Register step metadata\n if (workflowCtx) {\n const wfSpan = getActiveSpan();\n if (wfSpan) {\n const state = workflowStates.get(wfSpan);\n if (state) {\n state.steps.set(config.name, {\n name: config.name,\n index: stepIndex,\n status: 'running',\n startTime: Date.now(),\n compensate: config.compensate,\n });\n }\n }\n }\n\n return {\n ...baseCtx,\n\n getStepName(): string {\n return config.name;\n },\n\n getStepIndex(): number {\n return stepIndex;\n },\n\n complete(): void {\n if (workflowCtx) {\n workflowCtx.completeStep(config.name);\n }\n },\n\n skip(reason?: string): void {\n baseCtx.setAttribute('workflow.step.status', 'skipped');\n if (reason) {\n baseCtx.setAttribute('workflow.step.skip_reason', reason);\n }\n baseCtx.addEvent('step_skipped', {\n 'workflow.step.name': config.name,\n ...(reason && { 'workflow.step.skip_reason': reason }),\n });\n },\n\n getWorkflowContext(): WorkflowContext | null {\n return workflowCtx;\n },\n };\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Get workflow state from context\n */\nfunction getWorkflowState() {\n const span = getActiveSpan();\n return span ? workflowStates.get(span) : null;\n}\n\n/**\n * Add links to previous steps\n */\nasync function addStepLinks(\n ctx: StepContext,\n config: StepConfig,\n workflowCtx: WorkflowContext | null,\n): Promise<void> {\n if (!workflowCtx) return;\n\n const links: Link[] = [];\n\n // Link to previous step\n if (config.linkToPrevious) {\n const prevSpanContext = workflowCtx.getPreviousStep();\n if (prevSpanContext) {\n links.push({\n context: prevSpanContext,\n attributes: {\n 'workflow.link.type': 'sequence',\n },\n });\n }\n }\n\n // Link to specific steps\n if (config.linkTo) {\n const stepNames = Array.isArray(config.linkTo)\n ? config.linkTo\n : [config.linkTo];\n\n for (const stepName of stepNames) {\n const spanContext = workflowCtx.getPreviousStep(stepName);\n if (spanContext) {\n links.push({\n context: spanContext,\n attributes: {\n 'workflow.link.type': 'dependency',\n 'workflow.link.step': stepName,\n },\n });\n }\n }\n }\n\n // Add all links\n if (links.length > 0) {\n ctx.addLinks(links);\n }\n}\n\n/**\n * Sleep utility for retry backoff\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// ============================================================================\n// Convenience Exports\n// ============================================================================\n\n/**\n * Get current workflow context (if inside a workflow)\n *\n * Uses AsyncLocalStorage to ensure async-safety when multiple\n * workflows are running concurrently.\n */\nexport function getCurrentWorkflowContext(): WorkflowContext | null {\n return workflowContextStorage.getStore() ?? null;\n}\n\n/**\n * Check if currently executing inside a workflow\n *\n * Uses AsyncLocalStorage to ensure async-safety when multiple\n * workflows are running concurrently.\n */\nexport function isInWorkflow(): boolean {\n return workflowContextStorage.getStore() !== undefined;\n}\n"]}
@@ -9,11 +9,25 @@ function getContextStorage() {
9
9
  return contextStorage;
10
10
  }
11
11
  function getActiveContextWithBaggage() {
12
- const stored = contextStorage.getStore();
12
+ const stored = contextStorage.getStore()?.value;
13
13
  return stored ?? api.context.active();
14
14
  }
15
+ function enterOrRun(storage, value) {
16
+ const existingStore = storage.getStore();
17
+ if (existingStore) {
18
+ existingStore.value = value;
19
+ return;
20
+ }
21
+ const boxedValue = { value };
22
+ try {
23
+ storage.enterWith(boxedValue);
24
+ } catch {
25
+ storage.run(boxedValue, () => {
26
+ });
27
+ }
28
+ }
15
29
  function updateActiveContext(newContext) {
16
- contextStorage.enterWith(newContext);
30
+ enterOrRun(contextStorage, newContext);
17
31
  const contextWithManager = api.context;
18
32
  const manager = contextWithManager._getContextManager?.();
19
33
  if (!manager) return;
@@ -29,17 +43,17 @@ function updateActiveContext(newContext) {
29
43
  }
30
44
  function createTraceContext(span) {
31
45
  const spanContext = span.spanContext();
32
- const existingStored = contextStorage.getStore();
46
+ const existingStored = contextStorage.getStore()?.value;
33
47
  if (!existingStored) {
34
48
  const activeContext = api.context.active();
35
- contextStorage.enterWith(activeContext);
49
+ enterOrRun(contextStorage, activeContext);
36
50
  }
37
51
  const baggageHelpers = {
38
52
  getBaggage(key) {
39
53
  const activeCtx = api.context.active();
40
54
  let baggage = api.propagation.getBaggage(activeCtx);
41
55
  if (!baggage) {
42
- const storedContext = contextStorage.getStore();
56
+ const storedContext = contextStorage.getStore()?.value;
43
57
  if (storedContext) {
44
58
  baggage = api.propagation.getBaggage(storedContext);
45
59
  }
@@ -48,7 +62,7 @@ function createTraceContext(span) {
48
62
  },
49
63
  setBaggage(key, value) {
50
64
  const activeCtx = api.context.active();
51
- const storedContext = contextStorage.getStore();
65
+ const storedContext = contextStorage.getStore()?.value;
52
66
  const currentContext = storedContext ?? activeCtx;
53
67
  const baggage = api.propagation.getBaggage(currentContext) ?? api.propagation.createBaggage();
54
68
  const updated = baggage.setEntry(key, { value });
@@ -58,7 +72,7 @@ function createTraceContext(span) {
58
72
  },
59
73
  deleteBaggage(key) {
60
74
  const activeCtx = api.context.active();
61
- const storedContext = contextStorage.getStore();
75
+ const storedContext = contextStorage.getStore()?.value;
62
76
  const currentContext = storedContext ?? activeCtx;
63
77
  const baggage = api.propagation.getBaggage(currentContext);
64
78
  if (baggage) {
@@ -71,7 +85,7 @@ function createTraceContext(span) {
71
85
  const activeCtx = api.context.active();
72
86
  let baggage = api.propagation.getBaggage(activeCtx);
73
87
  if (!baggage) {
74
- const storedContext = contextStorage.getStore();
88
+ const storedContext = contextStorage.getStore()?.value;
75
89
  if (storedContext) {
76
90
  baggage = api.propagation.getBaggage(storedContext);
77
91
  }
@@ -90,7 +104,7 @@ function createTraceContext(span) {
90
104
  const activeCtx = api.context.active();
91
105
  let baggage = api.propagation.getBaggage(activeCtx);
92
106
  if (!baggage) {
93
- const storedContext = contextStorage.getStore();
107
+ const storedContext = contextStorage.getStore()?.value;
94
108
  if (storedContext) {
95
109
  baggage = api.propagation.getBaggage(storedContext);
96
110
  }
@@ -110,7 +124,7 @@ function createTraceContext(span) {
110
124
  }),
111
125
  setTypedBaggage: ((namespace, value) => {
112
126
  const activeCtx = api.context.active();
113
- const storedContext = contextStorage.getStore();
127
+ const storedContext = contextStorage.getStore()?.value;
114
128
  const currentContext = storedContext ?? activeCtx;
115
129
  let baggage = api.propagation.getBaggage(currentContext) ?? api.propagation.createBaggage();
116
130
  const prefix = namespace ? `${namespace}.` : "";
@@ -196,7 +210,8 @@ function defineBaggageSchema(namespace) {
196
210
 
197
211
  exports.createTraceContext = createTraceContext;
198
212
  exports.defineBaggageSchema = defineBaggageSchema;
213
+ exports.enterOrRun = enterOrRun;
199
214
  exports.getActiveContextWithBaggage = getActiveContextWithBaggage;
200
215
  exports.getContextStorage = getContextStorage;
201
- //# sourceMappingURL=chunk-W4EUTSB2.cjs.map
202
- //# sourceMappingURL=chunk-W4EUTSB2.cjs.map
216
+ //# sourceMappingURL=chunk-HZ3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AS,CAAA,CAAA,CAAA,GAAM,EAAA;AAC7C,MAAA,MAAM,cAAsC,EAAC;AAC7C,MAAA,KAAA,MAAW,CAAC,GAAA,EAAK,GAAG,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAC9C,QAAA,IAAI,QAAQ,MAAA,EAAW;AACrB,UAAA,WAAA,CAAY,GAAG,MAAM,CAAA,EAAG,GAAG,CAAA,CAAE,CAAA,GAAI,OAAO,GAAG,CAAA;AAAA,QAC7C;AAAA,MACF;AAGA,MAAA,MAAM,cAAA,GAAiBD,YAAQ,MAAA,EAAO;AACtC,MAAA,IAAI,UACFC,eAAA,CAAY,UAAA,CAAW,cAAc,CAAA,IAAKA,gBAAY,aAAA,EAAc;AAEtE,MAAA,KAAA,MAAW,CAAC,GAAA,EAAK,GAAG,KAAK,MAAA,CAAO,OAAA,CAAQ,WAAW,CAAA,EAAG;AACpD,QAAA,OAAA,GAAU,QAAQ,QAAA,CAAS,GAAA,EAAK,EAAE,KAAA,EAAO,KAAK,CAAA;AAAA,MAChD;AAEA,MAAA,MAAM,UAAA,GAAaA,eAAA,CAAY,UAAA,CAAW,cAAA,EAAgB,OAAO,CAAA;AACjE,MAAA,OAAOD,WAAA,CAAQ,IAAA,CAAK,UAAA,EAAY,EAAE,CAAA;AAAA,IACpC;AAAA,GACF;AACF","file":"chunk-HZ3FYBJG.cjs","sourcesContent":["/**\n * Trace context types and utilities\n */\n\nimport type {\n Span,\n SpanStatusCode,\n BaggageEntry,\n Context,\n Link,\n TimeInput,\n} from '@opentelemetry/api';\nimport { context, propagation } from '@opentelemetry/api';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\ntype AsyncLocalBox<T> = {\n value: T;\n};\n\n/**\n * AsyncLocalStorage for storing the active context with baggage\n * This allows setters to update the context and have it persist\n */\nconst contextStorage = new AsyncLocalStorage<AsyncLocalBox<Context>>();\n\n/**\n * Get the context storage instance (for initialization in functional.ts)\n */\nexport function getContextStorage(): AsyncLocalStorage<AsyncLocalBox<Context>> {\n return contextStorage;\n}\n\n/**\n * Get the active context, checking our stored context first\n * This ensures baggage setters work with OpenTelemetry's propagation\n */\nexport function getActiveContextWithBaggage(): Context {\n // Check stored context first (from setters), then fall back to active context\n // This ensures ctx.setBaggage() changes are visible to OpenTelemetry operations\n const stored = contextStorage.getStore()?.value;\n return stored ?? context.active();\n}\n\n/**\n * Set a value in AsyncLocalStorage, preferring enterWith() when available\n * (Node.js) and falling back to run() for environments that only support\n * run() (e.g. Cloudflare Workers).\n *\n * On runtimes without enterWith() we mutate the existing run() scope when one\n * exists. This is what allows baggage/correlation updates to remain visible\n * for the rest of the traced callback in Workers.\n */\nexport function enterOrRun<T>(\n storage: AsyncLocalStorage<AsyncLocalBox<T>>,\n value: T,\n): void {\n const existingStore = storage.getStore();\n if (existingStore) {\n existingStore.value = value;\n return;\n }\n\n const boxedValue = { value };\n try {\n storage.enterWith(boxedValue);\n } catch {\n // Cloudflare Workers define enterWith but throw at runtime\n storage.run(boxedValue, () => {});\n }\n}\n\n/**\n * Try to keep OpenTelemetry's context manager in sync with baggage updates\n */\ntype ContextManagerLike = {\n with?: (ctx: Context, fn: () => void) => void;\n _asyncLocalStorage?: { enterWith?: (ctx: Context) => void };\n};\n\nfunction updateActiveContext(newContext: Context): void {\n // Update our storage first so any helper reads see the new context\n enterOrRun(contextStorage, newContext);\n\n const contextWithManager = context as unknown as {\n _getContextManager?: () => ContextManagerLike;\n };\n\n const manager = contextWithManager._getContextManager?.();\n if (!manager) return;\n\n const asyncLocal =\n (manager as { _asyncLocalStorage?: { enterWith?: (ctx: Context) => void } })\n ._asyncLocalStorage ?? undefined;\n if (asyncLocal?.enterWith) {\n asyncLocal.enterWith(newContext);\n return;\n }\n\n if (typeof manager.with === 'function') {\n manager.with(newContext, () => {});\n }\n}\n\n/**\n * Base trace context containing trace identifiers\n */\nexport interface TraceContextBase {\n traceId: string;\n spanId: string;\n correlationId: string;\n}\n\n/**\n * Attribute value types following OpenTelemetry specification.\n * Supports primitive values and arrays of homogeneous primitives.\n */\nexport type AttributeValue =\n | string\n | number\n | boolean\n | string[]\n | number[]\n | boolean[];\n\n/**\n * Span methods available on trace context\n */\nexport interface SpanMethods {\n /** Set a single attribute on the span */\n setAttribute(key: string, value: AttributeValue): void;\n /** Set multiple attributes on the span */\n setAttributes(attrs: Record<string, AttributeValue>): void;\n /** Set the status of the span */\n setStatus(status: { code: SpanStatusCode; message?: string }): void;\n /** Record an exception on the span */\n recordException(exception: Error, time?: TimeInput): void;\n /** Add an event to the span (for logging milestones/checkpoints) */\n addEvent(\n name: string,\n attributesOrStartTime?: Record<string, AttributeValue> | TimeInput,\n startTime?: TimeInput,\n ): void;\n /** Add a link to another span */\n addLink(link: Link): void;\n /** Add multiple links to other spans */\n addLinks(links: Link[]): void;\n /** Update the span name dynamically */\n updateName(name: string): void;\n /** Check if the span is recording */\n isRecording(): boolean;\n}\n\n/**\n * Baggage methods available on trace context\n *\n * @template TBaggage - Optional type for typed baggage (defaults to undefined for untyped)\n */\nexport interface BaggageMethods<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n> {\n /**\n * Get a baggage entry by key\n * @param key - Baggage key\n * @returns Baggage entry value or undefined\n */\n getBaggage(key: string): string | undefined;\n\n /**\n * Set a baggage entry\n *\n * Note: OpenTelemetry contexts are immutable. For proper scoping across async\n * boundaries, use withBaggage() instead. This method updates baggage in the\n * current context which may not propagate to all child operations.\n *\n * @param key - Baggage key\n * @param value - Baggage value\n * @returns The baggage value that was set (for chaining)\n *\n * @example Using withBaggage() (recommended)\n * ```typescript\n * await withBaggage({ baggage: { 'key': 'value' }, fn: async () => {\n * // Baggage is available here and in child spans\n * });\n * ```\n */\n setBaggage(key: string, value: string): string;\n\n /**\n * Delete a baggage entry\n *\n * Note: OpenTelemetry contexts are immutable. For proper scoping across async\n * boundaries, use withBaggage() with only the entries you want instead.\n *\n * @param key - Baggage key\n */\n deleteBaggage(key: string): void;\n\n /**\n * Get all baggage entries\n * @returns Map of all baggage entries\n */\n getAllBaggage(): Map<string, BaggageEntry>;\n\n /**\n * Get typed baggage (only available when TBaggage is defined)\n * This is used internally by defineBaggageSchema()\n *\n * @internal\n */\n getTypedBaggage?: TBaggage extends Record<string, unknown>\n ? <T extends TBaggage>(namespace?: string) => Partial<T> | undefined\n : never;\n\n /**\n * Set typed baggage (only available when TBaggage is defined)\n * This is used internally by defineBaggageSchema()\n *\n * @internal\n */\n setTypedBaggage?: TBaggage extends Record<string, unknown>\n ? <T extends TBaggage>(\n namespace: string | undefined,\n value: Partial<T>,\n ) => void\n : never;\n}\n\n/**\n * Complete trace context that merges base context, span methods, and baggage methods\n *\n * This is the ctx parameter passed to factory functions in trace().\n * It provides access to trace IDs, span manipulation methods, and baggage operations.\n *\n * @template TBaggage - Optional type for typed baggage support\n *\n * @example Untyped (default)\n * ```typescript\n * export const handler = trace((ctx) => async () => {\n * ctx.getBaggage('key'); // returns string | undefined\n * });\n * ```\n *\n * @example Typed baggage\n * ```typescript\n * type TenantBaggage = { tenantId: string; region?: string };\n *\n * export const handler = trace<TenantBaggage>((ctx) => async () => {\n * // Use typed schema helper for type-safe access\n * const schema = defineBaggageSchema<TenantBaggage>('tenant');\n * const tenant = schema.get(ctx); // Partial<TenantBaggage> | undefined\n * });\n * ```\n */\nexport type TraceContext<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n> = TraceContextBase & SpanMethods & BaggageMethods<TBaggage>;\n\n/**\n * Create a TraceContext from an OpenTelemetry Span\n *\n * This utility extracts trace context information from a span\n * and provides span manipulation methods and baggage operations in a consistent format.\n *\n * Note: Baggage methods always operate on the currently active context,\n * which may differ from the context when createTraceContext was called.\n */\nexport function createTraceContext<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(span: Span): TraceContext<TBaggage> {\n const spanContext = span.spanContext();\n\n // Store the current active context in AsyncLocalStorage so baggage setters can update it\n // This ensures ctx.setBaggage() changes persist and are visible to OpenTelemetry operations\n // IMPORTANT: Only initialize if not already set (preserve baggage updates from parent spans)\n const existingStored = contextStorage.getStore()?.value;\n if (!existingStored) {\n const activeContext = context.active();\n enterOrRun(contextStorage, activeContext);\n }\n\n // Baggage helpers that always use the current active context\n // This ensures baggage operations work correctly even if context changes\n const baggageHelpers: BaggageMethods<TBaggage> = {\n getBaggage(key: string): string | undefined {\n // Check active context first (from withBaggage, context.with, etc.)\n // Then check stored context (from setters)\n // This ensures both withBaggage() and ctx.setBaggage() work correctly\n const activeCtx = context.active();\n let baggage = propagation.getBaggage(activeCtx);\n if (!baggage) {\n const storedContext = contextStorage.getStore()?.value;\n if (storedContext) {\n baggage = propagation.getBaggage(storedContext);\n }\n }\n return baggage?.getEntry(key)?.value;\n },\n\n setBaggage(key: string, value: string): string {\n // OpenTelemetry contexts are immutable, so we create a new context with updated baggage\n // Check active context first (may have baggage from withBaggage), then stored context\n const activeCtx = context.active();\n const storedContext = contextStorage.getStore()?.value;\n const currentContext = storedContext ?? activeCtx;\n const baggage =\n propagation.getBaggage(currentContext) ?? propagation.createBaggage();\n const updated = baggage.setEntry(key, { value });\n const newContext = propagation.setBaggage(currentContext, updated);\n\n updateActiveContext(newContext);\n\n return value;\n },\n\n deleteBaggage(key: string): void {\n // Check active context first, then stored context\n const activeCtx = context.active();\n const storedContext = contextStorage.getStore()?.value;\n const currentContext = storedContext ?? activeCtx;\n const baggage = propagation.getBaggage(currentContext);\n if (baggage) {\n const updated = baggage.removeEntry(key);\n const newContext = propagation.setBaggage(currentContext, updated);\n\n updateActiveContext(newContext);\n }\n },\n\n getAllBaggage(): Map<string, BaggageEntry> {\n // Check active context first, then stored context\n const activeCtx = context.active();\n let baggage = propagation.getBaggage(activeCtx);\n if (!baggage) {\n const storedContext = contextStorage.getStore()?.value;\n if (storedContext) {\n baggage = propagation.getBaggage(storedContext);\n }\n }\n if (!baggage) {\n return new Map();\n }\n\n // Convert baggage entries to a Map\n const entries = new Map<string, BaggageEntry>();\n for (const [key, entry] of baggage.getAllEntries()) {\n entries.set(key, entry);\n }\n return entries;\n },\n\n // Typed baggage helpers (used by defineBaggageSchema)\n getTypedBaggage: (<T extends Record<string, unknown>>(\n namespace?: string,\n ) => {\n // Check active context first, then stored context\n const activeCtx = context.active();\n let baggage = propagation.getBaggage(activeCtx);\n if (!baggage) {\n const storedContext = contextStorage.getStore()?.value;\n if (storedContext) {\n baggage = propagation.getBaggage(storedContext);\n }\n }\n if (!baggage) return;\n\n const prefix = namespace ? `${namespace}.` : '';\n const result: Record<string, unknown> = {};\n\n for (const [key, entry] of baggage.getAllEntries()) {\n if (namespace && key.startsWith(prefix)) {\n const fieldName = key.slice(prefix.length);\n result[fieldName] = entry.value;\n } else if (!namespace) {\n result[key] = entry.value;\n }\n }\n\n return Object.keys(result).length > 0\n ? (result as Partial<T>)\n : undefined;\n }) as TBaggage extends Record<string, unknown>\n ? <T extends TBaggage>(namespace?: string) => Partial<T> | undefined\n : never,\n\n setTypedBaggage: (<T extends Record<string, unknown>>(\n namespace: string | undefined,\n value: Partial<T>,\n ) => {\n // Check active context first, then stored context\n const activeCtx = context.active();\n const storedContext = contextStorage.getStore()?.value;\n const currentContext = storedContext ?? activeCtx;\n let baggage =\n propagation.getBaggage(currentContext) ?? propagation.createBaggage();\n\n const prefix = namespace ? `${namespace}.` : '';\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n const baggageKey = `${prefix}${key}`;\n baggage = baggage.setEntry(baggageKey, { value: String(val) });\n }\n }\n\n const newContext = propagation.setBaggage(currentContext, baggage);\n updateActiveContext(newContext);\n }) as TBaggage extends Record<string, unknown>\n ? <T extends TBaggage>(\n namespace: string | undefined,\n value: Partial<T>,\n ) => void\n : never,\n };\n\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n correlationId: spanContext.traceId.slice(0, 16),\n setAttribute: span.setAttribute.bind(span),\n setAttributes: span.setAttributes.bind(span),\n setStatus: span.setStatus.bind(span),\n recordException: span.recordException.bind(span),\n addEvent: span.addEvent.bind(span),\n addLink: span.addLink.bind(span),\n addLinks: span.addLinks.bind(span),\n updateName: span.updateName.bind(span),\n isRecording: span.isRecording.bind(span),\n ...baggageHelpers,\n };\n}\n\n/**\n * Define a typed baggage schema for type-safe baggage operations\n *\n * This helper provides a type-safe API for working with baggage entries.\n * The namespace parameter is optional and prefixes all keys to avoid collisions.\n *\n * @template T - The baggage schema type (all fields are treated as optional)\n * @param namespace - Optional namespace to prefix baggage keys\n *\n * @example Basic usage\n * ```typescript\n * type TenantBaggage = { tenantId: string; region?: string };\n * const tenantBaggage = defineBaggageSchema<TenantBaggage>('tenant');\n *\n * export const handler = trace<TenantBaggage>((ctx) => async () => {\n * // Get typed baggage\n * const tenant = tenantBaggage.get(ctx);\n * if (tenant?.tenantId) {\n * console.log('Tenant:', tenant.tenantId);\n * }\n *\n * // Set typed baggage\n * tenantBaggage.set(ctx, { tenantId: 't1', region: 'us-east-1' });\n * });\n * ```\n *\n * @example With withBaggage helper\n * ```typescript\n * const tenantBaggage = defineBaggageSchema<TenantBaggage>('tenant');\n *\n * export const handler = trace<TenantBaggage>((ctx) => async () => {\n * return await tenantBaggage.with(ctx, { tenantId: 't1' }, async () => {\n * // Baggage is available here and in child spans\n * const tenant = tenantBaggage.get(ctx);\n * });\n * });\n * ```\n */\nexport function defineBaggageSchema<T extends Record<string, unknown>>(\n namespace?: string,\n) {\n return {\n /**\n * Get typed baggage from context\n * @param ctx - Trace context\n * @returns Partial baggage object or undefined if no baggage is set\n */\n get: (ctx: TraceContext<T>): Partial<T> | undefined => {\n if (!ctx.getTypedBaggage) return undefined;\n return ctx.getTypedBaggage<T>(namespace);\n },\n\n /**\n * Set typed baggage in context\n *\n * Note: For proper scoping across async boundaries, use the `with` method instead\n *\n * @param ctx - Trace context\n * @param value - Partial baggage object to set\n */\n set: (ctx: TraceContext<T>, value: Partial<T>): void => {\n if (!ctx.setTypedBaggage) return;\n ctx.setTypedBaggage<T>(namespace, value);\n },\n\n /**\n * Run a function with typed baggage properly scoped\n *\n * This is the recommended way to set baggage as it ensures proper\n * scoping across async boundaries.\n *\n * @param ctx - Trace context (can be omitted, will use active context)\n * @param value - Partial baggage object to set\n * @param fn - Function to execute with the baggage\n */\n with: <R>(\n ctxOrValue: TraceContext<T> | Partial<T>,\n valueOrFn: Partial<T> | (() => R | Promise<R>),\n maybeFn?: () => R | Promise<R>,\n ): R | Promise<R> => {\n // Support both with(ctx, value, fn) and with(value, fn)\n const value = maybeFn\n ? (valueOrFn as Partial<T>)\n : (ctxOrValue as Partial<T>);\n const fn = maybeFn || (valueOrFn as () => R | Promise<R>);\n\n // Serialize typed baggage to flat key-value pairs\n const prefix = namespace ? `${namespace}.` : '';\n const flatBaggage: Record<string, string> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n flatBaggage[`${prefix}${key}`] = String(val);\n }\n }\n\n // Use the existing withBaggage helper\n const currentContext = context.active();\n let baggage =\n propagation.getBaggage(currentContext) ?? propagation.createBaggage();\n\n for (const [key, val] of Object.entries(flatBaggage)) {\n baggage = baggage.setEntry(key, { value: val });\n }\n\n const newContext = propagation.setBaggage(currentContext, baggage);\n return context.with(newContext, fn);\n },\n };\n}\n"]}
@@ -1,13 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var chunkRMGSBMQF_cjs = require('./chunk-RMGSBMQF.cjs');
3
+ var chunkQQLP4M6W_cjs = require('./chunk-QQLP4M6W.cjs');
4
4
  var chunk7FIGORWI_cjs = require('./chunk-7FIGORWI.cjs');
5
5
  var api = require('@opentelemetry/api');
6
6
 
7
7
  function traceProducer(config) {
8
8
  const spanName = `${config.system}.publish ${config.destination}`;
9
9
  return (fnFactory) => {
10
- return chunkRMGSBMQF_cjs.trace(
10
+ return chunkQQLP4M6W_cjs.trace(
11
11
  { name: spanName, spanKind: api.SpanKind.PRODUCER },
12
12
  (baseCtx) => {
13
13
  const ctx = extendContextForProducer(baseCtx, config);
@@ -41,7 +41,7 @@ function traceConsumer(config) {
41
41
  const operation = config.batchMode ? "receive" : "process";
42
42
  const spanName = `${config.system}.${operation} ${config.destination}`;
43
43
  return (fnFactory) => {
44
- return chunkRMGSBMQF_cjs.trace(
44
+ return chunkQQLP4M6W_cjs.trace(
45
45
  { name: spanName, spanKind: api.SpanKind.CONSUMER },
46
46
  (baseCtx) => {
47
47
  const linkStorage = { links: [] };
@@ -794,5 +794,5 @@ function clearOrderingState() {
794
794
  exports.clearOrderingState = clearOrderingState;
795
795
  exports.traceConsumer = traceConsumer;
796
796
  exports.traceProducer = traceProducer;
797
- //# sourceMappingURL=chunk-WOWTZ4EB.cjs.map
798
- //# sourceMappingURL=chunk-WOWTZ4EB.cjs.map
797
+ //# sourceMappingURL=chunk-I6JPSD4R.cjs.map
798
+ //# sourceMappingURL=chunk-I6JPSD4R.cjs.map