meowjsx 0.1.1-alpha.0 → 0.1.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/JSON.md CHANGED
@@ -1,6 +1,6 @@
1
- # JSON 描述入口
1
+ # JSON description entry
2
2
 
3
- `meowjsx/json` 把有限 JSON 描述构造成普通 MeowJSX VNode,使用原 runtime、Context、Signal、组件和 renderer 生命周期;core 根入口不反向导入 JSON 或 DOM。
3
+ `meowjsx/json` builds ordinary MeowJSX VNodes from finite JSON descriptions, using the existing runtime, Context, Signal, components and renderer lifecycle; the core root entry does not import JSON or the DOM back.
4
4
 
5
5
  ```ts
6
6
  import { createJsonView, defineJsonComponent, jsonSchema, parseJsonView } from "meowjsx/json";
@@ -23,12 +23,12 @@ const description = parseJsonView(
23
23
  const child = createJsonView(description, { catalog, bindings: new Map([["label", text]]) });
24
24
  ```
25
25
 
26
- 节点支持字符串、有限数字、布尔、null、节点数组,以及 `{component, props?, children?}`。component 必须是宿主 catalog 的准确名称;不提供任意 HTML 标签、raw HTML、ref、代码、动态 import、表达式或对象路径。描述中的绑定为独占形状 `{$binding:"准确名称"}`,action 为 `{$action:"准确名称"}`。名称只作 Map 精确查询,不解析点号或路径,也不授予外部权限。
26
+ Nodes support strings, finite numbers, booleans, null, node arrays, and `{component, props?, children?}`. `component` must be an exact name in the host catalog; arbitrary HTML tags, raw HTML, refs, code, dynamic imports, expressions or object paths are not provided. A binding in a description has the exclusive shape `{$binding:"exact name"}`, and an action has `{$action:"exact name"}`. Names are looked up only as exact Map keys; dots and paths are not parsed, and no external permissions are granted.
27
27
 
28
- `parseJsonView` 仅校验、复制和冻结数据,不执行组件、action、事件投影、Signal getter 或 runtime hook。`createJsonView` 再按给定 catalog 校验,绑定宿主的只读 Signal 和真实函数,构造 VNode;挂载和解绑仍由原 renderer 管理。action 的参数由 metadata 中的有限 schema 校验;可由宿主在 metadata 提供可信 `mapArgs` 把原生事件投影成明确参数,JSON 不能提供执行代码。callback 的原返回值保留。
28
+ `parseJsonView` only validates, copies and freezes data; it does not execute components, actions, event projections, Signal getters or runtime hooks. `createJsonView` then validates against the given catalog, binds the host's read-only Signals and real functions, and constructs VNodes; mounting and unmounting are still managed by the original renderer. Action arguments are validated by the finite schema in metadata; the host may provide a trusted `mapArgs` in metadata to project native events into explicit arguments, while JSON cannot provide executable code. The callback's original return value is preserved.
29
29
 
30
- `jsonSchema` 支持 string/number/boolean/enum/array/object/optional/data/union,描述与校验共用这些定义。object 字段严格,union 必须命中一个完整分支;`data()` 仅承诺纯 JsonValue,不会凭泛型声称已经校验复杂业务类型。数据内部的 constructor、$binding 或 $action 普通字段仍是数据,不递归解释为控制。某个 prop 的最外层若恰是独占引用标记,则保留给引用;需要这个字面对象时由 host binding 提供,而不是额外引入转义 DSL。
30
+ `jsonSchema` supports string/number/boolean/enum/array/object/optional/data/union, and description and validation share these definitions. Object fields are strict, and a union must match one complete branch; `data()` only promises a pure JsonValue and does not claim through generics that a complex business type has been validated. Ordinary fields named constructor, $binding or $action inside data are still data and are not recursively interpreted as controls. If a prop's outermost value happens to be an exclusive reference marker, it is kept as a reference; when that literal object is needed, the host binding provides it rather than an additional escape DSL.
31
31
 
32
- `defineJsonComponent` 将有限 metadata 与原组件 Props 静态关联,排除开放 Props 的任意索引字段;它不自动反射 TS 类型,也不宣称已有全组件 schema。具体组件库必须明确支持集。`describeJsonCatalog` 与 `describeJsonSchema` 从同一 metadata 输出有限描述,不另维护 schema。函数、File、类实例、accessor、循环引用、稀疏数组和非有限数字不是 JSON 数据;宿主仍负责网络、权限、持久化及真正数据来源。
32
+ `defineJsonComponent` statically associates finite metadata with the original component's Props and excludes arbitrary index fields of open Props; it does not reflect TS types automatically and does not claim that a whole-component schema exists. A concrete component library must state its supported set explicitly. `describeJsonCatalog` and `describeJsonSchema` output the finite description from the same metadata and do not maintain a separate schema. Functions, File, class instances, accessors, circular references, sparse arrays and non-finite numbers are not JSON data; the host is still responsible for network, permissions, persistence and the real data source.
33
33
 
