21 Commits

Author SHA1 Message Date
36d52a9e03 2.1.2 2025-01-19 00:27:07 +01:00
9c0b53f373 fix(core): Improve scope handling in async contexts. 2025-01-19 00:27:06 +01:00
58b189c1c7 2.1.1 2025-01-18 23:53:15 +01:00
b246894060 fix(build): Fix tsbuild script to include missing flag 2025-01-18 23:53:15 +01:00
3d0fc6adc5 2.1.0 2025-01-18 23:52:44 +01:00
d16e3b613c feat(ci): Add GitHub Actions workflows for CI/CD 2025-01-18 23:52:44 +01:00
af18c2f57a update description 2024-05-29 14:11:16 +02:00
9476ad8129 update tsconfig 2024-04-14 13:39:41 +02:00
d1284024d5 update npmextra.json: githost 2024-04-01 21:33:20 +02:00
0114de2690 update npmextra.json: githost 2024-04-01 19:57:28 +02:00
011f8427c1 update npmextra.json: githost 2024-03-30 21:46:24 +01:00
3866cb9580 switch to new org scheme 2023-07-11 00:01:09 +02:00
31140af566 switch to new org scheme 2023-07-10 02:41:36 +02:00
c4b9833145 2.0.0 2023-01-12 11:59:41 +01:00
3c6d217563 BREAKING CHANGE(switch to esm): update 2023-01-12 11:59:41 +01:00
8524299d39 1.0.29 2023-01-12 11:58:35 +01:00
227931b0d3 fix(core): update 2023-01-12 11:58:34 +01:00
e3be31bb93 1.0.28 2021-09-17 19:34:27 +02:00
3babab347f fix(core): update 2021-09-17 19:34:27 +02:00
765b388889 1.0.27 2021-09-17 19:21:35 +02:00
80b0bdd663 fix(core): update 2021-09-17 19:21:34 +02:00
24 changed files with 10351 additions and 11390 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

3
.gitignore vendored
View File

@ -3,7 +3,6 @@
# artifacts
coverage/
public/
pages/
# installs
node_modules/
@ -17,4 +16,4 @@ node_modules/
dist/
dist_*/
# custom
#------# custom

View File

@ -1,127 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- lossless
- docker
- notpriv
audit:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high
tags:
- lossless
- docker
- notpriv
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker
- priv
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

24
.vscode/launch.json vendored
View File

@ -2,28 +2,10 @@
"version": "0.2.0",
"configurations": [
{
"name": "current file",
"type": "node",
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"args": [
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
"type": "node-terminal"
}
]
}

View File

@ -15,7 +15,7 @@
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm"]
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}

68
changelog.md Normal file
View File

@ -0,0 +1,68 @@
# Changelog
## 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)
Add GitHub Actions workflows for CI/CD
- Introduce GitHub Actions workflows to handle CI/CD processes for different events and branch types.
- Remove GitLab CI configuration in favor of GitHub Actions.
- Ensure security audits and tests are run as part of the CI pipeline.
## 2024-05-29 to 2024-03-30 - 2.0.0 - Configuration Updates
Improvements and updates to configuration files.
- Updated project description
- Modified TypeScript configuration
- Updated npmextra.json for githost details
## 2023-07-11 to 2023-07-10 - 2.0.0 - Organizational Change
Transitioned to a new organizational scheme for improved project structure.
- Implemented new organizational scheme
## 2023-01-12 - 1.0.29 - Breaking Change
Important breaking changes introduced, switched project to ECMAScript Module (ESM) format.
- Switched to ECMAScript Module (ESM)
- Core functionality updated
## 2021-09-17 to 2020-07-20 - 1.0.28 to 1.0.23 - Core Fixes
Multiple core improvements and bug fixes across several versions.
- Core functionality updates across versions
## 2018-03-09 to 2018-03-05 - 1.0.21 to 1.0.20 - Documentation Updates
Enhancements and updates to project documentation.
- License information updated in README
- General README updates
## 2018-03-05 - 1.0.19 - Standards Update
Updated project to comply with the latest coding standards.
- Applied latest standard updates
## 2018-03-03 - 1.0.18 - Initial Working Version
Initial release with all dependencies configured.
- First working project version with dependencies
## 2017-10-16 - 1.0.2 - Documentation
Initial project documentation added.
- Added initial README file
## 2017-10-16 - 1.0.1 - Initial Release
The initial release of the project.
- Project setup and initial commit

