@xharness/util-values 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,46 @@
1
+ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
2
+ # section, a hash of its English and Chinese blocks outside code blocks and generated regions.
3
+ # After editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/util/values/README.md
5
+ /:
6
+ en: 6b543e93639271ad
7
+ zh: 397ce501111fc943
8
+ /xharness-util-values:
9
+ en: 62bdd0bdbc76d50d
10
+ zh: 4cd84b3d513d4b38
11
+ /xharness-util-values/summary:
12
+ en: 7c7e9304b1266973
13
+ zh: 68dd911e2a80d7a8
14
+ /xharness-util-values/table-of-contents:
15
+ en: 80b31a934611cb4a
16
+ zh: 05f3f7f9cb2fd881
17
+ /xharness-util-values/use-this-package:
18
+ en: bbff250eba0f1b89
19
+ zh: 0a618f05cc88ee2b
20
+ /xharness-util-values/use-this-package/validate-or-snapshot-json-data:
21
+ en: 4735ebea586791b3
22
+ zh: 90dd42c5019f520d
23
+ /xharness-util-values/use-this-package/read-streamed-arguments:
24
+ en: c53d8e94245c2378
25
+ zh: de0308a325b17dad
26
+ /xharness-util-values/use-this-package/publish-compare-or-retain-keyed-values:
27
+ en: 13628af2abe3eea6
28
+ zh: e284bb8d3ebe38ea
29
+ /xharness-util-values/use-this-package/close-a-discriminated-union:
30
+ en: f21b7bd8040a72eb
31
+ zh: 19548d3e537c0b5b
32
+ /xharness-util-values/understand-the-implementation:
33
+ en: b4b4f5bf1f554b97
34
+ zh: 8b01c6f8c0df1df4
35
+ /xharness-util-values/understand-the-implementation/source-map:
36
+ en: c2009e51c6f64c0e
37
+ zh: 3a848671bb98e07c
38
+ /xharness-util-values/further-exploration:
39
+ en: f5126b27552eef33
40
+ zh: e79ff48887de4079
41
+ /xharness-util-values/known-limitations-and-deferred-work:
42
+ en: dc3626bb369e1230
43
+ zh: e292836d13ee512c
44
+ /xharness-util-values/known-limitations-and-deferred-work/dev-note:
45
+ en: e67f633dc6fe7773
46
+ zh: 3bb0c20c93f16f98
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ ---
2
+ description: "Lossless JSON validation, detached snapshots, deep freezing, structural equality, and exhaustive-union helpers for runtime packages."
3
+ kind: "package-library"
4
+ ---
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ # @xharness/util-values
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ Callers can validate lossless JSON, read streamed arguments, detach a JSON snapshot, freeze a published value, compare JSON-compatible data, or terminate an unreachable branch without importing a capability package. Each streamed call uses its own `PartialArguments` reader; `PartialArguments.EMPTY` is a shared sealed view with no fields.
13
+
14
+ ## Table of Contents
15
+
16
+ - [Use this package](#use-this-package)
17
+ - [Understand the implementation](#understand-the-implementation)
18
+ - [Further Exploration](#further-exploration)
19
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
20
+ - [Dev Note](#dev-note)
21
+
22
+ -----
23
+
24
+ <a id="use-this-package"></a>
25
+ ## Use this package
26
+
27
+ ### Validate or snapshot JSON data
28
+
29
+ Use `isJsonValue()` for a predicate and `snapshotJsonValue()` when the caller also needs a detached copy. Both accept only lossless JSON roots: `null`, booleans, finite numbers other than negative zero, strings, dense intrinsic arrays, and plain or null-prototype records with enumerable string keys. Cycles, sparse arrays, symbol or non-enumerable own properties, functions, and class instances are rejected.
30
+
31
+ ```ts
32
+ import { isJsonValue, snapshotJsonValue, type JsonValue } from '@xharness/util-values'
33
+
34
+ declare const input: unknown
35
+
36
+ if (!isJsonValue(input)) throw new TypeError('expected lossless JSON')
37
+ const snapshot = snapshotJsonValue(input) as JsonValue
38
+ ```
39
+
40
+ Use `hasPlainPrototype(value)` when a caller checks only the container and reads its fields itself. It accepts an array that inherits a realm's intrinsic `Array.prototype` and `Object.prototype`, or a non-array object whose prototype is `null` or a realm's intrinsic `Object.prototype`; elements and property values are not inspected. All three functions accept values built in another JavaScript realm, such as an iframe, and reject an object or array that inherits any other prototype, because that prototype could supply `toJSON`.
41
+
42
+ ### Read streamed arguments
43
+
44
+ `PartialArguments` reads a JSON object's top-level fields lazily. `append()` retains separate fragments without scanning or concatenating them. Readers index new key/value ranges, skipping unrequested contents; only requested strings are decoded or counted, and only requested complete non-string values are parsed. `complete()` reports a closing delimiter, not validated contents; `invalid` reports errors already discovered by indexing or content reads. It is not a substitute for tool-input validation.
45
+
46
+ `refresh()` reports changes to previously observed answers at publication time; intervening reads do not acknowledge pending changes. It evaluates content before comparing completion, so decoding errors cannot suppress a completion update. String readers provide decoded text, bounded prefixes, and exact UTF-16 length, with optional step and offset for change detection. `settle(finalText)` compares fragments directly against the complete text: equal input seals the same view and retains its caches; missing or conflicting deltas produce a new sealed view. `fromText()` and `fromObject()` also create sealed views that reject appends. `isSealed` reads that append restriction without scanning or observing content; `closed()` also covers a closed outer object or failed indexing. See [the readers](src/partial-json.ts) for return distinctions.
47
+
48
+ ### Publish, compare, or retain keyed values
49
+
50
+ `deepFreeze(value)` freezes an object graph in place and returns the same value. It walks enumerable string-keyed children and deliberately leaves live `AbortSignal` objects mutable. `deepEqualJson(a, b)` compares JSON-compatible arrays and records structurally; callers must validate hostile or unconstrained values before comparison.
51
+
52
+ `WeakMapWithValues<Key, Value>` combines weak object-key lookup with a strongly retained, insertion-ordered `values` set. Each value belongs to one key. The owner must call `delete(key)` or `clear()` at the corresponding lifecycle boundary; the collection does not perform automatic cleanup.
53
+
54
+ ### Close a discriminated union
55
+
56
+ Use `assertNever(value, context?)` in the default branch of a closed discriminated union. A newly added variant then fails TypeScript compilation at every exhaustive switch, while a runtime value that escaped its declared type throws with the optional context label.
57
+
58
+ -----
59
+
60
+ <a id="understand-the-implementation"></a>
61
+ ## Understand the implementation
62
+
63
+ <details>
64
+ <summary>Implementation internals — click to expand</summary>
65
+
66
+ The JSON validator keeps one cursor per active container, reads one child at a time, and tracks only the active ancestor chain, so deeply nested values do not consume the JavaScript call stack and repeated non-cyclic references remain valid. Containers that inherit this realm's intrinsics are recognized by identity; those of another JavaScript realm are recognized by native constructor representations from the running engine. Snapshot writes use own data properties, including for names such as `__proto__`. Value operations derive their result only from their arguments; `WeakMapWithValues` stores only instance-owned associations.
67
+
68
+ ### Source map
69
+
70
+ | File | Role |
71
+ |---|---|
72
+ | [`src/index.ts`](src/index.ts) | JSON value type, plain-prototype recognition, validation and snapshot traversal, structural equality, deep freezing, weak-key/strong-value associations, and exhaustive-union failure |
73
+ | [`src/partial-json.ts`](src/partial-json.ts) | Lazy top-level argument scanning and observed-answer change detection |
74
+
75
+ </details>
76
+
77
+ -----
78
+
79
+ <a id="further-exploration"></a>
80
+ ## Further Exploration
81
+
82
+ - [Utility package map](../README.md) — adjacent stateless helpers.
83
+ - [Session subsystem](../../../docs/subsystems/session.md) — durable events that require lossless JSON.
84
+ - [Tools subsystem](../../../docs/subsystems/tools.md) — schema validation and canonical tool results built on `JsonValue`.
85
+
86
+ -----
87
+
88
+ ## Known Limitations and Deferred Work
89
+
90
+ <a id="known-limitations-and-deferred-work"></a>
91
+
92
+ - **`deepEqualJson` assumes JSON-compatible inputs** — it is not a general object comparator and does not define semantics for prototypes, symbols, accessors, cycles, maps, or sets.
93
+ - **`deepFreeze` follows enumerable string-keyed children** — it does not turn arbitrary host objects into immutable data, and it intentionally skips live `AbortSignal` instances.
94
+ - **`WeakMapWithValues` requires explicit cleanup and unique values** — values remain strongly held until their owning key is deleted or the collection is cleared, and one value must not be shared by several keys.
95
+
96
+ <a id="dev-note"></a>
97
+ ### Dev Note
98
+
99
+ <details>
100
+ <summary>Working context for maintainers — click to expand</summary>
101
+
102
+ None.
103
+
104
+ </details>
package/README.zh.md ADDED
@@ -0,0 +1,104 @@
1
+ ---
2
+ description: "供运行时包使用的无损 JSON 校验、分离式快照、深度冻结、结构相等与穷尽联合类型辅助函数。"
3
+ kind: "package-library"
4
+ ---
5
+
6
+ # @xharness/util-values
7
+
8
+ [English](README.md) | 中文
9
+
10
+ ## 概述
11
+
12
+ 调用方可以校验无损 JSON、读取流式参数、创建分离的 JSON 快照、冻结待发布值、比较 JSON 兼容数据,或终止不可达分支,而无需导入某个能力包。每次流式调用使用独立的 `PartialArguments` 读器;`PartialArguments.EMPTY` 是不含字段的共用封存视图。
13
+
14
+ ## 目录
15
+
16
+ - [使用本包](#use-this-package)
17
+ - [理解实现](#understand-the-implementation)
18
+ - [进一步探索](#further-exploration)
19
+ - [已知限制与延期工作](#known-limitations-and-deferred-work)
20
+ - [开发备注](#dev-note)
21
+
22
+ -----
23
+
24
+ <a id="use-this-package"></a>
25
+ ## 使用本包
26
+
27
+ ### 校验 JSON 数据或创建快照
28
+
29
+ 需要 predicate 时使用 `isJsonValue()`,还需要分离副本时使用 `snapshotJsonValue()`。两者只接受无损 JSON 根值:`null`、布尔值、除负零外的有限数字、字符串、稠密的内建数组,以及只含可枚举字符串键的普通或 null-prototype 记录。循环、稀疏数组、自有 symbol 属性或自有不可枚举属性、函数和 class 实例都会被拒绝。
30
+
31
+ ```ts
32
+ import { isJsonValue, snapshotJsonValue, type JsonValue } from '@xharness/util-values'
33
+
34
+ declare const input: unknown
35
+
36
+ if (!isJsonValue(input)) throw new TypeError('expected lossless JSON')
37
+ const snapshot = snapshotJsonValue(input) as JsonValue
38
+ ```
39
+
40
+ 调用方只校验容器本身、自行读取字段时,使用 `hasPlainPrototype(value)`。它接受继承某个 realm 内建 `Array.prototype` 与 `Object.prototype` 的数组,或原型为 `null` 或某个 realm 内建 `Object.prototype` 的非数组对象;不检查元素与属性值。这三个函数都接受在另一个 JavaScript realm(例如 iframe)中构造的值,并拒绝继承其他任何原型的对象或数组,因为该原型可能提供 `toJSON`。
41
+
42
+ ### 读取流式参数
43
+
44
+ `PartialArguments` 懒读取 JSON 对象的顶层字段。`append()` 分别保留分片,不扫描也不拼接。读器为新的键值范围建立索引,跳过未请求的内容;仅在请求时解码或计数字符串,仅在请求时解析已完整的非字符串值。`complete()` 表示结束分隔符已到达,不代表内容已校验;`invalid` 报告索引或内容读取已经发现的错误。它不能替代工具入参校验。
45
+
46
+ `refresh()` 在发布点报告已观察答案的变化;期间的读取不会确认待发布的变化。它先读取内容再比较完成状态,避免解码错误吞掉完成状态更新。字符串读器提供解码文本、有界前缀和精确 UTF-16 长度,并可为变化判定指定步长和偏移量。`settle(finalText)` 直接将分片与完整文本比较:输入相同时封存原视图并保留缓存,分片缺失或冲突时创建新的封存视图。`fromText()` 和 `fromObject()` 也创建拒绝追加的封存视图。`isSealed` 读取这一追加限制,不扫描或观察内容;`closed()` 还包含外层对象闭合或索引失败的情况。返回值区别见[读器定义](src/partial-json.ts)。
47
+
48
+ ### 发布、比较或保留键控值
49
+
50
+ `deepFreeze(value)` 原地冻结对象图并返回同一个值。它遍历可枚举字符串键的子项,并刻意让活跃 `AbortSignal` 对象保持可变。`deepEqualJson(a, b)` 按结构比较 JSON 兼容数组与记录;调用方必须先校验恶意或不受约束的值,再进行比较。
51
+
52
+ `WeakMapWithValues<Key, Value>` 组合弱对象键查找与强引用且保持插入顺序的 `values` set。每个 value 只属于一个 key。owner 必须在对应生命周期边界调用 `delete(key)` 或 `clear()`;该集合不执行自动清理。
53
+
54
+ ### 封闭可辨识联合类型
55
+
56
+ 在封闭可辨识联合类型的 default 分支中使用 `assertNever(value, context?)`。新增变体会让每个穷尽 switch 在 TypeScript 编译时失败;如果某个运行时值逃过了声明类型,该函数会抛出带可选上下文标签的错误。
57
+
58
+ -----
59
+
60
+ <a id="understand-the-implementation"></a>
61
+ ## 理解实现
62
+
63
+ <details>
64
+ <summary>实现细节——点击展开</summary>
65
+
66
+ JSON 校验器为每个正在遍历的容器保留一个位置,每次读取一个子项,并只跟踪当前祖先链,因此深层嵌套值不会消耗 JavaScript 调用栈,重复但无循环的引用仍然有效。继承本 realm 内建原型的容器按身份识别;继承其他 JavaScript realm 内建原型的容器通过当前引擎的原生构造器文本表示识别。快照写入使用自有数据属性,包括 `__proto__` 等名称。值操作的结果只取决于传入参数;`WeakMapWithValues` 仅保存实例自有的关联。
67
+
68
+ ### 源码地图
69
+
70
+ | 文件 | 职责 |
71
+ |---|---|
72
+ | [`src/index.ts`](src/index.ts) | JSON 值类型、普通原型识别、校验与快照遍历、结构相等、深度冻结、弱键/强值关联和穷尽联合类型失败 |
73
+ | [`src/partial-json.ts`](src/partial-json.ts) | 懒扫描顶层参数,并检测已读取答案的变化 |
74
+
75
+ </details>
76
+
77
+ -----
78
+
79
+ <a id="further-exploration"></a>
80
+ ## 进一步探索
81
+
82
+ - [工具包映射](../README.zh.md)——相邻的无状态 helper。
83
+ - [会话子系统](../../../docs/subsystems/session.zh.md)——要求无损 JSON 的持久事件。
84
+ - [工具子系统](../../../docs/subsystems/tools.zh.md)——构建于 `JsonValue` 之上的 schema 校验与规范工具结果。
85
+
86
+ -----
87
+
88
+ ## 已知限制与延期工作
89
+
90
+ <a id="known-limitations-and-deferred-work"></a>
91
+
92
+ - **`deepEqualJson` 假定输入兼容 JSON**——它不是通用对象比较器,不为 prototype、symbol、accessor、循环、map 或 set 定义语义。
93
+ - **`deepFreeze` 沿可枚举字符串键遍历子项**——它不会把任意宿主对象变成不可变数据,并会刻意跳过活跃 `AbortSignal` 实例。
94
+ - **`WeakMapWithValues` 要求显式清理且 value 唯一**——value 会保持强引用,直到 owner 删除其 key 或清空集合;同一 value 不得由多个 key 共享。
95
+
96
+ <a id="dev-note"></a>
97
+ ### 开发备注
98
+
99
+ <details>
100
+ <summary>维护者的工作上下文——点击展开</summary>
101
+
102
+ 无。
103
+
104
+ </details>