34
- value metadata 可提供按同 schema 校验、复制冻结的字面 `default`,仅在描述缺少该属性时填入;false、0、空串不会被当作缺失。它不执行 action、绑定或回调,也不能改变该属性显式值仍须符合 schema 的要求。
34
+ Value metadata may provide a literal `default` that is validated against the same schema and copied and frozen, filled in only when the description omits that property; false, 0 and the empty string are not treated as missing. It does not execute actions, bindings or callbacks, and does not change the requirement that an explicit value for that property still matches the schema.
package/README.md CHANGED
@@ -2,64 +2,52 @@
2
2
 
3
3
  ## Render-tree context
4
4
 
5
- `createContext(defaultValue)` 返回类型化的 Context 和 `Provider` 组件。
6
- `<Context.Provider value={value}>…</Context.Provider>` 不创建宿主节点;后代组件在同步
7
- render 中通过 `useContext(Context)` 读取最近的祖先值,没有 Provider 时得到默认值。
8
- 显式提供 `undefined` 仍是一个值,不会退回默认值。兄弟、独立根节点和 runtime 不共享环境。
9
-
10
- 环境跟随渲染树遍历,而非 VNode 创建时的位置。预先创建的 VNode、数组、宿主包装层和
11
- Signal 后续替换的子树使用当前区域捕获的环境;Promise 与 AsyncIterable 的延迟挂载同样保留它。
12
- 同步 HTML 输出采用相同祖先规则,但仍不支持 Promise / AsyncIterable 内容,遇到时抛错。
13
-
14
- `useContext` 只在组件同步执行期间读取环境。事件处理和 `await` 后需要使用 render 中预先
15
- 捕获的值,不把它当异步局部存储。Provider 不添加整树重渲染或依赖追踪;需要动态共享值时,
16
- 可将 Signal 对象作为 value,消费者使用原有 Signal 绑定。更换 Provider 的普通 value 不会
17
- 自动重跑已挂载后代。Context 的内部 scope 由 renderer 传递,用户不应修改它。
18
-
19
- `RuntimePlugin.resolveComponent({ component, props, runtime })` 可在组件调用前选择替代函数。
20
- 按 `pre`、普通、`post` 和各组注册顺序调用;首个非 `undefined` 结果胜出,返回原函数也停止,
21
- 结果不再递归解析。选择发生在 lifecycle scope 创建前,所选组件使用自己的 contract、parts
22
- 和清理逻辑,原组件不执行。`props` 是只读类型视图,不会复制或冻结对象。
23
-
24
- 此 hook 属于执行 runtime:预先创建的 VNode、Signal/Promise 后续挂载以及同步 HTML 均适用。
25
- `runtime.use()` 返回的 cleanup 卸载规则,不改写已挂载实例;其他 runtime 不受影响。
26
- 它不拦截模块副作用或直接函数调用,也不改变 `create` / `render` hook 的含义。
27
-
28
- ## 开发 metadata 与实例观察
29
-
30
- 组件函数可赋值 `metadata?: ComponentMetadata`。`ComponentMetadata` 是开放的类型扩展接口,
31
- 开发工具通过 declaration merging 注册自己的命名空间;core 不解释或读取其中的工具字段。
32
- `Component<Props>` 和 `defineComponent` 返回值均保留这个约束,普通函数可用
33
- `satisfies ComponentMetadata` 检查赋值。metadata 不属于 props 或组件运行选项。
34
-
35
- `runtime.createRenderer(strategy, { observer })` 可启用目标中立的实例观察:
36
- `onComponent(instance)` 报告创建,`onUnmount(instance)` 报告卸载;可选的
37
- `onNode(instance, node, mounted)` 报告节点关联变化。实例包含本 renderer 内的 `id`、
38
- `parent`、原函数 `originalComponent`、实际执行函数 `component`,以及实时只读的 `nodes` 集合。
39
- 集合含该实例及后代的宿主和文本输出,排除内部 marker;Signal、Promise、AsyncIterable 更新后仍保持当前关联。
40
- 数组和宿主标签不增加组件层级,直接函数调用不会产生组件实例。
41
-
42
- 内置 Fragment 和 Context Provider 按实际执行函数身份报告 `semantic` 为 `fragment` 或
43
- `context-provider`,不按名称猜测。替换组件使用所选函数的语义身份和 metadata。
44
- 观察不增加宿主包装层;未启用时不创建实例或节点索引。回调同步执行,抛错按挂载或清理失败处理,
45
- 工具应在自身边界处理诊断。实例卸载后从工具投影中移除,`id` 不用于跨次运行定位。
46
-
47
- 可选 `onFlush(changed)` 在微任务中合并实例失效通知,覆盖组件加卸载、节点关联及已挂载
48
- 宿主 Signal 属性更新;异常与回滚也通知当前事实可能改变的实例。`changed` 使用真实实例
49
- identity,包含本轮已卸载实例,不是成功提交记录。集合在调用前清空,回调引起的新变化进入
50
- 下一轮,不递归投递。它不表示 DOM layout、paint、全部异步工作或应用 ready;没有此回调时
51
- 不建立额外 dirty 集合或微任务。此回调抛错走 renderer 的 `onError(error, "async")`,不回滚
52
- 已发生的渲染;未提供错误出口则异步抛出。
53
-
54
- 工具可设置 `observer.roots`,按 child 对象引用限定观察子树;省略时观察整棵渲染树,
55
- 空数组时不观察实例。进入每个根后,首层组件的 `parent` 为 `null`,外层容器仍正常渲染、
56
- 传递 context 和执行 lifecycle,但不进入观察投影。根可为 VNode、Signal、Promise 或
57
- AsyncIterable,延迟输出继续使用该范围。调用方若把内容数组展开交给容器,应传入其中的
58
- 实际 child 引用。此范围不增加组件调用,不影响 runtime hooks 或组件替换。
59
-
60
- 多消费者使用 `createComponentObservation<TNode>({ roots?, onError? })`,而不是各自复制
61
- 实例 Map。它返回 `observer`、`read(root?)`、`subscribe(listener, { root? })` 和 `dispose()`。
62
- 将 `observer` 接入 renderer 后,先订阅再读取即可取得当前状态和后续失效通知:
5
+ `createContext(defaultValue)` returns a typed Context and a `Provider` component.
6
+ `<Context.Provider value={value}>…</Context.Provider>` does not create a host node; descendant components read the nearest
7
+ ancestor value with `useContext(Context)` during synchronous render, and get the default when there is no Provider.
8
+ An explicitly provided `undefined` is still a value and does not fall back to the default. Siblings, independent root nodes and runtimes do not share environment.
9
+
10
+ Environment follows render-tree traversal, not the location where the VNode was created. Pre-created VNodes, arrays, host wrapper layers and subtrees replaced later by a Signal use the environment captured in the current area; deferred mounting of Promises and AsyncIterables preserves it as well.
11
+ Synchronous HTML output follows the same ancestor rule, but still does not support Promise / AsyncIterable content and throws when it encounters them.
12
+
13
+ `useContext` reads environment only during the component's synchronous execution. Event handlers and code after `await` must use the value captured in render beforehand; do not treat it as asynchronous local storage. Provider does not add whole-tree re-render or dependency tracking; to share a dynamic value, pass a Signal object as the value and let consumers use the existing Signal binding. Replacing a Provider's ordinary value does not automatically re-run already mounted descendants. Context's internal scope is passed by the renderer and users must not modify it.
14
+
15
+ `RuntimePlugin.resolveComponent({ component, props, runtime })` can select a replacement function before the component is called.
16
+ It is called in the order `pre`, normal, `post`, and within each group's registration order; the first non-`undefined` result wins, and returning the original function also stops resolution; the result is not resolved recursively. Selection happens before the lifecycle scope is created, and the selected component uses its own contract, parts and cleanup logic while the original component does not execute. `props` is a read-only typed view and does not copy or freeze the object.
17
+
18
+ This hook belongs to the execution runtime: pre-created VNodes, Signal/Promise deferred mounts and synchronous HTML all apply. The cleanup returned by `runtime.use()` unmounts rules and does not rewrite already mounted instances; other runtimes are unaffected.
19
+ It does not intercept module side effects or direct function calls, and does not change the meaning of the `create` / `render` hooks.
20
+
21
+ ## Development metadata and instance observation
22
+
23
+ Component functions may carry `metadata?: ComponentMetadata`. `ComponentMetadata` is an open type-extension interface; development tools register their own namespaces through declaration merging, and core does not interpret or read their tool fields.
24
+ Both `Component<Props>` and the value returned by `defineComponent` preserve this constraint, and ordinary functions can use
25
+ `satisfies ComponentMetadata` to check assignment. Metadata is not part of props or component runtime options.
26
+
27
+ `runtime.createRenderer(strategy, { observer })` enables target-neutral instance observation:
28
+ `onComponent(instance)` reports creation, `onUnmount(instance)` reports unmounting; the optional
29
+ `onNode(instance, node, mounted)` reports node-association changes. An instance includes this renderer's `id`,
30
+ `parent`, the original function `originalComponent`, the actually executed function `component`, and a live read-only `nodes` collection.
31
+ The collection includes host and text output of that instance and its descendants, excluding internal markers; Signal, Promise and AsyncIterable updates keep the current associations.
32
+ Arrays and host tags do not add component levels, and direct function calls do not create component instances.
33
+
34
+ Built-in Fragment and Context Provider report `semantic` as `fragment` or
35
+ `context-provider` according to their actual executed function identity, not by name guessing. Replaced components use the selected function's semantic identity and metadata.
36
+ Observation adds no host wrapper layers; when disabled, no instance or node index is created. Callbacks run synchronously, and a throw is handled as a mount or cleanup failure; tools should handle diagnostics at their own boundary. Instances are removed from the tool projection after unmount, and `id` is not used to locate instances across runs.
37
+
38
+ The optional `onFlush(changed)` merges instance-invalidation notices in a microtask, covering component mount/unmount, node associations and updates to mounted host Signal props; exceptions and rollbacks also notify instances whose current facts may have changed. `changed` uses real instance
39
+ identity and includes instances unloaded in this round; it is not a successful-commit record. The set is cleared before the callback runs, and new changes caused by the callback go into the
40
+ next round without recursive delivery. It does not mean DOM layout, paint, all asynchronous work or application readiness; without this callback,
41
+ no additional dirty set or microtask is established. A throw from this callback goes through the renderer's `onError(error, "async")` and does not roll back
42
+ rendering that already happened; if no error outlet is provided, it is thrown asynchronously.
43
+
44
+ Tools can set `observer.roots` to limit the observed subtree by child object reference; when omitted the whole render tree is observed, and an empty array observes no instances. After entering each root, the first-level component's `parent` is `null`; outer containers still render normally,
45
+ pass context and run lifecycle, but do not enter the observation projection. A root may be a VNode, Signal, Promise or
46
+ AsyncIterable, and deferred output continues to use that scope. If the caller expands a content array into a container, it should pass the actual child references inside it. This scope adds no component calls and does not affect runtime hooks or component replacement.
47
+
48
+ Multiple consumers use `createComponentObservation<TNode>({ roots?, onError? })` instead of each copying
49
+ its own instance Map. It returns `observer`, `read(root?)`, `subscribe(listener, { root? })` and `dispose()`.
50
+ After wiring `observer` into the renderer, subscribe first and then read to obtain the current state and subsequent invalidation notices:
63
51
 
