streamseed 0.0.0-stage → 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 (57) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +117 -2
  3. package/dist/control/control.d.ts +89 -0
  4. package/dist/control/control.js +396 -0
  5. package/dist/index.d.ts +19 -0
  6. package/dist/index.js +15 -0
  7. package/dist/internal/abort.d.ts +8 -0
  8. package/dist/internal/abort.js +52 -0
  9. package/dist/internal/cbor-codec.d.ts +25 -0
  10. package/dist/internal/cbor-codec.js +134 -0
  11. package/dist/internal/ed25519.d.ts +15 -0
  12. package/dist/internal/ed25519.js +55 -0
  13. package/dist/internal/secp256k1.d.ts +3 -0
  14. package/dist/internal/secp256k1.js +15 -0
  15. package/dist/manifest/cbor.d.ts +54 -0
  16. package/dist/manifest/cbor.js +306 -0
  17. package/dist/manifest/codec.d.ts +6 -0
  18. package/dist/manifest/codec.js +360 -0
  19. package/dist/manifest/constants.d.ts +2 -0
  20. package/dist/manifest/constants.js +2 -0
  21. package/dist/manifest/errors.d.ts +20 -0
  22. package/dist/manifest/errors.js +23 -0
  23. package/dist/manifest/index.d.ts +6 -0
  24. package/dist/manifest/index.js +6 -0
  25. package/dist/manifest/language.d.ts +4 -0
  26. package/dist/manifest/language.js +26 -0
  27. package/dist/manifest/types.d.ts +73 -0
  28. package/dist/manifest/types.js +2 -0
  29. package/dist/node/codec.d.ts +23 -0
  30. package/dist/node/codec.js +231 -0
  31. package/dist/node/document.d.ts +10 -0
  32. package/dist/node/document.js +123 -0
  33. package/dist/node/media.d.ts +6 -0
  34. package/dist/node/media.js +69 -0
  35. package/dist/node/sequence.d.ts +44 -0
  36. package/dist/node/sequence.js +137 -0
  37. package/dist/node/types.d.ts +93 -0
  38. package/dist/node/types.js +105 -0
  39. package/dist/program/codec.d.ts +10 -0
  40. package/dist/program/codec.js +165 -0
  41. package/dist/program/resolver.d.ts +25 -0
  42. package/dist/program/resolver.js +189 -0
  43. package/dist/program/types.d.ts +61 -0
  44. package/dist/program/types.js +90 -0
  45. package/dist/protocol/constants.d.ts +33 -0
  46. package/dist/protocol/constants.js +32 -0
  47. package/dist/protocol/errors.d.ts +46 -0
  48. package/dist/protocol/errors.js +57 -0
  49. package/dist/protocol/hash.d.ts +14 -0
  50. package/dist/protocol/hash.js +42 -0
  51. package/dist/protocol/ids.d.ts +60 -0
  52. package/dist/protocol/ids.js +139 -0
  53. package/dist/wire/artifact.d.ts +28 -0
  54. package/dist/wire/artifact.js +74 -0
  55. package/dist/wire/codec.d.ts +12 -0
  56. package/dist/wire/codec.js +42 -0
  57. package/package.json +92 -3
