@sharedcontext/sdk 0.0.0-stage → 0.3.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 (36) hide show
  1. package/LICENSE-APACHE +201 -0
  2. package/LICENSE-MIT +21 -0
  3. package/NOTICE +8 -0
  4. package/README.md +94 -2
  5. package/dist/canonical.d.ts +47 -0
  6. package/dist/canonical.js +257 -0
  7. package/dist/client.d.ts +96 -0
  8. package/dist/client.js +205 -0
  9. package/dist/constants.d.ts +19 -0
  10. package/dist/constants.js +21 -0
  11. package/dist/event.d.ts +104 -0
  12. package/dist/event.js +173 -0
  13. package/dist/generated/content.d.ts +588 -0
  14. package/dist/generated/content.js +3 -0
  15. package/dist/generated/schemas.d.ts +10 -0
  16. package/dist/generated/schemas.js +22 -0
  17. package/dist/index.d.ts +8 -0
  18. package/dist/index.js +8 -0
  19. package/dist/reasons.d.ts +14 -0
  20. package/dist/reasons.js +142 -0
  21. package/dist/schema.d.ts +45 -0
  22. package/dist/schema.js +285 -0
  23. package/dist/types.d.ts +230 -0
  24. package/dist/types.js +3 -0
  25. package/package.json +46 -4
  26. package/schemas/sharedcontext-1/changes.schema.json +128 -0
  27. package/schemas/sharedcontext-1/content.schema.json +2076 -0
  28. package/schemas/sharedcontext-1/context.schema.json +218 -0
  29. package/schemas/sharedcontext-1/event.schema.json +55 -0
  30. package/schemas/sharedcontext-1/execution.schema.json +342 -0
  31. package/schemas/sharedcontext-1/history/content-1.0.schema.json +1915 -0
  32. package/schemas/sharedcontext-1/lineage.schema.json +753 -0
  33. package/schemas/sharedcontext-1/mcp-tools.schema.json +1357 -0
  34. package/schemas/sharedcontext-1/stored-event.schema.json +14 -0
  35. package/schemas/sharedcontext-directory-1/members.schema.json +52 -0
  36. package/schemas/sharedcontext-directory-1/memberships.schema.json +32 -0