64
52
  ```ts
65
53
  const observation = createComponentObservation<HostNode>({ onError: reportObserverError });
@@ -68,70 +56,67 @@ const unsubscribe = observation.subscribe(() => inspect(observation.read()));
68
56
  const current = observation.read();
69
57
  ```
70
58
 
71
- `read` 返回当前实例成员数组的副本,实例 `nodes` 仍是 renderer 所有的实时集合;它不是
72
- 不可变历史快照。`root` 是真实实例对象,包含其自身及后代;已卸载根读取为空。根内改动与
73
- 祖先改动均可使订阅失效,通知允许保守,不承诺精确的布局影响集。订阅没有隐式首次回放;
74
- 投递使用订阅名单快照,调用前再次检查有效性,因此本轮取消的订阅不再执行,新加入的
75
- 订阅从后续通知开始。一个消费者抛错不阻断其他消费者,错误交给观察中心的 `onError`;
76
- 缺少该出口或出口再次抛错时异步报错,不静默吞错。
59
+ `read` returns a copy of the current instance-member array; the instance `nodes` is still the renderer-owned live collection; it is not
60
+ an immutable historical snapshot. `root` is the real instance object and includes itself and its descendants; reading an unmounted root is empty. Changes inside the root and ancestor changes can both invalidate subscriptions; notification may be conservative and does not promise a precise layout-impact set. Subscriptions have no implicit first replay;
61
+ delivery uses a snapshot of the subscriber list and re-checks validity before calling, so subscriptions cancelled in this round no longer run, and newly added
62
+ subscriptions begin with later notifications. A throwing consumer does not block other consumers; the error goes to the observation center's `onError`;
63
+ if that outlet is missing or throws again, the error is reported asynchronously rather than silently swallowed.
77
64
 
