12 Commits

9 changed files with 448 additions and 358 deletions

View File

@ -1,5 +1,44 @@
# Changelog # Changelog
## 2025-01-19 - 2.1.6 - fix(core)
Updated dependencies and improved AsyncStore debugging and cleanup
- Upgraded 'simple-async-context' dependency to version ^0.0.16 for consistency and improvements.
- Added detailed debugging information in AsyncStore when DEBUG environment variable is set.
- Enhanced cleanup process for deleted keys in AsyncStore.
- Removed redundant dependencies from package.json and logcontext.plugins.ts.
## 2025-01-19 - 2.1.5 - fix(dependencies)
Update dependencies for improved compatibility
- Updated @types/node to version ^22.10.7
- Updated @types/shortid to version 2.2.0
- Updated simple-async-context to version ^0.0.15
## 2025-01-19 - 2.1.4 - fix(documentation)
Remove unnecessary conclusion section from the README for better clarity.
- Removed the 'Conclusion' header which was redundant in the README.
## 2025-01-19 - 2.1.3 - fix(readme)
Update README.md for better clarity and examples.
- Enhanced documentation with clearer examples of AsyncContext usage.
- Reorganized sections for improved understanding of `runScoped` and its benefits.
- Added detailed test script example in README.md.
- Clarified data isolation and deletion mechanisms within scoped functions.
## 2025-01-19 - 2.1.2 - fix(core)
Improve scope handling in async contexts.
- Modified the handling of scoped stores within `AsyncContext.runScoped` to simplify the API usage.
- Refactored tests to verify the context's behavior and isolation between parent and child stores.
## 2025-01-18 - 2.1.1 - fix(build)
Fix tsbuild script to include missing flag
- Updated the build script in package.json to include --allowimplicitany flag.
## 2025-01-18 - 2.1.0 - feat(ci) ## 2025-01-18 - 2.1.0 - feat(ci)
Add GitHub Actions workflows for CI/CD Add GitHub Actions workflows for CI/CD

View File