@@ -0,0 +1,52 @@
1
+ import { ERROR_CODES, streamSeedError } from "../protocol/errors.js";
2
+ /**
3
+ * 等待可取消的异步操作。
4
+ *
5
+ * AbortSignal 不能强制终止外部 Promise 的执行,但可以让 SDK 的等待方立即结束;
6
+ * 调用方若拥有底层资源,还应在 abort 监听器中主动关闭该资源。
7
+ */
8
+ export function awaitWithAbort(promise, signal) {
9
+ const pending = Promise.resolve(promise);
10
+ if (signal === undefined)
11
+ return pending;
12
+ if (signal.aborted) {
13
+ pending.catch(() => undefined);
14
+ return Promise.reject(cancelled(signal));
15
+ }
16
+ return new Promise((resolve, reject) => {
17
+ let settled = false;
18
+ const cleanup = () => {
19
+ signal.removeEventListener("abort", onAbort);
20
+ };
21
+ const onAbort = () => {
22
+ if (settled)
23
+ return;
24
+ settled = true;
25
+ cleanup();
26
+ reject(cancelled(signal));
27
+ };
28
+ signal.addEventListener("abort", onAbort, { once: true });
29
+ if (signal.aborted) {
30
+ onAbort();
31
+ pending.catch(() => undefined);
32
+ return;
33
+ }
34
+ pending.then((value) => {
35
+ if (settled)
36
+ return;
37
+ settled = true;
38
+ cleanup();
39
+ resolve(value);
40
+ }, (error) => {
41
+ if (settled)
42
+ return;
43
+ settled = true;
44
+ cleanup();
45
+ reject(error);
46
+ });
47
+ });
48
+ }
49
+ function cancelled(signal) {
50
+ return streamSeedError(ERROR_CODES.CANCELLED, "operation was aborted", signal.reason);
51
+ }
52
+ //# sourceMappingURL=abort.js.map
@@ -0,0 +1,25 @@
1
+ /** 只提供 V1 所需的 RFC 8949 core deterministic CBOR 原子操作。 */
2
+ export declare class CBOREncoder {
3
+ private readonly data;
4
+ array(length: number): void;
5
+ uint(value: bigint): void;
6
+ bytes(value: Uint8Array): void;
7
+ text(value: string): void;
8
+ raw(value: Uint8Array): void;
9
+ finish(): Uint8Array;
10
+ private head;
11
+ }
12
+ export declare class CBORDecoder {
13
+ private readonly data;
14
+ private readonly maxItem;
15
+ private offset;
16
+ constructor(data: Uint8Array, maxItem: bigint);
17
+ array(): number;
18
+ uint(): bigint;
19
+ bytes(requestedMax?: number): Uint8Array;
20
+ text(requestedMax?: number): string;
21
+ requireEOF(): void;
22
+ private head;
23
+ private stringBytes;
24
+ }
25
+ //# sourceMappingURL=cbor-codec.d.ts.map
@@ -0,0 +1,134 @@
1
+ import { streamSeedError, ERROR_CODES } from "../protocol/errors.js";
2
+ /** 只提供 V1 所需的 RFC 8949 core deterministic CBOR 原子操作。 */
3
+ export class CBOREncoder {
4
+ data = [];
5
+ array(length) {
6
+ if (!Number.isSafeInteger(length) || length < 0)
7
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, "invalid array length");
8
+ this.head(4, BigInt(length));
9
+ }
10
+ uint(value) {
11
+ if (value < 0n || value > 0xffffffffffffffffn)
12
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, "uint is outside uint64");
13
+ this.head(0, value);
14
+ }
15
+ bytes(value) {
16
+ this.head(2, BigInt(value.length));
17
+ for (const byte of value)
18
+ this.data.push(byte);
19
+ }
20
+ text(value) {
21
+ const encoded = new TextEncoder().encode(value);
22
+ this.head(3, BigInt(encoded.length));
23
+ for (const byte of encoded)
24
+ this.data.push(byte);
25
+ }
26
+ raw(value) {
27
+ for (const byte of value)
28
+ this.data.push(byte);
29
+ }
30
+ finish() { return new Uint8Array(this.data); }
31
+ head(major, value) {
32
+ if (value < 24n) {
33
+ this.data.push((major << 5) | Number(value));
34
+ }
35
+ else if (value <= 0xffn) {
36
+ this.data.push((major << 5) | 24, Number(value));
37
+ }
38
+ else if (value <= 0xffffn) {
39
+ this.data.push((major << 5) | 25, Number(value >> 8n), Number(value & 0xffn));
40
+ }
41
+ else if (value <= 0xffffffffn) {
42
+ this.data.push((major << 5) | 26);
43
+ for (let shift = 24n; shift >= 0n; shift -= 8n)
44
+ this.data.push(Number((value >> shift) & 0xffn));
45
+ }
46
+ else {
47
+ this.data.push((major << 5) | 27);
48
+ for (let shift = 56n; shift >= 0n; shift -= 8n)
49
+ this.data.push(Number((value >> shift) & 0xffn));
50
+ }
51
+ }
52
+ }
53
+ export class CBORDecoder {
54
+ data;
55
+ maxItem;
56
+ offset = 0;
57
+ constructor(data, maxItem) {
58
+ this.data = data;
59
+ this.maxItem = maxItem;
60
+ }
61
+ array() {
62
+ const { major, value } = this.head();
63
+ if (major !== 4)
64
+ throw streamSeedError(ERROR_CODES.INVALID_CBOR, `expected array, got major type ${major}`);
65
+ if (value > BigInt(Number.MAX_SAFE_INTEGER))
66
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, "array length is not safe");
67
+ return Number(value);
68
+ }
69
+ uint() {
70
+ const { major, value } = this.head();
71
+ if (major !== 0)
72
+ throw streamSeedError(ERROR_CODES.INVALID_CBOR, `expected uint, got major type ${major}`);
73
+ return value;
74
+ }
75
+ bytes(requestedMax = 0) {
76
+ const { major, value } = this.head();
77
+ if (major !== 2)
78
+ throw streamSeedError(ERROR_CODES.INVALID_CBOR, `expected byte string, got major type ${major}`);
79
+ return this.stringBytes(value, requestedMax);
80
+ }
81
+ text(requestedMax = 0) {
82
+ const { major, value } = this.head();
83
+ if (major !== 3)
84
+ throw streamSeedError(ERROR_CODES.INVALID_CBOR, `expected text string, got major type ${major}`);
85
+ const bytes = this.stringBytes(value, requestedMax);
86
+ try {
87
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
88
+ }
89
+ catch (error) {
90
+ throw streamSeedError(ERROR_CODES.INVALID_UTF8, "text string is not valid UTF-8", error);
91
+ }
92
+ }
93
+ requireEOF() {
94
+ if (this.offset !== this.data.length)
95
+ throw streamSeedError(ERROR_CODES.TRAILING_DATA, `${this.data.length - this.offset} trailing bytes`);
96
+ }
97
+ head() {
98
+ const first = this.data[this.offset++];
99
+ if (first === undefined)
100
+ throw streamSeedError(ERROR_CODES.INVALID_CBOR, "unexpected end of input");
101
+ const major = first >> 5;
102
+ const additional = first & 0x1f;
103
+ if (additional < 24)
104
+ return { major, value: BigInt(additional) };
105
+ if (additional === 31)
106
+ throw streamSeedError(ERROR_CODES.NON_CANONICAL_CBOR, "indefinite-length item is forbidden");
107
+ if (additional !== 24 && additional !== 25 && additional !== 26 && additional !== 27) {
108
+ throw streamSeedError(ERROR_CODES.INVALID_CBOR, "reserved CBOR additional information");
109
+ }
110
+ const count = 1 << (additional - 24);
111
+ if (this.offset + count > this.data.length)
112
+ throw streamSeedError(ERROR_CODES.INVALID_CBOR, "truncated CBOR argument");
113
+ let value = 0n;
114
+ for (let index = 0; index < count; index += 1)
115
+ value = (value << 8n) | BigInt(this.data[this.offset++]);
116
+ const shortest = additional === 24 ? 24n : additional === 25 ? 0x100n : additional === 26 ? 0x10000n : 0x100000000n;
117
+ if (value < shortest)
118
+ throw streamSeedError(ERROR_CODES.NON_CANONICAL_CBOR, "non-shortest CBOR argument");
119
+ return { major, value };
120
+ }
121
+ stringBytes(length, requestedMax) {
122
+ const requested = requestedMax > 0 ? BigInt(requestedMax) : 0n;
123
+ const limit = this.maxItem === 0n ? requested : requested === 0n || this.maxItem < requested ? this.maxItem : requested;
124
+ if (limit !== 0n && length > limit)
125
+ throw streamSeedError(ERROR_CODES.FIELD_TOO_LARGE, `item length ${length} exceeds ${limit}`);
126
+ if (length > BigInt(this.data.length - this.offset))
127
+ throw streamSeedError(ERROR_CODES.INVALID_CBOR, "truncated string or byte string");
128
+ const size = Number(length);
129
+ const output = this.data.slice(this.offset, this.offset + size);
130
+ this.offset += size;
131
+ return output;
132
+ }
133
+ }
134
+ //# sourceMappingURL=cbor-codec.js.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 严格检查 Ed25519 公钥编码。
3
+ *
4
+ * `zip215=false` 对齐 RFC 8032 / FIPS 186-5 风格的规范编码;另外拒绝小阶点,
5
+ * 使 ProgramInfo 和 NodeDocument 的发布者身份不能使用模糊的低阶点表示。
6
+ */
7
+ export declare function isValidPublicKey(value: Uint8Array): boolean;
8
+ /** 严格检查 R 点编码、小阶 R 以及 S < L。 */
9
+ export declare function isValidSignatureEncoding(value: Uint8Array): boolean;
10
+ /**
11
+ * 使用成熟密码库验证严格 Ed25519 签名。
12
+ * 此发布模块不执行私钥运算;调用方仍应先通过 isValidSignatureEncoding。
13
+ */
14
+ export declare function verifyEd25519(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): boolean;
15
+ //# sourceMappingURL=ed25519.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { ed25519 } from "@noble/curves/ed25519.js";
2
+ const ED25519_POINT_SIZE = 32;
3
+ const ED25519_SIGNATURE_SIZE = 64;
4
+ /**
5
+ * 严格检查 Ed25519 公钥编码。
6
+ *
7
+ * `zip215=false` 对齐 RFC 8032 / FIPS 186-5 风格的规范编码;另外拒绝小阶点,
8
+ * 使 ProgramInfo 和 NodeDocument 的发布者身份不能使用模糊的低阶点表示。
9
+ */
10
+ export function isValidPublicKey(value) {
11
+ if (value.length !== ED25519_POINT_SIZE)
12
+ return false;
13
+ try {
14
+ const point = ed25519.Point.fromBytes(value, false);
15
+ return !point.isSmallOrder();
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
21
+ /** 严格检查 R 点编码、小阶 R 以及 S < L。 */
22
+ export function isValidSignatureEncoding(value) {
23
+ if (value.length !== ED25519_SIGNATURE_SIZE)
24
+ return false;
25
+ try {
26
+ const r = ed25519.Point.fromBytes(value.subarray(0, ED25519_POINT_SIZE), false);
27
+ const s = littleEndianToBigInt(value.subarray(ED25519_POINT_SIZE));
28
+ return !r.isSmallOrder() && s < ed25519.Point.Fn.ORDER;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ /**
35
+ * 使用成熟密码库验证严格 Ed25519 签名。
36
+ * 此发布模块不执行私钥运算;调用方仍应先通过 isValidSignatureEncoding。
37
+ */
38
+ export function verifyEd25519(publicKey, message, signature) {
39
+ if (!isValidPublicKey(publicKey) || !isValidSignatureEncoding(signature))
40
+ return false;
41
+ try {
42
+ return ed25519.verify(signature, message, publicKey, { zip215: false });
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ function littleEndianToBigInt(value) {
49
+ let result = 0n;
50
+ for (let index = value.length - 1; index >= 0; index -= 1) {
51
+ result = (result << 8n) | BigInt(value[index] ?? 0);
52
+ }
53
+ return result;
54
+ }
55
+ //# sourceMappingURL=ed25519.js.map
@@ -0,0 +1,3 @@
1
+ /** Validate a canonical compressed secp256k1 public-key encoding. */
2
+ export declare function isValidCompressedPublicKey(value: Uint8Array): boolean;
3
+ //# sourceMappingURL=secp256k1.d.ts.map
@@ -0,0 +1,15 @@
1
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
2
+ /** Validate a canonical compressed secp256k1 public-key encoding. */
3
+ export function isValidCompressedPublicKey(value) {
4
+ if (value.length !== 33 || (value[0] !== 0x02 && value[0] !== 0x03))
5
+ return false;
6
+ try {
7
+ const hex = Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("");
8
+ secp256k1.Point.fromHex(hex).assertValidity();
9
+ return true;
10
+ }
11
+ catch {
12
+ return false;
13
+ }
14
+ }
15
+ //# sourceMappingURL=secp256k1.js.map
@@ -0,0 +1,54 @@
1
+ export type CborValue = {
2
+ kind: "uint";
3
+ value: bigint;
4
+ } | {
5
+ kind: "negative";
6
+ value: bigint;
7
+ } | {
8
+ kind: "bytes";
9
+ value: Uint8Array;
10
+ } | {
11
+ kind: "text";
12
+ value: string;
13
+ } | {
14
+ kind: "array";
15
+ value: CborValue[];
16
+ indefinite: boolean;
17
+ declared: bigint;
18
+ } | {
19
+ kind: "map";
20
+ value: CborMap;
21
+ indefinite: boolean;
22
+ declared: bigint;
23
+ } | {
24
+ kind: "other";
25
+ };
26
+ export interface CborMapEntry {
27
+ key: string;
28
+ keyBytes: Uint8Array;
29
+ value: CborValue;
30
+ }
31
+ export interface CborMap {
32
+ entries: CborMapEntry[];
33
+ index: Map<string, number>;
34
+ }
35
+ export declare function pointerChild(path: string, segment: string): string;
36
+ export declare function parseCBORDocument(bytes: Uint8Array): {
37
+ root: CborValue;
38
+ nonCanonical: boolean;
39
+ };
40
+ export declare function canonicalCBOR(value: CborValue): Uint8Array;
41
+ export declare function cborMapValue(object: Map<string, CborValue>): Extract<CborValue, {
42
+ kind: "map";
43
+ }>;
44
+ export declare function cborTextValue(value: string): Extract<CborValue, {
45
+ kind: "text";
46
+ }>;
47
+ export declare function cborUintValue(value: bigint): Extract<CborValue, {
48
+ kind: "uint";
49
+ }>;
50
+ export declare function cborModelInteger(value: number): CborValue;
51
+ export declare function cborBytesValue(value: Uint8Array): Extract<CborValue, {
52
+ kind: "bytes";
53
+ }>;
54
+ //# sourceMappingURL=cbor.d.ts.map
@@ -0,0 +1,306 @@
1
+ import { PROGRAM_MANIFEST_ERROR_CODES, ProgramManifestError } from "./errors.js";
2
+ function childPath(parent, segment) {
3
+ return { parent, segment };
4
+ }
5
+ function renderPath(node) {
6
+ const segments = [];
7
+ for (let current = node; current !== undefined; current = current.parent)
8
+ segments.push(current.segment);
9
+ return segments.reverse().map((segment) => `/${segment.replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
10
+ }
11
+ export function pointerChild(path, segment) {
12
+ return `${path}/${segment.replaceAll("~", "~0").replaceAll("/", "~1")}`;
13
+ }
14
+ function newFrame(value, path) {
15
+ return {
16
+ value, path, state: 0, indefinite: value.indefinite, remaining: value.declared,
17
+ pendingKey: "", pendingKeyBytes: new Uint8Array(), previousKeyBytes: undefined, index: 0
18
+ };
19
+ }
20
+ class CborParser {
21
+ data;
22
+ offset = 0;
23
+ nonCanonical = false;
24
+ constructor(data) {
25
+ this.data = data;
26
+ }
27
+ parseDocument() {
28
+ if (this.data.length === 0)
29
+ this.fail("", "empty CBOR document");
30
+ const root = this.readValue(undefined);
31
+ const stack = [];
32
+ if (root.kind === "array" || root.kind === "map")
33
+ stack.push(newFrame(root, undefined));
34
+ while (stack.length > 0) {
35
+ const top = stack[stack.length - 1];
36
+ if (top.value.kind === "array") {
37
+ if (top.indefinite) {
38
+ if (this.takeBreak()) {
39
+ stack.pop();
40
+ continue;
41
+ }
42
+ }
43
+ else if (top.remaining === 0n) {
44
+ stack.pop();
45
+ continue;
46
+ }
47
+ const path = childPath(top.path, String(top.index));
48
+ const child = this.readValue(path);
49
+ top.value.value.push(child);
50
+ top.index += 1;
51
+ if (!top.indefinite)
52
+ top.remaining -= 1n;
53
+ if (child.kind === "array" || child.kind === "map")
54
+ stack.push(newFrame(child, path));
55
+ continue;
56
+ }
57
+ if (top.state === 0) {
58
+ if (top.indefinite) {
59
+ if (this.takeBreak()) {
60
+ stack.pop();
61
+ continue;
62
+ }
63
+ }
64
+ else if (top.remaining === 0n) {
65
+ stack.pop();
66
+ continue;
67
+ }
68
+ const keyValue = this.readValue(top.path);
69
+ if (keyValue.kind !== "text")
70
+ this.fail(renderPath(top.path), "CBOR map keys must be text strings");
71
+ const keyBytes = canonicalCBOR(keyValue);
72
+ const keyPath = childPath(top.path, keyValue.value);
73
+ if (top.value.value.index.has(keyValue.value))
74
+ this.fail(renderPath(keyPath), "duplicate CBOR map key");
75
+ if (top.previousKeyBytes !== undefined && bytesCompare(top.previousKeyBytes, keyBytes) > 0)
76
+ this.nonCanonical = true;
77
+ top.pendingKey = keyValue.value;
78
+ top.pendingKeyBytes = keyBytes;
79
+ top.previousKeyBytes = keyBytes;
80
+ top.state = 1;
81
+ continue;
82
+ }
83
+ const path = childPath(top.path, top.pendingKey);
84
+ const child = this.readValue(path);
85
+ top.value.value.index.set(top.pendingKey, top.value.value.entries.length);
86
+ top.value.value.entries.push({ key: top.pendingKey, keyBytes: top.pendingKeyBytes, value: child });
87
+ top.pendingKey = "";
88
+ top.pendingKeyBytes = new Uint8Array();
89
+ top.state = 0;
90
+ if (!top.indefinite)
91
+ top.remaining -= 1n;
92
+ if (child.kind === "array" || child.kind === "map")
93
+ stack.push(newFrame(child, path));
94
+ }
95
+ if (this.offset !== this.data.length)
96
+ this.fail("", "trailing bytes after root CBOR value");
97
+ return { root, nonCanonical: this.nonCanonical };
98
+ }
99
+ readValue(path) {
100
+ const { major, argument, indefinite } = this.readHead(path);
101
+ switch (major) {
102
+ case 0: return { kind: "uint", value: argument };
103
+ case 1: return { kind: "negative", value: argument };
104
+ case 2:
105
+ if (indefinite) {
106
+ this.nonCanonical = true;
107
+ return { kind: "bytes", value: this.readIndefiniteString(path, false) };
108
+ }
109
+ return { kind: "bytes", value: this.readStringBytes(argument, path) };
110
+ case 3:
111
+ if (indefinite) {
112
+ this.nonCanonical = true;
113
+ return { kind: "text", value: this.decodeText(this.readIndefiniteString(path, true), path) };
114
+ }
115
+ return { kind: "text", value: this.decodeText(this.readStringBytes(argument, path), path) };
116
+ case 4:
117
+ if (indefinite)
118
+ this.nonCanonical = true;
119
+ return { kind: "array", value: [], indefinite, declared: argument };
120
+ case 5:
121
+ if (indefinite)
122
+ this.nonCanonical = true;
123
+ return { kind: "map", value: { entries: [], index: new Map() }, indefinite, declared: argument };
124
+ case 6: this.fail(renderPath(path), "CBOR tags are not allowed");
125
+ case 7:
126
+ if (indefinite)
127
+ this.fail(renderPath(path), "unexpected CBOR break");
128
+ return { kind: "other" };
129
+ default: this.fail(renderPath(path), "unsupported CBOR major type");
130
+ }
131
+ }
132
+ readHead(path) {
133
+ const first = this.data[this.offset++];
134
+ if (first === undefined)
135
+ this.fail(renderPath(path), "unexpected end of input");
136
+ const major = first >> 5;
137
+ const additional = first & 0x1f;
138
+ if (additional < 24)
139
+ return { major, argument: BigInt(additional), indefinite: false };
140
+ if (additional === 31) {
141
+ if (major < 2 || major > 5)
142
+ this.fail(renderPath(path), "indefinite-length header is only valid for byte strings, text strings, arrays and maps");
143
+ return { major, argument: 0n, indefinite: true };
144
+ }
145
+ if (additional !== 24 && additional !== 25 && additional !== 26 && additional !== 27) {
146
+ this.fail(renderPath(path), "reserved CBOR additional information");
147
+ }
148
+ const count = 1 << (additional - 24);
149
+ if (this.offset + count > this.data.length)
150
+ this.fail(renderPath(path), "truncated CBOR argument");
151
+ let argument = 0n;
152
+ for (let index = 0; index < count; index += 1)
153
+ argument = (argument << 8n) | BigInt(this.data[this.offset++]);
154
+ const shortest = additional === 24 ? 24n : additional === 25 ? 0x100n : additional === 26 ? 0x10000n : 0x100000000n;
155
+ if ((major !== 7 && argument < shortest) || (major === 7 && additional === 24 && argument < 24n))
156
+ this.nonCanonical = true;
157
+ return { major, argument, indefinite: false };
158
+ }
159
+ readStringBytes(length, path) {
160
+ if (length > BigInt(this.data.length - this.offset))
161
+ this.fail(renderPath(path), "truncated CBOR byte or text string");
162
+ const size = Number(length);
163
+ const output = this.data.slice(this.offset, this.offset + size);
164
+ this.offset += size;
165
+ return output;
166
+ }
167
+ readIndefiniteString(path, text) {
168
+ const chunks = [];
169
+ while (true) {
170
+ if (this.offset >= this.data.length)
171
+ this.fail(renderPath(path), "unterminated indefinite CBOR string");
172
+ if (this.takeBreak())
173
+ break;
174
+ const { major, argument, indefinite } = this.readHead(path);
175
+ const expected = text ? 3 : 2;
176
+ if (major !== expected || indefinite)
177
+ this.fail(renderPath(path), "invalid indefinite CBOR string chunk");
178
+ const chunk = this.readStringBytes(argument, path);
179
+ if (text)
180
+ this.decodeText(chunk, path);
181
+ chunks.push(chunk);
182
+ }
183
+ const output = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
184
+ let offset = 0;
185
+ for (const chunk of chunks) {
186
+ output.set(chunk, offset);
187
+ offset += chunk.length;
188
+ }
189
+ return output;
190
+ }
191
+ decodeText(bytes, path) {
192
+ try {
193
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
194
+ }
195
+ catch (cause) {
196
+ throw new ProgramManifestError(PROGRAM_MANIFEST_ERROR_CODES.INVALID_CBOR, renderPath(path), "CBOR text string is not valid UTF-8", { cause });
197
+ }
198
+ }
199
+ takeBreak() {
200
+ if (this.data[this.offset] !== 0xff)
201
+ return false;
202
+ this.offset += 1;
203
+ return true;
204
+ }
205
+ fail(path, message) {
206
+ throw new ProgramManifestError(PROGRAM_MANIFEST_ERROR_CODES.INVALID_CBOR, path, message);
207
+ }
208
+ }
209
+ export function parseCBORDocument(bytes) {
210
+ return new CborParser(bytes).parseDocument();
211
+ }
212
+ export function canonicalCBOR(value) {
213
+ const output = [];
214
+ appendCanonicalCBOR(value, output);
215
+ return Uint8Array.from(output);
216
+ }
217
+ function appendCanonicalCBOR(value, output) {
218
+ switch (value.kind) {
219
+ case "uint":
220
+ appendHead(output, 0, value.value);
221
+ return;
222
+ case "bytes":
223
+ appendHead(output, 2, BigInt(value.value.length));
224
+ for (const byte of value.value)
225
+ output.push(byte);
226
+ return;
227
+ case "text": {
228
+ const encoded = new TextEncoder().encode(value.value);
229
+ appendHead(output, 3, BigInt(encoded.length));
230
+ for (const byte of encoded)
231
+ output.push(byte);
232
+ return;
233
+ }
234
+ case "array":
235
+ appendHead(output, 4, BigInt(value.value.length));
236
+ for (const child of value.value)
237
+ appendCanonicalCBOR(child, output);
238
+ return;
239
+ case "map": {
240
+ const entries = [...value.value.entries].sort((left, right) => bytesCompare(left.keyBytes, right.keyBytes));
241
+ appendHead(output, 5, BigInt(entries.length));
242
+ for (const entry of entries) {
243
+ for (const byte of entry.keyBytes)
244
+ output.push(byte);
245
+ appendCanonicalCBOR(entry.value, output);
246
+ }
247
+ return;
248
+ }
249
+ case "negative":
250
+ case "other": return;
251
+ }
252
+ }
253
+ function appendHead(output, major, value) {
254
+ if (value < 24n)
255
+ output.push((major << 5) | Number(value));
256
+ else if (value <= 0xffn)
257
+ output.push((major << 5) | 24, Number(value));
258
+ else if (value <= 0xffffn)
259
+ output.push((major << 5) | 25, Number(value >> 8n), Number(value & 0xffn));
260
+ else if (value <= 0xffffffffn) {
261
+ output.push((major << 5) | 26);
262
+ for (let shift = 24n; shift >= 0n; shift -= 8n)
263
+ output.push(Number((value >> shift) & 0xffn));
264
+ }
265
+ else {
266
+ output.push((major << 5) | 27);
267
+ for (let shift = 56n; shift >= 0n; shift -= 8n)
268
+ output.push(Number((value >> shift) & 0xffn));
269
+ }
270
+ }
271
+ function bytesCompare(left, right) {
272
+ const length = Math.min(left.length, right.length);
273
+ for (let index = 0; index < length; index += 1) {
274
+ if (left[index] !== right[index])
275
+ return left[index] < right[index] ? -1 : 1;
276
+ }
277
+ return left.length - right.length;
278
+ }
279
+ export function cborMapValue(object) {
280
+ const value = {
281
+ kind: "map", value: { entries: [], index: new Map() }, indefinite: false, declared: 0n
282
+ };
283
+ for (const [key, child] of object) {
284
+ const keyBytes = canonicalCBOR(cborTextValue(key));
285
+ value.value.index.set(key, value.value.entries.length);
286
+ value.value.entries.push({ key, keyBytes, value: child });
287
+ }
288
+ return value;
289
+ }
290
+ export function cborTextValue(value) {
291
+ return { kind: "text", value };
292
+ }
293
+ export function cborUintValue(value) {
294
+ return { kind: "uint", value };
295
+ }
296
+ export function cborModelInteger(value) {
297
+ if (!Number.isSafeInteger(value))
298
+ return { kind: "other" };
299
+ if (value < 0)
300
+ return { kind: "negative", value: BigInt(-(value + 1)) + 1n };
301
+ return cborUintValue(BigInt(value));
302
+ }
303
+ export function cborBytesValue(value) {
304
+ return { kind: "bytes", value: value.slice() };
305
+ }
306
+ //# sourceMappingURL=cbor.js.map
@@ -0,0 +1,6 @@
1
+ import type { ProgramManifest } from "./types.js";
2
+ /** 验证模型并返回确定性 CBOR 字节。 */
3
+ export declare function encodeProgramManifest(manifest: ProgramManifest): Uint8Array;
4
+ /** 严格验证原字节并返回已验证的静态或直播节目单。 */
5
+ export declare function decodeProgramManifest(bytes: Uint8Array): ProgramManifest;
6
+ //# sourceMappingURL=codec.d.ts.map