78
- `dispose` 只停止观察并清理投影,不卸载视图。之后 `read` 为空、`subscribe` 拒绝;已有
79
- renderer 的迟到通知被忽略。通常一个观察中心接一个 renderer;实现按实例 identity 存储,
80
- 不会因不同 renderer 的数字 id 相同而覆盖。`roots` 可使用 getter,但范围仍在创建 renderer
81
- 时读取并固定,适用于工具在创建前设置真实 child;不是运行时动态切换入口。纯宿主或文本根
82
- 没有组件实例,外部 DOM/样式、字体加载和浏览器尺寸变化也不属于该观察合同。
65
+ `dispose` only stops observation and clears the projection; it does not unmount the view. Afterwards `read` is empty and `subscribe` rejects; late notifications
66
+ from an existing renderer are ignored. Usually one observation center is attached to one renderer; the implementation stores by instance identity and does not overwrite because different renderers have the same numeric id. `roots` may use a getter, but the scope is read and fixed when the renderer is created, suitable for tools that set the real child before creation; it is not a runtime dynamic-switch entry. Purely host or text roots
67
+ have no component instances, and external DOM/styles, font loading and browser size changes also do not belong to this observation contract.
83
68
 
84
- MeowJSX 的 core:JSX/VNode 工厂、Signal/batch/effect、组件与 part 契约、shadow/plugin/theme
85
- 契约、lifecycle 与 context,以及目标中立的 renderer seam(`RenderStrategy<TNode>` /
86
- `createRenderer()`)。core 不知道目标平台。
69
+ MeowJSX core: the JSX/VNode factory, Signal/batch/effect, component and part contracts, shadow/plugin/theme
70
+ contracts, lifecycle and context, and the target-neutral renderer seam (`RenderStrategy<TNode>` /
71
+ `createRenderer()`). Core does not know the target platform.
87
72
 