@ -1,6 +1,6 @@
{ {
"name": "@push.rocks/smartcontext", "name": "@push.rocks/smartcontext",
"version": "2.1.0", "version": "2.1.6",
"description": "A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.", "description": "A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.",
"exports": { "exports": {
".": "./dist_ts/index.js" ".": "./dist_ts/index.js"
@ -10,7 +10,7 @@
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/)",
"build": "(tsbuild --web)", "build": "(tsbuild --allowimplicitany --web)",
"buildDocs": "tsdoc" "buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
@ -19,15 +19,11 @@
"@git.zone/tsrun": "^1.2.39", "@git.zone/tsrun": "^1.2.39",
"@git.zone/tstest": "^1.0.57", "@git.zone/tstest": "^1.0.57",
"@push.rocks/smartdelay": "^3.0.5", "@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/tapbundle": "^5.0.4", "@push.rocks/tapbundle": "^5.5.6",
"@types/node": "^18.11.18" "@types/node": "^22.10.7"
}, },
"dependencies": { "dependencies": {
"@push.rocks/lik": "^6.0.0", "simple-async-context": "^0.0.16"
"@push.rocks/smartcls": "^1.0.9",
"@push.rocks/smartunique": "^3.0.3",
"@types/shortid": "0.0.29",
"simple-async-context": "^0.0.13"
}, },
"private": false, "private": false,
"browserslist": [ "browserslist": [

137
pnpm-lock.yaml generated
View File

@ -8,21 +8,9 @@ importers:
.: .:
dependencies: dependencies:
'@push.rocks/lik':
specifier: ^6.0.0
version: 6.1.0
'@push.rocks/smartcls':
specifier: ^1.0.9
version: 1.0.14
'@push.rocks/smartunique':
specifier: ^3.0.3
version: 3.0.9
'@types/shortid':
specifier: 0.0.29
version: 0.0.29
simple-async-context: simple-async-context:
specifier: ^0.0.13 specifier: ^0.0.16
version: 0.0.13 version: 0.0.16
devDependencies: devDependencies:
'@git.zone/tsbuild': '@git.zone/tsbuild':
specifier: ^2.1.27 specifier: ^2.1.27
@ -40,11 +28,11 @@ importers:
specifier: ^3.0.5 specifier: ^3.0.5
version: 3.0.5 version: 3.0.5
'@push.rocks/tapbundle': '@push.rocks/tapbundle':
specifier: ^5.0.4 specifier: ^5.5.6
version: 5.5.4(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3) version: 5.5.6(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3)
'@types/node': '@types/node':
specifier: ^18.11.18 specifier: ^22.10.7
version: 18.19.71 version: 22.10.7
packages: packages:
@ -729,9 +717,6 @@ packages:
'@push.rocks/smartcli@4.0.11': '@push.rocks/smartcli@4.0.11':
resolution: {integrity: sha512-KDWfUqWBoUZsOEtsDx36d6qc8GG7Zo5E+HHamYY68KVDO8BMu6jbBucoUUPDksczLEmbXKLmroBP1mn/xozQOA==} resolution: {integrity: sha512-KDWfUqWBoUZsOEtsDx36d6qc8GG7Zo5E+HHamYY68KVDO8BMu6jbBucoUUPDksczLEmbXKLmroBP1mn/xozQOA==}
'@push.rocks/smartcls@1.0.14':
resolution: {integrity: sha512-1Sew9ZVTS8mdaKMlOOKZ9uCcSa6QXAfT7yX8xgqF24bXZvyUcf0Lf0d6VvlAMiFJ3bA0H8AsmRFJ8F7HlKW1RA==}
'@push.rocks/smartcrypto@2.0.4': '@push.rocks/smartcrypto@2.0.4':
resolution: {integrity: sha512-1+/5bsjyataf5uUkUNnnVXGRAt+gHVk1KDzozjTqgqJxHvQk1d9fVDohL6CxUhUucTPtu5VR5xNBiV8YCDuGyw==} resolution: {integrity: sha512-1+/5bsjyataf5uUkUNnnVXGRAt+gHVk1KDzozjTqgqJxHvQk1d9fVDohL6CxUhUucTPtu5VR5xNBiV8YCDuGyw==}
@ -825,6 +810,9 @@ packages:
'@push.rocks/smartpromise@4.1.0': '@push.rocks/smartpromise@4.1.0':
resolution: {integrity: sha512-1E4QZx1bYFMEgbK1C9gb4CB3YRhfkvSeffc5CnT83n7NV4Qly/Sxe9G1Jn0sQBB5+sbFHwTlj/0al5+q4gXiDw==} resolution: {integrity: sha512-1E4QZx1bYFMEgbK1C9gb4CB3YRhfkvSeffc5CnT83n7NV4Qly/Sxe9G1Jn0sQBB5+sbFHwTlj/0al5+q4gXiDw==}
'@push.rocks/smartpromise@4.2.0':
resolution: {integrity: sha512-1Yb0u/Yu68D1GPuxPhfMe2MefffqqzK+WmtrCipQl75cBXyaiNiwwrRKaG47ZJquMS+BYxqC/P40cDVAWDvMfw==}
'@push.rocks/smartpuppeteer@2.0.2': '@push.rocks/smartpuppeteer@2.0.2':
resolution: {integrity: sha512-EcYCT0PX++WjfHp7W5UYX3t8x5gSNpJMMUvhA7SHz8b2t76ItslNWxprRcF0CUQyN1fozbf5StZf7dwdGc/dIA==} resolution: {integrity: sha512-EcYCT0PX++WjfHp7W5UYX3t8x5gSNpJMMUvhA7SHz8b2t76ItslNWxprRcF0CUQyN1fozbf5StZf7dwdGc/dIA==}
@ -882,8 +870,8 @@ packages:
'@push.rocks/smartyaml@2.0.5': '@push.rocks/smartyaml@2.0.5':
resolution: {integrity: sha512-tBcf+HaOIfeEsTMwgUZDtZERCxXQyRsWO8Ar5DjBdiSRchbhVGZQEBzXswMS0W5ZoRenjgPK+4tPW3JQGRTfbg==} resolution: {integrity: sha512-tBcf+HaOIfeEsTMwgUZDtZERCxXQyRsWO8Ar5DjBdiSRchbhVGZQEBzXswMS0W5ZoRenjgPK+4tPW3JQGRTfbg==}
'@push.rocks/tapbundle@5.5.4': '@push.rocks/tapbundle@5.5.6':
resolution: {integrity: sha512-FDL9I95vRENAZmqyQ9/45I1aDaDqFm62rNZOaroqbYX86R7pK75YtwqA0AqQ+QYALX055xw02xlRND5tZmPByQ==} resolution: {integrity: sha512-V6u+nZwt4fNccxbm3ztZgHr/QAj/uKhaaOUFgtaae0jzYdds4jNEI+mXLpfXuNMgm7Nx93Lk5XUxWKTI8drjNw==}
'@push.rocks/taskbuffer@3.1.7': '@push.rocks/taskbuffer@3.1.7':
resolution: {integrity: sha512-QktGVJPucqQmW/QNGnscf4FAigT1H7JWKFGFdRuDEaOHKFh9qN+PXG3QY7DtZ4jfXdGLxPN4yAufDuPSAJYFnw==} resolution: {integrity: sha512-QktGVJPucqQmW/QNGnscf4FAigT1H7JWKFGFdRuDEaOHKFh9qN+PXG3QY7DtZ4jfXdGLxPN4yAufDuPSAJYFnw==}
@ -1422,8 +1410,8 @@ packages:
'@types/node-forge@1.3.11': '@types/node-forge@1.3.11':
resolution: {integrity: sha512-FQx220y22OKNTqaByeBGqHWYz4cl94tpcxeFdvBo3wjG6XPBuZ0BNgNZRV5J5TFmmcsJ4IzsLkmGRiQbnYsBEQ==} resolution: {integrity: sha512-FQx220y22OKNTqaByeBGqHWYz4cl94tpcxeFdvBo3wjG6XPBuZ0BNgNZRV5J5TFmmcsJ4IzsLkmGRiQbnYsBEQ==}
'@types/node@18.19.71': '@types/node@22.10.7':
resolution: {integrity: sha512-evXpcgtZm8FY4jqBSN8+DmOTcVkkvTmAayeo4Wf3m1xAruyVGzGuDh/Fb/WWX2yLItUiho42ozyJjB0dw//Tkw==} resolution: {integrity: sha512-V09KvXxFiutGp6B7XkpaDXlNadZxrzajcY50EuoLIpQ6WWYCSvf19lVIazzfIzQvhUN2HjX12spLojTnhuKlGg==}
'@types/parse5@6.0.3': '@types/parse5@6.0.3':
resolution: {integrity: sha512-SuT16Q1K51EAVPz1K29DJ/sXjhSQ0zjvsypYJ6tlwVsRV9jwW5Adq2ch8Dq8kDBCkYnELS7N7VNCSB5nC56t/g==} resolution: {integrity: sha512-SuT16Q1K51EAVPz1K29DJ/sXjhSQ0zjvsypYJ6tlwVsRV9jwW5Adq2ch8Dq8kDBCkYnELS7N7VNCSB5nC56t/g==}
@ -1455,9 +1443,6 @@ packages:
'@types/serve-static@1.15.7': '@types/serve-static@1.15.7':
resolution: {integrity: sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==} resolution: {integrity: sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==}
'@types/shortid@0.0.29':
resolution: {integrity: sha1-gJPuBBam4r8qpjOBCRFLP7/6Dps=}
'@types/sinon-chai@3.2.12': '@types/sinon-chai@3.2.12':
resolution: {integrity: sha512-9y0Gflk3b0+NhQZ/oxGtaAJDvRywCa5sIyaVnounqLvmf93yBF4EgIRspePtkMs3Tr844nCclYMlcCNmLCvjuQ==} resolution: {integrity: sha512-9y0Gflk3b0+NhQZ/oxGtaAJDvRywCa5sIyaVnounqLvmf93yBF4EgIRspePtkMs3Tr844nCclYMlcCNmLCvjuQ==}
@ -3643,8 +3628,8 @@ packages:
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'} engines: {node: '>=14'}
simple-async-context@0.0.13: simple-async-context@0.0.16:
resolution: {integrity: sha512-dD45zmw9HBlSyWVQJ38VTP5RpuVED8zIiwHrouimeHxDIlNxt66j+iWHQIvbTrsd1SnWVRaLwbPvsVsy+rfjpw==} resolution: {integrity: sha512-FbE32PwJcZQU+rta11BGI5K+bSwPf2FPnkMmOJVWUOz5qRMgwEqRRc2e85fhkRkYe3Pb9P/r5ELWjgaBGBsnDQ==}
simple-swizzle@0.2.2: simple-swizzle@0.2.2:
resolution: {integrity: sha1-pNprY1/8zMoz9w0Xy5JZLeleVXo=} resolution: {integrity: sha1-pNprY1/8zMoz9w0Xy5JZLeleVXo=}
@ -3922,8 +3907,8 @@ packages:
unbzip2-stream@1.4.3: unbzip2-stream@1.4.3:
resolution: {integrity: sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==} resolution: {integrity: sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==}
undici-types@5.26.5: undici-types@6.20.0:
resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} resolution: {integrity: sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==}
unified@11.0.5: unified@11.0.5:
resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==} resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
@ -5040,7 +5025,7 @@ snapshots:
'@push.rocks/smartlog': 3.0.7 '@push.rocks/smartlog': 3.0.7
'@push.rocks/smartpromise': 4.1.0 '@push.rocks/smartpromise': 4.1.0
'@push.rocks/smartshell': 3.2.2 '@push.rocks/smartshell': 3.2.2
'@push.rocks/tapbundle': 5.5.4(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3) '@push.rocks/tapbundle': 5.5.6(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3)
'@types/ws': 8.5.13 '@types/ws': 8.5.13
figures: 6.1.0 figures: 6.1.0
ws: 8.18.0 ws: 8.18.0
@ -5086,7 +5071,7 @@ snapshots:
'@jest/schemas': 29.6.3 '@jest/schemas': 29.6.3
'@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-lib-coverage': 2.0.6
'@types/istanbul-reports': 3.0.4 '@types/istanbul-reports': 3.0.4
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/yargs': 17.0.33 '@types/yargs': 17.0.33
chalk: 4.1.2 chalk: 4.1.2
@ -5335,11 +5320,9 @@ snapshots:
'@push.rocks/smartrx': 3.0.7 '@push.rocks/smartrx': 3.0.7
yargs-parser: 21.1.1 yargs-parser: 21.1.1
'@push.rocks/smartcls@1.0.14': {}
'@push.rocks/smartcrypto@2.0.4': '@push.rocks/smartcrypto@2.0.4':
dependencies: dependencies:
'@push.rocks/smartpromise': 4.1.0 '@push.rocks/smartpromise': 4.2.0
'@types/node-forge': 1.3.11 '@types/node-forge': 1.3.11
node-forge: 1.3.1 node-forge: 1.3.1
@ -5349,7 +5332,7 @@ snapshots:
'@push.rocks/smartdelay': 3.0.5 '@push.rocks/smartdelay': 3.0.5
'@push.rocks/smartlog': 3.0.7 '@push.rocks/smartlog': 3.0.7
'@push.rocks/smartmongo': 2.0.10(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3) '@push.rocks/smartmongo': 2.0.10(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3)
'@push.rocks/smartpromise': 4.1.0 '@push.rocks/smartpromise': 4.2.0
'@push.rocks/smartrx': 3.0.7 '@push.rocks/smartrx': 3.0.7
'@push.rocks/smartstring': 4.0.15 '@push.rocks/smartstring': 4.0.15
'@push.rocks/smarttime': 4.1.1 '@push.rocks/smarttime': 4.1.1
@ -5386,7 +5369,7 @@ snapshots:
'@push.rocks/smartexpect@1.4.0': '@push.rocks/smartexpect@1.4.0':
dependencies: dependencies:
'@push.rocks/smartdelay': 3.0.5 '@push.rocks/smartdelay': 3.0.5
'@push.rocks/smartpromise': 4.1.0 '@push.rocks/smartpromise': 4.2.0
fast-deep-equal: 3.1.3 fast-deep-equal: 3.1.3
'@push.rocks/smartfeed@1.0.11': '@push.rocks/smartfeed@1.0.11':
@ -5511,7 +5494,7 @@ snapshots:
'@push.rocks/mongodump': 1.0.8 '@push.rocks/mongodump': 1.0.8
'@push.rocks/smartdata': 5.2.10(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3) '@push.rocks/smartdata': 5.2.10(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3)
'@push.rocks/smartpath': 5.0.18 '@push.rocks/smartpath': 5.0.18
'@push.rocks/smartpromise': 4.1.0 '@push.rocks/smartpromise': 4.2.0
mongodb-memory-server: 8.16.1 mongodb-memory-server: 8.16.1
transitivePeerDependencies: transitivePeerDependencies:
- '@aws-sdk/credential-providers' - '@aws-sdk/credential-providers'
@ -5593,6 +5576,8 @@ snapshots:
'@push.rocks/smartpromise@4.1.0': {} '@push.rocks/smartpromise@4.1.0': {}
'@push.rocks/smartpromise@4.2.0': {}
'@push.rocks/smartpuppeteer@2.0.2': '@push.rocks/smartpuppeteer@2.0.2':
dependencies: dependencies:
'@pushrocks/smartdelay': 2.0.13 '@pushrocks/smartdelay': 2.0.13
@ -5754,7 +5739,7 @@ snapshots:
'@types/js-yaml': 3.12.10 '@types/js-yaml': 3.12.10
js-yaml: 3.14.1 js-yaml: 3.14.1
'@push.rocks/tapbundle@5.5.4(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3)': '@push.rocks/tapbundle@5.5.6(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3)':
dependencies: dependencies:
'@open-wc/testing': 4.0.0 '@open-wc/testing': 4.0.0
'@push.rocks/consolecolor': 2.0.2 '@push.rocks/consolecolor': 2.0.2
@ -5767,7 +5752,7 @@ snapshots:
'@push.rocks/smartjson': 5.0.20 '@push.rocks/smartjson': 5.0.20
'@push.rocks/smartmongo': 2.0.10(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3) '@push.rocks/smartmongo': 2.0.10(@aws-sdk/credential-providers@3.731.1)(socks@2.8.3)
'@push.rocks/smartpath': 5.0.18 '@push.rocks/smartpath': 5.0.18
'@push.rocks/smartpromise': 4.1.0 '@push.rocks/smartpromise': 4.2.0
'@push.rocks/smartrequest': 2.0.23 '@push.rocks/smartrequest': 2.0.23
'@push.rocks/smarts3': 2.2.5 '@push.rocks/smarts3': 2.2.5
'@push.rocks/smartshell': 3.2.2 '@push.rocks/smartshell': 3.2.2
@ -6378,14 +6363,14 @@ snapshots:
'@types/accepts@1.3.7': '@types/accepts@1.3.7':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/babel__code-frame@7.0.6': {} '@types/babel__code-frame@7.0.6': {}
'@types/body-parser@1.19.5': '@types/body-parser@1.19.5':
dependencies: dependencies:
'@types/connect': 3.4.38 '@types/connect': 3.4.38
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/buffer-json@2.0.3': {} '@types/buffer-json@2.0.3': {}
@ -6401,17 +6386,17 @@ snapshots:
'@types/clean-css@4.2.11': '@types/clean-css@4.2.11':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
source-map: 0.6.1 source-map: 0.6.1
'@types/co-body@6.1.3': '@types/co-body@6.1.3':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/qs': 6.9.18 '@types/qs': 6.9.18
'@types/connect@3.4.38': '@types/connect@3.4.38':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/content-disposition@0.5.8': {} '@types/content-disposition@0.5.8': {}
@ -6424,11 +6409,11 @@ snapshots:
'@types/connect': 3.4.38 '@types/connect': 3.4.38
'@types/express': 5.0.0 '@types/express': 5.0.0
'@types/keygrip': 1.0.6 '@types/keygrip': 1.0.6
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/cors@2.8.17': '@types/cors@2.8.17':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/debounce@1.2.4': {} '@types/debounce@1.2.4': {}
@ -6442,14 +6427,14 @@ snapshots:
'@types/express-serve-static-core@4.19.6': '@types/express-serve-static-core@4.19.6':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/qs': 6.9.18 '@types/qs': 6.9.18
'@types/range-parser': 1.2.7 '@types/range-parser': 1.2.7
'@types/send': 0.17.4 '@types/send': 0.17.4
'@types/express-serve-static-core@5.0.5': '@types/express-serve-static-core@5.0.5':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/qs': 6.9.18 '@types/qs': 6.9.18
'@types/range-parser': 1.2.7 '@types/range-parser': 1.2.7
'@types/send': 0.17.4 '@types/send': 0.17.4
@ -6474,30 +6459,30 @@ snapshots:
'@types/from2@2.3.5': '@types/from2@2.3.5':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/fs-extra@11.0.4': '@types/fs-extra@11.0.4':
dependencies: dependencies:
'@types/jsonfile': 6.1.4 '@types/jsonfile': 6.1.4
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/fs-extra@9.0.13': '@types/fs-extra@9.0.13':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/glob@7.2.0': '@types/glob@7.2.0':
dependencies: dependencies:
'@types/minimatch': 5.1.2 '@types/minimatch': 5.1.2
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/glob@8.1.0': '@types/glob@8.1.0':
dependencies: dependencies:
'@types/minimatch': 5.1.2 '@types/minimatch': 5.1.2
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/gunzip-maybe@1.4.2': '@types/gunzip-maybe@1.4.2':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/hast@3.0.4': '@types/hast@3.0.4':
dependencies: dependencies:
@ -6531,7 +6516,7 @@ snapshots:
'@types/jsonfile@6.1.4': '@types/jsonfile@6.1.4':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/keygrip@1.0.6': {} '@types/keygrip@1.0.6': {}
@ -6548,7 +6533,7 @@ snapshots:
'@types/http-errors': 2.0.4 '@types/http-errors': 2.0.4
'@types/keygrip': 1.0.6 '@types/keygrip': 1.0.6
'@types/koa-compose': 3.2.8 '@types/koa-compose': 3.2.8
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/mdast@4.0.4': '@types/mdast@4.0.4':
dependencies: dependencies:
@ -6566,11 +6551,11 @@ snapshots:
'@types/node-forge@1.3.11': '@types/node-forge@1.3.11':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/node@18.19.71': '@types/node@22.10.7':
dependencies: dependencies:
undici-types: 5.26.5 undici-types: 6.20.0
'@types/parse5@6.0.3': {} '@types/parse5@6.0.3': {}
@ -6586,23 +6571,21 @@ snapshots:
'@types/s3rver@3.7.4': '@types/s3rver@3.7.4':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/semver@7.5.8': {} '@types/semver@7.5.8': {}
'@types/send@0.17.4': '@types/send@0.17.4':
dependencies: dependencies:
'@types/mime': 1.3.5 '@types/mime': 1.3.5
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/serve-static@1.15.7': '@types/serve-static@1.15.7':
dependencies: dependencies:
'@types/http-errors': 2.0.4 '@types/http-errors': 2.0.4
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/send': 0.17.4 '@types/send': 0.17.4
'@types/shortid@0.0.29': {}
'@types/sinon-chai@3.2.12': '@types/sinon-chai@3.2.12':
dependencies: dependencies:
'@types/chai': 5.0.1 '@types/chai': 5.0.1
@ -6620,11 +6603,11 @@ snapshots:
'@types/tar-stream@2.2.3': '@types/tar-stream@2.2.3':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/through2@2.0.41': '@types/through2@2.0.41':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/triple-beam@1.3.5': {} '@types/triple-beam@1.3.5': {}
@ -6648,7 +6631,7 @@ snapshots:
'@types/whatwg-url@8.2.2': '@types/whatwg-url@8.2.2':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/webidl-conversions': 7.0.3 '@types/webidl-conversions': 7.0.3
'@types/which@2.0.2': {} '@types/which@2.0.2': {}
@ -6657,11 +6640,11 @@ snapshots:
'@types/ws@7.4.7': '@types/ws@7.4.7':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/ws@8.5.13': '@types/ws@8.5.13':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
'@types/yargs-parser@21.0.3': {} '@types/yargs-parser@21.0.3': {}
@ -6671,7 +6654,7 @@ snapshots:
'@types/yauzl@2.10.3': '@types/yauzl@2.10.3':
dependencies: dependencies:
'@types/node': 18.19.71 '@types/node': 22.10.7
optional: true optional: true
'@ungap/structured-clone@1.2.1': {} '@ungap/structured-clone@1.2.1': {}
@ -7256,7 +7239,7 @@ snapshots:
dependencies: dependencies:
'@types/cookie': 0.4.1 '@types/cookie': 0.4.1
'@types/cors': 2.8.17 '@types/cors': 2.8.17
'@types/node': 18.19.71 '@types/node': 22.10.7
accepts: 1.3.8 accepts: 1.3.8
base64id: 2.0.0 base64id: 2.0.0
cookie: 0.4.2 cookie: 0.4.2
@ -7977,7 +7960,7 @@ snapshots:
jest-util@29.7.0: jest-util@29.7.0:
dependencies: dependencies:
'@jest/types': 29.6.3 '@jest/types': 29.6.3
'@types/node': 18.19.71 '@types/node': 22.10.7
chalk: 4.1.2 chalk: 4.1.2
ci-info: 3.9.0 ci-info: 3.9.0
graceful-fs: 4.2.11 graceful-fs: 4.2.11
@ -9190,7 +9173,7 @@ snapshots:
signal-exit@4.1.0: {} signal-exit@4.1.0: {}
simple-async-context@0.0.13: {} simple-async-context@0.0.16: {}
simple-swizzle@0.2.2: simple-swizzle@0.2.2:
dependencies: dependencies:
@ -9493,7 +9476,7 @@ snapshots:
buffer: 5.7.1 buffer: 5.7.1
through: 2.3.8 through: 2.3.8
undici-types@5.26.5: {} undici-types@6.20.0: {}
unified@11.0.5: unified@11.0.5:
dependencies: dependencies:

387
readme.md
View File

@ -2,251 +2,220 @@
A module to enrich logs with context, featuring async log contexts and scope management. A module to enrich logs with context, featuring async log contexts and scope management.
Special thanks to Ilias Bhallil for his awesome simple-async-context library.
## Install ## Install
To install the `@push.rocks/smartcontext` module, you can use npm. Make sure you have Node.js and npm installed on your system. Navigate to your project directory and run the following command: Make sure you have Node.js and npm installed, then run:
```bash ```bash
npm install @push.rocks/smartcontext npm install @push.rocks/smartcontext
``` ```
This command will download and install the module and its dependencies into your project's `node_modules` directory. This will install the library and its dependencies into your local `node_modules` folder.
## Usage ## Usage
The `@push.rocks/smartcontext` module provides an efficient way to enrich your logging with contextual information. It features asynchronous log contexts and scope management, especially useful in complex asynchronous workflows in Node.js applications. This documentation will guide you through its core components: `AsyncContext` and `AsyncStore`. The `@push.rocks/smartcontext` module provides an efficient way to enrich your code (often for logging) with contextual information. It uses asynchronous context management to support hierarchical scopes—particularly helpful in complex or nested asynchronous operations in Node.js.
### Setting Up and Basic Usage ### Basic Setup
First, import the necessary classes from the module in your TypeScript application:
```typescript
import { AsyncContext, AsyncStore } from '@push.rocks/smartcontext';
```
#### Creating a Context
You can create an `AsyncContext` for managing scope-based data sharing. Each context maintains a top-level `AsyncStore` instance. Lets create a simple context and store some data:
```typescript
const mainContext = new AsyncContext();
// Add some data to the store
mainContext.store.add('username', 'john_doe');
mainContext.store.add('role', 'admin');
console.log(mainContext.store.get('username')); // Outputs: 'john_doe'
console.log(mainContext.store.get('role')); // Outputs: 'admin'
```
This `mainContext` acts as a container for contextual data throughout the lifecycle of your application or a specific code block.
### Scoping with `runScoped`
The `runScoped` method allows you to run a function within a specific child `AsyncStore` scope. This is vital for isolating child data during asynchronous operations, while still having access to any relevant parent data:
```typescript
await mainContext.runScoped(async (childStore: AsyncStore) => {
childStore.add('transactionId', 'txn_123456');
console.log(childStore.get('transactionId')); // Outputs: 'txn_123456'
// Child store can also access data from the parent context:
console.log(childStore.get('username')); // Outputs: 'john_doe'
console.log(childStore.get('role')); // Outputs: 'admin'
});
```
Changes made within this child store do not leak back to the parent unless explicitly intended.
#### Isolating Data in Scoped Functions
Data added within a child scope is only stored locally, unless you decide to propagate it to the parent. Additionally, you can delete data in the child without affecting the parent:
```typescript
await mainContext.runScoped(async (childStore: AsyncStore) => {
childStore.add('temporaryData', 'tempValue');
console.log(childStore.get('temporaryData')); // Outputs: 'tempValue'
// Delete data in child scope
childStore.delete('temporaryData');
console.log(childStore.get('temporaryData')); // Outputs: undefined
});
```
In this example, `temporaryData` is never propagated to the parent. Once deleted within the scope, its gone for that child context.
### Advanced Usage
Below are some patterns to demonstrate more advanced scenarios.
#### Handling Complex Asynchronous Flows
Consider a scenario where you process a list of user requests asynchronously, assigning each request its own temporary data:
```typescript
import { AsyncContext } from '@push.rocks/smartcontext';
import { v4 as uuidv4 } from 'uuid';
async function processUserRequests(users: string[], asyncContext: AsyncContext) {
for (const user of users) {
await asyncContext.runScoped(async (childStore: AsyncStore) => {
// Assign a unique request ID
const requestId = uuidv4();
childStore.add('currentUser', user);
childStore.add('requestId', requestId);
console.log(`Processing user: ${childStore.get('currentUser')} with Request ID: ${childStore.get('requestId')}`);
// Simulate an async operation
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log(`Completed processing for user: ${childStore.get('currentUser')}`);
});
}
}
const mainContext = new AsyncContext();
processUserRequests(['alice', 'bob'], mainContext);
```
Each users scope remains neatly contained while still sharing any parent data (if present). This is highly beneficial in servers that handle multiple requests or tasks in parallel.
#### Sharing Data Across Scopes
Occasionally, you may want the child scope to add or modify data that persists in the parent. By default, `childStore` only extends the parent for lookup; changes remain local to the child. If you need truly shared data, you can write data directly to the parent store as well:
```typescript
const newContext = new AsyncContext();
await newContext.runScoped(async (childStore: AsyncStore) => {
// This affects only the child store
childStore.add('childMessage', 'I am a child.');
// Directly manipulate the parent store if needed:
newContext.store.add('parentMessage', 'I am the parent (updated).');
});
// Checking the parent store:
console.log(newContext.store.get('parentMessage')); // Outputs: 'I am the parent (updated)'
console.log(newContext.store.get('childMessage')); // Outputs: undefined (child-only)
```
This approach helps you maintain clarity on what data belongs to the parent vs. a transient child operation.
#### Parallel Scopes
When dealing with parallel asynchronous operations, each scope can be maintained independently. For instance, multiple login operations can be handled by the same parent context yet remain separate at runtime:
```typescript ```typescript
import { AsyncContext } from '@push.rocks/smartcontext'; import { AsyncContext } from '@push.rocks/smartcontext';
const userContext = new AsyncContext(); const asyncContext = new AsyncContext();
userContext.store.add('appVersion', '1.2.0');
async function handleUserLogin(userId: string, context: AsyncContext) { // The parent store is always accessible through `asyncContext.store`
await context.runScoped(async (childStore: AsyncStore) => { asyncContext.store.add('username', 'john_doe');
childStore.add('sessionUser', userId); console.log(asyncContext.store.get('username')); // 'john_doe'
```
console.log(`User: ${childStore.get('sessionUser')}, App: ${childStore.get('appVersion')}`);
// More processing for the user... ### `runScoped`
When you call `asyncContext.runScoped(async () => { ... })`, the library automatically creates a **child** `AsyncStore`. Inside that scoped function, `asyncContext.store` refers to the child store. Any data you add or delete there is isolated from the parent store. However, you can still read parent data if it hasnt been overridden.
```typescript
await asyncContext.runScoped(async () => {
// Inside this callback, `asyncContext.store` is a *child* store
asyncContext.store.add('transactionId', 'txn_abc123');
console.log(asyncContext.store.get('transactionId')); // 'txn_abc123'
// We can also see parent data like 'username'
console.log(asyncContext.store.get('username')); // 'john_doe'
});
// Outside `runScoped`, asyncContext.store reverts to the parent store
console.log(asyncContext.store.get('transactionId')); // undefined
```
### Isolating Data
Because each call to `runScoped` returns control to the parent store afterward, any keys added in a child scope disappear once the scope completes (unless you explicitly move them to the parent). This mechanism keeps data from leaking between scopes.
```typescript
// Parent store
asyncContext.store.add('someParentKey', 'parentValue');
// Child scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('scopedKey', 'childValue');
console.log(asyncContext.store.get('scopedKey')); // 'childValue'
});
// Outside, the child key is gone
console.log(asyncContext.store.get('scopedKey')); // undefined
```
### Deleting Data
If the child deletes a key that exists in the parent, it will only remove it from the childs view of the store. Once the scope completes, the parent store is unaffected.
```typescript
asyncContext.store.add('deletableKey', 'originalValue');
await asyncContext.runScoped(async () => {
console.log(asyncContext.store.get('deletableKey')); // 'originalValue'
asyncContext.store.delete('deletableKey');
console.log(asyncContext.store.get('deletableKey')); // undefined in child
});
console.log(asyncContext.store.get('deletableKey')); // 'originalValue' remains in parent
```
### Parallel or Sequential Scopes
You can call `runScoped` multiple times, whether sequentially or in parallel (with `Promise.all`). Each invocation creates its own isolated child store, preventing data collisions across asynchronous tasks.
```typescript
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey1', 'childValue1');
console.log(asyncContext.store.get('childKey1')); // 'childValue1'
});
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
console.log(asyncContext.store.get('childKey2')); // 'childValue2'
});
// Both keys were added in separate scopes, so they won't exist in the parent
console.log(asyncContext.store.get('childKey1')); // undefined
console.log(asyncContext.store.get('childKey2')); // undefined
```
### Testing Example
The following is a complete test script (using [tapbundle](https://www.npmjs.com/package/@push.rocks/tapbundle)) demonstrating how child stores inherit data from the parent but remain isolated. After each scoped block, new child keys vanish, and any parent keys deleted inside the child remain intact in the parent.
```typescript
import { tap, expect } from '@push.rocks/tapbundle';
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
const asyncContext = new AsyncContext();
tap.test('should run a scoped function and add data to a child store', async () => {
// Add some default data to the parent store
asyncContext.store.add('parentKey', 'parentValue');
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
// Now run a child scope, add some data, and check that parent data is still accessible
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey', 'childValue');
// Child sees its own data
expect(asyncContext.store.get('childKey')).toEqual('childValue');
// Child also sees parent data
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
}); });
} });
await Promise.all([ tap.test('should not contaminate the parent store with child-only data', async () => {
handleUserLogin('user123', userContext), // Create a new child scope
handleUserLogin('user456', userContext), await asyncContext.runScoped(async () => {
]); asyncContext.store.add('temporaryKey', 'temporaryValue');
``` expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
In this example, the `userContext` store data (like `appVersion`) is accessible within each child scope, but each user session remains isolated. The parents data is shared and read-only for the children, unless children write specifically to the parent context.
#### Error Handling and Context-Enriched Logging
By leveraging contextual data, your logs can capture additional diagnostic details automatically:
```typescript
async function performTaskWithLogging(taskId: string, context: AsyncContext) {
try {
await context.runScoped(async (childStore: AsyncStore) => {
childStore.add('taskId', taskId);
// Simulate some failing operation
throw new Error('Task failed due to unexpected error');
});
} catch (error) {
console.error(`[Error] Task ID: ${context.store.get('taskId')}, Error: ${error.message}`);
}
}
const loggingContext = new AsyncContext();
performTaskWithLogging('task_789', loggingContext);
```
In the example above, we track `taskId` in the context store, ensuring that any error logs or additional logging statements automatically include that identifying information.
### Managing Contexts Across Modules
In large applications, you might want different modules to read or update shared context data without tight coupling between modules. One pattern is to define an `AsyncContext` in a root or shared location and pass it as needed:
```typescript
// main.ts
import { AsyncContext } from '@push.rocks/smartcontext';
import { userModule } from './userModule';
import { billingModule } from './billingModule';
const globalContext = new AsyncContext();
globalContext.store.add('appName', 'SmartContextApp');
userModule(globalContext);
billingModule(globalContext);
```
Then, each module file can utilize that shared context:
```typescript
// userModule.ts
export async function userModule(context: AsyncContext) {
await context.runScoped(async (childStore) => {
childStore.add('moduleName', 'UserModule');
console.log(`[UserModule] appName: ${childStore.get('appName')}`);
}); });
} // After scope finishes, 'temporaryKey' won't exist in the parent
``` expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
```typescript tap.test('should allow adding data in multiple scopes independently', async () => {
// billingModule.ts // Add data in the first scope
export async function billingModule(context: AsyncContext) { await asyncContext.runScoped(async () => {
await context.runScoped(async (childStore) => { asyncContext.store.add('childKey1', 'childValue1');
childStore.add('moduleName', 'BillingModule'); expect(asyncContext.store.get('childKey1')).toEqual('childValue1');
console.log(`[BillingModule] appName: ${childStore.get('appName')}`);
}); });
}
// Add data in the second scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
expect(asyncContext.store.get('childKey2')).toEqual('childValue2');
});
// Neither childKey1 nor childKey2 should exist in the parent store
expect(asyncContext.store.get('childKey1')).toBeUndefined();
expect(asyncContext.store.get('childKey2')).toBeUndefined();
});
tap.test('should allow deleting data in a child store without removing it from the parent store', async () => {
// Ensure parent has some data
asyncContext.store.add('deletableKey', 'iShouldStayInParent');
await asyncContext.runScoped(async () => {
// Child sees the parent's data
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
// Delete it in the child
asyncContext.store.delete('deletableKey');
// Child no longer sees it
expect(asyncContext.store.get('deletableKey')).toBeUndefined();
});
// Parent still has it
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
});
tap.test('should allow multiple child scopes to share the same parent store data', async () => {
// Add a key to the parent store
asyncContext.store.add('sharedKey', 'sharedValue');
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
// First child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
// Second child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
});
export default tap.start();
``` ```
This approach keeps the code cleaner and ensures each module has access to shared data while retaining isolation where needed.
`@push.rocks/smartcontext` equips developers with a sophisticated asynchronous context management system, helping maintain clarity and consistency in logging and context sharing. Heres a recap of the benefits: With this updated `runScoped` design, theres no need to explicitly instantiate or manage child stores. The context automatically switches from the parent store to the child store while within the callback, then reverts back to the parent store afterwards. This structure makes it easy to:
- **Scoped Data**: Run logical operations within isolated child scopes, reducing contamination of global or parent-level data. - Keep each async operations state isolated
- **Asynchronous Safety**: Each asynchronous operation can track its own context, preventing race conditions on shared state. - Preserve read-access to parent context data
- **Enhanced Logging**: Include relevant contextual data in your logs automatically for easier debugging and tracing. - Avoid overwriting or polluting other operations data
- **Module-Friendly**: Share contexts without introducing deep module interdependencies.
These features simplify building robust Node.js applications, where concurrency and context tracking can otherwise become unwieldy. Enjoy exploring the breadth of this modules functionality, and tailor it to meet your projects unique challenges. This pattern works particularly well for logging or any scenario where you need to pass metadata through deeply nested async calls without manually juggling that data everywhere in your code.
## License and Legal Information ## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. This repository is under the [MIT License](./license). Please note that the MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as necessary for reasonable use in describing the origin of the work.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks ### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Usage must be approved in writing by Task Venture Capital GmbH.
### Company Information ### Company Information
Task Venture Capital GmbH Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. For any legal inquiries, please contact us at hello@task.vc. By using this repository, you acknowledge that you have read this section and agree to comply with its terms.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -2,87 +2,106 @@ import { tap, expect } from '@push.rocks/tapbundle';
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js'; import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
import { AsyncStore } from '../ts/logcontext.classes.asyncstore.js'; import { AsyncStore } from '../ts/logcontext.classes.asyncstore.js';
process.env.DEBUG = 'true';
/** /**
* This test file demonstrates how to use the AsyncContext and ensures * This test file demonstrates how to use the AsyncContext and ensures
* that runScoped() properly creates child AsyncStore contexts and merges parent data. * that runScoped() properly creates child AsyncStore contexts and merges parent data.
*/ */
const parentContext = new AsyncContext(); const asyncContext = new AsyncContext();
tap.test('should run a scoped function and add data to a child store', async () => { tap.test('should run a scoped function and add data to a child store', async () => {
// add some default data to the parent store // add some default data to the parent store
parentContext.store.add('parentKey', 'parentValue'); asyncContext.store.add('parentKey', 'parentValue');
expect(parentContext.store.get('parentKey')).toEqual('parentValue'); expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
// now run a child scope, add some data, and check that parent's data is still accessible // now run a child scope, add some data, and check that parent's data is still accessible
await parentContext.runScoped(async (childStore: AsyncStore) => { await asyncContext.runScoped(async () => {
childStore.add('childKey', 'childValue'); asyncContext.store.add('childKey', 'childValue');
// child should see its own data // child should see its own data
expect(childStore.get('childKey')).toEqual('childValue'); expect(asyncContext.store.get('childKey')).toEqual('childValue');
// child should also see parent data // child should also see parent data
expect(childStore.get('parentKey')).toEqual('parentValue'); expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
}); });
}); });
tap.test('should not contaminate the parent store with child-only data', async () => { tap.test('should not contaminate the parent store with child-only data', async () => {
// create a new child scope // create a new child scope
await parentContext.runScoped(async (childStore: AsyncStore) => { await asyncContext.runScoped(async () => {
childStore.add('temporaryKey', 'temporaryValue'); asyncContext.store.add('temporaryKey', 'temporaryValue');
expect(childStore.get('temporaryKey')).toEqual('temporaryValue'); expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
}); });
// after the child scope finishes, 'temporaryKey' should not exist in the parent // after the child scope finishes, 'temporaryKey' should not exist in the parent
expect(parentContext.store.get('temporaryKey')).toBeUndefined(); expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
}); });
tap.test('should allow adding data in multiple scopes independently', async () => { tap.test('should allow adding data in multiple scopes independently', async (toolsArg) => {
const done = toolsArg.cumulativeDefer();
// add data in first scope // add data in first scope
await parentContext.runScoped(async (childStore: AsyncStore) => { asyncContext.runScoped(async () => {
childStore.add('childKey1', 'childValue1'); const subDone = done.subDefer();
expect(childStore.get('childKey1')).toEqual('childValue1'); asyncContext.store.add('childKey1', 'childValue1-v1');
await toolsArg.delayFor(2000);
expect(asyncContext.store.get('childKey1')).toEqual('childValue1-v1');
subDone.resolve();
});
asyncContext.runScoped(async () => {
const subDone = done.subDefer();
asyncContext.store.add('childKey1', 'childValue1-v2');
await toolsArg.delayFor(1000);
expect(asyncContext.store.get('childKey1')).toEqual('childValue1-v2');
subDone.resolve();
}); });
// add data in second scope // add data in second scope
await parentContext.runScoped(async (childStore: AsyncStore) => { asyncContext.runScoped(async () => {
childStore.add('childKey2', 'childValue2'); asyncContext.store.add('childKey2', 'childValue2');
expect(childStore.get('childKey2')).toEqual('childValue2'); expect(asyncContext.store.get('childKey2')).toEqual('childValue2');
}); });
// neither childKey1 nor childKey2 should exist in the parent store // neither childKey1 nor childKey2 should exist in the parent store
expect(parentContext.store.get('childKey1')).toBeUndefined(); expect(asyncContext.store.get('childKey1')).toBeUndefined();
expect(parentContext.store.get('childKey2')).toBeUndefined(); expect(asyncContext.store.get('childKey2')).toBeUndefined();
await done.promise;
}); });
tap.test('should allow deleting data in a child store without removing it from the parent store', async () => { tap.test(
// ensure parent has some data 'should allow deleting data in a child store without removing it from the parent store',
parentContext.store.add('deletableKey', 'iShouldStayInParent'); async (toolsArg) => {
// ensure parent has some data
asyncContext.store.add('deletableKey', 'iShouldStayInParent');
await parentContext.runScoped(async (childStore: AsyncStore) => { await asyncContext.runScoped(async () => {
// child sees the parent's data // child sees the parent's data
expect(childStore.get('deletableKey')).toEqual('iShouldStayInParent'); expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
// attempt to delete it in the child // attempt to delete it in the child
childStore.delete('deletableKey'); asyncContext.store.delete('deletableKey');
// child no longer sees it // child no longer sees it
expect(childStore.get('deletableKey')).toBeUndefined(); expect(asyncContext.store.get('deletableKey')).toBeUndefined();
// but parent still has it // but parent still has it
expect(parentContext.store.get('deletableKey')).toEqual('iShouldStayInParent'); });
}); expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
}); }
);
tap.test('should allow multiple child scopes to share the same parent store data', async () => { tap.test('should allow multiple child scopes to share the same parent store data', async () => {
// add a key to the parent store // add a key to the parent store
parentContext.store.add('sharedKey', 'sharedValue'); asyncContext.store.add('sharedKey', 'sharedValue');
expect(parentContext.store.get('sharedKey')).toEqual('sharedValue'); expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
// first child scope // first child scope
await parentContext.runScoped(async (firstChild: AsyncStore) => { await asyncContext.runScoped(async () => {
expect(firstChild.get('sharedKey')).toEqual('sharedValue'); expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
}); });
// second child scope // second child scope
await parentContext.runScoped(async (secondChild: AsyncStore) => { await asyncContext.runScoped(async () => {
expect(secondChild.get('sharedKey')).toEqual('sharedValue'); expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
}); });
}); });
tap.start(); export default tap.start();

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartcontext', name: '@push.rocks/smartcontext',
version: '2.1.0', version: '2.1.6',
description: 'A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.' description: 'A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.'
} }

