@warlock.js/context 5.24.0 → 5.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +343 -343
- package/llms-full.txt +321 -321
- package/package.json +1 -1
- package/skills/define-context/SKILL.md +160 -160
- package/skills/orchestrate-contexts/SKILL.md +161 -161
package/package.json
CHANGED
|
@@ -1,160 +1,160 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: define-context
|
|
3
|
-
description: 'Extend Context<TStore> to define an AsyncLocalStorage-backed typed context — implement buildStore, use run / enter / update / get / set / getStore / clear / hasContext. Triggers: `Context`, `Context<TStore>`, `buildStore`, `run`, `enter`, `update`, `get`, `set`, `getStore`, `clear`, `hasContext`; "share user/tenant/trace id across async calls", "AsyncLocalStorage typed wrapper", "request-scoped store without thread-through"; typical import `import { Context } from "@warlock.js/context"`. Skip: orchestrating multiple contexts — `@warlock.js/context/orchestrate-contexts/SKILL.md`; native `AsyncLocalStorage`, `cls-hooked`, `nest-context`, React Context.'
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# Define a context
|
|
7
|
-
|
|
8
|
-
`@warlock.js/context` is a tiny wrapper on Node.js's `AsyncLocalStorage`. You extend the abstract `Context<TStore>` class to declare what your context stores, and you get a typed get/set/run API that propagates through every async call inside the scope.
|
|
9
|
-
|
|
10
|
-
## Install
|
|
11
|
-
|
|
12
|
-
```bash
|
|
13
|
-
npm install @warlock.js/context
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
## Shape
|
|
17
|
-
|
|
18
|
-
```ts
|
|
19
|
-
import { Context } from "@warlock.js/context";
|
|
20
|
-
|
|
21
|
-
interface UserContextStore {
|
|
22
|
-
userId: string;
|
|
23
|
-
role: "admin" | "user";
|
|
24
|
-
tenantId: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
class UserContext extends Context<UserContextStore> {
|
|
28
|
-
/**
|
|
29
|
-
* Called by `contextManager.buildStores(payload)` for each registered context.
|
|
30
|
-
* Override to provide initialization logic for this context's store.
|
|
31
|
-
*/
|
|
32
|
-
public buildStore(payload?: Record<string, any>): UserContextStore {
|
|
33
|
-
return {
|
|
34
|
-
userId: payload?.userId ?? "",
|
|
35
|
-
role: payload?.role ?? "user",
|
|
36
|
-
tenantId: payload?.tenantId ?? "",
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export const userContext = new UserContext();
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
`buildStore` is the **only** abstract method. Everything else is provided by `Context<TStore>`.
|
|
45
|
-
|
|
46
|
-
## Usage modes
|
|
47
|
-
|
|
48
|
-
### `run()` — scoped execution
|
|
49
|
-
|
|
50
|
-
```ts
|
|
51
|
-
await userContext.run(
|
|
52
|
-
{ userId: "123", role: "admin", tenantId: "acme" },
|
|
53
|
-
async () => {
|
|
54
|
-
// Context is available throughout this async scope and any awaited calls inside it.
|
|
55
|
-
const userId = userContext.get("userId"); // "123"
|
|
56
|
-
const role = userContext.get("role"); // "admin"
|
|
57
|
-
|
|
58
|
-
await someAsyncOperation(); // context propagates through awaits
|
|
59
|
-
},
|
|
60
|
-
);
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
Use `run()` when you have a clear scope boundary (a request handler, a job, a CLI command). The context is auto-cleaned when the callback returns.
|
|
64
|
-
|
|
65
|
-
### `enter()` — middleware-style, no callback
|
|
66
|
-
|
|
67
|
-
```ts
|
|
68
|
-
function authMiddleware(req, res, next) {
|
|
69
|
-
userContext.enter({
|
|
70
|
-
userId: req.user.id,
|
|
71
|
-
role: req.user.role,
|
|
72
|
-
tenantId: req.headers["x-tenant-id"],
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
next(); // context lives for the rest of the request
|
|
76
|
-
}
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
Use `enter()` when the framework doesn't give you a callback to wrap (Express-style middleware). Under the hood it's `AsyncLocalStorage.enterWith(store)`.
|
|
80
|
-
|
|
81
|
-
### `update()` — merge into the current context
|
|
82
|
-
|
|
83
|
-
```ts
|
|
84
|
-
userContext.update({ role: "admin" });
|
|
85
|
-
// existing store: { userId, role, tenantId } → { userId, role: "admin", tenantId }
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
If there's no current store, `update` creates one with the partial (cast to the full type). Use for incremental enrichment as the request flows through layers.
|
|
89
|
-
|
|
90
|
-
`update()` (and `set()`, which calls it) silently drops `__proto__` / `constructor` / `prototype` keys instead of merging them — merging with `Object.assign` would otherwise let a caller-shaped payload (e.g. `userContext.update(req.body)`) pollute `Object.prototype` for the whole process, since the context store is shared. The rest of the payload still merges normally; this closes only the prototype-pollution vector, not general trust of merged input — validate before you merge caller-supplied data.
|
|
91
|
-
|
|
92
|
-
## Reading
|
|
93
|
-
|
|
94
|
-
```ts
|
|
95
|
-
const userId = userContext.get("userId"); // TStore[K] | undefined
|
|
96
|
-
const store = userContext.getStore(); // TStore | undefined
|
|
97
|
-
const inside = userContext.hasContext(); // boolean
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
`get` is the daily-use accessor. `getStore` returns the whole record. `hasContext` distinguishes "key absent" from "no context at all" (which matters for safety checks at the framework boundary).
|
|
101
|
-
|
|
102
|
-
## Writing within a context
|
|
103
|
-
|
|
104
|
-
```ts
|
|
105
|
-
userContext.set("role", "admin"); // sugar for update({ role: "admin" })
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
Only call `set` inside an active context. Outside one, it enters a new context with just that key set — usually not what you want.
|
|
109
|
-
|
|
110
|
-
## Clearing
|
|
111
|
-
|
|
112
|
-
```ts
|
|
113
|
-
userContext.clear();
|
|
114
|
-
// replaces the current store with an empty object of TStore
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
Rare in app code. The auto-cleanup at the end of `run()` is the normal path.
|
|
118
|
-
|
|
119
|
-
## Convenience getters via subclass
|
|
120
|
-
|
|
121
|
-
Add domain-friendly getters on the subclass when a key is read a lot:
|
|
122
|
-
|
|
123
|
-
```ts
|
|
124
|
-
class TenantContext extends Context<TenantStore> {
|
|
125
|
-
public buildStore(payload?: Record<string, any>): TenantStore {
|
|
126
|
-
return {
|
|
127
|
-
tenantId: payload?.tenantId ?? "",
|
|
128
|
-
tenantName: payload?.tenantName ?? "",
|
|
129
|
-
config: payload?.config ?? {},
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
public get tenantId() {
|
|
134
|
-
return this.get("tenantId");
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
public get config() {
|
|
138
|
-
return this.get("config");
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
Now `tenantContext.tenantId` reads better than `tenantContext.get("tenantId")` at the call site.
|
|
144
|
-
|
|
145
|
-
## What it's NOT for
|
|
146
|
-
|
|
147
|
-
- **Persistent state across requests.** AsyncLocalStorage is per-call-tree; data dies when the scope ends. Use a cache, a database, or a singleton for cross-request data.
|
|
148
|
-
- **Thread-safe shared mutable state.** Each `run()` gets a fresh store. Two parallel `run()` calls don't see each other's updates.
|
|
149
|
-
- **Sync code that doesn't `await` anything.** Works, but if there's no async boundary the context add-overhead is wasted — just pass the data as a parameter.
|
|
150
|
-
|
|
151
|
-
## See also
|
|
152
|
-
|
|
153
|
-
- [`@warlock.js/context/orchestrate-contexts/SKILL.md`](@warlock.js/context/orchestrate-contexts/SKILL.md) — running multiple contexts together via the `contextManager` singleton.
|
|
154
|
-
|
|
155
|
-
## Things NOT to do
|
|
156
|
-
|
|
157
|
-
- Don't make every cross-cutting concern a context. Build one when it has its own lifecycle (request, db transaction, trace span). For one-off data, a function argument is clearer.
|
|
158
|
-
- Don't capture the store reference outside the scope — it's freed when `run()` ends. Read the value out before exiting the scope if you need it later.
|
|
159
|
-
- Don't mutate the store object directly without `update`/`set` — works, but obscures intent. The methods exist to make state changes searchable.
|
|
160
|
-
- Don't share one context instance across unrelated concerns. One typed context per domain concept reads better than one fat `globalContext`.
|
|
1
|
+
---
|
|
2
|
+
name: define-context
|
|
3
|
+
description: 'Extend Context<TStore> to define an AsyncLocalStorage-backed typed context — implement buildStore, use run / enter / update / get / set / getStore / clear / hasContext. Triggers: `Context`, `Context<TStore>`, `buildStore`, `run`, `enter`, `update`, `get`, `set`, `getStore`, `clear`, `hasContext`; "share user/tenant/trace id across async calls", "AsyncLocalStorage typed wrapper", "request-scoped store without thread-through"; typical import `import { Context } from "@warlock.js/context"`. Skip: orchestrating multiple contexts — `@warlock.js/context/orchestrate-contexts/SKILL.md`; native `AsyncLocalStorage`, `cls-hooked`, `nest-context`, React Context.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Define a context
|
|
7
|
+
|
|
8
|
+
`@warlock.js/context` is a tiny wrapper on Node.js's `AsyncLocalStorage`. You extend the abstract `Context<TStore>` class to declare what your context stores, and you get a typed get/set/run API that propagates through every async call inside the scope.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @warlock.js/context
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Shape
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { Context } from "@warlock.js/context";
|
|
20
|
+
|
|
21
|
+
interface UserContextStore {
|
|
22
|
+
userId: string;
|
|
23
|
+
role: "admin" | "user";
|
|
24
|
+
tenantId: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
class UserContext extends Context<UserContextStore> {
|
|
28
|
+
/**
|
|
29
|
+
* Called by `contextManager.buildStores(payload)` for each registered context.
|
|
30
|
+
* Override to provide initialization logic for this context's store.
|
|
31
|
+
*/
|
|
32
|
+
public buildStore(payload?: Record<string, any>): UserContextStore {
|
|
33
|
+
return {
|
|
34
|
+
userId: payload?.userId ?? "",
|
|
35
|
+
role: payload?.role ?? "user",
|
|
36
|
+
tenantId: payload?.tenantId ?? "",
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const userContext = new UserContext();
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`buildStore` is the **only** abstract method. Everything else is provided by `Context<TStore>`.
|
|
45
|
+
|
|
46
|
+
## Usage modes
|
|
47
|
+
|
|
48
|
+
### `run()` — scoped execution
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
await userContext.run(
|
|
52
|
+
{ userId: "123", role: "admin", tenantId: "acme" },
|
|
53
|
+
async () => {
|
|
54
|
+
// Context is available throughout this async scope and any awaited calls inside it.
|
|
55
|
+
const userId = userContext.get("userId"); // "123"
|
|
56
|
+
const role = userContext.get("role"); // "admin"
|
|
57
|
+
|
|
58
|
+
await someAsyncOperation(); // context propagates through awaits
|
|
59
|
+
},
|
|
60
|
+
);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Use `run()` when you have a clear scope boundary (a request handler, a job, a CLI command). The context is auto-cleaned when the callback returns.
|
|
64
|
+
|
|
65
|
+
### `enter()` — middleware-style, no callback
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
function authMiddleware(req, res, next) {
|
|
69
|
+
userContext.enter({
|
|
70
|
+
userId: req.user.id,
|
|
71
|
+
role: req.user.role,
|
|
72
|
+
tenantId: req.headers["x-tenant-id"],
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
next(); // context lives for the rest of the request
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Use `enter()` when the framework doesn't give you a callback to wrap (Express-style middleware). Under the hood it's `AsyncLocalStorage.enterWith(store)`.
|
|
80
|
+
|
|
81
|
+
### `update()` — merge into the current context
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
userContext.update({ role: "admin" });
|
|
85
|
+
// existing store: { userId, role, tenantId } → { userId, role: "admin", tenantId }
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
If there's no current store, `update` creates one with the partial (cast to the full type). Use for incremental enrichment as the request flows through layers.
|
|
89
|
+
|
|
90
|
+
`update()` (and `set()`, which calls it) silently drops `__proto__` / `constructor` / `prototype` keys instead of merging them — merging with `Object.assign` would otherwise let a caller-shaped payload (e.g. `userContext.update(req.body)`) pollute `Object.prototype` for the whole process, since the context store is shared. The rest of the payload still merges normally; this closes only the prototype-pollution vector, not general trust of merged input — validate before you merge caller-supplied data.
|
|
91
|
+
|
|
92
|
+
## Reading
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const userId = userContext.get("userId"); // TStore[K] | undefined
|
|
96
|
+
const store = userContext.getStore(); // TStore | undefined
|
|
97
|
+
const inside = userContext.hasContext(); // boolean
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`get` is the daily-use accessor. `getStore` returns the whole record. `hasContext` distinguishes "key absent" from "no context at all" (which matters for safety checks at the framework boundary).
|
|
101
|
+
|
|
102
|
+
## Writing within a context
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
userContext.set("role", "admin"); // sugar for update({ role: "admin" })
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Only call `set` inside an active context. Outside one, it enters a new context with just that key set — usually not what you want.
|
|
109
|
+
|
|
110
|
+
## Clearing
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
userContext.clear();
|
|
114
|
+
// replaces the current store with an empty object of TStore
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Rare in app code. The auto-cleanup at the end of `run()` is the normal path.
|
|
118
|
+
|
|
119
|
+
## Convenience getters via subclass
|
|
120
|
+
|
|
121
|
+
Add domain-friendly getters on the subclass when a key is read a lot:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
class TenantContext extends Context<TenantStore> {
|
|
125
|
+
public buildStore(payload?: Record<string, any>): TenantStore {
|
|
126
|
+
return {
|
|
127
|
+
tenantId: payload?.tenantId ?? "",
|
|
128
|
+
tenantName: payload?.tenantName ?? "",
|
|
129
|
+
config: payload?.config ?? {},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
public get tenantId() {
|
|
134
|
+
return this.get("tenantId");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
public get config() {
|
|
138
|
+
return this.get("config");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Now `tenantContext.tenantId` reads better than `tenantContext.get("tenantId")` at the call site.
|
|
144
|
+
|
|
145
|
+
## What it's NOT for
|
|
146
|
+
|
|
147
|
+
- **Persistent state across requests.** AsyncLocalStorage is per-call-tree; data dies when the scope ends. Use a cache, a database, or a singleton for cross-request data.
|
|
148
|
+
- **Thread-safe shared mutable state.** Each `run()` gets a fresh store. Two parallel `run()` calls don't see each other's updates.
|
|
149
|
+
- **Sync code that doesn't `await` anything.** Works, but if there's no async boundary the context add-overhead is wasted — just pass the data as a parameter.
|
|
150
|
+
|
|
151
|
+
## See also
|
|
152
|
+
|
|
153
|
+
- [`@warlock.js/context/orchestrate-contexts/SKILL.md`](@warlock.js/context/orchestrate-contexts/SKILL.md) — running multiple contexts together via the `contextManager` singleton.
|
|
154
|
+
|
|
155
|
+
## Things NOT to do
|
|
156
|
+
|
|
157
|
+
- Don't make every cross-cutting concern a context. Build one when it has its own lifecycle (request, db transaction, trace span). For one-off data, a function argument is clearer.
|
|
158
|
+
- Don't capture the store reference outside the scope — it's freed when `run()` ends. Read the value out before exiting the scope if you need it later.
|
|
159
|
+
- Don't mutate the store object directly without `update`/`set` — works, but obscures intent. The methods exist to make state changes searchable.
|
|
160
|
+
- Don't share one context instance across unrelated concerns. One typed context per domain concept reads better than one fat `globalContext`.
|
|
@@ -1,161 +1,161 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: orchestrate-contexts
|
|
3
|
-
description: 'Orchestrate multiple Context<TStore> instances via the contextManager singleton — register, buildStores, runAll, enterAll, clearAll. Triggers: `contextManager`, `register`, `buildStores`, `runAll`, `enterAll`, `clearAll`, `unregister`, `getContext`, `hasContext`; "run multiple contexts active for the same scope", "register contexts at boot", "avoid nested run() calls for request + database + tenant"; typical import `import { contextManager } from "@warlock.js/context"`. Skip: defining a single context class — `@warlock.js/context/define-context/SKILL.md`; native `AsyncLocalStorage` nesting, `cls-hooked` namespaces.'
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# Orchestrate contexts — `contextManager`
|
|
7
|
-
|
|
8
|
-
`contextManager` is a singleton that knows about every registered `Context` and runs them all together so you don't write nested `run()` calls by hand.
|
|
9
|
-
|
|
10
|
-
## Why use it
|
|
11
|
-
|
|
12
|
-
You can call `context.run(store, fn)` directly when you only have one context. With two or more, the manager handles the nesting:
|
|
13
|
-
|
|
14
|
-
```ts
|
|
15
|
-
// ❌ Without the manager — fragile, easy to forget a layer
|
|
16
|
-
await requestContext.run(reqStore, async () =>
|
|
17
|
-
databaseContext.run(dbStore, async () =>
|
|
18
|
-
tenantContext.run(tenantStore, async () => handle()),
|
|
19
|
-
),
|
|
20
|
-
);
|
|
21
|
-
|
|
22
|
-
// ✅ With the manager — one call, deterministic order
|
|
23
|
-
await contextManager.runAll({ request: reqStore, database: dbStore, tenant: tenantStore }, handle);
|
|
24
|
-
```
|
|
25
|
-
|
|
26
|
-
## Register contexts at boot
|
|
27
|
-
|
|
28
|
-
```ts
|
|
29
|
-
import { contextManager } from "@warlock.js/context";
|
|
30
|
-
import { requestContext } from "./request-context";
|
|
31
|
-
import { databaseContext } from "./database-context";
|
|
32
|
-
import { tenantContext } from "./tenant-context";
|
|
33
|
-
|
|
34
|
-
contextManager
|
|
35
|
-
.register("request", requestContext)
|
|
36
|
-
.register("database", databaseContext)
|
|
37
|
-
.register("tenant", tenantContext);
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
Returns the manager — chain registrations. Names must be unique; re-registering with the same name overwrites.
|
|
41
|
-
|
|
42
|
-
## Build stores + run
|
|
43
|
-
|
|
44
|
-
The typical flow is two-step: build initial stores from a request-like payload, then run.
|
|
45
|
-
|
|
46
|
-
```ts
|
|
47
|
-
app.use(async (req, res, next) => {
|
|
48
|
-
const stores = contextManager.buildStores({
|
|
49
|
-
request: req,
|
|
50
|
-
response: res,
|
|
51
|
-
tenantId: req.headers["x-tenant-id"],
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
await contextManager.runAll(stores, async () => {
|
|
55
|
-
await next();
|
|
56
|
-
});
|
|
57
|
-
});
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
`buildStores(payload)` calls each registered context's `buildStore(payload)` (the abstract method on `Context<TStore>` — see [`@warlock.js/context/define-context/SKILL.md`](@warlock.js/context/define-context/SKILL.md)) and returns `{ [contextName]: store }`.
|
|
61
|
-
|
|
62
|
-
`runAll(stores, fn)` nests every context's `run()` in registration order, then invokes `fn` at the innermost layer. All contexts are active inside `fn`.
|
|
63
|
-
|
|
64
|
-
## `enterAll()` — middleware without a callback
|
|
65
|
-
|
|
66
|
-
When the framework doesn't give you a callback to wrap (e.g. Express middleware where you call `next()` and return):
|
|
67
|
-
|
|
68
|
-
```ts
|
|
69
|
-
function contextMiddleware(req, res, next) {
|
|
70
|
-
const stores = contextManager.buildStores({ request: req, response: res });
|
|
71
|
-
contextManager.enterAll(stores);
|
|
72
|
-
next();
|
|
73
|
-
}
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
`enterAll` calls `enter()` on each registered context whose name has a **truthy** store value — a `name` with no key (or a falsy value like `undefined`) is skipped, leaving any already-active store for that context untouched. The entered contexts live for the rest of the request. Each can still be `clear()`-ed later. Use `runAll` when you can — `enterAll` doesn't auto-clean.
|
|
77
|
-
|
|
78
|
-
## Lookup + introspection
|
|
79
|
-
|
|
80
|
-
```ts
|
|
81
|
-
contextManager.hasContext("tenant"); // boolean
|
|
82
|
-
const tenant = contextManager.getContext<TenantContext>("tenant");
|
|
83
|
-
// returns the registered instance or undefined
|
|
84
|
-
contextManager.unregister("debug"); // remove a context
|
|
85
|
-
contextManager.clearAll(); // clear stores on every context
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
`getContext<T>` returns the registered instance cast to `T` (the generic is constrained to `Context<any>`, so pass the concrete context class — `getContext<TenantContext>("tenant")`). It's an unchecked cast: an unknown `name` returns `undefined`, and a wrong type argument won't be caught at runtime. Useful in shared utilities that want to read from a context without importing it at the call site.
|
|
89
|
-
|
|
90
|
-
## Order matters
|
|
91
|
-
|
|
92
|
-
`runAll` nests in **registration order**. The first-registered context is the outermost layer. If contexts have ordering constraints (database before tenant because tenant resolves via the db), register them in that order.
|
|
93
|
-
|
|
94
|
-
```ts
|
|
95
|
-
contextManager
|
|
96
|
-
.register("trace", traceContext) // outermost — runs first
|
|
97
|
-
.register("request", requestContext)
|
|
98
|
-
.register("database", databaseContext)
|
|
99
|
-
.register("tenant", tenantContext); // innermost — runs last, inside all others
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
## Real-world: multi-tenant request lifecycle
|
|
103
|
-
|
|
104
|
-
```ts
|
|
105
|
-
import { Context, contextManager } from "@warlock.js/context";
|
|
106
|
-
import { randomUUID } from "crypto";
|
|
107
|
-
|
|
108
|
-
class TraceContext extends Context<{ traceId: string; startTime: number }> {
|
|
109
|
-
public buildStore(): { traceId: string; startTime: number } {
|
|
110
|
-
return { traceId: randomUUID(), startTime: Date.now() };
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
public get traceId() {
|
|
114
|
-
return this.get("traceId");
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
class RequestContext extends Context<{ request: any; response: any }> {
|
|
119
|
-
public buildStore(payload?: any) {
|
|
120
|
-
return { request: payload?.request, response: payload?.response };
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
class TenantContext extends Context<{ tenantId: string }> {
|
|
125
|
-
public buildStore(payload?: any) {
|
|
126
|
-
return { tenantId: payload?.tenantId ?? "" };
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export const traceContext = new TraceContext();
|
|
131
|
-
export const requestContext = new RequestContext();
|
|
132
|
-
export const tenantContext = new TenantContext();
|
|
133
|
-
|
|
134
|
-
contextManager
|
|
135
|
-
.register("trace", traceContext)
|
|
136
|
-
.register("request", requestContext)
|
|
137
|
-
.register("tenant", tenantContext);
|
|
138
|
-
|
|
139
|
-
// In your HTTP layer:
|
|
140
|
-
async function handleRequest(req: any, res: any) {
|
|
141
|
-
const stores = contextManager.buildStores({
|
|
142
|
-
request: req,
|
|
143
|
-
response: res,
|
|
144
|
-
tenantId: req.headers["x-tenant-id"],
|
|
145
|
-
});
|
|
146
|
-
|
|
147
|
-
return contextManager.runAll(stores, async () => {
|
|
148
|
-
// All three contexts active here:
|
|
149
|
-
console.log(`Trace ${traceContext.get("traceId")} — tenant ${tenantContext.get("tenantId")}`);
|
|
150
|
-
|
|
151
|
-
await routeAndDispatch(req, res);
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
```
|
|
155
|
-
|
|
156
|
-
## Things NOT to do
|
|
157
|
-
|
|
158
|
-
- Don't register the same context under two names — every context is its own singleton and shares its store across registrations, but multiple names confuse `buildStores` (the payload is split per name).
|
|
159
|
-
- Don't `runAll` an empty stores map — every key without a registered context is silently ignored, and missing contexts get `{}` as their store. Better to construct the stores explicitly and fail loudly when a key is missing.
|
|
160
|
-
- Don't use the manager when only one context applies. `context.run(store, fn)` is shorter and has the same semantics.
|
|
161
|
-
- Don't expect `enterAll()` to auto-clean. It's a one-way setup — pair with `clearAll()` at the end of the request, or just use `runAll` when you can.
|
|
1
|
+
---
|
|
2
|
+
name: orchestrate-contexts
|
|
3
|
+
description: 'Orchestrate multiple Context<TStore> instances via the contextManager singleton — register, buildStores, runAll, enterAll, clearAll. Triggers: `contextManager`, `register`, `buildStores`, `runAll`, `enterAll`, `clearAll`, `unregister`, `getContext`, `hasContext`; "run multiple contexts active for the same scope", "register contexts at boot", "avoid nested run() calls for request + database + tenant"; typical import `import { contextManager } from "@warlock.js/context"`. Skip: defining a single context class — `@warlock.js/context/define-context/SKILL.md`; native `AsyncLocalStorage` nesting, `cls-hooked` namespaces.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Orchestrate contexts — `contextManager`
|
|
7
|
+
|
|
8
|
+
`contextManager` is a singleton that knows about every registered `Context` and runs them all together so you don't write nested `run()` calls by hand.
|
|
9
|
+
|
|
10
|
+
## Why use it
|
|
11
|
+
|
|
12
|
+
You can call `context.run(store, fn)` directly when you only have one context. With two or more, the manager handles the nesting:
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
// ❌ Without the manager — fragile, easy to forget a layer
|
|
16
|
+
await requestContext.run(reqStore, async () =>
|
|
17
|
+
databaseContext.run(dbStore, async () =>
|
|
18
|
+
tenantContext.run(tenantStore, async () => handle()),
|
|
19
|
+
),
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
// ✅ With the manager — one call, deterministic order
|
|
23
|
+
await contextManager.runAll({ request: reqStore, database: dbStore, tenant: tenantStore }, handle);
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Register contexts at boot
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { contextManager } from "@warlock.js/context";
|
|
30
|
+
import { requestContext } from "./request-context";
|
|
31
|
+
import { databaseContext } from "./database-context";
|
|
32
|
+
import { tenantContext } from "./tenant-context";
|
|
33
|
+
|
|
34
|
+
contextManager
|
|
35
|
+
.register("request", requestContext)
|
|
36
|
+
.register("database", databaseContext)
|
|
37
|
+
.register("tenant", tenantContext);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Returns the manager — chain registrations. Names must be unique; re-registering with the same name overwrites.
|
|
41
|
+
|
|
42
|
+
## Build stores + run
|
|
43
|
+
|
|
44
|
+
The typical flow is two-step: build initial stores from a request-like payload, then run.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
app.use(async (req, res, next) => {
|
|
48
|
+
const stores = contextManager.buildStores({
|
|
49
|
+
request: req,
|
|
50
|
+
response: res,
|
|
51
|
+
tenantId: req.headers["x-tenant-id"],
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
await contextManager.runAll(stores, async () => {
|
|
55
|
+
await next();
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`buildStores(payload)` calls each registered context's `buildStore(payload)` (the abstract method on `Context<TStore>` — see [`@warlock.js/context/define-context/SKILL.md`](@warlock.js/context/define-context/SKILL.md)) and returns `{ [contextName]: store }`.
|
|
61
|
+
|
|
62
|
+
`runAll(stores, fn)` nests every context's `run()` in registration order, then invokes `fn` at the innermost layer. All contexts are active inside `fn`.
|
|
63
|
+
|
|
64
|
+
## `enterAll()` — middleware without a callback
|
|
65
|
+
|
|
66
|
+
When the framework doesn't give you a callback to wrap (e.g. Express middleware where you call `next()` and return):
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
function contextMiddleware(req, res, next) {
|
|
70
|
+
const stores = contextManager.buildStores({ request: req, response: res });
|
|
71
|
+
contextManager.enterAll(stores);
|
|
72
|
+
next();
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`enterAll` calls `enter()` on each registered context whose name has a **truthy** store value — a `name` with no key (or a falsy value like `undefined`) is skipped, leaving any already-active store for that context untouched. The entered contexts live for the rest of the request. Each can still be `clear()`-ed later. Use `runAll` when you can — `enterAll` doesn't auto-clean.
|
|
77
|
+
|
|
78
|
+
## Lookup + introspection
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
contextManager.hasContext("tenant"); // boolean
|
|
82
|
+
const tenant = contextManager.getContext<TenantContext>("tenant");
|
|
83
|
+
// returns the registered instance or undefined
|
|
84
|
+
contextManager.unregister("debug"); // remove a context
|
|
85
|
+
contextManager.clearAll(); // clear stores on every context
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`getContext<T>` returns the registered instance cast to `T` (the generic is constrained to `Context<any>`, so pass the concrete context class — `getContext<TenantContext>("tenant")`). It's an unchecked cast: an unknown `name` returns `undefined`, and a wrong type argument won't be caught at runtime. Useful in shared utilities that want to read from a context without importing it at the call site.
|
|
89
|
+
|
|
90
|
+
## Order matters
|
|
91
|
+
|
|
92
|
+
`runAll` nests in **registration order**. The first-registered context is the outermost layer. If contexts have ordering constraints (database before tenant because tenant resolves via the db), register them in that order.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
contextManager
|
|
96
|
+
.register("trace", traceContext) // outermost — runs first
|
|
97
|
+
.register("request", requestContext)
|
|
98
|
+
.register("database", databaseContext)
|
|
99
|
+
.register("tenant", tenantContext); // innermost — runs last, inside all others
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Real-world: multi-tenant request lifecycle
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { Context, contextManager } from "@warlock.js/context";
|
|
106
|
+
import { randomUUID } from "crypto";
|
|
107
|
+
|
|
108
|
+
class TraceContext extends Context<{ traceId: string; startTime: number }> {
|
|
109
|
+
public buildStore(): { traceId: string; startTime: number } {
|
|
110
|
+
return { traceId: randomUUID(), startTime: Date.now() };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
public get traceId() {
|
|
114
|
+
return this.get("traceId");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
class RequestContext extends Context<{ request: any; response: any }> {
|
|
119
|
+
public buildStore(payload?: any) {
|
|
120
|
+
return { request: payload?.request, response: payload?.response };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
class TenantContext extends Context<{ tenantId: string }> {
|
|
125
|
+
public buildStore(payload?: any) {
|
|
126
|
+
return { tenantId: payload?.tenantId ?? "" };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export const traceContext = new TraceContext();
|
|
131
|
+
export const requestContext = new RequestContext();
|
|
132
|
+
export const tenantContext = new TenantContext();
|
|
133
|
+
|
|
134
|
+
contextManager
|
|
135
|
+
.register("trace", traceContext)
|
|
136
|
+
.register("request", requestContext)
|
|
137
|
+
.register("tenant", tenantContext);
|
|
138
|
+
|
|
139
|
+
// In your HTTP layer:
|
|
140
|
+
async function handleRequest(req: any, res: any) {
|
|
141
|
+
const stores = contextManager.buildStores({
|
|
142
|
+
request: req,
|
|
143
|
+
response: res,
|
|
144
|
+
tenantId: req.headers["x-tenant-id"],
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
return contextManager.runAll(stores, async () => {
|
|
148
|
+
// All three contexts active here:
|
|
149
|
+
console.log(`Trace ${traceContext.get("traceId")} — tenant ${tenantContext.get("tenantId")}`);
|
|
150
|
+
|
|
151
|
+
await routeAndDispatch(req, res);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## Things NOT to do
|
|
157
|
+
|
|
158
|
+
- Don't register the same context under two names — every context is its own singleton and shares its store across registrations, but multiple names confuse `buildStores` (the payload is split per name).
|
|
159
|
+
- Don't `runAll` an empty stores map — every key without a registered context is silently ignored, and missing contexts get `{}` as their store. Better to construct the stores explicitly and fail loudly when a key is missing.
|
|
160
|
+
- Don't use the manager when only one context applies. `context.run(store, fn)` is shorter and has the same semantics.
|
|
161
|
+
- Don't expect `enterAll()` to auto-clean. It's a one-way setup — pair with `clearAll()` at the end of the request, or just use `runAll` when you can.
|