This commit is contained in:
2026-02-15 20:09:47 +00:00
parent 7f09f1b6f4
commit 0c13bf6be4
9 changed files with 3423 additions and 3043 deletions

View File

@@ -1,5 +1,14 @@
# Changelog
## 2026-02-15 - 2.3.0 - feat(asynccontext)
replace simple-async-context with Node's AsyncLocalStorage and update implementation, tests, docs, and devDependencies
- Switched internal implementation to node:async_hooks AsyncLocalStorage (ts/plugins.ts and classes.asynccontext.ts) and adapted AsyncContext to use getStore()
- Removed dependency on simple-async-context and updated package.json (devDependencies bumped for @git.zone/* and @types/node; removed @push.rocks/tapbundle and simple-async-context)
- Updated tests: removed test/test.both.ts and added test/test.node+bun.ts using @git.zone/tstest/tapbundle
- Rewrote README to reflect new examples and usage (variable names/usage and API docs)
- Updated build script in package.json (removed --web) and adjusted npmextra.json with registry/release entries and namespaced keys
## 2025-01-25 - 2.2.1 - fix(core)
Remove unused logcontext classes and update exports

View File

@@ -1,5 +1,5 @@
{
"gitzone": {
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
@@ -19,13 +19,19 @@
"module",
"async log contexts"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"npmci": {
"npmAccessLevel": "public",
"npmGlobalTools": []
},
"tsdoc": {
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
},
"@ship.zone/szci": {
"npmGlobalTools": []
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@push.rocks/smartcontext",
"version": "2.2.1",
"version": "2.3.0",
"description": "A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.",
"exports": {
".": "./dist_ts/index.js"
@@ -10,20 +10,16 @@
"license": "MIT",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild --allowimplicitany --web)",
"build": "(tsbuild --allowimplicitany)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.1.27",
"@git.zone/tsbundle": "^2.0.7",
"@git.zone/tsrun": "^1.2.39",
"@git.zone/tstest": "^1.0.96",
"@git.zone/tsbuild": "^4.1.2",
"@git.zone/tsbundle": "^2.8.3",
"@git.zone/tsrun": "^2.0.1",
"@git.zone/tstest": "^3.1.8",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/tapbundle": "^5.5.6",
"@types/node": "^22.10.10"
},
"dependencies": {
"simple-async-context": "^0.0.23"
"@types/node": "^25.2.3"
},
"private": false,
"browserslist": [

6184
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

224
readme.md
View File

@@ -1,209 +1,121 @@
# @push.rocks/smartcontext
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.
A zero-dependency module for hierarchical async context management in Node.js, built on `AsyncLocalStorage`.
## Install
Make sure you have Node.js and npm installed, then run:
```bash
npm install @push.rocks/smartcontext
# or
pnpm install @push.rocks/smartcontext
```
This will install the library and its dependencies into your local `node_modules` folder.
## Usage
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.
`@push.rocks/smartcontext` provides scoped, hierarchical key-value stores that follow async execution flow. Child scopes inherit parent data, can add or delete keys without affecting the parent, and automatically clean up when the scope exits.
This is useful for log enrichment, request-scoped metadata, transaction tracking, and any scenario where contextual data needs to flow through deeply nested async calls.
### Basic Setup
```typescript
import { AsyncContext } from '@push.rocks/smartcontext';
const asyncContext = new AsyncContext();
const ctx = new AsyncContext();
// The parent store is always accessible through `asyncContext.store`
asyncContext.store.add('username', 'john_doe');
console.log(asyncContext.store.get('username')); // 'john_doe'
// Add data to the root store
ctx.store.add('userId', 'u_123');
console.log(ctx.store.get('userId')); // 'u_123'
```
### Scoped Execution with `runScoped`
### `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.
`runScoped` creates an isolated child store for the duration of the callback. Inside the callback, `ctx.store` transparently points to the child store. The child inherits all parent data but any additions or deletions are local to the child.
```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'
ctx.store.add('requestId', 'req_abc');
// We can also see parent data like 'username'
console.log(asyncContext.store.get('username')); // 'john_doe'
await ctx.runScoped(async () => {
// Child store sees parent data
console.log(ctx.store.get('requestId')); // 'req_abc'
// Add child-only data
ctx.store.add('spanId', 'span_001');
console.log(ctx.store.get('spanId')); // 'span_001'
});
// Outside `runScoped`, asyncContext.store reverts to the parent store
console.log(asyncContext.store.get('transactionId')); // undefined
// After scope exits, child data is gone
console.log(ctx.store.get('spanId')); // undefined
// Parent data is untouched
console.log(ctx.store.get('requestId')); // 'req_abc'
```
### Deleting Keys in a Child Scope
### 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.
Deleting a parent key inside a child scope only shadows it within that scope. The parent retains the original value.
```typescript
// Parent store
asyncContext.store.add('someParentKey', 'parentValue');
ctx.store.add('token', 'secret_value');
// Child scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('scopedKey', 'childValue');
console.log(asyncContext.store.get('scopedKey')); // 'childValue'
await ctx.runScoped(async () => {
ctx.store.delete('token');
console.log(ctx.store.get('token')); // undefined (shadowed)
});
// Outside, the child key is gone
console.log(asyncContext.store.get('scopedKey')); // undefined
console.log(ctx.store.get('token')); // 'secret_value' (parent unaffected)
```
### Parallel Scopes
### 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.
Multiple concurrent `runScoped` calls each get their own isolated child store, preventing data collisions across async tasks.
```typescript
asyncContext.store.add('deletableKey', 'originalValue');
await Promise.all([
ctx.runScoped(async () => {
ctx.store.add('worker', 'A');
// Only this scope sees worker=A
}),
ctx.runScoped(async () => {
ctx.store.add('worker', 'B');
// Only this scope sees worker=B
}),
]);
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
console.log(ctx.store.get('worker')); // undefined
```
### Retrieving All Data
### 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.
`store.getAll()` returns a merged view of the store hierarchy, with child values overriding parent values and deleted keys excluded.
```typescript
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey1', 'childValue1');
console.log(asyncContext.store.get('childKey1')); // 'childValue1'
});
ctx.store.add('env', 'production');
ctx.store.add('region', 'eu-west-1');
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
console.log(asyncContext.store.get('childKey2')); // 'childValue2'
await ctx.runScoped(async () => {
ctx.store.add('traceId', 'tr_xyz');
console.log(ctx.store.getAll());
// { env: 'production', region: 'eu-west-1', traceId: 'tr_xyz' }
});
// 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
```
### API Reference
### Testing Example
#### `AsyncContext`
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.
| Method / Property | Description |
|---|---|
| `store` | The current `AsyncStore` (root or scoped child) |
| `runScoped(fn)` | Execute `fn` with an isolated child store |
```typescript
import { tap, expect } from '@push.rocks/tapbundle';
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
#### `AsyncStore`
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');
});
});
tap.test('should not contaminate the parent store with child-only data', async () => {
// Create a new child scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('temporaryKey', 'temporaryValue');
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
});
// After scope finishes, 'temporaryKey' won't exist in the parent
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
tap.test('should allow adding data in multiple scopes independently', async () => {
// Add data in the first scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey1', 'childValue1');
expect(asyncContext.store.get('childKey1')).toEqual('childValue1');
});
// 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();
```
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:
- Keep each async operations state isolated
- Preserve read-access to parent context data
- Avoid overwriting or polluting other operations data
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.
| Method | Description |
|---|---|
| `add(key, value)` | Set a key-value pair |
| `get(key)` | Get a value (checks local store, then parent chain) |
| `delete(key)` | Remove a key (shadows parent key if inherited) |
| `getAll()` | Get all key-value pairs merged from the full parent chain |
## License and Legal Information
@@ -215,7 +127,7 @@ This project is owned and maintained by Task Venture Capital GmbH. The names and
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
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.
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.

View File

@@ -1,4 +1,4 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as asynccontext from '../ts/index.js';

View File

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

View File

@@ -2,10 +2,10 @@ import * as plugins from './plugins.js';
import { AsyncStore } from './classes.asyncstore.js';
export class AsyncContext {
private _context = new plugins.simpleAsyncContext.AsyncContext.Variable<AsyncStore>();
private _context = new plugins.AsyncLocalStorage<AsyncStore>();
private _store = new AsyncStore();
get store() {
return this._context.get() || this._store;
return this._context.getStore() || this._store;
}
set store(value: AsyncStore) {
this._store = value;

View File

@@ -1,4 +1,3 @@
// third party scope
import simpleAsyncContext from 'simple-async-context';
import { AsyncLocalStorage } from 'node:async_hooks';
export { simpleAsyncContext };
export { AsyncLocalStorage };