View File

@ -2,16 +2,30 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "logcontext",
"shortDescription": "enrich logs with context",
"npmPackagename": "@pushrocks/logcontext",
"license": "MIT"
"description": "A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.",
"npmPackagename": "@push.rocks/logcontext",
"license": "MIT",
"keywords": [
"logging",
"context management",
"context enrichment",
"asynchronous",
"scope management",
"typescript",
"nodejs",
"module",
"async log contexts"
]
}
},
"npmci": {
"npmAccessLevel": "public",
"npmGlobalTools": []
},
"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"
}
}

10932
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,30 +1,33 @@
{
"name": "@pushrocks/logcontext",
"version": "1.0.26",
"description": "enrich logs with context",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"name": "@push.rocks/smartcontext",
"version": "2.1.2",
"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"
},
"type": "module",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild --web)"
"build": "(tsbuild --allowimplicitany --web)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.24",
"@gitzone/tsbundle": "^1.0.72",
"@gitzone/tstest": "^1.0.43",
"@pushrocks/smartdelay": "^2.0.10",
"@pushrocks/tapbundle": "^3.2.9",
"@types/node": "^14.0.23",
"tslint": "^6.1.2",
"tslint-config-prettier": "^1.18.0"
"@git.zone/tsbuild": "^2.1.27",
"@git.zone/tsbundle": "^2.0.7",
"@git.zone/tsrun": "^1.2.39",
"@git.zone/tstest": "^1.0.57",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/tapbundle": "^5.0.4",
"@types/node": "^18.11.18"
},
"dependencies": {
"@pushrocks/lik": "^4.0.17",
"@pushrocks/smartcls": "^1.0.9",
"@pushrocks/smartunique": "^3.0.3",
"@types/shortid": "0.0.29"
"@push.rocks/lik": "^6.0.0",
"@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,
"browserslist": [
@ -41,5 +44,24 @@
"cli.js",
"npmextra.json",
"readme.md"
]
],
"keywords": [
"logging",
"context management",
"context enrichment",
"asynchronous",
"scope management",
"typescript",
"nodejs",
"module",
"async log contexts"
],
"homepage": "https://code.foss.global/push.rocks/logcontext#readme",
"repository": {
"type": "git",
"url": "git+https://code.foss.global/push.rocks/logcontext.git"
},
"bugs": {
"url": "https://code.foss.global/push.rocks/logcontext/issues"
}
}

9682
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

213
readme.md
View File