View File

@ -2,12 +2,17 @@ import * as plugins from './logcontext.plugins.js';
import { AsyncStore } from './logcontext.classes.asyncstore.js'; import { AsyncStore } from './logcontext.classes.asyncstore.js';
export class AsyncContext { export class AsyncContext {
private context = new plugins.simpleAsyncContext.AsyncContext.Variable<AsyncStore>(); private _context = new plugins.simpleAsyncContext.AsyncContext.Variable<AsyncStore>();
public store = new AsyncStore(); private _store = new AsyncStore();
public runScoped(functionArg: (storeArg: AsyncStore) => Promise<void>) { get store() {
this.context.run(this.store, async () => { return this._context.get() || this._store;
const childStore = new AsyncStore(this.store); }
functionArg(childStore) set store(value: AsyncStore) {
this._store = value;
}
public async runScoped(functionArg: () => Promise<void>) {
await this._context.run(new AsyncStore(this.store), async () => {
await functionArg()
}); });
} }
} }

View File

@ -1,50 +1,135 @@
import * as plugins from './logcontext.plugins.js'; import * as plugins from './logcontext.plugins.js';
export class AsyncStore { export class AsyncStore {
private static idCounter = 0;
private id: number;
private parentStore?: AsyncStore; private parentStore?: AsyncStore;
private deletedKeys: string[] = []; private deletedKeys: string[] = [];
private dataObject: {[key: string]: any} = {}; private dataObject: { [key: string]: any } = {};
constructor(parentStore?: AsyncStore) { constructor(parentStore?: AsyncStore) {
this.parentStore = parentStore; this.parentStore = parentStore;
this.id = AsyncStore.idCounter++;
} }
/**
* Logs debug info if process.env.DEBUG is set.
*/
private logDebug(functionName: string, before: Record<string, any>, after: Record<string, any>) {
if (process.env.DEBUG) {
console.log(`Store ID: ${this.id}`);
console.log(`Function: ${functionName}`);
console.log('--- Before ---');
console.log(before);
console.log('--- After ---');
console.log(after);
console.log('-----------------------');
}
}
/**
* Cleans up the deleted keys if they no longer exist in any parent store.
*/
private cleanUp() { private cleanUp() {
for (const key of this.deletedKeys) { for (const key of this.deletedKeys) {
if (this.parentStore && this.parentStore.get(key)) { if (this.parentStore && this.parentStore.get(key)) {
// ok still valid // Parent still has it, so keep in deletedKeys
} else { } else {
delete this.deletedKeys[key]; const index = this.deletedKeys.indexOf(key);
if (index !== -1) {
this.deletedKeys.splice(index, 1);
}
} }
} }
} }
/**
* Adds or updates a value under a specific key in this store.
*/
public add(keyArg: string, objectArg: any) { public add(keyArg: string, objectArg: any) {
// capture the before state
const before = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.cleanUp(); this.cleanUp();
// If this key was previously deleted, remove it from deletedKeys.
if (this.deletedKeys.includes(keyArg)) { if (this.deletedKeys.includes(keyArg)) {
this.deletedKeys = this.deletedKeys.filter((key) => key !== keyArg); this.deletedKeys = this.deletedKeys.filter((key) => key !== keyArg);
} }
this.dataObject[keyArg] = objectArg; this.dataObject[keyArg] = objectArg;
// capture the after state
const after = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.logDebug('add', before, after);
} }
/**
* Deletes a key from the current store.
* If a parent store has the key, we record it in `deletedKeys` so the child store "shadows" it.
*/
public delete(paramName: string) { public delete(paramName: string) {
// capture the before state
const before = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.cleanUp(); this.cleanUp();
if (this.parentStore.get(paramName)) { if (this.parentStore?.get(paramName)) {
// The parent store has this key; let's mark it as deleted in the child
this.deletedKeys.push(paramName); this.deletedKeys.push(paramName);
} }
delete this.dataObject[paramName]; delete this.dataObject[paramName];
// capture the after state
const after = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.logDebug('delete', before, after);
} }
/**
* Gets the value of a key, checking this store first, then the parent store if necessary.
* Will log the store state before/after for debugging.
*/
public get(paramName: string) { public get(paramName: string) {
// capture the before state
const before = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.cleanUp(); this.cleanUp();
// figure out if paramName is deleted or present
let result: any;
if (this.deletedKeys.includes(paramName)) { if (this.deletedKeys.includes(paramName)) {
return undefined; result = undefined;
} else {
result = this.dataObject[paramName] ?? this.parentStore?.get(paramName);
} }
return this.dataObject[paramName] || this.parentStore?.get(paramName);
// capture the after state; we can also show the `result` in the log
const after = {
...this.dataObject,
deletedKeys: [...this.deletedKeys],
retrievedKey: paramName,
result
};
this.logDebug('get', before, after);
return result;
} }
/**
* Returns all keys and values, merged with the parent store, but
* does NOT include keys that are "deleted" in the child.
* Child store should override parent if the same key exists in both.
*/
public getAll() { public getAll() {
this.cleanUp(); this.cleanUp();
return {...this.dataObject, ...(this.parentStore?.getAll() || {})}; // first, get parent's data as a shallow copy
const parentData = { ...(this.parentStore?.getAll() || {}) };
// remove keys from parent data that this child has deleted
for (const key of this.deletedKeys) {
delete parentData[key];
}
// child's data overrides parent data for any matching keys
return {
...parentData,
...this.dataObject
};
} }
} }

View File

@ -1,9 +1,3 @@
// pushrocks scope
import * as lik from '@push.rocks/lik';
import * as smartunique from '@push.rocks/smartunique';
export { lik, smartunique };
// third party scope // third party scope
import simpleAsyncContext from 'simple-async-context'; import simpleAsyncContext from 'simple-async-context';