88
73
  ```text
89
- JSX 源码 / 组件逻辑
74
+ JSX source / component logic
90
75
  │
91
- meowjsx(本包:core + JSX contract)
92
- └─→ meowjsx/web 同包的 DOM / event / HTML / mount 模块
76
+ meowjsx (this package: core + JSX contract)
77
+ └─→ meowjsx/web the same package's DOM / event / HTML / mount modules
93
78
  ```
94
79
 
95
- ## 导出
80
+ ## Exports
96
81
 
97
- - `.`、`./runtime`:`h`、`Fragment`、`raw`、`part`、`signal`/`batch`/`mapSignal`、
98
- `createRuntime`、`defaultRuntime`、`defineComponent`、`defineShadow`、
99
- `createThemePlugin`,以及 VNode/Signal/契约类型。
100
- - `./renderer`:`RenderStrategy<TNode>`、`createRenderer()`、`Renderer`/`Rendered`/
101
- `RendererOptions`、`ComponentObserver`/`ObservedComponent` 等 target seam 类型。`createRenderer()` 注入 component lifecycle、
102
- render hook、override 和 `key`/`componentPart` 身份,target 只实现节点与属性落地。
103
- - `./jsx-runtime`:`jsx`/`jsxs`/`jsxDEV`/`Fragment`。
104
- - `./jsx-dev-runtime`:development 自动 JSX 所需的 `jsxDEV`/`Fragment`,重用同一实现。
105
- - `./web`:DOM mount、静态 HTML、Web shadow、实例观察来源和骨架视觉控制。
106
- - `./json`:有限描述、host binding/action 引用、单源 metadata 校验与 catalog 描述,见 [JSON 入口](JSON.md)。
107
- - `Runtime.targetHooks`:target 自己拥有输出路径时(Web 的静态 HTML)复用 runtime 的
108
- 组件调用、render hook 与 override 语义,不必在 target 里复制一套。
82
+ - `.`, `./runtime`: `h`, `Fragment`, `raw`, `part`, `signal`/`batch`/`mapSignal`/`derived`,
83
+ `createRuntime`, `defaultRuntime`, `defineComponent`, `defineShadow`,
84
+ `createThemePlugin`, plus VNode/Signal/contract types.
85
+ - `./renderer`: `RenderStrategy<TNode>`, `createRenderer()`, `Renderer`/`Rendered`/
86
+ `RendererOptions`, `ComponentObserver`/`ObservedComponent` and other target-seam types. `createRenderer()` injects component lifecycle,
87
+ render hooks, overrides and `key`/`componentPart` identity; the target only implements node and attribute placement.
88
+ - `./jsx-runtime`: `jsx`/`jsxs`/`jsxDEV`/`Fragment`.
89
+ - `./jsx-dev-runtime`: the `jsxDEV`/`Fragment` needed by development automatic JSX, reusing the same implementation.
90
+ - `./web`: DOM mount, static HTML, Web shadow, instance-observation sources and skeleton visual controls.
91
+ - `./json`: finite descriptions, host binding/action references, single-source metadata validation and catalog descriptions; see [JSON entry](JSON.md).
92
+ - `Runtime.targetHooks`: when the target owns the output path (Web's static HTML), reuse the runtime's
93
+ component calls, render hooks and override semantics instead of copying a set into the target.
109
94
 
110
- core 根没有 `render`/`renderToHtml`:`render(node, Element)` 与 HTML 序列化从
111
- `meowjsx/web` 导入。根不回导 Web;两者使用同一份 core 模块,多个显式 Runtime 仍可独立创建。
95
+ The core root has no `render`/`renderToHtml`: `render(node, Element)` and HTML serialization are imported from
96
+ `meowjsx/web`. The root does not import Web back; both use the same core module, and multiple explicit Runtimes can still be created independently.
112
97
 
113
- ## 不变量:core 不含平台
98
+ ## Invariant: core contains no platform
114
99
 
115
- core 源码(含类型)不出现 `document`、`window`、DOM `Element`/`HTMLElement`、
116
- 浏览器 `Event`、CSS API 或终端 API。`packages/meowjsx/tsconfig.core.json` 在不含
117
- `dom` lib、`types: []` 的配置下检查整个 core:
100
+ The core source (including types) does not contain `document`, `window`, DOM `Element`/`HTMLElement`,
101
+ browser `Event`, CSS APIs or terminal APIs. `packages/meowjsx/tsconfig.core.json` checks the whole core under a configuration without the
102
+ `dom` lib and with `types: []`:
118
103
 
119
104
  ```sh
120
105
  bun node_modules/typescript/bin/tsc -p packages/meowjsx/tsconfig.core.json
121
106
  ```
122
107
 
123
- 上面命令从仓库根运行,只检查无 DOM 的 core 分组。包内 `bun run typecheck` 依次运行 core、renderer、Web 三个配置,最后的 Web 分组明确包含 DOM;它不等价于仅 core 的无 DOM 检查。`tsconfig.renderer.json` 独立检查目标中立 renderer seam,行为用例使用 fake target。
108
+ The command above runs from the repository root and only checks the DOM-free core group. The package's `bun run typecheck` runs core, renderer and Web configurations in order; the final Web group explicitly includes the DOM and is not equivalent to the DOM-free core-only check. `tsconfig.renderer.json` independently checks the target-neutral renderer seam, and behavior cases use a fake target.
124
109
 
125
- `ShadowContext.element` 是目标提供的 host handle,core 里类型为泛型 `TNode`
126
- (默认 `unknown`);Web 模块把它收窄成真实元素。主题契约(`Theme`/`ThemeRule`/
127
- `ThemeStyle` 及其合并规则)按规划留在 core,它只承载值,不接触任何样式 API。
110
+ `ShadowContext.element` is the target-provided host handle, typed as generic `TNode` in core
111
+ (defaults to `unknown`); the Web module narrows it to a real element. Theme contracts (`Theme`/`ThemeRule`/
112
+ `ThemeStyle` and their merge rules) stay in core as planned; they carry values only and touch no style API.
128
113
 
129
- ## 验证
114
+ ## Verification
130
115
 
131
- - `bun test packages/meowjsx/tests/unit`:Signal、VNode、plugin、契约、fake target seam,以及 Web 宿主测试。
132
- - `tests/types/` 中 core 与 Web 类型用例分别检查;core 类型环境不包含 DOM。
116
+ - `bun test packages/meowjsx/tests/unit`: Signal, VNode, plugin, contracts, fake target seam and Web host tests.
117
+ - `tests/types/` checks core and Web type cases separately; the core type environment does not include the DOM.
133
118
 
134
- ## Web 模块
119
+ ## Web module
135
120
 
136
121
  ```ts
137
122
  import { createRuntime, h } from "meowjsx";
@@ -142,19 +127,23 @@ const mounted = web.render(h("p", {}, "Hello"), document.querySelector("main")!)
142
127
  mounted.unmount();
143
128
  ```
144
129
 
145
- Web 源码位于 `web/`,DOM 类型只从该入口到达。静态 `renderToHtml` 不挂载 DOM、不执行 shadow;
146
- `createSkeletonController` 调用时才需要真实文档与 CSS Custom Highlight 支持。
147
- 模块导入会创建默认 Web renderer 和观察 Context,不会安装样式或监听器。
148
- `createWebRenderer(runtime)` 尊重该 runtime 已安装的组件、主题和 plugin;显式传入观察来源时,
149
- 其生命周期由消费者管理,不建立跨 renderer 的全局观察树。
130
+ The Web source lives in `web/`, and DOM types only arrive through that entry. Static `renderToHtml` does not mount a DOM or run shadow;
131
+ `createSkeletonController` needs a real document and CSS Custom Highlight support only when called.
132
+ Importing the module creates the default Web renderer and observation Context; it does not install styles or listeners.
133
+ `createWebRenderer(runtime)` respects the components, themes and plugins already installed in that runtime; when an observation source is passed explicitly,
134
+ its lifecycle is managed by the consumer, and no global observation tree is created across renderers.
135
+
136
+ Public JS artifacts preserve module relationships: the root, runtime, automatic JSX and Web entries reference the same core.
137
+ Release builds must not copy a defaultRuntime, Context or reactive scheduler per entry.
138
+
139
+ ## Derived signals
150
140
 
151
- 公共 JS 产物保留模块关系:根、runtime、自动 JSX 与 Web 入口引用同一份 core。
152
- 发布构建不能为每个入口复制一份 defaultRuntime、Context 或响应式调度器。
141
+ `derived(read)` is a read-only signal. `read` runs again when any signal it read changes, and subscribers hear the value when `Object.is` says it changed. `read` must not write signals. One source can also use `mapSignal`. A computation is not stored by writing another signal from `effect`.
153
142
 
154
- ## 有身份的动态列表
143
+ ## Keyed dynamic lists
155
144
 
156
- `keyed(items, key, render)` 让同 key 的行保持组件、节点、Context 与观察父链;更新只改变该行的只读 item Signal,
157
- 删除释放该行生命周期,重新排列移动已有范围。普通数组与 Signal 的整体替换语义不变。
145
+ `keyed(items, key, render)` keeps rows with the same key holding the same components, nodes, Context and observation parent chain; an update only changes that row's read-only item Signal,
146
+ a deletion releases that row's lifecycle, and reordering moves the existing range. Whole-replacement semantics for plain arrays and Signals are unchanged.
158
147
 
159
148
  ```ts
160
149
  const items = signal([{ id: "one", label: "First" }]);
@@ -170,7 +159,7 @@ const rows = keyed(
170
159
  );
171
160
  ```
172
161
 
173
- `render` 构造 Child,不是额外的生命周期 hook;在组件内读取 Signal 时仍用现有 Signal 属性或 `mapSignal`。
174
- key 必须唯一,且为字符串或有限数字;重复/非法 key、新行挂载失败保留原行与值,后续合法更新仍可继续。
175
- 目标的 insert/remove 失败不提供事务回滚。普通前后追加不移动旧行;任意重排时原生焦点是否保留取决于目标移动能力。
176
- 静态 HTML 读取一次列表,不订阅或挂载 DOM。
162
+ `render` constructs a Child and is not an extra lifecycle hook; when reading Signals inside a component, keep using the existing Signal properties or `mapSignal`.
163
+ Keys must be unique and must be strings or finite numbers; duplicate/invalid keys and new-row mount failures keep the original rows and values, and later valid updates still continue.
164
+ Target insert/remove failures provide no transactional rollback. Ordinary appends at either end do not move old rows; whether native focus survives arbitrary reordering depends on the target's move capability.
165
+ Static HTML reads the list once and does not subscribe or mount a DOM.
@@ -7,3 +7,9 @@ export declare function isPromiseLike<T = unknown>(value: unknown): value is Pro
7
7
  export declare function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T>;
8
8
  export declare function unwrap<T>(value: MaybeSignal<T>): T;
9
9
  export declare function mapSignal<T, M>(source: ReadableSignal<T>, map: (value: T) => M): ReadableSignal<M>;
10
+ /**
11
+ * Read-only signal. `read` runs again when any signal it touched changes.
12
+ * Subscribers are told only when `Object.is` sees a new value. `read` must not
13
+ * write signals; a cyclic read throws.
14
+ */
15
+ export declare function derived<T>(read: () => T): ReadableSignal<T>;
@@ -156,3 +156,95 @@ export function mapSignal(source, map) {
156
156
  };
157
157
  return mapped;
158
158
  }
