|
| 1 | +import { Equal, Hash, ParseResult, Schema } from "effect" |
| 2 | + |
| 3 | + |
| 4 | +export class KeyHash { |
| 5 | + readonly _type = "key" as const |
| 6 | + |
| 7 | + private constructor(private readonly hash: Uint8Array) {} |
| 8 | + |
| 9 | + static readonly KeyHashFromBytes = Schema.transformOrFail( |
| 10 | + Schema.Uint8ArrayFromSelf, |
| 11 | + Schema.declare((input: unknown): input is KeyHash => input instanceof KeyHash, { |
| 12 | + identifier: "KeyHash" |
| 13 | + }), |
| 14 | + { |
| 15 | + strict: true, |
| 16 | + decode: (bytes, _, ast) => { |
| 17 | + if (bytes.length !== 28) { |
| 18 | + return ParseResult.fail(new ParseResult.Type(ast, bytes, `Expected 28 bytes, got ${bytes.length}`)) |
| 19 | + } |
| 20 | + return ParseResult.succeed(new KeyHash(bytes)) |
| 21 | + }, |
| 22 | + encode: (cred) => ParseResult.succeed(cred.toBytes()) |
| 23 | + } |
| 24 | + ) |
| 25 | + |
| 26 | + static readonly KeyHashFromHex = Schema.compose(Schema.Uint8ArrayFromHex, KeyHash.KeyHashFromBytes) |
| 27 | + |
| 28 | + |
| 29 | + toBytes(): Uint8Array { |
| 30 | + return new Uint8Array(this.hash) |
| 31 | + } |
| 32 | + |
| 33 | + toHex(): string { |
| 34 | + return Buffer.from(this.hash).toString("hex") |
| 35 | + } |
| 36 | + |
| 37 | + // Equal protocol implementation |
| 38 | + [Equal.symbol](that: unknown): boolean { |
| 39 | + if (!(that instanceof KeyHash)) { |
| 40 | + return false |
| 41 | + } |
| 42 | + const thisBytes = this.hash |
| 43 | + const thatBytes = that.hash |
| 44 | + if (thisBytes.length !== thatBytes.length) { |
| 45 | + return false |
| 46 | + } |
| 47 | + for (let i = 0; i < thisBytes.length; i++) { |
| 48 | + if (thisBytes[i] !== thatBytes[i]) { |
| 49 | + return false |
| 50 | + } |
| 51 | + } |
| 52 | + return true |
| 53 | + } |
| 54 | + |
| 55 | + // Hash protocol implementation |
| 56 | + [Hash.symbol](): number { |
| 57 | + return Hash.array(Array.from(this.hash)) |
| 58 | + } |
| 59 | + |
| 60 | + toString() { |
| 61 | + return `KeyHash("${this.toHex()}")` |
| 62 | + } |
| 63 | + |
| 64 | + // JSON serialization - returns object with type and hash |
| 65 | + toJSON() { |
| 66 | + return { |
| 67 | + _type: this._type, |
| 68 | + hash: this.toHex() |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + // Method that uses Schema.decodeSync (throws on error) |
| 73 | + static readonly fromHex = Schema.decodeSync(this.KeyHashFromHex) |
| 74 | + |
| 75 | + static readonly fromBytes = Schema.decodeSync(this.KeyHashFromBytes) |
| 76 | + |
| 77 | + // Effect combinators namespace - populated after schemas are defined |
| 78 | + static readonly Effect = { |
| 79 | + fromHex: Schema.decode(KeyHash.KeyHashFromHex), |
| 80 | + fromBytes: Schema.decode(KeyHash.KeyHashFromBytes) |
| 81 | + } |
| 82 | +} |
0 commit comments