@tansr/protocol 0.2.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -0
  3. package/dist/canonical/common.d.ts +37 -0
  4. package/dist/canonical/common.js +149 -0
  5. package/dist/canonical/digest.d.ts +12 -0
  6. package/dist/canonical/digest.js +58 -0
  7. package/dist/canonical/encode.d.ts +15 -0
  8. package/dist/canonical/encode.js +157 -0
  9. package/dist/canonical/errors.d.ts +81 -0
  10. package/dist/canonical/errors.js +89 -0
  11. package/dist/canonical/index.d.ts +21 -0
  12. package/dist/canonical/index.js +21 -0
  13. package/dist/canonical/parse.d.ts +21 -0
  14. package/dist/canonical/parse.js +295 -0
  15. package/dist/client.d.ts +42 -0
  16. package/dist/client.js +1 -0
  17. package/dist/config.d.ts +4990 -0
  18. package/dist/config.js +657 -0
  19. package/dist/daemon.d.ts +70 -0
  20. package/dist/daemon.js +48 -0
  21. package/dist/events.d.ts +2152 -0
  22. package/dist/events.js +625 -0
  23. package/dist/governance.d.ts +445 -0
  24. package/dist/governance.js +183 -0
  25. package/dist/headless.d.ts +97 -0
  26. package/dist/headless.js +39 -0
  27. package/dist/identity.d.ts +96 -0
  28. package/dist/identity.js +45 -0
  29. package/dist/index.d.ts +525 -0
  30. package/dist/index.js +529 -0
  31. package/dist/ir.d.ts +1418 -0
  32. package/dist/ir.js +283 -0
  33. package/dist/journal.d.ts +297 -0
  34. package/dist/journal.js +150 -0
  35. package/dist/media.d.ts +563 -0
  36. package/dist/media.js +190 -0
  37. package/dist/metering.d.ts +225 -0
  38. package/dist/metering.js +90 -0
  39. package/dist/orchestration.d.ts +1551 -0
  40. package/dist/orchestration.js +333 -0
  41. package/dist/redact-patterns.d.ts +49 -0
  42. package/dist/redact-patterns.js +141 -0
  43. package/dist/storage.d.ts +507 -0
  44. package/dist/storage.js +110 -0
  45. package/dist/tool-result-artifact.d.ts +257 -0
  46. package/dist/tool-result-artifact.js +263 -0
  47. package/package.json +30 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tansr (tansr.com)
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.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # @tansr/protocol
2
+
3
+ Tansr 的 **L0 合同包**:IR 消息模型、kernel 事件协议、会话日志(journal)与配置的 zod schema,以及 `unified-v1` 统一 API 合同所用的 **canonical JSON 单模块**。纯 ESM、MIT;运行时依赖只有 `zod`。
4
+
5
+ 本包不含任何运行时行为(不发请求、不读文件、不持状态),只定义「字节与形」:`@tansr/sdk`、`@tansr/serve`、`@tansr/api-client` 与各语言 SDK 都以它为唯一事实源。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ npm i @tansr/protocol
11
+ # 或
12
+ pnpm add @tansr/protocol
13
+ ```
14
+
15
+ 纯 ESM(`"type": "module"`,NodeNext 解析);发布包只含 `dist/**`(`.js` + `.d.ts`)与 `LICENSE`,无 CommonJS 产物。
16
+
17
+ ## 入口
18
+
19
+ | 入口 | 内容 |
20
+ |---|---|
21
+ | `@tansr/protocol` | IR 消息 / 事件 / journal / 配置 schema 与类型、`PROTOCOL_VERSION`(事件包络 `v0`)、合同修订史(`contract-v0.x`,见源码头注) |
22
+ | `@tansr/protocol/canonical` | canonical JSON 编解码与域摘要(RFC-UAPI-1 §4),零 Node 依赖,**不**从根入口再导出 |
23
+
24
+ ### 根入口最小用法
25
+
26
+ ```ts
27
+ import { PROTOCOL_VERSION } from '@tansr/protocol';
28
+
29
+ PROTOCOL_VERSION; // 'v0'
30
+ ```
31
+
32
+ 具体 schema(事件、journal 记录、配置)按名导入即可;完整导出集见包内 `exports.snapshot.json`(发版门 ④ 以它判 semver)。
33
+
34
+ ### `./canonical` 最小用法
35
+
36
+ ```ts
37
+ import { createHash } from 'node:crypto';
38
+ import { encodeCanonical, parseStrict, decodeCanonical, domainDigest, toHex } from '@tansr/protocol/canonical';
39
+
40
+ // 编码:对象 → canonical 字节(键 ASCII-only 升序、无空白、整数 token 受限、深度 / 节点 / 字节有上界)
41
+ const bytes = encodeCanonical({ b: 1, a: 'x' }, { maxBytes: 64 * 1024 });
42
+
43
+ // 严格解码(服务端收 wire、摘要复算):非 canonical 输入抛 CanonicalError{ code: 'not_canonical', path?, offset?, reason? }
44
+ const strict = parseStrict(bytes, { maxBytes: 64 * 1024 });
45
+
46
+ // 归一化解码(客户端容错读):接受空白 / 键乱序 / 等价转义的合法 JSON
47
+ const loose = decodeCanonical('{ "b": 1, "a": "x" }', { maxBytes: 64 * 1024 });
48
+
49
+ // 域摘要:SHA256(UTF8(domain) ‖ 0x00 ‖ bytes);SHA-256 由调用方注入(同步或异步均可)
50
+ const sha256 = (framed: Uint8Array) => new Uint8Array(createHash('sha256').update(framed).digest());
51
+ const digest = domainDigest('tansr.unified.closure.v1', bytes, sha256);
52
+ toHex(digest as Uint8Array);
53
+ ```
54
+
55
+ 签名(摘自 `src/canonical/index.ts` 头注):
56
+
57
+ - `encodeCanonical(value, { maxBytes, maxDepth?, maxNodes?, isProxy? }) → Uint8Array`;`encodeCanonicalText(value, options) → string`(同字节的文本形)
58
+ - `parseStrict(input: Uint8Array | string, { maxBytes, maxDepth?, maxNodes? }) → unknown`
59
+ - `decodeCanonical(input: Uint8Array | string, options) → unknown`
60
+ - `domainDigest(domain, bytes, sha256) → Uint8Array | Promise<Uint8Array>`(`sha256` 为同步函数则同步返回);`frameDomain` / `toHex` / `subtleSha256`(基于 WebCrypto 的异步 SHA-256)
61
+ - `CanonicalError` / `CANONICAL_ERROR_CODES` / `NOT_CANONICAL_REASONS` / `CANONICAL_KEY_PATTERN` / `CANONICAL_MAX_DEPTH`(32)/ `CANONICAL_MAX_NODES`(100 000)
62
+
63
+ 纪律:`maxBytes` **必填、无缺省**;`maxDepth` / `maxNodes` 只能比包内上限更紧;字节上限作用于原始输入。服务端收 wire 与摘要复算一律用 `parseStrict`,客户端容错读才用 `decodeCanonical`——两者对合法 canonical 输入结果相同,对非 canonical 输入前者拒绝、后者接受。Node 侧需要 Proxy 判定时经 `isProxy: util.types.isProxy` 注入。
64
+
65
+ ## 合同冻结与版本策略
66
+
67
+ - `contract-v0` 自 W0 末冻结,任何形的变更走 RFC(`doc/rfc/`),修订号 `contract-v0.x` 与同名 git tag 对应;事件包络 `v` 维持 `v0`。
68
+ - 包版本遵「**0.x 期 minor = breaking**」(doc/89 §3.3):导出集任何增 / 删 / 签名变至少 minor,patch 不得携新导出;发版门 ④ 以 `exports.snapshot.json` + `exports.subpaths.snapshot.json` 与上一 tag 比对强制执行。
69
+ - 预发布 `X.Y.Z-rc.N` 走 dist-tag `next`,`-beta.N` 走 `beta`,正式版 `latest`;变更记录见 [`CHANGELOG.md`](./CHANGELOG.md),每版发布回执落仓内 `doc/release/protocol-<version>.md`,无回执无 tag(tag 形 `@tansr/protocol@<version>`)。
70
+ - canonical 规则与错误码表的规范文本:[RFC-UAPI-1 统一信封与 canonical 单模块](../../doc/rfc/RFC-UAPI-1-统一信封与canonical单模块.md) §4;统一 API 合同的结构 schema:`doc/rfc/unified-v1.schema.json`。
71
+
72
+ ## 许可
73
+
74
+ MIT,见 [`LICENSE`](./LICENSE)。
@@ -0,0 +1,37 @@
1
+ export declare const CANONICAL_MAX_DEPTH = 32;
2
+ export declare const CANONICAL_MAX_NODES = 100000;
3
+ export declare const CANONICAL_KEY_PATTERN: RegExp;
4
+ /** 解码侧选项:`maxBytes` 必填(≥ 1,作用于原始输入 UTF-8 字节);`maxDepth` / `maxNodes` 只可收紧。 */
5
+ export interface CanonicalDecodeOptions {
6
+ readonly maxBytes: number;
7
+ readonly maxDepth?: number;
8
+ readonly maxNodes?: number;
9
+ }
10
+ /** 编码侧选项:同解码侧,另可注入 `isProxy`(Node 封装传 `util.types.isProxy`;Web 无此能力则省略)。 */
11
+ export interface CanonicalEncodeOptions extends CanonicalDecodeOptions {
12
+ readonly isProxy?: (value: object) => boolean;
13
+ }
14
+ export interface NormalizedCanonicalOptions {
15
+ readonly maxBytes: number;
16
+ readonly maxDepth: number;
17
+ readonly maxNodes: number;
18
+ readonly isProxy: ((value: object) => boolean) | null;
19
+ }
20
+ /** 只认真正的 Uint8Array(含其子类,如 Node 的字节缓冲);ArrayBuffer / DataView / 其它 TypedArray 均拒。 */
21
+ export declare function isUint8Array(value: unknown): value is Uint8Array;
22
+ /** 经原型 getter 读取,不信任子类自报的 byteLength。 */
23
+ export declare function byteLengthOf(bytes: Uint8Array): number;
24
+ /**
25
+ * 选项归一化(运行时校验,不信任调用方类型):`maxBytes` 必填(≥ 1);`maxDepth` ≤ 32、`maxNodes` ≤ 100000 只允许收紧,
26
+ * 不允许放宽;未知键拒绝;编码侧可注入 `isProxy(value) => boolean`。
27
+ */
28
+ export declare function normalizeOptions(options: unknown, side: 'encode' | 'decode'): NormalizedCanonicalOptions;
29
+ /** 代理项配对校验:命中代理项才逐码元扫描;返回 true = 合法,false = 孤立 / 颠倒 / 高后非低。 */
30
+ export declare function wellFormed(text: string): boolean;
31
+ /**
32
+ * 首个非法 UTF-8 序列的起始字节偏移(Unicode 15 表 3-7 合法序列);全部合法返回 -1。
33
+ * 只在 fatal TextDecoder 已拒绝后调用,用于给 `invalid_utf8` 定位,不替代解码。
34
+ */
35
+ export declare function firstInvalidUtf8(bytes: Uint8Array): number;
36
+ /** UTF-8 字节长度(不分配):ASCII 快路径;孤立代理项按 TextEncoder 的替换语义计 3 字节(调用方已另行拒绝孤立代理项)。 */
37
+ export declare function utf8Length(text: string): number;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * canonical 单模块 — 常量、选项归一化与编解码共用的纯 ECMAScript 工具(RFC-UAPI-1 §4.1)。
3
+ *
4
+ * 固定常量:深度 ≤ 32(按祖先容器数,根 = 0)、节点 ≤ 100000(含标量,键不计)、键 = 非空可打印 ASCII。
5
+ * 字节上限无缺省:由调用方传入并作用于原始输入 / 累计输出的 UTF-8 字节。
6
+ */
7
+ import { CanonicalError } from './errors.js';
8
+ export const CANONICAL_MAX_DEPTH = 32;
9
+ export const CANONICAL_MAX_NODES = 100000;
10
+ export const CANONICAL_KEY_PATTERN = /^[\x21-\x7e]+$/;
11
+ const ENCODE_OPTIONS = Object.freeze(['maxBytes', 'maxDepth', 'maxNodes', 'isProxy']);
12
+ const DECODE_OPTIONS = Object.freeze(['maxBytes', 'maxDepth', 'maxNodes']);
13
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
14
+ const byteLengthGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'byteLength').get;
15
+ /** 只认真正的 Uint8Array(含其子类,如 Node 的字节缓冲);ArrayBuffer / DataView / 其它 TypedArray 均拒。 */
16
+ export function isUint8Array(value) {
17
+ return value instanceof Uint8Array;
18
+ }
19
+ /** 经原型 getter 读取,不信任子类自报的 byteLength。 */
20
+ export function byteLengthOf(bytes) {
21
+ return byteLengthGetter.call(bytes);
22
+ }
23
+ function invalidOptions(message) {
24
+ throw new CanonicalError('invalid_options', message);
25
+ }
26
+ function boundedInteger(options, key, minimum, maximum, fallback) {
27
+ if (!Object.hasOwn(options, key) || options[key] === undefined) {
28
+ if (fallback === undefined)
29
+ invalidOptions(`options.${key} is required`);
30
+ return fallback;
31
+ }
32
+ const value = options[key];
33
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum || value > maximum) {
34
+ invalidOptions(`options.${key} must be a safe integer in [${minimum}, ${maximum}]`);
35
+ }
36
+ return value;
37
+ }
38
+ /**
39
+ * 选项归一化(运行时校验,不信任调用方类型):`maxBytes` 必填(≥ 1);`maxDepth` ≤ 32、`maxNodes` ≤ 100000 只允许收紧,
40
+ * 不允许放宽;未知键拒绝;编码侧可注入 `isProxy(value) => boolean`。
41
+ */
42
+ export function normalizeOptions(options, side) {
43
+ if (options === null || typeof options !== 'object' || Array.isArray(options))
44
+ invalidOptions('options must be an object');
45
+ const allowed = side === 'encode' ? ENCODE_OPTIONS : DECODE_OPTIONS;
46
+ for (const key of Reflect.ownKeys(options)) {
47
+ if (typeof key !== 'string' || !allowed.includes(key))
48
+ invalidOptions(`unknown option ${String(key)}`);
49
+ }
50
+ const record = options;
51
+ let isProxy = null;
52
+ if (side === 'encode' && record.isProxy !== undefined) {
53
+ if (typeof record.isProxy !== 'function')
54
+ invalidOptions('options.isProxy must be a function');
55
+ isProxy = record.isProxy;
56
+ }
57
+ return {
58
+ maxBytes: boundedInteger(record, 'maxBytes', 1, Number.MAX_SAFE_INTEGER),
59
+ maxDepth: boundedInteger(record, 'maxDepth', 0, CANONICAL_MAX_DEPTH, CANONICAL_MAX_DEPTH),
60
+ maxNodes: boundedInteger(record, 'maxNodes', 1, CANONICAL_MAX_NODES, CANONICAL_MAX_NODES),
61
+ isProxy,
62
+ };
63
+ }
64
+ const SURROGATE = /[\ud800-\udfff]/;
65
+ /** 代理项配对校验:命中代理项才逐码元扫描;返回 true = 合法,false = 孤立 / 颠倒 / 高后非低。 */
66
+ export function wellFormed(text) {
67
+ if (!SURROGATE.test(text))
68
+ return true;
69
+ for (let index = 0; index < text.length; index++) {
70
+ const code = text.charCodeAt(index);
71
+ if (code >= 0xd800 && code <= 0xdbff) {
72
+ const next = text.charCodeAt(++index);
73
+ if (!(next >= 0xdc00 && next <= 0xdfff))
74
+ return false;
75
+ }
76
+ else if (code >= 0xdc00 && code <= 0xdfff)
77
+ return false;
78
+ }
79
+ return true;
80
+ }
81
+ /**
82
+ * 首个非法 UTF-8 序列的起始字节偏移(Unicode 15 表 3-7 合法序列);全部合法返回 -1。
83
+ * 只在 fatal TextDecoder 已拒绝后调用,用于给 `invalid_utf8` 定位,不替代解码。
84
+ */
85
+ export function firstInvalidUtf8(bytes) {
86
+ const length = bytes.length;
87
+ const cont = (index, low = 0x80, high = 0xbf) => index < length && bytes[index] >= low && bytes[index] <= high;
88
+ let index = 0;
89
+ while (index < length) {
90
+ const lead = bytes[index];
91
+ if (lead <= 0x7f) {
92
+ index += 1;
93
+ continue;
94
+ }
95
+ if (lead >= 0xc2 && lead <= 0xdf) {
96
+ if (cont(index + 1)) {
97
+ index += 2;
98
+ continue;
99
+ }
100
+ return index;
101
+ }
102
+ if (lead >= 0xe0 && lead <= 0xef) {
103
+ const secondLow = lead === 0xe0 ? 0xa0 : 0x80;
104
+ const secondHigh = lead === 0xed ? 0x9f : 0xbf;
105
+ if (cont(index + 1, secondLow, secondHigh) && cont(index + 2)) {
106
+ index += 3;
107
+ continue;
108
+ }
109
+ return index;
110
+ }
111
+ if (lead >= 0xf0 && lead <= 0xf4) {
112
+ const secondLow = lead === 0xf0 ? 0x90 : 0x80;
113
+ const secondHigh = lead === 0xf4 ? 0x8f : 0xbf;
114
+ if (cont(index + 1, secondLow, secondHigh) && cont(index + 2) && cont(index + 3)) {
115
+ index += 4;
116
+ continue;
117
+ }
118
+ return index;
119
+ }
120
+ return index;
121
+ }
122
+ return -1;
123
+ }
124
+ const ASCII_ONLY = /^[\x00-\x7f]*$/;
125
+ /** UTF-8 字节长度(不分配):ASCII 快路径;孤立代理项按 TextEncoder 的替换语义计 3 字节(调用方已另行拒绝孤立代理项)。 */
126
+ export function utf8Length(text) {
127
+ if (ASCII_ONLY.test(text))
128
+ return text.length;
129
+ let bytes = 0;
130
+ for (let index = 0; index < text.length; index++) {
131
+ const code = text.charCodeAt(index);
132
+ if (code < 0x80)
133
+ bytes += 1;
134
+ else if (code < 0x800)
135
+ bytes += 2;
136
+ else if (code >= 0xd800 && code <= 0xdbff) {
137
+ const next = text.charCodeAt(index + 1);
138
+ if (next >= 0xdc00 && next <= 0xdfff) {
139
+ bytes += 4;
140
+ index++;
141
+ }
142
+ else
143
+ bytes += 3;
144
+ }
145
+ else
146
+ bytes += 3;
147
+ }
148
+ return bytes;
149
+ }
@@ -0,0 +1,12 @@
1
+ /** 注入的 SHA-256:同步返回 32 字节,或返回其 Promise。 */
2
+ export type Sha256Function = (framed: Uint8Array) => Uint8Array | Promise<Uint8Array>;
3
+ /** `UTF8(domain) ‖ 0x00 ‖ bytes`(供需要自行喂入 HMAC / 流式摘要的调用方复用同一帧形)。 */
4
+ export declare function frameDomain(domain: string, bytes: Uint8Array): Uint8Array;
5
+ /** 域摘要。`sha256` 可返回 Uint8Array 或其 Promise;结果为 32 字节摘要(hex 用 `toHex`)。 */
6
+ export declare function domainDigest(domain: string, bytes: Uint8Array, sha256: (framed: Uint8Array) => Uint8Array): Uint8Array;
7
+ export declare function domainDigest(domain: string, bytes: Uint8Array, sha256: (framed: Uint8Array) => Promise<Uint8Array>): Promise<Uint8Array>;
8
+ export declare function domainDigest(domain: string, bytes: Uint8Array, sha256: Sha256Function): Uint8Array | Promise<Uint8Array>;
9
+ /** 小写 hex(与现有 `createHash(...).digest('hex')` 同形)。 */
10
+ export declare function toHex(bytes: Uint8Array): string;
11
+ /** Web / Node ≥ 20 通用的 SHA-256 注入实现(`globalThis.crypto.subtle`,异步)。 */
12
+ export declare function subtleSha256(bytes: Uint8Array): Promise<Uint8Array>;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * canonical 单模块 — 域摘要(RFC-UAPI-1 §4.2)。
3
+ *
4
+ * `digest = SHA256(UTF8(domain) ‖ 0x00 ‖ bytes)`。SHA-256 由调用方注入 `sha256(bytes) => Uint8Array | Promise<Uint8Array>`,
5
+ * 使同一模块在 Node(`node:crypto` 同步)与 Web(`crypto.subtle` 异步)两侧复用;本文件零 Node 依赖。
6
+ * 返回值与注入函数同步 / 异步形态一致:同步 sha256 → Uint8Array;Promise → Promise<Uint8Array>。
7
+ *
8
+ * 域名:非空字符串、不含 U+0000(分隔符)、无孤立代理项;现有域名恒不改(§4.2 列表),新域名须经 RFC 登记。
9
+ */
10
+ import { isUint8Array, wellFormed } from './common.js';
11
+ import { CanonicalError } from './errors.js';
12
+ const encoder = new TextEncoder();
13
+ const HEX = Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, '0'));
14
+ function checkDigest(digest) {
15
+ if (!isUint8Array(digest) || digest.length !== 32)
16
+ throw new CanonicalError('invalid_options', 'sha256 must return 32 bytes');
17
+ return digest;
18
+ }
19
+ /** `UTF8(domain) ‖ 0x00 ‖ bytes`(供需要自行喂入 HMAC / 流式摘要的调用方复用同一帧形)。 */
20
+ export function frameDomain(domain, bytes) {
21
+ if (typeof domain !== 'string' || domain.length === 0 || domain.includes('\u0000') || !wellFormed(domain)) {
22
+ throw new CanonicalError('invalid_options', 'domain must be a nonempty well-formed string without U+0000');
23
+ }
24
+ if (!isUint8Array(bytes))
25
+ throw new CanonicalError('invalid_input', 'bytes must be a Uint8Array');
26
+ const prefix = encoder.encode(domain);
27
+ const framed = new Uint8Array(prefix.length + 1 + bytes.length);
28
+ framed.set(prefix, 0);
29
+ framed[prefix.length] = 0x00;
30
+ framed.set(bytes, prefix.length + 1);
31
+ return framed;
32
+ }
33
+ export function domainDigest(domain, bytes, sha256) {
34
+ if (typeof sha256 !== 'function')
35
+ throw new CanonicalError('invalid_options', 'sha256 must be a function');
36
+ const digest = sha256(frameDomain(domain, bytes));
37
+ if (digest !== null && typeof digest === 'object' && typeof digest.then === 'function') {
38
+ return digest.then(checkDigest);
39
+ }
40
+ return checkDigest(digest);
41
+ }
42
+ /** 小写 hex(与现有 `createHash(...).digest('hex')` 同形)。 */
43
+ export function toHex(bytes) {
44
+ if (!isUint8Array(bytes))
45
+ throw new CanonicalError('invalid_input', 'bytes must be a Uint8Array');
46
+ let out = '';
47
+ for (let index = 0; index < bytes.length; index++)
48
+ out += HEX[bytes[index]];
49
+ return out;
50
+ }
51
+ /** Web / Node ≥ 20 通用的 SHA-256 注入实现(`globalThis.crypto.subtle`,异步)。 */
52
+ export async function subtleSha256(bytes) {
53
+ const subtle = globalThis.crypto?.subtle;
54
+ if (subtle === undefined)
55
+ throw new CanonicalError('invalid_options', 'crypto.subtle is unavailable in this runtime');
56
+ // 复制到独立 ArrayBuffer:subtle 不接受 SharedArrayBuffer 视图,也避免把调用方缓冲区的其余字节一并送入。
57
+ return new Uint8Array(await subtle.digest('SHA-256', bytes.slice().buffer));
58
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * canonical 单模块 — 编码器(RFC-UAPI-1 §4.1 / SDK2-ext-v1-wire §5)。
3
+ *
4
+ * 输出:ASCII 键按码元升序、无空白;数字只写 `0 | [1-9][0-9]*`(≤ 2^53−1);字符串逐标量、`JSON.stringify` 同形
5
+ * (`"` `\\` 与五个短转义、其余 < 0x20 写小写 `\u00xx`、`/` 与 U+2028/2029 及全部非 ASCII 直接 UTF-8)。
6
+ * 输入防护与三份产品实现同判据:拒 getter / 不可枚举 / Symbol 键 / 稀疏数组 / 循环 / 非 plain 原型 / 不安全整数 /
7
+ * 负数 / -0 / 非整数 / 孤立代理项 / 非 ASCII 键;Proxy 判定由调用方经 `options.isProxy` 注入(零 Node 依赖)。
8
+ *
9
+ * 上限:`maxBytes` 作用于累计输出 UTF-8 字节;深度按祖先容器数(根 = 0);节点含根、容器与标量,键不计。
10
+ */
11
+ import { type CanonicalEncodeOptions } from './common.js';
12
+ /** canonical 文本(UTF-16 字符串形态;与 `encodeCanonical` 同字节,供宿主内部比较免去编码 / 解码往返)。 */
13
+ export declare function encodeCanonicalText(value: unknown, options: CanonicalEncodeOptions): string;
14
+ /** canonical 字节(UTF-8 Uint8Array)。`options.maxBytes` 必填;`maxDepth` / `maxNodes` 只可收紧。 */
15
+ export declare function encodeCanonical(value: unknown, options: CanonicalEncodeOptions): Uint8Array;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * canonical 单模块 — 编码器(RFC-UAPI-1 §4.1 / SDK2-ext-v1-wire §5)。
3
+ *
4
+ * 输出:ASCII 键按码元升序、无空白;数字只写 `0 | [1-9][0-9]*`(≤ 2^53−1);字符串逐标量、`JSON.stringify` 同形
5
+ * (`"` `\\` 与五个短转义、其余 < 0x20 写小写 `\u00xx`、`/` 与 U+2028/2029 及全部非 ASCII 直接 UTF-8)。
6
+ * 输入防护与三份产品实现同判据:拒 getter / 不可枚举 / Symbol 键 / 稀疏数组 / 循环 / 非 plain 原型 / 不安全整数 /
7
+ * 负数 / -0 / 非整数 / 孤立代理项 / 非 ASCII 键;Proxy 判定由调用方经 `options.isProxy` 注入(零 Node 依赖)。
8
+ *
9
+ * 上限:`maxBytes` 作用于累计输出 UTF-8 字节;深度按祖先容器数(根 = 0);节点含根、容器与标量,键不计。
10
+ */
11
+ import { CANONICAL_KEY_PATTERN, normalizeOptions, utf8Length, wellFormed } from './common.js';
12
+ import { CanonicalError, childPointer } from './errors.js';
13
+ const encoder = new TextEncoder();
14
+ class Writer {
15
+ maxBytes;
16
+ maxDepth;
17
+ maxNodes;
18
+ isProxy;
19
+ parts = [];
20
+ used = 0;
21
+ nodes = 0;
22
+ ancestors = new Set();
23
+ constructor({ maxBytes, maxDepth, maxNodes, isProxy }) {
24
+ this.maxBytes = maxBytes;
25
+ this.maxDepth = maxDepth;
26
+ this.maxNodes = maxNodes;
27
+ this.isProxy = isProxy;
28
+ }
29
+ fail(code, message, path) {
30
+ throw new CanonicalError(code, message, { path });
31
+ }
32
+ /** 结构符 / 数字 / 字面量 / ASCII 键:字节数 = 码元数。 */
33
+ ascii(part, path) {
34
+ this.used += part.length;
35
+ if (this.used > this.maxBytes)
36
+ this.fail('bytes_exceeded', `encoded bytes exceed maxBytes ${this.maxBytes}`, path);
37
+ this.parts.push(part);
38
+ }
39
+ /** 已加引号的字符串:先以码元数快速否决(UTF-8 字节 ≥ 码元数),再精确累计。 */
40
+ quoted(part, path) {
41
+ if (part.length > this.maxBytes - this.used)
42
+ this.fail('bytes_exceeded', `encoded bytes exceed maxBytes ${this.maxBytes}`, path);
43
+ this.used += utf8Length(part);
44
+ if (this.used > this.maxBytes)
45
+ this.fail('bytes_exceeded', `encoded bytes exceed maxBytes ${this.maxBytes}`, path);
46
+ this.parts.push(part);
47
+ }
48
+ number(value, path) {
49
+ if (!Number.isInteger(value))
50
+ this.fail('invalid_number', 'number must be an integer (no fraction, NaN or Infinity)', path);
51
+ if (!Number.isSafeInteger(value))
52
+ this.fail('unsafe_integer', 'integer exceeds 2^53-1', path);
53
+ if (value < 0 || Object.is(value, -0))
54
+ this.fail('invalid_number', 'number must be nonnegative (no -0)', path);
55
+ this.ascii(String(value), path);
56
+ }
57
+ string(value, path) {
58
+ if (!wellFormed(value))
59
+ this.fail('lone_surrogate', 'string contains an unpaired surrogate', path);
60
+ this.quoted(JSON.stringify(value), path);
61
+ }
62
+ dataDescriptor(target, key, path) {
63
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
64
+ if (descriptor === undefined || !Object.hasOwn(descriptor, 'value') || !descriptor.enumerable) {
65
+ this.fail('invalid_property', 'properties must be enumerable own data properties (no accessor / hole)', path);
66
+ }
67
+ return descriptor.value;
68
+ }
69
+ array(value, depth, path) {
70
+ // `length` 是不可枚举的自有数据属性:直接读描述符的值,不经访问器。
71
+ const length = Object.getOwnPropertyDescriptor(value, 'length')?.value;
72
+ if (typeof length !== 'number' || !Number.isSafeInteger(length))
73
+ this.fail('invalid_property', 'array length is not an integer', path);
74
+ // 每个元素至少一个节点:越界必然发生,提前否决,避免先遍历再失败。
75
+ if (this.nodes + length > this.maxNodes)
76
+ this.fail('nodes_exceeded', `node count exceeds maxNodes ${this.maxNodes}`, path);
77
+ const keys = Reflect.ownKeys(value);
78
+ if (keys.length !== length + 1)
79
+ this.fail('invalid_property', 'array must be dense without extra own properties', path);
80
+ this.ascii('[', path);
81
+ for (let index = 0; index < length; index++) {
82
+ const item = childPointer(path, index);
83
+ const element = this.dataDescriptor(value, String(index), item);
84
+ if (index > 0)
85
+ this.ascii(',', path);
86
+ this.write(element, depth + 1, item);
87
+ }
88
+ this.ascii(']', path);
89
+ }
90
+ object(value, depth, path) {
91
+ const prototype = Object.getPrototypeOf(value);
92
+ if (prototype !== Object.prototype && prototype !== null)
93
+ this.fail('unsupported_value', 'objects must be plain (Object.prototype or null prototype)', path);
94
+ const ownKeys = Reflect.ownKeys(value);
95
+ for (const key of ownKeys)
96
+ if (typeof key !== 'string')
97
+ this.fail('invalid_property', 'symbol keys are not representable', path);
98
+ const keys = ownKeys.sort();
99
+ this.ascii('{', path);
100
+ for (let index = 0; index < keys.length; index++) {
101
+ const key = keys[index];
102
+ const member = childPointer(path, key);
103
+ const element = this.dataDescriptor(value, key, member);
104
+ if (!CANONICAL_KEY_PATTERN.test(key))
105
+ this.fail('invalid_key', 'keys must be nonempty printable ASCII (0x21-0x7e)', member);
106
+ if (index > 0)
107
+ this.ascii(',', path);
108
+ this.ascii(JSON.stringify(key) + ':', member);
109
+ this.write(element, depth + 1, member);
110
+ }
111
+ this.ascii('}', path);
112
+ }
113
+ write(value, depth, path) {
114
+ if (depth > this.maxDepth)
115
+ this.fail('depth_exceeded', `nesting depth exceeds maxDepth ${this.maxDepth}`, path);
116
+ if (++this.nodes > this.maxNodes)
117
+ this.fail('nodes_exceeded', `node count exceeds maxNodes ${this.maxNodes}`, path);
118
+ if (value === null) {
119
+ this.ascii('null', path);
120
+ return;
121
+ }
122
+ switch (typeof value) {
123
+ case 'string':
124
+ this.string(value, path);
125
+ return;
126
+ case 'boolean':
127
+ this.ascii(value ? 'true' : 'false', path);
128
+ return;
129
+ case 'number':
130
+ this.number(value, path);
131
+ return;
132
+ case 'object': break;
133
+ default: this.fail('unsupported_value', `${typeof value} is not representable`, path);
134
+ }
135
+ const target = value;
136
+ if (this.isProxy !== null && this.isProxy(target))
137
+ this.fail('unsupported_value', 'Proxy objects are not representable', path);
138
+ if (this.ancestors.has(target))
139
+ this.fail('cyclic_reference', 'value contains itself', path);
140
+ this.ancestors.add(target);
141
+ if (Array.isArray(target))
142
+ this.array(target, depth, path);
143
+ else
144
+ this.object(target, depth, path);
145
+ this.ancestors.delete(target);
146
+ }
147
+ }
148
+ /** canonical 文本(UTF-16 字符串形态;与 `encodeCanonical` 同字节,供宿主内部比较免去编码 / 解码往返)。 */
149
+ export function encodeCanonicalText(value, options) {
150
+ const writer = new Writer(normalizeOptions(options, 'encode'));
151
+ writer.write(value, 0, '');
152
+ return writer.parts.join('');
153
+ }
154
+ /** canonical 字节(UTF-8 Uint8Array)。`options.maxBytes` 必填;`maxDepth` / `maxNodes` 只可收紧。 */
155
+ export function encodeCanonical(value, options) {
156
+ return encoder.encode(encodeCanonicalText(value, options));
157
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * canonical 单模块 — 统一错误对象与码表(RFC-UAPI-1 §4;D7 解冻迁入,UAPI-01 U3-PROTO)。
3
+ *
4
+ * 错误对象恒为 `{ code, path?, offset?, message }`(+ `reason?` 仅 `not_canonical`):
5
+ * - `code`:下表之一(稳定小码表;三份薄封装各自映射到既有消息 / 既有码);
6
+ * - `path`:RFC 6901 JSON Pointer(根 = `''`,`/a/0/b`),编码侧指向违规 JS 值,解码侧指向违规节点或其容器;
7
+ * - `offset`:仅解码侧;原始输入的 **UTF-8 字节偏移**(非 UTF-16 码元),跨语言实现可直接对照;
8
+ * - `reason`:仅 `not_canonical` 附带,`'whitespace' | 'key_order' | 'escape'`(首个违规的类别)。
9
+ *
10
+ * 零 Node 依赖:本文件只用 ECMAScript 内建。
11
+ */
12
+ /** 码表。解码侧 / 编码侧 / 双侧 见各行注释。 */
13
+ export declare const CANONICAL_ERROR_CODES: Readonly<{
14
+ /** 双侧:选项非法(maxBytes 缺失 / 非正安全整数、maxDepth > 32、maxNodes > 100000、未知选项、sha256 非函数…) */
15
+ readonly invalid_options: "invalid_options";
16
+ /** 解码侧:输入既非 Uint8Array 亦非 string;摘要侧:bytes 非 Uint8Array */
17
+ readonly invalid_input: "invalid_input";
18
+ /** 双侧:解码 = 原始输入字节 > maxBytes(先于 UTF-8 解码);编码 = 累计输出 UTF-8 字节 > maxBytes */
19
+ readonly bytes_exceeded: "bytes_exceeded";
20
+ /** 解码侧:非法 UTF-8(过长编码、截断、CESU-8 代理项、> U+10FFFF) */
21
+ readonly invalid_utf8: "invalid_utf8";
22
+ /** 解码侧:输入在值 / 字符串 / 字面量 / 转义中途结束(含空输入) */
23
+ readonly unexpected_end: "unexpected_end";
24
+ /** 解码侧:结构错误(非法起始字符、缺冒号 / 逗号、未引号键、大写字面量、NaN / Infinity、BOM、非 JSON 空白) */
25
+ readonly unexpected_token: "unexpected_token";
26
+ /** 解码侧:根值之后仍有非空白字节 */
27
+ readonly trailing_data: "trailing_data";
28
+ /** 双侧:数字 token 不是 `0 | [1-9][0-9]*`(-0、负数、+1、.5、1e3、1.0、01、0x10);编码 = 非整数 / 负数 / -0 / NaN / Infinity */
29
+ readonly invalid_number: "invalid_number";
30
+ /** 双侧:整数超过 2^53−1 */
31
+ readonly unsafe_integer: "unsafe_integer";
32
+ /** 解码侧:字符串词法错误(非法转义、`\u` 不足 4 位十六进制、未转义控制字符 < 0x20) */
33
+ readonly invalid_string: "invalid_string";
34
+ /** 双侧:孤立 / 颠倒 / 高后非低的代理项(转义或 JS 字符串内) */
35
+ readonly lone_surrogate: "lone_surrogate";
36
+ /** 双侧:键不是非空可打印 ASCII(`^[\x21-\x7e]+$`) */
37
+ readonly invalid_key: "invalid_key";
38
+ /** 解码侧:同一对象内解码后相同的键(含 `\u0061` 与 `a`、`__proto__` 重复) */
39
+ readonly duplicate_key: "duplicate_key";
40
+ /** 双侧:节点祖先容器数 > maxDepth(根 = 0) */
41
+ readonly depth_exceeded: "depth_exceeded";
42
+ /** 双侧:节点总数(含根、容器与标量;键不计)> maxNodes */
43
+ readonly nodes_exceeded: "nodes_exceeded";
44
+ /** 编码侧:JS 值不可表示(undefined / function / symbol / bigint / 非 plain 对象 / Proxy) */
45
+ readonly unsupported_value: "unsupported_value";
46
+ /** 编码侧:属性形态非法(accessor、不可枚举、Symbol 键、稀疏数组、length 与自有键不符) */
47
+ readonly invalid_property: "invalid_property";
48
+ /** 编码侧:同一对象出现在自己的祖先链上 */
49
+ readonly cyclic_reference: "cyclic_reference";
50
+ /** 仅 parseStrict:输入是合法可归一化文档,但字节 ≠ 其 canonical 字节(reason = whitespace / key_order / escape) */
51
+ readonly not_canonical: "not_canonical";
52
+ }>;
53
+ export type CanonicalErrorCode = keyof typeof CANONICAL_ERROR_CODES;
54
+ /** `not_canonical` 的首个违规类别 */
55
+ export declare const NOT_CANONICAL_REASONS: readonly ["whitespace", "key_order", "escape"];
56
+ export type NotCanonicalReason = (typeof NOT_CANONICAL_REASONS)[number];
57
+ export interface CanonicalErrorDetail {
58
+ readonly path?: string;
59
+ readonly offset?: number;
60
+ readonly reason?: NotCanonicalReason;
61
+ }
62
+ /** `toJSON()` 输出形:只含在场字段。 */
63
+ export interface CanonicalErrorJson {
64
+ readonly code: CanonicalErrorCode;
65
+ readonly message: string;
66
+ readonly path?: string;
67
+ readonly offset?: number;
68
+ readonly reason?: NotCanonicalReason;
69
+ }
70
+ /** 统一错误:`{ code, path?, offset?, message }`(+ `reason?` 仅 not_canonical);`toJSON()` 只输出这些字段。 */
71
+ export declare class CanonicalError extends Error {
72
+ readonly code: CanonicalErrorCode;
73
+ readonly path?: string;
74
+ readonly offset?: number;
75
+ readonly reason?: NotCanonicalReason;
76
+ constructor(code: CanonicalErrorCode, message: string, detail?: CanonicalErrorDetail);
77
+ toJSON(): CanonicalErrorJson;
78
+ }
79
+ /** RFC 6901:`~` → `~0`,`/` → `~1`;键已限定为可打印 ASCII,其余字符原样。 */
80
+ export declare function pointerSegment(key: string | number): string;
81
+ export declare function childPointer(parent: string, key: string | number): string;