159
+ /**
160
+ * Read-only signal. `read` runs again when any signal it touched changes.
161
+ * Subscribers are told only when `Object.is` sees a new value. `read` must not
162
+ * write signals; a cyclic read throws.
163
+ */
164
+ export function derived(read) {
165
+ const listeners = new Set();
166
+ let cleanups = [];
167
+ let previous;
168
+ let ready = false;
169
+ let computing = false;
170
+ let queued = false;
171
+ const detach = () => {
172
+ for (const cleanup of cleanups)
173
+ cleanup();
174
+ cleanups = [];
175
+ };
176
+ const refresh = (notify) => {
177
+ if (computing) {
178
+ queued = true;
179
+ return;
180
+ }
181
+ const dependencies = new Set();
182
+ const previousEffect = activeEffect;
183
+ activeEffect = {
184
+ dependencies,
185
+ subscriptions: [],
186
+ stopped: false,
187
+ scheduled: false,
188
+ };
189
+ computing = true;
190
+ let next;
191
+ try {
192
+ next = read();
193
+ }
194
+ finally {
195
+ activeEffect = previousEffect;
196
+ computing = false;
197
+ }
198
+ detach();
199
+ if (listeners.size > 0) {
200
+ cleanups = [...dependencies].map((source) => source.subscribe(() => refresh(true)));
201
+ }
202
+ const changed = !ready || !Object.is(previous, next);
203
+ previous = next;
204
+ ready = true;
205
+ if (notify && changed) {
206
+ for (const listener of Array.from(listeners))
207
+ listener(next);
208
+ }
209
+ if (queued) {
210
+ queued = false;
211
+ refresh(true);
212
+ }
213
+ };
214
+ const computed = {
215
+ get value() {
216
+ if (computing)
217
+ throw new Error("derived read is cyclic");
218
+ trackSignal(computed);
219
+ computing = true;
220
+ try {
221
+ return read();
222
+ }
223
+ finally {
224
+ computing = false;
225
+ }
226
+ },
227
+ subscribe(listener) {
228
+ const start = listeners.size === 0;
229
+ listeners.add(listener);
230
+ try {
231
+ if (start)
232
+ refresh(false);
233
+ }
234
+ catch (error) {
235
+ listeners.delete(listener);
236
+ detach();
237
+ ready = false;
238
+ throw error;
239
+ }
240
+ return () => {
241
+ listeners.delete(listener);
242
+ if (listeners.size === 0) {
243
+ detach();
244
+ ready = false;
245
+ }
246
+ };
247
+ },
248
+ };
249
+ return computed;
250
+ }
@@ -2,7 +2,7 @@ export { createContext, useContext, type Context, type ContextScope } from "./co
2
2
  export { keyed, type KeyedChild } from "./keyed.js";
