{"_id":"@blueground/async-mdc","name":"@blueground/async-mdc","dist-tags":{"latest":"1.0.2"},"versions":{"1.0.2":{"name":"@blueground/async-mdc","version":"1.0.2","description":"Async hooks based Mapped Diagnostic Context, inspired by SLF4J's MDC. Typically used with logging libraries for log enrichment.","keywords":["async","asynclocalstorage","logger","logging","logs","mapped diagnostic context","mdc"],"homepage":"https://github.com/bluegroundltd/async-mdc#readme","bugs":{"url":"https://github.com/bluegroundltd/async-mdc/issues"},"repository":{"type":"git","url":"git+https://github.com/bluegroundltd/async-mdc.git"},"license":"MIT","author":{"name":"Stratos Pavlakis","email":"stratosp@theblueground.com"},"type":"module","exports":{"./package.json":"./package.json",".":{"require":"./dist/cjs/index.js","import":"./dist/esm/index.js"}},"main":"dist/cjs/index.js","module":"dist/esm/index.js","types":"dist/esm/index.d.ts","scripts":{"build:cjs":"tsc --module commonjs --declaration --sourceMap --outDir dist/cjs","build:esm":"tsc --module NodeNext --declaration --sourceMap --outDir dist/esm","build:package:esm":"echo '{\"type\": \"module\"}' > ./dist/esm/package.json","build:package:cjs":"echo '{\"type\": \"commonjs\"}' > ./dist/cjs/package.json","prebuild":"rimraf dist/ && mkdir dist","build":"run-s build:* build:package:*","lint:eslint":"eslint ./src","lint:prettier":"prettier --check ./src","lint:tsc":"tsc --noEmit","lint":"run-s lint:prettier lint:eslint lint:tsc","prepare":"husky","test":"test","types:cjs":"tsc --emitDeclarationOnly --declaration --outdir dist/cjs","types:esm":"tsc --emitDeclarationOnly --declaration --outdir dist/esm","types":"run-s types:*","release":"release-it"},"lint-staged":{"*.{js,ts}":["npm run lint","prettier --write"],"*.json":["prettier --write"]},"devDependencies":{"@commitlint/cli":"^19.3.0","@commitlint/config-conventional":"^19.2.2","@eslint/js":"^9.6.0","@types/node":"^20.14.9","eslint":"^8.57.0","eslint-config-prettier":"^9.1.0","husky":"^9.0.11","lint-staged":"^15.2.7","npm-run-all":"^4.1.5","prettier":"^3.3.2","release-it":"^17.4.1","rimraf":"^5.0.7","typescript":"^5.5.3","typescript-eslint":"^7.15.0"},"engines":{"node":">=20.0.0"},"publishConfig":{"access":"public"},"_id":"@blueground/async-mdc@1.0.2","gitHead":"bbabbfe0c554351f1a75e40828aa2ffbabe75a26","_nodeVersion":"20.18.1","_npmVersion":"10.8.2","dist":{"integrity":"sha512-l2Th4h9i4q81nKNtFC/QXGflzN50bTsq6UZ0XqxOsw4ZXRiCjr7rEbU8BkuzvzpdbfdNZ1X2Tk+tqOXkNX1pUg==","shasum":"27f4f7dad9b2f5580a4d5458f4fdbc098d513b87","tarball":"https://registry.npmjs.org/@blueground/async-mdc/-/async-mdc-1.0.2.tgz","fileCount":17,"unpackedSize":18673,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIFO1AUnHIzBXKVABPvKVu4jr5zm1b7hRyyZJh1zNZbAAAiEA0JMNez/m/qphHLCX0Z8YZ+vWY+d1CkhH0nAJfnkmgGU="}]},"_npmUser":{"name":"stratosp","email":"stratosp@theblueground.com"},"directories":{},"maintainers":[{"name":"stratosp","email":"stratosp@theblueground.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/async-mdc_1.0.2_1757089248547_0.7807999542138275"},"_hasShrinkwrap":false}},"time":{"created":"2025-09-05T16:20:48.363Z","1.0.2":"2025-09-05T16:20:48.718Z","modified":"2025-09-05T16:20:49.085Z"},"maintainers":[{"name":"stratosp","email":"stratosp@theblueground.com"}],"description":"Async hooks based Mapped Diagnostic Context, inspired by SLF4J's MDC. Typically used with logging libraries for log enrichment.","homepage":"https://github.com/bluegroundltd/async-mdc#readme","keywords":["async","asynclocalstorage","logger","logging","logs","mapped diagnostic context","mdc"],"repository":{"type":"git","url":"git+https://github.com/bluegroundltd/async-mdc.git"},"author":{"name":"Stratos Pavlakis","email":"stratosp@theblueground.com"},"bugs":{"url":"https://github.com/bluegroundltd/async-mdc/issues"},"license":"MIT","readme":"# Async MDC\n\nA lightweight, type-safe Mapped Diagnostic Context (MDC) implementation for Node.js applications using async hooks. This library provides a clean way to manage contextual data across asynchronous operations, making it perfect for request tracing, logging, and maintaining application state throughout the call chain.\n\n## Features\n\n- 🚀 **Zero Dependencies** - Built on Node.js native `AsyncLocalStorage`\n- 🔒 **Type Safe** - Full TypeScript support with custom store interfaces\n- 🛡️ **Safe Operations** - Both throwing and non-throwing variants for all operations\n- 🔄 **Logger Integration** - Works seamlessly with Pino, Bunyan, Winston, and other loggers\n\n## Install\n\n```sh\n$ npm i --save @bluegroundltd/async-mdc     # NPM\n$ yarn add --save @bluegroundltd/async-mdc  # Yarn\n$ bun add --save @bluegroundltd/async-mdc   # Bun\n$ pnpm add --save @bluegroundltd/async-mdc  # PNPM\n```\n\n## Basic Usage\n\n```typescript\n// mdc.ts\nimport {MDC} from '@bluegroundltd/async-mdc';\nexport {MDC};\n\n// You can define your own MDC store or use the default Record<string, any>\nexport interface MDCStore extends Record<string, unknown> {\n  correlationId: string;\n  user: {\n    userId: string;\n    email: string;\n  };\n  ip: string;\n  meta?: {\n    foo?: string;\n    bar?: string;\n  };\n}\n\nexport const mdc = new MDC<MDCStore>();\n\n// middleware.ts\nimport {mdc} from 'mdc.js';\napp.get((req, res, next) => {\n  mdc.set('user', req.session.user);\n  next();\n});\n\n// service.ts\nfunction foo() {\n  // access user\n  const user = mdc.safeGet('user');\n}\n```\n\n## API\n\n### new MDC([storage]): MDC\n\n```typescript\nimport {MDC} from '@bluegroundltd/async-mdc';\nexport {MDC};\n\n// You can define your own MDC store or use the default Record<string, any>\nexport interface MDCStore extends Record<string, unknown> {\n  color: string;\n  height?: number;\n}\n\nconst mdc = new MDC<MDCStore>();\n\n// or define your own storage\nconst asl = new AsyncLocalStorage<MDCStore>();\nconst mdc = new MDC<MDCStore>(asl);\n```\n\n### get(key, [defaultValue])\n\nGet the value associated with `key`.\n\n`get` throws if the underlying [AsyncLocalStorage](https://nodejs.org/api/async_context.html#class-asynclocalstorage) is not initialized\n\n```typescript\nmdc.get('color');\nmdc.get('color', 'black');\n```\n\n### safeGet(key, [defaultValue])\n\nGet the value associated with `key`.\n\n`safeGet` never throws and returns `undefined` or `defaultValue` if given instead\n\n```typescript\nmdc.safeGet('color');\nmdc.safeGet('color', 'black');\n```\n\n### set(key, value)\n\nAdds or updates an entry in this mdc with a specified key and a value.\n\n`set` throws if the underlying [AsyncLocalStorage](https://nodejs.org/api/async_context.html#class-asynclocalstorage) is not initialized\n\n```typescript\nmdc.set('color', 'white');\n```\n\n### safeSet(key, value)\n\nAdds or updates an entry in this mdc with a specified key and a value.\n\n`safeSet` never throws and behaves as a noop instead\n\n```typescript\nmdc.safeSet('color', 'white');\n```\n\n### getCopyOfStore(): Store\n\n`getCopyOfStore` returns a shallow copy of the async context's store\n\n```typescript\nmdc.getCopyOfStore();\n```\n\n### clear()\n\nClears the store by removing all of its keys\n\n```typescript\nmdc.clear();\n```\n\n### run<R>(store: Store, callback: () => R, ...args): R\n\nDelegates to the underlying [asyncLocalStorage.run](https://nodejs.org/api/async_context.html#asynclocalstoragerunstore-callback-args)\n\n## Usage with loggers\n\n### Pino\n\nhttps://github.com/pinojs/pino\n\n```typescript\n// logger.ts\nimport {pino} from 'pino';\nimport {MDC} from '@bluegroundltd/async-mdc';\n\n// Import from another module e.g. mdc.js\nimport {mdc} from 'mdc.js';\n// Or create and export from here\nexport const mdc = new MDC();\n\n// Enrich every log message with bindings from the MDC store\n// @see {@link https://github.com/pinojs/pino/blob/main/docs/api.md#mixin-function}\nfunction mixin() {\n  return mdc.getCopyOfStore();\n}\n\nexport const logger = pino({\n  mixin\n});\n```\n\n### Bunyan\n\nhttps://github.com/trentm/node-bunyan\n\n```typescript\n// logger.ts\nimport bunyan from 'bunyan';\nimport {MDC} from '@bluegroundltd/async-mdc';\n\n// Import from another module e.g. mdc.js\nimport {mdc} from 'mdc.js';\n// Or create and export from here\nexport const mdc = new MDC();\n\nconst logger = bunyan.createLogger({\n  name: 'myapp',\n  mdc,\n  serializers: {\n    ...bunyan.stdSerializers,\n    mdc(_mdc) {\n      return _mdc.getCopyOfStore();\n    }\n  }\n});\n```\n\n### Winston 3.x\n\nhttps://github.com/winstonjs/winston\n\n```typescript\n// logger.ts\nimport winston from 'winston';\nimport {MDC} from '@bluegroundltd/async-mdc';\n\n// Import from another module e.g. mdc.js\nimport {mdc} from 'mdc.js';\n// Or create and export from here\nexport const mdc = new MDC();\n\nconst mdcFormat = winston.format((info, opts) => {\n  return {\n    ...mdc.getCopyOfStore(),\n    ...info\n  };\n});\n\nconst logger = winston.createLogger({\n  level: 'info',\n  format: winston.format.combine(winston.format.json(), mdcFormat)\n});\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n### MIT License\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n---\n\n**Copyright © 2025 Blueground Ltd. All rights reserved.**\n","readmeFilename":"README.md","_rev":"1-4878ea6d6ae8dceecd29fffe831e6d25"}