@ -1,84 +1,181 @@
# @pushrocks/logcontext
enrich logs with context
# @push.rocks/smartcontext
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/logcontext)
* [gitlab.com (source)](https://gitlab.com/pushrocks/logcontext)
* [github.com (source mirror)](https://github.com/pushrocks/logcontext)
* [docs (typedoc)](https://pushrocks.gitlab.io/logcontext/)
A module to enrich logs with context, featuring async log contexts and scope management.
## Status for master
## Install
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/logcontext/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/logcontext/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/logcontext)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/logcontext)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/logcontext)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/logcontext)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/logcontext)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
Make sure you have Node.js and npm installed, then run:
```bash
npm install @push.rocks/smartcontext
```
This will install the library and its dependencies into your local `node_modules` folder.
## Usage
Use TypeScript for best in class instellisense.
The `@push.rocks/smartcontext` module provides an efficient way to enrich your logging (or any functionality) with contextual information. It uses asynchronous context management to support hierarchical scopes—particularly handy when dealing with complex or nested asynchronous operations in Node.js.
the logconext module exposes an easy to use syntax for nodejs style async logcontexts.
### Setting Up and Basic Usage
First, import the necessary classes:
```typescript
let testLogger = new logcontext.Logger('testNamespace');
import { AsyncContext } from '@push.rocks/smartcontext';
```
testLogger.scope(async () => {
testLogger.addData('id1', {
someData: 'someValue',
#### Creating a Context
An `AsyncContext` manages a top-level `AsyncStore`. You can attach any data you want to that store. For example:
```typescript
const asyncContext = new AsyncContext();
// Add data to the top-level store
asyncContext.store.add('username', 'john_doe');
console.log(asyncContext.store.get('username')); // 'john_doe'
```
### Using `runScoped`
The `runScoped` method now creates a child store *automatically* and makes that child store accessible via `asyncContext.store` **only** within the passed-in function. Once that scoped function completes, `asyncContext.store` reverts to the original (parent) store.
#### Example
```typescript
await asyncContext.runScoped(async () => {
// While in this scope, asyncContext.store refers to the child store.
asyncContext.store.add('transactionId', 'txn_123456');
console.log(asyncContext.store.get('transactionId')); // 'txn_123456'
// Data from the parent store is also accessible in the child
console.log(asyncContext.store.get('username')); // 'john_doe'
});
// Outside runScoped, asyncContext.store is the parent store again
console.log(asyncContext.store.get('transactionId')); // undefined
```
1. **Child Store Access**: Within the scope, `asyncContext.store` points to a *child* store.
2. **Parent Data**: Any keys from the parent are still visible in the child (unless overridden).
3. **No Cross-Contamination**: Keys added in the child store dont persist in the parent after the scope ends.
### Isolating and Deleting Data
If you add a key within a `runScoped` block, it stays there unless you intentionally move it to the parent. Also, if you delete a key in the child, it wont remove it from the parent store:
```typescript
// Parent store has some initial data
asyncContext.store.add('deletableKey', 'initialValue');
await asyncContext.runScoped(async () => {
console.log(asyncContext.store.get('deletableKey')); // 'initialValue'
asyncContext.store.delete('deletableKey'); // Delete in child
console.log(asyncContext.store.get('deletableKey')); // undefined (child only)
});
// Outside scope, parent's data is intact
console.log(asyncContext.store.get('deletableKey')); // 'initialValue'
```
### Multiple Scopes
You can create multiple scopes, each maintaining its own data isolation. That way, concurrent or sequential operations dont overwrite or “contaminate” each others data in the shared context.
```typescript
// Scope 1
await asyncContext.runScoped(async () => {
asyncContext.store.add('key1', 'value1');
console.log(asyncContext.store.get('key1')); // 'value1'
});
// Scope 2
await asyncContext.runScoped(async () => {
asyncContext.store.add('key2', 'value2');
console.log(asyncContext.store.get('key2')); // 'value2'
});
// After both scopes finish, neither key1 nor key2 is visible to the parent
console.log(asyncContext.store.get('key1')); // undefined
console.log(asyncContext.store.get('key2')); // undefined
```
### Deeper Nesting
If you nest `runScoped` calls, each subsequent call creates another child store, which inherits from the store thats currently active. This allows you to build deeper context layers when needed.
```typescript
await asyncContext.runScoped(async () => {
asyncContext.store.add('layer1', true);
await asyncContext.runScoped(async () => {
asyncContext.store.add('layer2', true);
// This store sees data from both layer1 and layer2
console.log(asyncContext.store.get('layer1')); // true
console.log(asyncContext.store.get('layer2')); // true
});
testLogger.log('hi');
testLogger.error(new Error('custom error message'));
setTimeout(() => {
outsideFunction(); // log scope will travel through callbacks and promises
}, 2000);
});
let outsideFunction = () => {
// Note:
// the below testLogger reference will have different contexts
// depending from which scope "outsideFunction" was called".
testLogger.log('some message');
};
// Only layer1 data remains in scope here; layer2 is gone
console.log(asyncContext.store.get('layer2')); // undefined
});
```
## class Logger
### Testing
Below is a simplified test example using [tapbundle](https://www.npmjs.com/package/@push.rocks/tapbundle). It demonstrates `runScoped()` creating isolated child stores and verifying behavior such as data inheritance and cleanup:
```typescript
import { Logger } from 'logcontext';
import { tap, expect } from '@push.rocks/tapbundle';
import { AsyncContext } from './logcontext.classes.asynccontext.js';
// instantiate new Logger
// argument optional, if left empty auto generated shortid will be used
let myLogger = new Logger('myNamespace');
const asyncContext = new AsyncContext();
// create a scope
myLogger.scope(async () => {
// everything that is appended to the call stack from inside here will have all appended context data available
tap.test('should run scoped and see parent data', async () => {
asyncContext.store.add('parentKey', 'parentValue');
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
// add some scoped context information
myLogger.addData('customerId', '12345678');
// will log something with priviously appended context of this scope in place
myLoger.log('awesomeText');
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey', 'childValue');
expect(asyncContext.store.get('childKey')).toEqual('childValue');
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
});
});
tap.test('should isolate new keys within a child scope', async () => {
await asyncContext.runScoped(async () => {
asyncContext.store.add('temporaryKey', 'temporaryValue');
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
});
// Key won't leak to the parent
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
// More tests ...
tap.start();
```
## Contribution
### Conclusion
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
The updated `runScoped` usage makes child store management more intuitive by dynamically switching `asyncContext.store` to a child store inside the scope, then reverting back to the parent store afterwards. This design ensures:
For further information read the linked docs at the top of this readme.
- **Scoped Modifications**: Data added or removed in a child scope stays in that scope.
- **Parent Inheritance**: Child scopes still read the parents data.
- **Easy Syntax**: No need to pass the child store around; simply call `asyncContext.store` within `runScoped`.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
With `@push.rocks/smartcontext`, you can maintain clear boundaries between different parts of your asynchronous code. This not only enriches your logging with context but also simplifies tracking data across nested or concurrent operations.
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
## License and Legal Information
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.
### Trademarks
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
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.

88
test/test.both.ts Normal file
View File

@ -0,0 +1,88 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
import { AsyncStore } from '../ts/logcontext.classes.asyncstore.js';
/**
* This test file demonstrates how to use the AsyncContext and ensures
* that runScoped() properly creates child AsyncStore contexts and merges parent data.
*/
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's data is still accessible
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey', 'childValue');
// child should see its own data
expect(asyncContext.store.get('childKey')).toEqual('childValue');
// child should also see 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 the child scope finishes, 'temporaryKey' should not exist in the parent
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
tap.test('should allow adding data in multiple scopes independently', async () => {
// add data in first scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey1', 'childValue1');
expect(asyncContext.store.get('childKey1')).toEqual('childValue1');
});
// add data in 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');
// attempt to delete it in the child
asyncContext.store.delete('deletableKey');
// child no longer sees it
expect(asyncContext.store.get('deletableKey')).toBeUndefined();
// but 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();

View File

@ -1,41 +0,0 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as logcontext from '../ts/index';
let testLogger = new logcontext.Logger('testNamespace');
tap.test('should log for .error()', async () => {
testLogger.error(new Error('first error message'));
});
tap.test('should log for .fatal()', async () => {
testLogger.fatal('this is fatal');
});
// set up independent log context
tap.testParallel('should create an async LogContext', async (tools) => {
testLogger.scope(async () => {
testLogger.logmap.addData('id1', {
someData: 'someValue',
});
await tools.delayFor(10).then(async () => {
testLogger.log('hi');
testLogger.error(new Error('custom error message'));
});
});
});
tap.testParallel('should create a new scope', async () => {
testLogger.scope(async () => {
testLogger.logmap.addData('id1', {
someData: 'otherValue',
});
testLogger.info('anything');
});
});
tap.test('should log within default scope', async (tools) => {
await tools.delayFor(3000);
testLogger.log('message without context');
});
tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

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

View File

@ -1 +1 @@
export * from './logcontext.classes.logger';
export * from './logcontext.classes.asynccontext.js';

View File

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

View File

@ -0,0 +1,50 @@
import * as plugins from './logcontext.plugins.js';
export class AsyncStore {
private parentStore?: AsyncStore;
private deletedKeys: string[] = [];
private dataObject: {[key: string]: any} = {};
constructor(parentStore?: AsyncStore) {
this.parentStore = parentStore;
}
private cleanUp() {
for (const key of this.deletedKeys) {
if (this.parentStore && this.parentStore.get(key)) {
// ok still valid
} else {
delete this.deletedKeys[key];
}
}
}
public add(keyArg: string, objectArg: any) {
this.cleanUp();
if (this.deletedKeys.includes(keyArg)) {
this.deletedKeys = this.deletedKeys.filter((key) => key !== keyArg);
}
this.dataObject[keyArg] = objectArg;
}
public delete(paramName: string) {
this.cleanUp();
if (this.parentStore.get(paramName)) {
this.deletedKeys.push(paramName);
}
delete this.dataObject[paramName];
}
public get(paramName: string) {
this.cleanUp();
if (this.deletedKeys.includes(paramName)) {
return undefined;
}
return this.dataObject[paramName] || this.parentStore?.get(paramName);
}
public getAll() {
this.cleanUp();
return {...this.dataObject, ...(this.parentStore?.getAll() || {})};
}
}

View File

@ -1,124 +0,0 @@
import * as plugins from './logcontext.plugins';
import { LogMap } from './logcontext.classes.logmap';
export class Logger {
namespaceString: string;
smartcls: plugins.smartcls.SmartCls;
logmap: LogMap;
thirdPartyLogger: any;
child: any;
settings = {
enableScope: () => {
this.settingsParams.scope = true;
},
disableScope: () => {
this.settingsParams.scope = false;
},
enableAddData: () => {
this.settingsParams.addData = true;
},
disableAddData: () => {
this.settingsParams.addData = false;
},
};
private settingsParams: { scope: boolean; addData: boolean } = {
scope: true,
addData: true,
};
constructor(namespaceArg: string = plugins.smartunique.shortId()) {
this.namespaceString = namespaceArg;
this.smartcls = new plugins.smartcls.SmartCls();
this.logmap = new LogMap(this.smartcls);
}
addData(paramNameArg: string, dataArg: any) {
if (this.settingsParams.addData) {
this.logmap.addData(paramNameArg, dataArg);
}
}
addThirdPartyLogger(thirdPartyLoggerArg) {
this.thirdPartyLogger = thirdPartyLoggerArg;
}
/**
* debug
* @param logMessageArg
*/
debug(logMessageArg) {
this.routeLog('debug', logMessageArg);
}
/**
* log
* @param logMessageArg
*/
log(logMessageArg) {
this.routeLog('log', logMessageArg);
}
/**
* info
* @param logObjectArg
*/
info(logObjectArg) {
this.routeLog('info', logObjectArg);
}
/**
* error
* @param logMessageArg
* @param args
*/
error(logMessageArg, ...args) {
this.routeLog('error', logMessageArg, ...args);
}
/**
* warn
* @param logMessageArg
* @param args
*/
warn(logMessageArg, ...args) {
this.routeLog('warn', logMessageArg, ...args);
}
/**
* fatal
* @param logMessageArg
* @param args
*/
fatal(logMessageArg, ...args) {
this.routeLog('fatal', logMessageArg, ...args);
}
// creates a new async scope
scope(funcArg: any) {
// create node continuation scope
if (this.settingsParams.scope) {
this.smartcls.run(funcArg);
} else {
funcArg();
}
}
/**
* routes the log according to whats available in the environment
* @param {string} logMethod
* @param {any} message
* @param {any[]} ...args
*/
private routeLog(logMethod, message, ...args) {
const logObject = {
message: message,
type: logMethod,
logContext: this.logmap.getAllData(),
};
if (this.thirdPartyLogger && this.thirdPartyLogger[logMethod]) {
this.thirdPartyLogger[logMethod](logObject, ...args);
} else {
console.log(logObject);
}
}
}

View File

@ -1,31 +0,0 @@
import * as plugins from './logcontext.plugins';
export class LogMap {
smartcls: plugins.smartcls.SmartCls;
paramMap = new plugins.lik.Stringmap();
constructor(clsNamespaceArg: plugins.smartcls.SmartCls) {
this.smartcls = clsNamespaceArg;
}
addData(paramName: string, logData) {
this.paramMap.addString(paramName);
this.smartcls.set(paramName, logData);
}
deleteData(paramName: string) {
this.smartcls.set(paramName, null);
}
getData(paramName: string) {
return this.smartcls.get(paramName);
}
getAllData() {
const returnObject = {};
for (const stringArg of this.paramMap.getStringArray()) {
returnObject[stringArg] = this.smartcls.get(stringArg);
}
return returnObject;
}
}

View File

@ -1,13 +1,10 @@
// native scope
import { AsyncLocalStorage } from 'async_hooks';
export {
AsyncLocalStorage
};
// pushrocks scope
import * as lik from '@pushrocks/lik';
import * as smartcls from '@pushrocks/smartcls';
import * as smartunique from '@pushrocks/smartunique';
import * as lik from '@push.rocks/lik';
import * as smartunique from '@push.rocks/smartunique';
export { lik, smartcls, smartunique };
export { lik, smartunique };
// third party scope
import simpleAsyncContext from 'simple-async-context';
export { simpleAsyncContext };

16
tsconfig.json Normal file
View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"baseUrl": ".",
"paths": {}
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}