3
3
  import type { Child, Cleanup, ComponentContract, ComponentRenderContext, ShadowDefinition, ShadowSetup, Component, ComponentPartRef, FragmentComponent, Props, Runtime, RuntimeOptions, RuntimePluginOption, VNode } from "./types.js";
4
4
  export type { Child, Cleanup, Component, ComponentContract, ComponentMetadata, ComponentPartRef, ComponentRegistry, ComponentRegistryMap, ComponentRenderContext, CreateContext, CreateHook, Effect, ElementType, FragmentComponent, Key, LifecycleScope, MaybeSignal, MountResult, Props, ReadableSignal, RegisteredComponentName, RegisteredComponentPart, RenderContext, RenderHook, ResolveComponentContext, ResolveComponentHook, Runtime, RuntimeOptions, RuntimePlugin, RuntimePluginContext, RuntimePluginEnforce, RuntimePluginOption, RuntimePluginSetup, RuntimeRendererOptions, RuntimeTargetHooks, ShadowContext, ShadowDefinition, ShadowRegistry, ShadowSetup, Signal, StyleObject, StyleScalar, StyleValue, Theme, ThemeContext, ThemeRule, ThemeRules, ThemeStyle, VNode, WritableSignal, } from "./types.js";
5
- export { batch, isAsyncIterable, isPromiseLike, isSignal, mapSignal, signal, unwrap, } from "./reactive.js";
5
+ export { batch, isAsyncIterable, isPromiseLike, derived, isSignal, mapSignal, signal, unwrap, } from "./reactive.js";
6
6
  export { createLifecycleScope } from "./lifecycle.js";