package/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 The sharedcontext authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The sharedcontext authors
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/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ sharedcontext
2
+ Copyright 2026 Cognium and the sharedcontext contributors.
3
+
4
+ Licensed under either of the Apache License, Version 2.0 (LICENSE-APACHE) or the MIT license
5
+ (LICENSE-MIT), at your option.
6
+
7
+ This product includes software developed by the sharedcontext contributors. The package has no
8
+ runtime dependencies.
package/README.md CHANGED
@@ -1,3 +1,95 @@
1
- # Temporary Holding Version
1
+ # @sharedcontext/sdk
2
2
 
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.
3
+ The `sharedcontext/1` work contract for JavaScript and TypeScript: what a client of a sharedcontext
4
+ service needs to write and read work items without holding the logic twice.
5
+
6
+ - **The contract's JSON Schemas**, shipped as files (`@sharedcontext/sdk/schemas/<file>`), and a
7
+ `validate(schema, value)` that checks a value against any of them (draft 2020-12, only the
8
+ keywords the contract uses). It throws for a schema file or fragment the package does not have.
9
+ - **The directory contract's JSON Schemas** (`sharedcontext-directory/1`, a directory's two HTTP
10
+ pages: `@sharedcontext/sdk/schemas/directory/<file>`), so a directory server written in
11
+ JavaScript can check what it serves:
12
+ `validate("sharedcontext-directory-1/members.schema.json", page)`.
13
+ - **TypeScript types** for the content of every event type (generated from
14
+ `content.schema.json`), for the signed envelope and for the MCP tools' arguments and results.
15
+ - **Event helpers**: the core's canonical JSON, the unsigned event template, the NIP-01 id, and the
16
+ core's envelope check. Signing goes through a `SharedcontextSigner` port: the package never holds
17
+ a key.
18
+ - **A small MCP client** for the service's `/mcp` (streamable HTTP, stateless JSON): `submit` and
19
+ `write`, `state`, `context`, `subscribe`, `changes`, `next`, `claimNext`, `draft`, `close`,
20
+ `stats`, `listTools`, `nodeEvents`, and `call` for any other tool.
21
+
22
+ An ES module (`import`) with no runtime dependencies. It runs on Node 20 and later, in browsers,
23
+ Deno, Bun and Cloudflare Workers: hashing is Web Crypto, the schemas are embedded (no file system),
24
+ and the types need neither DOM nor Node typings.
25
+
26
+ ## Use
27
+
28
+ ```sh
29
+ npm install @sharedcontext/sdk
30
+ ```
31
+
32
+ ```ts
33
+ import { SharedcontextClient, eventTemplate, type SharedcontextSigner } from "@sharedcontext/sdk";
34
+
35
+ const client = new SharedcontextClient({ baseUrl: "https://work.example.com", token });
36
+
37
+ // the caller's signer holds the key (a remote signer, a NIP-46 bunker, a local key in tests)
38
+ const signer: SharedcontextSigner = mySigner;
39
+
40
+ const t = eventTemplate({
41
+ pubkey: signer.pubkey,
42
+ createdAt: Math.floor(Date.now() / 1000),
43
+ type: "node.created",
44
+ project: "pj_…",
45
+ clientId: "create-task-42", // idempotency: an exact resend answers the first append
46
+ node: "tk_42",
47
+ content: { kind: "task", title: "Rotate the staging key", labels: ["ops"] },
48
+ });
49
+ const { seq } = await client.write(signer, t); // signs, checks the signer answered this template, submits
50
+
51
+ const view = await client.state("tk_42"); // the node folded, or null
52
+ const page = await client.subscribe(0, { node: "tk_42" }); // its events
53
+ ```
54
+
55
+ Refusals are `SharedcontextRefused` with a stable `reason` (`role_not_allowed`, `node_not_found`,
56
+ `signer_not_caller`, …; the full lists are `REJECT_REASONS`, `TOOL_REASONS` and `AUTH_REASONS`).
57
+ Anything else a server sends stays out of the error's message. A service that cannot be reached
58
+ in time (default 10 s per call) is `SharedcontextUnavailable`.
59
+
60
+ ```ts
61
+ import { validate, checkEvent, verifyEvent } from "@sharedcontext/sdk";
62
+
63
+ validate("content.schema.json#/$defs/node.created", { kind: "task", title: "x" }); // {valid, errors}
64
+ await verifyEvent(event, { receivedAt }); // the core's stateless check, without the signature: null or a reason
65
+ await checkEvent(event); // the contract's shape: envelope, id, canonical content, content by type
66
+ ```
67
+
68
+ `checkEvent` checks an event you are about to write. A stored event written under a newer minor of
69
+ the contract (an unknown type, or content fields this contract does not define) fails it even
70
+ though the log accepted it.
71
+
72
+ ## Agreement with the core
73
+
74
+ The Rust crate `sharedcontext` is the reference. This package's tests run in the core's tree and
75
+ check, against the core's own fixture log (every event written and signed by the core):
76
+
77
+ - canonical JSON and NIP-01 ids byte for byte, every event rebuilt from its parts to the same id;
78
+ - the envelope check's answer for every logged event and every envelope negative;
79
+ - the validator's answer, error for error, against the repository's own contract check, over every
80
+ case of the contract's cases files and every fixture line;
81
+ - the constants and reason lists, read from the core's source;
82
+ - the shipped schemas, byte for byte with the contract's (the directory contract's with the
83
+ crate's `contracts/sharedcontext-directory-1/`), and every example of the directory contract
84
+ valid.
85
+
86
+ What the package does not do: verify BIP-340 signatures (use any NIP-01 library; the service
87
+ verifies every event), and decide what the log's state and policy decide (claims, gates,
88
+ transitions, roles): content that passes here can still be refused.
89
+
90
+ ## License
91
+
92
+ Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
93
+ [MIT license](LICENSE-MIT) at your option.
94
+
95
+ Repository: https://github.com/cogniumhq/sharedcontext.
@@ -0,0 +1,47 @@
1
+ /** A JSON value as this package reads and writes it. */
2
+ export type Json = null | boolean | number | string | Json[] | {
3
+ [key: string]: Json;
4
+ };
5
+ /** A value `canonicalJson` takes: JSON, plus `bigint` for 64-bit integers and `undefined` fields (left out). */
6
+ export type JsonInput = null | boolean | number | bigint | string | readonly JsonInput[] | {
7
+ readonly [key: string]: JsonInput | undefined;
8
+ };
9
+ /** A value `canonicalJson` cannot write as content the core accepts. */
10
+ export declare class CanonicalJsonError extends Error {
11
+ readonly path: string;
12
+ constructor(path: string, reason: string);
13
+ }
14
+ /** The UTF-8 bytes of `s` (lone surrogates as U+FFFD, as a UTF-8 encoder does). */
15
+ export declare function utf8(s: string): Uint8Array;
16
+ /** The length of `s` in UTF-8 bytes: what the core's byte bounds (`CLIENT_ID_MAX`, `MAX_BODY_BYTES`) count. */
17
+ export declare function utf8Length(s: string): number;
18
+ /** No lone surrogate: the string has a UTF-8 form, as every Rust string does. */
19
+ export declare function isWellFormed(s: string): boolean;
20
+ /** Order two strings by their UTF-8 bytes (the same as by code points), as Rust orders `String`s. */
21
+ export declare function compareUtf8(a: string, b: string): number;
22
+ /**
23
+ * A non-integral number as serde_json writes an f64 (the shortest digits that read back, as
24
+ * JavaScript's): plain from 1e-5 up, else `d.ddde-X`. JavaScript writes plain from 1e-6, so the one
25
+ * decade between differs and is written here as serde_json does. A non-integral f64 is below 2^52,
26
+ * so the large-number forms never arise.
27
+ */
28
+ export declare function formatFloat(x: number): string;
29
+ /**
30
+ * Any JSON value in the core's canonical form: compact, keys sorted by UTF-8 bytes at every level,
31
+ * object fields that are `undefined` left out. An integer `number` must be safe (a `bigint` gives
32
+ * the rest of the core's 64-bit range); a non-integral one is written as the core writes an f64
33
+ * (no sharedcontext/1 content field takes one, but the log keeps a later minor's). Throws `CanonicalJsonError` on anything the core
34
+ * would not read back to the same bytes.
35
+ */
36
+ export declare function canonicalJson(value: unknown): string;
37
+ /** An event's content: `canonicalJson` of an object (the core takes nothing else as content). */
38
+ export declare function canonicalContent(content: object): string;
39
+ /**
40
+ * `text` is content the core accepts as canonical: a JSON object that it parses and writes back to
41
+ * the same bytes. Integers are checked over the core's whole range (`-2^63` to `2^64 - 1`), not
42
+ * JavaScript's. A number with a fraction or an exponent is refused when it is integral (`1.0`,
43
+ * `1e3`), and otherwise must be written as the core writes it back. (The core reads decimals with
44
+ * serde_json's default parser, which is not correctly rounded for every long fraction; for such a
45
+ * number the two can disagree.)
46
+ */
47
+ export declare function isCanonicalContent(text: string): boolean;
@@ -0,0 +1,257 @@
1
+ // Canonical JSON, as the Rust core writes and checks an event's content
2
+ // (`signed::canonical_content`, `signed::check_canonical_content`): a JSON object, compact, keys
3
+ // sorted by their UTF-8 bytes at every level, strings in serde_json's escaping (only `"`, `\` and
4
+ // the control characters are escaped, the rest is raw UTF-8), integers never written with a
5
+ // fraction or an exponent, and any other number written as serde_json writes an f64.
6
+ import { MAX_CONTENT_DEPTH } from "./constants.js";
7
+ /** A value `canonicalJson` cannot write as content the core accepts. */
8
+ export class CanonicalJsonError extends Error {
9
+ path;
10
+ constructor(path, reason) {
11
+ super(`${path}: ${reason}`);
12
+ this.path = path;
13
+ this.name = "CanonicalJsonError";
14
+ }
15
+ }
16
+ const U64_MAX = 18446744073709551615n;
17
+ const I64_MIN = -9223372036854775808n;
18
+ /** The UTF-8 bytes of `s` (lone surrogates as U+FFFD, as a UTF-8 encoder does). */
19
+ export function utf8(s) {
20
+ const out = [];
21
+ for (let i = 0; i < s.length; i++) {
22
+ let c = s.charCodeAt(i);
23
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
24
+ const d = s.charCodeAt(i + 1);
25
+ if (d >= 0xdc00 && d <= 0xdfff) {
26
+ c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);
27
+ i++;
28
+ }
29
+ }
30
+ if (c >= 0xd800 && c <= 0xdfff)
31
+ c = 0xfffd;
32
+ if (c < 0x80)
33
+ out.push(c);
34
+ else if (c < 0x800)
35
+ out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
36
+ else if (c < 0x10000)
37
+ out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
38
+ else
39
+ out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
40
+ }
41
+ return Uint8Array.from(out);
42
+ }
43
+ /** The length of `s` in UTF-8 bytes: what the core's byte bounds (`CLIENT_ID_MAX`, `MAX_BODY_BYTES`) count. */
44
+ export function utf8Length(s) {
45
+ return utf8(s).length;
46
+ }
47
+ /** No lone surrogate: the string has a UTF-8 form, as every Rust string does. */
48
+ export function isWellFormed(s) {
49
+ for (let i = 0; i < s.length; i++) {
50
+ const c = s.charCodeAt(i);
51
+ if (c >= 0xd800 && c <= 0xdbff) {
52
+ const d = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
53
+ if (d < 0xdc00 || d > 0xdfff)
54
+ return false;
55
+ i++;
56
+ }
57
+ else if (c >= 0xdc00 && c <= 0xdfff)
58
+ return false;
59
+ }
60
+ return true;
61
+ }
62
+ /** Order two strings by their UTF-8 bytes (the same as by code points), as Rust orders `String`s. */
63
+ export function compareUtf8(a, b) {
64
+ let i = 0;
65
+ let j = 0;
66
+ while (i < a.length && j < b.length) {
67
+ const x = a.codePointAt(i);
68
+ const y = b.codePointAt(j);
69
+ if (x !== y)
70
+ return x < y ? -1 : 1;
71
+ i += x > 0xffff ? 2 : 1;
72
+ j += y > 0xffff ? 2 : 1;
73
+ }
74
+ return i < a.length ? 1 : j < b.length ? -1 : 0;
75
+ }
76
+ /**
77
+ * A non-integral number as serde_json writes an f64 (the shortest digits that read back, as
78
+ * JavaScript's): plain from 1e-5 up, else `d.ddde-X`. JavaScript writes plain from 1e-6, so the one
79
+ * decade between differs and is written here as serde_json does. A non-integral f64 is below 2^52,
80
+ * so the large-number forms never arise.
81
+ */
82
+ export function formatFloat(x) {
83
+ const exp = x.toExponential(); // shortest digits: `d.ddde±X`
84
+ const kk = Number(exp.slice(exp.indexOf("e") + 1)) + 1; // the decimal point's position
85
+ return kk > -5 ? String(x) : exp;
86
+ }
87
+ function writeString(s, path) {
88
+ if (!isWellFormed(s))
89
+ throw new CanonicalJsonError(path, "a string with a lone surrogate has no UTF-8 form");
90
+ return JSON.stringify(s);
91
+ }
92
+ function write(v, path, depth) {
93
+ if (v === null)
94
+ return "null";
95
+ switch (typeof v) {
96
+ case "boolean":
97
+ return v ? "true" : "false";
98
+ case "string":
99
+ return writeString(v, path);
100
+ case "number":
101
+ if (!Number.isFinite(v))
102
+ throw new CanonicalJsonError(path, `${v} is not JSON`);
103
+ if (!Number.isInteger(v))
104
+ return formatFloat(v);
105
+ if (!Number.isSafeInteger(v))
106
+ throw new CanonicalJsonError(path, `${v} is past the integers JavaScript represents exactly: use a bigint`);
107
+ return Object.is(v, -0) ? "0" : String(v);
108
+ case "bigint":
109
+ if (v < I64_MIN || v > U64_MAX)
110
+ throw new CanonicalJsonError(path, `${v} is outside the 64-bit integers the core reads`);
111
+ return v.toString();
112
+ case "object": {
113
+ if (depth >= MAX_CONTENT_DEPTH)
114
+ throw new CanonicalJsonError(path, `nested deeper than ${MAX_CONTENT_DEPTH} levels`);
115
+ if (Array.isArray(v)) {
116
+ return `[${v
117
+ .map((x, i) => {
118
+ if (x === undefined)
119
+ throw new CanonicalJsonError(`${path}[${i}]`, "undefined in an array");
120
+ return write(x, `${path}[${i}]`, depth + 1);
121
+ })
122
+ .join(",")}]`;
123
+ }
124
+ const proto = Object.getPrototypeOf(v);
125
+ if (proto !== Object.prototype && proto !== null)
126
+ throw new CanonicalJsonError(path, "only plain objects, arrays and JSON scalars are content");
127
+ const o = v;
128
+ const keys = Object.keys(o)
129
+ .filter((k) => o[k] !== undefined)
130
+ .sort(compareUtf8);
131
+ return `{${keys.map((k) => `${writeString(k, path)}:${write(o[k], `${path}.${k}`, depth + 1)}`).join(",")}}`;
132
+ }
133
+ default:
134
+ throw new CanonicalJsonError(path, `a ${typeof v} is not JSON`);
135
+ }
136
+ }
137
+ /**
138
+ * Any JSON value in the core's canonical form: compact, keys sorted by UTF-8 bytes at every level,
139
+ * object fields that are `undefined` left out. An integer `number` must be safe (a `bigint` gives
140
+ * the rest of the core's 64-bit range); a non-integral one is written as the core writes an f64
141
+ * (no sharedcontext/1 content field takes one, but the log keeps a later minor's). Throws `CanonicalJsonError` on anything the core
142
+ * would not read back to the same bytes.
143
+ */
144
+ export function canonicalJson(value) {
145
+ return write(value, "$", 0);
146
+ }
147
+ /** An event's content: `canonicalJson` of an object (the core takes nothing else as content). */
148
+ export function canonicalContent(content) {
149
+ if (content === null || typeof content !== "object" || Array.isArray(content))
150
+ throw new CanonicalJsonError("$", "content must be a JSON object");
151
+ return write(content, "content", 0);
152
+ }
153
+ // ── the check ───────────────────────────────────────────────────────────────
154
+ const INTEGER = /^(?:0|-?[1-9][0-9]*)$/;
155
+ const NUMBER = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/;
156
+ /**
157
+ * `text` is content the core accepts as canonical: a JSON object that it parses and writes back to
158
+ * the same bytes. Integers are checked over the core's whole range (`-2^63` to `2^64 - 1`), not
159
+ * JavaScript's. A number with a fraction or an exponent is refused when it is integral (`1.0`,
160
+ * `1e3`), and otherwise must be written as the core writes it back. (The core reads decimals with
161
+ * serde_json's default parser, which is not correctly rounded for every long fraction; for such a
162
+ * number the two can disagree.)
163
+ */
164
+ export function isCanonicalContent(text) {
165
+ if (typeof text !== "string" || !isWellFormed(text) || text[0] !== "{")
166
+ return false;
167
+ let pos = 0;
168
+ const value = (depth) => {
169
+ const c = text[pos];
170
+ if (c === "{" || c === "[") {
171
+ if (depth >= MAX_CONTENT_DEPTH)
172
+ return false;
173
+ const close = c === "{" ? "}" : "]";
174
+ pos++;
175
+ if (text[pos] === close) {
176
+ pos++;
177
+ return true;
178
+ }
179
+ let last = null;
180
+ for (;;) {
181
+ if (c === "{") {
182
+ const start = pos;
183
+ if (!string())
184
+ return false;
185
+ const key = JSON.parse(text.slice(start, pos));
186
+ if (last !== null && compareUtf8(last, key) >= 0)
187
+ return false; // unsorted or repeated
188
+ last = key;
189
+ if (text[pos] !== ":")
190
+ return false;
191
+ pos++;
192
+ }
193
+ if (!value(depth + 1))
194
+ return false;
195
+ if (text[pos] === ",")
196
+ pos++;
197
+ else if (text[pos] === close) {
198
+ pos++;
199
+ return true;
200
+ }
201
+ else
202
+ return false;
203
+ }
204
+ }
205
+ if (c === '"')
206
+ return string();
207
+ for (const lit of ["true", "false", "null"]) {
208
+ if (text.startsWith(lit, pos)) {
209
+ pos += lit.length;
210
+ return true;
211
+ }
212
+ }
213
+ const m = /^-?[0-9][0-9.eE+-]*/.exec(text.slice(pos, pos + 40));
214
+ if (!m)
215
+ return false;
216
+ if (INTEGER.test(m[0])) {
217
+ const n = BigInt(m[0]);
218
+ if (n < I64_MIN || n > U64_MAX)
219
+ return false;
220
+ }
221
+ else {
222
+ // the core reads any other number as an f64: refused when integral, else it must be written
223
+ // as the core writes that f64 back
224
+ const x = Number(m[0]);
225
+ if (!NUMBER.test(m[0]) || !Number.isFinite(x) || Number.isInteger(x) || formatFloat(x) !== m[0])
226
+ return false;
227
+ }
228
+ pos += m[0].length;
229
+ return true;
230
+ };
231
+ const string = () => {
232
+ if (text[pos] !== '"')
233
+ return false;
234
+ let end = pos + 1;
235
+ for (; end < text.length && text[end] !== '"'; end++) {
236
+ if (text[end] === "\\")
237
+ end++;
238
+ else if (text.charCodeAt(end) < 0x20)
239
+ return false;
240
+ }
241
+ if (end >= text.length)
242
+ return false;
243
+ const raw = text.slice(pos, end + 1);
244
+ let decoded;
245
+ try {
246
+ decoded = JSON.parse(raw);
247
+ }
248
+ catch {
249
+ return false;
250
+ }
251
+ if (typeof decoded !== "string" || !isWellFormed(decoded) || JSON.stringify(decoded) !== raw)
252
+ return false;
253
+ pos = end + 1;
254
+ return true;
255
+ };
256
+ return value(0) && pos === text.length;
257
+ }