chore(cordis): upgrade core to 4.0.0-rc.12

This commit is contained in:
Shigma authored and imccyu committed 2026-11-05 20:34:44 +08:00
1 parent dd06371929
commit 1511a6ed44
51 files changed
+731 -400

No files matched your search

@@ -3,7 +3,7 @@
* @module subagent-settlement-fence
*/
import type { Context } from '@deepseek-ai/cordis'
import { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-agent-loop'
import type {} from '@deepseek-ai/dsh-subagent'
@@ -24,12 +24,12 @@ export function apply(ctx: Context): void {
let hasDelivered = false
ctx.effect(() => {
const disposeInbox = ctx.root.on('agent/inbox/inserted', ({ agent, message }) => {
const disposeInbox = ctx[Context.root].on('agent/inbox/inserted', ({ agent, message }) => {
if (agent.session.header.parentSession !== undefined || message.source.kind !== 'subagent-settled') return
hasDelivered = true
delivered.resolve(undefined)
})
const disposeStep = ctx.root.on('agent/pre-step', async ({ agent, turn, step }, next) => {
const disposeStep = ctx[Context.root].on('agent/pre-step', async ({ agent, turn, step }, next) => {
if (agent.session.header.parentSession === undefined && turn === 1 && step === 2 && !hasDelivered) {
await delivered.promise
}
@@ -1,7 +1,7 @@
/** Chromium acceptance of the shipped Web profile's actual Client plugin and module registries. */
import { FiberState } from '@deepseek-ai/cordis'
import type { Context, Plugin, RegistryService } from '@deepseek-ai/cordis'
import { Context, FiberState } from '@deepseek-ai/cordis'
import type { Plugin, RegistryService } from '@deepseek-ai/cordis'
import type { ClientModuleLoader, ClientModuleLoaderTarget } from '@deepseek-ai/dsh-client-modules/client'
import { chromium } from 'playwright'
import { hasExperimentalPackageReference } from '../../../scripts/experimental-package-policy.ts'
@@ -73,7 +73,7 @@ it('activates the actual default Client registry without experimental packages',
// Capture the first real root and immediately restore the registry method.
prototype.plugin = function (...args: Parameters<RegistryService['plugin']>) {
prototype.plugin = plugin
observation.ctx = this.ctx.root
observation.ctx = this.ctx[Context.root]
return plugin.apply(this, args)
}
const modules = create(options)
+19 -19
View File
@@ -9,17 +9,14 @@
en: fc6fd9ae25b8e9e5
zh: 1a2407d299404ace
/context/ctx-extend-meta:
en: 2c407cb9589b001f
zh: 70dc8650250cd4c5
en: 18c7f34127f5c5fc
zh: fa37a391e9c49f24
/context/ctx-isolate-name-label:
en: ab77052c3bf31e2b
zh: 686ca829ea5b8170
en: e086cbc07d463960
zh: 7912984e036dbae9
/context/ctx-intercept-name-config:
en: 1bd1e349f5c8687d
zh: 7634b27d2c9bade4
/context/ctx-root:
en: eb89a7f0d2bc1753
zh: 263219126a310d3b
en: e4a9d3a55ed550fc
zh: 85ebe8f0d30770e3
/context/ctx-baseurl:
en: 29c28e7558cea0ad
zh: 9b591e449c1bfd72
@@ -38,21 +35,24 @@
/context/static-members:
en: ceb197529207a8ed
zh: 7d444c03f8be0f0d
/context/static-members/context-root:
en: ad7203bb4b3533fe
zh: 02b867b883050548
/context/static-members/context-effect:
en: 19f4aaef44a7e8eb
zh: 2179cf28a7ee3f6a
en: 6c3b77ace7d4fda3
zh: 470c685819275d5f
/context/static-members/context-filter:
en: e8ca384b9a1ea98b
zh: 82189892bf0afcb0
en: 1c97248eeabea2d0
zh: 08eadac6a0871429
/context/static-members/context-isolate:
en: b8673b719837ce51
zh: 83892f9f96c3ac28
en: 471d09c9440bf738
zh: eecc52f4e5984dbf
/context/static-members/context-intercept:
en: f3ebe6568cc9a863
zh: bb51ab61a4e47d33
en: 57e806faa3abfff6
zh: 3d32af39e2019758
/context/static-members/context-is-value:
en: 7425e0ee4bc1ada7
zh: 93dee27133ded9e0
en: 0ef94fa412edfe17
zh: 30b64cd2fbb2d12e
/context/service-store-and-mixins:
en: 9f7ca8a6a0f80512
zh: 05e8cbc30e5709fc
+30 -29
View File
@@ -34,7 +34,7 @@ The child prototypally inherits every property of this context; own properties o
**Returns** a child context inheriting from this one.
[Source](../../vendor/cordis/src/context.ts#L99)
[Source](../../vendor/cordis/src/context.ts#L101)
### ctx.isolate(name, label?)
@@ -63,48 +63,38 @@ Below the returned context, reads and writes of the service `name` resolve again
**Returns** a child context whose `name` service resolves in the new scope.
[Source](../../vendor/cordis/src/context.ts#L121)
[Source](../../vendor/cordis/src/context.ts#L123)
### ctx.intercept(name, config)
```ts cordis-catalog
/**
* Add service-specific intercept config for plugins started below this
* Add service-specific intercept metadata for plugins started below this
* context.
*
* Plugins loaded under the returned context see `config` merged into the
* service's resolved config (ancestor entries first; see
* `Service[symbols.resolveConfig]`). The parent context is not affected.
* service's resolved intercept metadata (injected metadata first, then
* ancestor intercepts; see `Service[symbols.resolveIntercept]`). The parent
* context is not affected.
*
* @param name — the service name whose config to intercept.
* @param config — the intercept config to merge for that service.
* @param name — the service name whose metadata to intercept.
* @param config — the intercept metadata to merge for that service.
* @returns a child context carrying the additional intercept entry.
*/
intercept<K extends InjectKey>(name: K, config: Context[K] extends { [symbols.config]: infer T } ? T : never): this
intercept<K extends InjectKey>(name: K, config: Context[K] extends { [symbols.metadata]: infer T } ? T : never): this
intercept(name: string, config: any): this
```
Add service-specific intercept config for plugins started below this context.
Add service-specific intercept metadata for plugins started below this context.
Plugins loaded under the returned context see `config` merged into the service's resolved config (ancestor entries first; see `Service[symbols.resolveConfig]`). The parent context is not affected.
Plugins loaded under the returned context see `config` merged into the service's resolved intercept metadata (injected metadata first, then ancestor intercepts; see `Service[symbols.resolveIntercept]`). The parent context is not affected.
- `name` — the service name whose config to intercept.
- `config` — the intercept config to merge for that service.
- `name` — the service name whose metadata to intercept.
- `config` — the intercept metadata to merge for that service.
**Returns** a child context carrying the additional intercept entry.
[Source](../../vendor/cordis/src/context.ts#L139)
### ctx.root
```ts cordis-catalog
/** The root context of the application (every child context shares it). @experimental */
root: this
```
The root context of the application (every child context shares it). @experimental
[Source](../../vendor/cordis/src/context.ts#L22)
[Source](../../vendor/cordis/src/context.ts#L142)
### ctx.baseUrl
@@ -163,6 +153,17 @@ The plugin registry. Its methods are mixed onto `ctx` (`ctx.plugin`, `ctx.inject
## Static members
### Context.root
```ts cordis-catalog
/** Symbol key of the root context (see the `Context[symbols.root]` property). */
static readonly root: unique symbol
```
Symbol key of the root context (see the `Context[symbols.root]` property).
[Source](../../vendor/cordis/src/context.ts#L44)
### Context.effect
```ts cordis-catalog
@@ -172,7 +173,7 @@ static readonly effect: unique symbol
Symbol key under which a disposer exposes its EffectMeta diagnostics tree.
[Source](../../vendor/cordis/src/context.ts#L44)
[Source](../../vendor/cordis/src/context.ts#L46)
### Context.filter
@@ -183,7 +184,7 @@ static readonly filter: unique symbol
Symbol key for a context's listener filter, consulted on every event dispatch.
[Source](../../vendor/cordis/src/context.ts#L46)
[Source](../../vendor/cordis/src/context.ts#L48)
### Context.isolate
@@ -194,7 +195,7 @@ static readonly isolate: unique symbol
Symbol key of the isolation map (see the `Context[symbols.isolate]` property).
[Source](../../vendor/cordis/src/context.ts#L48)
[Source](../../vendor/cordis/src/context.ts#L50)
### Context.intercept
@@ -205,7 +206,7 @@ static readonly intercept: unique symbol
Symbol key of the intercept map (see the `Context[symbols.intercept]` property).
[Source](../../vendor/cordis/src/context.ts#L50)
[Source](../../vendor/cordis/src/context.ts#L52)
### Context.is(value)
@@ -230,7 +231,7 @@ Works across realms and across multiple copies of cordis, because the brand is k
**Returns** `true` if `value` is a Cordis context, narrowing its type.
[Source](../../vendor/cordis/src/context.ts#L61)
[Source](../../vendor/cordis/src/context.ts#L63)
## Service store and mixins
+30 -29
View File
@@ -36,7 +36,7 @@ extend(meta = {}): this
**返回**继承自当前上下文的子上下文。
[源码](../../vendor/cordis/src/context.ts#L99)
[源码](../../vendor/cordis/src/context.ts#L101)
### ctx.isolate(name, label?)
@@ -65,48 +65,38 @@ isolate(name: string, label?: symbol)
**返回**一个子上下文,其 `name` 服务在新作用域中解析。
[源码](../../vendor/cordis/src/context.ts#L121)
[源码](../../vendor/cordis/src/context.ts#L123)
### ctx.intercept(name, config)
```ts cordis-catalog
/**
* Add service-specific intercept config for plugins started below this
* Add service-specific intercept metadata for plugins started below this
* context.
*
* Plugins loaded under the returned context see `config` merged into the
* service's resolved config (ancestor entries first; see
* `Service[symbols.resolveConfig]`). The parent context is not affected.
* service's resolved intercept metadata (injected metadata first, then
* ancestor intercepts; see `Service[symbols.resolveIntercept]`). The parent
* context is not affected.
*
* @param name — the service name whose config to intercept.
* @param config — the intercept config to merge for that service.
* @param name — the service name whose metadata to intercept.
* @param config — the intercept metadata to merge for that service.
* @returns a child context carrying the additional intercept entry.
*/
intercept<K extends InjectKey>(name: K, config: Context[K] extends { [symbols.config]: infer T } ? T : never): this
intercept<K extends InjectKey>(name: K, config: Context[K] extends { [symbols.metadata]: infer T } ? T : never): this
intercept(name: string, config: any): this
```
为在此上下文之下启动的插件添加服务专属的拦截配置。
为在此上下文之下启动的插件添加服务专属的拦截元数据。
在返回的上下文下加载的插件会看到 `config` 已合并到服务解析后的配置中(祖先条目在前;见 `Service[symbols.resolveConfig]`)。父上下文不受影响。
在返回的上下文下加载的插件会看到 `config` 已合并到服务解析后的拦截元数据中(注入的元数据在前,其后是祖先上下文的拦截;见 `Service[symbols.resolveIntercept]`)。父上下文不受影响。
- `name`:要拦截其配置的服务名称。
- `config`:要为该服务合并的拦截配置。
- `name`:要拦截其元数据的服务名称。
- `config`:要为该服务合并的拦截元数据。
**返回**一个携带额外拦截条目的子上下文。
[源码](../../vendor/cordis/src/context.ts#L139)
### ctx.root
```ts cordis-catalog
/** The root context of the application (every child context shares it). @experimental */
root: this
```
应用的根上下文,所有子上下文均共享它。@experimental
[源码](../../vendor/cordis/src/context.ts#L22)
[源码](../../vendor/cordis/src/context.ts#L142)
### ctx.baseUrl
@@ -165,6 +155,17 @@ registry: RegistryService
## 静态成员
### Context.root
```ts cordis-catalog
/** Symbol key of the root context (see the `Context[symbols.root]` property). */
static readonly root: unique symbol
```
根上下文的 symbol 键(见 `Context[symbols.root]` 属性)。
[源码](../../vendor/cordis/src/context.ts#L44)
### Context.effect
```ts cordis-catalog
@@ -174,7 +175,7 @@ static readonly effect: unique symbol
资源释放函数用于公开其 EffectMeta 诊断树的 symbol 键。
[源码](../../vendor/cordis/src/context.ts#L44)
[源码](../../vendor/cordis/src/context.ts#L46)
### Context.filter
@@ -185,7 +186,7 @@ static readonly filter: unique symbol
上下文监听器过滤器的 symbol 键,每次分派事件时都会查询该过滤器。
[源码](../../vendor/cordis/src/context.ts#L46)
[源码](../../vendor/cordis/src/context.ts#L48)
### Context.isolate
@@ -196,7 +197,7 @@ static readonly isolate: unique symbol
隔离映射的 symbol 键(见 `Context[symbols.isolate]` 属性)。
[源码](../../vendor/cordis/src/context.ts#L48)
[源码](../../vendor/cordis/src/context.ts#L50)
### Context.intercept
@@ -207,7 +208,7 @@ static readonly intercept: unique symbol
拦截映射的 symbol 键(见 `Context[symbols.intercept]` 属性)。
[源码](../../vendor/cordis/src/context.ts#L50)
[源码](../../vendor/cordis/src/context.ts#L52)
### Context.is(value)
@@ -232,7 +233,7 @@ static is(value: any): value is Context
**返回** `true` 时,`value` 是 Cordis 上下文,并会收窄其类型。
[源码](../../vendor/cordis/src/context.ts#L61)
[源码](../../vendor/cordis/src/context.ts#L63)
## 服务存储与混入
+48 -48
View File
@@ -9,80 +9,80 @@
en: b5b3510f4b6dd13a
zh: a0c70471b6d779b5
/fiber/ctx-effect-execute-label:
en: 38bab93cf931eec1
zh: 50fed09622da4926
en: c3c64f4a17982e02
zh: 556d9d0892554636
/fiber/ctx-fiber:
en: a10e38bf26b4ecfe
zh: 7c91817984c95c99
/fiber/the-fiber-class:
en: 31ca1205552db9ef
zh: 5fa2e5b9a7396576
en: 0995b41083780a7f
zh: c1d6edd8c955ce73
/fiber/the-fiber-class/fiber-uid:
en: 2f0eb3658bb8497e
zh: 65d3c17ca8bd4f95
en: 97907b9b47f628e3
zh: afc3fd8bcf51fb06
/fiber/the-fiber-class/fiber-ctx:
en: 1b527d85759324f9
zh: 54aa40db2705b95c
en: 8393cd12c6f87ea4
zh: 788ec6d0567eafee
/fiber/the-fiber-class/fiber-config:
en: 73b05dc38761b681
zh: d663668f3e8fd33f
en: d24f74b8de157f3c
zh: f66c1ebcc87795ac
/fiber/the-fiber-class/fiber-state:
en: eda419fecddc4dc8
zh: 1a1b90f405cf3cbc
en: 024ffba980d93975
zh: 4aad0bca3d30329a
/fiber/the-fiber-class/fiber-dispose:
en: 43f4ad79a728a492
zh: 71b216695d0afb22
en: d73833a8055509c9
zh: 1f3be8f3f4233f97
/fiber/the-fiber-class/fiber-committed:
en: 0485c9d782bf90da
zh: 74304cd05e9c0796
en: 3bc72a323e4d548f
zh: 1c78f016d1a4f352
/fiber/the-fiber-class/fiber-provisions:
en: 1cf8235d0ca54124
zh: 3d2e39064853165f
en: dc529104da1e8423
zh: 021c26945c90996f
/fiber/the-fiber-class/fiber-inertia:
en: 2a3b1d3bc37bf986
zh: 83bd257ee685d38b
en: 19d756b6040508e1
zh: ad3ad8e3d97207f9
/fiber/the-fiber-class/fiber-name:
en: cdc0677ce1d83361
zh: a58305521a0626de
en: 0e3641a74c588380
zh: eacf740caf8f4680
/fiber/the-fiber-class/fiber-assertactive:
en: 0c3e8008ff2d69e2
zh: 7b454626d3e3a3b6
en: 0f848c17287d271e
zh: 3fbe6481321dacc9
/fiber/the-fiber-class/fiber-effect-execute-label:
en: 0e905aa798ce3830
zh: bbd0b0c537097d37
en: 20310a727bc5dce8
zh: 08296354bc91b457
/fiber/the-fiber-class/fiber-geteffects:
en: 729a1000bda8ee36
zh: 5bfc19df3addab80
en: 758fea501aa3ca1a
zh: a726b56da80bdbc7
/fiber/the-fiber-class/fiber-rawconfig:
en: 80d4007e42bd8b47
zh: 14c11dc09c6402ce
en: 06d5cba285f2ea40
zh: f5dea5faaefb1386
/fiber/the-fiber-class/fiber-effectiveconfig:
en: 8e9fcdcf458c8bde
zh: 36d21cafbf4f0198
en: 15bd2af0334d92c0
zh: 660b3421904532e6
/fiber/the-fiber-class/fiber-resolveconfig-config:
en: f8a9ca27b288bd4c
zh: 03ce360b5200fbdb
en: 4bffc7a79cad2f90
zh: 243a9ff94e7c9a39
/fiber/the-fiber-class/fiber-await:
en: 3f228c1861466386
zh: 43b3f3acfc3d314b
en: dce389b292d469e7
zh: 634fa390a1f4555c
/fiber/the-fiber-class/fiber-restart:
en: 152116f669f52e95
zh: 11d3cd941ce32d88
en: 7be06221fd6f0a12
zh: a2416eb6c313f8ce
/fiber/the-fiber-class/fiber-update-config-nosave:
en: a4f711258eb70e47
zh: fff4d880d820de10
en: d3b17d7ab1a3135e
zh: ba9167a3b8426036
/fiber/effect:
en: 007d5b214e8a8610
zh: d74c26fbb1b8aeb6
en: bf5ff8b45417829e
zh: 17b384d7375575ef
/fiber/disposable:
en: 56e4218392fa7234
zh: 8fea671180cacf6f
en: b405f69de650c34d
zh: 5dd7995aaccb5d87
/fiber/effectmeta:
en: 849aa91b8e67809f
zh: 4b31d7e2acd2a008
en: cf8a5328f613b1d6
zh: a4f37a82c132f0ed
/fiber/cordiserror:
en: d276771958d3c05f
zh: 0141656ade938d55
en: a32c8ed4338f6f7c
zh: 573e2a686eecf1f0
/fiber/validationerror:
en: 178782124cc15210
zh: 2b226f43f48af555
+49 -25
View File
@@ -34,7 +34,7 @@ Register a cleanup-aware effect on this fiber.
**Returns** a disposer that tears the effect down and settles once done.
[Source](../../vendor/cordis/src/fiber.ts#L421)
[Source](../../vendor/cordis/src/fiber.ts#L443)
### ctx.fiber
@@ -53,7 +53,7 @@ Runtime instance of one plugin application.
A fiber tracks dependency state, raw and effective config, lifecycle effects, and cleanup for the plugin context returned by `ctx.plugin()`.
[Source](../../vendor/cordis/src/fiber.ts#L184)
[Source](../../vendor/cordis/src/fiber.ts#L214)
### fiber.uid
@@ -64,7 +64,7 @@ public uid: number | null
Unique id within the registry; 0 for the root fiber, `null` once disposed.
[Source](../../vendor/cordis/src/fiber.ts#L186)
[Source](../../vendor/cordis/src/fiber.ts#L216)
### fiber.ctx
@@ -75,7 +75,7 @@ public readonly ctx: Context
The context this fiber's plugin runs in (extends the parent context).
[Source](../../vendor/cordis/src/fiber.ts#L188)
[Source](../../vendor/cordis/src/fiber.ts#L218)
### fiber.config
@@ -86,7 +86,7 @@ public config: any
Raw plugin input retained for the next activation.
[Source](../../vendor/cordis/src/fiber.ts#L190)
[Source](../../vendor/cordis/src/fiber.ts#L220)
### fiber.state
@@ -97,7 +97,7 @@ public state
Current lifecycle state; transitions emit `internal/status`.
[Source](../../vendor/cordis/src/fiber.ts#L192)
[Source](../../vendor/cordis/src/fiber.ts#L222)
### fiber.dispose
@@ -108,7 +108,7 @@ public readonly dispose: () => Promise<void>
Dispose this fiber: unload the plugin, then settle once cleanup finished.
[Source](../../vendor/cordis/src/fiber.ts#L194)
[Source](../../vendor/cordis/src/fiber.ts#L224)
### fiber.committed
@@ -119,7 +119,7 @@ public committed: Readonly<Dict<Impl>> | undefined
Required implementations retained through dependent teardown.
[Source](../../vendor/cordis/src/fiber.ts#L196)
[Source](../../vendor/cordis/src/fiber.ts#L226)
### fiber.provisions
@@ -130,7 +130,7 @@ public readonly provisions: Set<Impl>
Service implementations owned by this fiber, including isolated provisions.
[Source](../../vendor/cordis/src/fiber.ts#L198)
[Source](../../vendor/cordis/src/fiber.ts#L228)
### fiber.inertia
@@ -141,7 +141,7 @@ public inertia: Promise<void> | undefined
The in-flight load/unload transition, if one is currently running.
[Source](../../vendor/cordis/src/fiber.ts#L200)
[Source](../../vendor/cordis/src/fiber.ts#L230)
### fiber.name
@@ -152,7 +152,7 @@ get name()
The plugin's display name, inherited from the nearest named ancestor, else `'root'`.
[Source](../../vendor/cordis/src/fiber.ts#L342)
[Source](../../vendor/cordis/src/fiber.ts#L364)
### fiber.assertActive()
@@ -170,7 +170,7 @@ Throw if the fiber has already been disposed.
**Returns** nothing when the fiber is still active.
[Source](../../vendor/cordis/src/fiber.ts#L357)
[Source](../../vendor/cordis/src/fiber.ts#L379)
### fiber.effect(execute, label?)
@@ -201,7 +201,7 @@ Register a cleanup-aware effect on this fiber.
**Returns** a disposer that tears the effect down and settles once done.
[Source](../../vendor/cordis/src/fiber.ts#L421)
[Source](../../vendor/cordis/src/fiber.ts#L443)
### fiber.getEffects()
@@ -218,7 +218,7 @@ Return metadata for currently registered effects.
**Returns** one `EffectMeta` tree per labeled live effect.
[Source](../../vendor/cordis/src/fiber.ts#L574)
[Source](../../vendor/cordis/src/fiber.ts#L596)
### fiber.rawConfig
@@ -229,7 +229,7 @@ get rawConfig(): unknown
Raw input retained for the next activation, without evaluating expressions or validating it.
[Source](../../vendor/cordis/src/fiber.ts#L649)
[Source](../../vendor/cordis/src/fiber.ts#L671)
### fiber.effectiveConfig
@@ -244,7 +244,7 @@ get effectiveConfig(): unknown
The object passed to plugin activation or the latest successful update that retained the instance. Candidate resolution does not publish it; volatile updates retain its references. Undefined before activation and readable after unload; callers requiring a live instance check `state`.
[Source](../../vendor/cordis/src/fiber.ts#L664)
[Source](../../vendor/cordis/src/fiber.ts#L686)
### fiber.resolveConfig(config)
@@ -266,7 +266,7 @@ Evaluate and validate a candidate using this fiber's `internal/config` hooks and
**Returns** The candidate's resolved config, retaining the schema's result identity.
[Source](../../vendor/cordis/src/fiber.ts#L676)
[Source](../../vendor/cordis/src/fiber.ts#L698)
### fiber.await()
@@ -284,7 +284,7 @@ Wait for current lifecycle work and rethrow startup errors.
**Returns** this fiber, once it has settled into a stable state.
[Source](../../vendor/cordis/src/fiber.ts#L754)
[Source](../../vendor/cordis/src/fiber.ts#L776)
### fiber.restart()
@@ -302,7 +302,7 @@ Dispose and immediately reload this plugin with its current config.
**Returns** a promise resolving once the reload settled.
[Source](../../vendor/cordis/src/fiber.ts#L768)
[Source](../../vendor/cordis/src/fiber.ts#L790)
### fiber.update(config, noSave?)
@@ -324,7 +324,7 @@ Resolve a candidate, retain its raw config and apply it through the update water
**Returns** The awaited update/restart result, or undefined when a synchronous listener handles it.
[Source](../../vendor/cordis/src/fiber.ts#L783)
[Source](../../vendor/cordis/src/fiber.ts#L805)
## Effect
@@ -345,7 +345,7 @@ type Effect<T = any> =
| AsyncEffect<T>
```
[Source](../../vendor/cordis/src/fiber.ts#L83)
[Source](../../vendor/cordis/src/fiber.ts#L113)
## Disposable
@@ -363,7 +363,7 @@ Disposers run in reverse registration order when the owning fiber unloads; they
type Disposable<T = any> = () => T
```
[Source](../../vendor/cordis/src/fiber.ts#L74)
[Source](../../vendor/cordis/src/fiber.ts#L104)
## EffectMeta
@@ -379,7 +379,7 @@ interface EffectMeta {
}
```
[Source](../../vendor/cordis/src/fiber.ts#L96)
[Source](../../vendor/cordis/src/fiber.ts#L126)
## CordisError
@@ -405,7 +405,7 @@ namespace CordisError {
}
```
[Source](../../vendor/cordis/src/fiber.ts#L157)
[Source](../../vendor/cordis/src/fiber.ts#L187)
## ValidationError
@@ -421,7 +421,31 @@ class ValidationError extends TypeError {
*
* @param issues — the standard-schema issues, one message line each.
*/
constructor(issues: readonly StandardSchemaV1.Issue[])
constructor(public issues: readonly StandardSchemaV1.Issue[])
/**
* Test whether a value is a config `ValidationError`, including one from another copy of Cordis.
*
* @param error — the value to test.
* @returns `true` if `error` carries the global validation-error brand.
*/
static is(error: unknown): error is ValidationError
/**
* Convert an issue path to plain property keys.
*
* @param path — the standard-schema issue path; segments may be `{ key }` objects.
* @returns the property keys, or an empty array when the issue has no path.
*/
static normalizePath(path: StandardSchemaV1.Issue['path'] = [])
/**
* Format an issue path as a dotted string.
*
* @param path — the standard-schema issue path.
* @returns the keys joined with `.`.
*/
static formatPath(path: StandardSchemaV1.Issue['path'])
}
```
+49 -25
View File
@@ -36,7 +36,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable<Promise<void>>
**返回**一个用于撤销该作用的清理函数,并在清理完成后结算。
[源码](../../vendor/cordis/src/fiber.ts#L421)
[源码](../../vendor/cordis/src/fiber.ts#L443)
### ctx.fiber
@@ -55,7 +55,7 @@ fiber: Fiber
fiber 会跟踪 `ctx.plugin()` 返回的插件上下文所对应的依赖状态、原始配置与有效配置、生命周期作用和清理操作。
[源码](../../vendor/cordis/src/fiber.ts#L184)
[源码](../../vendor/cordis/src/fiber.ts#L214)
### fiber.uid
@@ -66,7 +66,7 @@ public uid: number | null
在注册表中的唯一 id;根 fiber 的 id 为 0,dispose 后为 `null`。
[源码](../../vendor/cordis/src/fiber.ts#L186)
[源码](../../vendor/cordis/src/fiber.ts#L216)
### fiber.ctx
@@ -77,7 +77,7 @@ public readonly ctx: Context
此 fiber 的插件运行所在的上下文(扩展自父上下文)。
[源码](../../vendor/cordis/src/fiber.ts#L188)
[源码](../../vendor/cordis/src/fiber.ts#L218)
### fiber.config
@@ -88,7 +88,7 @@ public config: any
为下次激活保留的原始插件输入。
[源码](../../vendor/cordis/src/fiber.ts#L190)
[源码](../../vendor/cordis/src/fiber.ts#L220)
### fiber.state
@@ -99,7 +99,7 @@ public state
当前生命周期状态;状态转换会发出 `internal/status`。
[源码](../../vendor/cordis/src/fiber.ts#L192)
[源码](../../vendor/cordis/src/fiber.ts#L222)
### fiber.dispose
@@ -110,7 +110,7 @@ public readonly dispose: () => Promise<void>
dispose 此 fiber:卸载插件,并在清理完成后结算。
[源码](../../vendor/cordis/src/fiber.ts#L194)
[源码](../../vendor/cordis/src/fiber.ts#L224)
### fiber.committed
@@ -121,7 +121,7 @@ public committed: Readonly<Dict<Impl>> | undefined
在依赖方清理完成前保留的所需服务实现。
[源码](../../vendor/cordis/src/fiber.ts#L196)
[源码](../../vendor/cordis/src/fiber.ts#L226)
### fiber.provisions
@@ -132,7 +132,7 @@ public readonly provisions: Set<Impl>
此 fiber 拥有的服务实现,包括隔离域中的服务。
[源码](../../vendor/cordis/src/fiber.ts#L198)
[源码](../../vendor/cordis/src/fiber.ts#L228)
### fiber.inertia
@@ -143,7 +143,7 @@ public inertia: Promise<void> | undefined
当前正在进行的加载或卸载转换;如果没有此类转换,则为 undefined。
[源码](../../vendor/cordis/src/fiber.ts#L200)
[源码](../../vendor/cordis/src/fiber.ts#L230)
### fiber.name
@@ -154,7 +154,7 @@ get name()
插件的显示名称,继承自最近的具名祖先;如果不存在,则为 `'root'`。
[源码](../../vendor/cordis/src/fiber.ts#L342)
[源码](../../vendor/cordis/src/fiber.ts#L364)
### fiber.assertActive()
@@ -172,7 +172,7 @@ assertActive()
**返回**:fiber 仍处于活动状态时不返回任何内容。
[源码](../../vendor/cordis/src/fiber.ts#L357)
[源码](../../vendor/cordis/src/fiber.ts#L379)
### fiber.effect(execute, label?)
@@ -203,7 +203,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable<Promise<void>>
**返回**一个用于撤销该作用的清理函数,并在清理完成后结算。
[源码](../../vendor/cordis/src/fiber.ts#L421)
[源码](../../vendor/cordis/src/fiber.ts#L443)
### fiber.getEffects()
@@ -220,7 +220,7 @@ getEffects()
**返回**:每个带标签的活动作用对应一棵 `EffectMeta` 树。
[源码](../../vendor/cordis/src/fiber.ts#L574)
[源码](../../vendor/cordis/src/fiber.ts#L596)
### fiber.rawConfig
@@ -232,7 +232,7 @@ get rawConfig(): unknown
保留供下次激活使用的原始输入,不执行表达式求值或验证。
[源码](../../vendor/cordis/src/fiber.ts#L649)
[源码](../../vendor/cordis/src/fiber.ts#L671)
### fiber.effectiveConfig
@@ -247,7 +247,7 @@ get effectiveConfig(): unknown
传给插件激活过程或最近一次成功保留实例的更新的对象。候选配置求值不发布结果;volatile 更新保留其中的引用。激活前为 undefined,卸载后仍可读取;需要运行中实例的调用方还应检查 `state`。
[源码](../../vendor/cordis/src/fiber.ts#L664)
[源码](../../vendor/cordis/src/fiber.ts#L686)
### fiber.resolveConfig(config)
@@ -270,7 +270,7 @@ resolveConfig(config: unknown): unknown
**返回**候选配置的解析结果,保留 schema 返回对象的身份。
[源码](../../vendor/cordis/src/fiber.ts#L676)
[源码](../../vendor/cordis/src/fiber.ts#L698)
### fiber.await()
@@ -288,7 +288,7 @@ async await()
**返回**:进入稳定状态后的此 fiber。
[源码](../../vendor/cordis/src/fiber.ts#L754)
[源码](../../vendor/cordis/src/fiber.ts#L776)
### fiber.restart()
@@ -306,7 +306,7 @@ dispose 此插件,并立即使用其当前配置重新加载。
**返回**一个在重新加载完成后兑现的 promise。
[源码](../../vendor/cordis/src/fiber.ts#L768)
[源码](../../vendor/cordis/src/fiber.ts#L790)
### fiber.update(config, noSave?)
@@ -328,7 +328,7 @@ update(config: any, noSave = false): Awaitable<void>
**返回** 可等待的更新或重启结果;同步监听器处理更新时为 undefined。
[源码](../../vendor/cordis/src/fiber.ts#L783)
[源码](../../vendor/cordis/src/fiber.ts#L805)
## Effect
@@ -349,7 +349,7 @@ type Effect<T = any> =
| AsyncEffect<T>
```
[源码](../../vendor/cordis/src/fiber.ts#L83)
[源码](../../vendor/cordis/src/fiber.ts#L113)
## Disposable
@@ -367,7 +367,7 @@ type Effect<T = any> =
type Disposable<T = any> = () => T
```
[源码](../../vendor/cordis/src/fiber.ts#L74)
[源码](../../vendor/cordis/src/fiber.ts#L104)
## EffectMeta
@@ -383,7 +383,7 @@ interface EffectMeta {
}
```
[源码](../../vendor/cordis/src/fiber.ts#L96)
[源码](../../vendor/cordis/src/fiber.ts#L126)
## CordisError
@@ -409,7 +409,7 @@ namespace CordisError {
}
```
[源码](../../vendor/cordis/src/fiber.ts#L157)
[源码](../../vendor/cordis/src/fiber.ts#L187)
## ValidationError
@@ -425,7 +425,31 @@ class ValidationError extends TypeError {
*
* @param issues — the standard-schema issues, one message line each.
*/
constructor(issues: readonly StandardSchemaV1.Issue[])
constructor(public issues: readonly StandardSchemaV1.Issue[])
/**
* Test whether a value is a config `ValidationError`, including one from another copy of Cordis.
*
* @param error — the value to test.
* @returns `true` if `error` carries the global validation-error brand.
*/
static is(error: unknown): error is ValidationError
/**
* Convert an issue path to plain property keys.
*
* @param path — the standard-schema issue path; segments may be `{ key }` objects.
* @returns the property keys, or an empty array when the issue has no path.
*/
static normalizePath(path: StandardSchemaV1.Issue['path'] = [])
/**
* Format an issue path as a dotted string.
*
* @param path — the standard-schema issue path.
* @returns the keys joined with `.`.
*/
static formatPath(path: StandardSchemaV1.Issue['path'])
}
```
+1 -1
View File
@@ -15,7 +15,7 @@ This file is GENERATED from source (`scripts/gen-cordis-catalog.ts`) and verifie
- `ctx.effect` — Register a disposable side effect tied to the fiber. ([`vendor/cordis/src/fiber.ts:9`](../../vendor/cordis/src/fiber.ts))
- `ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin` — Low-level service-store access and binding. ([`vendor/cordis/src/reflect.ts:7`](../../vendor/cordis/src/reflect.ts))
- `ctx.extend / ctx.isolate / ctx.intercept` — Derive a child context (scoped services / isolation / interception). ([`vendor/cordis/src/context.ts:42`](../../vendor/cordis/src/context.ts))
- `ctx.root / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger` — Ambient handles onto the running context graph. ([`vendor/cordis/src/context.ts:16`](../../vendor/cordis/src/context.ts))
- `ctx[Context.root] / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger` — Ambient handles onto the running context graph. ([`vendor/cordis/src/context.ts:16`](../../vendor/cordis/src/context.ts))
- `ctx.timer (+ interval / timeout / throttle / debounce)` — Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick). ([`vendor/timer/src/index.ts:4`](../../vendor/timer/src/index.ts))
- `ctx.loader` — The config Loader that booted the app (present under the loader). ([`vendor/loader/src/index.ts:30`](../../vendor/loader/src/index.ts))
+23 -20
View File
@@ -6,32 +6,35 @@
en: d2c0c5bce430d1be
zh: 124ab2656ea6d044
/service:
en: a163fe605c4a8045
zh: 060a6f4ce086c5c2
en: 7a6f25d41ad5192b
zh: 2792165d3c31015e
/service/service-name:
en: 32a75e66b17c0b79
zh: 0a5ff9fc45b3bea0
en: 1bd1a435be60580f
zh: cb8b96113cac2ed8
/service/static-members:
en: ceb197529207a8ed
zh: 7d444c03f8be0f0d
/service/static-members/service-init:
en: ade1a1c4543fac8c
zh: b7a4b616ee930b5b
en: a0740625ccc443b1
zh: 1efa474f255783ee
/service/static-members/service-check:
en: 111351ada5972a9a
zh: 1537da7793a6a02c
/service/static-members/service-config:
en: 93d8ff69722f9b46
zh: 9ba1532d164c2231
en: 699de9371410a4c0
zh: 32343701e1c3fb5a
/service/static-members/service-invoke:
en: 6d87f35f8cf52b05
zh: 278dbce6025b2834
en: 24ec894223f0958f
zh: 81b7615fc897f318
/service/static-members/service-metadata:
en: 735840e221643d61
zh: 1c2ce2f18786e0c6
/service/static-members/service-extend:
en: 5b78b68d8de8cef9
zh: 6df27f37da11a104
en: fa797364cccc8cc3
zh: 8fa77ae99efee25e
/service/static-members/service-tracker:
en: 52071ebded7ec026
zh: 4647fa3f989b5deb
/service/static-members/service-resolveconfig:
en: ad62f59468d1a765
zh: 4a31b52f61e1af6e
en: f59cdcca1f9b972a
zh: b50793b1114cff35
/service/static-members/service-mergeintercept:
en: af31055b96f4834f
zh: 27b22f17ba6329c0
/service/static-members/service-resolveintercept:
en: 72a73af9a6c877db
zh: 41cf10059ebf51ee
+34 -23
View File
@@ -9,7 +9,7 @@ Base class for services that expose a named API on `ctx`.
Subclasses call `super(ctx, name)` from their constructor. The service is registered immediately and is automatically removed with the owning fiber.
[Source](../../vendor/cordis/src/service.ts#L11)
[Source](../../vendor/cordis/src/service.ts#L12)
### service.name
@@ -20,7 +20,7 @@ public name!: string
The service name this instance is registered under.
[Source](../../vendor/cordis/src/service.ts#L30)
[Source](../../vendor/cordis/src/service.ts#L33)
## Static members
@@ -33,7 +33,7 @@ static readonly init: unique symbol
Symbol key of an instance method run after construction (class plugins).
[Source](../../vendor/cordis/src/service.ts#L13)
[Source](../../vendor/cordis/src/service.ts#L14)
### Service.check
@@ -44,18 +44,7 @@ static readonly check: unique symbol
Symbol key of the availability predicate passed to `ctx.provide()`.
[Source](../../vendor/cordis/src/service.ts#L15)
### Service.config
```ts cordis-catalog
/** Symbol key of the phantom intercept-config type parameter. */
static readonly config: unique symbol
```
Symbol key of the phantom intercept-config type parameter.
[Source](../../vendor/cordis/src/service.ts#L17)
[Source](../../vendor/cordis/src/service.ts#L16)
### Service.invoke
@@ -66,7 +55,18 @@ static readonly invoke: unique symbol
Symbol key of the call body making a service callable (e.g. `ctx.logger()`).
[Source](../../vendor/cordis/src/service.ts#L19)
[Source](../../vendor/cordis/src/service.ts#L18)
### Service.metadata
```ts cordis-catalog
/** Symbol key of the phantom intercept-metadata type parameter. */
static readonly metadata: unique symbol
```
Symbol key of the phantom intercept-metadata type parameter.
[Source](../../vendor/cordis/src/service.ts#L20)
### Service.extend
@@ -77,7 +77,7 @@ static readonly extend: unique symbol
Symbol key of the helper deriving an extended service instance.
[Source](../../vendor/cordis/src/service.ts#L21)
[Source](../../vendor/cordis/src/service.ts#L22)
### Service.tracker
@@ -88,15 +88,26 @@ static readonly tracker: unique symbol
Symbol key of the tracker metadata used for context tracing.
[Source](../../vendor/cordis/src/service.ts#L23)
[Source](../../vendor/cordis/src/service.ts#L24)
### Service.resolveConfig
### Service.mergeIntercept
```ts cordis-catalog
/** Symbol key of the intercept-config resolution helper below. */
static readonly resolveConfig: unique symbol
/** Symbol key of the intercept-metadata merge hook below. */
static readonly mergeIntercept: unique symbol
```
Symbol key of the intercept-config resolution helper below.
Symbol key of the intercept-metadata merge hook below.
[Source](../../vendor/cordis/src/service.ts#L25)
[Source](../../vendor/cordis/src/service.ts#L26)
### Service.resolveIntercept
```ts cordis-catalog
/** Symbol key of the intercept-metadata resolution helper below. */
static readonly resolveIntercept: unique symbol
```
Symbol key of the intercept-metadata resolution helper below.
[Source](../../vendor/cordis/src/service.ts#L28)
+34 -23
View File
@@ -11,7 +11,7 @@
子类在构造函数中调用 `super(ctx, name)`。服务会立即注册,并随所属 fiber 自动移除。
[源码](../../vendor/cordis/src/service.ts#L11)
[源码](../../vendor/cordis/src/service.ts#L12)
### service.name
@@ -22,7 +22,7 @@ public name!: string
此实例注册时使用的服务名称。
[源码](../../vendor/cordis/src/service.ts#L30)
[源码](../../vendor/cordis/src/service.ts#L33)
## 静态成员
@@ -35,7 +35,7 @@ static readonly init: unique symbol
构造完成后运行的实例方法所使用的符号键(类插件)。
[源码](../../vendor/cordis/src/service.ts#L13)
[源码](../../vendor/cordis/src/service.ts#L14)
### Service.check
@@ -46,18 +46,7 @@ static readonly check: unique symbol
传给 `ctx.provide()` 的可用性谓词所使用的符号键。
[源码](../../vendor/cordis/src/service.ts#L15)
### Service.config
```ts cordis-catalog
/** Symbol key of the phantom intercept-config type parameter. */
static readonly config: unique symbol
```
虚设拦截配置类型参数所使用的符号键。
[源码](../../vendor/cordis/src/service.ts#L17)
[源码](../../vendor/cordis/src/service.ts#L16)
### Service.invoke
@@ -68,7 +57,18 @@ static readonly invoke: unique symbol
使服务可被调用的调用体所使用的符号键(例如 `ctx.logger()`)。
[源码](../../vendor/cordis/src/service.ts#L19)
[源码](../../vendor/cordis/src/service.ts#L18)
### Service.metadata
```ts cordis-catalog
/** Symbol key of the phantom intercept-metadata type parameter. */
static readonly metadata: unique symbol
```
虚设拦截元数据类型参数所使用的符号键。
[源码](../../vendor/cordis/src/service.ts#L20)
### Service.extend
@@ -79,7 +79,7 @@ static readonly extend: unique symbol
用于派生扩展服务实例的辅助方法所使用的符号键。
[源码](../../vendor/cordis/src/service.ts#L21)
[源码](../../vendor/cordis/src/service.ts#L22)
### Service.tracker
@@ -90,15 +90,26 @@ static readonly tracker: unique symbol
上下文追踪所用跟踪器元数据的符号键。
[源码](../../vendor/cordis/src/service.ts#L23)
[源码](../../vendor/cordis/src/service.ts#L24)
### Service.resolveConfig
### Service.mergeIntercept
```ts cordis-catalog
/** Symbol key of the intercept-config resolution helper below. */
static readonly resolveConfig: unique symbol
/** Symbol key of the intercept-metadata merge hook below. */
static readonly mergeIntercept: unique symbol
```
下述拦截配置解析辅助方法所使用的符号键。
下述拦截元数据合并钩子所使用的符号键。
[源码](../../vendor/cordis/src/service.ts#L25)
[源码](../../vendor/cordis/src/service.ts#L26)
### Service.resolveIntercept
```ts cordis-catalog
/** Symbol key of the intercept-metadata resolution helper below. */
static readonly resolveIntercept: unique symbol
```
下述拦截元数据解析辅助方法所使用的符号键。
[源码](../../vendor/cordis/src/service.ts#L28)
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/cordis-root-and-intercept-metadata/guide.md
/:
en: 4de1e21e06e1c67a
zh: f3195026d93e8127
/ctx-context-root-replaces-ctx-root-and-service-intercept-metadata-is-renamed:
en: 546ad75e75ee931f
zh: 16cd20c00e92e6f5
/ctx-context-root-replaces-ctx-root-and-service-intercept-metadata-is-renamed/change:
en: 73b1b7e0bdffb92b
zh: 108e4d9d0d333c36
/ctx-context-root-replaces-ctx-root-and-service-intercept-metadata-is-renamed/migration:
en: 6080606517656f7e
zh: 1e045b715c3c4946
@@ -0,0 +1,29 @@
---
kind: upgrade-guide
description: "Cordis 4.0.0-rc.12 replaces ctx.root with ctx[Context.root] and renames the service intercept-metadata API."
---
# `ctx[Context.root]` replaces `ctx.root`, and service intercept metadata is renamed
English | [中文](guide.zh.md)
## Change
`@deepseek-ai/cordis` now carries upstream Cordis 4.0.0-rc.12. Third-party plugins and services written against the previous release are affected:
- `ctx.root` no longer exists. The root context is `ctx[Context.root]`; `Context.root` is a symbol exported on the `Context` class. Inside a plugin, reading `ctx.root` throws `cannot get property "root" without inject`.
- `Service.config` becomes `Service.metadata`. A service declares its intercept type with `declare [Service.metadata]: T`.
- `[Service.resolveConfig](base?, head?)` becomes `[Service.resolveIntercept]()`, which takes no arguments.
- A service's `Config.merge` hook is no longer called. Override `[Service.mergeIntercept](...values)` instead; it receives the values in increasing precedence.
- Metadata a plugin declares in object-form `inject` now has the lowest precedence. Intercepts added with `ctx.intercept()` override it; previously the injected value overrode them.
- A context created with `ctx.isolate(name)` no longer falls back to the enclosing plugin's injected `name`. Plugins started under it, and reads after its own provision is withdrawn, throw `cannot get property "<name>" without inject`.
- A failed `ctx.parallel()` throws an `AggregateError` whose message names the event, and a fiber disposed while it was not active, such as a failed one, now settles to `FiberState.DISPOSED`.
## Migration
1. Replace every `ctx.root` with `ctx[Context.root]`, importing `Context` as a value from `@deepseek-ai/cordis`. Plain JavaScript without the import can read `ctx[Symbol.for('cordis.root')]`.
2. In service classes, rename `declare [Service.config]` to `declare [Service.metadata]` and calls of `[Service.resolveConfig]()` to `[Service.resolveIntercept]()`. Replace `base` and `head` arguments by declaring the base value in `inject` and adding the override with `ctx.intercept()`.
3. Move a `Config.merge` implementation to a `[Service.mergeIntercept](...values)` method on the service class.
4. Where a plugin relied on its `inject` metadata overriding an ancestor `ctx.intercept()`, set the value with `ctx.intercept()` at the plugin's context instead.
5. Where code under `ctx.isolate(name)` needs the enclosing plugin's service, provide that service inside the isolated context or start the code from a context that is not isolated.
6. Run your TypeScript build: references to `ctx.root`, `Service.config` and `Service.resolveConfig` fail to compile. Start the plugin and confirm that services resolve and logs keep their names.
@@ -0,0 +1,29 @@
---
kind: upgrade-guide
description: "Cordis 4.0.0-rc.12 用 ctx[Context.root] 取代 ctx.root,并重命名服务拦截元数据 API。"
---
# `ctx[Context.root]` 取代 `ctx.root`,服务拦截元数据 API 重命名
[English](guide.md) | 中文
## 变更
`@deepseek-ai/cordis` 现在包含上游 Cordis 4.0.0-rc.12。针对上一版本编写的第三方插件和服务会受到以下影响:
- `ctx.root` 不再存在。根上下文改为 `ctx[Context.root]`;`Context.root` 是 `Context` 类上导出的 symbol。在插件内读取 `ctx.root` 会抛出 `cannot get property "root" without inject`。
- `Service.config` 改为 `Service.metadata`。服务用 `declare [Service.metadata]: T` 声明其拦截类型。
- `[Service.resolveConfig](base?, head?)` 改为不带参数的 `[Service.resolveIntercept]()`。
- 服务的 `Config.merge` 钩子不再被调用。改为重写 `[Service.mergeIntercept](...values)`;它按优先级从低到高接收各个值。
- 插件在对象形式的 `inject` 中声明的元数据现在优先级最低,用 `ctx.intercept()` 添加的拦截会覆盖它;此前是注入的值覆盖拦截。
- 用 `ctx.isolate(name)` 创建的上下文不再回退到外层插件注入的 `name`。在其下启动的插件,以及在其自身提供撤回后的读取,都会抛出 `cannot get property "<name>" without inject`。
- `ctx.parallel()` 失败时抛出的 `AggregateError` 的消息会注明事件名;在非活动状态下被销毁的 fiber(例如失败的 fiber)现在会进入 `FiberState.DISPOSED`。
## 迁移
1. 将所有 `ctx.root` 替换为 `ctx[Context.root]`,并从 `@deepseek-ai/cordis` 以值的形式导入 `Context`。无法导入的纯 JavaScript 可以读取 `ctx[Symbol.for('cordis.root')]`。
2. 在服务类中,将 `declare [Service.config]` 改为 `declare [Service.metadata]`,将对 `[Service.resolveConfig]()` 的调用改为 `[Service.resolveIntercept]()`。原来的 `base` 参数改为在 `inject` 中声明,`head` 参数改为用 `ctx.intercept()` 添加。
3. 将 `Config.merge` 的实现移到服务类的 `[Service.mergeIntercept](...values)` 方法中。
4. 如果插件依赖其 `inject` 元数据覆盖祖先的 `ctx.intercept()`,改为在该插件的上下文上用 `ctx.intercept()` 设置该值。
5. 如果 `ctx.isolate(name)` 之下的代码需要外层插件的服务,在隔离的上下文中提供该服务,或从未隔离的上下文启动这段代码。
6. 运行 TypeScript 构建:引用 `ctx.root`、`Service.config` 和 `Service.resolveConfig` 的代码会编译失败。启动插件,确认服务可以解析,日志名称保持不变。
+5 -5
View File
@@ -1,5 +1,5 @@
/** Owner Peers for Gateway specs: every in-process call names its Peer explicitly. */
import type { Context } from '@deepseek-ai/cordis'
import { Context } from '@deepseek-ai/cordis'
import { Peer } from '@deepseek-ai/dsh-client-connection'
import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol'
@@ -11,10 +11,10 @@ const owners = new WeakMap<Context, PeerScope>()
* @returns the tree's shared owner Peer.
*/
export function ownerPeer(ctx: Context): PeerScope {
let peer = owners.get(ctx.root)
let peer = owners.get(ctx[Context.root])
if (peer === undefined) {
peer = new Peer(ctx.root, { principal: { kind: 'owner' } })
owners.set(ctx.root, peer)
peer = new Peer(ctx[Context.root], { principal: { kind: 'owner' } })
owners.set(ctx[Context.root], peer)
}
return peer
}
@@ -26,5 +26,5 @@ export function ownerPeer(ctx: Context): PeerScope {
* @returns an independent Peer.
*/
export function peerFor(ctx: Context, principal: Principal): PeerScope {
return new Peer(ctx.root, { principal })
return new Peer(ctx[Context.root], { principal })
}
@@ -85,7 +85,7 @@ function controllers(
history: HistoryController
web: WebController
} {
roots.add(ctx.root)
roots.add(ctx[Context.root])
installSessionReadTestServices(ctx)
const history = new HistoryController(ctx)
return { history, web: new WebController(ctx, history, promote) }
@@ -1054,7 +1054,7 @@ describe('boot', () => {
writeFileSync(join(dir, 'exiting.mjs'), [
'export const name = "exiting"',
'export function apply(ctx) {',
' void ctx.root.fiber.dispose()',
' void ctx[Symbol.for("cordis.root")].fiber.dispose()',
'}',
'',
].join('\n'))
@@ -293,7 +293,7 @@ describe('shipped builtins', () => {
// implementation is stored under that symbol, so the root realm cannot
// resolve the service and a second composition mounting the same rows
// cannot collide with this one.
const rootKey = ctx.root[Context.isolate].demoRealmSvc
const rootKey = ctx[Context.root][Context.isolate].demoRealmSvc
expect(rootKey).toBeDefined()
expect(ctx.reflect.store[rootKey!]).toBeUndefined()
} finally {
+3 -3
View File
@@ -93,7 +93,7 @@ export class ConfigEditor extends Service {
await withFileLock(join(this.ownerContext.profileContext.dir, 'package.json'), async () => {
if (!this.entries().includes(entry) || entry.fiber === undefined) throw new Error('Configuration entry is no longer available')
const beforePatches = readProfilePatches('dsh', this.ownerContext.profileContext)
await reconcileProfilePatches(this.ownerContext.root, beforePatches, 'dsh')
await reconcileProfilePatches(this.ownerContext[Context.root], beforePatches, 'dsh')
if (!this.entries().includes(entry)) throw new Error('Configuration entry changed during reload')
const current = structuredClone((entry.options.config ?? {}) as Record<string, unknown>)
const inherited = this.inherited(entry, loadProfileDirectory('dsh', this.ownerContext.profileContext.dir, this.ownerContext.profileContext.installAnchor))
@@ -140,10 +140,10 @@ export class ConfigEditor extends Service {
}
await writeFileAtomic(path, String(document), { mode: 0o600 })
try {
await reconcileProfilePatches(this.ownerContext.root, patches, 'dsh', [entry.options.id])
await reconcileProfilePatches(this.ownerContext[Context.root], patches, 'dsh', [entry.options.id])
} catch (error) {
await writeFileAtomic(path, before, { mode: 0o600 })
await reconcileProfilePatches(this.ownerContext.root, beforePatches, 'dsh')
await reconcileProfilePatches(this.ownerContext[Context.root], beforePatches, 'dsh')
throw error
}
})
+1 -1
View File
@@ -971,7 +971,7 @@ class Hmr extends Service {
return job !== undefined && namespaceOf(job) === undefined
}))
}, undefined)
const result = await recomposeProfile(this.ownerContext.root, patches, 'dsh', { requiredIds, running })
const result = await recomposeProfile(this.ownerContext[Context.root], patches, 'dsh', { requiredIds, running })
const restartReason = compared === undefined || unavailable ? 'module-comparison' : result.restartReason
return { warnings: result.warnings, pending, ...restartReason === undefined ? {} : { restartReason } }
} finally {
@@ -348,7 +348,7 @@ it('reports a stopped entry that no recomposition started again by its fiber sta
f.ctx.registry.delete(plugin)
await Promise.all(fibers.map(fiber => fiber.await()))
// Applying the same patches leaves the unchanged Include's rows alone.
const warnings = await f.ctx.hmr.runExclusive(() => reconcileProfilePatches(f.ctx.root, readProfilePatches('test', f.profile), 'test'))
const warnings = await f.ctx.hmr.runExclusive(() => reconcileProfilePatches(f.ctx[Context.root], readProfilePatches('test', f.profile), 'test'))
expect(warnings).toEqual([expect.stringMatching(/^addon \(addon\): fiber state 4/u)])
})
+4 -4
View File
@@ -15,7 +15,7 @@
import { spawn, type ChildProcess } from 'node:child_process'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
import type { Context } from '@deepseek-ai/cordis'
import { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { auditStartupEntries } from '@deepseek-ai/dsh-app-boot'
import type {} from '@deepseek-ai/dsh-client-connection'
@@ -223,10 +223,10 @@ export function apply(ctx: Context, config: Config): void {
// route owner are still mounting. Await Loader settlement first; a
// hand-built tree without a Loader is already the complete tree.
const announceReady = (): void => {
if (ANNOUNCED_ROOTS.has(connectionCtx.root)) return
if (ANNOUNCED_ROOTS.has(connectionCtx[Context.root])) return
const webUrl = appRootUrl()
const authenticatedUrl = connectionCtx.connection.authenticatedUrl(webUrl)
ANNOUNCED_ROOTS.add(connectionCtx.root)
ANNOUNCED_ROOTS.add(connectionCtx[Context.root])
if (config.printUrl) {
console.log(`dsh web: ${authenticatedUrl}`)
}
@@ -245,7 +245,7 @@ export function apply(ctx: Context, config: Config): void {
if (settled === undefined) announceReady()
else {
void settled.then(async () => {
await auditStartupEntries(connectionCtx.root, 'dsh web', () => {})
await auditStartupEntries(connectionCtx[Context.root], 'dsh web', () => {})
// The tree can be disposed while the boot was in flight (early
// SIGTERM); a URL line or browser tab for a dead server would only
// mislead, and reading torn-down services would turn a clean shutdown
+2 -2
View File
@@ -1,5 +1,5 @@
/** Host HTTP bridge for browser-client RPC. */
import type { Context } from '@deepseek-ai/cordis'
import { Context } from '@deepseek-ai/cordis'
import type { IncomingMessage, ServerResponse } from 'node:http'
import z from '@deepseek-ai/schemastery'
import type {} from '@deepseek-ai/dsh-attachment'
@@ -136,7 +136,7 @@ export async function apply(ctx: Context, config?: ConnectionConfig): Promise<vo
const connection = new HostConnectionService(
ctx,
trustedHosts,
await BrowserAuth.create(ctx.root, ctx.credentials, cookieMaxAgeDays),
await BrowserAuth.create(ctx[Context.root], ctx.credentials, cookieMaxAgeDays),
)
ctx.inject(['webServer'], (webCtx) => {
assertImageBodyCapacity(webCtx, maxRequestBodyBytes)
@@ -16,7 +16,7 @@ declare module '@deepseek-ai/dsh-llm/types' {
import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types'
import type {} from '@deepseek-ai/dsh-working-directory'
import { FiberState, type Context } from '@deepseek-ai/cordis'
import { Context, FiberState } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-agent-instructions'
import {
@@ -788,7 +788,7 @@ export function apply(ctx: Context): void {
accepting = false
try {
// Root unload begins before child cleanup; only live plugin removal changes Session policy.
if (ctx.root.fiber.state === FiberState.ACTIVE) {
if (ctx[Context.root].fiber.state === FiberState.ACTIVE) {
for (const session of ctx.sessions.list()) {
if (permissionPresets.current(session) !== AUTO_PRESET) continue
permissionPresets.set(session, 'danger-full-access')
@@ -1469,7 +1469,7 @@ describe('cancellation and integration teardown', () => {
await auto.restart()
expect(ctx.root.fiber.state).toBe(FiberState.ACTIVE)
expect(ctx[Context.root].fiber.state).toBe(FiberState.ACTIVE)
expect(ctx.permissionPresets.current(session)).toBe('danger-full-access')
expect(ctx.permissionPresets.names).toContain(AUTO_PRESET)
expect(session.snapshotEvents().filter(event => event.type === 'approval/policy').at(-1)?.data)
@@ -1530,7 +1530,7 @@ describe('cancellation and integration teardown', () => {
const disposal = ctx.fiber.dispose().then(() => { disposed = true })
try {
await cancelled.promise
expect(ctx.root.fiber.state).toBe(FiberState.UNLOADING)
expect(ctx[Context.root].fiber.state).toBe(FiberState.UNLOADING)
expect(disposed).toBe(false)
expect(sessions.list()).toContain(session)
expect(events).toEqual(beforeShutdown)
@@ -1,6 +1,6 @@
/** Lifecycle-driven Cordis tree publication shared by Host and Client plugin faces. */
import type { Context } from '@deepseek-ai/cordis'
import { Context } from '@deepseek-ai/cordis'
import type { CordisTreeSnapshot } from './snapshot.ts'
import { CordisTreeCollector, type CordisTreeLimits } from './collector.ts'
@@ -19,7 +19,7 @@ export function observeCordisTree(
listener: CordisTreeSnapshotListener,
limits: CordisTreeLimits,
): () => void {
const collector = new CordisTreeCollector(ctx.root, limits)
const collector = new CordisTreeCollector(ctx[Context.root], limits)
let scheduled = false
let closed = false
const publish = (): void => {
@@ -1113,7 +1113,7 @@ export const INHERITED_CTX_API: readonly InheritedApiEntry[] = [
{ name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.' },
{ name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.' },
{ name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).' },
{ name: 'ctx.root / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' },
{ name: 'ctx[Context.root] / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' },
{ name: 'ctx.timer (+ interval / timeout / throttle / debounce)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick).' },
{ name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).' },
]
@@ -63,6 +63,21 @@ describe('sandbox context façade — escape surface is closed', () => {
expect(harness.ctx.tools.get('smuggled')).toBeUndefined()
})
it('withholds the ctx[Context.root] symbol key, so the root bypass registers nothing', async () => {
const harness = await setup()
const message = await runTouching(harness, `
ctx[Symbol.for('cordis.root')].tools.register({
name: 'smuggled_via_root_key',
description: 'raw, unguarded',
parameters: { type: 'object', properties: {} },
${CONTENT_OUTPUT_CODE}
async execute() { return [] },
})
`)
expect(message).toContain("reading 'tools'")
expect(harness.ctx.tools.get('smuggled_via_root_key')).toBeUndefined()
})
it('rejects assignment to the façade rather than silently dropping it', async () => {
const harness = await setup()
await expect(mount(harness, 'return { name: \'writer\', apply(ctx) { ctx.stash = 1 } }'))
@@ -71,7 +86,7 @@ describe('sandbox context façade — escape surface is closed', () => {
it('denies a service whose method returns a Context (the .ctx escape), registering nothing', async () => {
// A cordis Service instance carries `.ctx` (a real Context), so
// `ctx.systemPrompt.ctx.root.tools.register(…)` would escape the façade; service-return
// `ctx.systemPrompt.ctx[Context.root].tools.register(…)` would escape the façade; service-return
// guards reject that Context before the registration lands.
const harness = await setup()
const message = await (async (): Promise<string> => {
@@ -81,7 +96,7 @@ describe('sandbox context façade — escape surface is closed', () => {
name: 'svc-ctx-escape',
inject: ['systemPrompt', 'tools'],
apply(ctx) {
ctx.systemPrompt.ctx.root.tools.register({
ctx.systemPrompt.ctx[Symbol.for('cordis.root')].tools.register({
name: 'smuggled_via_service',
description: 'raw, unguarded',
parameters: { type: 'object', properties: {} },
@@ -10506,7 +10506,7 @@ export const INHERITED_CTX_API: readonly InheritedApiEntry[] = [
{ name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.' },
{ name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.' },
{ name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).' },
{ name: 'ctx.root / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' },
{ name: 'ctx[Context.root] / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' },
{ name: 'ctx.timer (+ interval / timeout / throttle / debounce)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick).' },
{ name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).' },
]
+2 -2
View File
@@ -13,7 +13,7 @@
* @module @deepseek-ai/dsh-mcp-client
*/
import type { Context, Fiber } from '@deepseek-ai/cordis'
import { Context, type Fiber } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { scopeOf } from '@deepseek-ai/dsh-scope'
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
@@ -210,7 +210,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
// Fiber and survives its reloads and final disposal.
let status!: ReturnType<typeof registerStatusCell>
ctx.effect(() => {
const owner = scopeOf(ctx) ?? ctx.root
const owner = scopeOf(ctx) ?? ctx[Context.root]
let names = activeServerNames.get(owner)
if (!names) {
names = new Set()
@@ -68,7 +68,7 @@ function withinFiber(fiber: Fiber, root: Fiber): boolean {
*/
export function leakedServices(ctx: Context, mount: Fiber): string[] {
const store = ctx.reflect.store
const rootIsolate = ctx.root[Context.isolate]
const rootIsolate = ctx[Context.root][Context.isolate]
const leaked: string[] = []
for (const key of Object.getOwnPropertySymbols(store)) {
const impl = store[key]
+2 -2
View File
@@ -9,7 +9,7 @@
* @module @deepseek-ai/dsh-sdk-jsonrpc-server
*/
import type { Context } from '@deepseek-ai/cordis'
import { Context } from '@deepseek-ai/cordis'
import type { Readable, Writable } from 'node:stream'
import Schema from '@deepseek-ai/schemastery'
import { JsonRpcLineTransport } from '@deepseek-ai/dsh-sdk-protocol'
@@ -47,7 +47,7 @@ export function apply(ctx: Context, config: JsonRpcConfig): void {
const resolvedConfig = config as JsonRpcConfig & { maxTokensAsSuccess: boolean }
// Protocol shutdown owns the complete runtime process, so it must await the
// root lifecycle (including persistence) before exiting.
const rootFiber = ctx.root.fiber
const rootFiber = ctx[Context.root].fiber
/* v8 ignore next -- production stdio wiring; tests always inject the runtime hooks */
const input = config.input ?? process.stdin
/* v8 ignore next -- production stdio wiring; tests always inject the runtime hooks */
+1 -1
View File
@@ -232,7 +232,7 @@ export class SettingsForms extends Service {
const ctx = ownerContext
ctx.effect(() => () => { this.closed = true })
ctx.on('app-boot/config-reload', () => { this.invalidate() })
void ctx.root.loader.await().then(() => this.importLegacyDocument()).catch((error: unknown) => { ctx.logger.error(error) })
void ctx[Context.root].loader.await().then(() => this.importLegacyDocument()).catch((error: unknown) => { ctx.logger.error(error) })
}
/** Move the sections of the removed `settings.yaml` into the active profile once the Loader has settled every entry.
@@ -4,7 +4,7 @@
* @module subagent-send-message-fence
*/
import type { Context } from '@deepseek-ai/cordis'
import { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-agent-loop'
/** Fixture plugin name. */
@@ -23,12 +23,12 @@ export function apply(ctx: Context): void {
let parentMaintenance: Promise<void> | undefined
ctx.effect(() => {
const disposeSession = ctx.root.on('session/event', (session, event) => {
const disposeSession = ctx[Context.root].on('session/event', (session, event) => {
if (session.header.parentSession !== undefined || event.type !== 'turn/end' || event.data.turn !== 1) return
hasStopped = true
parentStopped.resolve(undefined)
})
const disposeStatus = ctx.root.on('agent/status', ({ agent, status }) => {
const disposeStatus = ctx[Context.root].on('agent/status', ({ agent, status }) => {
if (
agent.session.header.parentSession === undefined &&
status === 'idle' &&
@@ -40,7 +40,7 @@ export function apply(ctx: Context): void {
})
}
})
const disposeInbox = ctx.root.on('agent/inbox/inserted', ({ agent, message }) => {
const disposeInbox = ctx[Context.root].on('agent/inbox/inserted', ({ agent, message }) => {
if (
agent.session.header.parentSession === undefined &&
message.source.kind === 'subagent-settled'
@@ -48,7 +48,7 @@ export function apply(ctx: Context): void {
childSettled.resolve(undefined)
}
})
const disposeStep = ctx.root.on('agent/pre-step', async ({ agent, turn, step }, next) => {
const disposeStep = ctx[Context.root].on('agent/pre-step', async ({ agent, turn, step }, next) => {
if (agent.session.header.parentSession !== undefined) {
childReady.resolve(undefined)
if (!hasStopped) await parentStopped.promise
+2 -2
View File
@@ -270,8 +270,8 @@ export abstract class TypertRemoteService<out T = never> extends Service<T> {
* tree registers it on the root, where it outlives any one Service.
*/
function provideInvocationAccessor(ctx: Context): void {
if (Object.hasOwn(ctx.root.reflect.props, 'invocation')) return
ctx.root.accessor('invocation', { get: () => undefined })
if (Object.hasOwn(ctx[Context.root].reflect.props, 'invocation')) return
ctx[Context.root].accessor('invocation', { get: () => undefined })
}
/**
+1 -1
View File
@@ -25,7 +25,7 @@ describe('Cordis core API generation', () => {
expect(pages.get('docs/cordis-api/events.md')).toContain('## DispatchMode')
expect(pages.get('docs/cordis-api/fiber.md')).toContain('## EffectMeta')
expect(pages.get('docs/cordis-api/registry.md')).toContain('## Plugin')
expect(pages.get('docs/cordis-api/service.md')).toContain('### Service.resolveConfig')
expect(pages.get('docs/cordis-api/service.md')).toContain('### Service.resolveIntercept')
const fiber = pages.get('docs/cordis-api/fiber.md') ?? ''
expect(fiber).toContain('```\n\nRegister a cleanup-aware effect on this fiber.')
+2 -1
View File
@@ -110,7 +110,8 @@ describe('Cordis rc.11 lifecycle', () => {
await isolated.plugin((child) => { expect(child.rc11View).toBe('inner') })
await withdraw()
expect(owner.rc11View).toBe('outer')
expect(isolated.rc11View).toBe('outer')
// The isolated context does not fall back to the injected view once its own provision is withdrawn.
expect(() => isolated.rc11View).toThrow('without inject')
})
await ctx.plugin((owner) => {
owner.isolate('rc11Private').provide('rc11Private', true)
+114
View File
@@ -0,0 +1,114 @@
/** Cordis rc.12 root access, intercept metadata, isolation, disposal and event errors. */
import { Context, FiberState, Service } from '@deepseek-ai/cordis'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
interface Metadata {
a?: number
b?: number
c?: number
tags?: string[]
}
declare module '@deepseek-ai/cordis' {
interface Context {
rc12Meta: MetadataService
rc12View: string
}
}
class MetadataService extends Service<Metadata> {
constructor(ctx: Context) {
super(ctx, 'rc12Meta')
}
read(): Metadata {
return this[Service.resolveIntercept]()
}
}
function root() {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
return ctx
}
describe('Cordis rc.12 core', () => {
it('exposes the root context through Context.root only', async () => {
const ctx = root()
const seen: unknown[] = []
await ctx.plugin((child: Context) => {
seen.push(child[Context.root])
seen.push(child[Symbol.for('cordis.root') as typeof Context.root])
expect(() => { Reflect.get(child, 'root') }).toThrow('cannot get property "root" without inject')
})
expect(seen).toEqual([ctx, ctx])
})
it('merges injected metadata under context intercepts', async () => {
const ctx = root()
await ctx.plugin(MetadataService)
let metadata!: Metadata
await ctx.intercept('rc12Meta', { b: 2 }).inject({ rc12Meta: { a: 1, b: 1 } }, (child) => {
metadata = child.intercept('rc12Meta', { c: 3 }).rc12Meta.read()
})
expect(metadata).toEqual({ a: 1, b: 2, c: 3 })
})
it('merges through an overridden mergeIntercept in increasing precedence', async () => {
class Tagged extends MetadataService {
override [Service.mergeIntercept](...values: Metadata[]): Metadata {
return { tags: values.flatMap(value => value.tags ?? []) }
}
}
const ctx = root()
await ctx.plugin(Tagged)
let metadata!: Metadata
await ctx.intercept('rc12Meta', { tags: ['outer'] }).inject({ rc12Meta: { tags: ['inject'] } }, (child) => {
metadata = child.intercept('rc12Meta', { tags: ['inner'] }).rc12Meta.read()
})
expect(metadata).toEqual({ tags: ['inject', 'outer', 'inner'] })
})
it('does not inherit the injected view across an isolation boundary', async () => {
const ctx = root()
ctx.provide('rc12View', 'outer')
const results: string[] = []
const read = (child: Context) => {
try {
return child.rc12View
} catch (error) {
return error instanceof Error ? error.message : String(error)
}
}
await ctx.inject(['rc12View'], async (owner) => {
await owner.plugin((child) => { results.push(read(child)) })
await owner.isolate('rc12View').plugin((child) => { results.push(read(child)) })
})
expect(results).toEqual(['outer', 'cannot get property "rc12View" without inject'])
})
it('settles pending and failed fibers to DISPOSED', async () => {
const ctx = root()
const pending = ctx.inject(['rc12NeverProvided'], () => {})
expect(pending.state).toBe(FiberState.PENDING)
await pending.dispose()
expect(pending.state).toBe(FiberState.DISPOSED)
const error = vi.spyOn(ctx.logger('fiber'), 'error').mockImplementation(() => {})
onTestFinished(() => { error.mockRestore() })
const failed = ctx.plugin(() => { throw new Error('rc12 boom') })
await expect(failed.await()).rejects.toThrow('rc12 boom')
expect(failed.state).toBe(FiberState.FAILED)
await failed.dispose()
expect(failed.state).toBe(FiberState.DISPOSED)
})
it('names the failing event in the parallel AggregateError', async () => {
const ctx = root()
ctx.on('rc12-parallel' as never, () => { throw new Error('listener failed') })
const symbol = Symbol('rc12-symbol')
ctx.on(symbol as never, () => { throw new Error('symbol listener failed') })
await expect(ctx.parallel('rc12-parallel' as never)).rejects.toThrow('one or more listeners of event "rc12-parallel" failed')
await expect(ctx.parallel(symbol as never)).rejects.toThrow('one or more listeners of event Symbol(rc12-symbol) failed')
})
})
+1 -1
View File
@@ -1193,7 +1193,7 @@ export const CORDIS_CATALOG_POLICY: CordisCatalogPolicy = {
{ name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.', source: 'vendor/cordis/src/fiber.ts:9' },
{ name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.', source: 'vendor/cordis/src/reflect.ts:7' },
{ name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).', source: 'vendor/cordis/src/context.ts:42' },
{ name: 'ctx.root / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.', source: 'vendor/cordis/src/context.ts:16' },
{ name: 'ctx[Context.root] / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.', source: 'vendor/cordis/src/context.ts:16' },
{ name: 'ctx.timer (+ interval / timeout / throttle / debounce)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick).', source: 'vendor/timer/src/index.ts:4' },
{ name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).', source: 'vendor/loader/src/index.ts:30' },
],
+5 -4
View File
@@ -16,7 +16,7 @@ Upstream workspace: `cordis-workspace` (local checkout: `~/repos/cordis-workspac
|---|---|---|---|---|---|
| `cosmokit/` | `@deepseek-ai/cosmokit` | `cosmokit` | 1.8.1 | https://github.com/deepseek-harness/cosmokit | `16f6fc058ade66e8ac5da0033d35a8d0f279f544` |
| `schemastery/` | `@deepseek-ai/schemastery` | `schemastery` | 3.18.0 | https://github.com/deepseek-harness/schemastery (`packages/core`) | `e67cee00ad725bd1534aee930a979ea3eec6f698` |
| `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.11 | https://github.com/cordiverse/cordis (`packages/core`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` |
| `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.12 | https://github.com/cordiverse/cordis (`packages/core`) | `01b396240ce47cf2779c40af9bc445bb748fe112` |
| `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.8 | https://github.com/cordiverse/cordis (`packages/loader`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` |
| `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.1.1 | https://github.com/cordiverse/cordis (`packages/include`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` |
| `group/` | `@deepseek-ai/cordis-plugin-group` | `@cordisjs/plugin-group` | 1.0.0 | https://github.com/deepseek-harness/cordis (`packages/group`) | `abb0a307cb1d3b0947f455d590cf5ba922d4caa4` |
@@ -30,14 +30,14 @@ Intentionally **not** vendored (verified unused by this set): `reggol`, `@cordis
## Local modifications
Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V28.
Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V29.
- **V1 · `hmr/src/index.ts`**: removed the `./locales/en-US.yml` / `./locales/zh-CN.yml` imports, the `.i18n({...})` call on the `Config` schema, and the `src/locales/` directory. Rationale: those imports require a runtime YAML loader hook (`@cordisjs/unyaml`) that we do not vendor; the i18n texts only localize config descriptions.
- **V2 · All `package.json` files**: regenerated for Harness releases with scoped names, release versions, publication metadata, precise bundled-runtime and `lib/types/**/*.d.ts` / `.d.ts.map` file entries, source exports where applicable, and declaration metadata pointing at `lib/types`. References within the vendored set use `workspace:~`. HMR declares `esbuild` as a direct dev dependency for its imported `BuildFailure` type, and Loader requires `node-addon-require-builtin@^0.1.4` to match published app runtimes.
- **V3 · All `tsconfig.json` files**: regenerated to extend the repo-root `tsconfig.base.json`, emit TypeScript intermediates to `lib/types`, and declare project references.
- **V4 · Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces.
- **V4 · Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Core's upstream source already uses explicit `.ts` specifiers. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces.
- **V5 · `schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface.
- **V6 · `cordis/src/fiber.ts` lifecycle hardening**: locally closes three reentrant disposal gaps. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup.
- **V7 · Cordis, Loader and Timer JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed to the fork.
- **V7 · Cordis, Loader and Timer JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed to the fork.
- **V9 · `hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. The Include change listener logs a rejected `Include.refresh()` instead of leaving the rejection unhandled; the rejection reports unsaved runtime changes while Include keeps its running tree. Covered by `packages/boot/hmr/tests/watch-config.spec.ts` and `scripts/cordis-vendor-hmr-include.spec.ts`.
- **V10 · Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`. Conditional exports select `.mjs` for import and `.cjs` for require; without them, concurrent imports under module-hook hosts reach the CJS entry and can race its require of ESM Cosmokit (`ERR_REQUIRE_ESM_RACE_CONDITION`).
- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` and the `!!js` YAML dialect as `entryListSchema`, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts` and `scripts/cordis-entry-commit.spec.ts`.
@@ -51,6 +51,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each
- **V25 · Loader lifecycle adaptations**: before a combined context/config update, Loader refreshes dependencies locally, which prevents activation against stale isolation bindings; disabled-entry updates await disposal. Failed fibers require an explicit update after correcting their input or dependencies. Core retains the effect hardening in V6; rc.11 owns dependency teardown ordering and superseded-activation handling.
- **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.11`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. In rc.11 the entry stays registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`.
- **V27 · `loader/src/config/tree.ts` explicit ids with `:`**: `ensureId()` accepts explicit ids containing `EntryTree.sep`; upstream rejects them. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `<package name>:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`.
- **V28 · Core rc.12 compatibility in Loader and Include**: `loader/src/index.ts` declares `[Service.metadata]`, resolves its intercept through `[Service.resolveIntercept]` and logs through `ctx[Context.root]`; `include/src/index.ts` logs through `ctx[Context.root]`. These lines match the `v4.0.0-rc.12` tag while the rest of both packages keeps its rc.11 baseline. Retire this entry when Loader and Include are synchronized to that tag.
### Resolver adaptations
+12 -9
View File
@@ -14,12 +14,12 @@ import { Fiber } from './fiber.ts'
* be read from `ctx`.
*/
export interface Context {
/** The root context of the application; every child context shares it. */
[symbols.root]: this
/** Isolation map: service name → scope label. Lookups for a name resolve within its label. */
[symbols.isolate]: Dict<symbol>
/** Intercept map: service name → config merged into that service's per-plugin config. */
[symbols.intercept]: Dict
/** The root context of the application (every child context shares it). @experimental */
root: this
/** Base URL used to resolve relative plugin/module specifiers, if the runtime sets one. */
baseUrl?: string | undefined
/** The event bus. Its methods are also mixed onto `ctx` (`ctx.on`, `ctx.emit`, ...). */
@@ -40,6 +40,8 @@ export interface Context {
* contexts without mutating their parent.
*/
export class Context {
/** Symbol key of the root context (see the `Context[symbols.root]` property). */
static readonly root: unique symbol = symbols.root
/** Symbol key under which a disposer exposes its {@link EffectMeta} diagnostics tree. */
static readonly effect: unique symbol = symbols.effect
/** Symbol key for a context's listener filter, consulted on every event dispatch. */
@@ -72,7 +74,7 @@ export class Context {
this[symbols.isolate] = Object.create(null)
this[symbols.intercept] = Object.create(null)
const self = new Proxy<this>(this, ReflectService.handler)
this.root = self
this[symbols.root] = self
this.baseUrl = undefined
this.fiber = new Fiber(self, {}, Object.create(null), null, () => [])
this.reflect = new ReflectService(self)
@@ -125,18 +127,19 @@ export class Context {
}
/**
* Add service-specific intercept config for plugins started below this
* Add service-specific intercept metadata for plugins started below this
* context.
*
* Plugins loaded under the returned context see `config` merged into the
* service's resolved config (ancestor entries first; see
* `Service[symbols.resolveConfig]`). The parent context is not affected.
* service's resolved intercept metadata (injected metadata first, then
* ancestor intercepts; see `Service[symbols.resolveIntercept]`). The parent
* context is not affected.
*
* @param name — the service name whose config to intercept.
* @param config — the intercept config to merge for that service.
* @param name — the service name whose metadata to intercept.
* @param config — the intercept metadata to merge for that service.
* @returns a child context carrying the additional intercept entry.
*/
intercept<K extends InjectKey>(name: K, config: Context[K] extends { [symbols.config]: infer T } ? T : never): this
intercept<K extends InjectKey>(name: K, config: Context[K] extends { [symbols.metadata]: infer T } ? T : never): this
intercept(name: string, config: any): this
intercept(name: string, config: any) {
const intercept = Object.create(this[symbols.intercept])
+8 -4
View File
@@ -166,8 +166,10 @@ export class EventsService {
this.emit('internal/dispatch', type, name, args, thisArg)
}
const filter = thisArg?.[Context.filter]
return [thisArg, (this._hooks[name] || [])
.filter(hook => hook.global || !filter || filter.call(thisArg, hook.ctx)).map(hook => hook.callback)] as const
const callbacks = (this._hooks[name] || [])
.filter(hook => hook.global || !filter || filter.call(thisArg, hook.ctx))
.map(hook => hook.callback)
return [thisArg, callbacks, name] as const
}
/**
@@ -189,10 +191,12 @@ export class EventsService {
* @returns a promise resolving once every listener has settled.
*/
async parallel(...args: any[]) {
const [thisArg, callbacks] = this._resolve('parallel', args)
const [thisArg, callbacks, name] = this._resolve('parallel', args)
const results = await Promise.allSettled(callbacks.map(async callback => Reflect.apply(callback, thisArg, args)))
const errors = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
if (errors.length) throw new AggregateError(errors.map(error => error.reason))
if (!errors.length) return
const label = typeof name === 'symbol' ? String(name) : `"${name}"`
throw new AggregateError(errors.map(error => error.reason), `one or more listeners of event ${label} failed`)
}
/**
+40 -18
View File
@@ -24,15 +24,45 @@ export class ValidationError extends TypeError {
*
* @param issues — the standard-schema issues, one message line each.
*/
constructor(issues: readonly StandardSchemaV1.Issue[]) {
constructor(public issues: readonly StandardSchemaV1.Issue[]) {
super(`invalid config:\n` + issues.map(issue => {
if (issue.path) {
return ` - ${issue.message} (at ${issue.path.join('.')})`
if (issue.path?.length) {
return ` - ${issue.message} (at ${ValidationError.formatPath(issue.path)})`
} else {
return ` - ${issue.message}`
}
}).join('\n'))
}
/**
* Test whether a value is a config `ValidationError`, including one from another copy of Cordis.
*
* @param error — the value to test.
* @returns `true` if `error` carries the global validation-error brand.
*/
static is(error: unknown): error is ValidationError {
return !!error?.[kValidationError]
}
/**
* Convert an issue path to plain property keys.
*
* @param path — the standard-schema issue path; segments may be `{ key }` objects.
* @returns the property keys, or an empty array when the issue has no path.
*/
static normalizePath(path: StandardSchemaV1.Issue['path'] = []) {
return path.map(segment => typeof segment === 'object' ? segment.key : segment)
}
/**
* Format an issue path as a dotted string.
*
* @param path — the standard-schema issue path.
* @returns the keys joined with `.`.
*/
static formatPath(path: StandardSchemaV1.Issue['path']) {
return ValidationError.normalizePath(path).map(String).join('.')
}
}
Object.defineProperty(ValidationError.prototype, kValidationError, {
@@ -239,15 +269,6 @@ export class Fiber {
this.uid = parent.registry.counter
this.ctx = this.context = parent.extend({ fiber: this })
const injectEntries = Object.entries(this.inject)
if (injectEntries.length) {
this.ctx[Context.intercept] = Object.create(parent[Context.intercept])
for (const [name, config] of injectEntries) {
if (isNullable(config)) continue
this.ctx[Context.intercept][name] = config
}
}
this._runner = {
epoch: INACTIVE,
getOuterStack,
@@ -290,15 +311,16 @@ export class Fiber {
return FiberState.UNLOADING
})
}
// `this.inertia` itself should never reject — both `_reload` and
// `_unload` swallow their own work errors via `ctx.logger.error`.
// If it *does* reject, the only remaining cause is the logger
// itself failing, which we can't recover from in this exact spot
// (calling the logger again is what just failed). Let the
// rejection propagate; process-level crash is the honest outcome.
// `inertia` never rejects: `_reload` and `_unload` both log their
// own work errors. A rejection here would mean the logger itself
// failed, so let it propagate.
while (this.inertia) {
await this.inertia
}
// `_setEpoch()` above returns early for a fiber that was not ACTIVE,
// so the cached state is not refreshed. Re-derive it now that
// `uid` is null; the empty callback falls through to `_getState()`.
this._updateState(() => {})
}
}, 'ctx.plugin()')
+7 -20
View File
@@ -1,14 +1,9 @@
import { defineProperty, hyphenate } from '@deepseek-ai/cosmokit'
import { Context } from './context.ts'
import { Fiber } from './fiber.ts'
import { Service } from './service.ts'
import { createCallable, joinPrototype, symbols, type Tracker } from './utils.ts'
declare module './context.ts' {
interface Intercept {
logger: LoggerService.Intercept
}
}
/** Logger method name and severity category. */
export type LoggerType = 'error' | 'info' | 'warn' | 'debug'
@@ -143,7 +138,9 @@ export class Logger {
if (args.length === 1 && args[0] instanceof Error) {
if (args[0].cause) {
this[type](args[0].cause)
} else if (isAggregateError(args[0])) {
} else if (isAggregateError(args[0]) && args[0].errors.length) {
// An aggregate with no members has nothing to flatten; it is logged
// as itself, like any other error.
args[0].errors.forEach(error => this[type](error))
return
}
@@ -192,6 +189,8 @@ export interface LoggerService extends Record<LoggerType, LoggerMethod> {
* directly to log with the current fiber-derived name.
*/
export class LoggerService {
declare [symbols.metadata]: LoggerService.Intercept
bufferSize = 1000
buffer: Message[] = []
ctx!: Context
@@ -241,21 +240,9 @@ export class LoggerService {
}, 'ctx.logger.exporter()')
}
private _resolveConfig(): LoggerService.Intercept {
let intercept = this.ctx[symbols.intercept]
const configs: LoggerService.Intercept[] = []
while ('logger' in intercept) {
if (Object.hasOwn(intercept, 'logger')) {
configs.unshift(intercept['logger'])
}
intercept = Object.getPrototypeOf(intercept)
}
return Object.assign({}, ...configs)
}
[symbols.invoke](name?: string): Logger {
const config = this._resolveConfig()
const caller = (this as any)[symbols.caller] as Context | undefined
const config: LoggerService.Intercept = Service.prototype[Service.resolveIntercept].call(this)
const fiber = (caller ?? this.ctx).fiber
name ??= config.name
name ??= hyphenate(fiber.name)
+39 -17
View File
@@ -132,6 +132,39 @@ export interface Impl {
isolate: symbol
}
/**
* Resolve an access to service `name` from the def site `ctx` by walking up its fibers.
*
* - `{ impl }`: a fiber provides the impl itself in the same isolation.
* - `{ fiber, impl }`: the impl comes from the committed view of `fiber`.
* - `{ fiber }`: `fiber` declares the service but is inactive.
* - `undefined`: no fiber declares the service, or the walk reaches a context that isolates `name` again.
*
* @param ctx — the def-site context of the access.
* @param name — the service name being accessed.
* @returns the fiber whose `inject` admits the access and the impl the access reaches, or `undefined`.
*/
export function locate(ctx: Context, name: string): { fiber?: Fiber; impl?: Impl } | undefined {
const key = ctx[symbols.isolate][name]
let table = ctx[symbols.isolate]
let fiber = ctx.fiber
while (true) {
let impl: Impl | undefined
for (const provision of fiber.provisions) {
if (provision.name === name && provision.ctx[symbols.isolate][name] === key) impl = provision
}
if (impl) return { impl }
while (table !== fiber.ctx[symbols.isolate]) {
if (!table || Object.hasOwn(table, name)) return
table = Object.getPrototypeOf(table)
}
impl = fiber.committed?.[name]
if (impl || name in fiber.inject) return { fiber, impl }
if (!fiber.runtime) return
fiber = fiber.parent.fiber
}
}
/**
* Reflection and service-resolution layer installed as `ctx.reflect`.
*
@@ -161,22 +194,11 @@ export class ReflectService {
const defSite = (ctx[symbols.shadow] as Context | undefined) ?? ctx
if (!defSite.fiber.runtime) return ctx.reflect.get(prop, false)
return ctx.events.waterfall('internal/get', ctx, prop, error, () => {
const key = defSite[symbols.isolate][prop]
let fiber = defSite.fiber
while (true) {
let impl = fiber.committed?.[prop]
for (const provision of fiber.provisions) {
if (provision.name === prop && provision.ctx[symbols.isolate][prop] === key) impl = provision
}
if (impl) return getTraceable(ctx, impl.value)
if (prop in fiber.inject) {
error.message = `cannot get required service "${prop}" in inactive context`
throw error
}
if (!fiber.runtime) throw error
if (fiber.parent[symbols.isolate][prop] !== key) throw error
fiber = fiber.parent.fiber
}
const result = locate(defSite, prop)
if (!result) throw error
if (result.impl) return getTraceable(ctx, result.impl.value)
error.message = `cannot get required service "${prop}" in inactive context`
throw error
})
} catch (e: any) {
throw e === error ? enhanceError(e) : e
@@ -297,7 +319,7 @@ export class ReflectService {
}
this.props[name] = { type: 'service' }
this.ctx.root[symbols.isolate][name] ??= Symbol(name)
this.ctx[symbols.root][symbols.isolate][name] ??= Symbol(name)
const key = this.ctx[symbols.isolate][name]
const impl: Impl = { uid: ++this._implCounter, name, value, ctx: this.ctx, check, isolate: key, dependents: new Set() }
if (this.store[key]) {
+4 -4
View File
@@ -20,7 +20,7 @@ export type Inject<M = Dict> = (keyof M)[] | { [K in keyof M]?: M[K] }
/** Context keys that correspond to services with typed intercept config. */
export type InjectKey = keyof {
[K in keyof Context & string as Context[K] extends { [symbols.config]: any } ? K : never]: any
[K in keyof Context & string as Context[K] extends { [symbols.metadata]: any } ? K : never]: any
}
/**
@@ -31,10 +31,10 @@ export type InjectKey = keyof {
*/
/**
* @param name — the required service name.
* @param config — optional intercept config applied for that service.
* @param config — optional intercept metadata injected for that service.
* @returns the class or method decorator.
*/
export function Inject<K extends InjectKey>(name: K, config?: Context[K] extends { [symbols.config]: infer T } ? T : never) {
export function Inject<K extends InjectKey>(name: K, config?: Context[K] extends { [symbols.metadata]: infer T } ? T : never) {
return function (value: any, decorator: ClassDecoratorContext<any> | ClassMethodDecoratorContext<any>) {
if (decorator.kind === 'class') {
if (!Object.hasOwn(value, 'inject')) {
@@ -43,7 +43,7 @@ export function Inject<K extends InjectKey>(name: K, config?: Context[K] extends
}
value.inject[name] = config
} else if (decorator.kind === 'method') {
const inject = (value[symbols.metadata] ??= {}).inject ??= Object.create(null)
const inject = (value[symbols.decorator] ??= {}).inject ??= Object.create(null)
inject[name] = config
decorator.addInitializer(function () {
const property = this[symbols.tracker]?.property
+33 -23
View File
@@ -1,5 +1,6 @@
import { defineProperty } from '@deepseek-ai/cosmokit'
import { defineProperty, isNullable } from '@deepseek-ai/cosmokit'
import { Context } from './context.ts'
import { locate } from './reflect.ts'
import { createCallable, joinPrototype, symbols, type Tracker } from './utils.ts'
/**
@@ -13,18 +14,20 @@ export abstract class Service<out T = never> {
static readonly init: unique symbol = symbols.init
/** Symbol key of the availability predicate passed to `ctx.provide()`. */
static readonly check: unique symbol = symbols.check
/** Symbol key of the phantom intercept-config type parameter. */
static readonly config: unique symbol = symbols.config
/** Symbol key of the call body making a service callable (e.g. `ctx.logger()`). */
static readonly invoke: unique symbol = symbols.invoke
/** Symbol key of the phantom intercept-metadata type parameter. */
static readonly metadata: unique symbol = symbols.metadata
/** Symbol key of the helper deriving an extended service instance. */
static readonly extend: unique symbol = symbols.extend
/** Symbol key of the tracker metadata used for context tracing. */
static readonly tracker: unique symbol = symbols.tracker
/** Symbol key of the intercept-config resolution helper below. */
static readonly resolveConfig: unique symbol = symbols.resolveConfig
/** Symbol key of the intercept-metadata merge hook below. */
static readonly mergeIntercept: unique symbol = symbols.mergeIntercept
/** Symbol key of the intercept-metadata resolution helper below. */
static readonly resolveIntercept: unique symbol = symbols.resolveIntercept
declare [symbols.config]: T
declare [symbols.metadata]: T
/** The service name this instance is registered under. */
public name!: string
@@ -73,32 +76,39 @@ export abstract class Service<out T = never> {
}
/**
* Merge intercept config from ancestors with optional base and head values.
* Merge intercept metadata values, lowest precedence first.
*
* Entries added closer to the root apply first; `base` is prepended and
* `head` appended. Uses `Config.merge` when the service declares one,
* otherwise a shallow `Object.assign`.
* Override to customize merging; the default is a shallow `Object.assign`.
*
* @param base — lowest-precedence config merged before all intercepts.
* @param head — highest-precedence config merged after all intercepts.
* @returns the merged config.
* @param values — the metadata values in increasing precedence.
* @returns the merged metadata.
*/
[symbols.resolveConfig](base?: T, head?: T): T {
[symbols.mergeIntercept](...values: T[]): T {
return Object.assign({}, ...values)
}
/**
* Resolve the intercept metadata visible to the current caller.
*
* The metadata injected by the fiber that admits the access applies first,
* then intercepts added by ancestor contexts, closest to the root first.
* The values are combined with `[Service.mergeIntercept]`.
*
* @returns the merged metadata.
*/
[symbols.resolveIntercept](): T {
const values: T[] = []
let intercept = this.ctx[Context.intercept]
const configs: any[] = []
while (this.name in intercept) {
if (Object.hasOwn(intercept, this.name)) {
configs.unshift(intercept[this.name])
values.unshift(intercept[this.name])
}
intercept = Object.getPrototypeOf(intercept)
}
if (base) configs.unshift(base)
if (head) configs.push(head)
if (this['Config']?.merge) {
return this['Config'].merge(...configs)
} else {
return Object.assign({}, ...configs)
}
const value = locate((this as any)[symbols.caller] ?? this.ctx, this.name)?.fiber?.inject[this.name]
if (!isNullable(value)) values.unshift(value)
const merge = this[symbols.mergeIntercept] ?? Service.prototype[symbols.mergeIntercept]
return merge.apply(this, values)
}
static [Symbol.hasInstance](instance: any) {
+7 -4
View File
@@ -1,5 +1,6 @@
import { defineProperty } from '@deepseek-ai/cosmokit'
import type { Context, Service } from './index.ts'
import type { Context } from './context.ts'
import type { Service } from './service.ts'
/** Ordered collection of disposable values with O(1) deletion by value. */
export class DisposableList<T extends WeakKey> {
@@ -53,11 +54,12 @@ export const symbols = {
caller: Symbol.for('cordis.caller'),
receiver: Symbol.for('cordis.receiver'),
original: Symbol.for('cordis.original'),
metadata: Symbol.for('cordis.metadata'),
decorator: Symbol.for('cordis.decorator'),
initHooks: Symbol.for('cordis.initHooks'),
checkProto: Symbol.for('cordis.checkProto'),
// context symbols
root: Symbol.for('cordis.root') as typeof Context.root,
effect: Symbol.for('cordis.effect') as typeof Context.effect,
filter: Symbol.for('cordis.filter') as typeof Context.filter,
isolate: Symbol.for('cordis.isolate') as typeof Context.isolate,
@@ -66,11 +68,12 @@ export const symbols = {
// service symbols
init: Symbol.for('cordis.init') as typeof Service.init,
check: Symbol.for('cordis.check') as typeof Service.check,
config: Symbol.for('cordis.config') as typeof Service.config,
invoke: Symbol.for('cordis.invoke') as typeof Service.invoke,
metadata: Symbol.for('cordis.metadata') as typeof Service.metadata,
extend: Symbol.for('cordis.extend') as typeof Service.extend,
tracker: Symbol.for('cordis.tracker') as typeof Service.tracker,
resolveConfig: Symbol.for('cordis.resolveConfig') as typeof Service.resolveConfig,
mergeIntercept: Symbol.for('cordis.mergeIntercept') as typeof Service.mergeIntercept,
resolveIntercept: Symbol.for('cordis.resolveIntercept') as typeof Service.resolveIntercept,
}
const GeneratorFunction = function* () {}.constructor
+1 -1
View File
@@ -133,7 +133,7 @@ export class Include extends EntryTree {
}
private warn = (format: string, ...args: any[]) => {
this.ctx.root.logger?.('loader').warn(format, ...args)
this.ctx[Context.root].logger?.('loader').warn(format, ...args)
}
async* [Service.init]() {
+3 -3
View File
@@ -75,7 +75,7 @@ export namespace Loader {
* Subclasses provide persistence by implementing `commit(change)` on `EntryTree`.
*/
export class Loader extends EntryTree {
declare [Service.config]: Loader.Intercept
declare [Service.metadata]: Loader.Intercept
public envData = process.env.CORDIS_SHARED
? JSON.parse(process.env.CORDIS_SHARED)
@@ -181,14 +181,14 @@ export class Loader extends EntryTree {
}
[Service.check]() {
const config: Loader.Intercept = Service.prototype[Service.resolveConfig].call(this)
const config: Loader.Intercept = Service.prototype[Service.resolveIntercept].call(this)
if (config.await && this.getTasks().length) return false
return true
}
showLog(entry: Entry, type: string) {
if (entry.options.group || !entry.parent.tree.enableLogs) return
this.ctx.root.logger?.('loader').info('%s plugin %C', type, entry.options.name)
this.ctx[Context.root].logger?.('loader').info('%s plugin %C', type, entry.options.name)
}
/** Return the loader entry id that owns `fiber`, if any. */