7
7
  export { createThemePlugin, styleText } from "./style.js";
8
8
  export declare function defineComponent<PropsType extends object, Name extends string, Part extends string>(contract: ComponentContract<Name, Part>, render: (props: PropsType, context: ComponentRenderContext<Name, Part, PropsType>) => Child): Component<PropsType, Name, Part>;
@@ -4,7 +4,7 @@ import { isContextProvider } from "./context.js";
4
4
  import { createRenderer as createTargetRenderer, } from "./renderer.js";
5
5
  import { addHook, createBaseVNode, createComponentContext, createComponentRegistry, createShadowRegistry, invokeComponent, removeHook, runCreateHooks, runRenderHooks, } from "./registry.js";
6
6
  import { createLifecycleScope, disposeCleanups } from "./lifecycle.js";
7
- export { batch, isAsyncIterable, isPromiseLike, isSignal, mapSignal, signal, unwrap, } from "./reactive.js";
7
+ export { batch, isAsyncIterable, isPromiseLike, derived, isSignal, mapSignal, signal, unwrap, } from "./reactive.js";
8
8
  export { createLifecycleScope } from "./lifecycle.js";
9
9
  export { createThemePlugin, styleText } from "./style.js";
10
10
  function isRuntimePluginArray(option) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meowjsx",
3
- "version": "0.1.1-alpha.0",
3
+ "version": "0.1.1-alpha.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "scripts": {