@midnight-ntwrk/midnight-did 0.4.0-snapshot.51.a3d433c5e196

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,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 [yyyy] [name of copyright owner]
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/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # @midnight-ntwrk/midnight-did
2
+
3
+ Mapping layer between on-ledger contract state and DID Core-compatible domain documents.
4
+
5
+ ## Responsibilities
6
+
7
+ - Convert contract ledger data to domain DID documents
8
+ - Resolve canonical absolute DID URLs from stored fragment identifiers
9
+ - Provide network/identifier utilities for `did:midnight`
10
+
11
+ ## Architecture
12
+
13
+ ```mermaid
14
+ graph TD
15
+ Ledger[(Contract ledger state)]
16
+ Mapper[LedgerToDomain]
17
+ Domain[Domain DID document]
18
+ Resolver[Resolver/API consumers]
19
+
20
+ Ledger --> Mapper --> Domain --> Resolver
21
+ ```
22
+
23
+ ## Resolution Sequence
24
+
25
+ ```mermaid
26
+ sequenceDiagram
27
+ participant Consumer
28
+ participant DIDPkg as did package
29
+ participant Mapper as LedgerToDomain
30
+ participant Domain
31
+
32
+ Consumer->>DIDPkg: DID Resolution input (DID string)
33
+ DIDPkg->>Mapper: map ledger state
34
+ Mapper->>Domain: construct canonical document
35
+ Domain-->>DIDPkg: validated model
36
+ DIDPkg-->>Consumer: DID Resolution Result
37
+ ```
38
+
39
+ ## Resolution Result Shape
40
+
41
+ `MidnightDIDResolver.resolveDIDResolutionResult` returns a DID Core Resolution
42
+ Result envelope with `didDocument`, `didDocumentMetadata`, and
43
+ `didResolutionMetadata`. Successful abstract `resolve` results return an empty
44
+ `didResolutionMetadata` object and do not set `contentType`. Missing ledger
45
+ state returns `didResolutionMetadata.error = "notFound"`.
46
+
47
+ The `resolve` and `resolveResult` methods remain convenience APIs for callers
48
+ that want a DID Document directly or a nullable document-plus-metadata pair.
49
+
50
+ Use `contentType` only for `resolveRepresentation`-style responses where the
51
+ body is a DID Document byte stream. Midnight DID Document representations should
52
+ be reported as `application/did+ld+json` for JSON-LD streams or
53
+ `application/did+json` for DID Core JSON streams.
54
+
55
+ ## Identifier Canonicalization
56
+
57
+ ```mermaid
58
+ stateDiagram-v2
59
+ [*] --> FragmentStored
60
+ FragmentStored --> AbsoluteReference : during resolution
61
+ AbsoluteReference --> [*]
62
+ ```
63
+
64
+ Resolution output uses absolute DID URL references where required by DID Core,
65
+ while compact fragment identifiers may still be used in ledger storage.
66
+
67
+ ## Build & Test
68
+
69
+ - Build: `pnpm --filter ./packages/did build`
70
+ - Test: `pnpm --filter ./packages/did test -- --pool=threads`
71
+ - Coverage: `pnpm --filter ./packages/did coverage`
@@ -0,0 +1,6 @@
1
+ export { LedgerToDomain } from "./ledger-to-domain.js";
2
+ export * from "./midnight.js";
3
+ export * from "./midnight-did-document.js";
4
+ export * from "./midnight-did-resolver.js";
5
+ export * from "./offchain-midnight-did.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,cAAc,eAAe,CAAC;AAC9B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { LedgerToDomain } from "./ledger-to-domain.js";
2
+ export * from "./midnight.js";
3
+ export * from "./midnight-did-document.js";
4
+ export * from "./midnight-did-resolver.js";
5
+ export * from "./offchain-midnight-did.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,cAAc,eAAe,CAAC;AAC9B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC","sourcesContent":["export { LedgerToDomain } from \"./ledger-to-domain.js\";\nexport * from \"./midnight.js\";\nexport * from \"./midnight-did-document.js\";\nexport * from \"./midnight-did-resolver.js\";\nexport * from \"./offchain-midnight-did.js\";\n"]}
@@ -0,0 +1,28 @@
1
+ import { DIDContract } from "@midnight-ntwrk/midnight-did-contract";
2
+ import { DIDDocumentMetadata, PublicKeyJwk, Service } from "@midnight-ntwrk/midnight-did-domain";
3
+ import { MidnightNetwork, parseContractAddress } from "./midnight.js";
4
+ import { MidnightDIDDocument } from "./midnight-did-document.js";
5
+ type Ledger = DIDContract.Ledger;
6
+ type LedgerPublicKeyJwk = DIDContract.PublicKeyJwk;
7
+ type LedgerSchnorrJubjubVerificationMethod = DIDContract.SchnorrJubjubVerificationMethod;
8
+ type LedgerService = DIDContract.Service;
9
+ export declare class LedgerToDomain {
10
+ private static readonly KeyTypeMap;
11
+ private static readonly CurveTypeMap;
12
+ private static readonly VerificationMethodTypeMap;
13
+ private static readonly VerificationMethodRelationMap;
14
+ static publicKeyJwk(publicKeyJwk: LedgerPublicKeyJwk): PublicKeyJwk;
15
+ static schnorrJubjubPublicKeyJwk(verificationMethod: LedgerSchnorrJubjubVerificationMethod): PublicKeyJwk;
16
+ private static ledgerOpaqueString;
17
+ static service(service: LedgerService): Service;
18
+ private static parseServiceType;
19
+ private static parseServiceEndpoint;
20
+ static verificationMethodId(id: string): string;
21
+ static absoluteDidUrlReference(did: string, id: string): string;
22
+ static toJSON(ledger: Ledger): object;
23
+ static ledgerStateToDIDDocument(ledger: Ledger, network: MidnightNetwork, contractAddress: ReturnType<typeof parseContractAddress>): MidnightDIDDocument;
24
+ static ledgerStateToMetadata(ledger: Ledger): DIDDocumentMetadata;
25
+ private static timestampToIsoString;
26
+ }
27
+ export {};
28
+ //# sourceMappingURL=ledger-to-domain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger-to-domain.d.ts","sourceRoot":"","sources":["../src/ledger-to-domain.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,uCAAuC,CAAC;AACpE,OAAO,EAIL,mBAAmB,EAInB,YAAY,EAEZ,OAAO,EAKR,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EAEL,eAAe,EACf,oBAAoB,EACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAEL,mBAAmB,EACpB,MAAM,4BAA4B,CAAC;AAsBpC,KAAK,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC;AACjC,KAAK,kBAAkB,GAAG,WAAW,CAAC,YAAY,CAAC;AACnD,KAAK,qCAAqC,GACxC,WAAW,CAAC,+BAA+B,CAAC;AAC9C,KAAK,aAAa,GAAG,WAAW,CAAC,OAAO,CAAC;AAkBzC,qBAAa,cAAc;IACzB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAKhC;IAEF,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAWlC;IAEF,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,yBAAyB,CAO/C;IAEF,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,6BAA6B,CAgBnD;IAEF,MAAM,CAAC,YAAY,CAAC,YAAY,EAAE,kBAAkB,GAAG,YAAY;IAsBnE,MAAM,CAAC,yBAAyB,CAC9B,kBAAkB,EAAE,qCAAqC,GACxD,YAAY;IASf,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAkBjC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO;IAwB/C,OAAO,CAAC,MAAM,CAAC,gBAAgB;IA4B/B,OAAO,CAAC,MAAM,CAAC,oBAAoB;IA4CnC,MAAM,CAAC,oBAAoB,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM;IAc/C,MAAM,CAAC,uBAAuB,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM;IAM/D,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IA0DrC,MAAM,CAAC,wBAAwB,CAC7B,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,eAAe,EACxB,eAAe,EAAE,UAAU,CAAC,OAAO,oBAAoB,CAAC,GACvD,mBAAmB;IAsHtB,MAAM,CAAC,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,mBAAmB;IAsBjE,OAAO,CAAC,MAAM,CAAC,oBAAoB;CASpC"}
@@ -0,0 +1,341 @@
1
+ import { DIDContract } from "@midnight-ntwrk/midnight-did-contract";
2
+ import { createService, createVerificationMethod, CurveType, encodeBase64Url, KeyType, normalizeServiceEndpoint, PublicKeyJwkSchema, ServiceEndpointSchema, VerificationMethodRelationType, VerificationMethodType, } from "@midnight-ntwrk/midnight-did-domain";
3
+ import { createMidnightDIDString, } from "./midnight.js";
4
+ import { createMidnightDIDDocument, } from "./midnight-did-document.js";
5
+ const bytesToHex = (bytes) => {
6
+ let hex = "";
7
+ for (const byte of bytes) {
8
+ hex += Number(byte).toString(16).padStart(2, "0");
9
+ }
10
+ return hex;
11
+ };
12
+ const LedgerCurveType = DIDContract.CurveType;
13
+ const LedgerKeyType = DIDContract.KeyType;
14
+ const LedgerVerificationMethodType = DIDContract.VerificationMethodType;
15
+ const LedgerVerificationMethodRelation = DIDContract.VerificationMethodRelation;
16
+ const bigintTo32Le = (value) => {
17
+ if (value < 0n) {
18
+ throw new Error("Jubjub public key coordinate must be non-negative");
19
+ }
20
+ const bytes = new Uint8Array(32);
21
+ let remaining = value;
22
+ for (let i = 0; i < bytes.length; i += 1) {
23
+ bytes[i] = Number(remaining & 0xffn);
24
+ remaining >>= 8n;
25
+ }
26
+ if (remaining !== 0n) {
27
+ throw new Error("Jubjub public key coordinate does not fit in 32 bytes");
28
+ }
29
+ return bytes;
30
+ };
31
+ export class LedgerToDomain {
32
+ static KeyTypeMap = {
33
+ [LedgerKeyType.EC]: KeyType.EC,
34
+ [LedgerKeyType.RSA]: KeyType.RSA,
35
+ [LedgerKeyType.oct]: KeyType.oct,
36
+ [LedgerKeyType.OKP]: KeyType.OKP,
37
+ };
38
+ static CurveTypeMap = {
39
+ [LedgerCurveType.Ed25519]: CurveType.Ed25519,
40
+ [LedgerCurveType.X25519]: CurveType.X25519,
41
+ [LedgerCurveType.Jubjub]: CurveType.Jubjub,
42
+ [LedgerCurveType.P256]: CurveType.P256,
43
+ [LedgerCurveType.Secp256k1]: CurveType.Secp256k1,
44
+ [LedgerCurveType.BLS12381G1]: CurveType.BLS12381G1,
45
+ [LedgerCurveType.BLS12381G2]: CurveType.BLS12381G2,
46
+ };
47
+ static VerificationMethodTypeMap = {
48
+ [LedgerVerificationMethodType.Undefined]: VerificationMethodType.Undefined,
49
+ [LedgerVerificationMethodType.JsonWebKey]: VerificationMethodType.JsonWebKey,
50
+ };
51
+ static VerificationMethodRelationMap = {
52
+ [LedgerVerificationMethodRelation.Undefined]: VerificationMethodRelationType.Undefined,
53
+ [LedgerVerificationMethodRelation.Authentication]: VerificationMethodRelationType.Authentication,
54
+ [LedgerVerificationMethodRelation.AssertionMethod]: VerificationMethodRelationType.AssertionMethod,
55
+ [LedgerVerificationMethodRelation.KeyAgreement]: VerificationMethodRelationType.KeyAgreement,
56
+ [LedgerVerificationMethodRelation.CapabilityInvocation]: VerificationMethodRelationType.CapabilityInvocation,
57
+ [LedgerVerificationMethodRelation.CapabilityDelegation]: VerificationMethodRelationType.CapabilityDelegation,
58
+ };
59
+ static publicKeyJwk(publicKeyJwk) {
60
+ const kty = this.KeyTypeMap[publicKeyJwk.kty];
61
+ const crv = this.CurveTypeMap[publicKeyJwk.crv];
62
+ const x = this.ledgerOpaqueString(publicKeyJwk.x, "publicKeyJwk.x");
63
+ const y = this.ledgerOpaqueString(publicKeyJwk.y, "publicKeyJwk.y");
64
+ if (kty === KeyType.OKP &&
65
+ (crv === CurveType.Ed25519 ||
66
+ crv === CurveType.X25519 ||
67
+ crv === CurveType.BLS12381G1 ||
68
+ crv === CurveType.BLS12381G2)) {
69
+ if (y !== "") {
70
+ throw new Error("OKP ledger publicKeyJwk.y must be empty");
71
+ }
72
+ return PublicKeyJwkSchema.parse({ kty, crv, x });
73
+ }
74
+ return PublicKeyJwkSchema.parse({ kty, crv, x, y });
75
+ }
76
+ static schnorrJubjubPublicKeyJwk(verificationMethod) {
77
+ return PublicKeyJwkSchema.parse({
78
+ kty: KeyType.EC,
79
+ crv: CurveType.Jubjub,
80
+ x: encodeBase64Url(bigintTo32Le(verificationMethod.publicKey.x)),
81
+ y: encodeBase64Url(bigintTo32Le(verificationMethod.publicKey.y)),
82
+ });
83
+ }
84
+ static ledgerOpaqueString(value, label) {
85
+ if (typeof value === "string")
86
+ return value;
87
+ if (value instanceof Uint8Array)
88
+ return new TextDecoder().decode(value);
89
+ if (ArrayBuffer.isView(value)) {
90
+ const view = value;
91
+ return new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
92
+ }
93
+ const shape = value === null
94
+ ? "null"
95
+ : typeof value === "object"
96
+ ? (value.constructor?.name ?? "object")
97
+ : typeof value;
98
+ throw new Error(`${label} has an unsupported runtime shape: ${shape}`);
99
+ }
100
+ static service(service) {
101
+ const rawId = service.id.trim();
102
+ const needsFragmentPrefix = rawId.startsWith("//") ||
103
+ (!rawId.startsWith("did:") &&
104
+ !rawId.startsWith("#") &&
105
+ !rawId.startsWith("/") &&
106
+ !rawId.startsWith(".") &&
107
+ !rawId.startsWith("?"));
108
+ const serviceId = needsFragmentPrefix ? `#${rawId}` : rawId;
109
+ const serviceEndpoint = this.parseServiceEndpoint(service.serviceEndpoint);
110
+ const serviceType = this.parseServiceType(service.typ ??
111
+ service.type ??
112
+ "");
113
+ return {
114
+ id: serviceId,
115
+ type: serviceType,
116
+ serviceEndpoint,
117
+ };
118
+ }
119
+ static parseServiceType(raw) {
120
+ const value = raw.trim();
121
+ if (value.length === 0) {
122
+ throw new Error("Invalid service type: empty value");
123
+ }
124
+ if (value.startsWith("[")) {
125
+ try {
126
+ const parsed = JSON.parse(value);
127
+ if (Array.isArray(parsed) &&
128
+ parsed.length > 0 &&
129
+ parsed.every((entry) => typeof entry === "string" && entry.trim().length > 0) &&
130
+ new Set(parsed.map((entry) => entry.trim())).size === parsed.length) {
131
+ return parsed.map((entry) => entry.trim());
132
+ }
133
+ }
134
+ catch {
135
+ throw new Error("Invalid service type: malformed JSON array");
136
+ }
137
+ throw new Error("Invalid service type: expected non-empty unique strings");
138
+ }
139
+ return value;
140
+ }
141
+ static parseServiceEndpoint(endpoint) {
142
+ const normalize = (value) => normalizeServiceEndpoint(value);
143
+ if (Array.isArray(endpoint)) {
144
+ const filtered = endpoint
145
+ .map((value) => (typeof value === "string" ? value.trim() : ""))
146
+ .filter((value) => value !== "");
147
+ if (filtered.length === 0) {
148
+ throw new Error("Invalid serviceEndpoint: empty legacy endpoint array");
149
+ }
150
+ if (filtered.length === 1)
151
+ return normalize(filtered[0]);
152
+ return normalize(filtered);
153
+ }
154
+ if (typeof endpoint === "string") {
155
+ const raw = endpoint.trim();
156
+ if (raw === "") {
157
+ throw new Error("Invalid serviceEndpoint: empty value");
158
+ }
159
+ try {
160
+ const parsed = JSON.parse(raw);
161
+ return normalize(ServiceEndpointSchema.parse(parsed));
162
+ }
163
+ catch {
164
+ const direct = ServiceEndpointSchema.safeParse(raw);
165
+ if (direct.success) {
166
+ return normalize(direct.data);
167
+ }
168
+ throw new Error("Invalid serviceEndpoint: malformed JSON payload");
169
+ }
170
+ }
171
+ const parsed = ServiceEndpointSchema.safeParse(endpoint);
172
+ if (parsed.success) {
173
+ return normalize(parsed.data);
174
+ }
175
+ throw new Error("Invalid serviceEndpoint: unsupported endpoint shape");
176
+ }
177
+ static verificationMethodId(id) {
178
+ const rawId = id.trim();
179
+ if (rawId.startsWith("did:")) {
180
+ if (rawId.includes("#"))
181
+ return rawId;
182
+ return `${rawId}#${rawId.slice(rawId.lastIndexOf(":") + 1)}`;
183
+ }
184
+ const needsFragmentPrefix = !rawId.startsWith("#") &&
185
+ !rawId.startsWith("/") &&
186
+ !rawId.startsWith(".") &&
187
+ !rawId.startsWith("?");
188
+ return needsFragmentPrefix ? `#${rawId}` : rawId;
189
+ }
190
+ static absoluteDidUrlReference(did, id) {
191
+ const normalized = this.verificationMethodId(id);
192
+ if (normalized.startsWith("did:"))
193
+ return normalized;
194
+ return `${did}${normalized}`;
195
+ }
196
+ static toJSON(ledger) {
197
+ const created = this.timestampToIsoString(ledger.created);
198
+ const updated = this.timestampToIsoString(ledger.updated);
199
+ const opaqueVerificationMethods = Array.from(ledger.verificationMethods, ([id, method]) => ({
200
+ id: this.verificationMethodId(id),
201
+ type: this.VerificationMethodTypeMap[method.typ],
202
+ publicKeyJwk: this.publicKeyJwk(method.publicKeyJwk),
203
+ }));
204
+ const schnorrJubjubVerificationMethods = Array.from(ledger.schnorrJubjubVerificationMethods, ([id, method]) => ({
205
+ id: this.verificationMethodId(id),
206
+ type: VerificationMethodType.JsonWebKey,
207
+ publicKeyJwk: this.schnorrJubjubPublicKeyJwk(method),
208
+ }));
209
+ return {
210
+ id: bytesToHex(ledger.id.bytes),
211
+ version: Number(ledger.version.toString()),
212
+ active: ledger.active,
213
+ operationCount: Number(ledger.operationCount.toString()),
214
+ created,
215
+ updated,
216
+ deactivated: ledger.deactivated,
217
+ alsoKnownAs: Array.from(ledger.alsoKnownAs),
218
+ verificationMethods: [
219
+ ...opaqueVerificationMethods,
220
+ ...schnorrJubjubVerificationMethods,
221
+ ],
222
+ authenticationRelation: Array.from(ledger.authenticationRelation, (value) => this.verificationMethodId(value)),
223
+ assertionMethodRelation: Array.from(ledger.assertionMethodRelation, (value) => this.verificationMethodId(value)),
224
+ keyAgreementRelation: Array.from(ledger.keyAgreementRelation, (value) => this.verificationMethodId(value)),
225
+ capabilityInvocationRelation: Array.from(ledger.capabilityInvocationRelation, (value) => this.verificationMethodId(value)),
226
+ capabilityDelegationRelation: Array.from(ledger.capabilityDelegationRelation, (value) => this.verificationMethodId(value)),
227
+ services: Array.from(ledger.services, ([, service]) => this.service(service)),
228
+ };
229
+ }
230
+ static ledgerStateToDIDDocument(ledger, network, contractAddress) {
231
+ const did = createMidnightDIDString(contractAddress, network);
232
+ const verificationMethod = [];
233
+ const verificationMethodIds = new Set();
234
+ const registerVerificationMethodId = (id) => {
235
+ const normalizedId = this.verificationMethodId(id);
236
+ if (verificationMethodIds.has(normalizedId)) {
237
+ throw new Error(`Duplicate verification method id '${this.absoluteDidUrlReference(did, id)}'`);
238
+ }
239
+ verificationMethodIds.add(normalizedId);
240
+ };
241
+ for (const [id, method] of ledger.verificationMethods) {
242
+ const verificationMethodType = LedgerToDomain.VerificationMethodTypeMap[method.typ];
243
+ if (verificationMethodType !== VerificationMethodType.JsonWebKey) {
244
+ throw new Error(`Unsupported verification method type for id '${id}': ${verificationMethodType}`);
245
+ }
246
+ registerVerificationMethodId(id);
247
+ verificationMethod.push(createVerificationMethod({
248
+ id: this.absoluteDidUrlReference(did, id),
249
+ type: verificationMethodType,
250
+ controller: did,
251
+ publicKeyJwk: this.publicKeyJwk(method.publicKeyJwk),
252
+ }));
253
+ }
254
+ for (const [id, method] of ledger.schnorrJubjubVerificationMethods) {
255
+ registerVerificationMethodId(id);
256
+ verificationMethod.push(createVerificationMethod({
257
+ id: this.absoluteDidUrlReference(did, id),
258
+ type: VerificationMethodType.JsonWebKey,
259
+ controller: did,
260
+ publicKeyJwk: this.schnorrJubjubPublicKeyJwk(method),
261
+ }));
262
+ }
263
+ const assertRelationTargetsExist = (relationName, relation) => {
264
+ if (relation.isEmpty())
265
+ return;
266
+ for (const methodId of relation) {
267
+ if (!verificationMethodIds.has(this.verificationMethodId(methodId))) {
268
+ throw new Error(`${relationName} references missing verification method '${this.absoluteDidUrlReference(did, methodId)}'`);
269
+ }
270
+ }
271
+ };
272
+ assertRelationTargetsExist("authentication", ledger.authenticationRelation);
273
+ assertRelationTargetsExist("assertionMethod", ledger.assertionMethodRelation);
274
+ assertRelationTargetsExist("keyAgreement", ledger.keyAgreementRelation);
275
+ assertRelationTargetsExist("capabilityInvocation", ledger.capabilityInvocationRelation);
276
+ assertRelationTargetsExist("capabilityDelegation", ledger.capabilityDelegationRelation);
277
+ const mapRelation = (relation) => relation.isEmpty()
278
+ ? undefined
279
+ : Array.from(relation, (value) => this.verificationMethodId(value));
280
+ const assertionMethod = mapRelation(ledger.assertionMethodRelation);
281
+ const authentication = mapRelation(ledger.authenticationRelation);
282
+ const capabilityDelegation = mapRelation(ledger.capabilityDelegationRelation);
283
+ const capabilityInvocation = mapRelation(ledger.capabilityInvocationRelation);
284
+ const keyAgreement = mapRelation(ledger.keyAgreementRelation);
285
+ const service = ledger.services.isEmpty()
286
+ ? undefined
287
+ : Array.from(ledger.services, ([, s]) => {
288
+ const parsed = this.service(s);
289
+ return createService({
290
+ id: this.absoluteDidUrlReference(did, s.id),
291
+ type: parsed.type,
292
+ serviceEndpoint: parsed.serviceEndpoint,
293
+ });
294
+ });
295
+ const alsoKnownAs = ledger.alsoKnownAs.isEmpty()
296
+ ? undefined
297
+ : Array.from(ledger.alsoKnownAs);
298
+ return createMidnightDIDDocument({
299
+ id: did,
300
+ verificationMethod,
301
+ authentication,
302
+ assertionMethod,
303
+ keyAgreement,
304
+ capabilityInvocation,
305
+ capabilityDelegation,
306
+ service,
307
+ alsoKnownAs,
308
+ });
309
+ }
310
+ static ledgerStateToMetadata(ledger) {
311
+ const created = this.timestampToIsoString(ledger.created);
312
+ const updated = this.timestampToIsoString(ledger.updated);
313
+ const deactivatedAt = ledger.deactivated
314
+ ? this.timestampToIsoString(ledger.updated)
315
+ : undefined;
316
+ const isDeactivated = ledger.deactivated || !ledger.active;
317
+ const metadata = {
318
+ created,
319
+ updated,
320
+ deactivated: isDeactivated ? true : undefined,
321
+ versionId: ledger.version.toString(),
322
+ };
323
+ if (isDeactivated && deactivatedAt !== undefined) {
324
+ metadata.updated = deactivatedAt;
325
+ }
326
+ return metadata;
327
+ }
328
+ static timestampToIsoString(timestamp) {
329
+ if (timestamp === 0n)
330
+ return undefined;
331
+ const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);
332
+ if (timestamp > maxSafe || timestamp < 0n)
333
+ return undefined;
334
+ const milliseconds = Number(timestamp);
335
+ if (Number.isNaN(milliseconds))
336
+ return undefined;
337
+ const iso = new Date(milliseconds).toISOString();
338
+ return iso.replace(/\.\d{3}Z$/, "Z");
339
+ }
340
+ }
341
+ //# sourceMappingURL=ledger-to-domain.js.map