@getcirrus/spaces 0.2.0 โ 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.
- package/dist/index.d.ts +24 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +88 -11989
- package/dist/index.js.map +1 -1
- package/package.json +9 -9
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["equals","asUint8Array","concat","length","asUint8Array","equals","fromString","toString","encode","length","i","j","decode","buffer","string","name","name","bytes","from","encode","decode","basex","alphabet","string","buffer","encode","decode","from","base64url","identity","from","toString","fromString","textEncoder","textDecoder","encode","decode","decode","varint","digest","varint.encodingLength","code","bytes","decode","varint.decode","equalBytes","encode","Digest.create","name","code","encode","digest","Digest.create","name","sha256","sha512","bytes","base","baseCache","code","Digest.create","digest","Digest.equals","Digest.decode","Digest.Digest","length","varint.decode","cache","cid","varint.encodingLength","identityBase","base2","base8","base10","base16","base32","base36","base58","base64","base256emoji","sha2","identity","string","fromString","base","bases","string","base","bases","uint8arrays.fromString","uint8arrays.equals","bytes","crypto","bytes","utf8ToBytes","randomBytes","crypto","_0n","_1n","bytes","isBytes_","length","bytesToHex_","hexToBytes_","concatBytes_","object","_0n","_1n","_2n","_3n","_4n","isLE","bytes","length","isLE","_32n","dataView","buffer","length","Bl","u64.split","Bl","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H","sha256","_0n","_1n","base","wbits","_2n","format","length","bytes","abytes","endo","randomBytesWeb","randomBytes","hmac","nobleHmac","r","s","is","create","p256","sha256","p256n","compressPubkey","decompressPubkey","sha256n","verifyDidSig","verifySig","verifyDidSig","_3n","sha256","k256","k256","uint8arrays.concat","uint8arrays.toString","expand","length","HMAC","expand","length","noble.randomBytes","bytes","uint8arrays.toString","ui8FromString","ui8ToString","did.formatDidKey","isUint8","useBuffer","Buffer","ui8ConcatNode","buffer","length","Buffer","fromBase64Native","fromBase64Node","bytes","alphabet","base","base64url","code","Buffer","toBase64Native","bytes","toBase64Node","alphabet","base64url","length","sha256","sha512","bytes","isUint8","STRICT_CID_CHECK_OPTIONS","cat","graphemeLenNative","length","utf8LenNode","string","code","isWellFormedRegExp","code","success","failure","failure","success","SPACE_URI_PREFIX","failure","success","n","r","t","e","i","o","a","u","d","isoDatestringValidator","base64","bytes","compareBytes","length","SpaceError","code","spaceHostAud","createDelegationToken","now","exports","base","length","buffer","length","bytes","buffer","name","ByteSequence","code","format","issues","format","format","cache","bytes","format","l.object","l.integer","l.string","l.bytes","l.literal","length","name","string","bytes","length","bytes","uint.readUint8","uint.readUint16","uint.readUint32","neg1b","pos1b","uint.readUint64","uint.uintBoundaries","toToken","length","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","bytes","bytes","toToken","length","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","toToken","length","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","length","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","uint.readUint8","uint.readUint16","uint.readUint32","uint.readUint64","bytes","success","ui8a","uint.decodeUint8","uint.decodeUint16","uint.decodeUint32","uint.decodeUint64","negint.decodeNegint8","negint.decodeNegint16","negint.decodeNegint32","negint.decodeNegint64","bytes.decodeBytesCompact","bytes.decodeBytes8","bytes.decodeBytes16","bytes.decodeBytes32","bytes.decodeBytes64","string.decodeStringCompact","string.decodeString8","string.decodeString16","string.decodeString32","string.decodeString64","array.decodeArrayCompact","array.decodeArray8","array.decodeArray16","array.decodeArray32","array.decodeArray64","array.decodeArrayIndefinite","map.decodeMapCompact","map.decodeMap8","map.decodeMap16","map.decodeMap32","map.decodeMap64","map.decodeMapIndefinite","tag.decodeTagCompact","tag.decodeTag8","tag.decodeTag16","tag.decodeTag32","tag.decodeTag64","float.decodeUndefined","float.decodeFloat16","float.decodeFloat32","float.decodeFloat64","float.decodeBreak","bytes","encoder","encode","decode","bytes","cborgEncode","cborgDecode","length","bytes","bytes","parseMeta","length","SuppressedError","compareBytes","bytes","compareBytes","compareBytes","bytes","CODE_SET: ReadonlySet<string>","ERROR_STATUS: Partial<Record<SpaceErrorCode, number>>","code: SpaceErrorCode","code","PUBLISHED_COLLECTIONS: readonly string[]","bytes","bytes","bytes","blobCids: string[]","bytes","tidNow","bytes","payload: Record<string, unknown>","results: ApplyWritesResult[\"results\"]","args: unknown[]","ops: OplogEntry[]","writes: PreparedSpaceWrite[]","sequence","now","headers: Record<string, string>","now","args: unknown[]","digest","spaceHostAud","clientUrl: URL","metadata: { jwks?: unknown; jwks_uri?: string }","jwksUrl: URL","name","doFetch: typeof fetch","kemKeypair: Promise<P256Keypair | null> | null","missing: string[]","spaceHostAud","retry: NotifyItem","prepared: PreparedSpaceWrite[]","statuses: Array<string | undefined>","tidNow","bytes","records: ImportedRecord[]","space: string","repo: string","blobCids: string[]","ref","repo: string | undefined","clientId: string | undefined","revMs: number","url: URL","code","cursor: string | undefined","object","upstreamSpaceHostAud","upstreamCreateDelegationToken"],"sources":["../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/const.js","../../../node_modules/.pnpm/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/equals.js","../../../node_modules/.pnpm/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/alloc.js","../../../node_modules/.pnpm/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/util/as-uint8array.js","../../../node_modules/.pnpm/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/concat.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bytes.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/vendor/base-x.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base10.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base16.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base2.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base256emoji.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base32.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base36.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base58.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base64.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base8.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/identity.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/codecs/json.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/vendor/varint.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/varint.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/digest.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/identity.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/hasher.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/sha2-browser.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/cid.js","../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/dist/src/basics.js","../../../node_modules/.pnpm/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/util/bases.js","../../../node_modules/.pnpm/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/from-string.js","../../../node_modules/.pnpm/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/to-string.js","../../../node_modules/.pnpm/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/index.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/utils.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/crypto.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/weierstrass.js","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/_shortw_utils.js","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/nist.js","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/p256.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/p256/encoding.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/p256/operations.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/p256/plugin.js","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/secp256k1.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/secp256k1/encoding.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/secp256k1/operations.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/secp256k1/plugin.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/plugins.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/did.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hkdf.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/hmac.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/random.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/verify.js","../../../node_modules/.pnpm/@atproto+crypto@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/crypto/dist/p256/keypair.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/lib/util.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/object.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/lib/nodejs-buffer.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/uint8array-concat.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/uint8array-from-base64.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/uint8array-to-base64.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/uint8array.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/cid.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/blob.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/lex-error.js","../../../node_modules/.pnpm/unicode-segmenter@0.14.5/node_modules/unicode-segmenter/core.js","../../../node_modules/.pnpm/unicode-segmenter@0.14.5/node_modules/unicode-segmenter/_grapheme_data.js","../../../node_modules/.pnpm/unicode-segmenter@0.14.5/node_modules/unicode-segmenter/_incb_data.js","../../../node_modules/.pnpm/unicode-segmenter@0.14.5/node_modules/unicode-segmenter/grapheme.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/utf8-grapheme-len.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/utf8-len.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/utf8-well-formed.js","../../../node_modules/.pnpm/@atproto+lex-data@0.1.11/node_modules/@atproto/lex-data/dist/utf8.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/did.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/handle.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/at-identifier.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/lib/result.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/nsid.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/recordkey.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/aturi_validation.js","../../../node_modules/.pnpm/iso-datestring-validator@2.2.2/node_modules/iso-datestring-validator/dist/index.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/datetime.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/language.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/tid.js","../../../node_modules/.pnpm/@atproto+syntax@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/syntax/dist/uri.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/bytes.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/error.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/credential.js","../../../node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/types.js","../../../node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/util.js","../../../node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/token.js","../../../node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/serializer.js","../../../node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/parser.js","../../../node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/index.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/http-signature.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/kem.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_blake.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/blake2.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/blake3.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/lthash.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/mac.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/util/lazy-property.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/util/array-agg.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/core/validation-issue.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/core/validation-error.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/core/validator.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/core/standard-schema.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/core/schema.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/core/string-format.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/util/memoize.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/schema/bytes.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/schema/integer.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/schema/literal.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/schema/object.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/schema/token.js","../../../node_modules/.pnpm/@atproto+lex-schema@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/lex-schema/dist/schema/string.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/types.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/util.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/repo-commit.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/is.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/token.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/byte-utils.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/bl.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/common.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/0uint.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/1negint.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/2bytes.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/3string.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/4array.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/5map.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/6tag.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/7float.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/jump.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/encode.js","../../../node_modules/.pnpm/cborg@4.5.8/node_modules/cborg/lib/decode.js","../../../node_modules/.pnpm/@atproto+lex-cbor@0.1.11/node_modules/@atproto/lex-cbor/dist/encoding.js","../../../node_modules/.pnpm/@atproto+lex-cbor@0.1.11/node_modules/@atproto/lex-cbor/dist/index.js","../../../node_modules/.pnpm/@atproto+star@0.0.1/node_modules/@atproto/star/dist/error.js","../../../node_modules/.pnpm/@atproto+star@0.0.1/node_modules/@atproto/star/dist/bytes-reader.js","../../../node_modules/.pnpm/@atproto+star@0.0.1/node_modules/@atproto/star/dist/star.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/space-meta-archive.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/sync/consumer.js","../../../node_modules/.pnpm/@atproto+space@0.0.0-spaces-alpha-20261124235736/node_modules/@atproto/space/dist/sync/provider.js","../src/errors.ts","../src/types.ts","../src/policy.ts","../../../node_modules/.pnpm/@atproto+lex-json@0.1.11/node_modules/@atproto/lex-json/dist/bytes.js","../../../node_modules/.pnpm/@atproto+lex-json@0.1.11/node_modules/@atproto/lex-json/dist/link.js","../../../node_modules/.pnpm/@atproto+lex-json@0.1.11/node_modules/@atproto/lex-json/dist/blob.js","../../../node_modules/.pnpm/@atproto+lex-json@0.1.11/node_modules/@atproto/lex-json/dist/lex-json.js","../src/records.ts","../src/schema.ts","../src/mac.ts","../src/tid.ts","../src/service-jwt.ts","../src/space-do.ts","../src/index-do.ts","../src/space-uri.ts","../src/blob-keys.ts","../src/auth.ts","../src/attestation.ts","../src/routes.ts","../src/tokens.ts"],"sourcesContent":["export const P256_DID_PREFIX = new Uint8Array([0x80, 0x24]);\nexport const SECP256K1_DID_PREFIX = new Uint8Array([0xe7, 0x01]);\nexport const BASE58_MULTIBASE_PREFIX = 'z';\nexport const DID_KEY_PREFIX = 'did:key:';\nexport const P256_JWT_ALG = 'ES256';\nexport const SECP256K1_JWT_ALG = 'ES256K';\n//# sourceMappingURL=const.js.map","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=equals.js.map","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map","/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array(buf) {\n return buf;\n}\n//# sourceMappingURL=as-uint8array.js.map","import { allocUnsafe } from '#alloc';\nimport { asUint8Array } from '#util/as-uint8array';\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat(arrays, length) {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = allocUnsafe(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return asUint8Array(output);\n}\n//# sourceMappingURL=concat.js.map","export const empty = new Uint8Array(0);\nexport function toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nexport function fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nexport function equals(aa, bb) {\n if (aa === bb) {\n return true;\n }\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nexport function coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {\n return o;\n }\n if (o instanceof ArrayBuffer) {\n return new Uint8Array(o);\n }\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nexport function fromString(str) {\n return new TextEncoder().encode(str);\n}\nexport function toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;\n//# sourceMappingURL=base-x.js.map","import { coerce } from '../bytes.js';\nimport basex from '../vendor/base-x.js';\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nexport function or(left, right) {\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nexport class Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport function from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nexport function baseX({ name, prefix, alphabet }) {\n const { encode, decode } = basex(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => coerce(decode(text))\n });\n}\nfunction decode(string, alphabetIdx, bitsPerChar, name) {\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = alphabetIdx[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\nfunction createAlphabetIdx(alphabet) {\n // Build the character lookup table:\n const alphabetIdx = {};\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i;\n }\n return alphabetIdx;\n}\n/**\n * RFC4648 Factory\n */\nexport function rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n const alphabetIdx = createAlphabetIdx(alphabet);\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabetIdx, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map","import { baseX } from './base.js';\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map","import { rfc4648 } from './base.js';\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});\n//# sourceMappingURL=base16.js.map","import { rfc4648 } from './base.js';\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map","import { from } from './base.js';\nconst alphabet = Array.from('๐๐ชโ๐ฐ๐๐๐๐๐๐๐๐๐๐๐๐๐โ๐ป๐ฅ๐พ๐ฟ๐โค๐๐คฃ๐๐๐๐ญ๐๐๐
๐๐๐ฅ๐ฅฐ๐๐๐๐ข๐ค๐๐๐ช๐โบ๐๐ค๐๐๐๐๐น๐คฆ๐๐โโจ๐คท๐ฑ๐๐ธ๐๐๐๐๐๐๐๐๐คฉ๐๐๐ค๐๐ฏ๐๐๐ถ๐๐คญโฃ๐๐๐๐ช๐๐ฅ๐๐๐ฉ๐ก๐คช๐๐ฅณ๐ฅ๐คค๐๐๐ณโ๐๐๐ด๐๐ฌ๐๐๐ท๐ป๐โญโ
๐ฅบ๐๐๐ค๐ฆโ๐ฃ๐๐โน๐๐๐ โ๐๐บ๐๐ป๐๐๐๐๐น๐ฃ๐ซ๐๐๐ต๐ค๐๐ด๐ค๐ผ๐ซโฝ๐คโ๐๐คซ๐๐ฎ๐๐ป๐๐ถ๐๐ฒ๐ฟ๐งก๐โก๐๐โโ๐๐ฐ๐คจ๐ถ๐ค๐ถ๐ฐ๐๐ข๐ค๐๐จ๐จ๐คฌโ๐๐บ๐ค๐๐๐ฑ๐๐ถ๐ฅดโถโกโ๐๐ธโฌ๐จ๐๐ฆ๐ท๐บโ ๐
๐๐ต๐๐คฒ๐ค ๐คง๐๐ต๐
๐ง๐พ๐๐๐ค๐๐คฏ๐ทโ๐ง๐ฏ๐๐๐ค๐๐โ๐ด๐ฃ๐ธ๐๐๐ฅ๐คข๐
๐ก๐ฉ๐๐ธ๐ป๐ค๐คฎ๐ผ๐ฅต๐ฉ๐๐๐ผ๐๐ฃ๐ฅ');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nexport const base256emoji = from({\n prefix: '๐',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map","import { rfc4648 } from './base.js';\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map","import { baseX } from './base.js';\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base36.js.map","import { baseX } from './base.js';\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map","import { rfc4648 } from './base.js';\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map","import { rfc4648 } from './base.js';\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map","import { fromString, toString } from '../bytes.js';\nimport { from } from './base.js';\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n});\n//# sourceMappingURL=identity.js.map","const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nexport const name = 'json';\nexport const code = 0x0200;\nexport function encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nexport function decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map","/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;\n//# sourceMappingURL=varint.js.map","import varint from './vendor/varint.js';\nexport function decode(data, offset = 0) {\n const code = varint.decode(data, offset);\n return [code, varint.decode.bytes];\n}\nexport function encodeTo(int, target, offset = 0) {\n varint.encode(int, target, offset);\n return target;\n}\nexport function encodingLength(int) {\n return varint.encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map","import { coerce, equals as equalBytes } from '../bytes.js';\nimport * as varint from '../varint.js';\n/**\n * Creates a multihash digest.\n */\nexport function create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode(multihash) {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map","import { coerce } from '../bytes.js';\nimport * as Digest from './digest.js';\nconst code = 0x0;\nconst name = 'identity';\nconst encode = coerce;\nfunction digest(input, options) {\n if (options?.truncate != null && options.truncate !== input.byteLength) {\n if (options.truncate < 0 || options.truncate > input.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`);\n }\n input = input.subarray(0, options.truncate);\n }\n return Digest.create(code, encode(input));\n}\nexport const identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map","import * as Digest from './digest.js';\nconst DEFAULT_MIN_DIGEST_LENGTH = 20;\nexport function from({ name, code, encode, minDigestLength, maxDigestLength }) {\n return new Hasher(name, code, encode, minDigestLength, maxDigestLength);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher {\n name;\n code;\n encode;\n minDigestLength;\n maxDigestLength;\n constructor(name, code, encode, minDigestLength, maxDigestLength) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH;\n this.maxDigestLength = maxDigestLength;\n }\n digest(input, options) {\n if (options?.truncate != null) {\n if (options.truncate < this.minDigestLength) {\n throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);\n }\n if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`);\n }\n }\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n if (result instanceof Uint8Array) {\n return createDigest(result, this.code, options?.truncate);\n }\n return result.then(digest => createDigest(digest, this.code, options?.truncate));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n/**\n * Create a Digest from the passed uint8array and code, optionally truncating it\n * first.\n */\nfunction createDigest(digest, code, truncate) {\n if (truncate != null && truncate !== digest.byteLength) {\n if (truncate > digest.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`);\n }\n digest = digest.subarray(0, truncate);\n }\n return Digest.create(code, digest);\n}\n//# sourceMappingURL=hasher.js.map","/* global crypto */\nimport { from } from './hasher.js';\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map","import { base32 } from './bases/base32.js';\nimport { base36 } from './bases/base36.js';\nimport { base58btc } from './bases/base58.js';\nimport { coerce } from './bytes.js';\nimport * as Digest from './hashes/digest.js';\nimport * as varint from './varint.js';\n// This way TS will also expose all the types from module\nexport * from './link/interface.js';\nexport function format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));\n }\n}\nexport function toJSON(link) {\n return {\n '/': format(link)\n };\n}\nexport function fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nexport class CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = Digest.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = Digest.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc;\n return [\n base58btc.prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ];\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc;\n return [base58btc.prefix, decoder.decode(source)];\n }\n case base32.prefix: {\n const decoder = base ?? base32;\n return [base32.prefix, decoder.decode(source)];\n }\n case base36.prefix: {\n const decoder = base ?? base36;\n return [base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = varint.encodingLength(version);\n const hashOffset = codeOffset + varint.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n varint.encodeTo(version, bytes, 0);\n varint.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map","import * as base10 from './bases/base10.js';\nimport * as base16 from './bases/base16.js';\nimport * as base2 from './bases/base2.js';\nimport * as base256emoji from './bases/base256emoji.js';\nimport * as base32 from './bases/base32.js';\nimport * as base36 from './bases/base36.js';\nimport * as base58 from './bases/base58.js';\nimport * as base64 from './bases/base64.js';\nimport * as base8 from './bases/base8.js';\nimport * as identityBase from './bases/identity.js';\nimport * as json from './codecs/json.js';\nimport * as raw from './codecs/raw.js';\nimport * as identity from './hashes/identity.js';\nimport * as sha2 from './hashes/sha2.js';\nimport { CID, hasher, digest, varint, bytes } from './index.js';\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji };\nexport const hashes = { ...sha2, ...identity };\nexport const codecs = { raw, json };\nexport { CID, hasher, digest, varint, bytes };\n//# sourceMappingURL=basics.js.map","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '#alloc';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;\n//# sourceMappingURL=bases.js.map","import bases from \"./util/bases.js\";\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`);\n}\n//# sourceMappingURL=from-string.js.map","import bases from \"./util/bases.js\";\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map","/**\n * @packageDocumentation\n *\n * `Uint8Array`s bring memory-efficient(ish) byte handling to browsers - they are similar to Node.js `Buffer`s but lack a lot of the utility methods present on that class.\n *\n * This module exports a number of function that let you do common operations - joining Uint8Arrays together, seeing if they have the same contents etc.\n *\n * Since Node.js `Buffer`s are also `Uint8Array`s, it falls back to `Buffer` internally where it makes sense for performance reasons.\n *\n * ## alloc(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * ### Example\n *\n * ```js\n * import { alloc } from 'uint8arrays/alloc'\n *\n * const buf = alloc(100)\n * ```\n *\n * ## allocUnsafe(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * On platforms that support it, memory referenced by the returned `Uint8Array` will not be initialized.\n *\n * ### Example\n *\n * ```js\n * import { allocUnsafe } from 'uint8arrays/alloc'\n *\n * const buf = allocUnsafe(100)\n * ```\n *\n * ## compare(a, b)\n *\n * Compare two `Uint8Arrays`\n *\n * ### Example\n *\n * ```js\n * import { compare } from 'uint8arrays/compare'\n *\n * const arrays = [\n * Uint8Array.from([3, 4, 5]),\n * Uint8Array.from([0, 1, 2])\n * ]\n *\n * const sorted = arrays.sort(compare)\n *\n * console.info(sorted)\n * // [\n * // Uint8Array[0, 1, 2]\n * // Uint8Array[3, 4, 5]\n * // ]\n * ```\n *\n * ## concat(arrays, \\[length])\n *\n * Concatenate one or more `Uint8Array`s and return a `Uint8Array` with their contents.\n *\n * If you know the length of the arrays, pass it as a second parameter, otherwise it will be calculated by traversing the list of arrays.\n *\n * ### Example\n *\n * ```js\n * import { concat } from 'uint8arrays/concat'\n *\n * const arrays = [\n * Uint8Array.from([0, 1, 2]),\n * Uint8Array.from([3, 4, 5])\n * ]\n *\n * const all = concat(arrays, 6)\n *\n * console.info(all)\n * // Uint8Array[0, 1, 2, 3, 4, 5]\n * ```\n *\n * ## equals(a, b)\n *\n * Returns true if the two arrays are the same array or if they have the same length and contents.\n *\n * ### Example\n *\n * ```js\n * import { equals } from 'uint8arrays/equals'\n *\n * const a = Uint8Array.from([0, 1, 2])\n * const b = Uint8Array.from([3, 4, 5])\n * const c = Uint8Array.from([0, 1, 2])\n *\n * console.info(equals(a, b)) // false\n * console.info(equals(a, c)) // true\n * console.info(equals(a, a)) // true\n * ```\n *\n * ## fromString(string, encoding = 'utf8')\n *\n * Returns a new `Uint8Array` created from the passed string and interpreted as the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { fromString } from 'uint8arrays/from-string'\n *\n * console.info(fromString('hello world')) // Uint8Array[104, 101 ...\n * console.info(fromString('00010203aabbcc', 'base16')) // Uint8Array[0, 1 ...\n * console.info(fromString('AAECA6q7zA', 'base64')) // Uint8Array[0, 1 ...\n * console.info(fromString('01234', 'ascii')) // Uint8Array[48, 49 ...\n * ```\n *\n * ## toString(array, encoding = 'utf8')\n *\n * Returns a string created from the passed `Uint8Array` in the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { toString } from 'uint8arrays/to-string'\n *\n * console.info(toString(Uint8Array.from([104, 101...]))) // 'hello world'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base16')) // '00010203aabbcc'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base64')) // 'AAECA6q7zA'\n * console.info(toString(Uint8Array.from([48, 49, 50...]), 'ascii')) // '01234'\n * ```\n *\n * ## xor(a, b)\n *\n * Returns a `Uint8Array` containing `a` and `b` xored together.\n *\n * ### Example\n *\n * ```js\n * import { xor } from 'uint8arrays/xor'\n *\n * console.info(xor(Uint8Array.from([1, 0]), Uint8Array.from([0, 1]))) // Uint8Array[1, 1]\n * ```\n *\n * ## xorCompare(a, b)\n *\n * Compares the distances between two xor `Uint8Array`s.\n *\n * ### Example\n *\n * ```ts\n * import { xor } from 'uint8arrays/xor'\n * import { xorCompare } from 'uint8arrays/xor-compare'\n *\n * const target = Uint8Array.from([1, 1])\n * const val1 = Uint8Array.from([1, 0])\n * const xor1 = xor(target, val1)\n *\n * const val2 = Uint8Array.from([0, 1])\n * const xor2 = xor(target, val2)\n *\n * console.info(xorCompare(xor1, xor2)) // -1 or 0 or 1\n * ```\n */\nimport { equals } from \"./equals.js\";\nimport { xor } from \"./xor.js\";\nimport { compare } from '#compare';\nimport { concat } from '#concat';\nimport { fromString } from '#from-string';\nimport { toString } from '#to-string';\nexport { compare, concat, equals, fromString, toString, xor };\n//# sourceMappingURL=index.js.map","import * as uint8arrays from 'uint8arrays';\nimport { BASE58_MULTIBASE_PREFIX, DID_KEY_PREFIX } from './const.js';\nexport const extractMultikey = (did) => {\n if (!did.startsWith(DID_KEY_PREFIX)) {\n throw new Error(`Incorrect prefix for did:key: ${did}`);\n }\n return did.slice(DID_KEY_PREFIX.length);\n};\n// The largest key these helpers handle is an uncompressed 65-byte public key\n// (plus a 2-byte multicodec prefix), which is about 92 characters in\n// base58btc. Longer inputs are rejected before decoding because the base58btc\n// decoder in uint8arrays runs in time quadratic in the input length, and keys\n// come from untrusted DID documents.\nconst MAX_BASE58_KEY_LENGTH = 128;\n/**\n * Length-bounded base58btc decode for public key material.\n *\n * @throws if the input is too long to be a supported public key, or is not\n * valid base58btc.\n */\nexport const base58ToKeyBytes = (str) => {\n if (str.length > MAX_BASE58_KEY_LENGTH) {\n throw new Error(`base58btc key too long (${str.length} > ${MAX_BASE58_KEY_LENGTH})`);\n }\n return uint8arrays.fromString(str, 'base58btc');\n};\nexport const extractPrefixedBytes = (multikey) => {\n if (!multikey.startsWith(BASE58_MULTIBASE_PREFIX)) {\n throw new Error(`Incorrect prefix for multikey: ${multikey}`);\n }\n return base58ToKeyBytes(multikey.slice(BASE58_MULTIBASE_PREFIX.length));\n};\nexport const hasPrefix = (bytes, prefix) => {\n return uint8arrays.equals(prefix, bytes.subarray(0, prefix.byteLength));\n};\n//# sourceMappingURL=utils.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';\nexport { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(title + ' boolean expected, got ' + value);\n}\n// tmp name until v2\nexport function _abool2(value, title = '') {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value, length, title = '') {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n }\n catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n }\n else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error('invalid validator function');\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\nexport function isHash(val) {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(object, fields, optFields = {}) {\n if (!object || typeof object !== 'object')\n throw new Error('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction assertIsSquare(Fp, root, n) {\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\nfunction sqrt5mod8(Fp, n) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (Fp, n) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n if (Fp.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t))\n return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) โก 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P โก 3 (mod 4)\n * 2. P โก 5 (mod 8)\n * 3. P โก 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n // P โก 3 (mod 4) => โn = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P โก 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P โก 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return Fp.ONE;\n if (power === _1n)\n return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num))\n return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) โก 1 if a is a square (mod p), quadratic residue\n * * (a | p) โก -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) โก 0 if a โก 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?\nisLE = false, opts = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength = undefined;\n let _sqrt = undefined;\n let modFromBytes = false;\n let allowedLengths = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE)\n throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS)\n _nbitLength = _opts.BITS;\n if (_opts.sqrt)\n _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean')\n isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean')\n modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n }\n else {\n if (typeof bitLenOrOpts === 'number')\n _nbitLength = bitLenOrOpts;\n if (opts.sqrt)\n _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP; // cached sqrtP\n const f = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: _sqrt ||\n ((n) => {\n if (!sqrtP)\n sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n });\n return Object.freeze(f);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes } from \"./utils.js\";\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from \"../utils.js\";\nimport { Field, FpInvertBatch, nLength, validateField } from \"./modular.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ(c, points) {\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / ๐) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(๐โ1) * (Math.ceil(๐ / ๐) + 1), where:\n * - ๐ is the window size\n * - ๐ is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger(c, fieldN, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, fieldN, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar ร 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 ร 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 ร 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n// TODO: remove\n/** @deprecated */\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\nfunction createField(order, field, isLE) {\n if (field) {\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n//# sourceMappingURL=curve.js.map","/**\n * Short Weierstrass curve methods. The formula is: yยฒ = xยณ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils';\nimport { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from \"../utils.js\";\nimport { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from \"./curve.js\";\nimport { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from \"./modular.js\";\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n const optsn = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function _normFnElement(Fn, key) {\n const { BYTES: expected } = Fn;\n let num;\n if (typeof key === 'bigint') {\n num = key;\n }\n else {\n let bytes = ensureBytes('private key', key);\n try {\n num = Fn.fromBytes(bytes);\n }\n catch (error) {\n throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);\n }\n }\n if (!Fn.isValidNot0(num))\n throw new Error('invalid private key: out of range [1..N-1]');\n return num;\n}\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * @example\n```js\nconst opts = {\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n};\nconst p256_Point = weierstrass(opts);\n```\n */\nexport function weierstrassN(params, extraOpts = {}) {\n const validated = _createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n _validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n wrapPrivateKey: 'boolean',\n });\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // yยฒ = xยณ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = yยฒ ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;\n const isHeadOdd = (head & 1) === 1; // ECDSA-specific\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // xยฒ * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // xยณ + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: yยฒ == xยณ + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y); // yยฒ\n const right = weierstrassEquation(x); // xยณ + ax + b\n return Fp.eql(left, right);\n }\n // Validate whether the passed curve params are valid.\n // Test 1: equation yยฒ = xยณ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant ฮ part should be non-zero: 4aยณ + 27bยฒ != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (X, Y, Z) โ (x=X/Z, y=Y/Z)\n const toAffineMemo = memoized((p, iz) => {\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) โ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(ensureBytes('pointHex', hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo } = extraOpts;\n if (!Fn.isValidNot0(scalar))\n throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point, fake; // Fake point is used to const-time mult\n const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n }\n else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n const { endo } = extraOpts;\n const p = this;\n if (!Fn.isValid(sc))\n throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p; // fast-path\n if (wnaf.hasCache(this))\n return this.multiply(sc);\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n }\n else {\n return wnaf.unsafe(p, sc);\n }\n }\n multiplyAndAddUnsafe(Q, a, b) {\n const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));\n return sum.is0() ? undefined : sum;\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n return toAffineMemo(this, invertedZ);\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n // TODO: remove\n get px() {\n return this.X;\n }\n get py() {\n return this.X;\n }\n get pz() {\n return this.Z;\n }\n toRawBytes(isCompressed = true) {\n return this.toBytes(isCompressed);\n }\n _setWindowSize(windowSize) {\n this.precompute(windowSize);\n }\n static normalizeZ(points) {\n return normalizeZ(Point, points);\n }\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(_normFnElement(Fn, privateKey));\n }\n }\n // base / generator point\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n Point.Fp = Fp;\n // scalar field\n Point.Fn = Fn;\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n function isValidSecretKey(secretKey) {\n try {\n return !!_normFnElement(Fn, secretKey);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)) {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey, isCompressed = true) {\n return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);\n }\n function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n if (typeof item === 'bigint')\n return false;\n if (item instanceof Point)\n return true;\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (Fn.allowedLengths || secretKey === publicKey)\n return undefined;\n const l = ensureBytes('key', item).length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = _normFnElement(Fn, secretKeyA);\n const b = Point.fromHex(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n // TODO: remove\n isValidPrivateKey: isValidSecretKey,\n randomPrivateKey: randomSecretKey,\n normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),\n precompute(windowSize = 8, point = Point.BASE) {\n return point.precompute(windowSize, false);\n },\n };\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n * We need `hash` for 2 features:\n * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`\n * 2. k generation in `sign`, using HMAC-drbg(hash)\n *\n * ECDSAOpts are only rarely needed.\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n ahash(hash);\n _validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;\n const hmac = ecdsaOpts.hmac ||\n ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts = {\n prehash: false,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,\n format: undefined, //'compact' as ECDSASigFormat,\n extraEntropy: false,\n };\n const defaultSigOpts_format = 'compact';\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer, `${format} signature`);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null)\n this.recovery = recovery;\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts_format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = Fn.BYTES;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(messageHash) {\n const FIELD_ORDER = Fp.ORDER;\n const { r, s, recovery: rec } = this;\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;\n if (hasCofactor && rec > 1)\n throw new Error('recovery id is ambiguous for h>1 curve');\n const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('recovery id 2 or 3 invalid');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0())\n throw new Error('point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts_format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const r = Fn.toBytes(this.r);\n const s = Fn.toBytes(this.s);\n if (format === 'recovered') {\n if (this.recovery == null)\n throw new Error('recovery bit must be present');\n return concatBytes(Uint8Array.of(this.recovery), r, s);\n }\n return concatBytes(r, s);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n // TODO: remove\n assertValidity() { }\n static fromCompact(hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'compact');\n }\n static fromDER(hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'der');\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;\n }\n toDERRawBytes() {\n return this.toBytes('der');\n }\n toDERHex() {\n return bytesToHex(this.toBytes('der'));\n }\n toCompactRawBytes() {\n return this.toBytes('compact');\n }\n toCompactHex() {\n return bytesToHex(this.toBytes('compact'));\n }\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = ecdsaOpts.bits2int ||\n function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, privateKey, opts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = kโ
G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b โ [1,qโ1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // mod n, not mod p\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = kโ
G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G ร k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n message = ensureBytes('message', message);\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig;\n }\n function tryParsingSig(sg) {\n // Try to deduce format\n let sig = undefined;\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj = !isHex &&\n sg !== null &&\n typeof sg === 'object' &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n if (isObj) {\n sig = new Signature(sg.r, sg.s);\n }\n else if (isHex) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n }\n if (!sig) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');\n }\n catch (error) {\n return false;\n }\n }\n }\n if (!sig)\n return false;\n return sig;\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1โ
G + u2โ
P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = ensureBytes('publicKey', publicKey);\n message = validateMsgAndHash(ensureBytes('message', message), prehash);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const sig = format === undefined\n ? tryParsingSig(signature)\n : Signature.fromBytes(ensureBytes('sig', signature), format);\n if (sig === false)\n return false;\n try {\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1โ
G + u2โ
P\n if (R.is0())\n return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n });\n}\n/** @deprecated use `weierstrass` in newer releases */\nexport function weierstrassPoints(c) {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n return _weierstrass_new_output_to_legacy(c, Point);\n}\nfunction _weierstrass_legacy_opts_to_new(c) {\n const CURVE = {\n a: c.a,\n b: c.b,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n let allowedLengths = c.allowedPrivateKeyLengths\n ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))\n : undefined;\n const Fn = Field(CURVE.n, {\n BITS: c.nBitLength,\n allowedLengths: allowedLengths,\n modFromBytes: c.wrapPrivateKey,\n });\n const curveOpts = {\n Fp,\n Fn,\n allowInfinityPoint: c.allowInfinityPoint,\n endo: c.endo,\n isTorsionFree: c.isTorsionFree,\n clearCofactor: c.clearCofactor,\n fromBytes: c.fromBytes,\n toBytes: c.toBytes,\n };\n return { CURVE, curveOpts };\n}\nfunction _ecdsa_legacy_opts_to_new(c) {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const ecdsaOpts = {\n hmac: c.hmac,\n randomBytes: c.randomBytes,\n lowS: c.lowS,\n bits2int: c.bits2int,\n bits2int_modN: c.bits2int_modN,\n };\n return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };\n}\nexport function _legacyHelperEquat(Fp, a, b) {\n /**\n * yยฒ = xยณ + ax + b: Short weierstrass curve formula. Takes x, returns yยฒ.\n * @returns yยฒ\n */\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // xยฒ * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // xยณ + a * x + b\n }\n return weierstrassEquation;\n}\nfunction _weierstrass_new_output_to_legacy(c, Point) {\n const { Fp, Fn } = Point;\n function isWithinCurveOrder(num) {\n return inRange(num, _1n, Fn.ORDER);\n }\n const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);\n return Object.assign({}, {\n CURVE: c,\n Point: Point,\n ProjectivePoint: Point,\n normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),\n weierstrassEquation,\n isWithinCurveOrder,\n });\n}\nfunction _ecdsa_new_output_to_legacy(c, _ecdsa) {\n const Point = _ecdsa.Point;\n return Object.assign({}, _ecdsa, {\n ProjectivePoint: Point,\n CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),\n });\n}\n// _ecdsa_legacy\nexport function weierstrass(c) {\n const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n const signs = ecdsa(Point, hash, ecdsaOpts);\n return _ecdsa_new_output_to_legacy(c, signs);\n}\n//# sourceMappingURL=weierstrass.js.map","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { weierstrass } from \"./abstract/weierstrass.js\";\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash) {\n return { hash };\n}\n/** @deprecated use new `weierstrass()` and `ecdsa()` methods */\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, hash: hash });\n return { ...create(defHash), create };\n}\n//# sourceMappingURL=_shortw_utils.js.map","/**\n * Internal module for NIST P256, P384, P521 curves.\n * Do not use for now.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';\nimport { createCurve } from \"./_shortw_utils.js\";\nimport { createHasher } from \"./abstract/hash-to-curve.js\";\nimport { Field } from \"./abstract/modular.js\";\nimport { mapToCurveSimpleSWU, } from \"./abstract/weierstrass.js\";\n// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n\n// a = Fp256.create(BigInt('-3'));\nconst p256_CURVE = {\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n};\n// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n\nconst p384_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'),\n n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n h: BigInt(1),\n a: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'),\n b: BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'),\n Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n};\n// p = 2n**521n - 1n\nconst p521_CURVE = {\n p: BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),\n n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n h: BigInt(1),\n a: BigInt('0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'),\n b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),\n Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n};\nconst Fp256 = Field(p256_CURVE.p);\nconst Fp384 = Field(p384_CURVE.p);\nconst Fp521 = Field(p521_CURVE.p);\nfunction createSWU(Point, opts) {\n const map = mapToCurveSimpleSWU(Point.Fp, opts);\n return (scalars) => map(scalars[0]);\n}\n/** NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. */\nexport const p256 = createCurve({ ...p256_CURVE, Fp: Fp256, lowS: false }, sha256);\n/** Hashing / encoding to p256 points / field. RFC 9380 methods. */\nexport const p256_hasher = /* @__PURE__ */ (() => {\n return createHasher(p256.Point, createSWU(p256.Point, {\n A: p256_CURVE.a,\n B: p256_CURVE.b,\n Z: p256.Point.Fp.create(BigInt('-10')),\n }), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: p256_CURVE.p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n });\n})();\n// export const p256_oprf: OPRF = createORPF({\n// name: 'P256-SHA256',\n// Point: p256.Point,\n// hash: sha256,\n// hashToGroup: p256_hasher.hashToCurve,\n// hashToScalar: p256_hasher.hashToScalar,\n// });\n/** NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. */\nexport const p384 = createCurve({ ...p384_CURVE, Fp: Fp384, lowS: false }, sha384);\n/** Hashing / encoding to p384 points / field. RFC 9380 methods. */\nexport const p384_hasher = /* @__PURE__ */ (() => {\n return createHasher(p384.Point, createSWU(p384.Point, {\n A: p384_CURVE.a,\n B: p384_CURVE.b,\n Z: p384.Point.Fp.create(BigInt('-12')),\n }), {\n DST: 'P384_XMD:SHA-384_SSWU_RO_',\n encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n p: p384_CURVE.p,\n m: 1,\n k: 192,\n expand: 'xmd',\n hash: sha384,\n });\n})();\n// export const p384_oprf: OPRF = createORPF({\n// name: 'P384-SHA384',\n// Point: p384.Point,\n// hash: sha384,\n// hashToGroup: p384_hasher.hashToCurve,\n// hashToScalar: p384_hasher.hashToScalar,\n// });\n// const Fn521 = Field(p521_CURVE.n, { allowedScalarLengths: [65, 66] });\n/** NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. */\nexport const p521 = createCurve({ ...p521_CURVE, Fp: Fp521, lowS: false, allowedPrivateKeyLengths: [130, 131, 132] }, sha512);\n/** @deprecated use `p256` for consistency with `p256_hasher` */\nexport const secp256r1 = p256;\n/** @deprecated use `p384` for consistency with `p384_hasher` */\nexport const secp384r1 = p384;\n/** @deprecated use `p521` for consistency with `p521_hasher` */\nexport const secp521r1 = p521;\n/** Hashing / encoding to p521 points / field. RFC 9380 methods. */\nexport const p521_hasher = /* @__PURE__ */ (() => {\n return createHasher(p521.Point, createSWU(p521.Point, {\n A: p521_CURVE.a,\n B: p521_CURVE.b,\n Z: p521.Point.Fp.create(BigInt('-4')),\n }), {\n DST: 'P521_XMD:SHA-512_SSWU_RO_',\n encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n p: p521_CURVE.p,\n m: 1,\n k: 256,\n expand: 'xmd',\n hash: sha512,\n });\n})();\n// export const p521_oprf: OPRF = createORPF({\n// name: 'P521-SHA512',\n// Point: p521.Point,\n// hash: sha512,\n// hashToGroup: p521_hasher.hashToCurve,\n// hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC\n// });\n//# sourceMappingURL=nist.js.map","/**\n * NIST secp256r1 aka p256.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {} from \"./abstract/hash-to-curve.js\";\nimport { p256_hasher, p256 as p256n } from \"./nist.js\";\n/** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */\nexport const p256 = p256n;\n/** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */\nexport const secp256r1 = p256n;\n/** @deprecated use `import { p256_hasher } from '@noble/curves/nist.js';` */\nexport const hashToCurve = /* @__PURE__ */ (() => p256_hasher.hashToCurve)();\n/** @deprecated use `import { p256_hasher } from '@noble/curves/nist.js';` */\nexport const encodeToCurve = /* @__PURE__ */ (() => p256_hasher.encodeToCurve)();\n//# sourceMappingURL=p256.js.map","import { p256 } from '@noble/curves/p256';\nexport const compressPubkey = (pubkeyBytes) => {\n const point = p256.ProjectivePoint.fromHex(pubkeyBytes);\n return point.toRawBytes(true);\n};\nexport const decompressPubkey = (compressed) => {\n if (compressed.length !== 33) {\n throw new Error('Expected 33 byte compress pubkey');\n }\n const point = p256.ProjectivePoint.fromHex(compressed);\n return point.toRawBytes(false);\n};\n//# sourceMappingURL=encoding.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map","import { p256 } from '@noble/curves/p256';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { equals as ui8equals } from 'uint8arrays';\nimport { P256_DID_PREFIX } from '../const.js';\nimport { extractMultikey, extractPrefixedBytes, hasPrefix } from '../utils.js';\nexport const verifyDidSig = async (did, data, sig, opts) => {\n const prefixedBytes = extractPrefixedBytes(extractMultikey(did));\n if (!hasPrefix(prefixedBytes, P256_DID_PREFIX)) {\n throw new Error(`Not a P-256 did:key: ${did}`);\n }\n const keyBytes = prefixedBytes.slice(P256_DID_PREFIX.length);\n return verifySig(keyBytes, data, sig, opts);\n};\nexport const verifySig = async (publicKey, data, sig, opts) => {\n const allowMalleable = opts?.allowMalleableSig ?? false;\n const msgHash = await sha256(data);\n return p256.verify(sig, msgHash, publicKey, {\n format: opts?.format ?? (allowMalleable ? undefined : 'compact'),\n lowS: !allowMalleable,\n });\n};\nexport const isCompactFormat = (sig) => {\n try {\n const parsed = p256.Signature.fromCompact(sig);\n return ui8equals(parsed.toCompactRawBytes(), sig);\n }\n catch {\n return false;\n }\n};\n//# sourceMappingURL=operations.js.map","import { P256_DID_PREFIX, P256_JWT_ALG } from '../const.js';\nimport { compressPubkey, decompressPubkey } from './encoding.js';\nimport { verifyDidSig } from './operations.js';\nexport const p256Plugin = {\n prefix: P256_DID_PREFIX,\n jwtAlg: P256_JWT_ALG,\n verifySignature: verifyDidSig,\n compressPubkey,\n decompressPubkey,\n};\n//# sourceMappingURL=plugin.js.map","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ฯ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createCurve } from \"./_shortw_utils.js\";\nimport { createHasher, isogenyMap, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, mod, pow2 } from \"./abstract/modular.js\";\nimport { _normFnElement, mapToCurveSimpleSWU, } from \"./abstract/weierstrass.js\";\nimport { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * โn = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey) === true;\n * ```\n */\nexport const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(utf8ToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();\nconst hasEven = (y) => y % _2n === _0n;\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = _normFnElement(Fn, priv);\n const p = BASE.multiply(d_); // P = d'โ
G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x โฅ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = xยณ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'โฅn. Ret bytes(d'โ
G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn } = Pointk1;\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'โ
G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fn, BASE } = Pointk1;\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r โฅ p.\n if (!inRange(r, _1n, secp256k1_CURVE.p))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s โฅ n.\n if (!inRange(s, _1n, secp256k1_CURVE.n))\n return false;\n // int(challenge(bytes(r)||bytes(P)||m))%n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = sโ
G - eโ
P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) โ r.\n if (R.is0() || !hasEven(y) || x !== r)\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)) => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n // TODO: remove\n secp256k1.utils.randomSecretKey;\n function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };\n }\n return {\n keygen,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey: randomSecretKey,\n randomPrivateKey: randomSecretKey,\n taggedHash,\n // TODO: remove\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n mod,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\n };\n})();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n}))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { secp256k1 as k256 } from '@noble/curves/secp256k1';\nexport const compressPubkey = (pubkeyBytes) => {\n const point = k256.ProjectivePoint.fromHex(pubkeyBytes);\n return point.toRawBytes(true);\n};\nexport const decompressPubkey = (compressed) => {\n if (compressed.length !== 33) {\n throw new Error('Expected 33 byte compress pubkey');\n }\n const point = k256.ProjectivePoint.fromHex(compressed);\n return point.toRawBytes(false);\n};\n//# sourceMappingURL=encoding.js.map","import { secp256k1 as k256 } from '@noble/curves/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport * as ui8 from 'uint8arrays';\nimport { SECP256K1_DID_PREFIX } from '../const.js';\nimport { extractMultikey, extractPrefixedBytes, hasPrefix } from '../utils.js';\nexport const verifyDidSig = async (did, data, sig, opts) => {\n const prefixedBytes = extractPrefixedBytes(extractMultikey(did));\n if (!hasPrefix(prefixedBytes, SECP256K1_DID_PREFIX)) {\n throw new Error(`Not a secp256k1 did:key: ${did}`);\n }\n const keyBytes = prefixedBytes.slice(SECP256K1_DID_PREFIX.length);\n return verifySig(keyBytes, data, sig, opts);\n};\nexport const verifySig = async (publicKey, data, sig, opts) => {\n const allowMalleable = opts?.allowMalleableSig ?? false;\n const msgHash = await sha256(data);\n return k256.verify(sig, msgHash, publicKey, {\n format: opts?.format ?? (allowMalleable ? undefined : 'compact'),\n lowS: !allowMalleable,\n });\n};\nexport const isCompactFormat = (sig) => {\n try {\n const parsed = k256.Signature.fromCompact(sig);\n return ui8.equals(parsed.toCompactRawBytes(), sig);\n }\n catch {\n return false;\n }\n};\n//# sourceMappingURL=operations.js.map","import { SECP256K1_DID_PREFIX, SECP256K1_JWT_ALG } from '../const.js';\nimport { compressPubkey, decompressPubkey } from './encoding.js';\nimport { verifyDidSig } from './operations.js';\nexport const secp256k1Plugin = {\n prefix: SECP256K1_DID_PREFIX,\n jwtAlg: SECP256K1_JWT_ALG,\n verifySignature: verifyDidSig,\n compressPubkey,\n decompressPubkey,\n};\n//# sourceMappingURL=plugin.js.map","import { p256Plugin } from './p256/plugin.js';\nimport { secp256k1Plugin } from './secp256k1/plugin.js';\nexport const plugins = [p256Plugin, secp256k1Plugin];\n//# sourceMappingURL=plugins.js.map","import * as uint8arrays from 'uint8arrays';\nimport { BASE58_MULTIBASE_PREFIX, DID_KEY_PREFIX, P256_JWT_ALG, SECP256K1_JWT_ALG, } from './const.js';\nimport { multibaseToBytes } from './multibase.js';\nimport { plugins } from './plugins.js';\nimport { extractMultikey, extractPrefixedBytes, hasPrefix } from './utils.js';\nexport const parseMultikey = (multikey) => {\n const prefixedBytes = extractPrefixedBytes(multikey);\n const plugin = plugins.find((p) => hasPrefix(prefixedBytes, p.prefix));\n if (!plugin) {\n throw new Error('Unsupported key type');\n }\n const keyBytes = plugin.decompressPubkey(prefixedBytes.slice(plugin.prefix.length));\n return {\n jwtAlg: plugin.jwtAlg,\n keyBytes,\n };\n};\nexport const formatMultikey = (jwtAlg, keyBytes) => {\n const plugin = plugins.find((p) => p.jwtAlg === jwtAlg);\n if (!plugin) {\n throw new Error('Unsupported key type');\n }\n const prefixedBytes = uint8arrays.concat([\n plugin.prefix,\n plugin.compressPubkey(keyBytes),\n ]);\n return (BASE58_MULTIBASE_PREFIX + uint8arrays.toString(prefixedBytes, 'base58btc'));\n};\nexport const parseDidKey = (did) => {\n const multikey = extractMultikey(did);\n return parseMultikey(multikey);\n};\nexport function formatDidKey(jwtAlg, keyBytes) {\n return `${DID_KEY_PREFIX}${formatMultikey(jwtAlg, keyBytes)}`;\n}\nexport function formatDidVerificationMethod(key) {\n switch (key.type) {\n case 'EcdsaSecp256r1VerificationKey2019': {\n const keyBytes = multibaseToBytes(key.publicKeyMultibase);\n return formatDidKey(P256_JWT_ALG, keyBytes);\n }\n case 'EcdsaSecp256k1VerificationKey2019': {\n const keyBytes = multibaseToBytes(key.publicKeyMultibase);\n return formatDidKey(SECP256K1_JWT_ALG, keyBytes);\n }\n case 'Multikey': {\n const { jwtAlg, keyBytes } = parseMultikey(key.publicKeyMultibase);\n return formatDidKey(jwtAlg, keyBytes);\n }\n default: {\n throw new Error(`Unsupported verification method type: ${key.type}`);\n }\n }\n}\n//# sourceMappingURL=did.js.map","/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See https://soatok.blog/2021/11/17/understanding-hkdf/.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\nimport { ahash, anumber, clean, toBytes } from \"./utils.js\";\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n */\nexport function expand(hash, prk, info, length = 32) {\n ahash(hash);\n anumber(length);\n const olen = hash.outputLen;\n if (length > 255 * olen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * olen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, olen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n clean(T, HKDF_COUNTER);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n * @example\n * import { hkdf } from '@noble/hashes/hkdf';\n * import { sha256 } from '@noble/hashes/sha2';\n * import { randomBytes } from '@noble/hashes/utils';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = 'application-key';\n * const hk1 = hkdf(sha256, inputKey, salt, info, 32);\n */\nexport const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map","import { expand, extract } from '@noble/hashes/hkdf';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha256 } from '@noble/hashes/sha256';\nexport const hmacSha256 = (key, data) => {\n return hmac(sha256, key, data);\n};\n// The two halves of HKDF, per RFC 5869 ยง2.2 and ยง2.3.\nexport const hkdfExtractSha256 = (salt, ikm) => {\n return extract(sha256, ikm, salt);\n};\nexport const hkdfExpandSha256 = (prk, info, length) => {\n return expand(sha256, prk, info, length);\n};\n//# sourceMappingURL=hmac.js.map","import * as noble from '@noble/hashes/utils';\nimport * as uint8arrays from 'uint8arrays';\nimport { sha256 } from './sha.js';\nexport const randomBytes = noble.randomBytes;\nexport const randomStr = (byteLength, encoding) => {\n const bytes = randomBytes(byteLength);\n return uint8arrays.toString(bytes, encoding);\n};\nexport const randomIntFromSeed = async (seed, high, low = 0) => {\n const hash = await sha256(seed);\n const number = Buffer.from(hash).readUintBE(0, 6);\n const range = high - low;\n const normalized = number % range;\n return normalized + low;\n};\n//# sourceMappingURL=random.js.map","import * as uint8arrays from 'uint8arrays';\nimport { parseDidKey } from './did.js';\nimport { plugins } from './plugins.js';\nexport const verifySignature = (didKey, data, sig, opts) => {\n const parsed = parseDidKey(didKey);\n if (opts?.jwtAlg && opts.jwtAlg !== parsed.jwtAlg) {\n throw new Error(`Expected key alg ${opts.jwtAlg}, got ${parsed.jwtAlg}`);\n }\n const plugin = plugins.find((p) => p.jwtAlg === parsed.jwtAlg);\n if (!plugin) {\n throw new Error(`Unsupported signature alg: ${parsed.jwtAlg}`);\n }\n return plugin.verifySignature(didKey, data, sig, opts);\n};\nexport const verifySignatureUtf8 = async (didKey, data, sig, opts) => {\n const dataBytes = uint8arrays.fromString(data, 'utf8');\n const sigBytes = uint8arrays.fromString(sig, 'base64url');\n return verifySignature(didKey, dataBytes, sigBytes, opts);\n};\n//# sourceMappingURL=verify.js.map","import { p256 } from '@noble/curves/p256';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { fromString as ui8FromString, toString as ui8ToString, } from 'uint8arrays';\nimport { P256_JWT_ALG } from '../const.js';\nimport * as did from '../did.js';\nexport class P256Keypair {\n constructor(privateKey, exportable) {\n this.privateKey = privateKey;\n this.exportable = exportable;\n this.jwtAlg = P256_JWT_ALG;\n this.publicKey = p256.getPublicKey(privateKey);\n }\n static async create(opts) {\n const { exportable = false } = opts || {};\n const privKey = p256.utils.randomPrivateKey();\n return new P256Keypair(privKey, exportable);\n }\n static async import(privKey, opts) {\n const { exportable = false } = opts || {};\n const privKeyBytes = typeof privKey === 'string' ? ui8FromString(privKey, 'hex') : privKey;\n return new P256Keypair(privKeyBytes, exportable);\n }\n publicKeyBytes() {\n return this.publicKey;\n }\n publicKeyStr(encoding = 'base64pad') {\n return ui8ToString(this.publicKey, encoding);\n }\n did() {\n return did.formatDidKey(this.jwtAlg, this.publicKey);\n }\n async sign(msg) {\n const msgHash = await sha256(msg);\n // return raw 64 byte sig not DER-encoded\n const sig = await p256.sign(msgHash, this.privateKey, { lowS: true });\n return sig.toCompactRawBytes();\n }\n /**\n * Elliptic-curve Diffie-Hellman with another P-256 public key (compressed or\n * uncompressed). Returns the 32-byte x-coordinate of the shared point.\n */\n ecdh(publicKey) {\n const sharedPoint = p256.getSharedSecret(this.privateKey, publicKey, true);\n return sharedPoint.slice(1);\n }\n async export() {\n if (!this.exportable) {\n throw new Error('Private key is not exportable');\n }\n return this.privateKey;\n }\n}\n//# sourceMappingURL=keypair.js.map","export function toHexString(number) {\n return `0x${number.toString(16).padStart(2, '0')}`;\n}\nexport function isUint8(val) {\n return Number.isInteger(val) && val >= 0 && val < 256;\n}\n//# sourceMappingURL=util.js.map","/**\n * Checks whether the input is an object (not null).\n *\n * Returns true for any non-null value with typeof 'object', including\n * arrays, plain objects, class instances, etc.\n *\n * @param input - The value to check\n * @returns `true` if the input is an object (not null)\n *\n * @example\n * ```typescript\n * import { isObject } from '@atproto/lex-data'\n *\n * isObject({}) // true\n * isObject([1, 2, 3]) // true\n * isObject(new Date()) // true\n * isObject(null) // false\n * isObject('string') // false\n * ```\n */\nexport function isObject(input) {\n return input != null && typeof input === 'object';\n}\nconst ObjectProto = Object.prototype;\nconst ObjectToString = Object.prototype.toString;\n/**\n * Checks whether the input is a plain object.\n *\n * A plain object is an object (not null) whose prototype is either null\n * or `Object.prototype`. This excludes arrays, class instances, and other\n * special objects.\n *\n * @param input - The value to check\n * @returns `true` if the input is a plain object\n *\n * @example\n * ```typescript\n * import { isPlainObject } from '@atproto/lex-data'\n *\n * isPlainObject({}) // true\n * isPlainObject({ a: 1 }) // true\n * isPlainObject(Object.create(null)) // true\n * isPlainObject([1, 2, 3]) // false\n * isPlainObject(new Date()) // false\n * isPlainObject(null) // false\n * ```\n */\nexport function isPlainObject(input) {\n return isObject(input) && isPlainProto(input);\n}\n/**\n * Checks whether the prototype of an object is plain (null or Object.prototype).\n *\n * This is useful for checking if an object is a plain object without\n * checking that it's non-null first (the null check is already done).\n *\n * @param input - The object to check (must be non-null)\n * @returns `true` if the object's prototype is plain\n *\n * @example\n * ```typescript\n * import { isPlainProto } from '@atproto/lex-data'\n *\n * isPlainProto({}) // true\n * isPlainProto(Object.create(null)) // true\n * isPlainProto([1, 2, 3]) // false (Array.prototype)\n * isPlainProto(new Date()) // false (Date.prototype)\n * ```\n */\nexport function isPlainProto(input) {\n const proto = Object.getPrototypeOf(input);\n if (proto === null)\n return true;\n return ((proto === ObjectProto ||\n // Needed to support NodeJS's `runInNewContext` which produces objects\n // with a different prototype\n Object.getPrototypeOf(proto) === null) &&\n ObjectToString.call(input) === '[object Object]');\n}\n//# sourceMappingURL=object.js.map","// Use Buffer in Node.js but don't speak its name directly to avoid bundlers\n// pulling in the `Buffer` polyfill\nconst BUFFER = /*#__PURE__*/ (() => 'Bu' + 'f'.repeat(2) + 'er')();\nconst useBuffer = globalThis.process != null &&\n // @ts-expect-error\n !globalThis.process.browser &&\n typeof globalThis[BUFFER] === 'function' &&\n typeof globalThis[BUFFER].isBuffer === 'function';\nexport const NodeJSBuffer = useBuffer\n ? globalThis[BUFFER]\n : /* v8 ignore next -- @preserve */ null;\nexport const isNodeJSBuffer = NodeJSBuffer\n ? NodeJSBuffer.isBuffer\n : /* v8 ignore next -- @preserve */ (_) => false;\n//# sourceMappingURL=nodejs-buffer.js.map","import { NodeJSBuffer } from './lib/nodejs-buffer.js';\nconst Buffer = NodeJSBuffer;\nexport const ui8ConcatNode = Buffer\n ? function ui8ConcatNode(items) {\n const array = Array.from(items, (arrayLike) => arrayLike instanceof Uint8Array ? arrayLike : Buffer.from(arrayLike));\n const buffer = Buffer.concat(array);\n // Do *not* return a Buffer to avoid differences between NodeJSBuffer\n // and Uint8Array regarding some operations (e.g., `slice`, `subarray`,\n // etc.).\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n : /* v8 ignore next -- @preserve */ null;\nexport function ui8ConcatPonyfill(items) {\n let totalLength = 0;\n // Consume the iterable once (e.g. in case it is a generator)\n const array = [];\n for (const arrayLike of items) {\n const { length } = arrayLike;\n if (length !== 0) {\n totalLength += length;\n array.push(arrayLike);\n }\n }\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arrayLike of array) {\n result.set(arrayLike, offset);\n offset += arrayLike.length;\n }\n return result;\n}\n//# sourceMappingURL=uint8array-concat.js.map","import { base64, base64pad, base64url, base64urlpad, } from 'multiformats/bases/base64';\nimport { NodeJSBuffer } from './lib/nodejs-buffer.js';\nconst Buffer = NodeJSBuffer;\nexport const fromBase64Native = typeof Uint8Array.fromBase64 === 'function'\n ? function fromBase64Native(b64, alphabet = 'base64') {\n return Uint8Array.fromBase64(b64, {\n alphabet,\n lastChunkHandling: 'loose',\n });\n }\n : /* v8 ignore next -- @preserve */ null;\nexport const fromBase64Node = Buffer\n ? function fromBase64Node(b64, alphabet = 'base64') {\n const bytes = Buffer.from(b64, alphabet);\n verifyBase64ForBytes(b64, bytes);\n // Convert to Uint8Array because even though Buffer is a sub class of\n // Uint8Array, it serializes differently to Uint8Array (e.g. in JSON) and\n // results in unexpected behavior downstream (e.g. in tests)\n return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n }\n : /* v8 ignore next -- @preserve */ null;\nexport function fromBase64Ponyfill(b64, alphabet = 'base64') {\n const isPadded = b64.endsWith('=');\n const base = alphabet === 'base64url'\n ? isPadded\n ? base64urlpad\n : base64url\n : isPadded\n ? base64pad\n : base64;\n // @NOTE multiformats requires the prefix to be present, which is definitely\n // not optimal. It might be worth considering a different library here.\n const bytes = base.decoder.decode(`${base.prefix}${b64}`);\n verifyBase64ForBytes(b64, bytes);\n return bytes;\n}\n// @NOTE NodeJS will silently stop decoding at the first invalid character,\n// while \"multiformats\" will not validate that the padding is correct. The\n// following function performs basic validation to ensure that the input was a\n// valid base64 string. The availability of the \"bytes\" allows to perform checks\n// with O[1] complexity.\nfunction verifyBase64ForBytes(b64, bytes) {\n const paddingCount = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0;\n const trimmedLength = b64.length - paddingCount;\n const expectedByteLength = Math.floor((trimmedLength * 3) / 4);\n if (bytes.length !== expectedByteLength) {\n throw new Error('Invalid base64 string');\n }\n const expectedB64Length = (bytes.length / 3) * 4;\n const expectedPaddingCount = expectedB64Length % 4 === 0 ? 0 : 4 - (expectedB64Length % 4);\n const expectedFullB64Length = expectedB64Length + expectedPaddingCount;\n if (b64.length > expectedFullB64Length) {\n throw new Error('Invalid base64 string');\n }\n // The previous might still allow false positive if only the last few\n // chars are invalid.\n for (let i = Math.ceil(expectedB64Length); i < b64.length - paddingCount; i++) {\n const code = b64.charCodeAt(i);\n if (!(code >= 65 && code <= 90) && // A-Z\n !(code >= 97 && code <= 122) && // a-z\n !(code >= 48 && code <= 57) && // 0-9\n code !== 43 && // +\n code !== 47 // /\n ) {\n throw new Error('Invalid base64 string');\n }\n }\n}\n//# sourceMappingURL=uint8array-from-base64.js.map","import { base64, base64url } from 'multiformats/bases/base64';\nimport { NodeJSBuffer } from './lib/nodejs-buffer.js';\nconst Buffer = NodeJSBuffer;\nexport const toBase64Native = typeof Uint8Array.prototype.toBase64 === 'function'\n ? function toBase64Native(bytes, alphabet = 'base64') {\n return bytes.toBase64({ alphabet, omitPadding: true });\n }\n : /* v8 ignore next -- @preserve */ null;\nexport const toBase64Node = Buffer\n ? function toBase64Node(bytes, alphabet = 'base64') {\n const buffer = bytes instanceof Buffer ? bytes : Buffer.from(bytes);\n const b64 = buffer.toString(alphabet);\n // @NOTE We strip padding for strict compatibility with multiformats\n // behavior. Tests failing because of the presence of padding are not\n // really synonymous with an actual error and we might (should?) actually\n // want to keep the padding at some point.\n return b64.charCodeAt(b64.length - 1) === /* '=' */ 0x3d\n ? b64.charCodeAt(b64.length - 2) === /* '=' */ 0x3d\n ? b64.slice(0, -2) // '=='\n : b64.slice(0, -1) // '='\n : b64;\n }\n : /* v8 ignore next -- @preserve */ null;\nexport function toBase64Ponyfill(bytes, alphabet = 'base64') {\n const codec = alphabet === 'base64url' ? base64url : base64;\n // @NOTE multiformats requires to strip the prefix, which is definitely not\n // optimal. It might be worth considering a different library here.\n return codec.encoder.encode(bytes).slice(codec.prefix.length);\n}\n//# sourceMappingURL=uint8array-to-base64.js.map","import { isNodeJSBuffer } from './lib/nodejs-buffer.js';\nimport { isObject } from './object.js';\nimport { ui8ConcatNode, ui8ConcatPonyfill } from './uint8array-concat.js';\nimport { fromBase64Native, fromBase64Node, fromBase64Ponyfill, } from './uint8array-from-base64.js';\nimport { toBase64Native, toBase64Node, toBase64Ponyfill, } from './uint8array-to-base64.js';\n// @TODO drop dependency on uint8arrays package once Uint8Array.fromBase64 /\n// Uint8Array.prototype.toBase64 is widely supported, and mark fromBase64 /\n// toBase64 as deprecated. We can also drop NodeJS specific implementations\n// once NodeJS <24 is no longer supported.\n/**\n * Encodes a Uint8Array into a base64 string.\n *\n * Uses native Uint8Array.prototype.toBase64 when available (Node.js 24+, modern browsers),\n * falling back to Node.js Buffer or a ponyfill implementation.\n *\n * @param bytes - The binary data to encode\n * @param alphabet - The base64 alphabet to use ('base64' or 'base64url'), defaults to 'base64'\n * @returns The base64 encoded string\n *\n * @example\n * ```typescript\n * import { toBase64 } from '@atproto/lex-data'\n *\n * const bytes = new Uint8Array([72, 101, 108, 108, 111])\n * toBase64(bytes) // 'SGVsbG8='\n * toBase64(bytes, 'base64url') // 'SGVsbG8' (URL-safe, no padding)\n * ```\n */\nexport const toBase64 = \n/* v8 ignore next -- @preserve */ toBase64Native ??\n toBase64Node ??\n toBase64Ponyfill;\n/**\n * Decodes a base64 string into a Uint8Array.\n *\n * Supports both padded and unpadded base64 strings. Uses native\n * Uint8Array.fromBase64 when available, falling back to Node.js Buffer\n * or a ponyfill implementation.\n *\n * @param b64 - The base64 string to decode\n * @param alphabet - The base64 alphabet to use ('base64' or 'base64url'), defaults to 'base64'\n * @returns The decoded binary data\n * @throws If the input is not a valid base64 string\n *\n * @example\n * ```typescript\n * import { fromBase64 } from '@atproto/lex-data'\n *\n * fromBase64('SGVsbG8=') // Uint8Array([72, 101, 108, 108, 111])\n * fromBase64('SGVsbG8', 'base64url') // Same, URL-safe alphabet\n * ```\n */\nexport const fromBase64 = \n/* v8 ignore next -- @preserve */ fromBase64Native ??\n fromBase64Node ??\n fromBase64Ponyfill;\n/* v8 ignore next -- @preserve */\nif (toBase64 === toBase64Ponyfill || fromBase64 === fromBase64Ponyfill) {\n /*#__PURE__*/\n console.warn('[@atproto/lex-data]: Uint8Array.fromBase64 / Uint8Array.prototype.toBase64 not available in this environment. Falling back to ponyfill implementation.');\n}\n/**\n * Returns the input if it is a Uint8Array, otherwise returns undefined.\n *\n * @param input - The value to check\n * @returns The input if it's a Uint8Array, otherwise undefined\n *\n * @example\n * ```typescript\n * import { ifUint8Array } from '@atproto/lex-data'\n *\n * ifUint8Array(new Uint8Array([1, 2])) // Uint8Array([1, 2])\n * ifUint8Array('not binary') // undefined\n * ifUint8Array(new ArrayBuffer(4)) // undefined\n * ```\n */\nexport function ifUint8Array(input) {\n if (input instanceof Uint8Array) {\n return input;\n }\n return undefined;\n}\n/**\n * Coerces various binary data representations into a Uint8Array.\n *\n * Handles the following input types:\n * - `Buffer` (Node.js) - Converted to Uint8Array\n * - `Uint8Array` - Returned as-is\n * - `ArrayBufferView` (e.g., DataView, other TypedArrays) - Converted to Uint8Array\n * - `ArrayBuffer` - Wrapped in a Uint8Array\n * - `ArrayLike` objects (e.g., `number[]`, etc.) - Converted to Uint8Array\n *\n * @param input - The value to convert\n * @returns A Uint8Array, or `undefined` if the input could not be converted\n *\n * @example\n * ```typescript\n * import { asUint8Array } from '@atproto/lex-data'\n *\n * asUint8Array(new Uint8Array([1, 2])) // Uint8Array([1, 2])\n * asUint8Array(new ArrayBuffer(4)) // Uint8Array of length 4\n * asUint8Array(new Int16Array([1, 2])) // Uint8Array view of the buffer\n * asUint8Array([1, 2, 3]) // Uint8Array([1, 2, 3])\n * asUint8Array('string') // undefined\n * ```\n */\nexport function asUint8Array(input) {\n // In Node.js, if the input is a NodeJSBuffer, we turn it into an actual\n // Uint8Array to avoid discrepancies between NodeJSBuffer and Uint8Array\n // regarding some operations (e.g., `slice`, `subarray`, etc.).\n if (isNodeJSBuffer(input)) {\n return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);\n }\n if (input instanceof Uint8Array) {\n return input;\n }\n if (ArrayBuffer.isView(input)) {\n return new Uint8Array(input.buffer, input.byteOffset, input.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n }\n if (input instanceof ArrayBuffer) {\n return new Uint8Array(input);\n }\n if (isArrayLike(input)) {\n const { length } = input;\n const uint8Array = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n const value = input[i];\n if (!isUint8(value))\n return undefined;\n uint8Array[i] = value;\n }\n return uint8Array;\n }\n return undefined;\n}\nfunction isUint8(value) {\n return (typeof value === 'number' &&\n value >= 0 &&\n value <= 255 &&\n Number.isInteger(value));\n}\nexport function toUint8Array(input) {\n const bytes = asUint8Array(input);\n if (bytes)\n return bytes;\n throw new TypeError(`Cannot convert value to Uint8Array: ${String(input)}`);\n}\nfunction isArrayLike(input) {\n if (!isObject(input) || !('length' in input)) {\n return false;\n }\n const { length } = input;\n if (typeof length !== 'number' ||\n length < 0 ||\n !Number.isSafeInteger(length)) {\n return false;\n }\n for (let i = 0; i < length; i++) {\n // Array-like objects must have all indices from 0 to length - 1 defined (no\n // holes)\n if (!(i in input))\n return false;\n }\n return true;\n}\n/**\n * Compares two Uint8Arrays for byte-by-byte equality.\n *\n * @param a - First Uint8Array to compare\n * @param b - Second Uint8Array to compare\n * @returns `true` if both arrays have the same length and identical bytes\n *\n * @example\n * ```typescript\n * import { ui8Equals } from '@atproto/lex-data'\n *\n * ui8Equals(new Uint8Array([1, 2]), new Uint8Array([1, 2])) // true\n * ui8Equals(new Uint8Array([1, 2]), new Uint8Array([1, 3])) // false\n * ui8Equals(new Uint8Array([1]), new Uint8Array([1, 2])) // false\n * ```\n */\nexport function ui8Equals(a, b) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n/**\n * Concatenates multiple Uint8Arrays into a single Uint8Array.\n *\n * Uses Node.js Buffer.concat when available for performance,\n * falling back to a ponyfill implementation.\n *\n * @param arrays - The Uint8Arrays to concatenate\n * @returns A new Uint8Array containing all input bytes in order\n *\n * @example\n * ```typescript\n * import { ui8Concat } from '@atproto/lex-data'\n *\n * const a = new Uint8Array([1, 2])\n * const b = new Uint8Array([3, 4])\n * ui8Concat([a, b]) // Uint8Array([1, 2, 3, 4])\n * ```\n */\nexport const ui8Concat = \n/* v8 ignore next -- @preserve */ ui8ConcatNode ?? ui8ConcatPonyfill;\nexport async function ui8ConcatAsync(iterable) {\n const chunks = [];\n for await (const chunk of iterable)\n chunks.push(chunk);\n return ui8Concat(chunks);\n}\n//# sourceMappingURL=uint8array.js.map","import { CID } from 'multiformats/cid';\nimport { create as createDigest } from 'multiformats/hashes/digest';\nimport { sha256, sha512 } from 'multiformats/hashes/sha2';\nimport { isUint8, toHexString } from './lib/util.js';\nimport { isObject } from './object.js';\nimport { ui8Equals } from './uint8array.js';\n/**\n * Codec code that indicates the CID references a CBOR-encoded data structure.\n *\n * Used when encoding structured data in AT Protocol repositories.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport const CBOR_DATA_CODEC = 0x71;\n/**\n * Codec code that indicates the CID references raw binary data (like media blobs).\n *\n * Used in DASL CIDs for binary blobs like images and media.\n *\n * @see {@link https://dasl.ing/cid.html Content IDs (DASL)}\n */\nexport const RAW_DATA_CODEC = 0x55;\n/**\n * Hash code that indicates that a CID uses SHA-256.\n */\nexport const SHA256_HASH_CODE = sha256.code;\n/**\n * Hash code that indicates that a CID uses SHA-512.\n */\nexport const SHA512_HASH_CODE = sha512.code;\n/**\n * Compares two {@link Multihash} for equality.\n *\n * @param a - First {@link Multihash}\n * @param b - Second {@link Multihash}\n * @returns `true` if both multihashes have the same code and digest\n */\nexport function multihashEquals(a, b) {\n if (a === b)\n return true;\n return a.code === b.code && ui8Equals(a.digest, b.digest);\n}\n// multiformats' CID class is not very portable because:\n//\n// - In dependent packages that use \"moduleResolution\" set to \"node16\",\n// \"nodenext\" or \"bundler\", TypeScript fails to properly resolve the\n// multiformats package when importing CID from @atproto/lex-data. This causes\n// type errors in those packages. This is caused by the fact that the\n// multiformats version <10 (which is the last version that supports CommonJS)\n// uses \"exports\" field in package.json, which do not contain \"types\"\n// entrypoints.\n// https://www.npmjs.com/package/multiformats/v/9.9.0?activeTab=code\n// - By defining our own interface and helper functions, we can have more\n// control over the public API exposed by this package.\n// - It allow us to have a stable interface in case we need to swap out, or\n// eventually update multiformats (should we choose to drop CommonJS support)\n// in the future.\n// @NOTE Even though it is not portable, we still re-export CID here so that\n// dependent packages where it can be used, have access to it (instead of\n// importing directly from \"multiformats\" or \"multiformats/cid\").\nexport { /** @deprecated */ CID };\n/**\n * Converts a {@link Cid} to a multiformats {@link CID} instance.\n *\n * @deprecated Packages depending on `@atproto/lex-data` should use the\n * {@link Cid} interface instead of relying on `multiformats`'s {@link CID}\n * implementation directly. This is to avoid compatibility issues, and in order\n * to allow better portability, compatibility and future updates.\n */\nexport function asMultiformatsCID(input) {\n const cid = \n // Already a multiformats CID instance\n CID.asCID(input) ??\n // Create a new multiformats CID instance\n CID.create(input.version, input.code, createDigest(input.multihash.code, input.multihash.digest));\n // @NOTE: the \"satisfies\" operator is used here to ensure that the Cid\n // interface is indeed compatible with multiformats' CID implementation, which\n // allows us to safely rely on multiformats' CID implementation where Cid are\n // needed.\n return cid;\n}\n/**\n * Type guard to check if a CID is a raw binary CID.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is a version 1 CID with raw multicodec\n */\nexport function isRawCid(cid) {\n return cid.version === 1 && cid.code === RAW_DATA_CODEC;\n}\n/**\n * Type guard to check if a CID is DASL compliant.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is DASL compliant (v1, raw/dag-cbor, sha256)\n */\nexport function isDaslCid(cid) {\n return (cid.version === 1 &&\n (cid.code === RAW_DATA_CODEC || cid.code === CBOR_DATA_CODEC) &&\n cid.multihash.code === SHA256_HASH_CODE &&\n cid.multihash.digest.byteLength === 0x20 // Should always be 32 bytes (256 bits) for SHA-256, but double-checking anyways\n );\n}\n/**\n * Type guard to check if a CID is a DAG-CBOR CID.\n *\n * @param cid - The CID to check\n * @returns `true` if the CID is a DAG-CBOR CID (v1, dag-cbor, sha256)\n */\nexport function isCborCid(cid) {\n return cid.code === CBOR_DATA_CODEC && isDaslCid(cid);\n}\nexport function checkCid(cid, options) {\n switch (options?.flavor) {\n case undefined:\n return true;\n case 'cbor':\n return isCborCid(cid);\n case 'dasl':\n return isDaslCid(cid);\n case 'raw':\n return isRawCid(cid);\n default:\n throw new TypeError(`Unknown CID flavor: ${options?.flavor}`);\n }\n}\nexport function isCid(value, options) {\n return isCidImplementation(value) && checkCid(value, options);\n}\nexport function ifCid(value, options) {\n if (isCid(value, options))\n return value;\n return null;\n}\nexport function asCid(value, options) {\n if (isCid(value, options))\n return value;\n throw new Error(`Invalid ${options?.flavor ? `${options.flavor} CID` : 'CID'} \"${value}\"`);\n}\nexport function decodeCid(cidBytes, options) {\n const cid = CID.decode(cidBytes);\n return asCid(cid, options);\n}\n/**\n * Maximum length of a CID string accepted by {@link parseCid}.\n *\n * The longest CID {@link parseCid} can legitimately produce (CIDv1 with a\n * sha512 digest) is 110 characters in base32, 105 in base36 and 93 in\n * base58btc. Longer inputs are rejected before decoding because the base36\n * and base58btc decoders used by `multiformats` run in time quadratic in the\n * input length, which lets a single large string block the event loop.\n */\nexport const MAX_CID_STRING_LENGTH = 128;\nexport function parseCid(input, options) {\n if (input.length > MAX_CID_STRING_LENGTH) {\n throw new Error(`CID string too long (${input.length} > ${MAX_CID_STRING_LENGTH})`);\n }\n const cid = CID.parse(input);\n return asCid(cid, options);\n}\n/**\n * Validates that a string is a valid CID representation.\n *\n * Unlike {@link parseCid}, this function returns a boolean instead of throwing.\n * It also verifies that the string is the canonical representation of the CID.\n *\n * @param input - The string to validate\n * @param options - Optional flavor constraints\n * @returns `true` if the string is a valid CID\n */\nexport function validateCidString(input, options) {\n return parseCidSafe(input, options)?.toString() === input;\n}\nexport function parseCidSafe(input, options) {\n try {\n return parseCid(input, options);\n }\n catch {\n return null;\n }\n}\n/**\n * Ensures that a string is a valid CID representation.\n *\n * @param input - The string to validate\n * @param options - Optional flavor constraints\n * @throws If the string is not a valid CID\n */\nexport function ensureValidCidString(input, options) {\n if (!validateCidString(input, options)) {\n throw new Error(`Invalid CID string \"${input}\"`);\n }\n}\n/**\n * Verifies whether the multihash of a given {@link cid} matches the hash of the provided {@link bytes}.\n * @params cid The CID to match against the bytes.\n * @params bytes The bytes to verify.\n * @returns true if the CID matches the bytes, false otherwise.\n */\nexport async function isCidForBytes(cid, bytes) {\n if (cid.multihash.code === sha256.code) {\n const multihash = await sha256.digest(bytes);\n return multihashEquals(multihash, cid.multihash);\n }\n if (cid.multihash.code === sha512.code) {\n const multihash = await sha512.digest(bytes);\n return multihashEquals(multihash, cid.multihash);\n }\n // Don't know how to verify other multihash codes\n throw new Error(`Unsupported CID multihash code: ${toHexString(cid.multihash.code)}`);\n}\n/**\n * Creates a CID from a multicodec, multihash code, and digest.\n *\n * @param code - The multicodec content type code\n * @param multihashCode - The multihash algorithm code\n * @param digest - The raw hash digest bytes\n * @returns A new CIDv1 instance\n *\n * @example\n * ```typescript\n * import { createCid, RAW_DATA_CODEC, SHA256_HASH_CODE } from '@atproto/lex-data'\n *\n * const cid = createCid(RAW_DATA_CODEC, SHA256_HASH_CODE, hashDigest)\n * ```\n */\nexport function createCid(code, multihashCode, digest) {\n const cid = CID.createV1(code, createDigest(multihashCode, digest));\n return cid;\n}\n/**\n * Creates a DAG-CBOR CID for the given CBOR bytes.\n *\n * Computes the SHA-256 hash of the bytes and creates a CIDv1 with DAG-CBOR multicodec.\n *\n * @param bytes - The CBOR-encoded bytes to hash\n * @returns A promise that resolves to the CborCid\n */\nexport async function cidForCbor(bytes) {\n const multihash = await sha256.digest(bytes);\n return CID.createV1(CBOR_DATA_CODEC, multihash);\n}\n/**\n * Creates a raw CID for the given binary bytes.\n *\n * Computes the SHA-256 hash of the bytes and creates a CIDv1 with raw multicodec.\n *\n * @param bytes - The raw binary bytes to hash\n * @returns A promise that resolves to the RawCid\n */\nexport async function cidForRawBytes(bytes) {\n const multihash = await sha256.digest(bytes);\n return CID.createV1(RAW_DATA_CODEC, multihash);\n}\n/**\n * Creates a raw CID from an existing SHA-256 hash digest.\n *\n * @param digest - The SHA-256 hash digest (must be 32 bytes)\n * @returns A RawCid with the given digest\n * @throws If the digest is not a valid SHA-256 hash (not 32 bytes)\n */\nexport function cidForRawHash(digest) {\n // Fool-proofing\n if (digest.length !== 0x20) {\n throw new Error(`Invalid SHA-256 hash length: ${toHexString(digest.length)}`);\n }\n return createCid(RAW_DATA_CODEC, sha256.code, digest);\n}\nfunction isCidImplementation(value) {\n if (CID.asCID(value)) {\n // CIDs created using older multiformats versions did not have a \"bytes\"\n // property.\n return value.bytes != null;\n }\n else {\n // Unknown implementation, do a structural check\n try {\n if (!isObject(value))\n return false;\n const val = value;\n if (val.version !== 0 && val.version !== 1)\n return false;\n if (!isUint8(val.code))\n return false;\n if (!isObject(val.multihash))\n return false;\n const mh = val.multihash;\n if (!isUint8(mh.code))\n return false;\n if (!(mh.digest instanceof Uint8Array))\n return false;\n // Ensure that the bytes array is consistent with other properties\n if (!(val.bytes instanceof Uint8Array))\n return false;\n if (val.bytes[0] !== val.version)\n return false;\n if (val.bytes[1] !== val.code)\n return false;\n if (val.bytes[2] !== mh.code)\n return false;\n if (val.bytes[3] !== mh.digest.length)\n return false;\n if (val.bytes.length !== 4 + mh.digest.length)\n return false;\n if (!ui8Equals(val.bytes.subarray(4), mh.digest))\n return false;\n if (typeof val.equals !== 'function')\n return false;\n if (val.equals(val) !== true)\n return false;\n return true;\n }\n catch {\n return false;\n }\n }\n}\n//# sourceMappingURL=cid.js.map","import { ifCid, parseCid, validateCidString } from './cid.js';\nimport { isPlainObject, isPlainProto } from './object.js';\n/**\n * Options to use with {@link ifCid}, {@link validateCidString}, and related CID\n * validation functions when validating CIDs in BlobRefs, in strict mode. This\n * ensures that the CID is a {@link RawCid} (CID v1, raw multicodec, sha256\n * multihash), which is the expected format for blob references in the AT\n * Protocol data model.\n */\nconst STRICT_CID_CHECK_OPTIONS = { flavor: 'raw' };\n// Number.isSafeInteger is actually safe to use with non-number values, so we\n// can use it as a type guard.\nconst isSafeInteger = Number.isSafeInteger;\nexport function isBlobRef(input, options) {\n return input?.$type === 'blob'\n ? isTypedBlobRef(input, options)\n : isLegacyBlobRef(input, options);\n}\nexport function getBlobMime(blob) {\n return blob?.mimeType;\n}\n/**\n * Extracts the size (in bytes) from a {@link TypedBlobRef}. For\n * {@link LegacyBlobRef}, size information is not available, so this function\n * returns `undefined` for legacy refs.\n *\n * @note The size property, in blob refs, cannot be 100% trusted since the PDS\n * might not have a local copy of the blob (to check the size against) and might\n * just be passing through the blob ref from the client without validating it.\n * So, while this function can be useful for getting size information when\n * available, it should not be solely relied upon for critical functionality\n * without additional validation.\n *\n * @example\n * ```ts\n * const size = getBlobSize(blobRef)\n * if (size !== undefined) {\n * console.log(`Blob size: ${size} bytes`)\n * } else {\n * console.log('Size information not available for legacy blob ref')\n * }\n * ```\n */\nexport function getBlobSize(blob) {\n if ('$type' in blob && blob.size >= 0)\n return blob.size;\n // LegacyBlobRef doesn't have size information\n return undefined;\n}\nexport function getBlobCid(blob) {\n if (!blob)\n return undefined;\n return '$type' in blob ? blob.ref : parseCid(blob.cid);\n}\nexport function getBlobCidString(blob) {\n if (!blob)\n return undefined;\n return '$type' in blob ? blob.ref.toString() : blob.cid;\n}\nexport function isTypedBlobRef(input, options) {\n if (!isPlainObject(input)) {\n return false;\n }\n if (input?.$type !== 'blob') {\n return false;\n }\n const { mimeType, size, ref } = input;\n // @NOTE Very basic mime validation\n if (typeof mimeType !== 'string' || !mimeType.includes('/')) {\n return false;\n }\n if (size === -1 && options?.strict === false) {\n // In non-strict mode, allow size to be -1 to accommodate legacy blob refs\n // that don't include size information.\n }\n else if (!isSafeInteger(size) || size < 0) {\n return false;\n }\n if (typeof ref !== 'object' || ref === null) {\n return false;\n }\n for (const key in input) {\n if (key !== '$type' &&\n key !== 'mimeType' &&\n key !== 'ref' &&\n key !== 'size') {\n return false;\n }\n }\n const cid = ifCid(ref, \n // Strict unless explicitly disabled\n options?.strict === false ? undefined : STRICT_CID_CHECK_OPTIONS);\n if (!cid) {\n return false;\n }\n return true;\n}\n/**\n * Type guard to check if a value is a valid {@link LegacyBlobRef}.\n *\n * Validates the structure of the input:\n * - `cid` must be a valid CID string\n * - `mimeType` must be a non-empty string\n * - No additional properties allowed\n *\n * @example\n * ```typescript\n * import { isLegacyBlobRef } from '@atproto/lex-data'\n *\n * if (isLegacyBlobRef(data)) {\n * console.log(data.cid) // CID as string\n * console.log(data.mimeType) // e.g., 'image/jpeg'\n * }\n * ```\n *\n * @see {@link isTypedBlobRef} for checking the current blob reference format\n */\nexport function isLegacyBlobRef(input, options) {\n if (!isPlainObject(input)) {\n return false;\n }\n const { cid, mimeType } = input;\n if (typeof cid !== 'string') {\n return false;\n }\n if (typeof mimeType !== 'string' || mimeType.length === 0) {\n return false;\n }\n for (const key in input) {\n if (key !== 'cid' && key !== 'mimeType') {\n return false;\n }\n }\n if (!validateCidString(cid, options?.strict === false ? undefined : STRICT_CID_CHECK_OPTIONS)) {\n return false;\n }\n return true;\n}\nexport function* enumBlobRefs(input, options) {\n // LegacyBlobRef not included by default\n const includeLegacy = options?.allowLegacy === true;\n // Using a stack to avoid recursion depth issues.\n const stack = [input];\n // Since we are using a stack, we could end-up in an infinite loop with cyclic\n // structures. Cyclic structures are not valid LexValues and should, thus,\n // never occur, but let's be safe.\n const visited = new Set();\n do {\n const value = stack.pop();\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n if (visited.has(value))\n continue;\n visited.add(value);\n stack.push(...value);\n }\n else if (isPlainProto(value)) {\n if (visited.has(value))\n continue;\n visited.add(value);\n if (isTypedBlobRef(value, options)) {\n yield value;\n }\n else if (includeLegacy && isLegacyBlobRef(value, options)) {\n yield value;\n }\n else {\n for (const v of Object.values(value)) {\n if (v != null)\n stack.push(v);\n }\n }\n }\n }\n } while (stack.length > 0);\n // Optimization: ease GC's work\n visited.clear();\n}\n//# sourceMappingURL=blob.js.map","/**\n * Error class for Lexicon-related errors.\n *\n * LexError extends the standard JavaScript {@link Error} with AT\n * Protocol-specific functionality including an `error` code property and\n * methods for representation as (XRPC) error responses payloads.\n *\n * @typeParam N - The specific error code type\n */\nexport class LexError extends Error {\n /**\n * @param error - The error code identifying the type of error, typically used in XRPC error payloads\n * @param message - Optional human-readable error message\n * @param options - Standard Error options (e.g., cause)\n */\n constructor(error, message, // Defaults to empty string in Error constructor\n options) {\n super(message, options);\n this.error = error;\n this.name = 'LexError';\n }\n /**\n * Returns a string representation of this error.\n *\n * @returns A formatted string: \"LexErrorClass: [MyErrorCode] My message\"\n */\n toString() {\n return `${this.name}: [${this.error}] ${this.message}`;\n }\n /**\n * Converts this error to a JSON-serializable object.\n *\n * @returns The error data suitable for JSON serialization\n * @note The `error` generic is *not* constrained to {@link N} to allow subclasses to override the error code type.\n */\n toJSON() {\n const { error, message } = this;\n return { error, message: message || undefined };\n }\n}\n//# sourceMappingURL=lex-error.js.map","// @ts-check\n\n/**\n * @template {number} [T=number]\n * @typedef {[from: number, to: number, category: T]} CategorizedUnicodeRange\n */\n\n/**\n * @typedef {CategorizedUnicodeRange<0>} UnicodeRange\n */\n\n/**\n * @typedef {string & { __tag: 'UnicodeDataEncoding' }} UnicodeDataEncoding\n *\n * Encoding for array of {@link UnicodeRange}, items separated by comma.\n *\n * Each {@link UnicodeDataRow} packed as a base36 integer:\n *\n * padding = to - from\n * encoding = base36(from) + ',' + base36(padding)\n *\n * Notes:\n * - base36 can hold surprisingly large numbers in a few characters.\n * - The biggest codepoint is 0xE01F0 (918,000) at this point\n * - The max value of a category is 23; https://www.unicode.org/reports/tr29/tr29-45.html#Table_Word_Break_Property_Values\n * - The longest range is 42,720; CJK UNIFIED IDEOGRAPH-20000..CJK UNIFIED IDEOGRAPH-2A6DF\n */\n\n/**\n * @template {number} [T=number]\n * @param {UnicodeDataEncoding} data\n * @param {string} [cats='']\n * @returns {Array<CategorizedUnicodeRange<T>>}\n */\nexport function decodeUnicodeData(data, cats = '') {\n let buf = /** @type {Array<CategorizedUnicodeRange<T>>} */([])\n , nums = data.split(',').map(s => s ? parseInt(s, 36) : 0)\n , n = 0;\n for (let i = 0; i < nums.length; i++)\n i % 2\n ? buf.push([n, n + nums[i], /** @type {T} */ (cats ? parseInt(cats[i >> 1], 36) : 0)])\n : n = nums[i];\n return buf;\n}\n\n/**\n * @template {object} Ext\n * @typedef {{\n * segment: string,\n * index: number,\n * input: string,\n * } & Ext} SegmentOutput\n */\n\n/**\n * @template {object} T\n * @typedef {IterableIterator<SegmentOutput<T>>} Segmenter\n */\n\n/**\n * @template {number} [T=number]\n * @param {number} cp\n * @param {CategorizedUnicodeRange<T>[]} ranges\n * @return {number} index of matched unicode range, or -1 if no match\n */\nexport function findUnicodeRangeIndex(cp, ranges, lo = 0, hi = ranges.length - 1) {\n while (lo <= hi) {\n let mid = lo + hi >>> 1\n , range = ranges[mid];\n if (cp < range[0]) hi = mid - 1;\n else if (cp > range[1]) lo = mid + 1;\n else return mid;\n }\n return -1;\n}\n","// The following code was generated by \"scripts/unicode.js\",\n// DO NOT EDIT DIRECTLY.\n//\n// @ts-check\n\nimport { decodeUnicodeData } from './core.js';\n\n/**\n * @typedef {import('./core.js').UnicodeDataEncoding} UnicodeDataEncoding\n */\n\n/**\n * @typedef {0} GC_Any\n * @typedef {1} GC_CR\n * @typedef {2} GC_Control\n * @typedef {3} GC_Extend\n * @typedef {4} GC_Extended_Pictographic\n * @typedef {5} GC_L\n * @typedef {6} GC_LF\n * @typedef {7} GC_LV\n * @typedef {8} GC_LVT\n * @typedef {9} GC_Prepend\n * @typedef {10} GC_Regional_Indicator\n * @typedef {11} GC_SpacingMark\n * @typedef {12} GC_T\n * @typedef {13} GC_V\n * @typedef {14} GC_ZWJ\n * @typedef {(\n * | GC_Any\n * | GC_CR\n * | GC_Control\n * | GC_Extend\n * | GC_Extended_Pictographic\n * | GC_L\n * | GC_LF\n * | GC_LV\n * | GC_LVT\n * | GC_Prepend\n * | GC_Regional_Indicator\n * | GC_SpacingMark\n * | GC_T\n * | GC_V\n * | GC_ZWJ\n * )} GraphemeCategoryNum\n */\n\n/**\n * @typedef {import('./core.js').CategorizedUnicodeRange<GraphemeCategoryNum>} GraphemeCategoryRange\n */\n\n/**\n * @typedef {(\n * | 'Any'\n * | 'CR'\n * | 'Control'\n * | 'Extend'\n * | 'Extended_Pictographic'\n * | 'L'\n * | 'LF'\n * | 'LV'\n * | 'LVT'\n * | 'Prepend'\n * | 'Regional_Indicator'\n * | 'SpacingMark'\n * | 'T'\n * | 'V'\n * | 'ZWJ'\n * )} GraphemeCategoryKey\n */\n\n/**\n * Grapheme category enum\n *\n * Note:\n * The object isn't actually frozen\n * because using `Object.freeze` increases 800 bytes on Brotli compression.\n *\n * @type {Readonly<Record<GraphemeCategoryKey, GraphemeCategoryNum>>}\n */\nexport const GraphemeCategory = {\n Any: 0,\n CR: 1,\n Control: 2,\n Extend: 3,\n Extended_Pictographic: 4,\n L: 5,\n LF: 6,\n LV: 7,\n LVT: 8,\n Prepend: 9,\n Regional_Indicator: 10,\n SpacingMark: 11,\n T: 12,\n V: 13,\n ZWJ: 14,\n};\n\n/**\n * @type {GraphemeCategoryRange[]}\n */\nexport const grapheme_ranges = decodeUnicodeData(\n /** @type {UnicodeDataEncoding} */\n (',9,a,,b,1,d,,e,h,3j,w,4p,,4t,,4u,,lc,33,w3,6,13l,18,14v,,14x,1,150,1,153,,16o,5,174,a,17g,,18r,k,19s,,1cm,6,1ct,,1cv,5,1d3,1,1d6,3,1e7,,1e9,,1f4,q,1ie,a,1kb,8,1kt,,1li,3,1ln,8,1lx,2,1m1,4,1nd,2,1ow,1,1p3,8,1qi,n,1r6,,1r7,v,1s3,,1tm,,1tn,,1to,,1tq,2,1tt,7,1u1,3,1u5,,1u6,1,1u9,6,1uq,1,1vl,,1vm,1,1x8,,1xa,,1xb,1,1xd,3,1xj,1,1xn,1,1xp,,1xz,,1ya,1,1z2,,1z5,1,1z7,,20s,,20u,2,20x,1,213,1,217,2,21d,,228,1,22d,,22p,1,22r,,24c,,24e,2,24h,4,24n,1,24p,,24r,1,24t,,25e,1,262,5,269,,26a,1,27w,,27y,1,280,,281,3,287,1,28b,1,28d,,28l,2,28y,1,29u,,2bi,,2bj,,2bk,,2bl,1,2bq,2,2bu,2,2bx,,2c7,,2dc,,2dd,2,2dg,,2f0,,2f2,2,2f5,3,2fa,2,2fe,3,2fp,1,2g2,1,2gx,,2gy,1,2ik,,2im,,2in,1,2ip,,2iq,,2ir,1,2iu,2,2iy,3,2j9,1,2jm,1,2k3,,2kg,1,2ki,1,2m3,1,2m6,,2m7,1,2m9,3,2me,2,2mi,2,2ml,,2mm,,2mv,,2n6,1,2o1,,2o2,1,2q2,,2q7,,2q8,1,2qa,2,2qe,,2qg,6,2qn,,2r6,1,2sx,,2sz,,2t0,6,2tj,7,2wh,,2wj,,2wk,8,2x4,6,2zc,1,305,,307,,309,,30e,1,31t,d,327,,328,4,32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,1jrt,2,1jt0,5,1jt6,c,1jtj,,1jtk,1,1k4v,,1k4w,6,1k54,5,1k5a,,1k5b,,1k7m,l,1k89,,1k8a,6,1k8h,,1k8i,1,1k8k,,1k8l,1,1kc1,5,1kca,,1kcc,1,1kcf,6,1kcm,,1kcn,,1kei,4,1keo,1,1ker,1,1ket,,1keu,,1kev,,1koj,1,1kol,1,1kow,1,1koy,,1koz,,1kqc,1,1kqe,4,1kqm,1,1kqo,2,1kre,,1ovk,f,1ow0,,1ow7,e,1xr2,b,1xre,2,1xrh,2,1zow,4,1zqo,6,206b,,206f,3,20jz,,20k1,1i,20lr,3,20o4,,20og,1,2ftp,1,2fts,3,2jgg,19,2jhs,m,2jxh,4,2jxp,5,2jxv,7,2jy3,7,2jyd,6,2jze,3,2k3m,2,2lmo,1i,2lob,1d,2lpx,,2lqc,,2lqz,4,2lr5,e,2mtc,6,2mtk,g,2mu3,6,2mub,1,2mue,4,2mxb,,2n1s,6,2nce,,2ne4,3,2nsc,3,2nzi,1,2ok0,6,2on8,6,2pz4,73,2q6l,2,2q7j,,2q98,5,2q9q,1,2qa6,,2qa9,9,2qb1,1k,2qcm,p,2qdd,e,2qe2,,2qen,,2qeq,8,2qf0,3,2qfd,c1,2qrf,4,2qrk,8t,2r0m,7d,2r9c,3j,2rg4,b,2rit,16,2rkc,3,2rm0,7,2rmi,5,2rns,7,2rou,29,2rrg,1a,2rss,9,2rt3,c8,2scg,sd,jny8,v,jnz4,2n,jo1s,3j,jo5c,6n,joc0,2rz'),\n '262122424333333393233393339333333333393393b3b3b3b3b333b33b3bb33333b3b3333333b3b33bb3333b33b3bb33333b3bbb333b333b33333b3b3b3b3333b3b33b3bb39333b33b33b3b3b333b333333b3b333333b33b3b3333b3335dc333333b3b3b33323333b3bb3b33b3b3b3333b3333b3b333bb3b33b3b3b3b3b333b333b3323e2244234444444444444444444444444444444444444444443333333333b3b3bb33333b353b3b3b3b333b3b333b333333b3bb3b3b3bb333232333333333333333b3b3333bb3b393933b3b33bb3b393b3b3b3333b33b33b3bbb33b333b3333bb3933b3b3b333b3b3b3b3b33b3b3b33b3b3b33b3b33b33b3b3b33bb39b9b3b33b3b33b9333b393b3b33b33b3b3b3333393b3b3b33b39bb3b332333b333dd3b33332333323333333333333333333333344444444a44444434444444444444423232',\n);\n","// The following code was generated by \"scripts/unicode.js\",\n// DO NOT EDIT DIRECTLY.\n//\n// @ts-check\n\nimport { decodeUnicodeData } from './core.js';\n\n/**\n * @typedef {import('./core.js').UnicodeRange} UnicodeRange\n * @typedef {import('./core.js').UnicodeDataEncoding} UnicodeDataEncoding\n */\n\n/**\n * The Unicode `Indic_Conjunct_Break=Consonant` derived property table\n *\n * @type {UnicodeRange[]}\n */\nexport const consonant_ranges = decodeUnicodeData(\n /** @type {UnicodeDataEncoding} */\n ('1sl,10,1ug,7,1vc,7,1w5,j,1wq,6,1wy,,1x2,3,1y4,1,1y7,,1yo,1,239,j,23u,6,242,1,245,4,261,,26t,j,27e,6,27m,1,27p,4,28s,1,28v,,29d,,2dx,j,2ei,f,2fs,2,2l1,11')\n);\n","// Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>.\n//\n// Modified original Rust library [source code]\n// (https://github.com/unicode-rs/unicode-segmentation/blob/1f88570/src/grapheme.rs)\n//\n// to create JavaScript library [unicode-segmenter]\n// (https://github.com/cometkim/unicode-segmenter)\n\n// @ts-check\n\nimport { findUnicodeRangeIndex } from './core.js';\nimport { GraphemeCategory, grapheme_ranges } from './_grapheme_data.js';\nimport { consonant_ranges } from './_incb_data.js';\n\n/**\n * @typedef {import('./_grapheme_data.js').GC_Any} GC_Any\n *\n * @typedef {import('./_grapheme_data.js').GraphemeCategoryNum} GraphemeCategoryNum\n * @typedef {import('./_grapheme_data.js').GraphemeCategoryRange} GraphemeCategoryRange\n *\n * @typedef {object} GraphemeSegmentExtra\n * @property {number} _hd The first code point of the segment\n * @property {GraphemeCategoryNum} _catBegin Beginning Grapheme_Cluster_Break category of the segment\n * @property {GraphemeCategoryNum} _catEnd Ending Grapheme_Cluster_Break category of the segment\n *\n * @typedef {import('./core.js').Segmenter<GraphemeSegmentExtra>} GraphemeSegmenter\n */\n\nexport { GraphemeCategory };\n\nconst BMP_MAX = 0xFFFF;\n\n/**\n * Unicode segmentation by extended grapheme rules.\n *\n * This is fully compatible with the {@link Intl.Segmenter.segment} API\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment\n *\n * @param {string} input\n * @return {GraphemeSegmenter} iterator for grapheme cluster segments\n */\nexport function* graphemeSegments(input) {\n let cp = input.codePointAt(0);\n\n // do nothing on empty string\n if (cp == null) return;\n\n /** Current cursor position. */\n let cursor = cp <= BMP_MAX ? 1 : 2;\n\n /** Total length of the input string. */\n let len = input.length;\n\n /** Category of codepoint immediately preceding cursor */\n let catBefore = cat(cp);\n\n /** @type {GraphemeCategoryNum} Category of codepoint immediately preceding cursor. */\n let catAfter = 0;\n\n /** The number of RIS codepoints preceding `cursor`. */\n let risCount = 0;\n\n /**\n * Emoji state for GB11: tracks if we've seen Extended_Pictographic followed by Extend* ZWJ\n * Only relevant when catBefore === ZWJ && catAfter === Extended_Pictographic\n */\n let emoji = false;\n\n /** InCB=Consonant - segment started with Indic consonant */\n let consonant = false;\n\n /** InCB=Linker - seen a linker after consonant */\n let linker = false;\n\n let index = 0;\n\n /** Beginning category of a segment */\n let _catBegin = catBefore;\n\n /** Memoize the beginning code point of the segment. */\n let _hd = cp;\n\n while (cursor < len) {\n cp = /** @type {number} */ (input.codePointAt(cursor));\n catAfter = cat(cp);\n\n let boundary = true;\n\n // GB3: CR ร LF\n if (catBefore === 1) {\n boundary = catAfter !== 6;\n }\n // GB4: (Control | CR | LF) รท\n else if (catBefore === 2 || catBefore === 6) {\n boundary = true;\n }\n // GB5: รท (Control | CR | LF)\n else if (catAfter === 1 || catAfter === 2 || catAfter === 6) {\n boundary = true;\n }\n // GB9, GB9a: ร (Extend | ZWJ | SpacingMark) - most common no-break case\n else if (catAfter === 3 || catAfter === 14 || catAfter === 11) {\n boundary = false;\n }\n // GB9b: Prepend ร\n else if (catBefore === 9) {\n boundary = false;\n }\n // GB11: ExtPic Extend* ZWJ ร ExtPic\n else if (catBefore === 14 && catAfter === 4) {\n boundary = !emoji;\n }\n // GB12, GB13: RI ร RI (odd count means no break)\n else if (catBefore === 10 && catAfter === 10) {\n // risCount is count BEFORE current RI, so odd means this is 2nd, 4th, etc.\n boundary = risCount++ % 2 === 1;\n }\n // GB6: L ร (L | V | LV | LVT)\n else if (catBefore === 5) {\n boundary = !(catAfter === 5 || catAfter === 13 || catAfter === 7 || catAfter === 8);\n }\n // GB7: (LV | V) ร (V | T)\n else if ((catBefore === 7 || catBefore === 13) && (catAfter === 13 || catAfter === 12)) {\n boundary = false;\n }\n // GB8: (LVT | T) ร T\n else if ((catBefore === 8 || catBefore === 12) && catAfter === 12) {\n boundary = false;\n }\n // GB9c: InCB=Consonant InCB=Extend* InCB=Linker InCB=Extend* ร InCB=Consonant\n else if (catAfter === 0 && consonant && linker && isIndicConjunctConsonant(cp)) {\n boundary = false;\n }\n // else GB999: รท Any\n\n if (boundary) {\n yield {\n segment: input.slice(index, cursor),\n index,\n input,\n _hd,\n _catBegin,\n _catEnd: catBefore,\n };\n\n // Reset segment state\n emoji = false;\n risCount = 0;\n index = cursor;\n _catBegin = catAfter;\n _hd = cp;\n } \n // Update state for continuing segment\n else {\n // emoji state for GB11\n if (catAfter === 14 && (catBefore === 3 || catBefore === 4)) {\n emoji = true;\n }\n // InCB state for GB9c\n else if (cp >= 2325) {\n if (!consonant && catBefore === 0) {\n consonant = isIndicConjunctConsonant(_hd);\n }\n if (consonant && catAfter === 3) {\n linker = linker\n || cp === 0x094D\n || cp === 0x09CD\n || cp === 0x0A4D\n || cp === 0x0ACD\n || cp === 0x0B4D\n || cp === 0x0C4D\n || cp === 0x0D4D;\n } else {\n linker = false;\n }\n }\n }\n\n cursor += cp <= BMP_MAX ? 1 : 2;\n catBefore = catAfter;\n }\n\n if (index < len) {\n yield {\n segment: input.slice(index),\n index,\n input,\n _hd,\n _catBegin,\n _catEnd: catBefore,\n };\n }\n}\n\n/**\n * Count number of extended grapheme clusters in given text.\n *\n * NOTE:\n *\n * This function is a small wrapper around {@link graphemeSegments}.\n *\n * If you call it more than once at a time, consider memoization\n * or use {@link graphemeSegments} or {@link splitGraphemes} once instead\n *\n * @param {string} text\n * @return {number} count of grapheme clusters\n */\nexport function countGraphemes(text) {\n let count = 0;\n for (let _ of graphemeSegments(text)) count += 1;\n return count;\n}\n\nexport {\n /**\n * @deprecated use {@link countGraphemes}\n */\n countGraphemes as countGrapheme,\n};\n\n/**\n * Split given text into extended grapheme clusters.\n *\n * @param {string} text\n * @return {IterableIterator<string>} iterator for grapheme clusters\n *\n * @see {@link graphemeSegments} if you need extra information.\n *\n * @example\n * [...splitGraphemes('abc')] // => ['a', 'b', 'c']\n */\nexport function* splitGraphemes(text) {\n for (let s of graphemeSegments(text)) yield s.segment;\n}\n\n// Segmented 4-bit packed lookup tables for BMP code points.\n// \n// Memory and code size optimization: Skip regions that can be easily inlined\n// - 0x3000-0x9FFF (CJK): 28,672 codepoints, only 12 non-Any ranges\n// - 0xAC00-0xD7A3 (Hangul syllables): 11,172 codepoints, LV or LVT computed at runtime\n// - 0xD7A4-0xD7FF (Hangul Jamo Extended-B): 92 codepoints, only 2 non-Any ranges\n// - 0xE000-0xFDFF (Private Use): 7,680 codepoints, only 1 non-Any range\n// - 0xFE00-0xFFFF (Specials): 512 codepoints -> very rare and small, binary search fallback\n// \n// Hangul syllables note:\n// - LV syllables: single codepoints at 0xAC00 + n*28\n// - LVT syllables: 27 consecutive codepoints after each LV\n// \n// Indexed category segments (4-bit packed, 2 categories per byte):\n// - SEG0: 0x0080-0x2FFF (12,160 codepoints -> 6,080 bytes)\n// - SEG1: 0xA000-0xABFF (3,072 codepoints -> 1,536 bytes)\n//\n// Total index size: 7,616 bytes (~7.4KB)\nconst SEG0 = new Uint8Array(6080), SEG0_MIN = 0x0080, SEG0_MAX = 0x2FFF;\nconst SEG1 = new Uint8Array(1536), SEG1_MIN = 0xA000, SEG1_MAX = 0xABFF;\nconst SEG_CURSOR = (() => {\n let cursor = 0;\n while (true) {\n let [start, end, cat] = grapheme_ranges[cursor];\n if (start > SEG1_MAX) break;\n cursor++;\n\n // Skip inlined ranges\n if (end < SEG0_MIN || (start > SEG0_MAX && end < SEG1_MIN)) continue;\n\n for (let cp = start; cp <= end; cp++) {\n let /** @type {Uint8Array} */ seg, idx = 0;\n\n if (cp <= SEG0_MAX) {\n seg = SEG0; idx = (cp - SEG0_MIN) >> 1;\n } else {\n seg = SEG1; idx = (cp - SEG1_MIN) >> 1;\n }\n\n seg[idx] = cp & 1\n ? (seg[idx] & 0x0F) | (cat << 4)\n : (seg[idx] & 0xF0) | cat;\n }\n }\n return cursor;\n})();\n\n/**\n * `Grapheme_Cluster_Break` property value of a given codepoint\n *\n * @see https://www.unicode.org/reports/tr29/tr29-43.html#Default_Grapheme_Cluster_Table\n *\n * @param {number} cp\n * @return {GraphemeCategoryNum}\n */\nfunction cat(cp) {\n // ASCII fast path\n if (cp < SEG0_MIN) {\n if (cp >= 32) return 0;\n if (cp === 10) return 6;\n if (cp === 13) return 1;\n return 2;\n }\n // Index Segment 0: 0x0080-0x2FFF\n if (cp <= SEG0_MAX) {\n let byte = SEG0[(cp - SEG0_MIN) >> 1];\n return /** @type {GraphemeCategoryNum} */ (cp & 1 ? byte >> 4 : byte & 0x0F);\n }\n // CJK fast path: 0x3000-0x9FFF\n if (cp < SEG1_MIN) {\n if (cp < 0x3030) return cp >= 0x302A ? 3 : 0;\n if (cp < 0x309B) {\n if (cp === 0x3030 || cp === 0x303D) return 4;\n return cp >= 0x3099 ? 3 : 0;\n }\n if (cp === 0x3297 || cp === 0x3299) return 4;\n return 0;\n }\n // Index Segment 1: 0xA000-0xABFF\n if (cp <= SEG1_MAX) {\n let byte = SEG1[(cp - SEG1_MIN) >> 1];\n return /** @type {GraphemeCategoryNum} */ (cp & 1 ? byte >> 4 : byte & 0x0F);\n }\n // Hangul syllables path: 0xAC00-0xD7A3\n if (cp <= 0xD7A3) {\n return (cp - 0xAC00) % 28 === 0 ? 7 : 8; // LV : LVT\n }\n // Hangul Jamo Extended-B path: 0xD7A4-0xD7FF\n if (cp <= 0xD7FF) {\n if (cp <= 0xD7C6) return cp >= 0xD7B0 ? 13 : 0; // V\n return cp >= 0xD7CB ? 12 : 0; // T\n }\n // Private Use fast path: 0xE000-0xFDFF\n if (cp < 0xFE00) {\n return cp === 0xFB1E ? 3 : 0;\n }\n // Specials (0xFE00-0xFFFF) and Non-BMP\n let idx = findUnicodeRangeIndex(cp, grapheme_ranges, SEG_CURSOR);\n return idx < 0 ? 0 : grapheme_ranges[idx][2];\n}\n\n/**\n * @param {number} cp\n * @return {boolean}\n */\nfunction isIndicConjunctConsonant(cp) {\n return findUnicodeRangeIndex(cp, consonant_ranges) >= 0;\n}\n","import { countGraphemes } from 'unicode-segmenter/grapheme';\n// @TODO: Drop usage of \"unicode-segmenter\" package when Intl.Segmenter is\n// widely supported.\n// https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter\nconst segmenter = 'Segmenter' in Intl && typeof Intl.Segmenter === 'function'\n ? /*#__PURE__*/ new Intl.Segmenter()\n : /* v8 ignore next -- @preserve */ null;\nexport const graphemeLenNative = segmenter\n ? function graphemeLenNative(str) {\n let length = 0;\n for (const _ of segmenter.segment(str))\n length++;\n return length;\n }\n : /* v8 ignore next -- @preserve */ null;\nexport function graphemeLenPonyfill(str) {\n return countGraphemes(str);\n}\n//# sourceMappingURL=utf8-grapheme-len.js.map","import { NodeJSBuffer } from './lib/nodejs-buffer.js';\n// @NOTE This file is not meant to be exported directly. Instead, we re-export\n// public functions from ./utf8.ts. The reason for this separation is that this\n// file allows to test both the NodeJS-optimized and ponyfill implementations.\nexport const utf8LenNode = NodeJSBuffer\n ? function utf8LenNode(string) {\n return NodeJSBuffer.byteLength(string, 'utf8');\n }\n : /* v8 ignore next -- @preserve */ null;\nexport function utf8LenCompute(string) {\n // The code below is similar to TextEncoder's implementation of UTF-8\n // encoding. However, using TextEncoder to get the byte length is slower\n // as it requires allocating a new Uint8Array and copying data:\n // return new TextEncoder().encode(string).byteLength\n // The base length is the string length (all ASCII)\n let len = string.length;\n let code;\n // The loop calculates the number of additional bytes needed for\n // non-ASCII characters\n for (let i = 0; i < string.length; i += 1) {\n code = string.charCodeAt(i);\n if (code <= 0x7f) {\n // ASCII, 1 byte\n }\n else if (code <= 0x7ff) {\n // 2 bytes char\n len += 1;\n }\n else {\n // 3 bytes char\n len += 2;\n // If the current char is a high surrogate, and the next char is a low\n // surrogate, skip the next char as the total is a 4 bytes char\n // (represented as a surrogate pair in UTF-16) and was already accounted\n // for.\n if (code >= 0xd800 && code <= 0xdbff) {\n code = string.charCodeAt(i + 1);\n if (code >= 0xdc00 && code <= 0xdfff) {\n i++;\n }\n }\n }\n }\n return len;\n}\n//# sourceMappingURL=utf8-len.js.map","// @NOTE This file is not meant to be exported directly. Instead, we re-export\n// public functions from ./utf8.ts. The reason for this separation is that this\n// file allows to test both the RegExp and ponyfill implementations.\n// Unicode property escapes (ES2018) are a SyntaxError where unsupported, which\n// a RegExp literal would throw as soon as this module is parsed. With the `u`\n// flag, a surrogate pair is matched as one code point, so only lone surrogates\n// match.\nconst loneSurrogate = /*#__PURE__*/ (() => {\n try {\n return new RegExp('\\\\p{Cs}', 'u');\n }\n catch {\n /* v8 ignore next -- @preserve */\n return null;\n }\n})();\nexport const isWellFormedRegExp = loneSurrogate\n ? function isWellFormedRegExp(str) {\n return !loneSurrogate.test(str);\n }\n : /* v8 ignore next -- @preserve */ null;\nexport function isWellFormedPonyfill(str) {\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n if (code < 0xd800 || code > 0xdfff)\n continue;\n // A high surrogate followed by a low surrogate is a valid pair\n if (code <= 0xdbff) {\n const next = str.charCodeAt(i + 1); // NaN past the end\n if (next >= 0xdc00 && next <= 0xdfff) {\n i++;\n continue;\n }\n }\n return false;\n }\n return true;\n}\n//# sourceMappingURL=utf8-well-formed.js.map","import { utf8FromBase64Node, utf8FromBase64Ponyfill, } from './utf8-from-base64.js';\nimport { utf8FromBytesNative, utf8FromBytesNode } from './utf8-from-bytes.js';\nimport { graphemeLenNative, graphemeLenPonyfill } from './utf8-grapheme-len.js';\nimport { utf8LenCompute, utf8LenNode } from './utf8-len.js';\nimport { utf8ToBase64Node, utf8ToBase64Ponyfill } from './utf8-to-base64.js';\nimport { isWellFormedPonyfill, isWellFormedRegExp } from './utf8-well-formed.js';\n/**\n * Converts a Uint8Array to a UTF-8 string.\n *\n * Uses Node.js Buffer when available for performance, falling back to\n * TextDecoder in environments without Buffer support.\n *\n * @param bytes - The binary data to decode\n * @returns The decoded string (as UTF-16 JavaScript string)\n *\n * @example\n * ```typescript\n * import { utf8FromBytes } from '@atproto/lex-data'\n *\n * const bytes = new Uint8Array([72, 101, 108, 108, 111])\n * utf8FromBytes(bytes) // 'Hello'\n * ```\n */\nexport const utf8FromBytes = utf8FromBytesNode ?? utf8FromBytesNative;\n/**\n * Counts the number of grapheme clusters (user-perceived characters) in a string.\n *\n * Grapheme clusters represent what users typically think of as \"characters\",\n * handling complex cases like:\n * - Emoji with skin tones and ZWJ sequences (e.g., family emoji)\n * - Combined characters (e.g., 'e' + combining accent)\n * - Regional indicator pairs (flag emoji)\n *\n * Uses native {@link Intl.Segmenter} when available, falling back to a ponyfill.\n *\n * @param str - The string to measure\n * @returns The number of grapheme clusters\n *\n * @example\n * ```typescript\n * import { graphemeLen } from '@atproto/lex-data'\n *\n * graphemeLen('hello') // 5\n * graphemeLen('cafe\\u0301') // 4 (cafe with combining accent)\n * graphemeLen('\\u{1F468}\\u{200D}\\u{1F469}\\u{200D}\\u{1F467}\\u{200D}\\u{1F466}') // 1 (family emoji)\n * ```\n */\nexport const graphemeLen = \n/* v8 ignore next -- @preserve */ graphemeLenNative ?? graphemeLenPonyfill;\n/* v8 ignore next -- @preserve */\nif (graphemeLen === graphemeLenPonyfill) {\n /*#__PURE__*/\n console.warn('[@atproto/lex-data]: Intl.Segmenter is not available in this environment. Falling back to ponyfill implementation.');\n}\n/**\n * Calculates the UTF-8 byte length of a string.\n *\n * Returns the number of bytes the string would occupy when encoded as UTF-8.\n * This is important for Lexicon validation where schemas specify byte limits.\n *\n * Uses Node.js Buffer.byteLength when available for performance,\n * falling back to a computed implementation.\n *\n * @param str - The string to measure\n * @returns The UTF-8 byte length\n *\n * @example\n * ```typescript\n * import { utf8Len } from '@atproto/lex-data'\n *\n * utf8Len('hello') // 5 (ASCII: 1 byte per char)\n * utf8Len('\\u00e9') // 2 (e with accent: 2 bytes)\n * utf8Len('\\u{1F600}') // 4 (emoji: 4 bytes)\n * utf8Len('\\u{1F468}\\u{200D}\\u{1F469}\\u{200D}\\u{1F467}\\u{200D}\\u{1F466}') // 25 (family emoji)\n * ```\n */\nexport const utf8Len = \n/* v8 ignore next -- @preserve */ utf8LenNode ?? utf8LenCompute;\n/**\n * Whether a string is well-formed, i.e. contains no lone surrogate, which has\n * no UTF-8 encoding (it would be replaced by U+FFFD when encoded), like\n * {@link String.prototype.isWellFormed}.\n *\n * Uses a Unicode property escape RegExp when supported, falling back to a\n * ponyfill.\n *\n * @example\n * ```typescript\n * import { isWellFormedString } from '@atproto/lex-data'\n *\n * isWellFormedString('\\u{1F600}') // true (surrogate pair)\n * isWellFormedString('\\uD83D') // false (lone high surrogate)\n * ```\n */\nexport const isWellFormedString = \n/* v8 ignore next -- @preserve */ isWellFormedRegExp ?? isWellFormedPonyfill;\n/**\n * Encodes a UTF-8 string to base64.\n *\n * First encodes the string as UTF-8 bytes, then encodes those bytes as base64.\n *\n * @param str - The string to encode\n * @param alphabet - The base64 alphabet to use ('base64' or 'base64url')\n * @returns The base64-encoded string\n *\n * @example\n * ```typescript\n * import { utf8ToBase64 } from '@atproto/lex-data'\n *\n * utf8ToBase64('Hello') // 'SGVsbG8='\n * ```\n */\nexport const utf8ToBase64 = \n/* v8 ignore next -- @preserve */ utf8ToBase64Node ?? utf8ToBase64Ponyfill;\n/**\n * Decodes a base64 string to UTF-8.\n *\n * Decodes the base64 to bytes, then interprets those bytes as UTF-8 text.\n *\n * @param b64 - The base64 string to decode\n * @param alphabet - The base64 alphabet to use ('base64' or 'base64url')\n * @returns The decoded UTF-8 string\n *\n * @example\n * ```typescript\n * import { utf8FromBase64 } from '@atproto/lex-data'\n *\n * utf8FromBase64('SGVsbG8=') // 'Hello'\n * ```\n */\nexport const utf8FromBase64 = \n/* v8 ignore next -- @preserve */ utf8FromBase64Node ?? utf8FromBase64Ponyfill;\n//# sourceMappingURL=utf8.js.map","// Human-readable constraints:\n// - valid W3C DID (https://www.w3.org/TR/did-core/#did-syntax)\n// - entire URI is ASCII: [a-zA-Z0-9._:%-]\n// - always starts \"did:\" (lower-case)\n// - method name is one or more lower-case letters, followed by \":\"\n// - remaining identifier can have any of the above chars, but can not end in \":\"\n// - it seems that a bunch of \":\" can be included, and don't need spaces between\n// - \"%\" is used only for \"percent encoding\" and must be followed by two hex characters (and thus can't end in \"%\")\n// - query (\"?\") and fragment (\"#\") stuff is defined for \"DID URIs\", but not as part of identifier itself\n// - \"The current specification does not take a position on the maximum length of a DID\"\n// - in current atproto, only allowing did:plc and did:web. But not *forcing* this at lexicon layer\n// - hard length limit of 8KBytes\n// - not going to validate \"percent encoding\" here\nexport function ensureValidDid(input) {\n if (!input.startsWith('did:')) {\n throw new InvalidDidError('DID requires \"did:\" prefix');\n }\n if (input.length > 2048) {\n throw new InvalidDidError('DID is too long (2048 chars max)');\n }\n if (input.endsWith(':') || input.endsWith('%')) {\n throw new InvalidDidError('DID can not end with \":\" or \"%\"');\n }\n // check that all chars are boring ASCII\n if (!/^[a-zA-Z0-9._:%-]*$/.test(input)) {\n throw new InvalidDidError('Disallowed characters in DID (ASCII letters, digits, and a couple other characters only)');\n }\n const { length, 1: method } = input.split(':');\n if (length < 3) {\n throw new InvalidDidError('DID requires prefix, method, and method-specific content');\n }\n if (!/^[a-z]+$/.test(method)) {\n throw new InvalidDidError('DID method must be lower-case letters');\n }\n}\nconst DID_REGEX = /^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/;\nexport function ensureValidDidRegex(input) {\n // simple regex to enforce most constraints via just regex and length.\n // hand wrote this regex based on above constraints\n if (!DID_REGEX.test(input)) {\n throw new InvalidDidError(\"DID didn't validate via regex\");\n }\n if (input.length > 2048) {\n throw new InvalidDidError('DID is too long (2048 chars max)');\n }\n}\nexport function isValidDid(input) {\n return (typeof input === 'string' && input.length <= 2048 && DID_REGEX.test(input));\n}\nexport class InvalidDidError extends Error {\n}\n//# sourceMappingURL=did.js.map","export const INVALID_HANDLE = 'handle.invalid';\n// Currently these are registration-time restrictions, not protocol-level\n// restrictions. We have a couple accounts in the wild that we need to clean up\n// before hard-disallow.\n// See also: https://en.wikipedia.org/wiki/Top-level_domain#Reserved_domains\nexport const DISALLOWED_TLDS = [\n '.local',\n '.arpa',\n '.invalid',\n '.localhost',\n '.internal',\n '.example',\n '.alt',\n // policy could concievably change on \".onion\" some day\n '.onion',\n // NOTE: .test is allowed in testing and devopment. In practical terms\n // \"should\" \"never\" actually resolve and get registered in production\n];\n// Handle constraints, in English:\n// - must be a possible domain name\n// - RFC-1035 is commonly referenced, but has been updated. eg, RFC-3696,\n// section 2. and RFC-3986, section 3. can now have leading numbers (eg,\n// 4chan.org)\n// - \"labels\" (sub-names) are made of ASCII letters, digits, hyphens\n// - can not start or end with a hyphen\n// - TLD (last component) should not start with a digit\n// - can't end with a hyphen (can end with digit)\n// - each segment must be between 1 and 63 characters (not including any periods)\n// - overall length can't be more than 253 characters\n// - separated by (ASCII) periods; does not start or end with period\n// - case insensitive\n// - domains (handles) are equal if they are the same lower-case\n// - punycode allowed for internationalization\n// - no whitespace, null bytes, joining chars, etc\n// - does not validate whether domain or TLD exists, or is a reserved or\n// special TLD (eg, .onion or .local)\n// - does not validate punycode\nexport function ensureValidHandle(input) {\n // check that all chars are boring ASCII\n if (!/^[a-zA-Z0-9.-]*$/.test(input)) {\n throw new InvalidHandleError('Disallowed characters in handle (ASCII letters, digits, dashes, periods only)');\n }\n if (input.length > 253) {\n throw new InvalidHandleError('Handle is too long (253 chars max)');\n }\n const labels = input.split('.');\n if (labels.length < 2) {\n throw new InvalidHandleError('Handle domain needs at least two parts');\n }\n for (let i = 0; i < labels.length; i++) {\n const l = labels[i];\n if (l.length < 1) {\n throw new InvalidHandleError('Handle parts can not be empty');\n }\n if (l.length > 63) {\n throw new InvalidHandleError('Handle part too long (max 63 chars)');\n }\n if (l.endsWith('-') || l.startsWith('-')) {\n throw new InvalidHandleError('Handle parts can not start or end with hyphens');\n }\n if (i + 1 === labels.length && !/^[a-zA-Z]/.test(l)) {\n throw new InvalidHandleError('Handle final component (TLD) must start with ASCII letter');\n }\n }\n}\n// simple regex translation of above constraints\nconst HANDLE_REGEX = /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;\nexport function ensureValidHandleRegex(input) {\n if (input.length > 253) {\n throw new InvalidHandleError('Handle is too long (253 chars max)');\n }\n if (!HANDLE_REGEX.test(input)) {\n throw new InvalidHandleError(\"Handle didn't validate via regex\");\n }\n}\nexport function normalizeHandle(handle) {\n return handle.toLowerCase();\n}\nexport function normalizeAndEnsureValidHandle(handle) {\n const normalized = normalizeHandle(handle);\n ensureValidHandle(normalized);\n return normalized;\n}\nexport function isValidHandle(input) {\n return (typeof input === 'string' && input.length <= 253 && HANDLE_REGEX.test(input));\n}\nexport function isValidTld(handle) {\n for (const tld of DISALLOWED_TLDS) {\n if (handle.endsWith(tld)) {\n return false;\n }\n }\n return true;\n}\nexport class InvalidHandleError extends Error {\n}\n/** @deprecated Never used */\nexport class ReservedHandleError extends Error {\n}\n/** @deprecated Never used */\nexport class UnsupportedDomainError extends Error {\n}\n/** @deprecated Never used */\nexport class DisallowedDomainError extends Error {\n}\n//# sourceMappingURL=handle.js.map","import { ensureValidDidRegex, isValidDid } from './did.js';\nimport { InvalidHandleError, ensureValidHandleRegex, isValidHandle, } from './handle.js';\n/**\n * Discriminates {@link HandleString} from a valid {@link AtIdentifierString}.\n *\n * @return `true` if the identifier is a handle, `false` otherwise\n */\nexport function isHandleIdentifier(id) {\n return !isDidIdentifier(id);\n}\n/**\n * Discriminates {@link DidString} from a valid {@link AtIdentifierString}.\n *\n * @return `true` if the identifier is a DID, `false` otherwise\n */\nexport function isDidIdentifier(id) {\n return id.startsWith('did:');\n}\n/**\n * Validates that a string is a valid {@link AtIdentifierString} format string,\n * throwing an error if it is not.\n *\n * @throws InvalidHandleError if the input string does not meet the atproto 'datetime' format requirements.\n * @see {@link AtIdentifierString}\n */\nexport function assertAtIdentifierString(input) {\n try {\n if (!input || typeof input !== 'string') {\n throw new TypeError('Identifier must be a non-empty string');\n }\n else if (input.startsWith('did:')) {\n ensureValidDidRegex(input);\n }\n else {\n ensureValidHandleRegex(input);\n }\n }\n catch (cause) {\n throw new InvalidHandleError('Invalid DID or handle', { cause });\n }\n}\n/**\n * Casts a string to a {@link AtIdentifierString} if it is a valid at-identifier\n * string, throwing an error if it is not.\n *\n * @throws InvalidHandleError if the input string does not meet the atproto 'at-identifier' format requirements.\n * @see {@link AtIdentifierString}\n */\nexport function asAtIdentifierString(input) {\n assertAtIdentifierString(input);\n return input;\n}\n/**\n * Type guard that checks if a value is a valid AT identifier (DID or handle).\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid AT identifier\n * @see {@link AtIdentifierString}\n */\nexport function isAtIdentifierString(input) {\n if (!input || typeof input !== 'string') {\n return false;\n }\n else if (input.startsWith('did:')) {\n return isValidDid(input);\n }\n else {\n return isValidHandle(input);\n }\n}\n/**\n * Returns the input if it is a valid {@link AtIdentifierString} format string, or\n * `undefined` if it is not.\n *\n * @see {@link AtIdentifierString}\n */\nexport function ifAtIdentifierString(input) {\n return isAtIdentifierString(input) ? input : undefined;\n}\n// Legacy exports (should we deprecate these ?)\nexport { assertAtIdentifierString as ensureValidAtIdentifier, isAtIdentifierString as isValidAtIdentifier, };\n//# sourceMappingURL=at-identifier.js.map","export function success(value) {\n return { success: true, value };\n}\nexport function failure(message) {\n return { success: false, message };\n}\n//# sourceMappingURL=result.js.map","import { failure, success } from './lib/result.js';\nexport class NSID {\n static parse(input) {\n return new NSID(input);\n }\n static create(authority, name) {\n const input = [...authority.split('.').reverse(), name].join('.');\n return new NSID(input);\n }\n static isValid(nsid) {\n return isValidNsid(nsid);\n }\n static from(input) {\n if (input instanceof NSID) {\n // No need to clone, NSID is immutable\n return input;\n }\n if (Array.isArray(input)) {\n return new NSID(input.join('.'));\n }\n return new NSID(String(input));\n }\n constructor(nsid) {\n this.segments = parseNsid(nsid);\n }\n get authority() {\n return this.segments\n .slice(0, this.segments.length - 1)\n .reverse()\n .join('.');\n }\n get name() {\n return this.segments.at(this.segments.length - 1);\n }\n toString() {\n return this.segments.join('.');\n }\n}\nexport function ensureValidNsid(input) {\n const result = validateNsid(input);\n if (!result.success)\n throw new InvalidNsidError(result.message);\n}\nexport function parseNsid(nsid) {\n const result = validateNsid(nsid);\n if (!result.success)\n throw new InvalidNsidError(result.message);\n return result.value;\n}\nexport function isValidNsid(input) {\n // Since the regex version is more performant for valid NSIDs, we use it when\n // we don't care about error details.\n return typeof input === 'string' && validateNsidRegex(input).success;\n}\n// Human readable constraints on NSID:\n// - a valid domain in reversed notation\n// - followed by an additional period-separated name, which is camel-case letters\nexport function validateNsid(input) {\n if (input.length > 253 + 1 + 63) {\n return failure('NSID is too long (317 chars max)');\n }\n if (hasDisallowedCharacters(input)) {\n return failure('Disallowed characters in NSID (ASCII letters, digits, dashes, periods only)');\n }\n const segments = input.split('.');\n if (segments.length < 3) {\n return failure('NSID needs at least three parts');\n }\n for (const l of segments) {\n if (l.length < 1) {\n return failure('NSID parts can not be empty');\n }\n if (l.length > 63) {\n return failure('NSID part too long (max 63 chars)');\n }\n if (startsWithHyphen(l) || endsWithHyphen(l)) {\n return failure('NSID parts can not start or end with hyphen');\n }\n }\n if (startsWithNumber(segments[0])) {\n return failure('NSID first part may not start with a digit');\n }\n if (!isValidIdentifier(segments[segments.length - 1])) {\n return failure('NSID name part must be only letters and digits (and no leading digit)');\n }\n return success(segments);\n}\nfunction hasDisallowedCharacters(v) {\n return !/^[a-zA-Z0-9.-]*$/.test(v);\n}\nfunction startsWithNumber(v) {\n const charCode = v.charCodeAt(0);\n return charCode >= 48 && charCode <= 57;\n}\nfunction startsWithHyphen(v) {\n return v.charCodeAt(0) === 45; /* - */\n}\nfunction endsWithHyphen(v) {\n return v.charCodeAt(v.length - 1) === 45; /* - */\n}\nfunction isValidIdentifier(v) {\n // Note, since we already know that \"v\" only contains [a-zA-Z0-9-], we can\n // simplify the following regex by checking only the first char and presence\n // of \"-\".\n // return /^[a-zA-Z][a-zA-Z0-9]*$/.test(v)\n return !startsWithNumber(v) && !v.includes('-');\n}\n/**\n * @deprecated Use {@link ensureValidNsid} if you care about error details,\n * {@link parseNsid}/{@link NSID.parse} if you need the parsed segments, or\n * {@link isValidNsid} if you just want a boolean.\n */\nexport function ensureValidNsidRegex(nsid) {\n const result = validateNsidRegex(nsid);\n if (!result.success)\n throw new InvalidNsidError(result.message);\n}\n/**\n * Regexp based validation that behaves identically to the previous code but\n * provides less detailed error messages (while being 20% to 50% faster).\n */\nexport function validateNsidRegex(value) {\n if (value.length > 253 + 1 + 63) {\n return failure('NSID is too long (317 chars max)');\n }\n if (\n // Fast check for small values\n value.length < 5 ||\n !/^[a-zA-Z](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?:\\.[a-zA-Z](?:[a-zA-Z0-9]{0,62})?)$/.test(value)) {\n return failure(\"NSID didn't validate via regex\");\n }\n return success(value);\n}\nexport class InvalidNsidError extends Error {\n}\n//# sourceMappingURL=nsid.js.map","const RECORD_KEY_MAX_LENGTH = 512;\nconst RECORD_KEY_MIN_LENGTH = 1;\nconst RECORD_KEY_INVALID_VALUES = new Set(['.', '..']);\nconst RECORD_KEY_REGEX = /^[a-zA-Z0-9_~.:-]{1,512}$/;\n// https://atproto.com/specs/record-key#record-key-syntax\n// Regardless of the type, Record Keys must fulfill some baseline syntax constraints:\n// - restricted to a subset of ASCII characters -- the allowed characters are\n// alphanumeric (A-Za-z0-9), period, dash, underscore, colon, or tilde (.-_:~)\n// - must have at least 1 and at most 512 characters\n// - the specific record key values . and .. are not allowed\n// - must be a permissible part of repository MST path string (the above\n// constraints satisfy this condition)\n// - must be permissible to include in a path component of a URI (following\n// RFC-3986, section 3.3). The above constraints satisfy this condition, by\n// matching the \"unreserved\" characters allowed in generic URI paths.\nexport function ensureValidRecordKey(input) {\n if (input.length > RECORD_KEY_MAX_LENGTH ||\n input.length < RECORD_KEY_MIN_LENGTH) {\n throw new InvalidRecordKeyError(`record key must be ${RECORD_KEY_MIN_LENGTH} to ${RECORD_KEY_MAX_LENGTH} characters`);\n }\n if (RECORD_KEY_INVALID_VALUES.has(input)) {\n throw new InvalidRecordKeyError('record key can not be \".\" or \"..\"');\n }\n // simple regex to enforce most constraints via just regex and length.\n if (!RECORD_KEY_REGEX.test(input)) {\n throw new InvalidRecordKeyError('record key syntax not valid (regex)');\n }\n}\nexport function isValidRecordKey(input) {\n return (typeof input === 'string' &&\n input.length >= RECORD_KEY_MIN_LENGTH &&\n input.length <= RECORD_KEY_MAX_LENGTH &&\n RECORD_KEY_REGEX.test(input) &&\n !RECORD_KEY_INVALID_VALUES.has(input));\n}\nexport class InvalidRecordKeyError extends Error {\n}\n//# sourceMappingURL=recordkey.js.map","import { isAtIdentifierString } from './at-identifier.js';\nimport { isValidDid } from './did.js';\nimport { failure, success } from './lib/result.js';\nimport { isValidNsid } from './nsid.js';\nimport { isValidRecordKey } from './recordkey.js';\n/**\n * Type guard that checks if a value is a valid {@link AtUriString}\n *\n * @see {@link AtUriString}\n */\nexport function isAtUriString(input, options) {\n return parseAtUriString(input, options).success;\n}\n/**\n * Returns the input if it is a valid {@link AtUriString} format string, or\n * `undefined` if it is not.\n *\n * @see {@link AtUriString}\n */\nexport function ifAtUriString(input, options) {\n return isAtUriString(input, options) ? input : undefined;\n}\n/**\n * Casts a string to an {@link AtUriString} if it is a valid AT URI format\n * string, throwing an error if it is not.\n *\n * @throws InvalidAtUriError if the input string does not meet the atproto AT URI format requirements.\n * @see {@link AtUriString}\n */\nexport function asAtUriString(input, options) {\n assertAtUriString(input, options);\n return input;\n}\n/**\n * Assert the validity of an {@link AtUriString}, throwing an error if the\n * {@link input} is not a valid AT URI.\n *\n * @throws InvalidAtUriError if the {@link input} is not a valid {@link AtUriString}\n */\nexport function assertAtUriString(input, options) {\n // Optimistically use faster isAtUriString(), throwing a detailed error only\n // in case of failure. This check, and the fact that the code after it always\n // throws, also ensures that isAtUriString() and assertAtUriString()'s\n // behavior are always consistent.\n const result = parseAtUriString(input, options);\n if (!result.success) {\n throw new InvalidAtUriError(result.message);\n }\n}\n/**\n * Assert the **non-strict** validity of an {@link AtUriString}, throwing a\n * detailed error if the {@link input} is not a valid AT URI.\n *\n * @throws InvalidAtUriError if the {@link input} is not a valid {@link AtUriString}\n * @deprecated use {@link assertAtUriString} with `{ strict: false }` option instead\n */\nexport function ensureValidAtUri(input) {\n assertAtUriString(input, { strict: false, detailed: true });\n}\n/**\n * Assert the (non-strict!) validity of an {@link AtUriString}, throwing an\n * error if the {@link input} is not a valid AT URI.\n *\n * @throws InvalidAtUriError if the {@link input} is not a valid {@link AtUriString}\n * @deprecated use {@link assertAtUriString} with `{ strict: false }` option instead\n */\nexport function ensureValidAtUriRegex(input) {\n assertAtUriString(input, { strict: false, detailed: false });\n}\n/**\n * Type guard that checks if a value is a valid {@link AtUriString} format\n * string, without enforcing strict record key validation. This is useful for\n * cases where you want to allow a wider range of valid ATURIs, such as when\n * validating user input or when the record key is not relevant.\n *\n * @deprecated use {@link isAtUriString} with `{ strict: false }` option instead\n */\nexport function isValidAtUri(input) {\n return isAtUriString(input, { strict: false });\n}\nexport class InvalidAtUriError extends Error {\n}\nconst INVALID_CHAR_REGEXP = /[^a-zA-Z0-9._~:@!$&'()*+,;=%/\\\\[\\]#?-]/;\nconst AT_URI_REGEXP = /^(?<uri>at:\\/\\/(?<authority>[^/?#\\s]+)(?:\\/(?<collection>[^/?#\\s]+)(?:\\/(?<rkey>[^/?#\\s]+))?)?(?<trailingSlash>\\/)?)(?:\\?(?<query>[^#\\s]*))?(?:#(?<hash>[^\\s]*))?$/;\nexport const SPACE_URI_PREFIX = 'at:space/';\n// @TODO remove before beta, with fromLegacySpaceUri().\nconst LEGACY_SPACE_URI_REGEXP = /^at:\\/\\/([^/?#\\s]+)\\/space\\//;\nconst SPACE_AT_URI_REGEXP = /^at:space\\/(?<authority>[^/?#\\s]+)\\/(?<spaceType>[^/?#\\s]+)\\/(?<skey>[^/?#\\s]+)(?:\\/(?<authorDid>[^/?#\\s]+)\\/(?<collection>[^/?#\\s]+)\\/(?<rkey>[^/?#\\s]+))?(?<trailingSlash>\\/)?(?:\\?(?<query>[^#\\s]*))?(?:#(?<hash>[^\\s]*))?$/;\n/**\n * Parses a valid {@link AtUriString} into a {@link AtUriParts} object, or\n * returns a failure with a detailed error message if the string is not a valid\n * {@link AtUriString}.\n */\nexport function parseAtUriString(input, options) {\n if (typeof input !== 'string') {\n return failure('ATURI must be a string');\n }\n if (input.length > 8192) {\n return failure('ATURI exceeds maximum length');\n }\n const invalidChar = input.match(INVALID_CHAR_REGEXP);\n if (invalidChar) {\n return failure('Disallowed characters in ATURI (ASCII)');\n }\n if (isSpaceUri(input)) {\n const current = fromLegacySpaceUri(input);\n if (current === undefined)\n return parseSpaceAtUriString(input, options);\n if (options?.strict !== false) {\n return failure('Space ATURI must start with \"at:space/\"');\n }\n return parseSpaceAtUriString(current, options);\n }\n const match = input.match(AT_URI_REGEXP);\n const groups = match?.groups;\n if (!groups) {\n // Regex validation failed, but we don't know exactly why. Provide more\n // detailed error messages if the \"detailed\" option is set, falling back to\n // a generic error.\n if (options?.detailed) {\n if (!input.startsWith('at://')) {\n return failure('ATURI must start with \"at://\" or \"at:space/\"');\n }\n if (input.includes(' ')) {\n return failure('ATURI can not contain spaces');\n }\n if (input.includes('//', 5)) {\n return failure('ATURI can not have empty path segments');\n }\n const pathStart = input.indexOf('/', 5); // after \"at://\"\n if (pathStart !== -1) {\n const fragmentIndex = input.indexOf('#');\n const pathEnd = fragmentIndex !== -1 ? fragmentIndex : input.length;\n const secondSlash = input.indexOf('/', pathStart + 1);\n if (secondSlash !== -1 && secondSlash !== pathEnd - 1) {\n return failure('ATURI can not have more than two path segments');\n }\n }\n }\n return failure('ATURI does not match expected format');\n }\n // @NOTE Percent-encoding is allowed by the AT URI specification, but any\n // percent-encoded characters appearing in the collection NSID or record key\n // will effectively be rejected by the isValidNsid and isValidRecordKey\n // validators. Since these values are defined to be plain ASCII identifiers,\n // this legacy behavior is beneficial: it ensures that normalized\n // (non-percent-encoded) values are always used, as prescribed by the spec.\n if (!isAtIdentifierString(groups.authority)) {\n return failure('ATURI has invalid authority');\n }\n if (groups.collection != null && !isValidNsid(groups.collection)) {\n return failure('ATURI has invalid collection');\n }\n if (groups.hash != null) {\n const result = parseJsonPointer(groups.hash, options);\n if (result.success) {\n groups.hash = result.value;\n }\n else {\n return failure(`ATURI has invalid fragment (${result.message})`);\n }\n }\n if (options?.strict !== false) {\n if (groups.trailingSlash != null) {\n return failure('ATURI can not have a trailing slash');\n }\n if (groups.query != null) {\n return failure('ATURI query part is not allowed');\n }\n if (groups.rkey != null && !isValidRecordKey(groups.rkey)) {\n return failure('ATURI has invalid record key');\n }\n }\n return success({ ...groups, isSpace: false });\n}\n/**\n * Whether a string addresses permissioned space data. Checks only for the\n * `at:space/` prefix (or the alpha form's) โ use {@link isAtUriString} to\n * validate the URI itself.\n */\nfunction isSpaceUri(input) {\n return (typeof input === 'string' &&\n (input.startsWith(SPACE_URI_PREFIX) || LEGACY_SPACE_URI_REGEXP.test(input)));\n}\n/**\n * Rewrites a space URI in its spaces alpha form, `at://{spaceDid}/space/{rest}`,\n * as `at:space/{spaceDid}/{rest}`. Returns `undefined` for any other input.\n *\n * Records written during the alpha may still embed URIs in the old form, so the\n * validators accept it in lenient mode (`strict: false`), and {@link AtUri}\n * reads it and prints the current form. Strict validation and\n * {@link SpaceRef.parse} accept only the current form.\n *\n * @TODO remove before beta, along with support for the old form.\n */\nexport function fromLegacySpaceUri(input) {\n const match = LEGACY_SPACE_URI_REGEXP.exec(input);\n return match\n ? `${SPACE_URI_PREFIX}${match[1]}/${input.slice(match[0].length)}`\n : undefined;\n}\n/** Whether a string is a valid ATURI addressing public repo data. */\nexport function isPublicAtUriString(input, options) {\n return !isSpaceUri(input) && isAtUriString(input, options);\n}\n/** Whether a string is a valid ATURI addressing permissioned space data. */\nexport function isSpaceAtUriString(input, options) {\n return isSpaceUri(input) && isAtUriString(input, options);\n}\n/**\n * Whether a string is a valid space ref โ the three-part form only. A URI naming\n * a record within a space is not a space ref.\n */\nexport function isSpaceRefString(input, options) {\n if (!isSpaceUri(input))\n return false;\n const result = parseAtUriString(input, options);\n return (result.success && result.value.isSpace && result.value.authorDid == null);\n}\n/**\n * A space's identity and membership are keyed on DIDs, so unlike a public ATURI\n * neither the authority nor the author may be a handle.\n */\nfunction parseSpaceAtUriString(input, options) {\n const groups = input.match(SPACE_AT_URI_REGEXP)?.groups;\n if (!groups) {\n return failure('Space ATURI does not match expected format');\n }\n if (!isValidDid(groups.authority)) {\n return failure('Space ATURI authority must be a DID');\n }\n if (!isValidNsid(groups.spaceType)) {\n return failure('Space ATURI has invalid space type');\n }\n if (groups.authorDid != null) {\n if (!isValidDid(groups.authorDid)) {\n return failure('Space ATURI author must be a DID');\n }\n if (!isValidNsid(groups.collection)) {\n return failure('Space ATURI has invalid collection');\n }\n }\n if (groups.hash != null) {\n const result = parseJsonPointer(groups.hash, options);\n if (result.success) {\n groups.hash = result.value;\n }\n else {\n return failure(`Space ATURI has invalid fragment (${result.message})`);\n }\n }\n if (options?.strict !== false) {\n if (groups.trailingSlash != null) {\n return failure('Space ATURI can not have a trailing slash');\n }\n if (groups.query != null) {\n return failure('Space ATURI query part is not allowed');\n }\n // A space key carries the same syntax requirements as a record key.\n if (!isValidRecordKey(groups.skey)) {\n return failure('Space ATURI has invalid space key');\n }\n if (groups.rkey != null && !isValidRecordKey(groups.rkey)) {\n return failure('Space ATURI has invalid record key');\n }\n }\n return success({ ...groups, isSpace: true });\n}\nconst BASIC_JSON_POINTER_REGEXP = /^\\/[a-zA-Z0-9._~:@!$&')(*+,;=%[\\]/-]*$/;\n/**\n * Checks if a string is a valid JSON pointer (RFC-6901) with the allowed chars\n * for ATURI fragments. This is a very loose validation that only checks the\n * basic syntax and charset.\n */\nfunction parseJsonPointer(value, options) {\n if (!BASIC_JSON_POINTER_REGEXP.test(value)) {\n return failure('Invalid JSON pointer');\n }\n const result = parsePercentEncoding(value);\n // In non-strict mode, we allow invalid percent-encoding in the fragment\n if (!result.success && options?.strict === false) {\n return success(value);\n }\n return result;\n}\nfunction parsePercentEncoding(value) {\n try {\n return success(decodeURIComponent(value));\n }\n catch {\n // decodeURIComponent throws if the percent-encoding is invalid (e.g. \"%FF\")\n return failure('Invalid percent-encoding');\n }\n}\n//# sourceMappingURL=aturi_validation.js.map","(()=>{\"use strict\";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})}},t={};function r(e,t){return void 0===t&&(t=\"-\"),new RegExp(\"^(?!0{4}\"+t+\"0{2}\"+t+\"0{2})((?=[0-9]{4}\"+t+\"(((0[^2])|1[0-2])|02(?=\"+t+\"(([0-1][0-9])|2[0-8])))\"+t+\"[0-9]{2})|(?=((([13579][26])|([2468][048])|(0[48]))0{2})|([0-9]{2}((((0|[2468])[48])|[2468][048])|([13579][26])))\"+t+\"02\"+t+\"29))([0-9]{4})\"+t+\"(?!((0[469])|11)\"+t+\"31)((0[1,3-9]|1[0-2])|(02(?!\"+t+\"3)))\"+t+\"(0[1-9]|[1-2][0-9]|3[0-1])$\").test(e)}function n(e){var t=/\\D/.exec(e);return t?t[0]:\"\"}function i(e,t,r){void 0===t&&(t=\":\"),void 0===r&&(r=!1);var i=new RegExp(\"^([0-1]|2(?=([0-3])|4\"+t+\"00))[0-9]\"+t+\"[0-5][0-9](\"+t+\"([0-5]|6(?=0))[0-9])?(.[0-9]{1,9})?$\");if(!r||!/[Z+\\-]/.test(e))return i.test(e);if(/Z$/.test(e))return i.test(e.replace(\"Z\",\"\"));var o=e.includes(\"+\"),a=e.split(/[+-]/),u=a[0],d=a[1];return i.test(u)&&function(e,t,r){return void 0===r&&(r=\":\"),new RegExp(t?\"^(0(?!(2\"+r+\"4)|0\"+r+\"3)|1(?=([0-1]|2(?=\"+r+\"[04])|[34](?=\"+r+\"0))))([03469](?=\"+r+\"[03])|[17](?=\"+r+\"0)|2(?=\"+r+\"[04])|5(?=\"+r+\"[034])|8(?=\"+r+\"[04]))\"+r+\"([03](?=0)|4(?=5))[05]$\":\"^(0(?=[^0])|1(?=[0-2]))([39](?=\"+r+\"[03])|[0-24-8](?=\"+r+\"00))\"+r+\"[03]0$\").test(e)}(d,o,n(d))}function o(e){var t=e.split(\"T\"),o=t[0],a=t[1],u=r(o,n(o));if(!a)return!1;var d,s=(d=a.match(/([^Z+\\-\\d])(?=\\d+\\1)/),Array.isArray(d)?d[0]:\"\");return u&&i(a,s,!0)}function a(e,t){return void 0===t&&(t=\"-\"),new RegExp(\"^[0-9]{4}\"+t+\"(0(?=[^0])|1(?=[0-2]))[0-9]$\").test(e)}e.r(t),e.d(t,{isValidDate:()=>r,isValidISODateString:()=>o,isValidTime:()=>i,isValidYearMonth:()=>a});var u=exports;for(var d in t)u[d]=t[d];t.__esModule&&Object.defineProperty(u,\"__esModule\",{value:!0})})();","import * as isoDatestringValidator from 'iso-datestring-validator';\n// Node ESM interop wraps \"iso-datestring-validator\" as { default: { ... } }\n// @TODO Remove \"iso-datestring-validator\" dependency\nconst { isValidISODateString } = ((m) => m.default ?? m)(isoDatestringValidator);\n/**\n * Indicates a date or string is not a valid representation of a datetime\n * according to the atproto\n * {@link https://atproto.com/specs/lexicon#datetime specification}.\n */\nexport class InvalidDatetimeError extends Error {\n}\n/**\n * @see {@link AtprotoDate}\n */\nexport function assertAtprotoDate(date) {\n const res = parseDate(date);\n if (!res.success) {\n throw new InvalidDatetimeError(res.message);\n }\n}\n/**\n * @see {@link AtprotoDate}\n */\nexport function asAtprotoDate(date) {\n assertAtprotoDate(date);\n return date;\n}\n/**\n * @see {@link AtprotoDate}\n */\nexport function isAtprotoDate(date) {\n return parseDate(date).success;\n}\n/**\n * @see {@link AtprotoDate}\n */\nexport function ifAtprotoDate(date) {\n return isAtprotoDate(date) ? date : undefined;\n}\n/**\n * Validates that a string is a valid {@link DatetimeString} format string,\n * throwing an error if it is not.\n *\n * @throws InvalidDatetimeError if the input string does not meet the atproto 'datetime' format requirements.\n * @see {@link DatetimeString}\n */\nexport function assertDatetimeString(input) {\n const result = parseString(input);\n if (!result.success) {\n throw new InvalidDatetimeError(result.message);\n }\n}\n/**\n * Casts a string to a {@link DatetimeString} if it is a valid datetime format\n * string, throwing an error if it is not.\n *\n * @throws InvalidDatetimeError if the input string does not meet the atproto 'datetime' format requirements.\n * @see {@link DatetimeString}\n */\nexport function asDatetimeString(input) {\n assertDatetimeString(input);\n return input;\n}\n/**\n * Checks if a string is a valid {@link DatetimeString} format string.\n *\n * @see {@link DatetimeString}\n */\nexport function isDatetimeString(input) {\n return parseString(input).success;\n}\n/**\n * Matches any ISO-ish datetime string. This is a more lenient check than\n * the strict {@link isDatetimeString} guard, which only allows datetimes that\n * fully conform to the AT Protocol specification (e.g. must include timezone).\n */\nexport function isDatetimeStringLenient(input) {\n // @NOTE the returned type assertion is inaccurate wrt. the DatetimeString\n // type definition. A more accurate solution would be to use a branded type\n // instead of a template literal for the \"datetime\" format\n if (typeof input !== 'string')\n return false;\n // @NOTE The \"iso-datestring-validator\" implementation is *not* compliant with\n // the AT Protocol datetime specification. In particular, it rejects some\n // valid AT Protocol datetimes (eg: \"1985-04-12T23:20:50.1235678912345Z\",\n // \"1985-04-12T23:20:50.123+01:45\", \"1985-04-12T23:20:50.1234567890Z\"). For\n // this reason, we accept anything that passes \"isDatetimeString\" validation.\n // That check runs first because it is much cheaper (\"isValidISODateString\"\n // compiles new RegExp objects on every call), and because virtually every\n // datetime found in practice passes it.\n if (isDatetimeString(input))\n return true;\n try {\n return isValidISODateString(input);\n }\n catch {\n // isValidISODateString can throw on some inputs.\n return false;\n }\n}\n/**\n * Returns the input if it is a valid {@link DatetimeString} format string, or\n * `undefined` if it is not.\n *\n * @see {@link DatetimeString}\n */\nexport function ifDatetimeString(input) {\n return isDatetimeString(input) ? input : undefined;\n}\n/**\n * Returns the current date and time as a {@link DatetimeString}.\n *\n * @see {@link DatetimeString}\n */\nexport function currentDatetimeString() {\n return toDatetimeString(new Date());\n}\n/**\n * Converts any {@link Date} into a {@link DatetimeString} if possible, throwing\n * an error if the date is not a valid atproto datetime.\n *\n * This is short-hand for `asAtprotoDate(date).toISOString()`.\n *\n * @throws InvalidDatetimeError if the input date is not a valid atproto datetime (eg, it is too far in the future or past, or it normalizes to a negative year).\n * @see {@link DatetimeString}\n */\nexport function toDatetimeString(input) {\n const date = typeof input === 'string' || typeof input === 'number'\n ? new Date(input)\n : input;\n return asAtprotoDate(date).toISOString();\n}\n/**\n * Takes a flexible datetime string and normalizes its representation.\n *\n * This function will work with any valid value that can be parsed as a date. It\n * *additionally* is more flexible about accepting datetimes that are missing\n * timezone information, and normalizing them to a valid atproto datetime.\n *\n * One use-case is a consistent, sortable string. Another is to work with older\n * invalid createdAt datetimes.\n *\n * @note This function might return different normalized strings for the same\n * input depending on the timezone of the machine it is run on, since it will\n * attempt to parse the input \"as is\" if it fails to parse with an explicit\n * timezone.\n *\n * @returns ISODatetimeString - a valid atproto datetime with millisecond precision (3 sub-second digits) and UTC timezone with trailing 'Z' syntax.\n * @throws InvalidDatetimeError - if the input string could not be parsed as a datetime, even with permissive parsing.\n */\nexport function normalizeDatetime(dtStr) {\n if (\n // Explicit timezone offset\n /[+-]\\d\\d:?\\d\\d/.test(dtStr) ||\n // 'Z' timezone designator\n /\\dZ\\b/.test(dtStr) ||\n // Timezone abbreviation (eg. \"EST\", \"PST\", \"UTC\", \"GMT\", etc), as in:\n // > Tue Mar 17 2026 16:38:44 PST (Pacific Standard Time)\n /\\b[A-Z]{3,4}\\b/.test(dtStr)) {\n // Since we do have a timezone designator, we can try parsing \"as is\" and\n // should get consistent results regardless of local timezone.\n // @NOTE NodeJS will reject dates with an un-recognized timezone designator\n // (like \"AFT\"), even if we add a well-known timezone abbreviation like\n // \"UTC\" or \"Z\".\n const date = new Date(dtStr);\n if (isAtprotoDate(date)) {\n return date.toISOString();\n }\n }\n else {\n // If there is no timezone information, try parsing as UTC using two\n // different syntaxes, falling back to parsing \"as is\".\n const dateZ = new Date(`${dtStr}Z`);\n if (isAtprotoDate(dateZ)) {\n return dateZ.toISOString();\n }\n const dateUTC = new Date(`${dtStr} UTC`);\n if (isAtprotoDate(dateUTC)) {\n return dateUTC.toISOString();\n }\n // Despite our best efforts to parse as a consistent value, appending \"Z\" or\n // \" UTC\" did not work, so we will try parsing \"as is\", which may yield\n // different results depending on the local timezone of the machine.\n const date = new Date(dtStr);\n if (isAtprotoDate(date)) {\n return date.toISOString();\n }\n }\n throw new InvalidDatetimeError('datetime did not parse as any timestamp format');\n}\n/**\n * Variant of {@link normalizeDatetime} which always returns a valid datetime\n * string.\n *\n * If a {@link InvalidDatetimeError} is encountered, returns the UNIX epoch time\n * as a UTC datetime (`1970-01-01T00:00:00.000Z`).\n *\n * @see {@link normalizeDatetime}\n */\nexport function normalizeDatetimeAlways(dtStr) {\n try {\n return normalizeDatetime(dtStr);\n }\n catch (err) {\n return '1970-01-01T00:00:00.000Z';\n }\n}\n// Legacy exports (should we deprecate these ?)\nexport { assertDatetimeString as ensureValidDatetime, isDatetimeString as isValidDatetime, };\nconst failure = (m) => ({ success: false, message: m });\nconst success = (v) => ({ success: true, value: v });\n/**\n * @see {@link https://www.rfc-editor.org/rfc/rfc3339#section-5.6 Internet Date/Time Format}\n *\n * @example\n * ```abnf\n * date-fullyear = 4DIGIT\n * date-month = 2DIGIT ; 01-12\n * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on\n * ; month/year\n * time-hour = 2DIGIT ; 00-23\n * time-minute = 2DIGIT ; 00-59\n * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second\n * ; rules\n * time-secfrac = \".\" 1*DIGIT\n * time-numoffset = (\"+\" / \"-\") time-hour \":\" time-minute\n * time-offset = \"Z\" / time-numoffset\n * partial-time = time-hour \":\" time-minute \":\" time-second\n * [time-secfrac]\n * full-date = date-fullyear \"-\" date-month \"-\" date-mday\n * full-time = partial-time time-offset\n * date-time = full-date \"T\" full-time\n * ```\n */\nconst DATETIME_REGEX = /^(?<full_year>[0-9]{4})-(?<date_month>0[1-9]|1[012])-(?<date_mday>[0-2][0-9]|3[01])T(?<time_hour>[0-1][0-9]|2[0-3]):(?<time_minute>[0-5][0-9]):(?<time_second>[0-5][0-9]|60)(?<time_secfrac>\\.[0-9]+)?(?<time_offset>Z|(?<time_numoffset>[+-](?:[0-1][0-9]|2[0-3]):[0-5][0-9]))$/;\n/**\n * Validates that the input is a datetime string according to atproto Lexicon\n * rules, and parses it into a Date object.\n */\nfunction parseString(input) {\n // @NOTE Performing cheap tests first\n if (typeof input !== 'string') {\n return failure('datetime must be a string');\n }\n if (input.length > 64) {\n return failure('datetime is too long (64 chars max)');\n }\n if (input.endsWith('-00:00')) {\n return failure('datetime can not use \"-00:00\" for UTC timezone');\n }\n if (!DATETIME_REGEX.test(input)) {\n return failure(\"datetime is not in a valid format (must match RFC 3339 & ISO 8601 with 'Z' or ยฑhh:mm timezone)\");\n }\n // must parse as ISO 8601; this also verifies semantics like leap seconds and\n // correct number of days in month, which the regex does not check for\n const date = new Date(input);\n return parseDate(date);\n}\n/**\n * Ensures that a Date object represents a valid datetime according to atproto\n * Lexicon rules. This ensures that `date.toISOString()` will produce a valid\n * datetime string that can be used where {@link DatetimeString} is expected.\n */\nfunction parseDate(date) {\n const fullYear = date.getUTCFullYear();\n // Ensures that the date is valid. We could check isNaN(date.getTime()) here\n // but since we'll check the year anyway, we just use that for the validity\n // check since an invalid date will have NaN year.\n if (Number.isNaN(fullYear)) {\n return failure('datetime did not parse as ISO 8601');\n }\n // Ensure that the ISO string representation does not start with ยฑYYYYYY\n if (fullYear < 0) {\n return failure('datetime normalized to a negative time');\n }\n if (fullYear > 9999) {\n return failure('datetime year is too far in the future');\n }\n return success(date);\n}\n//# sourceMappingURL=datetime.js.map","const BCP47_REGEXP = /^((?<grandfathered>(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)|(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang))|((?<language>([A-Za-z]{2,3}(-(?<extlang>[A-Za-z]{3}(-[A-Za-z]{3}){0,2}))?)|[A-Za-z]{4}|[A-Za-z]{5,8})(-(?<script>[A-Za-z]{4}))?(-(?<region>[A-Za-z]{2}|[0-9]{3}))?(-(?<variant>[A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*(-(?<extension>[0-9A-WY-Za-wy-z](-[A-Za-z0-9]{2,8})+))*(-(?<privateUseA>[xX](-[A-Za-z0-9]{1,8})+))?)|(?<privateUseB>[xX](-[A-Za-z0-9]{1,8})+))$/;\n/**\n * The primary language subtag must be a lowercase two- or three-letter code\n * (RFC 5646 ยง2.1.1 recommends lowercase; the atproto interop suite treats\n * uppercase primary subtags such as `JA`, and bare four-letter runs such as\n * `jaja`, as invalid).\n *\n * This is enforced only in the strict {@link parseLanguageString} path.\n * {@link isValidLanguage} intentionally stays permissive of these legacy forms\n * so that existing records are not retroactively invalidated.\n */\nfunction hasStrictPrimarySubtag(groups) {\n const language = groups.language;\n if (!language)\n return true; // grandfathered / private-use only: nothing to check\n const primary = language.split('-')[0];\n return /^[a-z]{2,3}$/.test(primary);\n}\nfunction matchValidLanguage(input) {\n const parsed = input.match(BCP47_REGEXP);\n if (!parsed?.groups)\n return null;\n if (hasDuplicateVariantOrSingleton(input, parsed.groups))\n return null;\n return parsed;\n}\n/**\n * Detect repeated variant subtags or repeated extension singleton\n * subtags within a well-formed BCP 47 langtag. The comparison is\n * case-insensitive.\n *\n * The regex alone cannot enforce this โ JavaScript named captures keep\n * only the last occurrence of a repeated group โ so this is run as a\n * post-match check on the original input string.\n *\n * Grandfathered and privateuse-only tags carry neither variants nor\n * extension singletons and short-circuit.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc5646.html#section-4.1 RFC 5646 ยง4.1 Choice of Language Tag}\n * @see {@link https://www.rfc-editor.org/rfc/rfc5646.html#section-2.1.1 RFC 5646 ยง2.1.1 Case Considerations}\n */\nfunction hasDuplicateVariantOrSingleton(input, groups) {\n if (groups.grandfathered || groups.privateUseB)\n return false;\n const subtags = input.split('-');\n let i = 1; // language\n if (subtags[0].length === 2 || subtags[0].length === 3) {\n // extlang: 0โ3 subtags of 3 letters\n let count = 0;\n while (count < 3 &&\n i < subtags.length &&\n /^[A-Za-z]{3}$/.test(subtags[i])) {\n i++;\n count++;\n }\n }\n // script\n if (i < subtags.length && /^[A-Za-z]{4}$/.test(subtags[i]))\n i++;\n // region\n if (i < subtags.length && /^([A-Za-z]{2}|[0-9]{3})$/.test(subtags[i]))\n i++;\n const seenVariants = new Set();\n while (i < subtags.length &&\n /^([A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3})$/.test(subtags[i])) {\n const key = subtags[i].toLowerCase();\n if (seenVariants.has(key))\n return true;\n seenVariants.add(key);\n i++;\n }\n const seenSingletons = new Set();\n while (i < subtags.length && /^[0-9A-WYZa-wyz]$/.test(subtags[i])) {\n const singleton = subtags[i].toLowerCase();\n if (seenSingletons.has(singleton))\n return true;\n seenSingletons.add(singleton);\n i++;\n while (i < subtags.length && /^[A-Za-z0-9]{2,8}$/.test(subtags[i]))\n i++;\n }\n return false;\n}\nexport function parseLanguageString(input) {\n const parsed = matchValidLanguage(input);\n if (!parsed?.groups)\n return null;\n const { groups } = parsed;\n if (!hasStrictPrimarySubtag(groups))\n return null;\n return {\n grandfathered: groups.grandfathered,\n language: groups.language,\n extlang: groups.extlang,\n script: groups.script,\n region: groups.region,\n variant: groups.variant,\n extension: groups.extension,\n privateUse: groups.privateUseA || groups.privateUseB,\n };\n}\n/**\n * Validates well-formed BCP 47 syntax.\n *\n * Only checks the ABNF grammar of RFC 5646 ยง2.1. Semantic constraints from\n * ยง4.1 (e.g. no repeated variant subtags) are NOT enforced โ use\n * {@link parseLanguageString} for strict validation.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc5646.html#section-2.1}\n */\nexport function isValidLanguage(input) {\n return BCP47_REGEXP.test(input);\n}\n//# sourceMappingURL=language.js.map","const TID_LENGTH = 13;\nconst TID_REGEX = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/;\nexport function ensureValidTid(input) {\n if (input.length !== TID_LENGTH) {\n throw new InvalidTidError(`TID must be ${TID_LENGTH} characters`);\n }\n // simple regex to enforce most constraints via just regex and length.\n if (!TID_REGEX.test(input)) {\n throw new InvalidTidError('TID syntax not valid (regex)');\n }\n}\nexport function isValidTid(input) {\n return (typeof input === 'string' &&\n input.length === TID_LENGTH &&\n TID_REGEX.test(input));\n}\nexport class InvalidTidError extends Error {\n}\n//# sourceMappingURL=tid.js.map","export function isValidUri(input) {\n return (typeof input === 'string' &&\n /^[A-Za-z][A-Za-z0-9+.-]*:(?:\\/\\/)?[^\\s/][^\\s]*$/.test(input));\n}\n//# sourceMappingURL=uri.js.map","import { toBase64 } from '@atproto/lex-data';\n// Byte-level helpers used within this package. Not part of its public API.\nexport function utf8(str) {\n return new TextEncoder().encode(str);\n}\n// Big-endian, following the TLS convention for wire encodings.\nexport function uint16be(value) {\n if (value < 0 || value > 0xffff) {\n throw new Error(`value does not fit in a uint16: ${value}`);\n }\n return new Uint8Array([value >>> 8, value & 0xff]);\n}\n// Compares in time independent of where the inputs differ, for checking MACs.\nexport function timingSafeEqual(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= a[i] ^ b[i];\n }\n return diff === 0;\n}\n// Structured field byte sequences are serialized as padded base64 (RFC 9651\n// ยง4.1.8), while `toBase64` omits padding.\nexport function toPaddedBase64(bytes) {\n const base64 = toBase64(bytes);\n return base64.padEnd(Math.ceil(base64.length / 4) * 4, '=');\n}\n// Lexicographic byte order: the first differing byte decides, and a prefix sorts\n// before any longer key it starts.\nexport function compareBytes(a, b) {\n const length = Math.min(a.length, b.length);\n for (let i = 0; i < length; i++) {\n if (a[i] !== b[i])\n return a[i] - b[i];\n }\n return a.length - b.length;\n}\n//# sourceMappingURL=bytes.js.map","/** Every error this package throws on a protocol failure carries a stable `code`. */\nexport class SpaceError extends Error {\n}\nexport class SpaceTokenError extends SpaceError {\n constructor(message, code = 'BadJwt', options) {\n super(message, options);\n this.code = code;\n this.name = 'SpaceTokenError';\n }\n}\nexport class SpaceSignatureError extends SpaceError {\n constructor() {\n super(...arguments);\n this.name = 'SpaceSignatureError';\n this.code = 'BadSpaceSignature';\n }\n}\nexport class SpaceMacError extends SpaceError {\n constructor() {\n super(...arguments);\n this.name = 'SpaceMacError';\n this.code = 'InvalidSpaceMac';\n }\n}\nexport class SpaceKemError extends SpaceError {\n constructor() {\n super(...arguments);\n this.name = 'SpaceKemError';\n this.code = 'InvalidKemKey';\n }\n}\nexport class SpaceRepoVerificationError extends SpaceError {\n constructor() {\n super(...arguments);\n this.name = 'SpaceRepoVerificationError';\n this.code = 'InvalidSpaceRepo';\n }\n}\nexport class SpaceMetaArchiveError extends SpaceError {\n constructor() {\n super(...arguments);\n this.name = 'SpaceMetaArchiveError';\n this.code = 'InvalidSpaceMeta';\n }\n}\n//# sourceMappingURL=error.js.map","import { randomStr, verifySignature } from '@atproto/crypto';\nimport { fromBase64, toBase64 } from '@atproto/lex-data';\nimport { isValidDid, } from '@atproto/syntax';\nimport { utf8 } from './bytes.js';\nimport { SpaceTokenError } from './error.js';\n/**\n * How a space authority is addressed when acting as the space host: the service\n * entry a delegation token and a client attestation name as their audience. The\n * space host is the authority's PDS, like any other atproto account.\n */\nexport function spaceHostAud(spaceDid) {\n return `${spaceDid}#atproto_pds`;\n}\nexport const DELEGATION_TOKEN_TYP = 'atproto-space-delegation+jwt';\nexport const SPACE_CREDENTIAL_TYP = 'atproto-space-credential+jwt';\nexport const CLIENT_ATTESTATION_TYP = 'atproto-client-attestation+jwt';\n// @NOTE credentials carry no audience; HTTP message signatures bind each use to an audience DID.\nconst SPACE_TOKEN_TYPES = {\n delegation: {\n typ: DELEGATION_TOKEN_TYP,\n kid: '#atproto',\n expiresInSec: 60,\n requireAud: true,\n requireCnf: false,\n singleUse: true,\n },\n credential: {\n typ: SPACE_CREDENTIAL_TYP,\n kid: '#atproto',\n expiresInSec: 600,\n requireAud: false,\n requireCnf: true,\n singleUse: false,\n },\n clientAttestation: {\n typ: CLIENT_ATTESTATION_TYP,\n kid: undefined,\n expiresInSec: 60,\n requireAud: true,\n requireCnf: false,\n singleUse: true,\n },\n};\nexport const CLOCK_SKEW_SEC = 5;\nexport const SPACE_CREDENTIAL_MAX_AGE_SEC = 3600;\n/** A user's authorization for an app to request a space credential on its behalf. */\nexport async function createDelegationToken(opts) {\n const spec = SPACE_TOKEN_TYPES.delegation;\n const token = buildSpaceToken({ typ: spec.typ, kid: spec.kid }, { iss: opts.iss, sub: opts.sub, aud: opts.aud }, opts.expiresInSec ?? spec.expiresInSec);\n return signSpaceToken(token, opts.keypair);\n}\n/** A space authority's grant to read a space, bound to the holder's `keyId`. */\nexport async function createSpaceCredential(opts) {\n const spec = SPACE_TOKEN_TYPES.credential;\n const expiresInSec = opts.expiresInSec ?? spec.expiresInSec;\n if (!Number.isFinite(expiresInSec) ||\n expiresInSec <= 0 ||\n expiresInSec > SPACE_CREDENTIAL_MAX_AGE_SEC) {\n throw new SpaceTokenError('invalid space credential lifetime');\n }\n const token = buildSpaceToken({ typ: spec.typ, kid: spec.kid }, { iss: opts.iss, sub: opts.sub, cnf: { kid: opts.keyId } }, expiresInSec);\n return signSpaceToken(token, opts.keypair);\n}\n/**\n * An OAuth client's proof of identity to a space host, signed with a key from the\n * client's JWKS (named by `kid`).\n */\nexport async function createClientAttestation(opts) {\n return signSpaceToken(buildClientAttestation(opts), opts.keypair);\n}\n/**\n * Builds a client attestation for any JWT signer, e.g. an `@atproto/jwk`\n * `Keyset`, which picks the key and sets `alg` itself.\n * {@link createClientAttestation} signs with a `Signer`.\n *\n * @example\n * ```ts\n * const { header, payload } = buildClientAttestation({\n * clientId,\n * aud: spaceHostAud(spaceDid),\n * })\n * const jwt = await keyset.createJwt(header, payload)\n * ```\n */\nexport function buildClientAttestation(opts) {\n const spec = SPACE_TOKEN_TYPES.clientAttestation;\n return buildSpaceToken({ typ: spec.typ, kid: opts.kid }, { iss: opts.clientId, sub: opts.clientId, aud: opts.aud }, opts.expiresInSec ?? spec.expiresInSec);\n}\nfunction buildSpaceToken(header, claims, expiresInSec) {\n const iat = Math.floor(Date.now() / 1000);\n return {\n header: {\n typ: header.typ,\n ...(header.kid ? { kid: header.kid } : undefined),\n },\n payload: {\n ...claims,\n iat,\n exp: iat + expiresInSec,\n jti: randomStr(16, 'hex'),\n },\n };\n}\nasync function signSpaceToken(token, signer) {\n const header = { alg: signer.jwtAlg, ...token.header };\n const signingInput = `${jsonToB64Url(header)}.${jsonToB64Url(token.payload)}`;\n const sig = await signer.sign(utf8(signingInput));\n return `${signingInput}.${toBase64(sig, 'base64url')}`;\n}\n// Structural validation only, no signature check. This is as far as we go for\n// client attestations, whose key comes from the client's JWKS, not a DID doc.\nexport function parseSpaceToken(type, jwt) {\n const spec = SPACE_TOKEN_TYPES[type];\n const parts = jwt.split('.');\n if (parts.length !== 3) {\n throw new SpaceTokenError('malformed token: expected 3 parts', 'BadJwt');\n }\n const [headerB64, payloadB64, sigB64] = parts;\n const header = decodeJsonPart(headerB64, 'header');\n const payload = decodeJsonPart(payloadB64, 'payload');\n if (header.typ !== spec.typ) {\n throw new SpaceTokenError(`wrong token type: expected \"${spec.typ}\", got \"${header.typ}\"`, 'BadJwtType');\n }\n if (typeof header.alg !== 'string' || !header.alg) {\n throw new SpaceTokenError('missing token \"alg\"', 'BadJwt');\n }\n if (spec.kid && header.kid !== spec.kid) {\n throw new SpaceTokenError(`wrong token \"kid\": expected \"${spec.kid}\", got \"${header.kid}\"`, 'BadJwt');\n }\n if (!payload.iss) {\n throw new SpaceTokenError('missing token \"iss\"', 'BadJwtIss');\n }\n if (!payload.sub) {\n throw new SpaceTokenError('missing token \"sub\"', 'BadJwtSub');\n }\n if (!Number.isFinite(payload.exp)) {\n throw new SpaceTokenError('missing token \"exp\"', 'BadJwt');\n }\n if (spec.requireAud && !payload.aud) {\n throw new SpaceTokenError('missing token \"aud\"', 'BadJwtAudience');\n }\n if (spec.requireCnf && !isValidDid(payload.cnf?.kid)) {\n throw new SpaceTokenError('missing token \"cnf.kid\"', 'BadJwtCnf');\n }\n if (typeof payload.jti !== 'string' || !payload.jti) {\n throw new SpaceTokenError(`a ${type} token requires a \"jti\"`, 'BadJwt');\n }\n if (type === 'credential' &&\n (!Number.isFinite(payload.iat) ||\n payload.exp <= payload.iat ||\n payload.exp - payload.iat > SPACE_CREDENTIAL_MAX_AGE_SEC)) {\n throw new SpaceTokenError('invalid space credential lifetime', 'BadJwt');\n }\n if (type === 'clientAttestation' && payload.iss !== payload.sub) {\n throw new SpaceTokenError('client attestation \"iss\" and \"sub\" must both be the client_id', 'BadJwtIss');\n }\n return {\n header,\n payload,\n signingInput: utf8(`${headerB64}.${payloadB64}`),\n sig: fromBase64(sigB64, 'base64url'),\n };\n}\nexport async function verifySpaceToken(type, jwt, opts) {\n const { header, payload, signingInput, sig } = parseSpaceToken(type, jwt);\n const now = Math.floor(Date.now() / 1000);\n if (type === 'credential' && payload.iat > now + CLOCK_SKEW_SEC) {\n throw new SpaceTokenError('space credential issued in the future', 'BadJwt');\n }\n if (now - CLOCK_SKEW_SEC >= payload.exp) {\n throw new SpaceTokenError('token expired', 'JwtExpired');\n }\n if (opts.aud !== undefined && payload.aud !== opts.aud) {\n throw new SpaceTokenError('token audience does not match this service', 'BadJwtAudience');\n }\n if (opts.sub !== undefined && payload.sub !== opts.sub) {\n throw new SpaceTokenError('token subject does not match the requested space', 'BadJwtSub');\n }\n const didKey = await opts.getSigningKey(payload.iss, false);\n if (await matchesSignature(didKey, header, signingInput, sig)) {\n return { header, payload };\n }\n // The signing key may have rotated since the one we hold was cached.\n const freshDidKey = await opts.getSigningKey(payload.iss, true);\n if (freshDidKey !== didKey &&\n (await matchesSignature(freshDidKey, header, signingInput, sig))) {\n return { header, payload };\n }\n throw new SpaceTokenError('invalid token signature', 'BadJwtSignature');\n}\nasync function matchesSignature(didKey, header, signingInput, sig) {\n try {\n return await verifySignature(didKey, signingInput, sig, {\n jwtAlg: header.alg,\n });\n }\n catch (err) {\n throw new SpaceTokenError(`could not verify token signature: ${errMsg(err)}`, 'BadJwtSignature');\n }\n}\nfunction jsonToB64Url(json) {\n return toBase64(utf8(JSON.stringify(json)), 'base64url');\n}\nfunction decodeJsonPart(b64, part) {\n try {\n return JSON.parse(new TextDecoder().decode(fromBase64(b64, 'base64url')));\n }\n catch (err) {\n throw new SpaceTokenError(`could not parse token ${part}: ${errMsg(err)}`, 'BadJwt');\n }\n}\nfunction errMsg(err) {\n return err instanceof Error ? err.message : String(err);\n}\n//# sourceMappingURL=credential.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ByteSequence = void 0;\nclass ByteSequence {\n constructor(base64Value) {\n this.base64Value = base64Value;\n }\n toBase64() {\n return this.base64Value;\n }\n}\nexports.ByteSequence = ByteSequence;\n//# sourceMappingURL=types.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isByteSequence = exports.isInnerList = exports.isValidKeyStr = exports.isValidTokenStr = exports.isAscii = void 0;\nconst asciiRe = /^[\\x20-\\x7E]*$/;\nconst tokenRe = /^[a-zA-Z*][:/!#$%&'*+\\-.^_`|~A-Za-z0-9]*$/;\nconst keyRe = /^[a-z*][*\\-_.a-z0-9]*$/;\nfunction isAscii(str) {\n return asciiRe.test(str);\n}\nexports.isAscii = isAscii;\nfunction isValidTokenStr(str) {\n return tokenRe.test(str);\n}\nexports.isValidTokenStr = isValidTokenStr;\nfunction isValidKeyStr(str) {\n return keyRe.test(str);\n}\nexports.isValidKeyStr = isValidKeyStr;\nfunction isInnerList(input) {\n return Array.isArray(input[0]);\n}\nexports.isInnerList = isInnerList;\nfunction isByteSequence(input) {\n return typeof input === 'object' && 'base64Value' in input;\n}\nexports.isByteSequence = isByteSequence;\n//# sourceMappingURL=util.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Token = void 0;\nconst util_1 = require(\"./util\");\nclass Token {\n constructor(value) {\n if (!(0, util_1.isValidTokenStr)(value)) {\n throw new TypeError('Invalid character in Token string. Tokens must start with *, A-Z and the rest of the string may only contain a-z, A-Z, 0-9, :/!#$%&\\'*+-.^_`|~');\n }\n this.value = value;\n }\n toString() {\n return this.value;\n }\n}\nexports.Token = Token;\n//# sourceMappingURL=token.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.serializeKey = exports.serializeParameters = exports.serializeToken = exports.serializeByteSequence = exports.serializeBoolean = exports.serializeString = exports.serializeDecimal = exports.serializeInteger = exports.serializeBareItem = exports.serializeInnerList = exports.serializeItem = exports.serializeDictionary = exports.serializeList = exports.SerializeError = void 0;\nconst types_1 = require(\"./types\");\nconst token_1 = require(\"./token\");\nconst util_1 = require(\"./util\");\nclass SerializeError extends Error {\n}\nexports.SerializeError = SerializeError;\nfunction serializeList(input) {\n return input.map(value => {\n if ((0, util_1.isInnerList)(value)) {\n return serializeInnerList(value);\n }\n else {\n return serializeItem(value);\n }\n }).join(', ');\n}\nexports.serializeList = serializeList;\nfunction serializeDictionary(input) {\n return Array.from(input.entries()).map(([key, value]) => {\n let out = serializeKey(key);\n if (value[0] === true) {\n out += serializeParameters(value[1]);\n }\n else {\n out += '=';\n if ((0, util_1.isInnerList)(value)) {\n out += serializeInnerList(value);\n }\n else {\n out += serializeItem(value);\n }\n }\n return out;\n }).join(', ');\n}\nexports.serializeDictionary = serializeDictionary;\nfunction serializeItem(input) {\n return serializeBareItem(input[0]) + serializeParameters(input[1]);\n}\nexports.serializeItem = serializeItem;\nfunction serializeInnerList(input) {\n return `(${input[0].map(value => serializeItem(value)).join(' ')})${serializeParameters(input[1])}`;\n}\nexports.serializeInnerList = serializeInnerList;\nfunction serializeBareItem(input) {\n if (typeof input === 'number') {\n if (Number.isInteger(input)) {\n return serializeInteger(input);\n }\n return serializeDecimal(input);\n }\n if (typeof input === 'string') {\n return serializeString(input);\n }\n if (input instanceof token_1.Token) {\n return serializeToken(input);\n }\n if (input instanceof types_1.ByteSequence) {\n return serializeByteSequence(input);\n }\n if (typeof input === 'boolean') {\n return serializeBoolean(input);\n }\n throw new SerializeError(`Cannot serialize values of type ${typeof input}`);\n}\nexports.serializeBareItem = serializeBareItem;\nfunction serializeInteger(input) {\n if (input < -999999999999999 || input > 999999999999999) {\n throw new SerializeError('Structured headers can only encode integers in the range range of -999,999,999,999,999 to 999,999,999,999,999 inclusive');\n }\n return input.toString();\n}\nexports.serializeInteger = serializeInteger;\nfunction serializeDecimal(input) {\n const out = input.toFixed(3).replace(/0+$/, '');\n const signifantDigits = out.split('.')[0].replace('-', '').length;\n if (signifantDigits > 12) {\n throw new SerializeError('Fractional numbers are not allowed to have more than 12 significant digits before the decimal point');\n }\n return out;\n}\nexports.serializeDecimal = serializeDecimal;\nfunction serializeString(input) {\n if (!(0, util_1.isAscii)(input)) {\n throw new SerializeError('Only ASCII strings may be serialized');\n }\n return `\"${input.replace(/(\"|\\\\)/g, (v) => '\\\\' + v)}\"`;\n}\nexports.serializeString = serializeString;\nfunction serializeBoolean(input) {\n return input ? '?1' : '?0';\n}\nexports.serializeBoolean = serializeBoolean;\nfunction serializeByteSequence(input) {\n return `:${input.toBase64()}:`;\n}\nexports.serializeByteSequence = serializeByteSequence;\nfunction serializeToken(input) {\n return input.toString();\n}\nexports.serializeToken = serializeToken;\nfunction serializeParameters(input) {\n return Array.from(input).map(([key, value]) => {\n let out = ';' + serializeKey(key);\n if (value !== true) {\n out += '=' + serializeBareItem(value);\n }\n return out;\n }).join('');\n}\nexports.serializeParameters = serializeParameters;\nfunction serializeKey(input) {\n if (!(0, util_1.isValidKeyStr)(input)) {\n throw new SerializeError('Keys in dictionaries must only contain lowercase letter, numbers, _-*. and must start with a letter or *');\n }\n return input;\n}\nexports.serializeKey = serializeKey;\n//# sourceMappingURL=serializer.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ParseError = exports.parseItem = exports.parseList = exports.parseDictionary = void 0;\nconst types_1 = require(\"./types\");\nconst token_1 = require(\"./token\");\nconst util_1 = require(\"./util\");\nfunction parseDictionary(input) {\n const parser = new Parser(input);\n return parser.parseDictionary();\n}\nexports.parseDictionary = parseDictionary;\nfunction parseList(input) {\n const parser = new Parser(input);\n return parser.parseList();\n}\nexports.parseList = parseList;\nfunction parseItem(input) {\n const parser = new Parser(input);\n return parser.parseItem();\n}\nexports.parseItem = parseItem;\nclass ParseError extends Error {\n constructor(position, message) {\n super(`Parse error: ${message} at offset ${position}`);\n }\n}\nexports.ParseError = ParseError;\nclass Parser {\n constructor(input) {\n this.input = input;\n this.pos = 0;\n }\n parseDictionary() {\n this.skipWS();\n const dictionary = new Map();\n while (!this.eof()) {\n const thisKey = this.parseKey();\n let member;\n if (this.lookChar() === '=') {\n this.pos++;\n member = this.parseItemOrInnerList();\n }\n else {\n member = [true, this.parseParameters()];\n }\n dictionary.set(thisKey, member);\n this.skipOWS();\n if (this.eof()) {\n return dictionary;\n }\n this.expectChar(',');\n this.pos++;\n this.skipOWS();\n if (this.eof()) {\n throw new ParseError(this.pos, 'Dictionary contained a trailing comma');\n }\n }\n return dictionary;\n }\n parseList() {\n this.skipWS();\n const members = [];\n while (!this.eof()) {\n members.push(this.parseItemOrInnerList());\n this.skipOWS();\n if (this.eof()) {\n return members;\n }\n this.expectChar(',');\n this.pos++;\n this.skipOWS();\n if (this.eof()) {\n throw new ParseError(this.pos, 'A list may not end with a trailing comma');\n }\n }\n return members;\n }\n parseItem(standaloneItem = true) {\n if (standaloneItem)\n this.skipWS();\n const result = [\n this.parseBareItem(),\n this.parseParameters()\n ];\n if (standaloneItem)\n this.checkTrail();\n return result;\n }\n parseItemOrInnerList() {\n if (this.lookChar() === '(') {\n return this.parseInnerList();\n }\n else {\n return this.parseItem(false);\n }\n }\n parseInnerList() {\n this.expectChar('(');\n this.pos++;\n const innerList = [];\n while (!this.eof()) {\n this.skipWS();\n if (this.lookChar() === ')') {\n this.pos++;\n return [\n innerList,\n this.parseParameters()\n ];\n }\n innerList.push(this.parseItem(false));\n const nextChar = this.lookChar();\n if (nextChar !== ' ' && nextChar !== ')') {\n throw new ParseError(this.pos, 'Expected a whitespace or ) after every item in an inner list');\n }\n }\n throw new ParseError(this.pos, 'Could not find end of inner list');\n }\n parseBareItem() {\n const char = this.lookChar();\n if (char === undefined) {\n throw new ParseError(this.pos, 'Unexpected end of string');\n }\n if (char.match(/^[-0-9]/)) {\n return this.parseIntegerOrDecimal();\n }\n if (char === '\"') {\n return this.parseString();\n }\n if (char.match(/^[A-Za-z*]/)) {\n return this.parseToken();\n }\n if (char === ':') {\n return this.parseByteSequence();\n }\n if (char === '?') {\n return this.parseBoolean();\n }\n throw new ParseError(this.pos, 'Unexpected input');\n }\n parseParameters() {\n const parameters = new Map();\n while (!this.eof()) {\n const char = this.lookChar();\n if (char !== ';') {\n break;\n }\n this.pos++;\n this.skipWS();\n const key = this.parseKey();\n let value = true;\n if (this.lookChar() === '=') {\n this.pos++;\n value = this.parseBareItem();\n }\n parameters.set(key, value);\n }\n return parameters;\n }\n parseIntegerOrDecimal() {\n let type = 'integer';\n let sign = 1;\n let inputNumber = '';\n if (this.lookChar() === '-') {\n sign = -1;\n this.pos++;\n }\n // The spec wants this check but it's unreachable code.\n //if (this.eof()) {\n // throw new ParseError(this.pos, 'Empty integer');\n //}\n if (!isDigit(this.lookChar())) {\n throw new ParseError(this.pos, 'Expected a digit (0-9)');\n }\n while (!this.eof()) {\n const char = this.getChar();\n if (isDigit(char)) {\n inputNumber += char;\n }\n else if (type === 'integer' && char === '.') {\n if (inputNumber.length > 12) {\n throw new ParseError(this.pos, 'Exceeded maximum decimal length');\n }\n inputNumber += '.';\n type = 'decimal';\n }\n else {\n // We need to 'prepend' the character, so it's just a rewind\n this.pos--;\n break;\n }\n if (type === 'integer' && inputNumber.length > 15) {\n throw new ParseError(this.pos, 'Exceeded maximum integer length');\n }\n if (type === 'decimal' && inputNumber.length > 16) {\n throw new ParseError(this.pos, 'Exceeded maximum decimal length');\n }\n }\n if (type === 'integer') {\n return parseInt(inputNumber, 10) * sign;\n }\n else {\n if (inputNumber.endsWith('.')) {\n throw new ParseError(this.pos, 'Decimal cannot end on a period');\n }\n if (inputNumber.split('.')[1].length > 3) {\n throw new ParseError(this.pos, 'Number of digits after the decimal point cannot exceed 3');\n }\n return parseFloat(inputNumber) * sign;\n }\n }\n parseString() {\n let outputString = '';\n this.expectChar('\"');\n this.pos++;\n while (!this.eof()) {\n const char = this.getChar();\n if (char === '\\\\') {\n if (this.eof()) {\n throw new ParseError(this.pos, 'Unexpected end of input');\n }\n const nextChar = this.getChar();\n if (nextChar !== '\\\\' && nextChar !== '\"') {\n throw new ParseError(this.pos, 'A backslash must be followed by another backslash or double quote');\n }\n outputString += nextChar;\n }\n else if (char === '\"') {\n return outputString;\n }\n else if (!(0, util_1.isAscii)(char)) {\n throw new ParseError(this.pos, 'Strings must be in the ASCII range');\n }\n else {\n outputString += char;\n }\n }\n throw new ParseError(this.pos, 'Unexpected end of input');\n }\n parseToken() {\n // The specification wants this check, but it's an unreachable code block.\n // if (!/^[A-Za-z*]/.test(this.lookChar())) {\n // throw new ParseError(this.pos, 'A token must begin with an asterisk or letter (A-Z, a-z)');\n //}\n let outputString = '';\n while (!this.eof()) {\n const char = this.lookChar();\n if (char === undefined || !/^[:/!#$%&'*+\\-.^_`|~A-Za-z0-9]$/.test(char)) {\n return new token_1.Token(outputString);\n }\n outputString += this.getChar();\n }\n return new token_1.Token(outputString);\n }\n parseByteSequence() {\n this.expectChar(':');\n this.pos++;\n const endPos = this.input.indexOf(':', this.pos);\n if (endPos === -1) {\n throw new ParseError(this.pos, 'Could not find a closing \":\" character to mark end of Byte Sequence');\n }\n const b64Content = this.input.substring(this.pos, endPos);\n this.pos += b64Content.length + 1;\n if (!/^[A-Za-z0-9+/=]*$/.test(b64Content)) {\n throw new ParseError(this.pos, 'ByteSequence does not contain a valid base64 string');\n }\n return new types_1.ByteSequence(b64Content);\n }\n parseBoolean() {\n this.expectChar('?');\n this.pos++;\n const char = this.getChar();\n if (char === '1') {\n return true;\n }\n if (char === '0') {\n return false;\n }\n throw new ParseError(this.pos, 'Unexpected character. Expected a \"1\" or a \"0\"');\n }\n parseKey() {\n var _a;\n if (!((_a = this.lookChar()) === null || _a === void 0 ? void 0 : _a.match(/^[a-z*]/))) {\n throw new ParseError(this.pos, 'A key must begin with an asterisk or letter (a-z)');\n }\n let outputString = '';\n while (!this.eof()) {\n const char = this.lookChar();\n if (char === undefined || !/^[a-z0-9_\\-.*]$/.test(char)) {\n return outputString;\n }\n outputString += this.getChar();\n }\n return outputString;\n }\n /**\n * Looks at the next character without advancing the cursor.\n *\n * Returns undefined if we were at the end of the string.\n */\n lookChar() {\n return this.input[this.pos];\n }\n /**\n * Checks if the next character is 'char', and fail otherwise.\n */\n expectChar(char) {\n if (this.lookChar() !== char) {\n throw new ParseError(this.pos, `Expected ${char}`);\n }\n }\n getChar() {\n return this.input[this.pos++];\n }\n eof() {\n return this.pos >= this.input.length;\n }\n // Advances the pointer to skip all whitespace.\n skipOWS() {\n while (true) {\n const c = this.input.substr(this.pos, 1);\n if (c === ' ' || c === '\\t') {\n this.pos++;\n }\n else {\n break;\n }\n }\n }\n // Advances the pointer to skip all spaces\n skipWS() {\n while (this.lookChar() === ' ') {\n this.pos++;\n }\n }\n // At the end of parsing, we need to make sure there are no bytes after the\n // header except whitespace.\n checkTrail() {\n this.skipWS();\n if (!this.eof()) {\n throw new ParseError(this.pos, 'Unexpected characters at end of input');\n }\n }\n}\nexports.default = Parser;\nconst isDigitRegex = /^[0-9]$/;\nfunction isDigit(char) {\n if (char === undefined)\n return false;\n return isDigitRegex.test(char);\n}\n//# sourceMappingURL=parser.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Token = void 0;\n__exportStar(require(\"./serializer\"), exports);\n__exportStar(require(\"./parser\"), exports);\n__exportStar(require(\"./types\"), exports);\n__exportStar(require(\"./util\"), exports);\nvar token_1 = require(\"./token\");\nObject.defineProperty(exports, \"Token\", { enumerable: true, get: function () { return token_1.Token; } });\n//# sourceMappingURL=index.js.map","import { isByteSequence, isInnerList, parseDictionary, serializeInnerList, serializeItem, } from 'structured-headers';\nimport { parseDidKey, verifySignature } from '@atproto/crypto';\nimport { fromBase64 } from '@atproto/lex-data';\nimport { toPaddedBase64, utf8 } from './bytes.js';\nimport { SpaceSignatureError } from './error.js';\nconst SIGNATURE_LABEL = 'sig';\nconst SIGNATURE_ALG = 'ecdsa-p256-sha256';\nconst SIGNATURE_TAG = 'atproto-space-credential';\n// A credential use covers the credential and its audience DID, in that order.\nconst CREDENTIAL_COMPONENTS = [\n ['authorization', new Map()],\n ['atproto-space-audience', new Map()],\n];\n/** Sign a request authorized by a space credential, covering the credential and its audience DID. */\nexport async function createSpaceSig({ authorization, audience, keypair, }) {\n assertP256DidKey(keypair.did());\n const signatureInput = serializeInnerList([\n CREDENTIAL_COMPONENTS,\n new Map([['tag', SIGNATURE_TAG]]),\n ]);\n const base = signatureBase(CREDENTIAL_COMPONENTS, [authorization, audience], signatureInput);\n return { signatureInput, signature: await keypair.sign(base) };\n}\n/** Create the authorization, audience, and signature headers for a space request. */\nexport async function createSpaceSigHeaders(opts) {\n const { signatureInput, signature } = await createSpaceSig(opts);\n return {\n headers: {\n authorization: opts.authorization,\n 'atproto-space-audience': opts.audience,\n 'signature-input': `${SIGNATURE_LABEL}=${signatureInput}`,\n signature: `${SIGNATURE_LABEL}=:${toPaddedBase64(signature)}:`,\n },\n };\n}\n/**\n * Verify the signature on a request authorized by a space credential, against\n * the key the credential is bound to (its `cnf.kid`).\n */\nexport async function verifyCredentialSig(headers, keyId) {\n const values = credentialValues(headers);\n const { signatureParams, signature } = findSignature(headers['signature-input'], headers['signature'], {\n tag: SIGNATURE_TAG,\n components: CREDENTIAL_COMPONENTS,\n alg: SIGNATURE_ALG,\n keyId,\n }, SpaceSignatureError);\n assertP256DidKey(keyId);\n const base = signatureBase(CREDENTIAL_COMPONENTS, values, signatureParams);\n const valid = signature.length === 64 &&\n (await verifySignature(keyId, base, signature, {\n format: 'compact',\n allowMalleableSig: true,\n }).catch(() => false));\n if (!valid) {\n throw new SpaceSignatureError('invalid HTTP message signature');\n }\n}\n/** Whether `keyId` is a P-256 did:key, the only kind a space credential can be bound to. */\nexport function isP256DidKey(keyId) {\n try {\n return parseDidKey(keyId).jwtAlg === 'ES256';\n }\n catch {\n return false;\n }\n}\nfunction assertP256DidKey(keyId) {\n if (!isP256DidKey(keyId)) {\n throw new SpaceSignatureError('signature key must be a P-256 did:key');\n }\n}\n/** The values a credential use covers, both required. */\nfunction credentialValues(headers) {\n const authorization = headers['authorization'];\n if (typeof authorization !== 'string' || !authorization) {\n throw new SpaceSignatureError('missing or malformed \"authorization\" field');\n }\n const audience = headers['atproto-space-audience'];\n if (typeof audience !== 'string' || !audience) {\n throw new SpaceSignatureError('missing or malformed \"atproto-space-audience\" field');\n }\n return [authorization, audience];\n}\n/**\n * Find the one signature tagged `tag` in a message's `Signature-Input` and\n * `Signature` fields, and check it meets the application's requirements. Labels\n * carry no meaning (RFC 9421 ยง7.2.5), so the tag is what identifies it. Other\n * parameters, like `created`, are covered by the signature but not interpreted.\n * Returns the signature with its serialized parameters.\n */\nexport function findSignature(inputField, signatureField, required, SignatureError) {\n if (typeof inputField !== 'string' || typeof signatureField !== 'string') {\n throw new SignatureError('missing or malformed signature headers');\n }\n let inputs, signatures;\n try {\n inputs = parseDictionary(inputField);\n signatures = parseDictionary(signatureField);\n }\n catch (cause) {\n throw new SignatureError('missing or malformed signature headers', {\n cause,\n });\n }\n const { tag } = required;\n const tagged = membersWithTag(inputs, tag);\n if (tagged.length > 1) {\n throw new SignatureError(`more than one signature with tag \"${tag}\"`);\n }\n const signature = tagged[0] && getSignature(signatures, tagged[0].label);\n if (!signature) {\n throw new SignatureError(`missing or malformed signature with tag \"${tag}\"`);\n }\n const { params } = tagged[0];\n const [components, parameters] = params;\n const expected = formatComponents(required.components);\n if (formatComponents(components) !== expected) {\n throw new SignatureError(`signature must cover exactly ${expected}, in order`);\n }\n if (parameters.has('alg') && parameters.get('alg') !== required.alg) {\n throw new SignatureError(`signature algorithm must be ${required.alg}`);\n }\n if (parameters.has('keyid') && parameters.get('keyid') !== required.keyId) {\n throw new SignatureError('signature keyid does not match the expected key');\n }\n return { signatureParams: serializeInnerList(params), signature };\n}\n/** The members of a `Signature-Input` or `Accept-Signature` field tagged `tag`. */\nexport function membersWithTag(members, tag) {\n const tagged = [];\n for (const [label, member] of members) {\n if (isInnerList(member) && member[1].get('tag') === tag) {\n tagged.push({ label, params: member });\n }\n }\n return tagged;\n}\n// The signature bytes under `label` in a `Signature` field, if well formed.\nfunction getSignature(signatures, label) {\n const member = signatures.get(label);\n if (!member ||\n isInnerList(member) ||\n !isByteSequence(member[0]) ||\n member[1].size !== 0) {\n return undefined;\n }\n return fromBase64(member[0].toBase64());\n}\n/** A covered component list without its parameters, e.g. `(\"authorization\" \"atproto-space-audience\")`. */\nexport function formatComponents(components) {\n return serializeInnerList([components, new Map()]);\n}\n/**\n * The signature base (RFC 9421 ยง2.5) for a signature covering `components`,\n * whose values are given in order, under the serialized `signatureParams`.\n */\nexport function signatureBase(components, values, signatureParams) {\n const lines = components.map((component, i) => `${serializeItem(component)}: ${values[i].trim()}`);\n lines.push(`\"@signature-params\": ${signatureParams}`);\n return utf8(lines.join('\\n'));\n}\n//# sourceMappingURL=http-signature.js.map","import { P256Keypair, P256_JWT_ALG, hkdfExpandSha256, hkdfExtractSha256, parseDidKey, } from '@atproto/crypto';\nimport { ui8Concat } from '@atproto/lex-data';\nimport { uint16be, utf8 } from './bytes.js';\nimport { SpaceKemError } from './error.js';\n/**\n * Syncer side: generate a fresh ephemeral keypair and derive a shared secret\n * against the author's `#atproto_kem` key. Use a new one for every request.\n */\nexport async function encapsulate(authorKemKey) {\n const authorKeyBytes = p256KeyBytes(authorKemKey);\n const ephemeral = await P256Keypair.create();\n const dh = ephemeral.ecdh(authorKeyBytes);\n const keyShare = ephemeral.did();\n const sharedSecret = deriveSharedSecret(dh, p256KeyBytes(keyShare), authorKeyBytes);\n return { keyShare, sharedSecret };\n}\n/**\n * Repo host side: derive the same shared secret from the syncer's `keyShare`\n * using the author's KEM keypair.\n */\nexport function decapsulate(authorKemKeypair, keyShare) {\n const enc = p256KeyBytes(keyShare);\n const dh = authorKemKeypair.ecdh(enc);\n return deriveSharedSecret(dh, enc, p256KeyBytes(authorKemKeypair.did()));\n}\n// A fixed label tying the secret to this protocol.\nconst HPKE_INFO = utf8('atproto-mac');\n// HPKE labels every HKDF input with a version and the IDs of the algorithms in\n// use: 0x0010 is DHKEM(P-256, HKDF-SHA256), 0x0001 is HKDF-SHA256, and 0xffff\n// is the Export-only AEAD.\nconst HPKE_VERSION = utf8('HPKE-v1');\nconst KEM_ID = ui8Concat([utf8('KEM'), uint16be(0x0010)]);\nconst SUITE_ID = ui8Concat([\n utf8('HPKE'),\n uint16be(0x0010),\n uint16be(0x0001),\n uint16be(0xffff),\n]);\nconst MODE_BASE = new Uint8Array([0x00]);\nconst EMPTY = new Uint8Array(0);\n// HPKE's SetupBaseS (or SetupBaseR) followed by an export with an empty\n// exporter context, given the ECDH result `dh`.\nfunction deriveSharedSecret(dh, enc, authorKeyBytes) {\n // The KEM's secret, from the ECDH result and both public keys.\n const eaePrk = labeledExtract(KEM_ID, EMPTY, 'eae_prk', dh);\n const kemSecret = labeledExpand(KEM_ID, eaePrk, 'shared_secret', ui8Concat([enc, authorKeyBytes]), 32);\n // The key schedule, in base mode with no pre-shared key.\n const pskIdHash = labeledExtract(SUITE_ID, EMPTY, 'psk_id_hash', EMPTY);\n const infoHash = labeledExtract(SUITE_ID, EMPTY, 'info_hash', HPKE_INFO);\n const context = ui8Concat([MODE_BASE, pskIdHash, infoHash]);\n const secret = labeledExtract(SUITE_ID, kemSecret, 'secret', EMPTY);\n const exporterSecret = labeledExpand(SUITE_ID, secret, 'exp', context, 32);\n return labeledExpand(SUITE_ID, exporterSecret, 'sec', EMPTY, 32);\n}\nfunction labeledExtract(id, salt, label, ikm) {\n return hkdfExtractSha256(salt, ui8Concat([HPKE_VERSION, id, utf8(label), ikm]));\n}\nfunction labeledExpand(id, prk, label, info, length) {\n return hkdfExpandSha256(prk, ui8Concat([uint16be(length), HPKE_VERSION, id, utf8(label), info]), length);\n}\n// The uncompressed public key (0x04 || x || y) for a P-256 did:key. HPKE encodes\n// keys uncompressed, even though did:key uses the compressed form.\nfunction p256KeyBytes(didKey) {\n let parsed;\n try {\n parsed = parseDidKey(didKey);\n }\n catch (cause) {\n throw new SpaceKemError('invalid KEM key', { cause });\n }\n if (parsed.jwtAlg !== P256_JWT_ALG) {\n throw new SpaceKemError('KEM key must be a P-256 did:key');\n }\n return parsed.keyBytes;\n}\n//# sourceMappingURL=kem.js.map","/**\n * Internal helpers for blake hash.\n * @module\n */\nimport { rotr } from \"./utils.js\";\n/**\n * Internal blake variable.\n * For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].\n */\n// prettier-ignore\nexport const BSIGMA = /* @__PURE__ */ Uint8Array.from([\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,\n 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,\n 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,\n 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,\n // Blake1, unused in others\n 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,\n 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,\n 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,\n 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,\n]);\n// Mixing function G splitted in two halfs\nexport function G1s(a, b, c, d, x) {\n a = (a + b + x) | 0;\n d = rotr(d ^ a, 16);\n c = (c + d) | 0;\n b = rotr(b ^ c, 12);\n return { a, b, c, d };\n}\nexport function G2s(a, b, c, d, x) {\n a = (a + b + x) | 0;\n d = rotr(d ^ a, 8);\n c = (c + d) | 0;\n b = rotr(b ^ c, 7);\n return { a, b, c, d };\n}\n//# sourceMappingURL=_blake.js.map","/**\n * blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.\n * b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.\n * @module\n */\nimport { BSIGMA, G1s, G2s } from \"./_blake.js\";\nimport { SHA256_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createOptHasher, Hash, swap32IfBE, swap8IfBE, toBytes, u32 } from \"./utils.js\";\n// Same as SHA512_IV, but swapped endianness: LE instead of BE. iv[1] is iv[0], etc.\nconst B2B_IV = /* @__PURE__ */ Uint32Array.from([\n 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,\n 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,\n]);\n// Temporary buffer\nconst BBUF = /* @__PURE__ */ new Uint32Array(32);\n// Mixing function G splitted in two halfs\nfunction G1b(a, b, c, d, msg, x) {\n // NOTE: V is LE here\n const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore\n let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore\n let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore\n let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore\n let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore\n // v[a] = (v[a] + v[b] + x) | 0;\n let ll = u64.add3L(Al, Bl, Xl);\n Ah = u64.add3H(ll, Ah, Bh, Xh);\n Al = ll | 0;\n // v[d] = rotr(v[d] ^ v[a], 32)\n ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });\n ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) });\n // v[c] = (v[c] + v[d]) | 0;\n ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));\n // v[b] = rotr(v[b] ^ v[c], 24)\n ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });\n ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) });\n (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);\n (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);\n (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);\n (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);\n}\nfunction G2b(a, b, c, d, msg, x) {\n // NOTE: V is LE here\n const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore\n let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore\n let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore\n let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore\n let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore\n // v[a] = (v[a] + v[b] + x) | 0;\n let ll = u64.add3L(Al, Bl, Xl);\n Ah = u64.add3H(ll, Ah, Bh, Xh);\n Al = ll | 0;\n // v[d] = rotr(v[d] ^ v[a], 16)\n ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });\n ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) });\n // v[c] = (v[c] + v[d]) | 0;\n ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));\n // v[b] = rotr(v[b] ^ v[c], 63)\n ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });\n ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) });\n (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);\n (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);\n (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);\n (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);\n}\nfunction checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {\n anumber(keyLen);\n if (outputLen < 0 || outputLen > keyLen)\n throw new Error('outputLen bigger than keyLen');\n const { key, salt, personalization } = opts;\n if (key !== undefined && (key.length < 1 || key.length > keyLen))\n throw new Error('key length must be undefined or 1..' + keyLen);\n if (salt !== undefined && salt.length !== saltLen)\n throw new Error('salt must be undefined or ' + saltLen);\n if (personalization !== undefined && personalization.length !== persLen)\n throw new Error('personalization must be undefined or ' + persLen);\n}\n/** Class, from which others are subclassed. */\nexport class BLAKE2 extends Hash {\n constructor(blockLen, outputLen) {\n super();\n this.finished = false;\n this.destroyed = false;\n this.length = 0;\n this.pos = 0;\n anumber(blockLen);\n anumber(outputLen);\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.buffer = new Uint8Array(blockLen);\n this.buffer32 = u32(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n // Main difference with other hashes: there is flag for last block,\n // so we cannot process current block before we know that there\n // is the next one. This significantly complicates logic and reduces ability\n // to do zero-copy processing\n const { blockLen, buffer, buffer32 } = this;\n const len = data.length;\n const offset = data.byteOffset;\n const buf = data.buffer;\n for (let pos = 0; pos < len;) {\n // If buffer is full and we still have input (don't process last block, same as blake2s)\n if (this.pos === blockLen) {\n swap32IfBE(buffer32);\n this.compress(buffer32, 0, false);\n swap32IfBE(buffer32);\n this.pos = 0;\n }\n const take = Math.min(blockLen - this.pos, len - pos);\n const dataOffset = offset + pos;\n // full block && aligned to 4 bytes && not last in input\n if (take === blockLen && !(dataOffset % 4) && pos + take < len) {\n const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));\n swap32IfBE(data32);\n for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {\n this.length += blockLen;\n this.compress(data32, pos32, false);\n }\n swap32IfBE(data32);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n this.length += take;\n pos += take;\n }\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n const { pos, buffer32 } = this;\n this.finished = true;\n // Padding\n clean(this.buffer.subarray(pos));\n swap32IfBE(buffer32);\n this.compress(buffer32, 0, true);\n swap32IfBE(buffer32);\n const out32 = u32(out);\n this.get().forEach((v, i) => (out32[i] = swap8IfBE(v)));\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n const { buffer, length, finished, destroyed, outputLen, pos } = this;\n to || (to = new this.constructor({ dkLen: outputLen }));\n to.set(...this.get());\n to.buffer.set(buffer);\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // @ts-ignore\n to.outputLen = outputLen;\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\nexport class BLAKE2b extends BLAKE2 {\n constructor(opts = {}) {\n const olen = opts.dkLen === undefined ? 64 : opts.dkLen;\n super(128, olen);\n // Same as SHA-512, but LE\n this.v0l = B2B_IV[0] | 0;\n this.v0h = B2B_IV[1] | 0;\n this.v1l = B2B_IV[2] | 0;\n this.v1h = B2B_IV[3] | 0;\n this.v2l = B2B_IV[4] | 0;\n this.v2h = B2B_IV[5] | 0;\n this.v3l = B2B_IV[6] | 0;\n this.v3h = B2B_IV[7] | 0;\n this.v4l = B2B_IV[8] | 0;\n this.v4h = B2B_IV[9] | 0;\n this.v5l = B2B_IV[10] | 0;\n this.v5h = B2B_IV[11] | 0;\n this.v6l = B2B_IV[12] | 0;\n this.v6h = B2B_IV[13] | 0;\n this.v7l = B2B_IV[14] | 0;\n this.v7h = B2B_IV[15] | 0;\n checkBlake2Opts(olen, opts, 64, 16, 16);\n let { key, personalization, salt } = opts;\n let keyLength = 0;\n if (key !== undefined) {\n key = toBytes(key);\n keyLength = key.length;\n }\n this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);\n if (salt !== undefined) {\n salt = toBytes(salt);\n const slt = u32(salt);\n this.v4l ^= swap8IfBE(slt[0]);\n this.v4h ^= swap8IfBE(slt[1]);\n this.v5l ^= swap8IfBE(slt[2]);\n this.v5h ^= swap8IfBE(slt[3]);\n }\n if (personalization !== undefined) {\n personalization = toBytes(personalization);\n const pers = u32(personalization);\n this.v6l ^= swap8IfBE(pers[0]);\n this.v6h ^= swap8IfBE(pers[1]);\n this.v7l ^= swap8IfBE(pers[2]);\n this.v7h ^= swap8IfBE(pers[3]);\n }\n if (key !== undefined) {\n // Pad to blockLen and update\n const tmp = new Uint8Array(this.blockLen);\n tmp.set(key);\n this.update(tmp);\n }\n }\n // prettier-ignore\n get() {\n let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;\n return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];\n }\n // prettier-ignore\n set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {\n this.v0l = v0l | 0;\n this.v0h = v0h | 0;\n this.v1l = v1l | 0;\n this.v1h = v1h | 0;\n this.v2l = v2l | 0;\n this.v2h = v2h | 0;\n this.v3l = v3l | 0;\n this.v3h = v3h | 0;\n this.v4l = v4l | 0;\n this.v4h = v4h | 0;\n this.v5l = v5l | 0;\n this.v5h = v5h | 0;\n this.v6l = v6l | 0;\n this.v6h = v6h | 0;\n this.v7l = v7l | 0;\n this.v7h = v7h | 0;\n }\n compress(msg, offset, isLast) {\n this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.\n BBUF.set(B2B_IV, 16); // Second half from IV.\n let { h, l } = u64.fromBig(BigInt(this.length));\n BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.\n BBUF[25] = B2B_IV[9] ^ h; // High word.\n // Invert all bits for last block\n if (isLast) {\n BBUF[28] = ~BBUF[28];\n BBUF[29] = ~BBUF[29];\n }\n let j = 0;\n const s = BSIGMA;\n for (let i = 0; i < 12; i++) {\n G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);\n G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);\n G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);\n G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);\n G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);\n G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);\n G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);\n G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);\n G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);\n G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);\n G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);\n G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);\n G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);\n G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);\n G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);\n G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);\n }\n this.v0l ^= BBUF[0] ^ BBUF[16];\n this.v0h ^= BBUF[1] ^ BBUF[17];\n this.v1l ^= BBUF[2] ^ BBUF[18];\n this.v1h ^= BBUF[3] ^ BBUF[19];\n this.v2l ^= BBUF[4] ^ BBUF[20];\n this.v2h ^= BBUF[5] ^ BBUF[21];\n this.v3l ^= BBUF[6] ^ BBUF[22];\n this.v3h ^= BBUF[7] ^ BBUF[23];\n this.v4l ^= BBUF[8] ^ BBUF[24];\n this.v4h ^= BBUF[9] ^ BBUF[25];\n this.v5l ^= BBUF[10] ^ BBUF[26];\n this.v5h ^= BBUF[11] ^ BBUF[27];\n this.v6l ^= BBUF[12] ^ BBUF[28];\n this.v6h ^= BBUF[13] ^ BBUF[29];\n this.v7l ^= BBUF[14] ^ BBUF[30];\n this.v7h ^= BBUF[15] ^ BBUF[31];\n clean(BBUF);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer32);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/**\n * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.\n * @param msg - message that would be hashed\n * @param opts - dkLen output length, key for MAC mode, salt, personalization\n */\nexport const blake2b = /* @__PURE__ */ createOptHasher((opts) => new BLAKE2b(opts));\n// prettier-ignore\nexport function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {\n let j = 0;\n for (let i = 0; i < rounds; i++) {\n ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));\n ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));\n ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));\n ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));\n ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));\n ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));\n ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));\n ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));\n ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));\n ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));\n ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));\n ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));\n ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));\n ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));\n ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));\n ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));\n }\n return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };\n}\nconst B2S_IV = SHA256_IV;\nexport class BLAKE2s extends BLAKE2 {\n constructor(opts = {}) {\n const olen = opts.dkLen === undefined ? 32 : opts.dkLen;\n super(64, olen);\n // Internal state, same as SHA-256\n this.v0 = B2S_IV[0] | 0;\n this.v1 = B2S_IV[1] | 0;\n this.v2 = B2S_IV[2] | 0;\n this.v3 = B2S_IV[3] | 0;\n this.v4 = B2S_IV[4] | 0;\n this.v5 = B2S_IV[5] | 0;\n this.v6 = B2S_IV[6] | 0;\n this.v7 = B2S_IV[7] | 0;\n checkBlake2Opts(olen, opts, 32, 8, 8);\n let { key, personalization, salt } = opts;\n let keyLength = 0;\n if (key !== undefined) {\n key = toBytes(key);\n keyLength = key.length;\n }\n this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);\n if (salt !== undefined) {\n salt = toBytes(salt);\n const slt = u32(salt);\n this.v4 ^= swap8IfBE(slt[0]);\n this.v5 ^= swap8IfBE(slt[1]);\n }\n if (personalization !== undefined) {\n personalization = toBytes(personalization);\n const pers = u32(personalization);\n this.v6 ^= swap8IfBE(pers[0]);\n this.v7 ^= swap8IfBE(pers[1]);\n }\n if (key !== undefined) {\n // Pad to blockLen and update\n abytes(key);\n const tmp = new Uint8Array(this.blockLen);\n tmp.set(key);\n this.update(tmp);\n }\n }\n get() {\n const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;\n return [v0, v1, v2, v3, v4, v5, v6, v7];\n }\n // prettier-ignore\n set(v0, v1, v2, v3, v4, v5, v6, v7) {\n this.v0 = v0 | 0;\n this.v1 = v1 | 0;\n this.v2 = v2 | 0;\n this.v3 = v3 | 0;\n this.v4 = v4 | 0;\n this.v5 = v5 | 0;\n this.v6 = v6 | 0;\n this.v7 = v7 | 0;\n }\n compress(msg, offset, isLast) {\n const { h, l } = u64.fromBig(BigInt(this.length));\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);\n this.v0 ^= v0 ^ v8;\n this.v1 ^= v1 ^ v9;\n this.v2 ^= v2 ^ v10;\n this.v3 ^= v3 ^ v11;\n this.v4 ^= v4 ^ v12;\n this.v5 ^= v5 ^ v13;\n this.v6 ^= v6 ^ v14;\n this.v7 ^= v7 ^ v15;\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer32);\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/**\n * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.\n * @param msg - message that would be hashed\n * @param opts - dkLen output length, key for MAC mode, salt, personalization\n */\nexport const blake2s = /* @__PURE__ */ createOptHasher((opts) => new BLAKE2s(opts));\n//# sourceMappingURL=blake2.js.map","/**\n * Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF.\n *\n * It is advertised as \"the fastest cryptographic hash\". However, it isn't true in JS.\n * Why is this so slow? While it should be 6x faster than blake2b, perf diff is only 20%:\n *\n * * There is only 30% reduction in number of rounds from blake2s\n * * Speed-up comes from tree structure, which is parallelized using SIMD & threading.\n * These features are not present in JS, so we only get overhead from trees.\n * * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs.\n * * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm\n * @module\n */\nimport { SHA256_IV } from \"./_md.js\";\nimport { fromBig } from \"./_u64.js\";\nimport { BLAKE2, compress } from \"./blake2.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createXOFer, swap32IfBE, toBytes, u32, u8 } from \"./utils.js\";\n// Flag bitset\nconst B3_Flags = {\n CHUNK_START: 0b1,\n CHUNK_END: 0b10,\n PARENT: 0b100,\n ROOT: 0b1000,\n KEYED_HASH: 0b10000,\n DERIVE_KEY_CONTEXT: 0b100000,\n DERIVE_KEY_MATERIAL: 0b1000000,\n};\nconst B3_IV = SHA256_IV.slice();\nconst B3_SIGMA = /* @__PURE__ */ (() => {\n const Id = Array.from({ length: 16 }, (_, i) => i);\n const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);\n const res = [];\n for (let i = 0, v = Id; i < 7; i++, v = permute(v))\n res.push(...v);\n return Uint8Array.from(res);\n})();\n/** Blake3 hash. Can be used as MAC and KDF. */\nexport class BLAKE3 extends BLAKE2 {\n constructor(opts = {}, flags = 0) {\n super(64, opts.dkLen === undefined ? 32 : opts.dkLen);\n this.chunkPos = 0; // Position of current block in chunk\n this.chunksDone = 0; // How many chunks we already have\n this.flags = 0 | 0;\n this.stack = [];\n // Output\n this.posOut = 0;\n this.bufferOut32 = new Uint32Array(16);\n this.chunkOut = 0; // index of output chunk\n this.enableXOF = true;\n const { key, context } = opts;\n const hasContext = context !== undefined;\n if (key !== undefined) {\n if (hasContext)\n throw new Error('Only \"key\" or \"context\" can be specified at same time');\n const k = toBytes(key).slice();\n abytes(k, 32);\n this.IV = u32(k);\n swap32IfBE(this.IV);\n this.flags = flags | B3_Flags.KEYED_HASH;\n }\n else if (hasContext) {\n const ctx = toBytes(context);\n const contextKey = new BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT)\n .update(ctx)\n .digest();\n this.IV = u32(contextKey);\n swap32IfBE(this.IV);\n this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;\n }\n else {\n this.IV = B3_IV.slice();\n this.flags = flags;\n }\n this.state = this.IV.slice();\n this.bufferOut = u8(this.bufferOut32);\n }\n // Unused\n get() {\n return [];\n }\n set() { }\n b2Compress(counter, flags, buf, bufPos = 0) {\n const { state: s, pos } = this;\n const { h, l } = fromBig(BigInt(counter), true);\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags);\n s[0] = v0 ^ v8;\n s[1] = v1 ^ v9;\n s[2] = v2 ^ v10;\n s[3] = v3 ^ v11;\n s[4] = v4 ^ v12;\n s[5] = v5 ^ v13;\n s[6] = v6 ^ v14;\n s[7] = v7 ^ v15;\n }\n compress(buf, bufPos = 0, isLast = false) {\n // Compress last block\n let flags = this.flags;\n if (!this.chunkPos)\n flags |= B3_Flags.CHUNK_START;\n if (this.chunkPos === 15 || isLast)\n flags |= B3_Flags.CHUNK_END;\n if (!isLast)\n this.pos = this.blockLen;\n this.b2Compress(this.chunksDone, flags, buf, bufPos);\n this.chunkPos += 1;\n // If current block is last in chunk (16 blocks), then compress chunks\n if (this.chunkPos === 16 || isLast) {\n let chunk = this.state;\n this.state = this.IV.slice();\n // If not the last one, compress only when there are trailing zeros in chunk counter\n // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed.\n // 1 (001) - leaf not finished (just push current chunk to stack)\n // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)\n // 3 (011) - last leaf not finished\n // 4 (100) - leafs finished at depth=1 and depth=2\n for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {\n if (!(last = this.stack.pop()))\n break;\n this.buffer32.set(last, 0);\n this.buffer32.set(chunk, 8);\n this.pos = this.blockLen;\n this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);\n chunk = this.state;\n this.state = this.IV.slice();\n }\n this.chunksDone++;\n this.chunkPos = 0;\n this.stack.push(chunk);\n }\n this.pos = 0;\n }\n _cloneInto(to) {\n to = super._cloneInto(to);\n const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;\n to.state.set(state.slice());\n to.stack = stack.map((i) => Uint32Array.from(i));\n to.IV.set(IV);\n to.flags = flags;\n to.chunkPos = chunkPos;\n to.chunksDone = chunksDone;\n to.posOut = posOut;\n to.chunkOut = chunkOut;\n to.enableXOF = this.enableXOF;\n to.bufferOut32.set(this.bufferOut32);\n return to;\n }\n destroy() {\n this.destroyed = true;\n clean(this.state, this.buffer32, this.IV, this.bufferOut32);\n clean(...this.stack);\n }\n // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)\n b2CompressOut() {\n const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;\n const { h, l } = fromBig(BigInt(this.chunkOut++));\n swap32IfBE(buffer32);\n // prettier-ignore\n const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags);\n out32[0] = v0 ^ v8;\n out32[1] = v1 ^ v9;\n out32[2] = v2 ^ v10;\n out32[3] = v3 ^ v11;\n out32[4] = v4 ^ v12;\n out32[5] = v5 ^ v13;\n out32[6] = v6 ^ v14;\n out32[7] = v7 ^ v15;\n out32[8] = s[0] ^ v8;\n out32[9] = s[1] ^ v9;\n out32[10] = s[2] ^ v10;\n out32[11] = s[3] ^ v11;\n out32[12] = s[4] ^ v12;\n out32[13] = s[5] ^ v13;\n out32[14] = s[6] ^ v14;\n out32[15] = s[7] ^ v15;\n swap32IfBE(buffer32);\n swap32IfBE(out32);\n this.posOut = 0;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n // Padding\n clean(this.buffer.subarray(this.pos));\n // Process last chunk\n let flags = this.flags | B3_Flags.ROOT;\n if (this.stack.length) {\n flags |= B3_Flags.PARENT;\n swap32IfBE(this.buffer32);\n this.compress(this.buffer32, 0, true);\n swap32IfBE(this.buffer32);\n this.chunksDone = 0;\n this.pos = this.blockLen;\n }\n else {\n flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;\n }\n this.flags = flags;\n this.b2CompressOut();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const { blockLen, bufferOut } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.b2CompressOut();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n if (!this.enableXOF)\n throw new Error('XOF is not possible after digest call');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.enableXOF = false;\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n}\n/**\n * BLAKE3 hash function. Can be used as MAC and KDF.\n * @param msg - message that would be hashed\n * @param opts - `dkLen` for output length, `key` for MAC mode, `context` for KDF mode\n * @example\n * const data = new Uint8Array(32);\n * const hash = blake3(data);\n * const mac = blake3(data, { key: new Uint8Array(32) });\n * const kdf = blake3(data, { context: 'application name' });\n */\nexport const blake3 = /* @__PURE__ */ createXOFer((opts) => new BLAKE3(opts));\n//# sourceMappingURL=blake3.js.map","import { blake3 } from '@noble/hashes/blake3';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8 } from './bytes.js';\nconst LANES = 1024;\nconst LANE_BYTES = 2; // @NOTE cannot change without reworking the Uint16Array impl\nexport const LTHASH_STATE_BYTES = LANES * LANE_BYTES; // 2048\n/**\n * A homomorphic set hash. Each element expands to 1024 little-endian u16 lanes\n * which are summed into the state mod 2^16. Addition and subtraction commute, so\n * the state depends only on the current set, not on insertion order.\n */\nexport class LtHash {\n constructor(state) {\n if (state && state.length !== LTHASH_STATE_BYTES) {\n throw new TypeError(`LtHash state must be ${LTHASH_STATE_BYTES} bytes, got ${state.length}`);\n }\n const buffer = new ArrayBuffer(LTHASH_STATE_BYTES);\n this.bytes = new Uint8Array(buffer);\n this.lanes = new Uint16Array(buffer);\n if (state)\n this.bytes.set(state);\n }\n add(element) {\n const lanes = expand(element);\n for (let i = 0; i < LANES; i++) {\n this.lanes[i] += lanes[i];\n }\n return this;\n }\n remove(element) {\n const lanes = expand(element);\n for (let i = 0; i < LANES; i++) {\n this.lanes[i] -= lanes[i];\n }\n return this;\n }\n // The full state, for persistence.\n state() {\n return new Uint8Array(this.bytes);\n }\n digest() {\n return sha256(this.bytes);\n }\n isEmpty() {\n for (let i = 0; i < LANES; i++) {\n if (this.lanes[i] !== 0)\n return false;\n }\n return true;\n }\n equals(other) {\n for (let i = 0; i < LANES; i++) {\n if (this.lanes[i] !== other.lanes[i])\n return false;\n }\n return true;\n }\n}\n// Expand to 1024 u16 lanes with BLAKE3 in XOF mode.\nfunction expand(element) {\n const expanded = blake3(utf8(element), {\n dkLen: LTHASH_STATE_BYTES,\n });\n // Copy: the result may be a view at an offset a Uint16Array can't straddle.\n const buffer = new ArrayBuffer(LTHASH_STATE_BYTES);\n new Uint8Array(buffer).set(expanded);\n return new Uint16Array(buffer);\n}\n//# sourceMappingURL=lthash.js.map","import { ByteSequence, isByteSequence, isInnerList, parseDictionary, serializeDictionary, serializeInnerList, } from 'structured-headers';\nimport { hmacSha256 } from '@atproto/crypto';\nimport { fromBase64, ui8Equals } from '@atproto/lex-data';\nimport { isValidDid } from '@atproto/syntax';\nimport { timingSafeEqual, toPaddedBase64 } from './bytes.js';\nimport { SpaceMacError } from './error.js';\nimport { findSignature, formatComponents, membersWithTag, signatureBase, } from './http-signature.js';\n/**\n * Space repos authenticate commits and records with a MAC rather than a\n * signature, so a leaked response proves nothing to a third party. A MAC is an\n * HTTP message signature (RFC 9421) using `hmac-sha256`, keyed by a per-request\n * shared secret (see `kem.ts`).\n *\n * The syncer requests a MAC with an `Accept-Signature` header, whose `tag` names\n * a profile. The host responds with a header describing the commit or record it\n * returned, and a MAC covering that header.\n */\nexport const COMMIT_MAC_PROFILE = 'atproto-space-commit';\nexport const RECORD_MAC_PROFILE = 'atproto-space-record';\n/** The header each profile's MAC covers. */\nexport const MAC_COVERED_HEADER = {\n [COMMIT_MAC_PROFILE]: 'atproto-space-commit',\n [RECORD_MAC_PROFILE]: 'atproto-space-record',\n};\nconst MAC_ALG = 'hmac-sha256';\n// The label this syncer requests its MAC under. A host answers under the label\n// that was requested, though a syncer finds the MAC by its tag.\nconst MAC_LABEL = 'mac';\n// The parameters a host fulfills: the key share to use, the profile's tag, and\n// optionally the algorithm. A syncer uses a new key share for each request, so\n// `created`, `expires`, and `nonce` would add nothing.\nconst MAC_REQUEST_PARAMS = ['keyid', 'tag', 'alg'];\n// A MAC covers its profile's header, flagged `sf` as a structured field.\nfunction macComponents(profile) {\n return [[MAC_COVERED_HEADER[profile], new Map([['sf', true]])]];\n}\n// ---- Requests ----\n/**\n * The syncer's `Accept-Signature` request header, asking for a MAC keyed by the\n * shared secret for `keyShare` (see `encapsulate`), e.g.\n * `mac=(\"atproto-space-commit\";sf);keyid=\"did:key:zDna...\";tag=\"atproto-space-commit\"`\n */\nexport function formatMacRequest(profile, keyShare) {\n const signatureParams = serializeInnerList([\n macComponents(profile),\n new Map([\n ['keyid', keyShare],\n ['tag', profile],\n ]),\n ]);\n return `${MAC_LABEL}=${signatureParams}`;\n}\n/**\n * Find the MAC requested for `profile` in an `Accept-Signature` header, checking\n * that the host can fulfill it. Requests with other tags are ignored, so this\n * returns undefined when none is for `profile`.\n */\nexport function parseMacRequest(value, profile) {\n if (value === undefined)\n return undefined;\n const requests = parseMacField(value, 'Accept-Signature');\n const tagged = membersWithTag(requests, profile);\n if (tagged.length === 0)\n return undefined;\n if (tagged.length > 1) {\n throw new SpaceMacError(`more than one MAC requested with tag \"${profile}\"`);\n }\n const { label, params } = tagged[0];\n const [components, parameters] = params;\n const expected = formatComponents(macComponents(profile));\n if (formatComponents(components) !== expected) {\n throw new SpaceMacError(`MAC must cover exactly ${expected}`);\n }\n for (const name of parameters.keys()) {\n if (!MAC_REQUEST_PARAMS.includes(name)) {\n throw new SpaceMacError(`unsupported MAC parameter: ${name}`);\n }\n }\n if (parameters.has('alg') && parameters.get('alg') !== MAC_ALG) {\n throw new SpaceMacError(`MAC algorithm must be ${MAC_ALG}`);\n }\n const keyShare = parameters.get('keyid');\n if (!isValidDid(keyShare)) {\n throw new SpaceMacError('missing or malformed keyid');\n }\n return { label, keyShare, signatureParams: serializeInnerList(params) };\n}\n/**\n * The response headers for a commit: an `Atproto-Space-Commit` header describing\n * it, and a MAC covering that header. The header holds the commit's fields, e.g.\n * `ver=1, repo=\"did:example:alice\", space=\"at:space/...\", rev=\"3mwcj3b6uak2f\", data=:q3J0...=:`\n */\nexport function createCommitMacHeaders(commit, params) {\n const header = serializeDictionary(new Map([\n ['ver', [commit.ver, new Map()]],\n ['repo', [commit.repo, new Map()]],\n ['space', [commit.space, new Map()]],\n ['rev', [commit.rev, new Map()]],\n ['data', [new ByteSequence(toPaddedBase64(commit.data)), new Map()]],\n ]));\n return createMacHeaders(COMMIT_MAC_PROFILE, header, params);\n}\n/**\n * The response headers for a record: an `Atproto-Space-Record` header naming it,\n * and a MAC covering that header. The header holds the record's uri and cid, e.g.\n * `uri=\"at:space/...\", cid=\"bafyrei...\"`\n */\nexport function createRecordMacHeaders(uri, cid, params) {\n const header = serializeDictionary(new Map([\n ['uri', [uri, new Map()]],\n ['cid', [cid.toString(), new Map()]],\n ]));\n return createMacHeaders(RECORD_MAC_PROFILE, header, params);\n}\n// The covered header, with the `Signature-Input` and `Signature` headers of a MAC\n// over it.\nfunction createMacHeaders(profile, coveredHeader, { label, signatureParams, sharedSecret }) {\n const base = signatureBase(macComponents(profile), [coveredHeader], signatureParams);\n const mac = hmacSha256(sharedSecret, base);\n return {\n headers: {\n [MAC_COVERED_HEADER[profile]]: coveredHeader,\n 'signature-input': `${label}=${signatureParams}`,\n signature: `${label}=:${toPaddedBase64(mac)}:`,\n },\n };\n}\n/**\n * Verify a response's MAC, and that the `Atproto-Space-Commit` header it covers\n * describes `commit`.\n */\nexport function verifyCommitMac(commit, params) {\n const fields = verifyMac(COMMIT_MAC_PROFILE, params);\n const data = bareItem(fields, 'data');\n const matches = bareItem(fields, 'ver') === commit.ver &&\n bareItem(fields, 'repo') === commit.repo &&\n bareItem(fields, 'space') === commit.space &&\n bareItem(fields, 'rev') === commit.rev &&\n data !== undefined &&\n isByteSequence(data) &&\n ui8Equals(fromBase64(data.toBase64()), commit.data);\n if (!matches) {\n throw new SpaceMacError('commit does not match its MAC');\n }\n}\n/**\n * Verify a response's MAC, and that the `Atproto-Space-Record` header it covers\n * names `uri` and `cid`.\n */\nexport function verifyRecordMac(uri, cid, params) {\n const fields = verifyMac(RECORD_MAC_PROFILE, params);\n if (bareItem(fields, 'uri') !== uri ||\n bareItem(fields, 'cid') !== cid.toString()) {\n throw new SpaceMacError('record does not match its MAC');\n }\n}\n// Check the MAC requested for `profile`, returning the fields of the header it covers.\nfunction verifyMac(profile, { keyShare, sharedSecret, headers }) {\n const components = macComponents(profile);\n const { signatureParams, signature } = findSignature(headers.get('signature-input'), headers.get('signature'), { tag: profile, components, alg: MAC_ALG, keyId: keyShare }, SpaceMacError);\n const header = MAC_COVERED_HEADER[profile];\n const fields = parseMacField(headers.get(header), header);\n // The `sf` flag covers the header as re-serialized from its parsed form.\n const base = signatureBase(components, [serializeDictionary(fields)], signatureParams);\n if (!timingSafeEqual(hmacSha256(sharedSecret, base), signature)) {\n throw new SpaceMacError('MAC does not match');\n }\n return fields;\n}\nfunction parseMacField(value, name) {\n if (typeof value !== 'string') {\n throw new SpaceMacError(`missing or malformed ${name} header`);\n }\n try {\n return parseDictionary(value);\n }\n catch (cause) {\n throw new SpaceMacError(`malformed ${name} header`, { cause });\n }\n}\n// A dictionary member's value, ignoring any parameters.\nfunction bareItem(fields, key) {\n const member = fields.get(key);\n return member && !isInnerList(member) ? member[0] : undefined;\n}\n//# sourceMappingURL=mac.js.map","/*@__NO_SIDE_EFFECTS__*/\nexport function lazyProperty(obj, key, value) {\n Object.defineProperty(obj, key, {\n value,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n return value;\n}\n//# sourceMappingURL=lazy-property.js.map","/**\n * Aggregates items in an array based on a comparison function and an aggregation function.\n *\n * @param arr - The input array to aggregate.\n * @param cmp - A comparison function that determines if two items belong to the same group.\n * @param agg - An aggregation function that combines items in a group into a single item.\n * @returns An array of aggregated items.\n * @example\n * ```ts\n * const input = [1, 1, 2, 2, 3, 3, 3]\n * const result = arrayAgg(\n * input,\n * (a, b) => a === b,\n * (items) => { value: items[0], sum: items.reduce((sum, item) => sum + item, 0) },\n * )\n * // result is [{ value: 1, sum: 2 }, { value: 2, sum: 4 }, { value: 3, sum: 6 }]\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function arrayAgg(arr, cmp, agg) {\n if (arr.length === 0)\n return [];\n const groups = [[arr[0]]];\n const skipped = Array(arr.length);\n outer: for (let i = 1; i < arr.length; i++) {\n if (skipped[i])\n continue;\n const item = arr[i];\n for (let j = 0; j < groups.length; j++) {\n if (cmp(item, groups[j][0])) {\n groups[j].push(item);\n skipped[i] = true;\n continue outer;\n }\n }\n groups.push([item]);\n }\n return groups.map(agg);\n}\n//# sourceMappingURL=array-agg.js.map","import { ifCid, isLegacyBlobRef, isPlainObject } from '@atproto/lex-data';\nconst STRING_PREVIEW_MAX_LENGTH = 256;\nconst STRING_PREVIEW_TRUNCATED_SUFFIX = 'โฆ';\n/**\n * Abstract base class for all validation issues.\n *\n * An issue represents a single validation failure, containing:\n * - A code identifying the type of issue\n * - The path to the invalid value in the data structure\n * - The actual input value that failed validation\n *\n * Subclasses add specific properties relevant to each issue type and implement\n * the {@link message} property for human-readable error messages (that don't\n * contain the error path)\n */\nexport class Issue {\n constructor(code, path, input) {\n this.code = code;\n this.path = path;\n this.input = input;\n }\n /**\n * Returns a human-readable description of the validation issue.\n */\n toString() {\n return `${this.message}${stringifyPath(this.path)}`;\n }\n /**\n * Converts the issue to a JSON-serializable object.\n *\n * @returns An object containing the issue code, path, and message\n */\n toJSON() {\n return {\n code: this.code,\n path: this.path,\n message: this.message,\n };\n }\n}\n/**\n * A custom validation issue with a user-defined message.\n *\n * Use this for validation rules that don't fit into the standard issue categories.\n */\nexport class IssueCustom extends Issue {\n constructor(path, input, message) {\n super('custom', path, input);\n this.path = path;\n this.input = input;\n this.message = message;\n }\n}\n/**\n * Issue for string values that don't match an expected format.\n *\n * Used for AT Protocol specific formats like DID, handle, NSID, AT-URI, etc.\n */\nexport class IssueInvalidFormat extends Issue {\n constructor(path, input, format, detail) {\n super('invalid_format', path, input);\n this.format = format;\n this.detail = detail;\n }\n get message() {\n return `Invalid ${this.formatDescription}${this.detail ? ` (${this.detail}, ` : ' ('}got ${stringifyValue(this.input)})`;\n }\n /** Returns a human-readable description of the expected format. */\n get formatDescription() {\n switch (this.format) {\n case 'at-identifier':\n return `AT identifier`;\n case 'did':\n return `DID`;\n case 'nsid':\n return `NSID`;\n case 'cid':\n return `CID string`;\n case 'tid':\n return `TID string`;\n case 'record-key':\n return `record key`;\n default:\n return this.format;\n }\n }\n toJSON() {\n return {\n ...super.toJSON(),\n format: this.format,\n };\n }\n}\n/**\n * Issue for values that have an unexpected type.\n *\n * This is one of the most common validation issues, occurring when the\n * runtime type of a value doesn't match the expected schema type.\n */\nexport class IssueInvalidType extends Issue {\n constructor(path, input, expected) {\n super('invalid_type', path, input);\n this.expected = expected;\n }\n get message() {\n return `Expected ${oneOf(this.expected.map(stringifyExpectedType))} value type (got ${stringifyValue(this.input)})`;\n }\n toJSON() {\n return {\n ...super.toJSON(),\n expected: this.expected,\n };\n }\n}\n/**\n * Issue for values that don't match any of the expected literal values.\n *\n * Used when a value must be one of a specific set of allowed values\n * (e.g., enum-like constraints).\n */\nexport class IssueInvalidValue extends Issue {\n constructor(path, input, values) {\n super('invalid_value', path, input);\n this.values = values;\n }\n get message() {\n return `Expected ${oneOf(this.values.map(stringifyValue))} (got ${stringifyValue(this.input)})`;\n }\n toJSON() {\n return {\n ...super.toJSON(),\n values: this.values,\n };\n }\n}\n/**\n * Issue for missing required object properties.\n */\nexport class IssueRequiredKey extends Issue {\n constructor(path, input, key) {\n super('required_key', path, input);\n this.key = key;\n }\n get message() {\n return `Missing required key \"${String(this.key)}\"`;\n }\n toJSON() {\n return {\n ...super.toJSON(),\n key: this.key,\n };\n }\n}\n/**\n * Issue for values that exceed a maximum constraint.\n */\nexport class IssueTooBig extends Issue {\n constructor(path, input, maximum, type, actual) {\n super('too_big', path, input);\n this.maximum = maximum;\n this.type = type;\n this.actual = actual;\n }\n get message() {\n return `${this.type} too big (maximum ${this.maximum}, got ${this.actual})`;\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n maximum: this.maximum,\n };\n }\n}\n/**\n * Issue for values that are below a minimum constraint.\n */\nexport class IssueTooSmall extends Issue {\n constructor(path, input, minimum, type, actual) {\n super('too_small', path, input);\n this.minimum = minimum;\n this.type = type;\n this.actual = actual;\n }\n get message() {\n return `${this.type} too small (minimum ${this.minimum}, got ${this.actual})`;\n }\n toJSON() {\n return {\n ...super.toJSON(),\n type: this.type,\n minimum: this.minimum,\n };\n }\n}\n// -----------------------------------------------------------------------------\n// Helper functions for formatting error messages\n// -----------------------------------------------------------------------------\nfunction stringifyExpectedType(expected) {\n if (expected === '$typed') {\n return 'an object which includes the \"$type\" property';\n }\n return expected;\n}\nfunction stringifyPath(path) {\n return ` at ${buildJsonPath(path)}`;\n}\nfunction buildJsonPath(path) {\n return `$${path.map(toJsonPathSegment).join('')}`;\n}\nfunction toJsonPathSegment(segment) {\n if (typeof segment === 'number' || typeof segment === 'symbol') {\n return `[${String(segment)}]`;\n }\n else if (/^[a-zA-Z_$][a-zA-Z0-9_]*$/.test(segment)) {\n return `.${segment}`;\n }\n else {\n return `[${JSON.stringify(segment)}]`;\n }\n}\nfunction oneOf(arr) {\n if (arr.length === 0)\n return '';\n if (arr.length === 1)\n return arr[0];\n return `one of ${arr.slice(0, -1).join(', ')} or ${arr.at(-1)}`;\n}\nfunction stringifyValue(value) {\n switch (typeof value) {\n case 'bigint':\n return `${value}n`;\n case 'number':\n case 'boolean':\n return String(value);\n case 'string':\n return JSON.stringify(value.length < STRING_PREVIEW_MAX_LENGTH\n ? value\n : `${value.slice(0, STRING_PREVIEW_MAX_LENGTH - STRING_PREVIEW_TRUNCATED_SUFFIX.length)}${STRING_PREVIEW_TRUNCATED_SUFFIX}`);\n case 'object':\n if (value === null)\n return 'null';\n if (Array.isArray(value)) {\n return `[${stringifyArray(value, stringifyValue)}]`;\n }\n if (isPlainObject(value)) {\n return `{${stringifyArray(Object.entries(value), stringifyObjectEntry)}}`;\n }\n if (ifCid(value))\n return 'cid';\n if (isLegacyBlobRef(value))\n return 'legacy-blob';\n if (value instanceof Date)\n return 'date';\n if (value instanceof RegExp)\n return 'regexp';\n if (value instanceof Map)\n return 'map';\n if (value instanceof Set)\n return 'set';\n return 'object';\n default:\n return typeof value;\n }\n}\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyObjectEntry([key, _value]) {\n return `${JSON.stringify(key)}: ...`;\n}\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringifyArray(arr, fn, n = 2) {\n return arr.slice(0, n).map(fn).join(', ') + (arr.length > n ? ', ...' : '');\n}\n//# sourceMappingURL=validation-issue.js.map","import { LexError } from '@atproto/lex-data';\nimport { arrayAgg } from '../util/array-agg.js';\nimport { IssueInvalidType, IssueInvalidValue, } from './validation-issue.js';\n/**\n * Error thrown when validation fails.\n *\n * Contains detailed information about all validation issues encountered,\n * including the path to each invalid value and descriptions of what was\n * expected vs what was received.\n *\n * Extends {@link LexError} with the error name \"InvalidRequest\" for\n * consistency with the AT Protocol error handling conventions.\n *\n * @example\n * ```typescript\n * const error = new LexValidationError([\n * new IssueInvalidType(['user', 'age'], 'hello', ['number'])\n * ])\n * console.log(error.message)\n * // \"Expected integer value type (got \"some-string\") at $.user.age\"\n *\n * console.log(error.issues.length) // 1\n * console.log(error.toJSON())\n * // { error: 'InvalidRequest', message: '...', issues: [...] }\n * ```\n *\n * @note this class implements {@link ResultFailure} to allow it to be used\n * directly as a failure reason in validation results, avoiding the need for\n * wrapping it in an additional object.\n */\nexport class LexValidationError extends LexError {\n /**\n * Creates a new validation error from a list of issues.\n *\n * Issues are automatically aggregated to combine related issues at the same\n * path (e.g., multiple type expectations from a union schema).\n *\n * @param issues - The validation issues that caused this error\n * @param options - Standard Error options (e.g., `cause`)\n */\n constructor(issues, options) {\n const issuesAgg = aggregateIssues(issues);\n super('InvalidRequest', issuesAgg.join(', '), options);\n this.name = 'LexValidationError';\n /** @see {ResultFailure.success} */\n this.success = false;\n this.issues = issuesAgg;\n }\n /** @see {ResultFailure.reason} */\n get reason() {\n return this;\n }\n /**\n * Converts the error to a JSON-serializable object.\n *\n * @returns An object containing the error details and issues details\n */\n toJSON() {\n return {\n ...super.toJSON(),\n issues: this.issues.map((issue) => issue.toJSON()),\n };\n }\n}\nfunction aggregateIssues(issues) {\n // Quick path for common cases\n if (issues.length <= 1)\n return issues;\n if (issues.length === 2 && issues[0].code !== issues[1].code)\n return issues;\n return [\n // Aggregate invalid_type with identical paths\n ...arrayAgg(issues.filter((issue) => issue instanceof IssueInvalidType), (a, b) => comparePropertyPaths(a.path, b.path), (issues) => new IssueInvalidType(issues[0].path, issues[0].input, Array.from(new Set(issues.flatMap((iss) => iss.expected))))),\n // Aggregate invalid_value with identical paths\n ...arrayAgg(issues.filter((issue) => issue instanceof IssueInvalidValue), (a, b) => comparePropertyPaths(a.path, b.path), (issues) => new IssueInvalidValue(issues[0].path, issues[0].input, Array.from(new Set(issues.flatMap((iss) => iss.values))))),\n // Pass through other issues\n ...issues.filter((issue) => !(issue instanceof IssueInvalidType) &&\n !(issue instanceof IssueInvalidValue)),\n ];\n}\n/*@__NO_SIDE_EFFECTS__*/\nfunction comparePropertyPaths(a, b) {\n if (a.length !== b.length)\n return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i])\n return false;\n }\n return true;\n}\n//# sourceMappingURL=validation-error.js.map","import { LexValidationError } from './validation-error.js';\nimport { IssueInvalidFormat, IssueInvalidType, IssueInvalidValue, IssueRequiredKey, IssueTooBig, IssueTooSmall, } from './validation-issue.js';\n/**\n * Manages the state and context for validation operations.\n *\n * The `ValidationContext` class is responsible for:\n * - Tracking the current path in nested structures for error reporting\n * - Collecting validation issues during traversal\n * - Enforcing validation mode (validate vs parse)\n * - Providing factory methods for creating validation results\n *\n * Use the static {@link ValidationContext.validate} method as the primary entry point\n * for validation. This ensures proper mode enforcement and issue aggregation.\n *\n * @example\n * ```typescript\n * // Primary usage via static method\n * const result = ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // Within a custom validator implementation\n * class MyValidator implements Validator {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n * ```\n */\nexport class ValidationContext {\n static validate(input, validator, options) {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n strict: options?.strict ?? true,\n });\n return context.validate(input, validator);\n }\n /**\n * Creates a new validation context with the specified options.\n *\n * @param options - The validation options (path and mode are required)\n */\n constructor(options) {\n /**\n * Accumulated validation issues collected during traversal.\n */\n this.issues = [];\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path);\n this.options = options;\n }\n /**\n * Returns a copy of the current validation path.\n *\n * The path represents the location in the data structure being validated,\n * used for constructing meaningful error messages.\n */\n get path() {\n return Array.from(this.currentPath);\n }\n /**\n * Creates a new path by appending segments to the current path.\n *\n * @param path - Optional path segment(s) to append\n * @returns A new path array with the segment(s) appended\n */\n concatPath(path) {\n if (path == null)\n return this.path;\n return this.currentPath.concat(path);\n }\n /**\n * Validates input against a validator within this context.\n *\n * This is the primary entry point for validation within a context. Always use\n * this method instead of calling {@link Validator.validateInContext} directly,\n * as this method enforces validation mode rules and handles transformation detection.\n *\n * @typeParam V - The validator type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @returns A validation result with the validated value or error\n */\n validate(input, validator) {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this);\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return new LexValidationError(Array.from(this.issues));\n }\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned LexValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value]);\n }\n }\n return result;\n }\n /**\n * Validates a child property of an object within this context.\n *\n * This method automatically manages the path stack, pushing the property key\n * before validation and popping it afterward. Use this for validating object\n * properties to ensure proper path tracking in error messages.\n *\n * @typeParam I - The input object type\n * @typeParam K - The property key type\n * @typeParam V - The validator type\n * @param input - The parent object containing the property\n * @param key - The property key to validate\n * @param validator - The validator to use for the property value\n * @returns A validation result for the property value\n *\n * @example\n * ```typescript\n * // In a custom object validator\n * const result = ctx.validateChild(input, 'name', stringSchema)\n * // If validation fails, error path will include 'name'\n * ```\n */\n validateChild(input, key, validator) {\n // @NOTE we could add support for recursive schemas by keeping track of\n // \"parent\" objects in the context and checking for circular references\n // here. This would allow us to validate recursive structures without\n // hitting maximum call stack errors, and would also allow us to provide\n // better error messages for circular reference issues. However, this is not\n // a priority at the moment as recursive structures are not supported in\n // the context of AT Protocol lexicons, and we can always add this in the\n // future if needed.\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key);\n try {\n return this.validate(input[key], validator);\n }\n finally {\n this.currentPath.length--;\n }\n }\n /**\n * Adds a validation issue to the context without immediately failing.\n *\n * Use this method to collect multiple issues during validation before\n * determining the final result. Issues added this way will be included\n * in the final error if validation fails.\n *\n * @param issue - The validation issue to add\n */\n addIssue(issue) {\n this.issues.push(issue);\n }\n /**\n * Helper method to create a successful validation result.\n *\n * @typeParam V - The value type\n * @param value - The validated value\n * @returns A successful validation result\n */\n success(value) {\n return { success: true, value };\n }\n /**\n * Creates a failed validation result from a single issue.\n *\n * Any previously accumulated issues in the context are included in the error.\n *\n * @param issue - The validation issue that caused the failure\n * @returns A failed validation result\n */\n issue(issue) {\n return new LexValidationError([...this.issues, issue]);\n }\n /**\n * Creates a failure for an invalid value that doesn't match expected values.\n *\n * @param input - The actual value that was received\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue\n */\n issueInvalidValue(input, values) {\n return this.issue(new IssueInvalidValue(this.path, input, values));\n }\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - An array of expected type names\n * @returns A failed validation result with an invalid type issue\n */\n issueInvalidType(input, expected) {\n return this.issue(new IssueInvalidType(this.path, input, expected));\n }\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue\n */\n issueUnexpectedType(input, expected) {\n return this.issueInvalidType(input, [expected]);\n }\n /**\n * Creates a failure for a missing required key in an object.\n *\n * @param input - The object missing the required key\n * @param key - The name of the required key\n * @returns A failed validation result with a required key issue\n */\n issueRequiredKey(input, key) {\n return this.issue(new IssueRequiredKey(this.path, input, key));\n }\n /**\n * Creates a failure for an invalid string format.\n *\n * @param input - The actual value that was received\n * @param format - The expected format name (e.g., 'did', 'handle', 'uri')\n * @param msg - Optional additional message describing the format error\n * @returns A failed validation result with an invalid format issue\n */\n issueInvalidFormat(input, format, msg) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg));\n }\n /**\n * Creates a failure for a value that exceeds a maximum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param max - The maximum allowed value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too big issue\n */\n issueTooBig(input, type, max, actual) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual));\n }\n /**\n * Creates a failure for a value that is below a minimum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param min - The minimum required value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too small issue\n */\n issueTooSmall(input, type, min, actual) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual));\n }\n /**\n * Creates a failure for an invalid property value within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid value\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue at the property path\n */\n issueInvalidPropertyValue(input, property, values) {\n const value = input[property];\n const path = this.concatPath(property);\n return this.issue(new IssueInvalidValue(path, value, values));\n }\n /**\n * Creates a failure for an invalid property type within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid type\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue at the property path\n */\n issueInvalidPropertyType(input, property, expected) {\n const value = input[property];\n const path = this.concatPath(property);\n return this.issue(new IssueInvalidType(path, value, [expected]));\n }\n}\n//# sourceMappingURL=validator.js.map","import { ValidationContext } from './validator.js';\n/**\n * The Standard Schema adapter for {@link Validator} instances.\n */\nexport class StandardSchemaAdapter {\n constructor(validator) {\n this.version = 1;\n this.vendor = '@atproto/lex-schema';\n this.validator = validator;\n }\n validate(value, options) {\n // Perform validation in \"parse\" mode to ensure transformations (defaults,\n // coercions, etc.) are applied. Also ensures that the output type is\n // returned. Note that ValidationResult is compatible with\n // StandardSchemaV1.Result :-)\n return ValidationContext.validate(value, this.validator, {\n ...options?.libraryOptions,\n mode: 'parse',\n });\n }\n}\n//# sourceMappingURL=standard-schema.js.map","import { lazyProperty } from '../util/lazy-property.js';\nimport { StandardSchemaAdapter } from './standard-schema.js';\nimport { ValidationContext } from './validator.js';\n/**\n * Abstract base class for all schema validators in the lexicon system.\n *\n * This class provides the standard validation interface that all schema types\n * implement. It offers multiple methods for validating and parsing data:\n *\n * - **Assertion methods**: `assert()`, `check()` - throw on invalid input\n * - **Type guard methods**: `matches()`, `ifMatches()` - return boolean or optional value\n * - **Parse methods**: `parse()`, `safeParse()` - allow value transformation/coercion\n * - **Validate methods**: `validate()`, `safeValidate()` - validation without coercion\n *\n * All methods are also available with a `$` prefix (e.g., `$parse()`, `$validate()`)\n * for consistent access in generated lexicon namespaces.\n *\n * @typeParam TInput - The type accepted as valid input during validation\n * @typeParam TOutput - The type returned after parsing (may include transformations)\n *\n * @example\n * ```typescript\n * class MySchema extends Schema<string> {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n *\n * const schema = new MySchema()\n * schema.assert('hello') // OK\n * schema.assert(123) // Throws LexValidationError\n * schema.matches('hello') // true\n * schema.matches(123) // false\n * ```\n */\nexport class Schema {\n get '~standard'() {\n // Lazily create, and cache, the Standard Schema adapter for this schema\n // instance.\n return lazyProperty(this, '~standard', new StandardSchemaAdapter(this));\n }\n /**\n * @note use {@link check}() instead of {@link assert}() if you encounter a\n * `ts(2775)` error and you are not able to fully type the validator. This\n * will typically arise in generic contexts, where the narrowed type is not\n * needed.\n */\n assert(input, options) {\n const result = this.safeValidate(input, options);\n if (!result.success)\n throw result.reason;\n }\n /**\n * Alias for {@link assert}(). Most useful in generic contexts where the\n * validator is not exactly typed, allowing to avoid \"_Assertions require\n * every name in the call target to be declared with an explicit type\n * annotation. ts(2775)_\" errors.\n */\n check(input, options) {\n this.assert(input, options);\n }\n /**\n * Casts the input (by validating it) to the output type if it matches the\n * schema, otherwise throws. This is the same as calling {@link parse}() with\n * `mode: \"validate\"`.\n */\n cast(input, options) {\n const result = this.safeValidate(input, options);\n if (result.success)\n return result.value;\n throw result.reason;\n }\n /**\n * Type guard that checks if the input matches this schema.\n *\n * @example\n * ```typescript\n * if (schema.matches(data)) {\n * // data is narrowed to the schema's input type\n * console.log(data)\n * }\n * ```\n */\n matches(input, options) {\n const result = this.safeValidate(input, options);\n return result.success;\n }\n /**\n * Returns the input if it matches this schema, otherwise returns `undefined`.\n *\n * This is useful for optional filtering operations where you want to\n * conditionally extract values that match a schema.\n *\n * @example\n * ```typescript\n * const validData = schema.ifMatches(data)\n * if (validData !== undefined) {\n * // validData is the schema's input type\n * console.log(validData)\n * }\n * ```\n */\n ifMatches(input, options) {\n return this.matches(input, options) ? input : undefined;\n }\n /**\n * Parses the input, allowing value transformations and coercion.\n *\n * Unlike {@link validate}, this method allows the schema to transform\n * the input value (e.g., applying default values, type coercion).\n * Throws a {@link LexValidationError} if the input is invalid.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns The parsed and potentially transformed value\n * @throws {LexValidationError} If the input fails validation\n *\n * @example\n * ```typescript\n * const result = schema.parse(rawData)\n * // result has defaults applied and is fully typed\n * ```\n */\n parse(input, options) {\n const result = this.safeParse(input, options);\n if (result.success)\n return result.value;\n throw result.reason;\n }\n /**\n * Safely parses the input without throwing, returning a result object.\n *\n * This method allows value transformations like {@link parse}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @param input - The value to parse\n * @param options - Optional parsing configuration\n * @returns A {@link ValidationResult} with either the parsed value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeParse(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeParse(input, options) {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'parse',\n });\n }\n /**\n * Validates the input strictly without allowing transformations.\n *\n * Unlike {@link parse}, this method requires the input to exactly match\n * the schema without any transformations (no defaults applied, no coercion).\n * Throws a {@link LexValidationError} if the input is invalid or would require transformation.\n *\n * @typeParam I - The input type (preserved in the return type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns The validated input with narrowed type\n * @throws {LexValidationError} If the input fails validation or requires transformation\n *\n * @example\n * ```typescript\n * const validated = schema.validate(data)\n * // validated is typed as the intersection of input type and schema type\n * ```\n */\n validate(input, options) {\n const result = this.safeValidate(input, options);\n if (result.success)\n return result.value;\n throw result.reason;\n }\n /**\n * Safely validates the input without throwing, returning a result object.\n *\n * This method performs strict validation like {@link validate}, but\n * returns a discriminated union result instead of throwing on error.\n *\n * @typeParam I - The input type (preserved in the result value type)\n * @param input - The value to validate\n * @param options - Optional validation configuration\n * @returns A {@link ValidationResult} with either the validated value or validation errors\n *\n * @example\n * ```typescript\n * const result = schema.safeValidate(data)\n * if (result.success) {\n * console.log(result.value)\n * } else {\n * console.error(result.reason.issues)\n * }\n * ```\n */\n safeValidate(input, options) {\n return ValidationContext.validate(input, this, {\n ...options,\n mode: 'validate',\n });\n }\n // @NOTE Dollar-prefixed aliases\n //\n // The `lex-builder` lib generates namespaced utility functions that allow\n // accessing the schema's methods without the need to specify the \".main.\"\n // part of the namespace. This allows utilities for a particular record type\n // to be called like \"app.bsky.feed.post.<utility>()\" instead of\n // \"app.bsky.feed.post.main.<utility>()\".\n //\n // Because those utilities could conflict with other schemas (e.g. if there is\n // a lexicon definition with the same name as the \"<utility>\"), those exported\n // utilities will be prefixed with \"$\".\n //\n // Similarly, since those utilities are defined as simple \"const\", they are\n // also bound (using JS's .bind) to the schema instance, so that they can be\n // used without worrying about the context (e.g. \"app.bsky.feed.post.$parse()\"\n // will work regardless of how it is imported or called).\n //\n // In order to provide the same functionalities for non-main definitions, we\n // also define those aliases directly on the schema instance, so that they can\n // be used in the same way as the utilities generated by \"lex-builder\". For\n // example, if there is a non-main definition \"app.bsky.feed.defs.postView\",\n // it will also be possible to call \"app.bsky.feed.defs.postView.$parse()\".\n //\n // These methods are also \"bound\" to the instance so that they can be used\n // exactly like the utilities generated by \"lex-builder\", without worrying\n // about the context.\n //\n // There are two ways we could \"bind\" those methods to the instance:\n // 1. Define them as getters that return the bound method (e.g. get $parse() {\n // return this.parse.bind(this) })\n // 2. Define them as properties that are initialized in the constructor (e.g.\n // this.$parse = this.parse.bind(this))\n //\n // Since a **lot** of those methods would end-up being created in systems that\n // contains many schemas (e.g. the appview), we choose the first approach\n // (getters) in order to avoid the overhead of creating all those bound\n // functions upfront when instantiating the schemas.\n /**\n * Bound alias for {@link assert} for compatibility with generated utilities.\n * @see {@link assert}\n */\n get $assert() {\n return lazyProperty(this, '$assert', this.assert.bind(this));\n }\n /**\n * Bound alias for {@link check} for compatibility with generated utilities.\n * @see {@link check}\n */\n get $check() {\n return lazyProperty(this, '$check', this.check.bind(this));\n }\n /**\n * Bound alias for {@link cast} for compatibility with generated utilities.\n * @see {@link cast}\n */\n get $cast() {\n return lazyProperty(this, '$cast', this.cast.bind(this));\n }\n /**\n * Bound alias for {@link matches} for compatibility with generated utilities.\n * @see {@link matches}\n */\n get $matches() {\n return lazyProperty(this, '$matches', this.matches.bind(this));\n }\n /**\n * Bound alias for {@link ifMatches} for compatibility with generated utilities.\n * @see {@link ifMatches}\n */\n get $ifMatches() {\n return lazyProperty(this, '$ifMatches', this.ifMatches.bind(this));\n }\n /**\n * Bound alias for {@link parse} for compatibility with generated utilities.\n * @see {@link parse}\n */\n get $parse() {\n return lazyProperty(this, '$parse', this.parse.bind(this));\n }\n /**\n * Bound alias for {@link safeParse} for compatibility with generated utilities.\n * @see {@link safeParse}\n */\n get $safeParse() {\n return lazyProperty(this, '$safeParse', this.safeParse.bind(this));\n }\n /**\n * Bound alias for {@link validate} for compatibility with generated utilities.\n * @see {@link validate}\n */\n get $validate() {\n return lazyProperty(this, '$validate', this.validate.bind(this));\n }\n /**\n * Bound alias for {@link safeValidate} for compatibility with generated utilities.\n * @see {@link safeValidate}\n */\n get $safeValidate() {\n return lazyProperty(this, '$safeValidate', this.safeValidate.bind(this));\n }\n}\n//# sourceMappingURL=schema.js.map","import { validateCidString } from '@atproto/lex-data';\nimport { isAtIdentifierString, isAtUriString, isDatetimeString, isDatetimeStringLenient, isSpaceRefString, isValidDid, isValidHandle, isValidLanguage, isValidNsid, isValidRecordKey, isValidTid, isValidUri, parseLanguageString, } from '@atproto/syntax';\n// -----------------------------------------------------------------------------\n// Individual string format types and type guards\n// -----------------------------------------------------------------------------\n// Re-exporting from @atproto/syntax without modification to preserve types and\n// documentation for types and utilities that are already well-defined there.\n// @TODO rework other string formats in @atproto/syntax to follow this pattern\n// and re-export here, e.g. language tags, NSIDs, record keys, etc.\nexport { asAtIdentifierString, assertAtIdentifierString, ifAtIdentifierString, isAtIdentifierString, } from '@atproto/syntax';\n// AtIdentifierString utilities\nexport { isDidIdentifier, isHandleIdentifier } from '@atproto/syntax';\nexport { asDatetimeString, assertDatetimeString, ifDatetimeString, isDatetimeString, isDatetimeStringLenient, } from '@atproto/syntax';\n// DatetimeString utilities\nexport { currentDatetimeString, toDatetimeString } from '@atproto/syntax';\nexport { asAtUriString, assertAtUriString, ifAtUriString, isAtUriString, } from '@atproto/syntax';\nexport { isSpaceRefString } from '@atproto/syntax';\n/**\n * Lenient version of {@link isSpaceRefString} that does not enforce the validity\n * of the space key, and accepts a space ref in its spaces alpha form,\n * `at://{spaceDid}/space/{spaceType}/{skey}`.\n *\n * @see {@link isSpaceRefString}\n */\nexport function isSpaceRefStringLenient(input) {\n return isSpaceRefString(input, { strict: false });\n}\n/**\n * Lenient version of {@link isAtUriString} that does not enforce the validity\n * of the record key (rkey) path component (if present).\n *\n * @see {@link isAtUriString}\n */\nexport function isAtUriStringLenient(input) {\n return isAtUriString(input, { strict: false });\n}\n/**\n * Type guard that checks if a value is a valid CID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid CID string\n */\nexport const isCidString = ((input) => typeof input === 'string' && validateCidString(input));\n/**\n * Type guard that checks if a value is a valid DID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid DID string\n */\nexport const isDidString = isValidDid;\n/**\n * Type guard that checks if a value is a valid handle string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid handle string\n */\nexport const isHandleString = isValidHandle;\n/**\n * Type guard that checks if a value is a valid BCP-47 language tag.\n *\n * Strict: rejects tags whose syntax is well-formed but violate semantic\n * constraints from RFC 5646 ยง4.1 (e.g. repeated variant subtags or repeated\n * extension singletons). Use {@link isLanguageStringLenient} to accept those.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid language string\n */\nexport const isLanguageString = ((input) => typeof input === 'string' &&\n parseLanguageString(input) !== null);\n/**\n * Lenient version of {@link isLanguageString} that only checks well-formed\n * BCP 47 syntax (RFC 5646 ยง2.1) and does not enforce semantic constraints\n * from ยง4.1.\n *\n * @see {@link isLanguageString}\n */\nexport const isLanguageStringLenient = isValidLanguage;\n/**\n * Type guard that checks if a value is a valid NSID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid NSID string\n */\nexport const isNsidString = isValidNsid;\n/**\n * Type guard that checks if a value is a valid record key string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid record key string\n */\nexport const isRecordKeyString = isValidRecordKey;\n/**\n * Type guard that checks if a value is a valid TID string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid TID string\n */\nexport const isTidString = isValidTid;\n/**\n * Type guard that checks if a value is a valid URI string.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid URI string\n */\nexport const isUriString = isValidUri;\nconst stringFormatVerifiers = /*#__PURE__*/ Object.freeze({\n __proto__: null,\n 'at-identifier': [isAtIdentifierString],\n 'at-uri': [isAtUriString, isAtUriStringLenient],\n cid: [isCidString],\n datetime: [isDatetimeString, isDatetimeStringLenient],\n did: [isDidString],\n handle: [isHandleString],\n language: [isLanguageString, isLanguageStringLenient],\n nsid: [isNsidString],\n 'record-key': [isRecordKeyString],\n 'space-ref': [isSpaceRefString, isSpaceRefStringLenient],\n tid: [isTidString],\n uri: [isUriString],\n});\n/**\n * Type guard that checks if a string matches a specific format.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to check\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns `true` if the string matches the format\n *\n * @example\n * ```typescript\n * const value: string = 'did:plc:1234...'\n * if (isStringFormat(value, 'did')) {\n * // value is typed as DidString\n * console.log('Valid DID:', value)\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isStringFormat(input, format, options) {\n const formatVerifier = stringFormatVerifiers[format];\n // Fool-proof\n if (!formatVerifier)\n throw new TypeError(`Unknown string format: ${format}`);\n const check = options?.strict === false && formatVerifier.length > 1\n ? formatVerifier[1]\n : formatVerifier[0];\n return check(input);\n}\n/**\n * Asserts that a string matches a specific format, throwing if invalid.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to check\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @throws {TypeError} If the string doesn't match the format\n *\n * @example\n * ```typescript\n * assertStringFormat(value, 'handle')\n * // value is now typed as HandleString\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function assertStringFormat(input, format, options) {\n if (!isStringFormat(input, format, options)) {\n throw new TypeError(`Invalid string format (${format}): ${input}`);\n }\n}\n/**\n * Validates and returns a string as the specified format type, throwing if invalid.\n *\n * This is useful when you need to convert a string to a format type in an expression.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to validate against\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns The input typed as the format type\n * @throws {TypeError} If the string doesn't match the format\n *\n * @example\n * ```typescript\n * const did = asStringFormat(userInput, 'did')\n * // did is typed as DidString\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function asStringFormat(input, format, options) {\n assertStringFormat(input, format, options);\n return input;\n}\n/**\n * Returns the string as the format type if valid, otherwise returns `undefined`.\n *\n * This is useful for optional validation where you want to handle invalid values\n * without throwing.\n *\n * @typeParam I - The input string type\n * @typeParam F - The format to validate against\n * @param input - The string to validate\n * @param format - The format name to validate against\n * @returns The typed string if valid, otherwise `undefined`\n *\n * @example\n * ```typescript\n * const did = ifStringFormat(maybeInvalid, 'did')\n * if (did) {\n * // did is typed as DidString\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function ifStringFormat(input, format, options) {\n return isStringFormat(input, format, options) ? input : undefined;\n}\n/**\n * Array of all valid string format names.\n *\n * @example\n * ```typescript\n * for (const format of STRING_FORMATS) {\n * console.log(format) // 'at-identifier', 'at-uri', 'cid', ...\n * }\n * ```\n */\nexport const STRING_FORMATS = /*#__PURE__*/ Object.freeze(\n/*#__PURE__*/ Object.keys(stringFormatVerifiers));\n//# sourceMappingURL=string-format.js.map","/*@__NO_SIDE_EFFECTS__*/\nexport function memoizedOptions(fn) {\n let cache = null;\n return function cached(...args) {\n // Not using the cache if there are args\n if (args.length > 0) {\n return fn(...args);\n }\n if (cache != null) {\n return cache.value;\n }\n const value = fn(...args);\n cache = { value };\n return value;\n };\n}\n/*@__NO_SIDE_EFFECTS__*/\nexport function memoizedTransformer(fn) {\n let cache;\n return function cached(key, ...args) {\n if (args.length > 0)\n return fn(key, ...args);\n cache ??= new WeakMap();\n const cached = cache.get(key);\n if (cached)\n return cached;\n const result = fn(key, ...args);\n cache.set(key, result);\n return result;\n };\n}\n//# sourceMappingURL=memoize.js.map","import { asUint8Array, ifUint8Array } from '@atproto/lex-data';\nimport { Schema } from '../core.js';\nimport { memoizedOptions } from '../util/memoize.js';\n/**\n * Schema for validating binary data as Uint8Array with optional length constraints.\n *\n * In \"parse\" mode, coerces various binary formats (Buffer, ArrayBuffer, etc.)\n * into Uint8Array. In \"validate\" mode, only accepts Uint8Array directly.\n *\n * @example\n * ```ts\n * const schema = new BytesSchema({ maxLength: 1024 })\n * const result = schema.validate(new Uint8Array([1, 2, 3]))\n * ```\n */\nexport class BytesSchema extends Schema {\n constructor(options) {\n super();\n this.type = 'bytes';\n this.options = options;\n }\n validateInContext(input, ctx) {\n // In \"parse\" mode, coerce different binary formats into Uint8Array. Plain\n // arrays and array-like objects are not binary data and are rejected.\n const bytes = ctx.options.mode === 'parse' && isBinary(input)\n ? asUint8Array(input)\n : ifUint8Array(input);\n if (!bytes) {\n return ctx.issueUnexpectedType(input, 'bytes');\n }\n const minLength = this.options?.minLength;\n if (minLength != null && bytes.length < minLength) {\n return ctx.issueTooSmall(bytes, 'bytes', minLength, bytes.length);\n }\n const maxLength = this.options?.maxLength;\n if (maxLength != null && bytes.length > maxLength) {\n return ctx.issueTooBig(bytes, 'bytes', maxLength, bytes.length);\n }\n return ctx.success(bytes);\n }\n}\nfunction isBinary(input) {\n return input instanceof ArrayBuffer || ArrayBuffer.isView(input);\n}\n/**\n * Creates a bytes schema for validating binary data with optional length constraints.\n *\n * Validates Uint8Array values and can coerce other binary formats in parse mode.\n *\n * @param options - Optional configuration for minimum and maximum byte length\n * @returns A new {@link BytesSchema} instance\n *\n * @example\n * ```ts\n * // Basic bytes schema\n * const dataSchema = l.bytes()\n *\n * // With size constraints\n * const avatarSchema = l.bytes({ maxLength: 1000000 }) // 1MB max\n *\n * // With minimum size\n * const hashSchema = l.bytes({ minLength: 32, maxLength: 32 }) // Exactly 32 bytes\n * ```\n */\nexport const bytes = \n/*#__PURE__*/ memoizedOptions((options) => new BytesSchema(options));\n//# sourceMappingURL=bytes.js.map","import { Schema } from '../core.js';\nimport { memoizedOptions } from '../util/memoize.js';\n/**\n * Schema for validating integer values with optional range constraints.\n *\n * Only accepts safe integers (values that can be exactly represented in JavaScript).\n * Use {@link IntegerSchemaOptions} to constrain the allowed range.\n *\n * @example\n * ```ts\n * const schema = new IntegerSchema({ minimum: 0, maximum: 100 })\n * const result = schema.validate(42)\n * ```\n */\nexport class IntegerSchema extends Schema {\n constructor(options) {\n super();\n this.type = 'integer';\n this.options = options;\n }\n validateInContext(input, ctx) {\n if (!isInteger(input)) {\n return ctx.issueUnexpectedType(input, 'integer');\n }\n if (this.options?.minimum != null && input < this.options.minimum) {\n return ctx.issueTooSmall(input, 'integer', this.options.minimum, input);\n }\n if (this.options?.maximum != null && input > this.options.maximum) {\n return ctx.issueTooBig(input, 'integer', this.options.maximum, input);\n }\n return ctx.success(input);\n }\n}\n/**\n * Simple wrapper around {@link Number.isSafeInteger} that acts as a type guard.\n */\nfunction isInteger(input) {\n return Number.isSafeInteger(input);\n}\n/**\n * Creates an integer schema with optional minimum and maximum constraints.\n *\n * Validates that the input is a safe integer (can be exactly represented in JavaScript)\n * and optionally falls within a specified range.\n *\n * @param options - Optional configuration for minimum and maximum values\n * @returns A new {@link IntegerSchema} instance\n *\n * @example\n * ```ts\n * // Basic integer\n * const countSchema = l.integer()\n *\n * // With minimum value\n * const positiveSchema = l.integer({ minimum: 1 })\n *\n * // With range constraints\n * const percentSchema = l.integer({ minimum: 0, maximum: 100 })\n *\n * // Age validation\n * const ageSchema = l.integer({ minimum: 0, maximum: 150 })\n * ```\n */\nexport const integer = \n/*#__PURE__*/ memoizedOptions((options) => new IntegerSchema(options));\n//# sourceMappingURL=integer.js.map","import { Schema, } from '../core.js';\n/**\n * Schema that only accepts a specific literal value.\n *\n * Validates that the input is exactly equal to the specified value using\n * strict equality (===).\n *\n * @template TValue - The literal type (null, string, number, or boolean)\n *\n * @example\n * ```ts\n * const schema = new LiteralSchema('admin')\n * schema.validate('admin') // success\n * schema.validate('user') // fails\n * ```\n */\nexport class LiteralSchema extends Schema {\n constructor(value) {\n super();\n this.type = 'literal';\n this.value = value;\n }\n validateInContext(input, ctx) {\n if (input !== this.value) {\n return ctx.issueInvalidValue(input, [this.value]);\n }\n return ctx.success(this.value);\n }\n}\n/**\n * Creates a literal schema that only accepts the exact specified value.\n *\n * Useful for discriminator fields in unions, constant values, or type narrowing.\n *\n * @param value - The exact value that must be matched\n * @returns A new {@link LiteralSchema} instance\n *\n * @example\n * ```ts\n * // String literal\n * const roleSchema = l.literal('admin')\n *\n * // Number literal\n * const versionSchema = l.literal(1)\n *\n * // Boolean literal\n * const enabledSchema = l.literal(true)\n *\n * // Null literal\n * const nullSchema = l.literal(null)\n *\n * // In discriminated unions\n * const actionSchema = l.discriminatedUnion('type', [\n * l.object({ type: l.literal('create'), data: l.unknown() }),\n * l.object({ type: l.literal('delete'), id: l.string() }),\n * ])\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function literal(value) {\n return new LiteralSchema(value);\n}\n//# sourceMappingURL=literal.js.map","import { isPlainObject } from '@atproto/lex-data';\nimport { Schema, } from '../core.js';\nimport { lazyProperty } from '../util/lazy-property.js';\n/**\n * Schema for validating objects with a defined shape.\n *\n * Each property in the shape is validated against its corresponding schema.\n * Properties wrapped in `optional()` are not required.\n *\n * @template TShape - The object shape type mapping property names to validators\n *\n * @example\n * ```ts\n * const schema = new ObjectSchema({\n * name: l.string(),\n * age: l.optional(l.integer()),\n * })\n * const result = schema.validate({ name: 'Alice' })\n * ```\n */\nexport class ObjectSchema extends Schema {\n constructor(shape) {\n super();\n this.type = 'object';\n this.shape = shape;\n }\n get validatorsMap() {\n const map = new Map(Object.entries(this.shape));\n return lazyProperty(this, 'validatorsMap', map);\n }\n validateInContext(input, ctx) {\n if (!isPlainObject(input)) {\n return ctx.issueUnexpectedType(input, 'object');\n }\n // Lazily copy value\n let copy;\n for (const [key, propDef] of this.validatorsMap) {\n const result = ctx.validateChild(input, key, propDef);\n if (!result.success) {\n if (!(key in input)) {\n // Transform into \"required key\" issue\n return ctx.issueRequiredKey(input, key);\n }\n return result;\n }\n // Skip copying if key is not present in input (and value is undefined)\n if (result.value === undefined && !(key in input)) {\n continue;\n }\n if (!Object.is(result.value, input[key])) {\n if (ctx.options.mode === 'validate') {\n // In \"validate\" mode, we can't modify the input, so we issue an error\n return ctx.issueInvalidPropertyValue(input, key, [result.value]);\n }\n copy ??= { ...input };\n copy[key] = result.value;\n }\n }\n return ctx.success(copy ?? input);\n }\n}\n/**\n * Creates an object schema with the specified property validators.\n *\n * Validates that the input is a plain object and each property matches\n * its corresponding schema. Properties wrapped in `optional()` are not required.\n *\n * @param properties - Object mapping property names to their validators\n * @returns A new {@link ObjectSchema} instance\n *\n * @example\n * ```ts\n * // Basic object\n * const userSchema = l.object({\n * name: l.string(),\n * email: l.string({ format: 'uri' }),\n * })\n *\n * // With optional properties\n * const profileSchema = l.object({\n * displayName: l.string(),\n * bio: l.optional(l.string({ maxLength: 256 })),\n * avatar: l.optional(l.blob({ accept: ['image/*'] })),\n * })\n *\n * // Nested objects\n * const postSchema = l.object({\n * text: l.string(),\n * author: l.object({\n * did: l.string({ format: 'did' }),\n * handle: l.string({ format: 'handle' }),\n * }),\n * })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function object(properties) {\n return new ObjectSchema(properties);\n}\n//# sourceMappingURL=object.js.map","import { $type, Schema, } from '../core.js';\n/**\n * Schema for Lexicon token values.\n *\n * Tokens are named constants in Lexicon, identified by their NSID and hash.\n * They validate to their string value (e.g., 'app.bsky.feed.defs#requestLess').\n * TokenSchema instances can also be used as values themselves.\n *\n * @template TValue - The token string literal type\n *\n * @example\n * ```ts\n * const schema = new TokenSchema('app.bsky.feed.defs#requestLess')\n * schema.validate('app.bsky.feed.defs#requestLess') // success\n * ```\n */\nexport class TokenSchema extends Schema {\n constructor(value) {\n super();\n this.type = 'token';\n this.value = value;\n }\n get $token() {\n return this.value;\n }\n validateInContext(input, ctx) {\n if (input === this.value) {\n return ctx.success(this.value);\n }\n // @NOTE: allow using the token instance itself (but convert to the actual\n // token value)\n if (ctx.options.mode === 'parse' &&\n input instanceof TokenSchema &&\n input.value === this.value) {\n return ctx.success(this.value);\n }\n if (typeof input !== 'string') {\n return ctx.issueUnexpectedType(input, 'token');\n }\n return ctx.issueInvalidValue(input, [this.value]);\n }\n // When using the TokenSchema instance as data, let's serialize it to the\n // token value\n toJSON() {\n return this.value;\n }\n toString() {\n return this.value;\n }\n}\n/**\n * Creates a token schema for Lexicon named constants.\n *\n * Tokens are used in Lexicon as named constants or enum-like values.\n * The token instance can be used both as a schema validator and as\n * the token value itself (it serializes to its string value).\n *\n * @param nsid - The NSID part of the token\n * @param hash - The hash part of the token (defaults to 'main')\n * @returns A new {@link TokenSchema} instance\n *\n * @example\n * ```ts\n * // Define tokens\n * const requestLess = l.token('app.bsky.feed.defs', 'requestLess')\n * const requestMore = l.token('app.bsky.feed.defs', 'requestMore')\n *\n * // Use as a value\n * console.log(requestLess.toString()) // 'app.bsky.feed.defs#requestLess'\n *\n * // Use in union for validation\n * const feedbackSchema = l.union([requestLess, requestMore])\n *\n * // Validate\n * feedbackSchema.parse('app.bsky.feed.defs#requestLess') // success\n *\n * // Token instances can be used as values in other schemas\n * const feedbackRequest = l.object({\n * feedback: requestLess, // Accepts the token value\n * })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function token(nsid, hash = 'main') {\n return new TokenSchema($type(nsid, hash));\n}\n//# sourceMappingURL=token.js.map","import { graphemeLen, ifCid, isWellFormedString, utf8Len, } from '@atproto/lex-data';\nimport { IssueCustom, Schema, isStringFormat, } from '../core.js';\nimport { memoizedOptions } from '../util/memoize.js';\nimport { TokenSchema } from './token.js';\n/**\n * Schema for validating string values with optional format and length constraints.\n *\n * Supports various string formats defined in the Lexicon specification, as well as\n * length constraints measured in UTF-8 bytes or grapheme clusters.\n *\n * @template TOptions - The configuration options type\n *\n * @example\n * ```ts\n * const schema = new StringSchema({ format: 'datetime', maxLength: 64 })\n * const result = schema.validate('2024-01-15T10:30:00Z')\n * ```\n */\nexport class StringSchema extends Schema {\n constructor(options) {\n super();\n this.type = 'string';\n this.options = options;\n }\n validateInContext(input, ctx) {\n const str = coerceToString(input);\n if (str == null || (str !== input && ctx.options.mode !== 'parse')) {\n return ctx.issueUnexpectedType(input, 'string');\n }\n // A lone surrogate has no UTF-8 encoding (it would be replaced by U+FFFD\n // when serialized).\n if (!isWellFormedString(str)) {\n return ctx.issue(new IssueCustom(ctx.path, str, 'String contains a lone surrogate'));\n }\n let lazyUtf8Len;\n const minLength = this.options.minLength;\n if (minLength != null) {\n if ((lazyUtf8Len ??= utf8Len(str)) < minLength) {\n return ctx.issueTooSmall(str, 'string', minLength, lazyUtf8Len);\n }\n }\n const maxLength = this.options.maxLength;\n if (maxLength != null) {\n // Optimization: we can avoid computing the UTF-8 length if the maximum\n // possible length, in bytes, of the input JS string is smaller than the\n // maxLength (in UTF-8 string bytes).\n if (str.length * 3 <= maxLength) {\n // Input string so small it can't possibly exceed maxLength\n }\n else if ((lazyUtf8Len ??= utf8Len(str)) > maxLength) {\n return ctx.issueTooBig(str, 'string', maxLength, lazyUtf8Len);\n }\n }\n // Optimization: count graphemes once\n let lazyGraphLen;\n const minGraphemes = this.options.minGraphemes;\n if (minGraphemes != null) {\n if (str.length < minGraphemes) {\n // If the JavaScript string length (UTF-16) is below the minimal limit,\n // its grapheme length (which <= .length) will also be below.\n // Fail early.\n return ctx.issueTooSmall(str, 'grapheme', minGraphemes, str.length);\n }\n else if ((lazyGraphLen ??= graphemeLen(str)) < minGraphemes) {\n return ctx.issueTooSmall(str, 'grapheme', minGraphemes, lazyGraphLen);\n }\n }\n const maxGraphemes = this.options.maxGraphemes;\n if (maxGraphemes != null) {\n if (str.length <= maxGraphemes) {\n // If the JavaScript string length (UTF-16) is within the maximum limit,\n // its grapheme length (which <= .length) will also be within.\n }\n else if ((lazyGraphLen ??= graphemeLen(str)) > maxGraphemes) {\n return ctx.issueTooBig(str, 'grapheme', maxGraphemes, lazyGraphLen);\n }\n }\n const format = this.options.format;\n if (format != null && !isStringFormat(str, format, ctx.options)) {\n return ctx.issueInvalidFormat(str, format);\n }\n return ctx.success(str);\n }\n}\nexport function coerceToString(input) {\n switch (typeof input) {\n // @NOTE We do *not* coerce numbers/booleans to strings because that can\n // lead to them being accepted as string instead of being coerced to\n // number/boolean when the input is a string and the expected result is\n // number/boolean (e.g. in params).\n case 'string':\n return input;\n case 'object': {\n if (input == null)\n return null;\n // @NOTE Allow using TokenSchema instances in places expecting strings,\n // converting them to their string value.\n if (input instanceof TokenSchema) {\n return input.toString();\n }\n if (input instanceof Date) {\n if (Number.isNaN(input.getTime()))\n return null;\n return input.toISOString();\n }\n if (input instanceof URL) {\n return input.toString();\n }\n const cid = ifCid(input);\n if (cid)\n return cid.toString();\n if (input instanceof String) {\n return input.valueOf();\n }\n }\n // falls through\n default:\n return null;\n }\n}\n/**\n * Creates a string schema with optional format and length constraints.\n *\n * Strings can be validated against various formats (datetime, uri, did, handle, etc.)\n * and constrained by length in UTF-8 bytes or grapheme clusters.\n *\n * @param options - Optional configuration for format and length constraints\n * @returns A new {@link StringSchema} instance\n *\n * @example\n * ```ts\n * // Basic string\n * const nameSchema = l.string()\n *\n * // With format validation\n * const dateSchema = l.string({ format: 'datetime' })\n *\n * // With length constraints (UTF-8 bytes)\n * const bioSchema = l.string({ maxLength: 256 })\n *\n * // With grapheme constraints (user-perceived characters)\n * const displayNameSchema = l.string({ maxGraphemes: 64 })\n *\n * // Combining constraints\n * const handleSchema = l.string({ format: 'handle', minLength: 3, maxLength: 253 })\n * ```\n */\nexport const string = /*#__PURE__*/ memoizedOptions((options = {}) => new StringSchema(options));\n//# sourceMappingURL=string.js.map","import { l } from '@atproto/lex-schema';\nexport const COMMIT_VERSION = 1;\n// The maximum size of a record's DRISL encoding.\nexport const MAX_RECORD_SIZE = 1024 * 1024; // 1 MiB\n// Matches `com.atproto.space.defs#commit`.\nconst commitSchema = l.object({\n ver: l.integer(),\n repo: l.string({ format: 'did' }),\n space: l.string({ format: 'space-ref' }),\n rev: l.string({ format: 'tid' }),\n data: l.bytes(),\n});\nexport const REPO_STAR_TYPE = 'atproto-space-repo';\nexport const REPO_STAR_LIMITS = {\n maxMetaLength: 64 * 1024, // 64 KiB\n maxKeyLength: 4 * 1024, // 4 KiB\n maxValueLength: MAX_RECORD_SIZE,\n};\n// The metadata of a repo's STAR archive: the repo's commit, typed by its profile.\nconst repoStarMetaSchema = l.object({\n $type: l.literal(REPO_STAR_TYPE),\n ...commitSchema.shape,\n});\nexport const SPACE_META_STAR_TYPE = 'atproto-space-meta';\nexport const SPACE_META_VERSION = 1;\nexport const SPACE_META_STAR_LIMITS = {\n maxMetaLength: 64 * 1024, // 64 KiB\n maxKeyLength: 4 * 1024, // 4 KiB\n maxValueLength: 1024 * 1024, // 1 MiB\n};\n// The metadata of a space meta archive.\nconst spaceMetaStarMetaSchema = l.object({\n $type: l.literal(SPACE_META_STAR_TYPE),\n ver: l.literal(SPACE_META_VERSION),\n space: l.string({ format: 'space-ref' }),\n});\n// A repo in the writer set, as listWriters reports it. Keyed by the repo's DID.\nconst spaceMetaWriterSchema = l.object({\n repoRev: l.string({ format: 'tid' }),\n data: l.bytes(),\n spaceRev: l.string({ format: 'tid' }),\n});\nexport const defs = {\n repoStarMeta: {\n name: 'repo metadata',\n schema: repoStarMetaSchema,\n },\n spaceMetaStarMeta: {\n name: 'space meta archive metadata',\n schema: spaceMetaStarMetaSchema,\n },\n spaceMetaWriter: {\n name: 'writer',\n schema: spaceMetaWriterSchema,\n },\n};\n//# sourceMappingURL=types.js.map","import { isValidNsid, isValidRecordKey, } from '@atproto/syntax';\nimport { SpaceRepoVerificationError } from './error.js';\nexport function formatRecordPath(collection, rkey) {\n return `${collection}/${rkey}`;\n}\nexport function parseRecordPath(path) {\n const { length, 0: collection, 1: rkey } = path.split('/');\n if (length !== 2) {\n throw new SpaceRepoVerificationError(`invalid record path: ${path}`);\n }\n if (!isValidNsid(collection)) {\n throw new SpaceRepoVerificationError(`invalid NSID in record path: ${path}`);\n }\n if (!isValidRecordKey(rkey)) {\n throw new SpaceRepoVerificationError(`invalid record key in record path: ${path}`);\n }\n return { collection, rkey };\n}\n// The element a record contributes to a repo's set hash.\nexport function formatSetHashElement(collection, rkey, cid) {\n const path = formatRecordPath(collection, rkey);\n return `${path}/${cid.toString()}`;\n}\n//# sourceMappingURL=util.js.map","import { ui8Equals } from '@atproto/lex-data';\nimport { SpaceRepoVerificationError } from './error.js';\nimport { LtHash } from './lthash.js';\nimport { verifyCommitMac } from './mac.js';\nimport { COMMIT_VERSION, } from './types.js';\nimport { formatSetHashElement } from './util.js';\nexport class RepoCommit {\n constructor(setHash = new LtHash()) {\n this.setHash = setHash;\n }\n // nullish state yields an empty repo\n static fromState(state) {\n return new RepoCommit(new LtHash(state));\n }\n static fromRecords(records) {\n const commit = new RepoCommit();\n for (const { collection, rkey, cid } of records) {\n commit.add(collection, rkey, cid);\n }\n return commit;\n }\n add(collection, rkey, cid) {\n this.setHash.add(formatSetHashElement(collection, rkey, cid));\n return this;\n }\n remove(collection, rkey, cid) {\n this.setHash.remove(formatSetHashElement(collection, rkey, cid));\n return this;\n }\n applyOp(op) {\n if (op.prev)\n this.remove(op.collection, op.rkey, op.prev);\n if (op.cid)\n this.add(op.collection, op.rkey, op.cid);\n return this;\n }\n applyOps(ops) {\n for (const op of ops) {\n this.applyOp(op);\n }\n return this;\n }\n /**\n * Whether this repo's contents match a commit. Verify the commit first โ on its\n * own this says nothing about authenticity.\n */\n matches(commit) {\n return ui8Equals(this.setHash.digest(), commit.data);\n }\n /**\n * Build a commit over the current contents. A commit carries no signature: the\n * repo host authenticates it to each syncer with a MAC (see `mac.ts`).\n */\n toCommit(ctx) {\n return {\n ver: COMMIT_VERSION,\n repo: ctx.repo,\n space: ctx.space,\n rev: ctx.rev,\n data: this.setHash.digest(),\n };\n }\n}\n/**\n * Verify a commit against the MAC its response carried. Once this passes, `data`\n * is trusted as the author's claim about their repo, which is what makes\n * {@link RepoCommit#matches} meaningful.\n *\n * @throws {SpaceRepoVerificationError} if the commit is not for the requested\n * space and repo, or has an unsupported version\n * @throws {SpaceMacError} if the MAC does not match\n */\nexport function verifyCommit(commit, params) {\n if (commit.ver !== COMMIT_VERSION) {\n throw new SpaceRepoVerificationError(`unsupported commit version: ${commit.ver}`);\n }\n if (commit.repo !== params.repo) {\n throw new SpaceRepoVerificationError(`commit is for another repo: ${commit.repo}`);\n }\n if (commit.space !== params.space) {\n throw new SpaceRepoVerificationError(`commit is for another space: ${commit.space}`);\n }\n verifyCommitMac(commit, params);\n}\n//# sourceMappingURL=repo-commit.js.map","// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\n// Types that reach getObjectType() - excludes types with fast-paths above:\n// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)\nconst objectTypeNames = [\n 'Object', // for Object.create(null) and other non-plain objects\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {\n return typeOf\n }\n /* c8 ignore next 3 */\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n // Also catches Node.js Buffer which extends Uint8Array\n if (value instanceof Uint8Array) {\n return 'Uint8Array'\n }\n // Fast path for plain objects (most common case after primitives/arrays/bytes)\n if (value.constructor === Object) {\n return 'Object'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n /* c8 ignore next */\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n /* c8 ignore next */\n return undefined\n}\n","class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n /* c8 ignore next 1 */\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n\n /**\n * Check equality between two Type instances. Safe to use across different\n * copies of the Type class (e.g., when bundlers duplicate the module).\n * (major, name) uniquely identifies a Type; terminal is implied by these.\n * @param {Type} a\n * @param {Type} b\n * @returns {boolean}\n */\n static equals (a, b) {\n return a === b || (a.major === b.major && a.name === b.name)\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n","// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {Uint8Array|number[]} buf\n * @returns {Uint8Array}\n */\nexport function asU8A (buf) {\n /* c8 ignore next */\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\n// Threshold for manual UTF-8 encoding vs native methods.\n// Node.js Buffer.from: crossover ~24 chars\n// Browser TextEncoder: crossover ~200 chars\nconst FROM_STRING_THRESHOLD_BUFFER = 24\nconst FROM_STRING_THRESHOLD_TEXTENCODER = 200\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length >= FROM_STRING_THRESHOLD_BUFFER\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n /* c8 ignore next 7 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {Uint8Array}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n // Buffer.slice() returns a view, not a copy, so we need special handling\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n /* c8 ignore next 9 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n /* c8 ignore next 1 */\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n // this case is occasionally missed during test runs so becomes coverage-flaky\n /* c8 ignore next 4 */\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return asU8A(globalThis.Buffer.concat(chunks, length))\n }\n /* c8 ignore next 19 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n /* c8 ignore next 8 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n /* c8 ignore next 12 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n /* c8 ignore next 17 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n /* c8 ignore next */\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n /* c8 ignore next 5 */\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n } /* c8 ignore next 3 */\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n if ((c >= 0xD800) && (c <= 0xDFFF)) {\n c = 0xFFFD // Unpaired Surrogate\n }\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n /* c8 ignore next 10 */\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n","/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(Uint8Array|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {Uint8Array|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n /* c8 ignore next 2 */\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n\n/**\n * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.\n * It provides the same interface as Bl but writes to a fixed destination.\n */\nexport class U8Bl {\n /**\n * @param {Uint8Array} dest\n */\n constructor (dest) {\n this.dest = dest\n /** @type {number} */\n this.cursor = 0\n // chunks is for interface compatibility with Bl - encode.js checks chunks.length\n // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].\n /** @type {Uint8Array[]} */\n this.chunks = [dest]\n }\n\n reset () {\n this.cursor = 0\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n if (this.cursor + bytes.length > this.dest.length) {\n throw new Error('write out of bounds, destination buffer is too small')\n }\n this.dest.set(bytes, this.cursor)\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n const byts = this.dest.subarray(0, this.cursor)\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n","const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n","/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeUint (writer, token) {\n return encodeUintValue(writer, 0, token.value)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (writer, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n writer.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n writer.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n writer.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n writer.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0\n}\n","/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeNegint (writer, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n /* c8 ignore next 4 */\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0\n}\n","import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = data.slice(pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeBytes (writer, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)\n writer.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n","import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\n\nconst textDecoder = new TextDecoder()\n\n// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for\n// map keys) are faster to decode with a simple loop than TextDecoder overhead.\nconst ASCII_THRESHOLD = 32\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),\n * a simple loop is faster than TextDecoder.\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n * @returns {string}\n */\nfunction toStr (bytes, start, end) {\n const len = end - start\n if (len < ASCII_THRESHOLD) {\n let str = ''\n for (let i = start; i < end; i++) {\n const c = bytes[i]\n if (c & 0x80) { // non-ASCII, fall back to TextDecoder\n return textDecoder.decode(bytes.subarray(start, end))\n }\n str += String.fromCharCode(c)\n }\n return str\n }\n return textDecoder.decode(bytes.subarray(start, end))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = data.slice(pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeArray (writer, token) {\n uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeMap (writer, token) {\n uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n */\nexport function encodeTag (writer, token) {\n uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n","// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { encodeUint } from './0uint.js'\n\n/**\n * @typedef {import('../interface').ByteWriter} ByteWriter\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n */\n\nexport const MINOR_FALSE = 20\nexport const MINOR_TRUE = 21\nexport const MINOR_NULL = 22\nexport const MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (writer, token, options) {\n const float = token.value\n\n if (float === false) {\n writer.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n writer.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n writer.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n writer.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n writer.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n writer.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n /* c8 ignore next 6 */\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n /* c8 ignore next 6 */\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n /* c8 ignore next 4 */\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @param {Token} _tok1\n * @param {Token} _tok2\n * @returns {number}\n */\nencodeFloat.compareTokens = encodeUint.compareTokens\n/*\nencodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {\n return _tok1\n throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)\n}\n*/\n","import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {Uint8Array|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n","import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl, U8Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A, compare, fromString } from './byte-utils.js'\n\nimport { encodeUint, encodeUintValue } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface').Reference} Reference\n * @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n * @typedef {import('../interface').ByteWriter} ByteWriter\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @type {EncodeOptions} */\nexport const rfc8949EncodeOptions = Object.freeze({\n float64: true,\n mapSorter: rfc8949MapSorter,\n quickEncodeToken\n})\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst defaultWriter = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const maxLength = isMap ? obj.size : keys.length\n\n /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */\n let entries\n\n if (maxLength) {\n // Pre-allocate the array with the expected size\n entries = new Array(maxLength)\n refStack = Ref.createCheck(refStack, obj)\n const skipUndefined = !isMap && options.ignoreUndefinedProperties\n\n let i = 0\n for (const key of keys) {\n const value = isMap ? obj.get(key) : obj[key]\n if (skipUndefined && value === undefined) {\n continue\n }\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(value, options, refStack)\n ]\n }\n\n // Truncate only if properties were skipped\n if (i < maxLength) {\n entries.length = i\n }\n }\n\n if (!entries?.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, entries.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, entries.length), entries]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter)\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n /* c8 ignore next 2 */\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key types\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)\n /* c8 ignore next 5 */\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx\n *\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction rfc8949MapSorter (e1, e2) {\n if (e1[0] instanceof Token && e2[0] instanceof Token) {\n const t1 = /** @type {TokenEx} */ (e1[0])\n const t2 = /** @type {TokenEx} */ (e2[0])\n\n if (!t1._keyBytes) {\n t1._keyBytes = encodeRfc8949(t1.value)\n }\n\n if (!t2._keyBytes) {\n t2._keyBytes = encodeRfc8949(t2.value)\n }\n\n return compare(t1._keyBytes, t2._keyBytes)\n }\n\n throw new Error('rfc8949MapSorter: complex key types are not supported yet')\n}\n\n/**\n * @param {any} data\n * @returns {Uint8Array}\n */\nfunction encodeRfc8949 (data) {\n return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)\n}\n\n/**\n * @param {ByteWriter} writer\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (writer, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(writer, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](writer, tokens, options)\n }\n}\n\n// CBOR major type prefixes, cached from Type for hot path performance\nconst MAJOR_UINT = Type.uint.majorEncoded\nconst MAJOR_NEGINT = Type.negint.majorEncoded\nconst MAJOR_BYTES = Type.bytes.majorEncoded\nconst MAJOR_STRING = Type.string.majorEncoded\nconst MAJOR_ARRAY = Type.array.majorEncoded\n\n// Simple value bytes (CBOR major type 7 + minor value)\nconst SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE\nconst SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE\nconst SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL\nconst SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * Check if direct encoding can be used for the given options.\n * Direct encoding bypasses token creation for most values.\n * @param {EncodeOptions} options\n * @returns {boolean}\n */\nfunction canDirectEncode (options) {\n // Cannot use direct encode with addBreakTokens (needs special break token handling).\n // Direct encode checks typeEncoders per-value, falling back to tokens as needed.\n // Maps fall back to token-based encoding for efficient key sorting.\n return options.addBreakTokens !== true\n}\n\n/**\n * Direct encode a value to the writer, bypassing token creation for most types.\n * Falls back to token-based encoding for custom type encoders.\n * @param {ByteWriter} writer\n * @param {any} data\n * @param {EncodeOptions} options\n * @param {Reference|undefined} refStack\n */\nfunction directEncode (writer, data, options, refStack) {\n const typ = is(data)\n\n // Check for custom encoder for THIS specific type\n const customEncoder = options.typeEncoders && options.typeEncoders[typ]\n if (customEncoder) {\n const tokens = customEncoder(data, typ, options, refStack)\n if (tokens != null) {\n // Custom encoder returned tokens, serialize immediately\n tokensToEncoded(writer, tokens, cborEncoders, options)\n return\n }\n // Custom encoder returned null, fall through to default handling\n }\n\n // Direct encode based on type\n switch (typ) {\n case 'null':\n writer.push([SIMPLE_NULL])\n return\n\n case 'undefined':\n writer.push([SIMPLE_UNDEFINED])\n return\n\n case 'boolean':\n writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])\n return\n\n case 'number':\n if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {\n // Float, use token encoder for complex float encoding\n encodeFloat(writer, new Token(Type.float, data), options)\n } else if (data >= 0) {\n encodeUintValue(writer, MAJOR_UINT, data)\n } else {\n // Negative integer\n encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)\n }\n return\n\n case 'bigint':\n if (data >= BigInt(0)) {\n encodeUintValue(writer, MAJOR_UINT, data)\n } else {\n encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)\n }\n return\n\n case 'string': {\n const bytes = fromString(data)\n encodeUintValue(writer, MAJOR_STRING, bytes.length)\n writer.push(bytes)\n return\n }\n\n case 'Uint8Array':\n encodeUintValue(writer, MAJOR_BYTES, data.length)\n writer.push(data)\n return\n\n case 'Array':\n if (!data.length) {\n writer.push([MAJOR_ARRAY]) // Empty array: 0x80\n return\n }\n refStack = Ref.createCheck(refStack, data)\n encodeUintValue(writer, MAJOR_ARRAY, data.length)\n for (const elem of data) {\n directEncode(writer, elem, options, refStack)\n }\n return\n\n case 'Object':\n case 'Map':\n // Maps require key sorting, use token-based encoding for efficiency\n // (pre-encoding all keys for sorting is expensive)\n {\n const tokens = typeEncoders.Object(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n return\n\n default:\n // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)\n {\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n const tokens = typeEncoder(data, typ, options, refStack)\n tokensToEncoded(writer, tokens, cborEncoders, options)\n }\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @param {Uint8Array} [destination]\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options, destination) {\n // arg ordering is different to encodeInto for backward compatibility\n const hasDest = destination instanceof Uint8Array\n let writeTo = hasDest ? new U8Bl(destination) : defaultWriter\n\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n if (hasDest) {\n // Copy quick bytes into destination buffer\n writeTo.push(quickBytes)\n return writeTo.toBytes()\n }\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n if (!hasDest) {\n writeTo = new Bl(size)\n }\n encoder(writeTo, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (writeTo.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])\n }\n }\n writeTo.reset()\n tokensToEncoded(writeTo, tokens, encoders, options)\n return writeTo.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n defaultWriter.reset()\n directEncode(defaultWriter, data, options, undefined)\n return defaultWriter.toBytes(true)\n }\n\n return encodeCustom(data, cborEncoders, options)\n}\n\n/**\n * @param {any} data\n * @param {Uint8Array} destination\n * @param {EncodeOptions} [options]\n * @returns {{ written: number }}\n */\nfunction encodeInto (data, destination, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n\n // Use direct encode path when possible\n if (canDirectEncode(options)) {\n const writer = new U8Bl(destination)\n directEncode(writer, data, options, undefined)\n return { written: writer.toBytes().length }\n }\n\n const result = encodeCustom(data, cborEncoders, options, destination)\n return { written: result.length }\n}\n\nexport { objectToTokens, encode, encodeCustom, encodeInto, Ref }\n","import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n /* c8 ignore next 4 */\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (!useMaps && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (rejectDuplicateMapKeys) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (Type.equals(token.type, Type.break)) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (Type.equals(token.type, Type.array)) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.map)) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (Type.equals(token.type, Type.tag)) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options)\n return options.tags[token.value](tagged)\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n /* c8 ignore next */\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n // Convert Buffer to plain Uint8Array for faster slicing in decode path\n const u8aData = asU8A(data)\n const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n","import { Token, Type, decode as cborgDecode, decodeFirst as cborgDecodeFirst, encode as cborgEncode, } from 'cborg';\nimport { decodeCid, ifCid } from '@atproto/lex-data';\n// @NOTE cborg is an implementation detail of this module and must not leak into\n// the public API\nconst CID_CBOR_TAG = 42;\n/**\n * Configuration options for CBOR encoding that enforces AT Protocol data model\n * constraints.\n *\n * This configuration ensures:\n * - CIDs are encoded using CBOR tag 42 with a leading 0x00 byte prefix\n * - Map keys must be strings (no numeric or other key types allowed)\n * - `undefined` values are not permitted (undefined object properties will be stripped)\n * - Only safe integer numbers are allowed (no floats or non-integer values)\n */\nconst encodeOptions = {\n float64: true,\n ignoreUndefinedProperties: true,\n typeEncoders: {\n Map: (map) => {\n for (const key of map.keys()) {\n if (typeof key !== 'string') {\n throw new Error('Only string keys are allowed in CBOR \"map\" by the AT Data Model');\n }\n }\n // @NOTE Maps will be encoded as CBOR \"map\", which will be decoded as object.\n return null;\n },\n Object: (obj) => {\n const cid = ifCid(obj);\n if (cid) {\n const bytes = new Uint8Array(cid.bytes.byteLength + 1);\n bytes.set(cid.bytes, 1); // prefix is 0x00, for historical reasons\n return [new Token(Type.tag, CID_CBOR_TAG), new Token(Type.bytes, bytes)];\n }\n // Fallback to default object encoder\n return null;\n },\n undefined: () => {\n throw new Error('`undefined` is not supported by the AT Data Model');\n },\n number: (num) => {\n if (Number.isSafeInteger(num))\n return null;\n throw new Error(`Non-integer numbers (${num}) are not supported by the AT Data Model`);\n },\n },\n};\n/**\n * Configuration options for CBOR decoding that enforces AT Protocol data model\n * constraints.\n */\nconst decodeOptions = {\n allowIndefinite: false,\n coerceUndefinedToNull: true,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true,\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n tags: /*#__PURE__*/ Object.assign([], {\n [CID_CBOR_TAG]: (bytes) => {\n if (bytes[0] !== 0) {\n throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00');\n }\n const cibBytes = bytes.subarray(1); // ignore leading 0x00\n return decodeCid(cibBytes);\n },\n }),\n};\n/**\n * Encodes a LexValue to CBOR bytes using the AT Protocol data model (DRISL format).\n *\n * @param data - The LexValue to encode\n * @returns The CBOR-encoded bytes\n * @throws {Error} If the data contains non-string map keys, undefined values, or non-integer numbers\n *\n * @example\n * ```typescript\n * import { encode } from '@atproto/lex-cbor'\n *\n * // Encode a simple object\n * const bytes = encode({ text: 'Hello', count: 42 })\n *\n * // Encode an AT Protocol record\n * const recordBytes = encode({\n * $type: 'app.bsky.feed.post',\n * text: 'Hello from AT Protocol!',\n * createdAt: new Date().toISOString(),\n * })\n * ```\n */\nexport function encode(data) {\n return cborgEncode(data, encodeOptions);\n}\n/**\n * Decodes CBOR bytes to a LexValue using the AT Protocol data model (DRISL format).\n *\n * @typeParam T - Allows casting the decoded values to a specific LexValue subtype\n * @param bytes - The CBOR bytes to decode\n * @returns The decoded LexValue\n * @throws {Error} If the bytes are not valid CBOR or violate AT Protocol constraints\n *\n * @example\n * ```typescript\n * import { encode, decode } from '@atproto/lex-cbor'\n * import type { LexValue } from '@atproto/lex'\n *\n * // Round-trip encoding and decoding\n * const original = { text: 'Hello', count: 42 }\n * const bytes = encode(original)\n * const decoded: LexValue = decode(bytes)\n *\n * // Decode with a specific type\n * interface Post {\n * $type: string\n * text: string\n * createdAt: string\n * }\n * const post = decode<Post>(recordBytes)\n * ```\n */\nexport function decode(bytes) {\n return cborgDecode(bytes, decodeOptions);\n}\n/**\n * Generator that yields multiple decoded LexValues from a buffer containing\n * concatenated CBOR-encoded values.\n *\n * This is useful for processing streams or files containing multiple\n * CBOR-encoded records back-to-back (e.g., CAR file blocks or event streams).\n *\n * @typeParam T - Allows casting the decoded values to a specific LexValue subtype\n * @param data - The buffer containing one or more CBOR-encoded values\n * @yields Decoded LexValues one at a time\n * @throws {Error} If any value in the buffer is not valid CBOR or violates AT Protocol constraints\n *\n * @example\n * ```typescript\n * import { encode, decodeAll } from '@atproto/lex-cbor'\n *\n * // Concatenate multiple encoded values\n * const bytes1 = encode({ id: 1, text: 'First' })\n * const bytes2 = encode({ id: 2, text: 'Second' })\n * const combined = new Uint8Array([...bytes1, ...bytes2])\n *\n * // Decode all values from the combined buffer\n * for (const value of decodeAll(combined)) {\n * console.log(value)\n * }\n * // Output:\n * // { id: 1, text: 'First' }\n * // { id: 2, text: 'Second' }\n * ```\n */\nexport function* decodeAll(data) {\n do {\n const [result, remainingBytes] = cborgDecodeFirst(data, decodeOptions);\n yield result;\n data = remainingBytes;\n } while (data.byteLength > 0);\n}\n//# sourceMappingURL=encoding.js.map","import { cidForCbor } from '@atproto/lex-data';\nimport { encode } from './encoding.js';\nexport { decode, decodeAll, encode } from './encoding.js';\nexport { decode as cborDecode, decodeAll as cborDecodeAll, encode as cborEncode, } from './encoding.js';\n/**\n * Computes a CID (Content Identifier) for a given LexValue.\n *\n * This function first encodes the value to CBOR bytes using the AT Protocol\n * data model constraints, then computes the CID hash of those bytes. The\n * resulting CID can be used to uniquely identify and reference the content.\n *\n * @param value - The LexValue to compute a CID for\n * @returns A promise that resolves to the CID for the CBOR-encoded value\n *\n * @example\n * ```typescript\n * import { cidForLex } from '@atproto/lex-cbor'\n *\n * const record = {\n * $type: 'app.bsky.feed.post',\n * text: 'Hello, AT Protocol!',\n * createdAt: new Date().toISOString(),\n * }\n *\n * const cid = await cidForLex(record)\n * console.log(cid.toString()) // e.g., 'bafyreih...'\n * ```\n */\nexport async function cidForLex(value) {\n return cidForCbor(encode(value));\n}\n//# sourceMappingURL=index.js.map","export class StarParseError extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = 'StarParseError';\n }\n}\n//# sourceMappingURL=error.js.map","import { ui8Concat } from '@atproto/lex-data';\n/**\n * Reads exact numbers of bytes from a stream of chunks, whatever their sizes.\n */\nexport class BytesReader {\n constructor(input) {\n // Bytes received but not yet read.\n this.buffer = new Uint8Array();\n this.ended = false;\n this.iterator =\n Symbol.asyncIterator in input\n ? input[Symbol.asyncIterator]()\n : input[Symbol.iterator]();\n }\n /** Read `length` bytes, or fewer if the input ends first. */\n async read(length) {\n const chunks = [this.buffer];\n let bufferedLength = this.buffer.length;\n while (bufferedLength < length && !this.ended) {\n const next = await this.iterator.next();\n if (next.done) {\n this.ended = true;\n }\n else {\n chunks.push(next.value);\n bufferedLength += next.value.length;\n }\n }\n const bytes = chunks.length === 1 ? chunks[0] : ui8Concat(chunks);\n this.buffer = bytes.subarray(length);\n return bytes.subarray(0, length);\n }\n /** Stop reading, closing the input. */\n async destroy() {\n this.buffer = new Uint8Array();\n await this.iterator.return?.();\n }\n}\n//# sourceMappingURL=bytes-reader.js.map","import { decode, encode } from '@atproto/lex-cbor';\nimport { isPlainObject, ui8Equals } from '@atproto/lex-data';\nimport { BytesReader } from './bytes-reader.js';\nimport { StarParseError } from './error.js';\n/**\n * Reading and writing STAR archives: a metadata header, then key/value pairs\n * each preceded by a `0x01` control byte, then a `0x00` control byte to end the\n * archive.\n *\n * ```\n * [ magic | len | meta ] [ 1 | len | key | len | val ] [ 1 | len | key | len | val ] ... [ 0 ]\n * ```\n *\n * Each `len` is an unsigned varint in its shortest form. Applications define\n * what the keys and values mean in a profile, named by the metadata's `$type`.\n *\n * @see https://dasl.ing/star.html\n */\nconst STAR_MAGIC = new Uint8Array([0x2a, 0x6c, 0x01, 0x00]);\nconst CONTROL_PAIR = 0x01;\nconst CONTROL_END = 0x00;\nconst MAX_VARINT_BYTES = 9;\nexport async function* writeStar(meta, pairs) {\n yield STAR_MAGIC;\n yield* frame(encode(meta));\n for await (const { key, value } of pairs) {\n yield Uint8Array.of(CONTROL_PAIR);\n yield* frame(key);\n yield* frame(value);\n }\n yield Uint8Array.of(CONTROL_END);\n}\nfunction* frame(bytes) {\n yield encodeVarint(bytes.length);\n yield bytes;\n}\n/**\n * Read a STAR archive. The header is read eagerly, the pairs lazily as `pairs` is\n * drained.\n *\n * Lengths are checked against the limits in `opts` before a frame is read, so an\n * oversized frame is never buffered.\n */\nexport const readStar = async (input, opts = {}) => {\n const { maxMetaLength = Infinity, maxKeyLength = Infinity, maxValueLength = Infinity, } = opts;\n const reader = new BytesReader(input);\n try {\n const magic = await reader.read(STAR_MAGIC.length);\n if (!ui8Equals(magic, STAR_MAGIC)) {\n throw new StarParseError('invalid magic bytes');\n }\n const metaBytes = await readFrame(reader, maxMetaLength);\n return {\n meta: parseMeta(metaBytes),\n pairs: readPairs(reader, maxKeyLength, maxValueLength),\n [Symbol.asyncDispose]: () => reader.destroy(),\n };\n }\n catch (err) {\n await reader.destroy();\n throw err;\n }\n};\nasync function* readPairs(reader, maxKeyLength, maxValueLength) {\n try {\n while (true) {\n const control = await readByte(reader);\n if (control === CONTROL_END)\n break;\n if (control !== CONTROL_PAIR) {\n throw new StarParseError(`invalid control byte: ${control}`);\n }\n const key = await readFrame(reader, maxKeyLength);\n const value = await readFrame(reader, maxValueLength);\n yield { key, value };\n }\n const trailing = await reader.read(1);\n if (trailing.length > 0) {\n throw new StarParseError('unexpected bytes after end of archive');\n }\n }\n finally {\n await reader.destroy();\n }\n}\nfunction parseMeta(bytes) {\n let meta;\n try {\n meta = decode(bytes);\n }\n catch (cause) {\n throw new StarParseError('invalid metadata', { cause });\n }\n if (!isPlainObject(meta) || typeof meta.$type !== 'string') {\n throw new StarParseError('metadata must be a map with a $type');\n }\n // The decoder accepts some non-canonical forms (such as unsorted map keys),\n // so check that the metadata re-encodes to the same bytes.\n if (!ui8Equals(encode(meta), bytes)) {\n throw new StarParseError('metadata is not canonical DRISL');\n }\n return meta;\n}\nasync function readFrame(reader, maxLength) {\n const length = await readVarint(reader);\n if (length > maxLength) {\n throw new StarParseError(`length ${length} exceeds limit of ${maxLength}`);\n }\n const bytes = await reader.read(length);\n if (bytes.length !== length) {\n throw new StarParseError('unexpected end of archive');\n }\n return bytes;\n}\n// Unsigned varint: 7 bits per byte, least significant group first, with the\n// high bit set on every byte but the last. Arithmetic rather than bitwise\n// operators, since lengths can exceed 32 bits.\nfunction encodeVarint(value) {\n const bytes = [];\n while (value >= 0x80) {\n bytes.push((value % 0x80) | 0x80);\n value = Math.floor(value / 0x80);\n }\n bytes.push(value);\n return Uint8Array.from(bytes);\n}\nasync function readVarint(reader) {\n let value = 0;\n for (let i = 0; i < MAX_VARINT_BYTES; i++) {\n const byte = await readByte(reader);\n value += (byte & 0x7f) * 2 ** (7 * i);\n if (byte < 0x80) {\n // A final zero byte only pads the encoding, which STAR forbids.\n if (byte === 0 && i > 0) {\n throw new StarParseError('non-canonical varint');\n }\n return value;\n }\n }\n throw new StarParseError('varint too long');\n}\nasync function readByte(reader) {\n const [byte] = await reader.read(1);\n if (byte === undefined) {\n throw new StarParseError('unexpected end of archive');\n }\n return byte;\n}\n//# sourceMappingURL=star.js.map","var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n};\nvar __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {\n return function (env) {\n function fail(e) {\n env.error = env.hasError ? new SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n };\n})(typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n});\nimport { decode, encode } from '@atproto/lex-cbor';\nimport { isPlainObject } from '@atproto/lex-data';\nimport { readStar, writeStar } from '@atproto/star';\nimport { isValidDid, } from '@atproto/syntax';\nimport { compareBytes, utf8 } from './bytes.js';\nimport { SpaceMetaArchiveError } from './error.js';\nimport { SPACE_META_STAR_LIMITS, SPACE_META_STAR_TYPE, SPACE_META_VERSION, defs, } from './types.js';\nconst POLICY_KEY = 'policy';\nconst WRITER_KEY_PREFIX = 'writer/';\nconst SECTIONS = ['policy', 'policyState', 'writers'];\n/** Serialize a space meta archive, putting each section into key order. */\nexport async function* writeSpaceMetaStar(archive) {\n const meta = {\n $type: SPACE_META_STAR_TYPE,\n ver: SPACE_META_VERSION,\n space: archive.space,\n };\n const policyState = archive.policyState.map(({ key, value }) => toPair(key, value));\n const writers = archive.writers.map(({ did, ...writer }) => toPair(`${WRITER_KEY_PREFIX}${did}`, writer));\n yield* writeStar(meta, [\n toPair(POLICY_KEY, archive.policy),\n ...sortByKey(policyState),\n ...sortByKey(writers),\n ]);\n}\n/**\n * Read a space meta archive, rejecting it if a length limit is exceeded, a\n * section is missing or out of place, or a key is duplicated or out of order.\n * Read whole, since it holds a space's configuration and writer set rather than\n * its records.\n */\nexport async function readSpaceMetaStar(star) {\n const env_1 = { stack: [], error: void 0, hasError: false };\n try {\n const reader = __addDisposableResource(env_1, await readStar(star, SPACE_META_STAR_LIMITS), true);\n const meta = parseDef(defs.spaceMetaStarMeta, reader.meta);\n let policy;\n const policyState = [];\n const writers = [];\n const decoder = new TextDecoder();\n let section;\n let prevKey;\n for await (const pair of reader.pairs) {\n const key = decoder.decode(pair.key);\n const keySection = sectionOf(key);\n if (keySection !== section) {\n if (section && SECTIONS.indexOf(keySection) < SECTIONS.indexOf(section)) {\n throw new SpaceMetaArchiveError(`section out of order at ${key}`);\n }\n section = keySection;\n prevKey = undefined;\n }\n if (prevKey && compareBytes(pair.key, prevKey) <= 0) {\n throw new SpaceMetaArchiveError(`duplicate or out-of-order key: ${key}`);\n }\n prevKey = pair.key;\n const value = decodeMap(key, pair.value);\n switch (keySection) {\n case 'policy':\n policy = value;\n break;\n case 'policyState':\n policyState.push({ key, value });\n break;\n case 'writers':\n writers.push(parseWriter(key, value));\n break;\n }\n }\n if (!policy) {\n throw new SpaceMetaArchiveError('missing policy');\n }\n return { space: meta.space, policy, policyState, writers };\n }\n catch (e_1) {\n env_1.error = e_1;\n env_1.hasError = true;\n }\n finally {\n const result_1 = __disposeResources(env_1);\n if (result_1)\n await result_1;\n }\n}\nfunction sectionOf(key) {\n if (key === POLICY_KEY)\n return 'policy';\n if (key.startsWith(WRITER_KEY_PREFIX))\n return 'writers';\n return 'policyState';\n}\nfunction parseWriter(key, value) {\n const did = key.slice(WRITER_KEY_PREFIX.length);\n if (!isValidDid(did)) {\n throw new SpaceMetaArchiveError(`invalid DID in writer key: ${key}`);\n }\n const { repoRev, data, spaceRev } = parseDef(defs.spaceMetaWriter, value);\n return { did, repoRev, data, spaceRev };\n}\nfunction decodeMap(key, bytes) {\n let value;\n try {\n value = decode(bytes);\n }\n catch (cause) {\n throw new SpaceMetaArchiveError(`invalid cbor at ${key}`, { cause });\n }\n if (!isPlainObject(value)) {\n throw new SpaceMetaArchiveError(`value at ${key} is not a map`);\n }\n return value;\n}\nfunction parseDef(def, data) {\n try {\n return def.schema.parse(data);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new SpaceMetaArchiveError(`invalid ${def.name}: ${message}`, {\n cause: err,\n });\n }\n}\nfunction toPair(key, value) {\n return { key: utf8(key), value: encode(value) };\n}\nfunction sortByKey(pairs) {\n return pairs.sort((a, b) => compareBytes(a.key, b.key));\n}\n//# sourceMappingURL=space-meta-archive.js.map","import { decode, encode } from '@atproto/lex-cbor';\nimport { cidForCbor, isPlainObject, parseCidSafe, } from '@atproto/lex-data';\nimport { readStar } from '@atproto/star';\nimport { compareBytes } from '../bytes.js';\nimport { SpaceRepoVerificationError } from '../error.js';\nimport { verifyRecordMac } from '../mac.js';\nimport { RepoCommit, verifyCommit, } from '../repo-commit.js';\nimport { COMMIT_VERSION, REPO_STAR_LIMITS, defs, } from '../types.js';\nimport { parseRecordPath } from '../util.js';\n/**\n * Read a serialized repo, streaming out its records, without authenticating its\n * commit. The records are checked against the commit's data as in\n * {@link verifyRepoStar}, but nothing vouches for the commit itself. This suits a\n * repo host importing an account's own repo, which comes with no MAC to check.\n */\nexport async function readRepoStar(star) {\n const starReader = await readStar(star, REPO_STAR_LIMITS);\n // Note the try/catch would better be implemented with a DisposableStack, but\n // that isn't (widely) available yet.\n try {\n const commit = parseMeta(starReader.meta);\n if (commit.ver !== COMMIT_VERSION) {\n throw new SpaceRepoVerificationError(`unsupported commit version: ${commit.ver}`);\n }\n return {\n commit,\n records: verifyStarRecords(starReader.pairs, commit),\n [Symbol.asyncDispose]: starReader[Symbol.asyncDispose].bind(starReader),\n };\n }\n catch (err) {\n await starReader[Symbol.asyncDispose]();\n throw err;\n }\n}\n/**\n * Verify a serialized repo, streaming out its records.\n *\n * The commit in the archive's metadata is verified against the response's MAC\n * up front. Each record is folded into a running set hash as `records` is\n * drained, and the result is compared against the commit's data once the\n * archive ends. Only that match shows the repo was received complete, so\n * `records` must be fully consumed before trusting what it yielded โ\n * {@link verifyRepoStarFull} does that.\n */\nexport async function verifyRepoStar(star, params) {\n const repo = await readRepoStar(star);\n try {\n verifyCommit(repo.commit, params);\n return repo;\n }\n catch (err) {\n await repo[Symbol.asyncDispose]();\n throw err;\n }\n}\n/**\n * Verify a serialized repo and collect its records. Prefer {@link verifyRepoStar}\n * for large repos, where streaming avoids holding every record at once.\n */\nexport async function verifyRepoStarFull(star, params) {\n const { commit, records } = await verifyRepoStar(star, params);\n const collected = [];\n for await (const record of records) {\n collected.push(record);\n }\n return { commit, records: collected };\n}\n/**\n * Verify a `getRecord` response against the MAC it carried: it must be the\n * record that was requested, the MAC must cover its uri and cid, and its value\n * must encode to that cid.\n *\n * @throws {SpaceRepoVerificationError} if the record is not the one requested,\n * or its value does not match its cid\n * @throws {SpaceMacError} if the MAC does not match\n */\nexport async function verifyRecord(record, params) {\n if (record.uri !== params.uri) {\n throw new SpaceRepoVerificationError(`record is not the one requested: ${record.uri}`);\n }\n const cid = parseCidSafe(record.cid, { flavor: 'cbor' });\n if (!cid) {\n throw new SpaceRepoVerificationError(`invalid record cid: ${record.cid}`);\n }\n verifyRecordMac(params.uri, cid, params);\n const valueCid = await cidForCbor(encode(record.value));\n if (!valueCid.equals(cid)) {\n throw new SpaceRepoVerificationError('record value does not match its cid');\n }\n}\nasync function* verifyStarRecords(pairs, commit) {\n const decoder = new TextDecoder();\n const repo = new RepoCommit();\n let prevKey;\n for await (const { key, value } of pairs) {\n const path = decoder.decode(key);\n const { collection, rkey } = parseRecordPath(path);\n if (prevKey !== undefined && compareBytes(key, prevKey) <= 0) {\n throw new SpaceRepoVerificationError(`records out of order at ${path}`);\n }\n prevKey = key;\n let record;\n try {\n record = decode(value);\n }\n catch (cause) {\n throw new SpaceRepoVerificationError(`invalid record cbor at ${path}`, {\n cause,\n });\n }\n // Ensure that the encoded record is a plain object (LexMap)\n if (!isPlainObject(record)) {\n throw new SpaceRepoVerificationError(`invalid record at ${path}`);\n }\n const cid = await cidForCbor(value);\n repo.add(collection, rkey, cid);\n yield { collection, rkey, cid, record };\n }\n if (!repo.matches(commit)) {\n throw new SpaceRepoVerificationError('records do not match the commit data');\n }\n}\nfunction parseMeta(meta) {\n try {\n return defs.repoStarMeta.schema.parse(meta);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new SpaceRepoVerificationError(`invalid ${defs.repoStarMeta.name}: ${message}`, { cause: err });\n }\n}\n//# sourceMappingURL=consumer.js.map","import { encode } from '@atproto/lex-cbor';\nimport { cidForCbor } from '@atproto/lex-data';\nimport { writeStar } from '@atproto/star';\nimport { compareBytes, utf8 } from '../bytes.js';\nimport { SpaceRepoVerificationError } from '../error.js';\nimport { REPO_STAR_TYPE, } from '../types.js';\nimport { formatRecordPath } from '../util.js';\n/**\n * Serialize a repo as a STAR archive: the commit as the metadata, then one\n * path/record pair per record. Blobs are excluded.\n *\n * Records must be given in strict path order, as the archive requires.\n */\nexport async function* writeRepoStar(commit, records) {\n const meta = { $type: REPO_STAR_TYPE, ...commit };\n yield* writeStar(meta, toStarPairs(records));\n}\nasync function* toStarPairs(records) {\n let prevKey;\n for await (const { collection, rkey, bytes } of records) {\n const path = formatRecordPath(collection, rkey);\n const key = utf8(path);\n if (prevKey !== undefined && compareBytes(key, prevKey) <= 0) {\n throw new SpaceRepoVerificationError(`records out of order at ${path}`);\n }\n prevKey = key;\n yield { key, value: bytes };\n }\n}\nexport async function serializeRecord(collection, rkey, record) {\n const bytes = encode(record);\n return { collection, rkey, bytes, cid: await cidForCbor(bytes) };\n}\n//# sourceMappingURL=provider.js.map","/**\n * Typed errors for the spaces engine.\n *\n * Durable Object RPC flattens thrown errors into a wrapper `Error` whose\n * message is `\"${name}: ${message}\"`, so every error here encodes its\n * protocol error name as a message prefix. Worker-side handlers recover the\n * name with {@link parseSpaceErrorCode} and map it onto the lexicon error\n * shape.\n */\n\n/** Protocol error names used across the space and policy endpoints. */\nexport const SPACE_ERROR_CODES = [\n\t\"SpaceNotFound\",\n\t\"SpaceDeleted\",\n\t\"SpaceAlreadyExists\",\n\t\"RepoNotFound\",\n\t\"RepoDeactivated\",\n\t\"RepoTakendown\",\n\t\"RecordNotFound\",\n\t\"RecordAlreadyExists\",\n\t\"BlobNotFound\",\n\t\"AppNotAuthorized\",\n\t\"NotAuthorized\",\n\t\"AccountNotAuthorized\",\n\t\"InvalidDelegationToken\",\n\t\"InvalidClientAttestation\",\n\t\"InvalidCredential\",\n\t\"PolicyMismatch\",\n\t\"UnsupportedPolicy\",\n\t\"ServiceNotResolvable\",\n\t\"InvalidCursor\",\n\t\"InvalidRequest\",\n\t\"FutureRev\",\n\t\"InvalidSpaceMac\",\n\t\"InvalidRepoFile\",\n\t\"RepoMismatch\",\n\t\"InvalidSpaceMeta\",\n\t\"RegistrationNotConfirmed\",\n\t\"UpstreamFailure\",\n\t// Space credential authentication failures, named as the reference\n\t// names them (all 401).\n\t\"MissingJwt\",\n\t\"BadJwt\",\n\t\"BadJwtType\",\n\t\"BadJwtIss\",\n\t\"BadJwtSub\",\n\t\"BadJwtAudience\",\n\t\"BadJwtCnf\",\n\t\"BadJwtSignature\",\n\t\"JwtExpired\",\n\t\"BadSpaceSignature\",\n\t\"BadSpaceAudience\",\n\t\"CredentialRevoked\",\n\t\"Forbidden\",\n\t\"KemKeyUnavailable\",\n\t\"SpacesSchemaOutdated\",\n] as const;\n\nexport type SpaceErrorCode = (typeof SPACE_ERROR_CODES)[number];\n\nconst CODE_SET: ReadonlySet<string> = new Set(SPACE_ERROR_CODES);\n\n/** HTTP status for each error name when it isn't the default 400. */\nconst ERROR_STATUS: Partial<Record<SpaceErrorCode, number>> = {\n\tSpaceNotFound: 404,\n\tRepoNotFound: 404,\n\tBlobNotFound: 404,\n\tRecordAlreadyExists: 409,\n\tSpaceAlreadyExists: 409,\n\tAppNotAuthorized: 403,\n\t// NotAuthorized is the management methods' \"not the space authority\",\n\t// a 400 as the reference answers it.\n\tAccountNotAuthorized: 403,\n\tForbidden: 403,\n\tUpstreamFailure: 502,\n\tInvalidClientAttestation: 401,\n\tMissingJwt: 401,\n\tBadJwt: 401,\n\tBadJwtType: 401,\n\tBadJwtIss: 401,\n\tBadJwtSub: 401,\n\tBadJwtAudience: 401,\n\tBadJwtCnf: 401,\n\tBadJwtSignature: 401,\n\tJwtExpired: 401,\n\tBadSpaceSignature: 401,\n\tBadSpaceAudience: 401,\n\tCredentialRevoked: 401,\n\tKemKeyUnavailable: 503,\n\tSpacesSchemaOutdated: 503,\n};\n\nexport class SpaceError extends Error {\n\toverride name = \"SpaceError\";\n\tconstructor(\n\t\treadonly code: SpaceErrorCode,\n\t\tmessage: string,\n\t) {\n\t\t// The `${code}: ` prefix survives the DO RPC boundary.\n\t\tsuper(`${code}: ${message}`);\n\t}\n\n\tget status(): number {\n\t\treturn ERROR_STATUS[this.code] ?? 400;\n\t}\n\n\t/** The human message without the code prefix. */\n\tget detail(): string {\n\t\treturn this.message.slice(this.code.length + 2);\n\t}\n}\n\n/**\n * Recover the space error name from an error that may have crossed a DO RPC\n * boundary. Returns null for errors that aren't space errors.\n */\nexport function parseSpaceErrorCode(\n\terr: unknown,\n): { code: SpaceErrorCode; message: string } | null {\n\tif (err instanceof SpaceError) {\n\t\treturn { code: err.code, message: err.detail };\n\t}\n\tif (err instanceof Error) {\n\t\t// Durable Object RPC re-throws errors with the class name folded into\n\t\t// the message (\"SpaceError: RecordNotFound: ...\"), so scan the first\n\t\t// few prefix segments for a known code.\n\t\tlet message = err.message;\n\t\tfor (let hop = 0; hop < 3; hop++) {\n\t\t\tconst colon = message.indexOf(\": \");\n\t\t\tif (colon <= 0) break;\n\t\t\tconst code = message.slice(0, colon);\n\t\t\tif (CODE_SET.has(code)) {\n\t\t\t\treturn {\n\t\t\t\t\tcode: code as SpaceErrorCode,\n\t\t\t\t\tmessage: message.slice(colon + 2),\n\t\t\t\t};\n\t\t\t}\n\t\t\tmessage = message.slice(colon + 2);\n\t\t}\n\t}\n\treturn null;\n}\n\n/** HTTP status for a recovered space error name. */\nexport function spaceErrorStatus(code: SpaceErrorCode): number {\n\treturn ERROR_STATUS[code] ?? 400;\n}\n","/**\n * Shared types crossing the Worker โ Durable Object RPC boundary.\n */\n\n/**\n * The minimal keypair shape the engine signs with: the account's\n * `#atproto` key, for space tokens and service-auth JWTs. Structural, so a\n * host can pass any `@atproto/crypto` keypair without the engine's public\n * types depending on a particular build of that package.\n */\nexport interface SpaceSigningKeypair {\n\tjwtAlg: string;\n\tdid(): string;\n\tsign(msg: Uint8Array): Promise<Uint8Array>;\n}\n\n/** A write prepared by the Worker: validated, CBOR-encoded, CID computed. */\nexport type PreparedSpaceWrite =\n\t| {\n\t\t\taction: \"create\" | \"update\";\n\t\t\tcollection: string;\n\t\t\trkey: string;\n\t\t\tcid: string;\n\t\t\tbytes: Uint8Array;\n\t\t\t/** Blob CIDs referenced by the record. */\n\t\t\tblobCids: string[];\n\t }\n\t| {\n\t\t\taction: \"delete\";\n\t\t\tcollection: string;\n\t\t\trkey: string;\n\t };\n\n/** A repo revision that is owed a write notification. */\nexport interface RepoCommitResult {\n\trev: string;\n\t/** sha256 digest of the LtHash state: the commit's `data`. */\n\tdata: Uint8Array;\n}\n\nexport interface ApplyWritesResult extends RepoCommitResult {\n\tresults: Array<{\n\t\taction: \"create\" | \"update\" | \"delete\";\n\t\tcollection: string;\n\t\trkey: string;\n\t\tcid: string | null;\n\t}>;\n}\n\nexport interface SpaceMeta {\n\turi: string;\n\tauthority: string;\n\ttype: string;\n\tskey: string;\n\tisAuthority: boolean;\n\tcreatedAt: string;\n\tdeletedAt: string | null;\n}\n\nexport const PERSONALSPACE_POLICY = \"com.atproto.personalspace.policy\";\nexport const MEMBERSPACE_POLICY = \"com.atproto.memberspace.policy\";\nexport const MANAGEDSPACE_POLICY = \"com.atproto.managedspace.policy\";\n\n/**\n * A space policy as stored and enforced: one of the three baseline\n * policies, normalised with its defaults filled in. The wire shape and the\n * stored shape are the same object.\n */\nexport type SpacePolicy =\n\t| { $type: typeof PERSONALSPACE_POLICY }\n\t| {\n\t\t\t$type: typeof MEMBERSPACE_POLICY;\n\t\t\tpublicRead: boolean;\n\t\t\tpublicWrite: boolean;\n\t\t\tallowedApps?: string[];\n\t\t\tpublishPolicy: boolean;\n\t\t\tpublishMembers: boolean;\n\t }\n\t| {\n\t\t\t$type: typeof MANAGEDSPACE_POLICY;\n\t\t\tmanagingApp: string;\n\t\t\tpublishPolicy: boolean;\n\t };\n\nexport interface SpaceMember {\n\tdid: string;\n\tread: boolean;\n\twrite: boolean;\n}\n\nexport interface SpaceWriter {\n\tdid: string;\n\trepoRev: string;\n\tdata: Uint8Array;\n\tspaceRev: string;\n\t/** Removed from the writer set at `spaceRev`, until it writes again. */\n\tremoved: boolean;\n}\n\n/** A syncer's webhook registration (`authorizeSpaceSync`'s `notify`). */\nexport interface NotifyRegistration {\n\tendpoint: string;\n\ttoken: string;\n}\n\n/** The space sequence position assigned to an accepted repo update. */\nexport interface SpaceSequence {\n\tspaceRev: string;\n\tprevSpaceRev?: string;\n}\n\nexport interface RepoState {\n\tsetHash: Uint8Array;\n\trev: string;\n}\n\nexport interface SpaceRecordRow {\n\tcollection: string;\n\trkey: string;\n\tcid: string;\n\tbytes?: Uint8Array;\n}\n\nexport interface OplogEntry {\n\trev: string;\n\tidx: number;\n\tcollection: string;\n\trkey: string;\n\tcid: string | null;\n\tprev: string | null;\n\t/** Current record bytes for creates/updates that are not stale. */\n\tbytes?: Uint8Array;\n}\n\n/** A record imported from a repo archive, prepared by the Worker. */\nexport interface ImportedRecord {\n\tcollection: string;\n\trkey: string;\n\tcid: string;\n\tbytes: Uint8Array;\n\tblobCids: string[];\n}\n\nexport interface NotifyItem {\n\tservice: string;\n\tendpoint: string;\n\tlxm: string;\n\tbody: Record<string, unknown>;\n\t/**\n\t * Pending items sharing a key are coalesced: a newer one replaces the\n\t * older, resetting its backoff and deadline โ unless `keepPending`, when\n\t * a pending item wins.\n\t */\n\tcoalesceKey?: string;\n\tkeepPending?: boolean;\n\t/** Give up retrying after this time (ms since epoch). */\n\tdeadline?: number;\n\t/**\n\t * Retry schedule: `fanout` (best effort, a few attempts), `repo` (a repo\n\t * host's notifyRepoUpdate, exponential up to the deadline) or `syncer`\n\t * (a syncer's deletion or expiry notice, 1 minute to 12 hours).\n\t */\n\tpolicy?: \"fanout\" | \"repo\" | \"syncer\";\n\t/** `service` signs a service JWT; `none` sends a token-bearing webhook. */\n\tauth?: \"service\" | \"none\";\n}\n\n/**\n * Host configuration for the space engine's Durable Objects. Supplied by\n * the host Worker's subclass โ the engine never reads env vars itself, so\n * the same class can later serve a dedicated authority DID with no account\n * attached.\n */\nexport interface SpaceHostConfig {\n\t/** The DID whose permissioned repos this engine serves. */\n\toperatorDid: string;\n\t/** Signing keypair provider (service JWTs for notification delivery). */\n\tgetKeypair(): Promise<SpaceSigningKeypair>;\n}\n","/**\n * Space policies: the three baseline policies every PDS supports, as\n * `com.atproto.space.createSpace` / `updateSpace` take them. A policy is an\n * open union discriminated by `$type` that both selects the policy and\n * carries its configuration.\n *\n * What is stored is exactly what is enforced: {@link normalizePolicy}\n * refuses a policy this host doesn't implement and fills in every default.\n * Unknown fields are dropped, as Lexicon evolution allows.\n */\n\nimport { SpaceError } from \"./errors.js\";\nimport {\n\tMANAGEDSPACE_POLICY,\n\tMEMBERSPACE_POLICY,\n\tPERSONALSPACE_POLICY,\n\ttype SpacePolicy,\n} from \"./types.js\";\n\n/** The collection a published policy record lives in (rkey `self`). */\nexport const POLICY_COLLECTION = \"com.atproto.space.policy\";\nexport const POLICY_RKEY = \"self\";\n/** The collection published member records live in (rkey = member DID). */\nexport const MEMBER_COLLECTION = \"com.atproto.memberspace.member\";\n/** The collections the host publishes a space's configuration to. */\nexport const PUBLISHED_COLLECTIONS: readonly string[] = [\n\tPOLICY_COLLECTION,\n\tMEMBER_COLLECTION,\n];\n\nconst isBool = (value: unknown): value is boolean => typeof value === \"boolean\";\n\nfunction isUri(value: unknown): value is string {\n\tif (typeof value !== \"string\") return false;\n\ttry {\n\t\tnew URL(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction optionalBool(input: Record<string, unknown>, key: string): boolean {\n\tconst value = input[key];\n\tif (value === undefined) return false;\n\tif (!isBool(value)) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `Policy ${key} must be a boolean`);\n\t}\n\treturn value;\n}\n\n/** Validate and normalise a policy from a request or an archive. */\nexport function normalizePolicy(input: unknown): SpacePolicy {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"policy must be an object\");\n\t}\n\tconst policy = input as Record<string, unknown>;\n\tswitch (policy.$type) {\n\t\tcase PERSONALSPACE_POLICY:\n\t\t\treturn { $type: PERSONALSPACE_POLICY };\n\t\tcase MEMBERSPACE_POLICY: {\n\t\t\tconst allowedApps = policy.allowedApps;\n\t\t\tif (\n\t\t\t\tallowedApps !== undefined &&\n\t\t\t\t(!Array.isArray(allowedApps) || allowedApps.some((app) => !isUri(app)))\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"allowedApps must be an array of OAuth client ID URIs\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t$type: MEMBERSPACE_POLICY,\n\t\t\t\tpublicRead: optionalBool(policy, \"publicRead\"),\n\t\t\t\tpublicWrite: optionalBool(policy, \"publicWrite\"),\n\t\t\t\t...(allowedApps !== undefined\n\t\t\t\t\t? { allowedApps: [...(allowedApps as string[])] }\n\t\t\t\t\t: {}),\n\t\t\t\tpublishPolicy: optionalBool(policy, \"publishPolicy\"),\n\t\t\t\tpublishMembers: optionalBool(policy, \"publishMembers\"),\n\t\t\t};\n\t\t}\n\t\tcase MANAGEDSPACE_POLICY: {\n\t\t\tconst managingApp = policy.managingApp;\n\t\t\t// A did#serviceId reference: the app's service entry, which a bare\n\t\t\t// DID (an account's #atproto_pds) is not.\n\t\t\tconst [did, fragment, extra] =\n\t\t\t\ttypeof managingApp === \"string\" ? managingApp.split(\"#\") : [];\n\t\t\tif (!did?.startsWith(\"did:\") || !fragment || extra !== undefined) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`managingApp must be a did#serviceId reference, got: ${String(managingApp)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t$type: MANAGEDSPACE_POLICY,\n\t\t\t\tmanagingApp: managingApp as string,\n\t\t\t\tpublishPolicy: optionalBool(policy, \"publishPolicy\"),\n\t\t\t};\n\t\t}\n\t\tdefault:\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"UnsupportedPolicy\",\n\t\t\t\t`Unsupported policy: ${String(policy.$type)}`,\n\t\t\t);\n\t}\n}\n\n/** The member list and its methods belong to the memberspace policy. */\nexport function assertMemberspace(\n\tpolicy: SpacePolicy,\n): asserts policy is Extract<\n\tSpacePolicy,\n\t{ $type: typeof MEMBERSPACE_POLICY }\n> {\n\tif (policy.$type !== MEMBERSPACE_POLICY) {\n\t\tthrow new SpaceError(\n\t\t\t\"PolicyMismatch\",\n\t\t\t\"Space is not governed by the memberspace policy\",\n\t\t);\n\t}\n}\n\n/**\n * Whether any user may read. Only then can a credential be minted without\n * a delegation token saying who the user is.\n */\nexport function isPublicRead(policy: SpacePolicy): boolean {\n\treturn policy.$type === MEMBERSPACE_POLICY && policy.publicRead;\n}\n\nexport function isPolicyPublished(policy: SpacePolicy): boolean {\n\treturn policy.$type !== PERSONALSPACE_POLICY && policy.publishPolicy;\n}\n\nexport function areMembersPublished(policy: SpacePolicy): boolean {\n\treturn policy.$type === MEMBERSPACE_POLICY && policy.publishMembers;\n}\n\n/**\n * Only memberspace restricts apps, against the attested client_id, so an\n * app that presents no attestation is never one of the allowed apps.\n */\nexport function isAppAuthorized(\n\tpolicy: SpacePolicy,\n\tclientId: string | undefined,\n): boolean {\n\tif (policy.$type !== MEMBERSPACE_POLICY || !policy.allowedApps) return true;\n\treturn clientId !== undefined && policy.allowedApps.includes(clientId);\n}\n\n/**\n * A DID as a record key, for published member records. A record key can't\n * contain `%`, so the percent-encoded port of a localhost did:web is left\n * unencoded, as the reference does. Unambiguous because the unencoded form\n * would otherwise be a did:web path, which atproto doesn't support.\n */\nexport function didToRecordKey(did: string): string {\n\treturn did.replace(\"%3A\", \":\");\n}\n\nexport function recordKeyToDid(rkey: string): string {\n\treturn rkey.replace(/^(did:web:[^:]+):(\\d+)$/, \"$1%3A$2\");\n}\n\n/** Records published from a space's configuration are the host's to write. */\nexport function assertNotPublishedCollection(collection: string): void {\n\tif (PUBLISHED_COLLECTIONS.includes(collection)) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`${collection} records are published by the PDS from a space's configuration and cannot be written directly`,\n\t\t);\n\t}\n}\n","import { fromBase64, toBase64 } from '@atproto/lex-data';\n/**\n * Parses a `{$bytes: string}` JSON object into a `Uint8Array`.\n *\n * In the AT Protocol data model, binary data is represented in JSON as an object\n * with a single `$bytes` property containing a base64-encoded string. This function\n * decodes that representation back into raw bytes.\n *\n * @param input - An object potentially containing a `$bytes` property\n * @returns The decoded `Uint8Array` if the input is a valid `$bytes` object,\n * or `undefined` if the input is not a valid `$bytes` representation\n *\n * @example\n * ```typescript\n * // Parse a $bytes object to Uint8Array\n * const bytes = parseLexBytes({ $bytes: 'SGVsbG8sIHdvcmxkIQ==' })\n * // bytes is Uint8Array containing \"Hello, world!\"\n *\n * // Returns undefined for non-$bytes objects\n * const result = parseLexBytes({ foo: 'bar' })\n * // result is undefined\n *\n * // Returns undefined for objects with extra properties\n * const invalid = parseLexBytes({ $bytes: 'SGVsbG8=', extra: true })\n * // invalid is undefined\n * ```\n */\nexport function parseLexBytes(input) {\n if (!input || !('$bytes' in input)) {\n return undefined;\n }\n for (const key in input) {\n if (key !== '$bytes') {\n return undefined;\n }\n }\n if (typeof input.$bytes !== 'string') {\n return undefined;\n }\n try {\n return fromBase64(input.$bytes);\n }\n catch {\n return undefined;\n }\n}\n/**\n * Encodes a `Uint8Array` into a `{$bytes: string}` JSON representation.\n *\n * In the AT Protocol data model, binary data is represented in JSON as an object\n * with a single `$bytes` property containing a base64-encoded string. This function\n * performs that encoding.\n *\n * @param bytes - The binary data to encode\n * @returns An object with a `$bytes` property containing the base64-encoded data\n *\n * @example\n * ```typescript\n * const bytes = new TextEncoder().encode('Hello, world!')\n * const encoded = encodeLexBytes(bytes)\n * // encoded is { $bytes: 'SGVsbG8sIHdvcmxkIQ==' }\n * ```\n */\nexport function encodeLexBytes(bytes) {\n return { $bytes: toBase64(bytes) };\n}\n//# sourceMappingURL=bytes.js.map","import { parseCid } from '@atproto/lex-data';\nexport function parseLexLink(input, options) {\n if (!input || !('$link' in input)) {\n return undefined;\n }\n for (const key in input) {\n if (key !== '$link') {\n return undefined;\n }\n }\n const { $link } = input;\n if (typeof $link !== 'string') {\n return undefined;\n }\n if ($link.length === 0) {\n return undefined;\n }\n // Arbitrary limit to prevent DoS via extremely long CIDs\n if ($link.length > 2048) {\n return undefined;\n }\n try {\n return parseCid($link, options);\n }\n catch {\n return undefined;\n }\n}\n/**\n * Encodes a {@link Cid} instance into a `{$link: string}` JSON representation.\n *\n * In the AT Protocol data model, CID references are represented in JSON as an\n * object with a single `$link` property containing a base32-encoded CID string,\n * prefixed with \"b\". This function performs that encoding.\n *\n * @param cid - The CID to encode\n * @returns An object with a `$link` property containing the string representation of the CID\n *\n * @example\n * ```typescript\n * const cid = CID.parse('bafyreib2rxk3rybloqtqwbo')\n * const encoded = encodeLexLink(cid)\n * // encoded is { $link: 'bafyreib2rxk3rybloqtqwbo' }\n * ```\n */\nexport function encodeLexLink(cid) {\n return { $link: cid.toString() };\n}\n//# sourceMappingURL=link.js.map","import { isTypedBlobRef } from '@atproto/lex-data';\nimport { parseLexLink } from './link.js';\n/**\n * Parses a blob reference from a JSON object.\n *\n * In the AT Protocol, blobs are referenced using a specific object structure\n * with `$type: 'blob'`, a `ref` property containing a CID link, and metadata\n * like `mimeType` and `size`. This function validates and parses such objects\n * into `BlobRef` instances.\n *\n * The function handles both cases where the `ref` property is:\n * - A `{$link: string}` object (when parsing from JSON)\n * - Already a `Cid` instance (when the parent object has been partially converted)\n *\n * @param input - A Lex map potentially representing a blob reference\n * @param options - Optional blob reference validation options\n * @returns The parsed `BlobRef` if the input is a valid blob reference,\n * or `undefined` if the input is not a valid blob representation\n *\n * @example\n * ```typescript\n * // Parse a blob reference from JSON\n * const blobRef = parseTypedBlobRef({\n * $type: 'blob',\n * ref: { $link: 'bafyreib2rxk3rybloqtqwbo' },\n * mimeType: 'image/png',\n * size: 12345\n * })\n *\n * // blobRef.ref is a Cid instance\n *\n * // Returns undefined for non-blob objects\n * const result = parseTypedBlobRef({ foo: 'bar' })\n * // result is undefined\n * ```\n */\nexport function parseTypedBlobRef(input, options) {\n if (input.$type !== 'blob')\n return undefined;\n const ref = input?.ref;\n if (!ref || typeof ref !== 'object')\n return undefined;\n // @NOTE Because json to lex conversion can be performed both in a depth-first\n // manner (e.g. via lexParse) or in a breadth-first manner (e.g. via\n // jsonToLex), the `ref` property may either be a LexMap with a $link\n // property, or it may already be a CID instance.\n if ('$link' in ref) {\n const cid = parseLexLink(ref);\n if (!cid)\n return undefined;\n const blob = { ...input, ref: cid };\n if (isTypedBlobRef(blob, options))\n return blob;\n }\n if (isTypedBlobRef(input)) {\n return input;\n }\n return undefined;\n}\n//# sourceMappingURL=blob.js.map","import { isCid, utf8FromBytes } from '@atproto/lex-data';\nimport { parseTypedBlobRef } from './blob.js';\nimport { encodeLexBytes, parseLexBytes } from './bytes.js';\nimport { encodeLexLink, parseLexLink } from './link.js';\n/**\n * The AT Protocol data model only allows CIDv1 links using the dag-cbor or raw\n * codec with a sha-256 multihash. Enforced when parsing `$link` in strict mode.\n */\nconst STRICT_CID_CHECK_OPTIONS = { flavor: 'dasl' };\n/**\n * Serialize a Lex value to a JSON string.\n *\n * This function serializes AT Protocol data model values to JSON, automatically\n * encoding special types:\n * - `Cid` instances are encoded as `{$link: string}`\n * - `Uint8Array` instances are encoded as `{$bytes: string}` (base64)\n *\n * @param input - The Lex value to stringify\n * @returns A JSON string representation of the value\n *\n * @example\n * ```typescript\n * import { lexStringify } from '@atproto/lex'\n *\n * // Stringify with CID and bytes encoding\n * const json = lexStringify({\n * ref: someCid,\n * data: new Uint8Array([72, 101, 108, 108, 111])\n * })\n * // json is '{\"ref\":{\"$link\":\"bafyrei...\"},\"data\":{\"$bytes\":\"SGVsbG8=\"}}'\n * ```\n */\nexport function lexStringify(input) {\n // @NOTE Because of the way the \"replacer\" works in JSON.stringify, it's\n // simpler to convert Lex to JSON first rather than trying to do it\n // on-the-fly.\n return JSON.stringify(lexToJson(input));\n}\n/**\n * Parses a JSON string into Lex values.\n *\n * This function parses JSON and automatically decodes AT Protocol special types:\n * - `{$link: string}` objects are decoded to `Cid` instances\n * - `{$bytes: string}` objects are decoded to `Uint8Array` instances\n * - `{$type: 'blob'}` objects are validated\n *\n * @typeParam T - Type cast for the resulting Lex value. Use when you want to specify the expected structure of the parsed data.\n * @param input - The JSON string to parse\n * @param options - Parsing options (e.g., strict mode)\n * @returns The parsed Lex value\n * @throws {SyntaxError} If the input is not valid JSON\n * @throws {TypeError} If strict mode is enabled and invalid Lex values are found\n *\n * @example\n * ```typescript\n * import { lexParse } from '@atproto/lex'\n *\n * // Parse JSON with $link and $bytes decoding\n * const parsed = lexParse<{\n * ref: Cid\n * data: Uint8Array\n * }>(`{\n * \"ref\": { \"$link\": \"bafyrei...\" },\n * \"data\": { \"$bytes\": \"SGVsbG8sIHdvcmxkIQ==\" }\n * }`)\n *\n * // Parse a single CID\n * const someCid = lexParse<Cid>('{\"$link\": \"bafyrei...\"}')\n *\n * // Parse binary data\n * const someBytes = lexParse<Uint8Array>('{\"$bytes\": \"SGVsbG8sIHdvcmxkIQ==\"}')\n * ```\n */\nexport function lexParse(input, options = { strict: false }) {\n // @NOTE see ./lex-json.bench.ts for performance comparison of implementation\n // that uses a reviver function in JSON.parse vs. the current implementation.\n return jsonToLex(JSON.parse(input), options);\n}\n/**\n * Parses a JSON string from a byte array into Lex values.\n */\nexport function lexParseJsonBytes(bytes, options) {\n // @NOTE see ./json-bytes-decoder.bench.ts for performance comparison of\n // implementation that uses a decoder class that operates directly on bytes\n // vs. the current implementation that first decodes bytes to string and then\n // parses JSON. For more common cases, it seems that the trivial\n // implementation works better than the decoder based solution, while having a\n // small overhead for slower cases (~2% difference). Because of this, we keep\n // the trivial implementation:\n return lexParse(utf8FromBytes(bytes), options);\n}\n/**\n * Converts a parsed JSON representation of Lexicon value to a {@link LexValue}.\n *\n * This function transforms already-parsed JSON objects into Lex values by\n * decoding AT Protocol special types:\n * - `{$link: string}` objects are converted to `Cid` instances\n * - `{$bytes: string}` objects are converted to `Uint8Array` instances\n *\n * Use this when you have a JavaScript object (e.g., from `JSON.parse()`) and\n * need to convert it to the Lex data model. For parsing JSON strings directly,\n * use {@link lexParse} instead.\n *\n * @param value - The JSON value to convert\n * @param options - Parsing options (e.g., strict mode)\n * @returns The converted Lex value\n * @throws {TypeError} If strict mode is enabled and invalid Lex values are found\n * @throws {TypeError} If the value contains unsupported types (e.g., undefined at top level)\n *\n * @example\n * ```typescript\n * import { jsonToLex } from '@atproto/lex'\n *\n * // Convert parsed JSON to Lex values\n * const lex = jsonToLex({\n * ref: { $link: 'bafyrei...' }, // Converted to Cid\n * data: { $bytes: 'SGVsbG8sIHdvcmxkIQ==' } // Converted to Uint8Array\n * })\n * ```\n */\nexport function jsonToLex(value, options = { strict: false }) {\n switch (typeof value) {\n case 'object': {\n if (value === null)\n return null;\n if (Array.isArray(value))\n return jsonArrayToLex(value, options);\n return (parseSpecialJsonObject(value, options) ??\n jsonObjectToLexMap(value, options));\n }\n case 'number':\n if (Number.isSafeInteger(value))\n return value;\n if (options.strict === false)\n return value;\n throw new TypeError(`Invalid non-integer number: ${value}`);\n case 'boolean':\n case 'string':\n return value;\n default:\n throw new TypeError(`Invalid JSON value: ${typeof value}`);\n }\n}\nfunction jsonArrayToLex(input, options) {\n // Lazily copy value\n let copy;\n for (let i = 0; i < input.length; i++) {\n const inputItem = input[i];\n const item = jsonToLex(inputItem, options);\n if (item !== inputItem) {\n copy ??= Array.from(input);\n copy[i] = item;\n }\n }\n return copy ?? input;\n}\nfunction jsonObjectToLexMap(input, options) {\n // Lazily copy value\n let copy = undefined;\n for (const [key, jsonValue] of Object.entries(input)) {\n // Prevent prototype pollution\n if (key === '__proto__') {\n throw new TypeError('Invalid key: __proto__');\n }\n // Ignore (strip) undefined values\n if (jsonValue === undefined) {\n copy ??= { ...input };\n delete copy[key];\n continue;\n }\n const value = jsonToLex(jsonValue, options);\n if (value !== jsonValue) {\n copy ??= { ...input };\n copy[key] = value;\n }\n }\n return copy ?? input;\n}\n/**\n * Converts a Lex value to a JSON-compatible value.\n *\n * This function transforms Lex data model values into plain JavaScript objects\n * suitable for JSON serialization:\n * - `Cid` instances are converted to `{$link: string}` objects\n * - `Uint8Array` instances are converted to `{$bytes: string}` objects (base64)\n *\n * Use this when you need to convert Lex values to plain objects (e.g., for\n * custom serialization or inspection). For direct JSON string output, use\n * {@link lexStringify} instead.\n *\n * @param value - The Lex value to convert\n * @returns The JSON-compatible value\n * @throws {TypeError} If the value contains unsupported types\n *\n * @example\n * ```typescript\n * import { lexToJson } from '@atproto/lex'\n *\n * // Convert Lex values to JSON-compatible objects\n * const obj = lexToJson({\n * ref: someCid, // Converted to { $link: string }\n * data: someBytes // Converted to { $bytes: string }\n * })\n * ```\n */\nexport function lexToJson(value) {\n switch (typeof value) {\n case 'object':\n if (value === null) {\n return value;\n }\n else if (Array.isArray(value)) {\n return lexArrayToJson(value);\n }\n else if (isCid(value)) {\n return encodeLexLink(value);\n }\n else if (ArrayBuffer.isView(value)) {\n return encodeLexBytes(value);\n }\n else {\n return encodeLexMap(value);\n }\n case 'boolean':\n case 'string':\n case 'number':\n return value;\n default:\n throw new TypeError(`Invalid Lex value: ${typeof value}`);\n }\n}\nfunction lexArrayToJson(input) {\n // Lazily copy value\n let copy;\n for (let i = 0; i < input.length; i++) {\n const inputItem = input[i];\n const item = lexToJson(inputItem);\n if (item !== inputItem) {\n copy ??= Array.from(input);\n copy[i] = item;\n }\n }\n return copy ?? input;\n}\nfunction encodeLexMap(input) {\n // Lazily copy value\n let copy = undefined;\n for (const [key, lexValue] of Object.entries(input)) {\n // Prevent prototype pollution\n if (key === '__proto__') {\n throw new TypeError('Invalid key: __proto__');\n }\n // Ignore (strip) undefined values\n if (lexValue === undefined) {\n copy ??= { ...input };\n delete copy[key];\n continue;\n }\n const jsonValue = lexToJson(lexValue);\n if (jsonValue !== lexValue) {\n copy ??= { ...input };\n copy[key] = jsonValue;\n }\n }\n return copy ?? input;\n}\n/**\n * @internal\n */\nexport function parseSpecialJsonObject(input, options) {\n // Hot path: use hints to avoid parsing when possible\n if (input.$link !== undefined) {\n const cid = parseLexLink(input, options.strict ? STRICT_CID_CHECK_OPTIONS : undefined);\n if (cid)\n return cid;\n if (options.strict)\n throw new TypeError(`Invalid $link object`);\n }\n else if (input.$bytes !== undefined) {\n const bytes = parseLexBytes(input);\n if (bytes)\n return bytes;\n if (options.strict)\n throw new TypeError(`Invalid $bytes object`);\n }\n else if (input.$type !== undefined) {\n // @NOTE Since blobs are \"just\" regular lex objects with a special shape,\n // and because an object that does not conform to the blob shape would still\n // result in undefined being returned, we only attempt to parse blobs when\n // the strict option is enabled.\n if (options.strict) {\n if (input.$type === 'blob') {\n const blob = parseTypedBlobRef(input, options);\n if (blob)\n return blob;\n throw new TypeError(`Invalid blob object`);\n }\n else if (typeof input.$type !== 'string') {\n throw new TypeError(`Invalid $type property (${typeof input.$type})`);\n }\n else if (input.$type.length === 0) {\n throw new TypeError(`Empty $type property`);\n }\n }\n }\n // @NOTE We ignore legacy blob representation here. They can be handled at the\n // application level if needed.\n return undefined;\n}\n//# sourceMappingURL=lex-json.js.map","/**\n * Record preparation and serialization for the Worker side of the write\n * and read paths. Records are stored as dag-cbor bytes with their CID,\n * computed here โ the same encoding path the reference uses.\n */\n\nimport { encode, decode, cidForLex } from \"@atproto/lex-cbor\";\nimport { enumBlobRefs, getBlobCidString } from \"@atproto/lex-data\";\nimport type { LexValue } from \"@atproto/lex-data\";\nimport { jsonToLex, lexToJson } from \"@atproto/lex-json\";\nimport type { JsonValue } from \"@atproto/lex-json\";\n\nexport interface PreparedRecord {\n\tcid: string;\n\tbytes: Uint8Array;\n\tblobCids: string[];\n\t/** The lex-normalised record, for echoing back in responses. */\n\tjson: unknown;\n}\n\n/**\n * Convert a client-supplied JSON record into its stored form: lex value โ\n * dag-cbor bytes โ CID, with blob references enumerated for the space's\n * blob tracking.\n */\nexport async function prepareRecord(record: unknown): Promise<PreparedRecord> {\n\tconst lex = jsonToLex(record as JsonValue) as LexValue;\n\tconst bytes = encode(lex);\n\tconst cid = await cidForLex(lex);\n\tconst blobCids: string[] = [];\n\tfor (const ref of enumBlobRefs(lex)) {\n\t\tblobCids.push(getBlobCidString(ref));\n\t}\n\treturn { cid: cid.toString(), bytes, blobCids, json: lexToJson(lex) };\n}\n\n/** Decode stored record bytes back into response JSON. */\nexport function recordBytesToJson(bytes: Uint8Array): unknown {\n\treturn lexToJson(decode(bytes));\n}\n","/**\n * SQLite schema for SpaceDurableObject.\n *\n * Mirrors the reference PDS's `002-space` migration table for table, minus\n * the `space` column on every row โ one DO per space makes it redundant.\n *\n * There is no migration path between alpha schema versions: bumping\n * {@link SPACE_SCHEMA_VERSION} puts existing DOs into a refusing state until\n * `pds spaces reset` wipes them. That is the alpha policy, applied honestly.\n */\n\n/**\n * Bump on any breaking change to the tables below.\n *\n * 2: baseline policies replace simplespace config; members carry\n * read/write access; writers carry space revisions; revoked\n * credentials; coalescing notification queue.\n * 3: webhook registrations (endpoint + token) replace registerNotify;\n * writers keep a removal marker; queue rows carry their retry policy\n * and authentication.\n * 4: space URIs move to `at:space/{did}/{type}/{skey}`. Space DOs are\n * named by URI, so spaces stored under the old form are unreachable.\n */\nexport const SPACE_SCHEMA_VERSION = 4;\n\nexport const SPACE_DO_SCHEMA = `\n\t-- One row. schema_version is checked on every open.\n\tCREATE TABLE IF NOT EXISTS meta (\n\t\turi TEXT NOT NULL,\n\t\tauthority TEXT NOT NULL,\n\t\ttype TEXT NOT NULL,\n\t\tskey TEXT NOT NULL,\n\t\tis_authority INTEGER NOT NULL,\n\t\tcreated_at TEXT NOT NULL,\n\t\tdeleted_at TEXT,\n\t\tschema_version INTEGER NOT NULL\n\t);\n\n\t-- Operator's permissioned repo in this space.\n\tCREATE TABLE IF NOT EXISTS record (\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tcid TEXT NOT NULL,\n\t\tbytes BLOB NOT NULL,\n\t\trev TEXT NOT NULL,\n\t\tindexed_at TEXT NOT NULL,\n\t\tPRIMARY KEY (collection, rkey)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_record_rev ON record(rev);\n\n\tCREATE TABLE IF NOT EXISTS record_blob (\n\t\tblob_cid TEXT NOT NULL,\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tPRIMARY KEY (blob_cid, collection, rkey)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_record_blob_record ON record_blob(collection, rkey);\n\n\tCREATE TABLE IF NOT EXISTS repo_state (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tset_hash BLOB NOT NULL,\n\t\trev TEXT NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS oplog (\n\t\trev TEXT NOT NULL,\n\t\tidx INTEGER NOT NULL,\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tcid TEXT,\n\t\tprev TEXT,\n\t\tPRIMARY KEY (rev, idx)\n\t);\n\n\t-- Authority role only. The policy is stored as its normalised lexicon\n\t-- object (com.atproto.{personal,member,managed}space.policy).\n\tCREATE TABLE IF NOT EXISTS config (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tpolicy TEXT NOT NULL\n\t);\n\n\t-- memberspace member list.\n\tCREATE TABLE IF NOT EXISTS member (\n\t\tdid TEXT PRIMARY KEY,\n\t\tcan_read INTEGER NOT NULL,\n\t\tcan_write INTEGER NOT NULL\n\t);\n\n\t-- The writer set, sequenced by space revision. A removed writer keeps\n\t-- its row, marked removed at the revision of its removal, so listWriters\n\t-- can report the removal until it writes again.\n\tCREATE TABLE IF NOT EXISTS writer (\n\t\tdid TEXT PRIMARY KEY,\n\t\trepo_rev TEXT NOT NULL,\n\t\tdata BLOB NOT NULL,\n\t\tspace_rev TEXT NOT NULL,\n\t\tremoved_at INTEGER\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_writer_space_rev ON writer(space_rev);\n\n\t-- Syncer webhook registrations, made through authorizeSpaceSync. Active\n\t-- until the credential of their latest authorization expires\n\t-- (expires_at, ms); expiry_notified marks a lapse already announced.\n\tCREATE TABLE IF NOT EXISTS notify_registration (\n\t\tendpoint TEXT NOT NULL,\n\t\ttoken TEXT NOT NULL,\n\t\texpires_at INTEGER NOT NULL,\n\t\texpiry_notified INTEGER NOT NULL DEFAULT 0,\n\t\tPRIMARY KEY (endpoint, token)\n\t);\n\n\t-- Outbound notifications, both roles. A row with a coalesce_key is\n\t-- replaced by a newer one with the same key; deadline (ms) is when\n\t-- retrying stops. policy picks the retry schedule ('fanout' | 'repo' |\n\t-- 'syncer'); auth is 'service' (a service JWT from the operator) or\n\t-- 'none' (a syncer webhook, authenticated by the token in its body).\n\tCREATE TABLE IF NOT EXISTS notify_queue (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tservice TEXT NOT NULL,\n\t\tbody TEXT NOT NULL,\n\t\tattempts INTEGER NOT NULL DEFAULT 0,\n\t\tnext_at INTEGER NOT NULL,\n\t\tdeadline INTEGER,\n\t\tcoalesce_key TEXT UNIQUE,\n\t\tpolicy TEXT NOT NULL DEFAULT 'fanout',\n\t\tauth TEXT NOT NULL DEFAULT 'service'\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_notify_queue_next ON notify_queue(next_at);\n\n\t-- Credentials for this space revoked by its authority (repo-host role).\n\tCREATE TABLE IF NOT EXISTS revoked_credential (\n\t\tjti TEXT PRIMARY KEY,\n\t\texpires_at INTEGER NOT NULL\n\t);\n\n\t-- Replay protection, both roles.\n\tCREATE TABLE IF NOT EXISTS replay (\n\t\tkind TEXT NOT NULL,\n\t\tkey TEXT NOT NULL,\n\t\texpires_at INTEGER NOT NULL,\n\t\tPRIMARY KEY (kind, key)\n\t);\n`;\n\n/** Retain oplog entries for at most this many days. */\nexport const OPLOG_RETENTION_DAYS = 30;\n/** Retain at most this many oplog entries. */\nexport const OPLOG_RETENTION_OPS = 10_000;\n/**\n * Give up delivering a notification without its own deadline after this\n * many attempts: syncer fan-out is reasonable-effort, and a syncer that\n * misses one recovers through listRepos.\n */\nexport const NOTIFY_MAX_ATTEMPTS = 5;\n/** A repo host retries its write notification to the authority this long. */\nexport const NOTIFY_WRITE_RETRY_MS = 24 * 60 * 60 * 1000;\n/**\n * A syncer's deletion or expiry notice is retried after each of these\n * delays in turn, repeating the last, for at least\n * {@link SYNCER_NOTICE_RETRY_WINDOW_MS}.\n */\nexport const SYNCER_NOTICE_RETRY_DELAYS_MS = [\n\t60_000,\n\t10 * 60_000,\n\t60 * 60_000,\n\t6 * 60 * 60_000,\n\t12 * 60 * 60_000,\n];\nexport const SYNCER_NOTICE_RETRY_WINDOW_MS = 72 * 60 * 60 * 1000;\n/** The largest notify token a syncer may register. */\nexport const MAX_NOTIFY_TOKEN_LENGTH = 512;\n/** Cap on the backoff between notification retries. */\nexport const NOTIFY_BACKOFF_MAX_MS = 60 * 60 * 1000;\n/** notifyWrite refuses repo revisions this far ahead of the clock. */\nexport const MAX_REV_CLOCK_SKEW_MS = 5 * 60 * 1000;\n/** The largest record a space repo accepts, as its DRISL encoding. */\nexport const MAX_SPACE_RECORD_BYTES = 1024 * 1024;\n/** Base delay for notification retry backoff, in milliseconds. */\nexport const NOTIFY_BACKOFF_BASE_MS = 30_000;\n\nexport const INDEX_DO_SCHEMA = `\n\tCREATE TABLE IF NOT EXISTS space (\n\t\turi TEXT PRIMARY KEY,\n\t\tauthority TEXT NOT NULL,\n\t\ttype TEXT NOT NULL,\n\t\tskey TEXT NOT NULL,\n\t\tis_authority INTEGER NOT NULL,\n\t\tstate TEXT NOT NULL, -- 'pending' | 'active' | 'deleted'\n\t\tcreated_at TEXT NOT NULL,\n\t\tupdated_at TEXT NOT NULL,\n\t\tschema_version INTEGER NOT NULL\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_space_state ON space(state);\n\n\t-- Blobs referenced by an imported space repo that had not been uploaded\n\t-- yet. uploadBlob claims them and promotes the staged copy into each\n\t-- space's blob prefix.\n\tCREATE TABLE IF NOT EXISTS pending_blob (\n\t\tcid TEXT NOT NULL,\n\t\turi TEXT NOT NULL,\n\t\tcreated_at INTEGER NOT NULL,\n\t\tPRIMARY KEY (cid, uri)\n\t);\n`;\n\n/** Forget pending imported-space blobs that were never uploaded. */\nexport const PENDING_BLOB_TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Remove `pending` index entries that never activated after this long. */\nexport const PENDING_ENTRY_TTL_MS = 24 * 60 * 60 * 1000;\n","/**\n * Commits and MACs.\n *\n * A space repo commit carries no signature. A syncer authenticates what a\n * repo host serves with a MAC instead: an HTTP message signature (RFC 9421)\n * using `hmac-sha256`, keyed by a per-request secret both sides derive with\n * HPKE secret export against the account's `#atproto_kem` key. The syncer\n * asks with `Accept-Signature`, naming its ephemeral key and a profile tag;\n * the host answers with a header describing the commit or record\n * (`Atproto-Space-Commit` / `Atproto-Space-Record`) and a MAC covering it.\n * A leaked response proves nothing to a third party. The KEM key is the only\n * secret here, and it lives with the Worker.\n */\n\nimport {\n\tCOMMIT_MAC_PROFILE,\n\tMAC_COVERED_HEADER,\n\tRECORD_MAC_PROFILE,\n\tRepoCommit,\n\tSpaceKemError,\n\tSpaceMacError,\n\tcreateCommitMacHeaders,\n\tcreateRecordMacHeaders,\n\tdecapsulate,\n\tparseMacRequest,\n} from \"@atproto/space\";\nimport type { CreateMacParams, MacProfile } from \"@atproto/space\";\nimport { P256Keypair } from \"@atproto/crypto\";\nimport { parseCid, toBase64 } from \"@atproto/lex-data\";\nimport { SpaceError } from \"./errors.js\";\nimport type { RepoState } from \"./types.js\";\n\nexport { COMMIT_MAC_PROFILE, RECORD_MAC_PROFILE };\nexport type { MacProfile };\n\n/** The MAC profiles, as plain strings for the public API. */\nexport type SpaceMacProfile = \"atproto-space-commit\" | \"atproto-space-record\";\n\n/** The request header a syncer asks for a MAC with. */\nexport const MAC_REQUEST_HEADER = \"accept-signature\";\n\n/** The response headers a browser syncer must read to check a MAC. */\nexport function macExposedHeaders(profile: SpaceMacProfile): string[] {\n\treturn [\n\t\tMAC_COVERED_HEADER[profile as MacProfile],\n\t\t\"signature-input\",\n\t\t\"signature\",\n\t];\n}\n\n/** A space repo commit (`com.atproto.space.defs#commit`). */\nexport interface SpaceCommit {\n\tver: number;\n\trepo: string;\n\tspace: string;\n\trev: string;\n\t/** sha256 digest of the LtHash state. */\n\tdata: Uint8Array;\n}\n\n/** The commit over a repo's persisted state. */\nexport function buildCommit(params: {\n\tspaceUri: string;\n\t/** The repo author (the operator DID for every repo Cirrus serves). */\n\trepo: string;\n\tstate: RepoState;\n}): SpaceCommit {\n\treturn RepoCommit.fromState(params.state.setHash).toCommit({\n\t\tspace: params.spaceUri as never,\n\t\trepo: params.repo as never,\n\t\trev: params.state.rev as never,\n\t});\n}\n\n/**\n * Lexicon JSON form of a commit (`com.atproto.space.defs#commit`): bytes\n * fields encode as `{\"$bytes\": \"<base64>\"}`.\n */\nexport function commitToJson(commit: SpaceCommit): Record<string, unknown> {\n\treturn {\n\t\tver: commit.ver,\n\t\trepo: commit.repo,\n\t\tspace: commit.space,\n\t\trev: commit.rev,\n\t\tdata: bytesToJson(commit.data),\n\t};\n}\n\n/** Lexicon JSON form of a bare bytes value. */\nexport function bytesToJson(bytes: Uint8Array): { $bytes: string } {\n\treturn { $bytes: toBase64(bytes) };\n}\n\n/** Import the account's `#atproto_kem` keypair from its hex private key. */\nexport async function importKemKeypair(\n\tprivateKeyHex: string,\n): Promise<P256Keypair> {\n\treturn P256Keypair.import(privateKeyHex);\n}\n\n/** Generate a fresh `#atproto_kem` keypair. */\nexport async function generateKemKey(): Promise<{\n\tprivateKeyHex: string;\n\t/** The public key as a did:key. */\n\tdidKey: string;\n\t/** The public key multibase, for a DID document verification method. */\n\tpublicKeyMultibase: string;\n}> {\n\tconst keypair = await P256Keypair.create({ exportable: true });\n\tconst exported = await keypair.export();\n\tconst didKey = keypair.did();\n\treturn {\n\t\tprivateKeyHex: Array.from(exported, (b) =>\n\t\t\tb.toString(16).padStart(2, \"0\"),\n\t\t).join(\"\"),\n\t\tdidKey,\n\t\tpublicKeyMultibase: didKey.slice(\"did:key:\".length),\n\t};\n}\n\n/** The public half of a KEM private key, as a did:key. */\nexport async function kemDidKey(privateKeyHex: string): Promise<string> {\n\treturn (await importKemKeypair(privateKeyHex)).did();\n}\n\nexport interface MacRequestInput {\n\t/** The `Accept-Signature` request header, if any. */\n\tacceptSignature: string | undefined;\n\t/** Whether the request was authorised by a space credential. */\n\tcredential: boolean;\n\tprofile: MacProfile;\n\tgetKemKeypair: () => Promise<P256Keypair | null>;\n}\n\n/** What a MAC is computed with, once requested and decapsulated. */\nexport type MacParams = CreateMacParams;\n\n/**\n * The MAC owed by a read that returns a commit or record. A space\n * credential must ask for one with the profile's tag; an account reading its\n * own data gets one only if it asks. Requests with other tags are ignored.\n * Returns undefined when no MAC is owed.\n */\nexport async function macRequest(\n\treq: MacRequestInput,\n): Promise<MacParams | undefined> {\n\tlet request;\n\ttry {\n\t\trequest = parseMacRequest(req.acceptSignature, req.profile);\n\t} catch (err) {\n\t\tthrow invalidMac(err);\n\t}\n\tif (!request) {\n\t\tif (!req.credential) return undefined;\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidSpaceMac\",\n\t\t\t`A MAC must be requested with tag \"${req.profile}\"`,\n\t\t);\n\t}\n\tconst keypair = await req.getKemKeypair();\n\tif (!keypair) {\n\t\tthrow new SpaceError(\n\t\t\t\"KemKeyUnavailable\",\n\t\t\t\"This host has no #atproto_kem key configured, so it cannot authenticate space data to syncers\",\n\t\t);\n\t}\n\ttry {\n\t\treturn { ...request, sharedSecret: decapsulate(keypair, request.keyShare) };\n\t} catch (err) {\n\t\tthrow invalidMac(err);\n\t}\n}\n\nfunction invalidMac(err: unknown): SpaceError {\n\tif (err instanceof SpaceMacError || err instanceof SpaceKemError) {\n\t\treturn new SpaceError(\"InvalidSpaceMac\", err.message);\n\t}\n\treturn new SpaceError(\"InvalidSpaceMac\", \"Invalid Accept-Signature header\");\n}\n\n/** The MAC response headers for a commit, when one is owed. */\nexport function commitMacHeaders(\n\tmac: MacParams | undefined,\n\tcommit: SpaceCommit,\n): Record<string, string> {\n\tif (!mac) return {};\n\treturn createCommitMacHeaders(\n\t\tcommit as Parameters<typeof createCommitMacHeaders>[0],\n\t\tmac,\n\t).headers;\n}\n\n/** The MAC response headers for a record, when one is owed. */\nexport function recordMacHeaders(\n\tmac: MacParams | undefined,\n\turi: string,\n\tcid: string,\n): Record<string, string> {\n\tif (!mac) return {};\n\treturn createRecordMacHeaders(uri as never, parseCid(cid), mac).headers;\n}\n","/**\n * Revision (TID) helpers for the space repo.\n */\n\nimport { now as tidNow } from \"@atcute/tid\";\n\nconst S32_CHAR = \"234567abcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Next revision: a fresh TID guaranteed strictly greater than `prev`.\n * `@atcute/tid`'s clock is monotonic within an isolate, but the previous\n * rev may come from a different isolate's clock (e.g. after a DO restart),\n * so bump lexicographically when needed.\n */\nexport function nextRev(prev: string | null | undefined): string {\n\tconst candidate = tidNow();\n\tif (!prev || candidate > prev) return candidate;\n\t// Increment the previous TID by one in s32 space.\n\tconst chars = prev.split(\"\");\n\tfor (let i = chars.length - 1; i >= 0; i--) {\n\t\tconst idx = S32_CHAR.indexOf(chars[i]!);\n\t\tif (idx < S32_CHAR.length - 1) {\n\t\t\tchars[i] = S32_CHAR[idx + 1]!;\n\t\t\treturn chars.join(\"\");\n\t\t}\n\t\tchars[i] = S32_CHAR[0]!;\n\t}\n\t// prev was the maximal TID; not reachable with real clocks.\n\treturn candidate;\n}\n\n/**\n * The smallest TID whose timestamp is `ms` milliseconds in the past, with a\n * zero clockid. Used as a deletion cutoff for oplog compaction.\n */\nexport function tidCutoff(msAgo: number): string {\n\tconst micros = BigInt(Math.max(0, Date.now() - msAgo)) * 1000n;\n\t// TID layout: 53 bits of microseconds followed by 10 bits of clockid,\n\t// encoded as 13 sortable-base32 characters.\n\tlet value = (micros << 10n) & ((1n << 63n) - 1n);\n\tlet out = \"\";\n\tfor (let i = 12; i >= 0; i--) {\n\t\tout = S32_CHAR[Number(value & 31n)] + out;\n\t\tvalue >>= 5n;\n\t}\n\treturn out;\n}\n\n/** The timestamp a TID encodes, in milliseconds since the epoch. */\nexport function tidTimestampMs(tid: string): number {\n\tlet value = 0n;\n\tfor (const char of tid) {\n\t\tconst idx = S32_CHAR.indexOf(char);\n\t\tif (idx === -1) throw new Error(`Invalid TID: ${tid}`);\n\t\tvalue = (value << 5n) | BigInt(idx);\n\t}\n\treturn Number(value >> 10n) / 1000;\n}\n","/**\n * Minimal atproto service-auth JWT creation, used for outbound\n * `com.atproto.space.notifyWrite` / `notifySpaceDeleted` calls. Matches the\n * shape `verifyServiceJwt` implementations expect: `{iss, aud, lxm?, jti,\n * iat, exp}` signed with the account signing key (alg from the keypair).\n */\n\nimport type { SpaceSigningKeypair } from \"./types.js\";\n\nconst encoder = new TextEncoder();\n\nfunction base64url(bytes: Uint8Array): string {\n\tlet bin = \"\";\n\tfor (const b of bytes) bin += String.fromCharCode(b);\n\treturn btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nexport interface ServiceJwtParams {\n\tiss: string;\n\taud: string;\n\tlxm?: string;\n\t/** Lifetime in seconds (default 60). */\n\texpiresInSec?: number;\n}\n\nexport async function createServiceJwt(\n\tparams: ServiceJwtParams,\n\tkeypair: SpaceSigningKeypair,\n): Promise<string> {\n\tconst iat = Math.floor(Date.now() / 1000);\n\tconst header = { typ: \"JWT\", alg: keypair.jwtAlg };\n\tconst payload: Record<string, unknown> = {\n\t\tiat,\n\t\tiss: params.iss,\n\t\taud: params.aud,\n\t\texp: iat + (params.expiresInSec ?? 60),\n\t\tjti: crypto.randomUUID(),\n\t};\n\tif (params.lxm) payload.lxm = params.lxm;\n\n\tconst signingInput = `${base64url(encoder.encode(JSON.stringify(header)))}.${base64url(\n\t\tencoder.encode(JSON.stringify(payload)),\n\t)}`;\n\tconst sig = await keypair.sign(encoder.encode(signingInput));\n\treturn `${signingInput}.${base64url(sig)}`;\n}\n","/**\n * SpaceDurableObject โ one instance per space, addressed by\n * `idFromName(spaceUri)`.\n *\n * Holds everything Cirrus knows about that space: the operator's\n * permissioned repo (records, oplog, LtHash state, blob references) and,\n * when the operator is the authority, the space's policy, member list,\n * writer set (sequenced by space revision) and notification registrations.\n * Both roles share the outbound notification queue, and the replay and\n * revocation tables for tokens presented against the space.\n *\n * Constraints inherited from the Cirrus architecture:\n * - No R2 I/O in here, ever. Blobs are the Worker's job.\n * - No key material in here except through\n * {@link SpaceHostConfig.getKeypair}, used only for outbound notification\n * service JWTs from the alarm. Commits are unsigned and MACs are the\n * Worker's, so the KEM key never enters this class.\n * - The host supplies its identity via {@link getHostConfig}; this class\n * must not read `env.DID`. If it ever contains a branch on which host is\n * running it, the boundary has failed.\n */\n\nimport { DurableObject } from \"cloudflare:workers\";\nimport { RepoCommit } from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport {\n\tMEMBER_COLLECTION,\n\tPOLICY_COLLECTION,\n\tPOLICY_RKEY,\n\tareMembersPublished,\n\tassertMemberspace,\n\tdidToRecordKey,\n\tisPolicyPublished,\n} from \"./policy.js\";\nimport { prepareRecord } from \"./records.js\";\nimport {\n\tNOTIFY_BACKOFF_BASE_MS,\n\tNOTIFY_BACKOFF_MAX_MS,\n\tNOTIFY_MAX_ATTEMPTS,\n\tOPLOG_RETENTION_DAYS,\n\tOPLOG_RETENTION_OPS,\n\tSPACE_DO_SCHEMA,\n\tSPACE_SCHEMA_VERSION,\n\tSYNCER_NOTICE_RETRY_DELAYS_MS,\n\tSYNCER_NOTICE_RETRY_WINDOW_MS,\n} from \"./schema.js\";\nimport { bytesToJson } from \"./mac.js\";\nimport { nextRev, tidCutoff } from \"./tid.js\";\nimport { createServiceJwt } from \"./service-jwt.js\";\nimport type {\n\tApplyWritesResult,\n\tImportedRecord,\n\tNotifyItem,\n\tNotifyRegistration,\n\tOplogEntry,\n\tPreparedSpaceWrite,\n\tRepoCommitResult,\n\tRepoState,\n\tSpaceHostConfig,\n\tSpaceMember,\n\tSpaceMeta,\n\tSpacePolicy,\n\tSpaceRecordRow,\n\tSpaceSequence,\n\tSpaceWriter,\n} from \"./types.js\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** Interval between maintenance passes (compaction, replay cleanup). */\nconst MAINTENANCE_INTERVAL_MS = DAY_MS;\n/** How many queued notifications to attempt per alarm invocation. */\nconst NOTIFY_BATCH = 20;\n\ninterface QueueRow {\n\tid: number;\n\tservice: string;\n\tbody: string;\n\tattempts: number;\n\tnext_at: number;\n\tdeadline: number | null;\n\tpolicy: \"fanout\" | \"repo\" | \"syncer\";\n\tauth: \"service\" | \"none\";\n}\n\nconst NOTIFY_SPACE_UPDATE_LXM = \"com.atproto.space.notifySpaceUpdate\";\nconst REPO_WRITE = \"com.atproto.space.defs#repoWrite\";\nconst REPO_REMOVED = \"com.atproto.space.defs#repoRemoved\";\nconst SPACE_DELETED = \"com.atproto.space.notifySpaceUpdate#spaceDeleted\";\nconst REGISTRATION_EXPIRED =\n\t\"com.atproto.space.notifySpaceUpdate#registrationExpired\";\n\n/** 50-100% of a delay, so retries from many spaces don't align. */\nfunction jitter(delay: number): number {\n\treturn Math.floor(delay * (0.5 + Math.random() / 2));\n}\n\n/** HTTP statuses worth retrying; anything else is a permanent refusal. */\nexport function isRetryableStatus(status: number): boolean {\n\treturn status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\nexport abstract class SpaceDurableObject<\n\tEnv = unknown,\n> extends DurableObject<Env> {\n\tprivate sql: SqlStorage;\n\tprivate initialized = false;\n\tprivate outdated = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.sql = ctx.storage.sql;\n\t}\n\n\t/**\n\t * Host identity and signing configuration. Implemented by the host\n\t * Worker's subclass; see {@link SpaceHostConfig}.\n\t */\n\tprotected abstract getHostConfig():\n\t\t| SpaceHostConfig\n\t\t| Promise<SpaceHostConfig>;\n\n\t// ------------------------------------------------------------------\n\t// Initialisation and schema versioning\n\t// ------------------------------------------------------------------\n\n\tprivate async ensureInitialized(): Promise<void> {\n\t\tif (this.initialized) return;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tif (this.initialized) return;\n\t\t\tconst hasMeta =\n\t\t\t\tthis.sql\n\t\t\t\t\t.exec(\n\t\t\t\t\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'\",\n\t\t\t\t\t)\n\t\t\t\t\t.toArray().length > 0;\n\t\t\tif (hasMeta) {\n\t\t\t\tconst row = this.sql\n\t\t\t\t\t.exec(\"SELECT schema_version FROM meta LIMIT 1\")\n\t\t\t\t\t.toArray()[0];\n\t\t\t\tif (row && (row.schema_version as number) !== SPACE_SCHEMA_VERSION) {\n\t\t\t\t\t// Alpha policy: no migrations between schema versions. The DO\n\t\t\t\t\t// refuses every RPC until `pds spaces reset` wipes it.\n\t\t\t\t\tthis.outdated = true;\n\t\t\t\t\tthis.initialized = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.sql.exec(SPACE_DO_SCHEMA);\n\t\t\tthis.initialized = true;\n\t\t});\n\t}\n\n\t/**\n\t * Gate every RPC: initialise storage and refuse when the stored schema\n\t * belongs to a different alpha build.\n\t */\n\tprivate async ensureOpen(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpacesSchemaOutdated\",\n\t\t\t\t\"Space data was written by an incompatible alpha build. Run `pds spaces reset` to wipe space data (the public repo is unaffected).\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate readMeta(): SpaceMeta | null {\n\t\tconst row = this.sql.exec(\"SELECT * FROM meta LIMIT 1\").toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\turi: row.uri as string,\n\t\t\tauthority: row.authority as string,\n\t\t\ttype: row.type as string,\n\t\t\tskey: row.skey as string,\n\t\t\tisAuthority: (row.is_authority as number) === 1,\n\t\t\tcreatedAt: row.created_at as string,\n\t\t\tdeletedAt: (row.deleted_at as string | null) ?? null,\n\t\t};\n\t}\n\n\t/** Meta for an existing, non-deleted space, or throw. */\n\tprivate requireLiveMeta(): SpaceMeta {\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space is not initialised\");\n\t\t}\n\t\tif (meta.deletedAt) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space has been deleted\");\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** The policy of a live space this host governs, or SpaceNotFound. */\n\tprivate requirePolicy(): { meta: SpaceMeta; policy: SpacePolicy } {\n\t\tconst meta = this.requireLiveMeta();\n\t\tconst policy = this.readPolicy();\n\t\tif (!policy) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space not found\");\n\t\t}\n\t\treturn { meta, policy };\n\t}\n\n\tasync rpcGetMeta(): Promise<SpaceMeta | null> {\n\t\tawait this.ensureOpen();\n\t\treturn this.readMeta();\n\t}\n\n\t/**\n\t * Initialise this DO as the operator's repo in a space (either role).\n\t * For the authority role a policy creates the space: refused when a live\n\t * space already has one. A deleted space may be created again; its\n\t * tables were wiped at deletion, so reviving is a fresh start. Returns\n\t * the commit when publishing the policy wrote to the repo.\n\t */\n\tasync rpcInit(params: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tisAuthority: boolean;\n\t\tpolicy?: SpacePolicy;\n\t}): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst existing = this.readMeta();\n\t\tif (existing && existing.uri !== params.uri) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Space DO already holds ${existing.uri}`,\n\t\t\t);\n\t\t}\n\t\tif (existing && !existing.deletedAt && params.policy && this.readPolicy()) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpaceAlreadyExists\",\n\t\t\t\t`Space already exists: ${params.uri}`,\n\t\t\t);\n\t\t}\n\t\tconst publishWrites = params.policy\n\t\t\t? await this.preparePolicyRecordWrites(params.policy)\n\t\t\t: [];\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tif (!existing) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)\n\t\t\t\t\t VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`,\n\t\t\t\t\tparams.uri,\n\t\t\t\t\tparams.authority,\n\t\t\t\t\tparams.type,\n\t\t\t\t\tparams.skey,\n\t\t\t\t\tparams.isAuthority ? 1 : 0,\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tSPACE_SCHEMA_VERSION,\n\t\t\t\t);\n\t\t\t} else if (existing.deletedAt) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"UPDATE meta SET deleted_at = NULL, created_at = ?, is_authority = ?\",\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tparams.isAuthority ? 1 : 0,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!params.policy) return null;\n\t\t\tthis.writePolicy(params.policy);\n\t\t\treturn this.applyWritesSync(publishWrites);\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Permissioned repo: writes\n\t// ------------------------------------------------------------------\n\n\tasync rpcApplyWrites(\n\t\twrites: PreparedSpaceWrite[],\n\t): Promise<ApplyWritesResult> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(\n\t\t\t() => this.applyWritesSync(writes)!,\n\t\t);\n\t}\n\n\t/**\n\t * Apply a batch as one commit sharing a single rev. Must run in a\n\t * transaction. Returns null for an empty batch. Each write lands before\n\t * the next is read, so a batch can create and then update a record, and\n\t * a repeated create is refused rather than counted twice.\n\t */\n\tprivate applyWritesSync(\n\t\twrites: PreparedSpaceWrite[],\n\t): ApplyWritesResult | null {\n\t\tif (writes.length === 0) return null;\n\t\tconst state = this.readRepoState();\n\t\tconst commit = RepoCommit.fromState(state?.setHash ?? null);\n\t\tconst rev = nextRev(state?.rev ?? null);\n\t\tconst indexedAt = new Date().toISOString();\n\t\tconst results: ApplyWritesResult[\"results\"] = [];\n\t\tlet idx = 0;\n\n\t\tfor (const write of writes) {\n\t\t\tconst prevRow = this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT cid FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t)\n\t\t\t\t.toArray()[0];\n\t\t\tconst prev = prevRow ? (prevRow.cid as string) : null;\n\n\t\t\tif (write.action === \"create\" && prev) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordAlreadyExists\",\n\t\t\t\t\t`Record already exists: ${write.collection}/${write.rkey}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (write.action !== \"create\" && !prev) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordNotFound\",\n\t\t\t\t\t`Record not found: ${write.collection}/${write.rkey}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (write.action === \"delete\") {\n\t\t\t\tthis.deleteRecordRow(write.collection, write.rkey);\n\t\t\t\tcommit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);\n\t\t\t\tthis.appendOplog(rev, idx++, write.collection, write.rkey, null, prev);\n\t\t\t\tresults.push({\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\tcid: null,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT OR REPLACE INTO record (collection, rkey, cid, bytes, rev, indexed_at)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\t\twrite.collection,\n\t\t\t\twrite.rkey,\n\t\t\t\twrite.cid,\n\t\t\t\twrite.bytes,\n\t\t\t\trev,\n\t\t\t\tindexedAt,\n\t\t\t);\n\t\t\tthis.replaceRecordBlobs(write.collection, write.rkey, write.blobCids);\n\t\t\tif (prev) {\n\t\t\t\tcommit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);\n\t\t\t}\n\t\t\tcommit.setHash.add(`${write.collection}/${write.rkey}/${write.cid}`);\n\t\t\tthis.appendOplog(\n\t\t\t\trev,\n\t\t\t\tidx++,\n\t\t\t\twrite.collection,\n\t\t\t\twrite.rkey,\n\t\t\t\twrite.cid,\n\t\t\t\tprev,\n\t\t\t);\n\t\t\tresults.push({\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t\trkey: write.rkey,\n\t\t\t\tcid: write.cid,\n\t\t\t});\n\t\t}\n\n\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\treturn { rev, data: commit.setHash.digest(), results };\n\t}\n\n\tprivate deleteRecordRow(collection: string, rkey: string): void {\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record_blob WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t}\n\n\tprivate replaceRecordBlobs(\n\t\tcollection: string,\n\t\trkey: string,\n\t\tblobCids: string[],\n\t): void {\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record_blob WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t\tfor (const blobCid of blobCids) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"INSERT OR IGNORE INTO record_blob (blob_cid, collection, rkey) VALUES (?, ?, ?)\",\n\t\t\t\tblobCid,\n\t\t\t\tcollection,\n\t\t\t\trkey,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate writeRepoState(setHash: Uint8Array, rev: string): void {\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO repo_state (id, set_hash, rev) VALUES (1, ?, ?)\n\t\t\t ON CONFLICT (id) DO UPDATE SET set_hash = excluded.set_hash, rev = excluded.rev`,\n\t\t\tsetHash,\n\t\t\trev,\n\t\t);\n\t}\n\n\tprivate appendOplog(\n\t\trev: string,\n\t\tidx: number,\n\t\tcollection: string,\n\t\trkey: string,\n\t\tcid: string | null,\n\t\tprev: string | null,\n\t): void {\n\t\tthis.sql.exec(\n\t\t\t\"INSERT INTO oplog (rev, idx, collection, rkey, cid, prev) VALUES (?, ?, ?, ?, ?, ?)\",\n\t\t\trev,\n\t\t\tidx,\n\t\t\tcollection,\n\t\t\trkey,\n\t\t\tcid,\n\t\t\tprev,\n\t\t);\n\t}\n\n\t/** The collections the repo holds records in, for clearRecords' grants. */\n\tasync rpcListCollections(): Promise<string[]> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.sql\n\t\t\t.exec(\"SELECT DISTINCT collection FROM record ORDER BY collection\")\n\t\t\t.toArray()\n\t\t\t.map((row) => row.collection as string);\n\t}\n\n\t/**\n\t * Delete every record outside `keep` and clear the oplog, leaving the\n\t * repo at a new rev with the digest of what remains. Returns null when\n\t * there was nothing to delete.\n\t */\n\tasync rpcClearRecords(keep: string[]): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst state = this.readRepoState();\n\t\t\tif (!state) return null;\n\t\t\tconst placeholders = keep.map(() => \"?\").join(\", \");\n\t\t\tconst notKept =\n\t\t\t\tkeep.length > 0 ? `collection NOT IN (${placeholders})` : \"1=1\";\n\t\t\tconst doomed = this.sql\n\t\t\t\t.exec(`SELECT COUNT(*) AS n FROM record WHERE ${notKept}`, ...keep)\n\t\t\t\t.toArray()[0]?.n as number;\n\t\t\tif (!doomed) return null;\n\t\t\tthis.sql.exec(`DELETE FROM record_blob WHERE ${notKept}`, ...keep);\n\t\t\tthis.sql.exec(`DELETE FROM record WHERE ${notKept}`, ...keep);\n\t\t\tthis.sql.exec(\"DELETE FROM oplog\");\n\t\t\tconst commit = new RepoCommit();\n\t\t\tfor (const row of this.sql\n\t\t\t\t.exec(\"SELECT collection, rkey, cid FROM record\")\n\t\t\t\t.toArray()) {\n\t\t\t\tcommit.setHash.add(`${row.collection}/${row.rkey}/${row.cid}`);\n\t\t\t}\n\t\t\tconst rev = nextRev(state.rev);\n\t\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\t\treturn { rev, data: commit.setHash.digest() };\n\t\t});\n\t}\n\n\t/**\n\t * Replace the repo with records imported from its previous host. Takes a\n\t * new rev here and none of its history, so the oplog starts empty.\n\t * Returns the digest so the Worker can confirm it matches the archive's\n\t * commit.\n\t */\n\tasync rpcImportRepo(records: ImportedRecord[]): Promise<RepoCommitResult> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst state = this.readRepoState();\n\t\t\tthis.sql.exec(\"DELETE FROM record_blob\");\n\t\t\tthis.sql.exec(\"DELETE FROM record\");\n\t\t\tthis.sql.exec(\"DELETE FROM oplog\");\n\t\t\tconst rev = nextRev(state?.rev ?? null);\n\t\t\tconst indexedAt = new Date().toISOString();\n\t\t\tconst commit = new RepoCommit();\n\t\t\tfor (const record of records) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO record (collection, rkey, cid, bytes, rev, indexed_at)\n\t\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\t\t\trecord.collection,\n\t\t\t\t\trecord.rkey,\n\t\t\t\t\trecord.cid,\n\t\t\t\t\trecord.bytes,\n\t\t\t\t\trev,\n\t\t\t\t\tindexedAt,\n\t\t\t\t);\n\t\t\t\tthis.replaceRecordBlobs(\n\t\t\t\t\trecord.collection,\n\t\t\t\t\trecord.rkey,\n\t\t\t\t\trecord.blobCids,\n\t\t\t\t);\n\t\t\t\tcommit.setHash.add(`${record.collection}/${record.rkey}/${record.cid}`);\n\t\t\t}\n\t\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\t\treturn { rev, data: commit.setHash.digest() };\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Permissioned repo: reads\n\t// ------------------------------------------------------------------\n\n\tprivate readRepoState(): RepoState | null {\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT set_hash, rev FROM repo_state WHERE id = 1\")\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tsetHash: new Uint8Array(row.set_hash as ArrayBuffer),\n\t\t\trev: row.rev as string,\n\t\t};\n\t}\n\n\tasync rpcGetRecord(\n\t\tcollection: string,\n\t\trkey: string,\n\t): Promise<{ cid: string; bytes: Uint8Array } | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT cid, bytes FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\tcollection,\n\t\t\t\trkey,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tcid: row.cid as string,\n\t\t\tbytes: new Uint8Array(row.bytes as ArrayBuffer),\n\t\t};\n\t}\n\n\t/**\n\t * List records ordered by (collection, rkey) โ equivalent to record-URI\n\t * order since every record shares the space and repo prefix. Descending\n\t * by default, matching the reference; `reverse` flips to ascending.\n\t */\n\tasync rpcListRecords(params: {\n\t\tcollection?: string;\n\t\tlimit: number;\n\t\tafter?: { collection: string; rkey: string };\n\t\treverse?: boolean;\n\t\texcludeValues?: boolean;\n\t}): Promise<{ records: SpaceRecordRow[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst asc = params.reverse === true;\n\t\tconst op = asc ? \">\" : \"<\";\n\t\tconst order = asc ? \"ASC\" : \"DESC\";\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.collection) {\n\t\t\twhere += \" AND collection = ?\";\n\t\t\targs.push(params.collection);\n\t\t}\n\t\tif (params.after) {\n\t\t\twhere += ` AND (collection ${op} ? OR (collection = ? AND rkey ${op} ?))`;\n\t\t\targs.push(\n\t\t\t\tparams.after.collection,\n\t\t\t\tparams.after.collection,\n\t\t\t\tparams.after.rkey,\n\t\t\t);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT collection, rkey, cid${params.excludeValues ? \"\" : \", bytes\"} FROM record\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY collection ${order}, rkey ${order}\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\trecords: page.map((row) => ({\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tcid: row.cid as string,\n\t\t\t\t...(params.excludeValues\n\t\t\t\t\t? {}\n\t\t\t\t\t: { bytes: new Uint8Array(row.bytes as ArrayBuffer) }),\n\t\t\t})),\n\t\t\thasMore,\n\t\t};\n\t}\n\n\t/**\n\t * Records in strict byte order of their `{collection}/{rkey}` path, as a\n\t * repo archive requires โ not (collection, rkey) order, which differs\n\t * when one collection NSID prefixes another. `state` is the repo state\n\t * the page was read at: the page and the state are one snapshot\n\t * (synchronous reads, single-threaded DO), so a streaming export can\n\t * fence against concurrent writes.\n\t */\n\tasync rpcListRecordsByPath(params: {\n\t\tafterPath?: string;\n\t\tlimit: number;\n\t}): Promise<{\n\t\trecords: Array<{ collection: string; rkey: string; bytes: Uint8Array }>;\n\t\thasMore: boolean;\n\t\tstate: RepoState | null;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst state = this.readRepoState();\n\t\t// SQLite's default BINARY collation compares UTF-8 bytes, which is\n\t\t// the archive's order.\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT collection, rkey, bytes FROM record\n\t\t\t\t ${params.afterPath !== undefined ? \"WHERE collection || '/' || rkey > ?\" : \"\"}\n\t\t\t\t ORDER BY collection || '/' || rkey ASC\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...(params.afterPath !== undefined ? [params.afterPath] : []),\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\trecords: page.map((row) => ({\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tbytes: new Uint8Array(row.bytes as ArrayBuffer),\n\t\t\t})),\n\t\t\thasMore,\n\t\t\tstate,\n\t\t};\n\t}\n\n\t/**\n\t * What listSpaces reports for this space: the operator's repo state in\n\t * it and, for a space the operator is the authority of, its revision.\n\t */\n\tasync rpcGetSpaceView(): Promise<{\n\t\trepoRev?: string;\n\t\tdata?: Uint8Array;\n\t\tspaceRev?: string;\n\t} | null> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta || meta.deletedAt) return null;\n\t\tconst state = this.readRepoState();\n\t\tconst spaceRev = meta.isAuthority ? this.currentSpaceRev() : null;\n\t\treturn {\n\t\t\t...(state\n\t\t\t\t? {\n\t\t\t\t\t\trepoRev: state.rev,\n\t\t\t\t\t\tdata: RepoCommit.fromState(state.setHash).setHash.digest(),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(spaceRev ? { spaceRev } : {}),\n\t\t};\n\t}\n\n\tasync rpcGetRepoState(): Promise<RepoState | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.readRepoState();\n\t}\n\n\t/**\n\t * List oplog entries after `since` (a rev) or `after` (an exact cursor\n\t * position). Creates and updates carry the record's current bytes when\n\t * the oplog cid still matches the live record; superseded values are\n\t * omitted. When the page reaches the head, `head` carries the repo\n\t * state read in the same transaction so the Worker can attach the\n\t * commit without a state race.\n\t */\n\tasync rpcListRepoOps(params: {\n\t\tsince?: string;\n\t\tafter?: { rev: string; idx: number };\n\t\tlimit: number;\n\t\texcludeValues?: boolean;\n\t}): Promise<{ ops: OplogEntry[]; hasMore: boolean; head?: RepoState }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst args: unknown[] = [];\n\t\t\tlet where = \"1=1\";\n\t\t\tif (params.after) {\n\t\t\t\twhere += \" AND (o.rev > ? OR (o.rev = ? AND o.idx > ?))\";\n\t\t\t\targs.push(params.after.rev, params.after.rev, params.after.idx);\n\t\t\t} else if (params.since) {\n\t\t\t\twhere += \" AND o.rev > ?\";\n\t\t\t\targs.push(params.since);\n\t\t\t}\n\t\t\tconst values = params.excludeValues ? \"\" : \", r.bytes AS live_bytes\";\n\t\t\tconst rows = this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t`SELECT o.rev, o.idx, o.collection, o.rkey, o.cid, o.prev${values}\n\t\t\t\t\t FROM oplog o\n\t\t\t\t\t ${params.excludeValues ? \"\" : \"LEFT JOIN record r ON r.collection = o.collection AND r.rkey = o.rkey AND r.cid = o.cid\"}\n\t\t\t\t\t WHERE ${where}\n\t\t\t\t\t ORDER BY o.rev ASC, o.idx ASC\n\t\t\t\t\t LIMIT ?`,\n\t\t\t\t\t...args,\n\t\t\t\t\tparams.limit + 1,\n\t\t\t\t)\n\t\t\t\t.toArray();\n\t\t\tconst hasMore = rows.length > params.limit;\n\t\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\t\tconst ops: OplogEntry[] = page.map((row) => ({\n\t\t\t\trev: row.rev as string,\n\t\t\t\tidx: row.idx as number,\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tcid: (row.cid as string | null) ?? null,\n\t\t\t\tprev: (row.prev as string | null) ?? null,\n\t\t\t\t...(row.live_bytes\n\t\t\t\t\t? { bytes: new Uint8Array(row.live_bytes as ArrayBuffer) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\t// The commit is returned on every page, read in the same\n\t\t\t// transaction so it never races the page.\n\t\t\tconst head = this.readRepoState();\n\t\t\treturn { ops, hasMore, ...(head ? { head } : {}) };\n\t\t});\n\t}\n\n\t/** Distinct blob CIDs referenced by records, ascending, paged. */\n\tasync rpcListBlobs(params: {\n\t\tsince?: string;\n\t\tlimit: number;\n\t\tafterCid?: string;\n\t}): Promise<{ cids: string[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.since) {\n\t\t\twhere += \" AND r.rev > ?\";\n\t\t\targs.push(params.since);\n\t\t}\n\t\tif (params.afterCid) {\n\t\t\twhere += \" AND b.blob_cid > ?\";\n\t\t\targs.push(params.afterCid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT DISTINCT b.blob_cid FROM record_blob b\n\t\t\t\t JOIN record r ON r.collection = b.collection AND r.rkey = b.rkey\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY b.blob_cid ASC\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { cids: page.map((r) => r.blob_cid as string), hasMore };\n\t}\n\n\t/** Whether a blob CID is referenced by any record in this space. */\n\tasync rpcHasSpaceBlob(cid: string): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\"SELECT 1 FROM record_blob WHERE blob_cid = ? LIMIT 1\", cid)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Replay protection and revocation\n\t// ------------------------------------------------------------------\n\n\t/**\n\t * Record a single-use key. Returns true when the key was fresh (now\n\t * recorded), false when it was already seen and must be refused.\n\t */\n\tasync rpcCheckReplay(\n\t\tkind: string,\n\t\tkey: string,\n\t\texpiresAtSec: number,\n\t): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tconst result = this.sql.exec(\n\t\t\t\"INSERT OR IGNORE INTO replay (kind, key, expires_at) VALUES (?, ?, ?)\",\n\t\t\tkind,\n\t\t\tkey,\n\t\t\texpiresAtSec,\n\t\t);\n\t\treturn result.rowsWritten > 0;\n\t}\n\n\t/**\n\t * Record credentials the authority revoked (repo-host role). Held until\n\t * any credential with that jti must have expired anyway. Needs no live\n\t * repo: a revocation can precede the first write.\n\t */\n\tasync rpcRevokeCredentials(\n\t\tjtis: string[],\n\t\texpiresAtSec: number,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tfor (const jti of jtis) {\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT INTO revoked_credential (jti, expires_at) VALUES (?, ?)\n\t\t\t\t ON CONFLICT (jti) DO UPDATE SET expires_at = excluded.expires_at`,\n\t\t\t\tjti,\n\t\t\t\texpiresAtSec,\n\t\t\t);\n\t\t}\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tasync rpcIsCredentialRevoked(jti: string): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT 1 FROM revoked_credential WHERE jti = ? AND expires_at > ?\",\n\t\t\t\t\tjti,\n\t\t\t\t\tMath.floor(Date.now() / 1000),\n\t\t\t\t)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Authority role: policy, members, writers, notifications\n\t// ------------------------------------------------------------------\n\n\tprivate writePolicy(policy: SpacePolicy): void {\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO config (id, policy) VALUES (1, ?)\n\t\t\t ON CONFLICT (id) DO UPDATE SET policy = excluded.policy`,\n\t\t\tJSON.stringify(policy),\n\t\t);\n\t}\n\n\tprivate readPolicy(): SpacePolicy | null {\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT policy FROM config WHERE id = 1\")\n\t\t\t.toArray()[0];\n\t\treturn row ? (JSON.parse(row.policy as string) as SpacePolicy) : null;\n\t}\n\n\t/**\n\t * State needed to answer getSpaceCredential and notifyWrite: meta\n\t * (including the deletion tombstone) and the policy. Never throws on a\n\t * deleted space โ a late credential request must get SpaceDeleted, not\n\t * SpaceNotFound, and that mapping is the caller's.\n\t */\n\tasync rpcGetAuthorityState(): Promise<{\n\t\tmeta: SpaceMeta | null;\n\t\tpolicy: SpacePolicy | null;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\treturn { meta: this.readMeta(), policy: this.readPolicy() };\n\t}\n\n\tprivate hasRecord(collection: string, rkey: string): boolean {\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT 1 FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\tcollection,\n\t\t\t\t\trkey,\n\t\t\t\t)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\tprivate async preparePut(\n\t\tcollection: string,\n\t\trkey: string,\n\t\trecord: Record<string, unknown>,\n\t): Promise<PreparedSpaceWrite> {\n\t\tconst prepared = await prepareRecord(record);\n\t\treturn {\n\t\t\taction: this.hasRecord(collection, rkey) ? \"update\" : \"create\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t\tcid: prepared.cid,\n\t\t\tbytes: prepared.bytes,\n\t\t\tblobCids: prepared.blobCids,\n\t\t};\n\t}\n\n\tprivate prepareDeleteIfExists(\n\t\tcollection: string,\n\t\trkey: string,\n\t): PreparedSpaceWrite[] {\n\t\treturn this.hasRecord(collection, rkey)\n\t\t\t? [{ action: \"delete\", collection, rkey }]\n\t\t\t: [];\n\t}\n\n\t/** Publish, update or withdraw the policy record to match the policy. */\n\tprivate async preparePolicyRecordWrites(\n\t\tpolicy: SpacePolicy,\n\t): Promise<PreparedSpaceWrite[]> {\n\t\tif (isPolicyPublished(policy)) {\n\t\t\treturn [\n\t\t\t\tawait this.preparePut(POLICY_COLLECTION, POLICY_RKEY, {\n\t\t\t\t\t$type: POLICY_COLLECTION,\n\t\t\t\t\tpolicy,\n\t\t\t\t}),\n\t\t\t];\n\t\t}\n\t\treturn this.prepareDeleteIfExists(POLICY_COLLECTION, POLICY_RKEY);\n\t}\n\n\t/**\n\t * Publish, update or withdraw a member's record to match their entry.\n\t * `access` is omitted for a DID that is no longer a member.\n\t */\n\tprivate async prepareMemberRecordWrites(\n\t\tpolicy: SpacePolicy,\n\t\tdid: string,\n\t\taccess?: { read: boolean; write: boolean },\n\t): Promise<PreparedSpaceWrite[]> {\n\t\tconst rkey = didToRecordKey(did);\n\t\tif (access && areMembersPublished(policy)) {\n\t\t\treturn [\n\t\t\t\tawait this.preparePut(MEMBER_COLLECTION, rkey, {\n\t\t\t\t\t$type: MEMBER_COLLECTION,\n\t\t\t\t\tread: access.read,\n\t\t\t\t\twrite: access.write,\n\t\t\t\t}),\n\t\t\t];\n\t\t}\n\t\treturn this.prepareDeleteIfExists(MEMBER_COLLECTION, rkey);\n\t}\n\n\tprivate readMembers(): SpaceMember[] {\n\t\treturn this.sql\n\t\t\t.exec(\"SELECT did, can_read, can_write FROM member ORDER BY did\")\n\t\t\t.toArray()\n\t\t\t.map((row) => ({\n\t\t\t\tdid: row.did as string,\n\t\t\t\tread: (row.can_read as number) === 1,\n\t\t\t\twrite: (row.can_write as number) === 1,\n\t\t\t}));\n\t}\n\n\t/**\n\t * Replace the policy wholesale. A different `$type` migrates the space:\n\t * state held by the previous policy (the member list) is discarded, and\n\t * a published member list is withdrawn with it.\n\t */\n\tasync rpcUpdatePolicy(next: SpacePolicy): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy: current } = this.requirePolicy();\n\t\tconst writes = await this.preparePolicyRecordWrites(next);\n\t\tif (areMembersPublished(current) !== areMembersPublished(next)) {\n\t\t\tfor (const member of this.readMembers()) {\n\t\t\t\twrites.push(\n\t\t\t\t\t...(await this.prepareMemberRecordWrites(next, member.did, member)),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tthis.writePolicy(next);\n\t\t\tif (current.$type !== next.$type) {\n\t\t\t\tthis.sql.exec(\"DELETE FROM member\");\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t}\n\n\t/**\n\t * Add members or replace their access, in one commit. A DID listed twice\n\t * takes its last entry. Revoking write access removes the member from\n\t * the writer set, sequenced and announced like any removal.\n\t */\n\tasync rpcPutMembers(\n\t\tmembers: SpaceMember[],\n\t): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst byDid = new Map(members.map((m) => [m.did, m]));\n\t\tconst writes: PreparedSpaceWrite[] = [];\n\t\tfor (const member of byDid.values()) {\n\t\t\twrites.push(\n\t\t\t\t...(await this.prepareMemberRecordWrites(policy, member.did, member)),\n\t\t\t);\n\t\t}\n\t\tconst commit = this.ctx.storage.transactionSync(() => {\n\t\t\tfor (const member of byDid.values()) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)\n\t\t\t\t\t ON CONFLICT (did) DO UPDATE SET can_read = excluded.can_read, can_write = excluded.can_write`,\n\t\t\t\t\tmember.did,\n\t\t\t\t\tmember.read ? 1 : 0,\n\t\t\t\t\tmember.write ? 1 : 0,\n\t\t\t\t);\n\t\t\t\tif (!member.write) this.removeWriterSync(member.did);\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t\treturn commit;\n\t}\n\n\t/**\n\t * Remove members, in one commit, and from the writer set. DIDs that are\n\t * not members are ignored, leaving any writer set entry alone.\n\t */\n\tasync rpcRemoveMembers(dids: string[]): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst members = [...new Set(dids)].filter(\n\t\t\t(did) =>\n\t\t\t\tthis.sql.exec(\"SELECT 1 FROM member WHERE did = ?\", did).toArray()\n\t\t\t\t\t.length > 0,\n\t\t);\n\t\tconst writes: PreparedSpaceWrite[] = [];\n\t\tfor (const did of members) {\n\t\t\twrites.push(...(await this.prepareMemberRecordWrites(policy, did)));\n\t\t}\n\t\tconst commit = this.ctx.storage.transactionSync(() => {\n\t\t\tfor (const did of members) {\n\t\t\t\tthis.sql.exec(\"DELETE FROM member WHERE did = ?\", did);\n\t\t\t\tthis.removeWriterSync(did);\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t\treturn commit;\n\t}\n\n\tasync rpcGetMember(did: string): Promise<SpaceMember | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT did, can_read, can_write FROM member WHERE did = ?\", did)\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tdid: row.did as string,\n\t\t\tread: (row.can_read as number) === 1,\n\t\t\twrite: (row.can_write as number) === 1,\n\t\t};\n\t}\n\n\tasync rpcListMembers(params: {\n\t\tlimit: number;\n\t\tafterDid?: string;\n\t}): Promise<{ members: SpaceMember[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.afterDid) {\n\t\t\twhere += \" AND did > ?\";\n\t\t\targs.push(params.afterDid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT did, can_read, can_write FROM member WHERE ${where} ORDER BY did ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\tmembers: page.map((row) => ({\n\t\t\t\tdid: row.did as string,\n\t\t\t\tread: (row.can_read as number) === 1,\n\t\t\t\twrite: (row.can_write as number) === 1,\n\t\t\t})),\n\t\t\thasMore,\n\t\t};\n\t}\n\n\t/** The space's current revision: the latest in its writer set, removals included. */\n\tprivate currentSpaceRev(): string | null {\n\t\treturn (\n\t\t\t(this.sql.exec(\"SELECT MAX(space_rev) AS rev FROM writer\").toArray()[0]\n\t\t\t\t?.rev as string | null) ?? null\n\t\t);\n\t}\n\n\tasync rpcGetSpaceRev(): Promise<string | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\treturn this.currentSpaceRev();\n\t}\n\n\t/**\n\t * Record a writer's latest (repoRev, data), from notifyRepoUpdate or own\n\t * writes, advance the space sequence, and queue the update for the\n\t * registered syncers in the same transaction. Monotonic per writer: a\n\t * delayed or replayed notification with an older (or equal) rev changes\n\t * nothing and returns null. A newer write from a removed writer re-adds\n\t * it.\n\t */\n\tasync rpcRecordWriter(\n\t\tdid: string,\n\t\trepoRev: string,\n\t\tdata: Uint8Array,\n\t): Promise<SpaceSequence | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { meta } = this.requirePolicy();\n\t\tconst sequence = this.ctx.storage.transactionSync(() => {\n\t\t\tconst existing = this.sql\n\t\t\t\t.exec(\"SELECT repo_rev FROM writer WHERE did = ?\", did)\n\t\t\t\t.toArray()[0];\n\t\t\tif (existing && (existing.repo_rev as string) >= repoRev) return null;\n\t\t\tconst prevSpaceRev = this.currentSpaceRev();\n\t\t\tconst spaceRev = nextRev(prevSpaceRev);\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)\n\t\t\t\t ON CONFLICT (did) DO UPDATE SET repo_rev = excluded.repo_rev, data = excluded.data,\n\t\t\t\t\tspace_rev = excluded.space_rev, removed_at = NULL`,\n\t\t\t\tdid,\n\t\t\t\trepoRev,\n\t\t\t\tdata,\n\t\t\t\tspaceRev,\n\t\t\t);\n\t\t\tconst sequence = { spaceRev, ...(prevSpaceRev ? { prevSpaceRev } : {}) };\n\t\t\tthis.queueSpaceUpdate(meta.uri, {\n\t\t\t\t$type: REPO_WRITE,\n\t\t\t\trepo: did,\n\t\t\t\trepoRev,\n\t\t\t\tdata: bytesToJson(data),\n\t\t\t\t...sequence,\n\t\t\t});\n\t\t\treturn sequence;\n\t\t});\n\t\tif (sequence) await this.scheduleNextAlarm();\n\t\treturn sequence;\n\t}\n\n\t/**\n\t * Remove a repo from the writer set at a new space revision, keeping its\n\t * row marked removed so listWriters reports the removal, and announce it.\n\t * Returns false when the repo is not in the writer set. Must run in a\n\t * transaction.\n\t */\n\tprivate removeWriterSync(did: string): boolean {\n\t\tconst meta = this.readMeta();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT removed_at FROM writer WHERE did = ?\", did)\n\t\t\t.toArray()[0];\n\t\tif (!meta || !row || row.removed_at !== null) return false;\n\t\tconst prevSpaceRev = this.currentSpaceRev();\n\t\tconst spaceRev = nextRev(prevSpaceRev);\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE writer SET space_rev = ?, removed_at = ? WHERE did = ?\",\n\t\t\tspaceRev,\n\t\t\tDate.now(),\n\t\t\tdid,\n\t\t);\n\t\tthis.queueSpaceUpdate(meta.uri, {\n\t\t\t$type: REPO_REMOVED,\n\t\t\trepo: did,\n\t\t\tspaceRev,\n\t\t\t...(prevSpaceRev ? { prevSpaceRev } : {}),\n\t\t});\n\t\treturn true;\n\t}\n\n\t/**\n\t * Drop an account from the writer set. It is tracked again if it later\n\t * writes while still authorised. Idempotent.\n\t */\n\tasync rpcRemoveWriter(did: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\tthis.ctx.storage.transactionSync(() => this.removeWriterSync(did));\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate readWriter(row: Record<string, SqlStorageValue>): SpaceWriter {\n\t\treturn {\n\t\t\tdid: row.did as string,\n\t\t\trepoRev: row.repo_rev as string,\n\t\t\tdata: new Uint8Array(row.data as ArrayBuffer),\n\t\t\tspaceRev: row.space_rev as string,\n\t\t\tremoved: row.removed_at !== null,\n\t\t};\n\t}\n\n\t/** The writer set, removals included, in ascending space revision after `cursor`. */\n\tasync rpcListWriters(params: {\n\t\tlimit: number;\n\t\tcursor?: string;\n\t}): Promise<SpaceWriter[]> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\treturn this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT did, repo_rev, data, space_rev, removed_at FROM writer\n\t\t\t\t ${params.cursor ? \"WHERE space_rev > ?\" : \"\"}\n\t\t\t\t ORDER BY space_rev ASC LIMIT ?`,\n\t\t\t\t...(params.cursor ? [params.cursor] : []),\n\t\t\t\tparams.limit,\n\t\t\t)\n\t\t\t.toArray()\n\t\t\t.map((row) => this.readWriter(row));\n\t}\n\n\t/** The space's host-side state, for migrating its authority's account. */\n\tasync rpcExportMeta(): Promise<{\n\t\tpolicy: SpacePolicy;\n\t\tmembers: SpaceMember[];\n\t\twriters: SpaceWriter[];\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\t// Removed writers stay behind: the archive carries only the writer\n\t\t// set itself.\n\t\tconst writers = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT did, repo_rev, data, space_rev, removed_at FROM writer WHERE removed_at IS NULL ORDER BY did\",\n\t\t\t)\n\t\t\t.toArray()\n\t\t\t.map((row) => this.readWriter(row));\n\t\treturn { policy, members: this.readMembers(), writers };\n\t}\n\n\t/**\n\t * Import a space exported by its previous host, replacing whatever this\n\t * host held for it, so a migration step can be retried. Publishing is\n\t * left to the authority's repo, which arrives afterwards with importRepo.\n\t * Registrations, revocations and tombstones are not carried over.\n\t */\n\tasync rpcImportMeta(params: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tpolicy: SpacePolicy;\n\t\tmembers: SpaceMember[];\n\t\twriters: SpaceWriter[];\n\t}): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst existing = this.readMeta();\n\t\tif (existing && existing.uri !== params.uri) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Space DO already holds ${existing.uri}`,\n\t\t\t);\n\t\t}\n\t\tthis.ctx.storage.transactionSync(() => {\n\t\t\tif (!existing) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)\n\t\t\t\t\t VALUES (?, ?, ?, ?, 1, ?, NULL, ?)`,\n\t\t\t\t\tparams.uri,\n\t\t\t\t\tparams.authority,\n\t\t\t\t\tparams.type,\n\t\t\t\t\tparams.skey,\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tSPACE_SCHEMA_VERSION,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis.sql.exec(\"UPDATE meta SET deleted_at = NULL, is_authority = 1\");\n\t\t\t}\n\t\t\tthis.writePolicy(params.policy);\n\t\t\tthis.sql.exec(\"DELETE FROM member\");\n\t\t\tfor (const member of params.members) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)\",\n\t\t\t\t\tmember.did,\n\t\t\t\t\tmember.read ? 1 : 0,\n\t\t\t\t\tmember.write ? 1 : 0,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.sql.exec(\"DELETE FROM writer\");\n\t\t\tfor (const writer of params.writers) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)\",\n\t\t\t\t\twriter.did,\n\t\t\t\t\twriter.repoRev,\n\t\t\t\t\twriter.data,\n\t\t\t\t\twriter.spaceRev,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\tasync rpcGetNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t): Promise<{ expiresAt: number } | null> {\n\t\tawait this.ensureOpen();\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\t\tregistration.endpoint,\n\t\t\t\tregistration.token,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\treturn row ? { expiresAt: row.expires_at as number } : null;\n\t}\n\n\t/**\n\t * Register a syncer's webhook, or renew it, to the expiry of the\n\t * credential it was authorised with. Renewal clears a lapse already\n\t * announced, so the next lapse is announced too.\n\t */\n\tasync rpcPutNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t\texpiresAt: number,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) throw new SpaceError(\"SpaceNotFound\", \"Space not found\");\n\t\tif (meta.deletedAt) {\n\t\t\tthrow new SpaceError(\"SpaceDeleted\", \"Space has been deleted\");\n\t\t}\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO notify_registration (endpoint, token, expires_at, expiry_notified) VALUES (?, ?, ?, 0)\n\t\t\t ON CONFLICT (endpoint, token) DO UPDATE SET expires_at = excluded.expires_at, expiry_notified = 0`,\n\t\t\tregistration.endpoint,\n\t\t\tregistration.token,\n\t\t\texpiresAt,\n\t\t);\n\t}\n\n\t/** Withdraw a registration, as when its syncer is denied access. */\n\tasync rpcRemoveNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\tregistration.endpoint,\n\t\t\tregistration.token,\n\t\t);\n\t}\n\n\t/**\n\t * Queue a sequenced writer-set change for the registered syncers: best\n\t * effort to each active registration, and in place of the update an\n\t * expiry notice, delivered reliably, to each registration that has\n\t * lapsed since the last one. Each lapse is claimed once. Must run in a\n\t * transaction.\n\t */\n\tprivate queueSpaceUpdate(\n\t\tspace: string,\n\t\tupdate: Record<string, unknown>,\n\t): void {\n\t\tconst now = Date.now();\n\t\tconst registrations = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT endpoint, token, expires_at, expiry_notified FROM notify_registration\",\n\t\t\t)\n\t\t\t.toArray();\n\t\tfor (const row of registrations) {\n\t\t\tconst endpoint = row.endpoint as string;\n\t\t\tconst token = row.token as string;\n\t\t\tif ((row.expires_at as number) > now) {\n\t\t\t\tthis.insertNotify({\n\t\t\t\t\tservice: endpoint,\n\t\t\t\t\tendpoint,\n\t\t\t\t\tlxm: NOTIFY_SPACE_UPDATE_LXM,\n\t\t\t\t\tbody: { space, token, update },\n\t\t\t\t\tpolicy: \"fanout\",\n\t\t\t\t\tauth: \"none\",\n\t\t\t\t});\n\t\t\t} else if ((row.expiry_notified as number) === 0) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"UPDATE notify_registration SET expiry_notified = 1 WHERE endpoint = ? AND token = ?\",\n\t\t\t\t\tendpoint,\n\t\t\t\t\ttoken,\n\t\t\t\t);\n\t\t\t\tthis.queueSyncerNotice({ endpoint, token }, space, {\n\t\t\t\t\t$type: REGISTRATION_EXPIRED,\n\t\t\t\t\tspaceRev: update.spaceRev,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/** A deletion or expiry notice, delivered reliably for 72 hours. */\n\tprivate queueSyncerNotice(\n\t\tregistration: NotifyRegistration,\n\t\tspace: string,\n\t\tnotice: Record<string, unknown>,\n\t): void {\n\t\tthis.insertNotify({\n\t\t\tservice: registration.endpoint,\n\t\t\tendpoint: registration.endpoint,\n\t\t\tlxm: NOTIFY_SPACE_UPDATE_LXM,\n\t\t\tbody: { space, token: registration.token, update: notice },\n\t\t\tpolicy: \"syncer\",\n\t\t\tauth: \"none\",\n\t\t\t// A deletion notice replaces whatever is pending; an expiry notice\n\t\t\t// never replaces one, so a deletion notice is never lost.\n\t\t\tcoalesceKey: `syncer\\n${registration.endpoint}\\n${registration.token}`,\n\t\t\tkeepPending: notice.$type !== SPACE_DELETED,\n\t\t\tdeadline: Date.now() + SYNCER_NOTICE_RETRY_WINDOW_MS,\n\t\t});\n\t}\n\n\t/**\n\t * Queue outbound notifications for the alarm to deliver with bounded\n\t * retries. An item with a coalesce key replaces any pending item with\n\t * the same key, resetting its backoff and deadline.\n\t */\n\tasync rpcEnqueueNotify(\n\t\titems: NotifyItem[],\n\t\topts: { delayMs?: number } = {},\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tif (items.length === 0) return;\n\t\tconst nextAt = Date.now() + (opts.delayMs ?? 0);\n\t\tfor (const item of items) this.insertNotify(item, nextAt);\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate insertNotify(item: NotifyItem, nextAt = Date.now()): void {\n\t\tconst body = JSON.stringify({\n\t\t\tendpoint: item.endpoint,\n\t\t\tlxm: item.lxm,\n\t\t\tbody: item.body,\n\t\t});\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO notify_queue (service, body, attempts, next_at, deadline, coalesce_key, policy, auth)\n\t\t\t VALUES (?, ?, 0, ?, ?, ?, ?, ?)\n\t\t\t ON CONFLICT (coalesce_key) DO ${\n\t\t\t\t\titem.keepPending\n\t\t\t\t\t\t? \"NOTHING\"\n\t\t\t\t\t\t: `UPDATE SET\n\t\t\t\tservice = excluded.service, body = excluded.body, attempts = 0,\n\t\t\t\tnext_at = excluded.next_at, deadline = excluded.deadline,\n\t\t\t\tpolicy = excluded.policy, auth = excluded.auth`\n\t\t\t\t}`,\n\t\t\titem.service,\n\t\t\tbody,\n\t\t\tnextAt,\n\t\t\titem.deadline ?? null,\n\t\t\titem.coalesceKey ?? null,\n\t\t\titem.policy ?? \"fanout\",\n\t\t\titem.auth ?? \"service\",\n\t\t);\n\t}\n\n\t/** Drop a pending coalesced notification, e.g. once a newer one landed. */\n\tasync rpcClearNotify(coalesceKey: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_queue WHERE coalesce_key = ?\",\n\t\t\tcoalesceKey,\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Deletion and status\n\t// ------------------------------------------------------------------\n\n\t/**\n\t * Tombstone the space (authority role), delete the authority's own repo\n\t * in it, and queue a deletion notice to every registered syncer, lapsed\n\t * registrations included. The meta row is retained so a late\n\t * authorizeSpaceSync can answer SpaceDeleted rather than SpaceNotFound.\n\t * Idempotent.\n\t */\n\tasync rpcDeleteSpace(): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space is not initialised\");\n\t\t}\n\t\tif (meta.deletedAt) return;\n\t\tthis.ctx.storage.transactionSync(() => {\n\t\t\tfor (const row of this.sql\n\t\t\t\t.exec(\"SELECT endpoint, token FROM notify_registration\")\n\t\t\t\t.toArray()) {\n\t\t\t\tthis.queueSyncerNotice(\n\t\t\t\t\t{ endpoint: row.endpoint as string, token: row.token as string },\n\t\t\t\t\tmeta.uri,\n\t\t\t\t\t{ $type: SPACE_DELETED },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.sql.exec(\"UPDATE meta SET deleted_at = ?\", new Date().toISOString());\n\t\t\tfor (const table of [\n\t\t\t\t\"record\",\n\t\t\t\t\"record_blob\",\n\t\t\t\t\"repo_state\",\n\t\t\t\t\"oplog\",\n\t\t\t\t\"config\",\n\t\t\t\t\"member\",\n\t\t\t\t\"writer\",\n\t\t\t\t\"notify_registration\",\n\t\t\t\t\"replay\",\n\t\t\t]) {\n\t\t\t\tthis.sql.exec(`DELETE FROM ${table}`);\n\t\t\t}\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\t/** Wipe everything, including queued notifications and alarms. */\n\tasync rpcDestroy(): Promise<void> {\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.initialized = false;\n\t\tthis.outdated = false;\n\t}\n\n\tasync rpcStatus(): Promise<{\n\t\tmeta: SpaceMeta | null;\n\t\toutdated: boolean;\n\t\tpolicyType: string | null;\n\t\trecordCount: number;\n\t\tmemberCount: number;\n\t\twriterCount: number;\n\t\tqueuedNotifications: number;\n\t}> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) {\n\t\t\treturn {\n\t\t\t\tmeta: null,\n\t\t\t\toutdated: true,\n\t\t\t\tpolicyType: null,\n\t\t\t\trecordCount: 0,\n\t\t\t\tmemberCount: 0,\n\t\t\t\twriterCount: 0,\n\t\t\t\tqueuedNotifications: 0,\n\t\t\t};\n\t\t}\n\t\tconst count = (table: string): number =>\n\t\t\t(this.sql.exec(`SELECT COUNT(*) AS n FROM ${table}`).toArray()[0]\n\t\t\t\t?.n as number) ?? 0;\n\t\treturn {\n\t\t\tmeta: this.readMeta(),\n\t\t\toutdated: false,\n\t\t\tpolicyType: this.readPolicy()?.$type ?? null,\n\t\t\trecordCount: count(\"record\"),\n\t\t\tmemberCount: count(\"member\"),\n\t\t\twriterCount: count(\"writer WHERE removed_at IS NULL\"),\n\t\t\tqueuedNotifications: count(\"notify_queue\"),\n\t\t};\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Alarm: notification delivery, oplog compaction, expiry cleanup\n\t// ------------------------------------------------------------------\n\n\toverride async alarm(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) return;\n\n\t\tawait this.deliverQueuedNotifications();\n\t\tthis.runMaintenanceIfDue();\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate async deliverQueuedNotifications(): Promise<void> {\n\t\tconst now = Date.now();\n\t\t// Syncer notices are tried once more after their window closes.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_queue WHERE deadline IS NOT NULL AND deadline <= ? AND policy != 'syncer'\",\n\t\t\tnow,\n\t\t);\n\t\tconst due = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT id, service, body, attempts, next_at, deadline, policy, auth FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?\",\n\t\t\t\tnow,\n\t\t\t\tNOTIFY_BATCH,\n\t\t\t)\n\t\t\t.toArray() as unknown as QueueRow[];\n\t\tif (due.length === 0) return;\n\n\t\tconst host = await this.getHostConfig();\n\t\tconst keypair = await host.getKeypair();\n\n\t\t// In parallel, so a slow endpoint doesn't hold up the others.\n\t\tawait Promise.all(\n\t\t\tdue.map(async (row) => {\n\t\t\t\tconst parsed = JSON.parse(row.body) as {\n\t\t\t\t\tendpoint: string;\n\t\t\t\t\tlxm: string;\n\t\t\t\t\tbody: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tif (\n\t\t\t\t\trow.policy === \"syncer\" &&\n\t\t\t\t\t!this.isSyncerNoticeOwed(parsed.endpoint, parsed.body)\n\t\t\t\t) {\n\t\t\t\t\tthis.sql.exec(\"DELETE FROM notify_queue WHERE id = ?\", row.id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet delivered = false;\n\t\t\t\tlet retryable = true;\n\t\t\t\ttry {\n\t\t\t\t\tconst headers: Record<string, string> = {\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t};\n\t\t\t\t\tif (row.auth === \"service\") {\n\t\t\t\t\t\tconst token = await createServiceJwt(\n\t\t\t\t\t\t\t{ iss: host.operatorDid, aud: row.service, lxm: parsed.lxm },\n\t\t\t\t\t\t\tkeypair,\n\t\t\t\t\t\t);\n\t\t\t\t\t\theaders.Authorization = `Bearer ${token}`;\n\t\t\t\t\t}\n\t\t\t\t\tconst res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tbody: JSON.stringify(parsed.body),\n\t\t\t\t\t\t// A syncer chose this endpoint: never follow it elsewhere.\n\t\t\t\t\t\tredirect: row.auth === \"none\" ? \"manual\" : \"follow\",\n\t\t\t\t\t\tsignal: AbortSignal.timeout(10_000),\n\t\t\t\t\t});\n\t\t\t\t\tdelivered = res.ok;\n\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\tretryable = isRetryableStatus(res.status);\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`notify ${parsed.lxm} to ${row.service} failed: ${res.status}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconsole.warn(`notify to ${row.service} errored:`, err);\n\t\t\t\t}\n\t\t\t\tthis.settleNotify(row, parsed, delivered, retryable);\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** A deletion or expiry notice that no longer applies is dropped unsent. */\n\tprivate isSyncerNoticeOwed(\n\t\tendpoint: string,\n\t\tbody: Record<string, unknown>,\n\t): boolean {\n\t\tconst update = body.update as { $type?: string } | undefined;\n\t\tif (update?.$type === SPACE_DELETED) {\n\t\t\t// Not owed if the space has been recreated since.\n\t\t\treturn Boolean(this.readMeta()?.deletedAt);\n\t\t}\n\t\t// An expiry notice: not owed if the syncer has renewed since.\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\t\tendpoint,\n\t\t\t\tbody.token as string,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\treturn Boolean(row && (row.expires_at as number) <= Date.now());\n\t}\n\n\tprivate settleNotify(\n\t\trow: QueueRow,\n\t\tparsed: { endpoint: string; body: Record<string, unknown> },\n\t\tdelivered: boolean,\n\t\tretryable: boolean,\n\t): void {\n\t\tconst attempts = row.attempts + 1;\n\t\tconst now = Date.now();\n\t\tconst remove = () =>\n\t\t\tthis.sql.exec(\"DELETE FROM notify_queue WHERE id = ?\", row.id);\n\t\tif (delivered) return void remove();\n\t\tif (row.policy === \"syncer\") {\n\t\t\tif (!retryable || (row.deadline !== null && row.deadline <= now)) {\n\t\t\t\tremove();\n\t\t\t\tthis.abandonSyncerNotice(parsed.endpoint, parsed.body);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst delays = SYNCER_NOTICE_RETRY_DELAYS_MS;\n\t\t\tconst delay = delays[Math.min(attempts, delays.length) - 1]!;\n\t\t\tthis.sql.exec(\n\t\t\t\t\"UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?\",\n\t\t\t\tattempts,\n\t\t\t\tnow + jitter(delay),\n\t\t\t\trow.id,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst exhausted =\n\t\t\trow.deadline === null ? attempts >= NOTIFY_MAX_ATTEMPTS : false;\n\t\tif (!retryable || exhausted) return void remove();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?\",\n\t\t\tattempts,\n\t\t\tnow +\n\t\t\t\tjitter(\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\tNOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts,\n\t\t\t\t\t\tNOTIFY_BACKOFF_MAX_MS,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\trow.id,\n\t\t);\n\t}\n\n\t/**\n\t * Give up on a notice. A syncer that rejects its expiry notice, or can't\n\t * be reached, is unregistered, unless it has renewed since.\n\t */\n\tprivate abandonSyncerNotice(\n\t\tendpoint: string,\n\t\tbody: Record<string, unknown>,\n\t): void {\n\t\tconst update = body.update as { $type?: string } | undefined;\n\t\tif (update?.$type !== REGISTRATION_EXPIRED) return;\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_registration WHERE endpoint = ? AND token = ? AND expires_at <= ?\",\n\t\t\tendpoint,\n\t\t\tbody.token as string,\n\t\t\tDate.now(),\n\t\t);\n\t}\n\n\tprivate runMaintenanceIfDue(): void {\n\t\tconst now = Date.now();\n\t\tconst last =\n\t\t\t(this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT expires_at FROM replay WHERE kind = '__maintenance' AND key = 'last' LIMIT 1\",\n\t\t\t\t)\n\t\t\t\t.toArray()[0]?.expires_at as number | undefined) ?? 0;\n\t\tif (now - last < MAINTENANCE_INTERVAL_MS) return;\n\n\t\t// Oplog compaction: 30 days or 10,000 ops, whichever is smaller.\n\t\t// DO SQLite is billed and capped; the reference has no compaction\n\t\t// yet, ours must.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM oplog WHERE rev < ?\",\n\t\t\ttidCutoff(OPLOG_RETENTION_DAYS * DAY_MS),\n\t\t);\n\t\tconst excess = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT rev, idx FROM oplog ORDER BY rev DESC, idx DESC LIMIT 1 OFFSET ?\",\n\t\t\t\tOPLOG_RETENTION_OPS,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tif (excess) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"DELETE FROM oplog WHERE rev < ? OR (rev = ? AND idx <= ?)\",\n\t\t\t\texcess.rev,\n\t\t\t\texcess.rev,\n\t\t\t\texcess.idx,\n\t\t\t);\n\t\t}\n\n\t\tconst nowSec = Math.floor(now / 1000);\n\t\t// Replay and revocation entries expire on their own clock.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM replay WHERE kind != '__maintenance' AND expires_at < ?\",\n\t\t\tnowSec,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM revoked_credential WHERE expires_at <= ?\",\n\t\t\tnowSec,\n\t\t);\n\t\t// Lapsed registrations are kept on purpose: the next update to the\n\t\t// space owes each an expiry notice, and abandoning that notice is what\n\t\t// unregisters it.\n\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO replay (kind, key, expires_at) VALUES ('__maintenance', 'last', ?)\n\t\t\t ON CONFLICT (kind, key) DO UPDATE SET expires_at = excluded.expires_at`,\n\t\t\tnow,\n\t\t);\n\t}\n\n\tprivate async scheduleNextAlarm(): Promise<void> {\n\t\tconst nextQueue = this.sql\n\t\t\t.exec(\"SELECT MIN(next_at) AS next FROM notify_queue\")\n\t\t\t.toArray()[0]?.next as number | null;\n\t\tconst nextMaintenance = Date.now() + MAINTENANCE_INTERVAL_MS;\n\t\tconst next = nextQueue\n\t\t\t? Math.min(Math.max(nextQueue, Date.now() + 1000), nextMaintenance)\n\t\t\t: nextMaintenance;\n\t\tconst current = await this.ctx.storage.getAlarm();\n\t\tif (current === null || next < current) {\n\t\t\tawait this.ctx.storage.setAlarm(next);\n\t\t}\n\t}\n}\n","/**\n * SpaceIndexDurableObject โ singleton registry of space URIs with role\n * flags, timestamps and lifecycle state, addressed by `idFromName(\"spaces\")`.\n *\n * Serves listSpaces, the dashboard, export and reset. Nothing reads it on\n * the hot path: the space DO id is derived from the URI, so reads never\n * depend on the index. Creation is a two-step write โ the index entry is\n * written `pending`, the space DO is initialised, then the entry is marked\n * `active`. A `pending` entry that never activates is cleaned up by this\n * DO's alarm.\n */\n\nimport { DurableObject } from \"cloudflare:workers\";\nimport {\n\tINDEX_DO_SCHEMA,\n\tPENDING_BLOB_TTL_MS,\n\tPENDING_ENTRY_TTL_MS,\n\tSPACE_SCHEMA_VERSION,\n} from \"./schema.js\";\n\nexport type SpaceIndexState = \"pending\" | \"active\" | \"deleted\";\n\nexport interface SpaceIndexEntry {\n\turi: string;\n\tauthority: string;\n\ttype: string;\n\tskey: string;\n\tisAuthority: boolean;\n\tstate: SpaceIndexState;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nconst ALARM_INTERVAL_MS = 6 * 60 * 60 * 1000;\n\nexport class SpaceIndexDurableObject<Env = unknown> extends DurableObject<Env> {\n\tprivate sql: SqlStorage;\n\tprivate initialized = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.sql = ctx.storage.sql;\n\t}\n\n\tprivate async ensureInitialized(): Promise<void> {\n\t\tif (this.initialized) return;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tif (this.initialized) return;\n\t\t\tthis.sql.exec(INDEX_DO_SCHEMA);\n\t\t\tthis.initialized = true;\n\t\t\tconst alarm = await this.ctx.storage.getAlarm();\n\t\t\tif (alarm === null) {\n\t\t\t\tawait this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Register (or revive) an entry in `pending` state. */\n\tasync rpcRegister(entry: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tisAuthority: boolean;\n\t}): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst now = new Date().toISOString();\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO space (uri, authority, type, skey, is_authority, state, created_at, updated_at, schema_version)\n\t\t\t VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)\n\t\t\t ON CONFLICT (uri) DO UPDATE SET\n\t\t\t\tstate = CASE WHEN space.state = 'active' THEN 'active' ELSE 'pending' END,\n\t\t\t\tis_authority = excluded.is_authority,\n\t\t\t\tupdated_at = excluded.updated_at`,\n\t\t\tentry.uri,\n\t\t\tentry.authority,\n\t\t\tentry.type,\n\t\t\tentry.skey,\n\t\t\tentry.isAuthority ? 1 : 0,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\tSPACE_SCHEMA_VERSION,\n\t\t);\n\t}\n\n\tasync rpcActivate(uri: string): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'active', updated_at = ? WHERE uri = ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\turi,\n\t\t);\n\t}\n\n\tasync rpcMarkDeleted(uri: string): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'deleted', updated_at = ? WHERE uri = ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\turi,\n\t\t);\n\t}\n\n\tasync rpcGet(uri: string): Promise<SpaceIndexEntry | null> {\n\t\tawait this.ensureInitialized();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT * FROM space WHERE uri = ?\", uri)\n\t\t\t.toArray()[0];\n\t\treturn row ? toEntry(row) : null;\n\t}\n\n\tasync rpcList(params: {\n\t\ttype?: string;\n\t\tauthority?: string;\n\t\tstate?: SpaceIndexState;\n\t\tlimit: number;\n\t\tafterUri?: string;\n\t}): Promise<{ spaces: SpaceIndexEntry[]; hasMore: boolean }> {\n\t\tawait this.ensureInitialized();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.type) {\n\t\t\twhere += \" AND type = ?\";\n\t\t\targs.push(params.type);\n\t\t}\n\t\tif (params.authority) {\n\t\t\twhere += \" AND authority = ?\";\n\t\t\targs.push(params.authority);\n\t\t}\n\t\tif (params.state) {\n\t\t\twhere += \" AND state = ?\";\n\t\t\targs.push(params.state);\n\t\t}\n\t\tif (params.afterUri) {\n\t\t\twhere += \" AND uri > ?\";\n\t\t\targs.push(params.afterUri);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT * FROM space WHERE ${where} ORDER BY uri ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { spaces: page.map(toEntry), hasMore };\n\t}\n\n\tasync rpcStats(): Promise<{\n\t\ttotal: number;\n\t\tactive: number;\n\t\tpending: number;\n\t\tdeleted: number;\n\t\thosted: number;\n\t}> {\n\t\tawait this.ensureInitialized();\n\t\tconst count = (where: string): number =>\n\t\t\t(this.sql\n\t\t\t\t.exec(`SELECT COUNT(*) AS n FROM space WHERE ${where}`)\n\t\t\t\t.toArray()[0]?.n as number) ?? 0;\n\t\treturn {\n\t\t\ttotal: count(\"1=1\"),\n\t\t\tactive: count(\"state = 'active'\"),\n\t\t\tpending: count(\"state = 'pending'\"),\n\t\t\tdeleted: count(\"state = 'deleted'\"),\n\t\t\thosted: count(\"is_authority = 1 AND state = 'active'\"),\n\t\t};\n\t}\n\n\t/**\n\t * Note blobs an imported space repo references but whose bytes have not\n\t * been uploaded yet, so uploadBlob can promote them when they arrive.\n\t */\n\tasync rpcAddPendingBlobs(uri: string, cids: string[]): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst now = Date.now();\n\t\tfor (const cid of cids) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"INSERT OR REPLACE INTO pending_blob (cid, uri, created_at) VALUES (?, ?, ?)\",\n\t\t\t\tcid,\n\t\t\t\turi,\n\t\t\t\tnow,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Claim a freshly uploaded blob: the spaces whose imported records\n\t * reference it. Claimed entries are removed.\n\t */\n\tasync rpcClaimPendingBlob(cid: string): Promise<string[]> {\n\t\tawait this.ensureInitialized();\n\t\tconst uris = this.sql\n\t\t\t.exec(\"SELECT uri FROM pending_blob WHERE cid = ?\", cid)\n\t\t\t.toArray()\n\t\t\t.map((row) => row.uri as string);\n\t\tif (uris.length > 0) {\n\t\t\tthis.sql.exec(\"DELETE FROM pending_blob WHERE cid = ?\", cid);\n\t\t}\n\t\treturn uris;\n\t}\n\n\t/** Wipe the registry (spaces reset). */\n\tasync rpcDestroy(): Promise<void> {\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.initialized = false;\n\t}\n\n\t/**\n\t * Tombstone `pending` entries that never activated. They become\n\t * `deleted` rather than being removed: a crash between the space DO's\n\t * initialisation and the index activation leaves real DO storage\n\t * behind, and the index row is the only durable manifest `spaces reset`\n\t * has for finding and destroying it.\n\t */\n\toverride async alarm(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst cutoff = new Date(Date.now() - PENDING_ENTRY_TTL_MS).toISOString();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'deleted', updated_at = ? WHERE state = 'pending' AND updated_at < ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\tcutoff,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM pending_blob WHERE created_at < ?\",\n\t\t\tDate.now() - PENDING_BLOB_TTL_MS,\n\t\t);\n\t\tawait this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);\n\t}\n}\n\nfunction toEntry(row: Record<string, unknown>): SpaceIndexEntry {\n\treturn {\n\t\turi: row.uri as string,\n\t\tauthority: row.authority as string,\n\t\ttype: row.type as string,\n\t\tskey: row.skey as string,\n\t\tisAuthority: (row.is_authority as number) === 1,\n\t\tstate: row.state as SpaceIndexState,\n\t\tcreatedAt: row.created_at as string,\n\t\tupdatedAt: row.updated_at as string,\n\t};\n}\n","/**\n * Space URI handling.\n *\n * A space is addressed as `at:space/{authorityDid}/{typeNsid}/{skey}`, and a\n * record in a space appends `/{authorDid}/{collection}/{rkey}`. The\n * `at:space/` prefix tells it apart from a public `at://` URI.\n *\n * Params are parsed strictly: the alpha's earlier `at://{did}/space/...`\n * form is refused, as the reference refuses it. Only record values written\n * during the alpha may still carry it, and the engine never parses those.\n */\n\n/** The prefix of every space URI. */\nexport const SPACE_URI_PREFIX = \"at:space/\";\n\nimport { isDid, isNsid, isRecordKey } from \"@atcute/lexicons/syntax\";\nimport { SpaceError } from \"./errors.js\";\n\nexport interface SpaceRef {\n\t/** The full space URI. */\n\turi: string;\n\t/** The space authority DID. */\n\tauthority: string;\n\t/** The space type NSID. */\n\ttype: string;\n\t/** The space key (record-key syntax). */\n\tskey: string;\n}\n\n/**\n * Parse a space URI. Returns null when the string is not a valid space\n * reference.\n */\nexport function parseSpaceUri(uri: string): SpaceRef | null {\n\tif (!uri.startsWith(SPACE_URI_PREFIX)) return null;\n\tconst parts = uri.slice(SPACE_URI_PREFIX.length).split(\"/\");\n\tif (parts.length !== 3) return null;\n\tconst [authority, type, skey] = parts as [string, string, string];\n\tif (!isDid(authority) || !isNsid(type) || !isRecordKey(skey)) return null;\n\tconst ref = {\n\t\turi: formatSpaceUri(authority, type, skey),\n\t\tauthority,\n\t\ttype,\n\t\tskey,\n\t};\n\t// Round-trip requirement mirrors the reference's SpaceRef.parse.\n\tif (ref.uri !== uri) return null;\n\treturn ref;\n}\n\n/**\n * Parse a space URI or throw. The error is XRPC's generic InvalidRequest, as\n * the reference answers: no lexicon declares a more specific one.\n */\nexport function requireSpaceUri(uri: string | undefined): SpaceRef {\n\tconst ref = uri ? parseSpaceUri(uri) : null;\n\tif (!ref) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `Invalid space URI: ${uri}`);\n\t}\n\treturn ref;\n}\n\nexport function formatSpaceUri(\n\tauthority: string,\n\ttype: string,\n\tskey: string,\n): string {\n\treturn `${SPACE_URI_PREFIX}${authority}/${type}/${skey}`;\n}\n\n/** URI of a record within a space: `{spaceUri}/{repoDid}/{collection}/{rkey}`. */\nexport function spaceRecordUri(\n\tspaceUri: string,\n\trepo: string,\n\tcollection: string,\n\trkey: string,\n): string {\n\treturn `${spaceUri}/${repo}/${collection}/${rkey}`;\n}\n\nconst BASE32_ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/**\n * Stable identifier for a space used in R2 key prefixes: the lowercase,\n * unpadded base32 encoding of the SHA-256 of the space URI. Deterministic,\n * filesystem-safe and free of the URI's slashes and colons.\n */\nexport async function spaceId(spaceUri: string): Promise<string> {\n\tconst digest = new Uint8Array(\n\t\tawait crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(spaceUri)),\n\t);\n\tlet out = \"\";\n\tlet bits = 0;\n\tlet value = 0;\n\tfor (const byte of digest) {\n\t\tvalue = (value << 8) | byte;\n\t\tbits += 8;\n\t\twhile (bits >= 5) {\n\t\t\tout += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];\n\t\t\tbits -= 5;\n\t\t}\n\t}\n\tif (bits > 0) {\n\t\tout += BASE32_ALPHABET[(value << (5 - bits)) & 31];\n\t}\n\treturn out;\n}\n","/**\n * R2 key layout for space blobs.\n *\n * A blob referenced by a record in a space lives at\n * `${did}/space/${spaceId}/${cid}` and is served only by the\n * credential-gated `com.atproto.space.getBlob`. The same blob referenced\n * from two spaces is stored twice: per-space prefixes make space deletion\n * and full reset a prefix delete with no cross-space reference counting.\n */\n\nimport { spaceId } from \"./space-uri.js\";\n\n/**\n * Key for a staged (uploaded, not yet referenced) blob. Must match the\n * host's public blob layout: uploads land here and are promoted to their\n * serving key when a record write references them.\n */\nexport function stagedBlobKey(did: string, cid: string): string {\n\treturn `${did}/staged/${cid}`;\n}\n\n/** Prefix holding every space blob for the account. */\nexport function spaceBlobRootPrefix(did: string): string {\n\treturn `${did}/space/`;\n}\n\n/** Prefix holding one space's blobs. `id` comes from {@link spaceId}. */\nexport function spaceBlobPrefix(did: string, id: string): string {\n\treturn `${did}/space/${id}/`;\n}\n\n/** Key for one blob in one space. */\nexport function spaceBlobKey(did: string, id: string, cid: string): string {\n\treturn `${did}/space/${id}/${cid}`;\n}\n\n/** Convenience: key for a blob given the space URI rather than its id. */\nexport async function spaceBlobKeyForUri(\n\tdid: string,\n\tspaceUri: string,\n\tcid: string,\n): Promise<string> {\n\treturn spaceBlobKey(did, await spaceId(spaceUri), cid);\n}\n\n/**\n * Copy a staged upload into a space's blob prefix. Idempotent; returns\n * whether the blob is now at its destination (false when it was neither\n * there nor staged).\n */\nexport async function promoteStagedBlobToSpace(\n\tbucket: R2Bucket,\n\tdid: string,\n\tspaceUri: string,\n\tcid: string,\n): Promise<boolean> {\n\tconst destKey = await spaceBlobKeyForUri(did, spaceUri, cid);\n\tif (await bucket.head(destKey)) return true;\n\tconst staged = await bucket.get(stagedBlobKey(did, cid));\n\tif (!staged) return false;\n\tawait bucket.put(destKey, staged.body, { httpMetadata: staged.httpMetadata });\n\treturn true;\n}\n\n/**\n * Promote a freshly uploaded blob into every space whose imported records\n * reference it (see `com.atproto.space.importRepo`). The host calls this\n * from `com.atproto.repo.uploadBlob`, mirroring how an imported public repo's\n * blobs are made permanent on upload.\n */\nexport async function promotePendingSpaceBlob(params: {\n\tbucket: R2Bucket;\n\tdid: string;\n\tcid: string;\n\tclaimPendingBlob: (cid: string) => Promise<string[]>;\n}): Promise<number> {\n\tconst uris = await params.claimPendingBlob(params.cid);\n\tfor (const uri of uris) {\n\t\tawait promoteStagedBlobToSpace(params.bucket, params.did, uri, params.cid);\n\t}\n\treturn uris.length;\n}\n","/**\n * Worker-side verification of space credentials and delegation tokens.\n *\n * A space credential is presented as `Authorization: Atproto-Space-Credential\n * <jwt>` (scheme case-insensitive), with an `Atproto-Space-Audience` header\n * naming the service being called and an HTTP message signature over both,\n * by the P-256 key the credential is bound to (`cnf.kid`). A delegation\n * token arrives in the `getSpaceCredential` request body.\n *\n * Everything here is stateless except the revocation and replay checks,\n * which are one RPC each to the space DO. Key resolution goes through the\n * host's DID resolver with a forced refresh on signature failure (handled\n * inside `verifySpaceToken`) so key rotation doesn't strand callers.\n */\n\nimport {\n\tSpaceSignatureError,\n\tSpaceTokenError,\n\tspaceHostAud,\n\tverifyCredentialSig,\n\tverifySpaceToken,\n} from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport type { SpaceErrorCode } from \"./errors.js\";\nimport { parseSpaceUri } from \"./space-uri.js\";\nimport type { SpaceRef } from \"./space-uri.js\";\n\n/** Resolve an issuer DID's `#atproto` key to a did:key string. */\nexport type GetSigningKey = (\n\tiss: string,\n\tforceRefresh: boolean,\n) => Promise<string>;\n\n/** Record a single-use key; false when it was already seen. */\nexport type CheckReplay = (\n\tkind: string,\n\tkey: string,\n\texpiresAtSec: number,\n) => Promise<boolean>;\n\n/** Whether a credential has been revoked by the space's authority. */\nexport type CheckRevoked = (jti: string) => Promise<boolean>;\n\nexport const SPACE_CREDENTIAL_SCHEME = \"Atproto-Space-Credential\";\nexport const SPACE_AUDIENCE_HEADER = \"atproto-space-audience\";\n\n/**\n * Split an Authorization header into scheme and token. The scheme is\n * case-insensitive, as for every HTTP authentication scheme.\n */\nfunction splitAuthorization(\n\tauthorization: string | undefined,\n): { scheme: string; token: string } | null {\n\tif (!authorization) return null;\n\tconst parts = authorization.split(\" \");\n\tif (parts.length !== 2 || !parts[0] || !parts[1]) return null;\n\treturn { scheme: parts[0].toLowerCase(), token: parts[1] };\n}\n\n/** Whether an Authorization header carries a space credential. */\nexport function isSpaceCredentialAuth(\n\tauthorization: string | undefined,\n): boolean {\n\treturn (\n\t\tsplitAuthorization(authorization)?.scheme ===\n\t\tSPACE_CREDENTIAL_SCHEME.toLowerCase()\n\t);\n}\n\nexport interface VerifyCredentialOpts {\n\t/** Request headers, lower-cased names. */\n\theaders: Record<string, string | undefined>;\n\t/**\n\t * The DID this request is addressed to: the repo DID for repo-host\n\t * reads, the authority DID for space-host methods. The signed\n\t * `Atproto-Space-Audience` header must name it.\n\t */\n\taudience: string;\n\tgetSigningKey: GetSigningKey;\n\tcheckRevoked: CheckRevoked;\n}\n\nexport interface SpaceCredentialResult {\n\tkind: \"credential\";\n\t/** The credential issuer: the space's authority DID. */\n\tiss: string;\n\tjti: string;\n}\n\n/**\n * Verify a space credential presented against `space`: the token itself\n * (type, signature against the issuer's `#atproto` key, expiry, lifetime),\n * its issuer being the space's authority and its subject the space, the\n * HTTP message signature by its bound key over the credential and the\n * audience, the audience naming this service, and revocation.\n */\nexport async function verifySpaceCredentialAuth(\n\tspace: SpaceRef,\n\topts: VerifyCredentialOpts,\n): Promise<SpaceCredentialResult> {\n\tconst authorization = splitAuthorization(opts.headers.authorization);\n\tif (\n\t\t!authorization ||\n\t\tauthorization.scheme !== SPACE_CREDENTIAL_SCHEME.toLowerCase()\n\t) {\n\t\tthrow new SpaceError(\"MissingJwt\", \"Missing space credential\");\n\t}\n\n\tlet payload;\n\ttry {\n\t\t({ payload } = await verifySpaceToken(\"credential\", authorization.token, {\n\t\t\tgetSigningKey: opts.getSigningKey,\n\t\t}));\n\t} catch (err) {\n\t\tthrow tokenError(err, \"BadJwt\");\n\t}\n\tconst subject = parseSpaceUri(payload.sub);\n\tif (!subject) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadJwtSub\",\n\t\t\t`Space token subject is not a space URI: ${payload.sub}`,\n\t\t);\n\t}\n\tif (payload.iss !== subject.authority) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadJwtIss\",\n\t\t\t\"Space credential issuer is not the space authority\",\n\t\t);\n\t}\n\n\tconst audience = opts.headers[SPACE_AUDIENCE_HEADER];\n\tif (!audience?.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadSpaceSignature\",\n\t\t\t\"Missing or invalid space audience DID\",\n\t\t);\n\t}\n\ttry {\n\t\tawait verifyCredentialSig(opts.headers, payload.cnf.kid);\n\t} catch (err) {\n\t\tif (err instanceof SpaceSignatureError) {\n\t\t\tthrow new SpaceError(\"BadSpaceSignature\", err.message);\n\t\t}\n\t\tthrow err;\n\t}\n\tif (audience !== opts.audience) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadSpaceAudience\",\n\t\t\t\"Space audience does not match the request\",\n\t\t);\n\t}\n\tif (payload.sub !== space.uri) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidCredential\",\n\t\t\t\"Credential is not scoped to this space\",\n\t\t);\n\t}\n\tif (await opts.checkRevoked(payload.jti)) {\n\t\tthrow new SpaceError(\n\t\t\t\"CredentialRevoked\",\n\t\t\t\"Space credential has been revoked\",\n\t\t);\n\t}\n\treturn { kind: \"credential\", iss: payload.iss, jti: payload.jti };\n}\n\nexport interface DelegationResult {\n\t/** The user the delegation token vouches for. */\n\tuserDid: string;\n}\n\n/**\n * Verify a delegation token from a `getSpaceCredential` body: signature\n * against the issuer's `#atproto` key, audience the space authority's\n * `#atproto_pds`, subject the requested space, single use by `(iss, jti)`.\n * Any failure is `InvalidDelegationToken`: the token arrives in the body\n * rather than as the request's authorization, so it is an invalid request,\n * not an authentication failure.\n */\nexport async function verifyDelegationToken(\n\ttoken: string,\n\tspace: SpaceRef,\n\topts: { getSigningKey: GetSigningKey; checkReplay: CheckReplay },\n): Promise<DelegationResult> {\n\tlet payload;\n\ttry {\n\t\t({ payload } = await verifySpaceToken(\"delegation\", token, {\n\t\t\tgetSigningKey: opts.getSigningKey,\n\t\t}));\n\t} catch (err) {\n\t\tthrow tokenError(err, \"InvalidDelegationToken\", \"InvalidDelegationToken\");\n\t}\n\tif (payload.sub !== space.uri) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token subject does not match requested space\",\n\t\t);\n\t}\n\tif (\n\t\tpayload.aud !== spaceHostAud(space.authority as `did:${string}:${string}`)\n\t) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token audience does not match the space authority\",\n\t\t);\n\t}\n\tif (!payload.iss.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token issuer is not a DID\",\n\t\t);\n\t}\n\tconst fresh = await opts.checkReplay(\n\t\t\"delegation\",\n\t\t`${payload.iss}:${payload.jti}`,\n\t\tpayload.exp,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token has already been used\",\n\t\t);\n\t}\n\treturn { userDid: payload.iss };\n}\n\nfunction tokenError(\n\terr: unknown,\n\tfallback: SpaceErrorCode,\n\toverride?: SpaceErrorCode,\n): SpaceError {\n\t// Server-side detail for operators; clients get the token library's\n\t// message, never infrastructure internals.\n\tconsole.warn(\"space token verification failed:\", err);\n\tif (err instanceof SpaceTokenError) {\n\t\treturn new SpaceError(override ?? err.code, err.message);\n\t}\n\t// DID resolution failures and other infrastructure errors must surface\n\t// as auth errors, never 500s.\n\treturn new SpaceError(override ?? fallback, \"Token verification failed\");\n}\n","/**\n * Client attestation verification (app-identity gating, `allowList` app\n * access). The attestation is a short-lived JWT signed by the OAuth\n * client's published JWKS key, with `iss` = `sub` = client_id and `aud`\n * the space host. Verified against the client's `client-metadata.json`.\n *\n * The client_id in the payload is attacker-controlled until the signature\n * verifies, so nothing is fetched before it has been validated as an\n * https client-metadata URL and checked against the caller's allow-list โ\n * a space gated on an allow-list never performs network I/O for a client\n * that could not be authorized anyway. All fetches are bounded by a\n * timeout.\n */\n\nimport { createLocalJWKSet, jwtVerify } from \"jose\";\nimport { CLIENT_ATTESTATION_TYP, parseSpaceToken } from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport type { CheckReplay } from \"./auth.js\";\n\n/** Upper bound for each outbound metadata/JWKS fetch. */\nconst FETCH_TIMEOUT_MS = 5000;\n\nexport interface VerifyAttestationOpts {\n\t/** Expected audience: `spaceHostAud(authorityDid)`. */\n\texpectedAud: string;\n\t/**\n\t * When set, an (unverified) client_id outside this list is rejected\n\t * before any network I/O. The membership check runs regardless of\n\t * signature state because the caller re-derives authorization from the\n\t * returned client_id after full verification.\n\t */\n\tallowedClientIds?: readonly string[];\n\tcheckReplay: CheckReplay;\n\t/** Fetch override for tests. */\n\tfetch?: typeof fetch;\n}\n\n/**\n * Verify a client attestation and return the attested client_id.\n * Single-use by `(clientId, jti)`.\n */\nexport async function verifyClientAttestation(\n\tattestation: string,\n\topts: VerifyAttestationOpts,\n): Promise<string> {\n\tlet parsed;\n\ttry {\n\t\tparsed = parseSpaceToken(\"clientAttestation\", attestation);\n\t} catch (err) {\n\t\tthrow invalid(err);\n\t}\n\tconst clientId = parsed.payload.iss;\n\tif (parsed.payload.aud !== opts.expectedAud) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation audience does not match this space host\",\n\t\t);\n\t}\n\n\t// Everything below this point costs network I/O, so gate on what can be\n\t// decided statically first: the client_id must be a plausible https\n\t// client-metadata URL, and must be one the space could authorize at all.\n\tlet clientUrl: URL;\n\ttry {\n\t\tclientUrl = new URL(clientId);\n\t} catch {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation client_id is not a URL\",\n\t\t);\n\t}\n\tif (\n\t\tclientUrl.protocol !== \"https:\" ||\n\t\tclientUrl.username ||\n\t\tclientUrl.password\n\t) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation client_id must be a plain https URL\",\n\t\t);\n\t}\n\tif (opts.allowedClientIds && !opts.allowedClientIds.includes(clientId)) {\n\t\tthrow new SpaceError(\n\t\t\t\"AppNotAuthorized\",\n\t\t\t\"App is not authorized for this space\",\n\t\t);\n\t}\n\n\tconst doFetch = opts.fetch ?? fetch;\n\tconst boundedJson = async (url: string): Promise<unknown> => {\n\t\tconst res = await doFetch(url, {\n\t\t\theaders: { Accept: \"application/json\" },\n\t\t\tsignal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n\t\t\t// No redirects. Not \"error\": workerd refuses it outright, so every\n\t\t\t// fetch would throw. A 3xx under \"manual\" fails the ok check.\n\t\t\tredirect: \"manual\",\n\t\t});\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`fetch of ${url} returned ${res.status}`);\n\t\t}\n\t\treturn res.json();\n\t};\n\n\tlet metadata: { jwks?: unknown; jwks_uri?: string };\n\ttry {\n\t\tmetadata = (await boundedJson(clientId)) as typeof metadata;\n\t} catch {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Could not resolve client metadata\",\n\t\t);\n\t}\n\n\tlet jwks = metadata.jwks;\n\tif (!jwks && typeof metadata.jwks_uri === \"string\") {\n\t\tlet jwksUrl: URL;\n\t\ttry {\n\t\t\tjwksUrl = new URL(metadata.jwks_uri);\n\t\t} catch {\n\t\t\tjwksUrl = null as never;\n\t\t}\n\t\tif (!jwksUrl || jwksUrl.protocol !== \"https:\") {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidClientAttestation\",\n\t\t\t\t\"Client metadata jwks_uri must be an https URL\",\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\tjwks = await boundedJson(metadata.jwks_uri);\n\t\t} catch {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidClientAttestation\",\n\t\t\t\t\"Could not resolve client JWKS\",\n\t\t\t);\n\t\t}\n\t}\n\tif (!jwks) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Client metadata declares no JWKS\",\n\t\t);\n\t}\n\n\ttry {\n\t\tconst keySet = createLocalJWKSet(\n\t\t\tjwks as Parameters<typeof createLocalJWKSet>[0],\n\t\t);\n\t\tawait jwtVerify(attestation, keySet, {\n\t\t\tissuer: clientId,\n\t\t\tsubject: clientId,\n\t\t\taudience: opts.expectedAud,\n\t\t\ttyp: CLIENT_ATTESTATION_TYP,\n\t\t\trequiredClaims: [\"jti\", \"exp\"],\n\t\t\tclockTolerance: 5,\n\t\t});\n\t} catch (err) {\n\t\tthrow invalid(err);\n\t}\n\n\tconst fresh = await opts.checkReplay(\n\t\t\"attestation\",\n\t\t`${clientId}:${parsed.payload.jti}`,\n\t\tparsed.payload.exp,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Client attestation has already been used\",\n\t\t);\n\t}\n\treturn clientId;\n}\n\nfunction invalid(err: unknown): SpaceError {\n\treturn new SpaceError(\n\t\t\"InvalidClientAttestation\",\n\t\terr instanceof Error ? err.message : \"Invalid client attestation\",\n\t);\n}\n","/**\n * Hono route factory for `com.atproto.space.*` and\n * `com.atproto.memberspace.*`.\n *\n * The factory is host-agnostic: everything account-specific โ session\n * authentication, DID resolution, record validation, the operator identity\n * and its keys โ arrives through {@link SpaceRoutesHost}. The host mounts\n * the returned app behind its feature flag.\n */\n\nimport { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport {\n\tcreateSpaceCredential,\n\tisP256DidKey,\n\tparseSpaceToken,\n\treadRepoStar,\n\treadSpaceMetaStar,\n\tspaceHostAud,\n\twriteRepoStar,\n\twriteSpaceMetaStar,\n} from \"@atproto/space\";\nimport type { P256Keypair } from \"@atproto/crypto\";\nimport { encode } from \"@atproto/lex-cbor\";\nimport {\n\tcidForCbor,\n\tenumBlobRefs,\n\tfromBase64,\n\tgetBlobCidString,\n} from \"@atproto/lex-data\";\nimport type { LexValue } from \"@atproto/lex-data\";\nimport { now as tidNow } from \"@atcute/tid\";\nimport { isDid } from \"@atcute/lexicons/syntax\";\nimport {\n\tisSpaceCredentialAuth,\n\tverifyDelegationToken,\n\tverifySpaceCredentialAuth,\n\ttype GetSigningKey,\n} from \"./auth.js\";\nimport { verifyClientAttestation } from \"./attestation.js\";\nimport {\n\tCOMMIT_MAC_PROFILE,\n\tMAC_REQUEST_HEADER,\n\tRECORD_MAC_PROFILE,\n\tbuildCommit,\n\tbytesToJson,\n\tcommitMacHeaders,\n\tcommitToJson,\n\timportKemKeypair,\n\tmacExposedHeaders,\n\tmacRequest,\n\trecordMacHeaders,\n\ttype MacParams,\n\ttype MacProfile,\n} from \"./mac.js\";\nimport { SpaceError, parseSpaceErrorCode, spaceErrorStatus } from \"./errors.js\";\nimport {\n\tMEMBER_COLLECTION,\n\tPUBLISHED_COLLECTIONS,\n\tassertNotPublishedCollection,\n\tdidToRecordKey,\n\tisAppAuthorized,\n\tisPublicRead,\n\tnormalizePolicy,\n\trecordKeyToDid,\n} from \"./policy.js\";\nimport { prepareRecord, recordBytesToJson } from \"./records.js\";\nimport {\n\tMAX_NOTIFY_TOKEN_LENGTH,\n\tMAX_REV_CLOCK_SKEW_MS,\n\tMAX_SPACE_RECORD_BYTES,\n\tNOTIFY_BACKOFF_BASE_MS,\n\tNOTIFY_WRITE_RETRY_MS,\n} from \"./schema.js\";\nimport { createServiceJwt } from \"./service-jwt.js\";\nimport {\n\tpromoteStagedBlobToSpace,\n\tspaceBlobKey,\n\tspaceBlobPrefix,\n} from \"./blob-keys.js\";\nimport {\n\tformatSpaceUri,\n\tparseSpaceUri,\n\trequireSpaceUri,\n\tspaceId,\n\tspaceRecordUri,\n} from \"./space-uri.js\";\nimport type { SpaceRef } from \"./space-uri.js\";\nimport { isRetryableStatus } from \"./space-do.js\";\nimport type { SpaceDurableObject } from \"./space-do.js\";\nimport type { SpaceIndexDurableObject } from \"./index-do.js\";\nimport { tidTimestampMs } from \"./tid.js\";\nimport {\n\tMANAGEDSPACE_POLICY,\n\tMEMBERSPACE_POLICY,\n\tPERSONALSPACE_POLICY,\n\ttype ImportedRecord,\n\ttype NotifyItem,\n\ttype NotifyRegistration,\n\ttype PreparedSpaceWrite,\n\ttype RepoCommitResult,\n\ttype SpaceMember,\n\ttype SpacePolicy,\n\ttype SpaceSigningKeypair,\n} from \"./types.js\";\n\nconst NOTIFY_REPO_UPDATE_LXM = \"com.atproto.space.notifyRepoUpdate\";\nconst CREDENTIALS_REVOKED_LXM = \"com.atproto.space.notifyCredentialsRevoked\";\nconst CONFIRM_REGISTRATION_LXM = \"com.atproto.space.confirmRegistration\";\nconst CHECK_ACCESS_LXM = \"com.atproto.managedspace.checkAccess\";\n/** A managing app or syncer endpoint that doesn't answer in this window fails. */\nconst UPSTREAM_TIMEOUT_MS = 10_000;\n/** The queue key for this repo's pending update notification to a foreign authority. */\nconst NOTIFY_REPO_UPDATE_COALESCE_KEY = \"notifyRepoUpdate:authority\";\n/** Upper bound on archives accepted by importRepo / importSpaceMeta. */\nconst MAX_IMPORT_BYTES = 100 * 1024 * 1024;\n/** Revocations are held until any credential they name has expired. */\nconst REVOCATION_TTL_SEC = 3600 + 2 * 5;\n/** The media type of STAR archives (repos and space meta). */\nconst STAR_CONTENT_TYPE = \"application/vnd.dasl.star\";\n/** Batched member changes take at most this many entries. */\nconst MAX_MEMBER_BATCH = 100;\n\nexport type SpaceStub = DurableObjectStub<SpaceDurableObject>;\nexport type SpaceIndexStub = DurableObjectStub<SpaceIndexDurableObject>;\n\n/** The operation shapes checked against a session's `space:` grants. */\nexport type SpaceScopeMatch = {\n\ttype: string;\n\tauthority: string;\n\tskey: string;\n} & (\n\t| { action: \"read\" | \"read_self\" }\n\t| { action: \"create\" | \"update\" | \"delete\"; collection: string }\n\t| { manage: \"create\" | \"update\" | \"delete\" }\n);\n\n/**\n * A host session (OAuth token with `space:` grants, or a fully-trusted\n * operator session). App passwords are excluded in the alpha โ the host's\n * authenticate() must not produce one of these for them.\n */\nexport interface SpaceSessionAuth {\n\tdid: string;\n\t/** Fully-trusted operator session: skips scope checks. */\n\tfullTrust: boolean;\n\tallowsSpace(match: SpaceScopeMatch): boolean;\n}\n\nexport interface SpaceRoutesHost {\n\toperatorDid: string;\n\t/** R2 bucket for blobs; space blob endpoints 503 without it. */\n\tblobs?: R2Bucket;\n\t/** The account's `#atproto` keypair: space tokens and service auth. */\n\tgetKeypair(): Promise<SpaceSigningKeypair>;\n\t/**\n\t * The account's `#atproto_kem` P-256 private key (hex), which MACs space\n\t * data for syncers. Null when unconfigured: reads that owe a MAC then\n\t * answer KemKeyUnavailable.\n\t */\n\tgetKemPrivateKey(): string | null | Promise<string | null>;\n\t/** DID-doc `#atproto` key resolution for foreign issuers. */\n\tgetSigningKey: GetSigningKey;\n\t/**\n\t * Resolve a service identifier to an HTTPS endpoint: `did#fragment`\n\t * names that service entry, a bare DID its `#atproto_pds`. Null when\n\t * unresolvable.\n\t */\n\tresolveServiceEndpoint(service: string): Promise<string | null>;\n\t/** Verify an inbound service-auth JWT bound to `lxm`. */\n\tverifyServiceJwt(\n\t\ttoken: string,\n\t\tlxm: string,\n\t): Promise<{ iss: string; aud: string }>;\n\t/**\n\t * Host session authentication (OAuth / operator sessions). Returns a\n\t * Response for authentication failures.\n\t */\n\tauthenticate(c: Context): Promise<SpaceSessionAuth | Response>;\n\t/**\n\t * Whether the operator's account is active. A deactivated authority\n\t * issues no credentials and lists no repos. Treated as active when\n\t * absent.\n\t */\n\tisAccountActive?(): Promise<boolean>;\n\t/**\n\t * Lexicon validation with the host's validator. Throws on invalid\n\t * records; the thrown message is surfaced as an InvalidRecord error.\n\t */\n\tvalidateRecord(input: {\n\t\tcollection: string;\n\t\trecord: unknown;\n\t\trkey: string;\n\t\tvalidate?: boolean;\n\t}): { record: unknown; status?: \"valid\" | \"unknown\" };\n\tgetSpaceDO(uri: string): SpaceStub;\n\tgetIndexDO(): SpaceIndexStub;\n\t/** Fetch override for outbound calls (tests). */\n\toutboundFetch?: typeof fetch;\n}\n\n// ---------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------\n\nfunction errorResponse(c: Context, err: unknown): Response {\n\tconst parsed = parseSpaceErrorCode(err);\n\tif (parsed) {\n\t\treturn c.json(\n\t\t\t{ error: parsed.code, message: parsed.message },\n\t\t\tspaceErrorStatus(parsed.code) as 400,\n\t\t);\n\t}\n\tthrow err;\n}\n\nfunction waitUntil(c: Context, promise: Promise<unknown>): void {\n\ttry {\n\t\tc.executionCtx.waitUntil(promise);\n\t} catch {\n\t\t// No execution context (tests): let it float.\n\t\tvoid promise.catch((err) => console.warn(\"background task failed\", err));\n\t}\n}\n\n/** Request headers as a plain object with lower-cased names. */\nfunction headerRecord(c: Context): Record<string, string | undefined> {\n\treturn Object.fromEntries(c.req.raw.headers);\n}\n\n/** Append to a comma-separated response header without clobbering it. */\nfunction appendHeader(c: Context, name: string, value: string): void {\n\tc.header(name, value, { append: true });\n}\n\ninterface AuthedRead {\n\tkind: \"credential\" | \"session\";\n}\n\ntype ScopeResult = Response | null;\n\nexport function createSpaceRoutes(host: SpaceRoutesHost): Hono {\n\tconst app = new Hono();\n\t// Looked up per call rather than bound here, so a host's tests can stub\n\t// the global fetch after the routes are built.\n\tconst doFetch: typeof fetch =\n\t\thost.outboundFetch ?? ((input, init) => globalThis.fetch(input, init));\n\n\tlet kemKeypair: Promise<P256Keypair | null> | null = null;\n\tfunction getKemKeypair(): Promise<P256Keypair | null> {\n\t\tkemKeypair ??= Promise.resolve(host.getKemPrivateKey()).then((hex) =>\n\t\t\thex ? importKemKeypair(hex) : null,\n\t\t);\n\t\treturn kemKeypair;\n\t}\n\n\t/** The `repo` param on every repo-host method must be the operator DID. */\n\tfunction requireRepoParam(repo: unknown): void {\n\t\tif (repo !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoNotFound\",\n\t\t\t\t`Repository not found: ${String(repo)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Verify a space credential addressed to this host. Every audience is\n\t * the operator DID: Cirrus serves only the operator's repos, and hosts\n\t * only spaces under the operator's authority.\n\t */\n\tasync function credentialAuth(c: Context, ref: SpaceRef): Promise<void> {\n\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\tawait verifySpaceCredentialAuth(ref, {\n\t\t\theaders: headerRecord(c),\n\t\t\taudience: host.operatorDid,\n\t\t\tgetSigningKey: host.getSigningKey,\n\t\t\tcheckRevoked: (jti) => stub.rpcIsCredentialRevoked(jti),\n\t\t});\n\t}\n\n\t/**\n\t * Authenticate a read: a space credential for the requested space, or a\n\t * host session covering `read_self` on it. The `repo` param on every\n\t * repo-host method must be the operator DID โ anything else is\n\t * RepoNotFound, deliberately indistinguishable from an absent repo.\n\t */\n\tasync function readAuth(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\trepo: string | undefined,\n\t): Promise<AuthedRead | Response> {\n\t\trequireRepoParam(repo);\n\t\tif (isSpaceCredentialAuth(c.req.header(\"Authorization\"))) {\n\t\t\tawait credentialAuth(c, ref);\n\t\t\treturn { kind: \"credential\" };\n\t\t}\n\t\tconst session = await host.authenticate(c);\n\t\tif (session instanceof Response) return session;\n\t\tconst scopeError = assertScope(c, session, {\n\t\t\ttype: ref.type,\n\t\t\tauthority: ref.authority,\n\t\t\tskey: ref.skey,\n\t\t\taction: \"read_self\",\n\t\t});\n\t\tif (scopeError) return scopeError;\n\t\treturn { kind: \"session\" };\n\t}\n\n\t/**\n\t * The MAC owed by a read that returns a commit or record, with the\n\t * response headers a browser syncer needs to read the MAC.\n\t */\n\tasync function readMac(\n\t\tc: Context,\n\t\tauth: AuthedRead,\n\t\tprofile: MacProfile,\n\t): Promise<MacParams | undefined> {\n\t\tappendHeader(c, \"Vary\", \"Accept-Signature\");\n\t\tconst mac = await macRequest({\n\t\t\tacceptSignature: c.req.header(MAC_REQUEST_HEADER),\n\t\t\tcredential: auth.kind === \"credential\",\n\t\t\tprofile,\n\t\t\tgetKemKeypair,\n\t\t});\n\t\tif (mac) {\n\t\t\tfor (const header of macExposedHeaders(profile)) {\n\t\t\t\tappendHeader(c, \"Access-Control-Expose-Headers\", header);\n\t\t\t}\n\t\t}\n\t\treturn mac;\n\t}\n\n\tfunction assertScope(\n\t\tc: Context,\n\t\tsession: SpaceSessionAuth,\n\t\tmatch: SpaceScopeMatch,\n\t): ScopeResult {\n\t\tif (session.fullTrust) return null;\n\t\tif (session.allowsSpace(match)) return null;\n\t\treturn c.json(\n\t\t\t{\n\t\t\t\terror: \"InsufficientScope\",\n\t\t\t\tmessage: \"Token does not cover this space operation\",\n\t\t\t},\n\t\t\t403,\n\t\t);\n\t}\n\n\t/** The operator hosts this space, or SpaceNotFound. */\n\tfunction assertSpaceHost(ref: SpaceRef): void {\n\t\tif (ref.authority !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t}\n\n\t/** As assertSpaceHost, and the authority's account must be active. */\n\tasync function assertActiveSpaceHost(ref: SpaceRef): Promise<void> {\n\t\tassertSpaceHost(ref);\n\t\tif (host.isAccountActive && !(await host.isAccountActive())) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoDeactivated\",\n\t\t\t\t`Repo has been deactivated: ${ref.authority}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * A space created here is anchored on its creator's DID, so ownership\n\t * is a comparison against the space URI, made before anything else.\n\t */\n\tfunction assertOwner(ref: SpaceRef, session: SpaceSessionAuth): void {\n\t\tif (session.did !== ref.authority) {\n\t\t\tthrow new SpaceError(\"NotAuthorized\", \"Not the space authority\");\n\t\t}\n\t\tassertSpaceHost(ref);\n\t}\n\n\t/** The policy of a live space this host governs. */\n\tasync function requirePolicy(\n\t\tstub: SpaceStub,\n\t\tref: SpaceRef,\n\t): Promise<SpacePolicy> {\n\t\tconst { meta, policy } = await stub.rpcGetAuthorityState();\n\t\tif (!meta || meta.deletedAt || !policy) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t\treturn policy;\n\t}\n\n\t/**\n\t * Whether a policy authorises an account to read or write. `repo` is\n\t * absent for a read with no delegation token, which a policy authorises\n\t * only if it does not gate on the account. The authority always passes\n\t * under every policy: it alone can reconfigure the space, so it must not\n\t * be able to lock itself out.\n\t *\n\t * A managing app that can't be reached throws UpstreamFailure rather\n\t * than denying: denying would read as a loss of access, withdrawing a\n\t * syncer's registration and making a repo host drop its notification.\n\t */\n\tasync function authorizeRepo(params: {\n\t\tpolicy: SpacePolicy;\n\t\tref: SpaceRef;\n\t\trepo: string | undefined;\n\t\taccess: \"read\" | \"write\";\n\t\tclientId?: string;\n\t\tstub: SpaceStub;\n\t}): Promise<boolean> {\n\t\tconst { policy, ref, repo, access, clientId, stub } = params;\n\t\tif (repo === ref.authority) return true;\n\t\tswitch (policy.$type) {\n\t\t\tcase PERSONALSPACE_POLICY:\n\t\t\t\treturn false;\n\t\t\tcase MEMBERSPACE_POLICY: {\n\t\t\t\tif (access === \"read\" && policy.publicRead) return true;\n\t\t\t\tif (!repo) return false;\n\t\t\t\tconst member = await stub.rpcGetMember(repo);\n\t\t\t\tif (access === \"read\") return member?.read ?? false;\n\t\t\t\t// A member without write access stays excluded even under\n\t\t\t\t// publicWrite.\n\t\t\t\tif (member) return member.write;\n\t\t\t\treturn policy.publicWrite;\n\t\t\t}\n\t\t\tcase MANAGEDSPACE_POLICY:\n\t\t\t\treturn (await checkAccess(policy.managingApp, ref, repo, clientId))[\n\t\t\t\t\taccess\n\t\t\t\t];\n\t\t}\n\t}\n\n\t/** Ask a managed space's managing app for an account's access. */\n\tasync function checkAccess(\n\t\tmanagingApp: string,\n\t\tref: SpaceRef,\n\t\trepo: string | undefined,\n\t\tclientId: string | undefined,\n\t): Promise<{ read: boolean; write: boolean }> {\n\t\ttry {\n\t\t\tconst endpoint = await host.resolveServiceEndpoint(managingApp);\n\t\t\tif (!endpoint) throw new Error(\"could not resolve the managing app\");\n\t\t\tconst token = await createServiceJwt(\n\t\t\t\t{ iss: host.operatorDid, aud: managingApp, lxm: CHECK_ACCESS_LXM },\n\t\t\t\tawait host.getKeypair(),\n\t\t\t);\n\t\t\tconst url = new URL(`${endpoint}/xrpc/${CHECK_ACCESS_LXM}`);\n\t\t\turl.searchParams.set(\"space\", ref.uri);\n\t\t\tif (repo) url.searchParams.set(\"repo\", repo);\n\t\t\tif (clientId) url.searchParams.set(\"clientId\", clientId);\n\t\t\t// No redirects: the endpoint comes from a DID document, and a\n\t\t\t// 3xx answer is a failure like any other.\n\t\t\tconst res = await doFetch(url.toString(), {\n\t\t\t\theaders: { Authorization: `Bearer ${token}` },\n\t\t\t\tredirect: \"manual\",\n\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (!res.ok) throw new Error(`checkAccess answered ${res.status}`);\n\t\t\tconst body = (await res.json()) as { read?: unknown; write?: unknown };\n\t\t\tif (typeof body.read !== \"boolean\" || typeof body.write !== \"boolean\") {\n\t\t\t\tthrow new Error(\"checkAccess answered without read and write\");\n\t\t\t}\n\t\t\treturn { read: body.read, write: body.write };\n\t\t} catch (err) {\n\t\t\tconsole.warn(`managing app check for ${ref.uri} failed:`, err);\n\t\t\tthrow new SpaceError(\"UpstreamFailure\", \"Managing app did not answer\");\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the space DO exists for a write. The first write into a foreign\n\t * space registers it `pending` in the index, initialises the DO as repo\n\t * host, then activates the entry. The operator's own spaces must already\n\t * exist: a write must neither conjure an ungoverned space nor revive a\n\t * deleted one.\n\t */\n\tasync function ensureSpaceForWrite(\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t): Promise<void> {\n\t\tconst meta = await stub.rpcGetMeta();\n\t\tif (meta && !meta.deletedAt) return;\n\t\tif (ref.authority === host.operatorDid) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpaceNotFound\",\n\t\t\t\t`Space not found: ${ref.uri}. Create it with com.atproto.space.createSpace.`,\n\t\t\t);\n\t\t}\n\t\tconst index = host.getIndexDO();\n\t\tawait index.rpcRegister({\n\t\t\turi: ref.uri,\n\t\t\tauthority: ref.authority,\n\t\t\ttype: ref.type,\n\t\t\tskey: ref.skey,\n\t\t\tisAuthority: false,\n\t\t});\n\t\tawait stub.rpcInit({\n\t\t\turi: ref.uri,\n\t\t\tauthority: ref.authority,\n\t\t\ttype: ref.type,\n\t\t\tskey: ref.skey,\n\t\t\tisAuthority: false,\n\t\t});\n\t\tawait index.rpcActivate(ref.uri);\n\t}\n\n\t/**\n\t * Promote staged blobs to the space's R2 prefix. Runs before the DO\n\t * commit so nothing reacting to the commit sees a 404. Idempotent per\n\t * CID; CIDs that are neither staged nor at the destination are skipped.\n\t */\n\tasync function promoteSpaceBlobs(\n\t\tref: SpaceRef,\n\t\tblobCids: string[],\n\t): Promise<string[]> {\n\t\tconst missing: string[] = [];\n\t\tif (!host.blobs || blobCids.length === 0) return missing;\n\t\tawait Promise.all(\n\t\t\tblobCids.map(async (cid) => {\n\t\t\t\tconst present = await promoteStagedBlobToSpace(\n\t\t\t\t\thost.blobs!,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\tref.uri,\n\t\t\t\t\tcid,\n\t\t\t\t);\n\t\t\t\tif (!present) missing.push(cid);\n\t\t\t}),\n\t\t);\n\t\treturn missing;\n\t}\n\n\t/**\n\t * After a commit: the authority sequences its own update into the writer\n\t * set, which queues it for registered syncers; a repo host in a foreign\n\t * space delivers its latest state to the authority, immediately,\n\t * persisting a retryable failure for the DO's alarm to retry for up to\n\t * 24 hours. Retries coalesce, so only the newest revision is pending.\n\t */\n\tasync function postWrite(\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t\tcommit: RepoCommitResult,\n\t): Promise<void> {\n\t\tif (ref.authority === host.operatorDid) {\n\t\t\tawait stub.rpcRecordWriter(host.operatorDid, commit.rev, commit.data);\n\t\t\treturn;\n\t\t}\n\t\tconst body = {\n\t\t\tspace: ref.uri,\n\t\t\trepo: host.operatorDid,\n\t\t\trepoRev: commit.rev,\n\t\t\tdata: bytesToJson(commit.data),\n\t\t};\n\t\tconst aud = spaceHostAud(ref.authority as `did:${string}:${string}`);\n\t\tconst endpoint = await host.resolveServiceEndpoint(aud).catch(() => null);\n\t\tif (!endpoint) {\n\t\t\tconsole.warn(`notifyRepoUpdate: no endpoint for ${ref.authority}`);\n\t\t\treturn;\n\t\t}\n\t\tconst retry: NotifyItem = {\n\t\t\tservice: aud,\n\t\t\tendpoint,\n\t\t\tlxm: NOTIFY_REPO_UPDATE_LXM,\n\t\t\tbody,\n\t\t\tcoalesceKey: NOTIFY_REPO_UPDATE_COALESCE_KEY,\n\t\t\tdeadline: Date.now() + NOTIFY_WRITE_RETRY_MS,\n\t\t\tpolicy: \"repo\",\n\t\t\tauth: \"service\",\n\t\t};\n\t\ttry {\n\t\t\tconst token = await createServiceJwt(\n\t\t\t\t{ iss: host.operatorDid, aud, lxm: NOTIFY_REPO_UPDATE_LXM },\n\t\t\t\tawait host.getKeypair(),\n\t\t\t);\n\t\t\tconst res = await doFetch(`${endpoint}/xrpc/${NOTIFY_REPO_UPDATE_LXM}`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t// Not re-POSTed elsewhere with service auth: a 3xx is refused.\n\t\t\t\tredirect: \"manual\",\n\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (res.ok || !isRetryableStatus(res.status)) {\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`notifyRepoUpdate to ${ref.authority} refused: ${res.status}; not retrying`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait stub.rpcClearNotify(NOTIFY_REPO_UPDATE_COALESCE_KEY);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.warn(\n\t\t\t\t`notifyRepoUpdate to ${ref.authority} failed: ${res.status}`,\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tconsole.warn(`notifyRepoUpdate to ${ref.authority} errored:`, err);\n\t\t}\n\t\tawait stub.rpcEnqueueNotify([retry], { delayMs: NOTIFY_BACKOFF_BASE_MS });\n\t}\n\n\tinterface WriteInput {\n\t\taction: \"create\" | \"update\" | \"delete\";\n\t\tcollection: string;\n\t\trkey?: string;\n\t\tvalue?: unknown;\n\t}\n\n\t/**\n\t * Common write pipeline for createRecord/putRecord/deleteRecord and\n\t * applyWrites: validate, prepare bytes and CIDs, promote blobs, ensure\n\t * the space DO, apply the batch, notify in the background.\n\t */\n\tasync function runWrites(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\tsession: SpaceSessionAuth,\n\t\twrites: WriteInput[],\n\t\tvalidate: boolean | undefined,\n\t): Promise<\n\t\t| Response\n\t\t| {\n\t\t\t\trev: string;\n\t\t\t\tresults: Array<{\n\t\t\t\t\taction: string;\n\t\t\t\t\tcollection: string;\n\t\t\t\t\trkey: string;\n\t\t\t\t\tcid: string | null;\n\t\t\t\t\tvalidationStatus?: string;\n\t\t\t\t}>;\n\t\t }\n\t> {\n\t\tconst prepared: PreparedSpaceWrite[] = [];\n\t\tconst statuses: Array<string | undefined> = [];\n\t\tconst blobCids = new Set<string>();\n\n\t\tfor (const write of writes) {\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertNotPublishedCollection(write.collection);\n\n\t\t\tif (write.action === \"delete\") {\n\t\t\t\tprepared.push({\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey!,\n\t\t\t\t});\n\t\t\t\tstatuses.push(undefined);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst rkey = write.rkey ?? tidNow();\n\t\t\tlet validated;\n\t\t\ttry {\n\t\t\t\tvalidated = host.validateRecord({\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trecord: write.value,\n\t\t\t\t\trkey,\n\t\t\t\t\tvalidate,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"InvalidRecord\",\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst preparedRecord = await prepareRecord(validated.record);\n\t\t\tif (preparedRecord.bytes.length > MAX_SPACE_RECORD_BYTES) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`Record exceeds the maximum space record size of ${MAX_SPACE_RECORD_BYTES} bytes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const cid of preparedRecord.blobCids) blobCids.add(cid);\n\t\t\tprepared.push({\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t\trkey,\n\t\t\t\tcid: preparedRecord.cid,\n\t\t\t\tbytes: preparedRecord.bytes,\n\t\t\t\tblobCids: preparedRecord.blobCids,\n\t\t\t});\n\t\t\tstatuses.push(validated.status);\n\t\t}\n\n\t\t// The copy completes before the DO commit is applied, so a relay or\n\t\t// syncer reacting to the commit never sees a 404.\n\t\tawait promoteSpaceBlobs(ref, Array.from(blobCids));\n\n\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\tawait ensureSpaceForWrite(ref, stub);\n\t\tconst result = await stub.rpcApplyWrites(prepared);\n\n\t\twaitUntil(c, postWrite(ref, stub, result));\n\n\t\treturn {\n\t\t\trev: result.rev,\n\t\t\tresults: result.results.map((r, i) => ({\n\t\t\t\t...r,\n\t\t\t\t...(statuses[i] !== undefined ? { validationStatus: statuses[i] } : {}),\n\t\t\t})),\n\t\t};\n\t}\n\n\t/** Notify after a configuration change that published to the repo. */\n\tfunction afterConfigCommit(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t\tcommit: RepoCommitResult | null,\n\t): void {\n\t\tif (commit) waitUntil(c, postWrite(ref, stub, commit));\n\t}\n\n\t// ---------------------------------------------------------------\n\t// Write endpoints (repo host, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.createRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\trecord?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"create\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t\tvalue: body.record,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tbody.validate,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\tconst write = result.results[0]!;\n\t\t\treturn c.json({\n\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\tref.uri,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t),\n\t\t\t\tcid: write.cid,\n\t\t\t\t...(write.validationStatus\n\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.putRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\trecord?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\trequireString(body.rkey, \"rkey\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\n\t\t\t// Upsert: the scope asserted is the operation actually performed.\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst meta = await stub.rpcGetMeta();\n\t\t\tconst exists =\n\t\t\t\tmeta && !meta.deletedAt\n\t\t\t\t\t? (await stub.rpcGetRecord(body.collection!, body.rkey!)) !== null\n\t\t\t\t\t: false;\n\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: exists ? \"update\" : \"create\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t\tvalue: body.record,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tbody.validate,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\tconst write = result.results[0]!;\n\t\t\treturn c.json({\n\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\tref.uri,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t),\n\t\t\t\tcid: write.cid,\n\t\t\t\t...(write.validationStatus\n\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.deleteRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\trequireString(body.rkey, \"rkey\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[{ action: \"delete\", collection: body.collection!, rkey: body.rkey }],\n\t\t\t\tundefined,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\t// Deleting an absent record succeeds: nothing committed, nothing\n\t\t\t// notified.\n\t\t\tif (parseSpaceErrorCode(err)?.code === \"RecordNotFound\") {\n\t\t\t\treturn c.json({});\n\t\t\t}\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.applyWrites\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\twrites?: Array<{\n\t\t\t\t\t$type?: string;\n\t\t\t\t\tcollection?: string;\n\t\t\t\t\trkey?: string;\n\t\t\t\t\tvalue?: unknown;\n\t\t\t\t}>;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\tif (!Array.isArray(body.writes)) {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"writes must be an array\");\n\t\t\t}\n\t\t\tif (body.writes.length > 200) {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"Too many writes. Max: 200\");\n\t\t\t}\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\n\t\t\tconst inputs: WriteInput[] = body.writes.map((write, i) => {\n\t\t\t\tconst action =\n\t\t\t\t\twrite.$type === \"com.atproto.space.applyWrites#create\"\n\t\t\t\t\t\t? (\"create\" as const)\n\t\t\t\t\t\t: write.$type === \"com.atproto.space.applyWrites#update\"\n\t\t\t\t\t\t\t? (\"update\" as const)\n\t\t\t\t\t\t\t: write.$type === \"com.atproto.space.applyWrites#delete\"\n\t\t\t\t\t\t\t\t? (\"delete\" as const)\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\tif (!action || !write.collection) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t`Write ${i}: unknown $type or missing collection`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (action !== \"create\" && !write.rkey) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t`Write ${i}: ${action} requires rkey`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\taction,\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\tvalue: write.value,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tconst result = await runWrites(c, ref, session, inputs, body.validate);\n\t\t\tif (result instanceof Response) return result;\n\t\t\treturn c.json({\n\t\t\t\tresults: result.results.map((write) => {\n\t\t\t\t\tif (write.action === \"delete\") {\n\t\t\t\t\t\treturn { $type: \"com.atproto.space.applyWrites#deleteResult\" };\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\t$type: `com.atproto.space.applyWrites#${write.action}Result`,\n\t\t\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\t\t\tref.uri,\n\t\t\t\t\t\t\thost.operatorDid,\n\t\t\t\t\t\t\twrite.collection,\n\t\t\t\t\t\t\twrite.rkey,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tcid: write.cid,\n\t\t\t\t\t\t...(write.validationStatus\n\t\t\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.clearRecords\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; repo?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.repo, \"repo\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tif (body.repo !== session.did) {\n\t\t\t\tthrow new SpaceError(\"Forbidden\", \"repo must match authenticated user\");\n\t\t\t}\n\t\t\trequireRepoParam(body.repo);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst meta = await stub.rpcGetMeta();\n\t\t\tif (!meta || meta.deletedAt) return c.json({});\n\n\t\t\t// In the authority's own repo the published policy and member\n\t\t\t// records are the host's copy of the space's configuration, not\n\t\t\t// the account's records, so they stay, and keeping them takes no\n\t\t\t// grant.\n\t\t\tconst keep =\n\t\t\t\tref.authority === host.operatorDid ? [...PUBLISHED_COLLECTIONS] : [];\n\t\t\tfor (const collection of await stub.rpcListCollections()) {\n\t\t\t\tif (keep.includes(collection)) continue;\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\t\t\tconst commit = await stub.rpcClearRecords(keep);\n\t\t\tif (commit) waitUntil(c, postWrite(ref, stub, commit));\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.importRepo\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst bytes = await readBody(c);\n\n\t\t\tlet records: ImportedRecord[];\n\t\t\tlet space: string;\n\t\t\tlet repo: string;\n\t\t\ttry {\n\t\t\t\tconst archive = await readRepoStar([bytes]);\n\t\t\t\ttry {\n\t\t\t\t\tspace = archive.commit.space;\n\t\t\t\t\trepo = archive.commit.repo;\n\t\t\t\t\trecords = [];\n\t\t\t\t\tfor await (const record of archive.records) {\n\t\t\t\t\t\t// Stored re-encoded, as any other write is. A record that\n\t\t\t\t\t\t// wasn't canonical DRISL in the archive would no longer match\n\t\t\t\t\t\t// its cid, nor the commit data.\n\t\t\t\t\t\tconst encoded = encode(record.record as LexValue);\n\t\t\t\t\t\tconst cid = await cidForCbor(encoded);\n\t\t\t\t\t\tif (!cid.equals(record.cid)) {\n\t\t\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t\t\t`Invalid STAR: record is not canonical DRISL at ${record.collection}/${record.rkey}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst blobCids: string[] = [];\n\t\t\t\t\t\tfor (const ref of enumBlobRefs(record.record as LexValue, {\n\t\t\t\t\t\t\tstrict: false,\n\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\tblobCids.push(getBlobCidString(ref));\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecords.push({\n\t\t\t\t\t\t\tcollection: record.collection,\n\t\t\t\t\t\t\trkey: record.rkey,\n\t\t\t\t\t\t\tcid: cid.toString(),\n\t\t\t\t\t\t\tbytes: encoded,\n\t\t\t\t\t\t\tblobCids,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tawait archive[Symbol.asyncDispose]();\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthrow invalidArchive(err, \"InvalidRepoFile\");\n\t\t\t}\n\n\t\t\tif (repo !== host.operatorDid || repo !== session.did) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoMismatch\",\n\t\t\t\t\t\"Repo does not match the authenticated account\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst ref = requireSpaceUri(space);\n\t\t\t// Importing replaces the whole repo, so it takes full access to the\n\t\t\t// space: read, and every write on every collection (\"*\" matches\n\t\t\t// only a grant covering them all), as the reference requires.\n\t\t\tfor (const match of [\n\t\t\t\t{ action: \"read\" },\n\t\t\t\t{ action: \"create\", collection: \"*\" },\n\t\t\t\t{ action: \"update\", collection: \"*\" },\n\t\t\t\t{ action: \"delete\", collection: \"*\" },\n\t\t\t] as const) {\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\t...match,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tif (ref.authority === host.operatorDid) {\n\t\t\t\t// The authority's space must arrive first, via importSpaceMeta.\n\t\t\t\tawait requirePolicy(stub, ref);\n\t\t\t} else {\n\t\t\t\tawait ensureSpaceForWrite(ref, stub);\n\t\t\t}\n\t\t\tawait stub.rpcImportRepo(records);\n\n\t\t\t// Blobs are uploaded separately. Those already staged are promoted\n\t\t\t// now; the rest are claimed by uploadBlob when they arrive.\n\t\t\tconst missing = await promoteSpaceBlobs(\n\t\t\t\tref,\n\t\t\t\tArray.from(new Set(records.flatMap((r) => r.blobCids))),\n\t\t\t);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tawait host.getIndexDO().rpcAddPendingBlobs(ref.uri, missing);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Read and sync endpoints (credential or session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.get(\"/xrpc/com.atproto.space.getRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst collection = c.req.query(\"collection\");\n\t\t\tconst rkey = c.req.query(\"rkey\");\n\t\t\trequireString(collection, \"collection\");\n\t\t\trequireString(rkey, \"rkey\");\n\t\t\tconst mac = await readMac(c, auth, RECORD_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst record = await stub.rpcGetRecord(collection!, rkey!);\n\t\t\tconst uri = spaceRecordUri(ref.uri, host.operatorDid, collection!, rkey!);\n\t\t\tif (!record) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordNotFound\",\n\t\t\t\t\t`Could not locate record: ${uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{ uri, cid: record.cid, value: recordBytesToJson(record.bytes) },\n\t\t\t\t200,\n\t\t\t\trecordMacHeaders(mac, uri, record.cid),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRecords\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst collection = c.req.query(\"collection\");\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 50, 1000);\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\t\t\tconst after = parseRecordCursor(c.req.query(\"cursor\"));\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListRecords({\n\t\t\t\tcollection,\n\t\t\t\tlimit,\n\t\t\t\tafter,\n\t\t\t\texcludeValues,\n\t\t\t});\n\t\t\tconst records = page.records.map((record) => ({\n\t\t\t\tcollection: record.collection,\n\t\t\t\trkey: record.rkey,\n\t\t\t\tcid: record.cid,\n\t\t\t\t...(record.bytes\n\t\t\t\t\t? { value: recordBytesToJson(new Uint8Array(record.bytes)) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\tconst last = page.records[page.records.length - 1];\n\t\t\treturn c.json({\n\t\t\t\trecords,\n\t\t\t\t...(page.hasMore && last\n\t\t\t\t\t? { cursor: `${last.collection}/${last.rkey}` }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getLatestCommit\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst state = await stub.rpcGetRepoState();\n\t\t\tif (!state) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: { setHash: new Uint8Array(state.setHash), rev: state.rev },\n\t\t\t});\n\t\t\treturn c.json(\n\t\t\t\t{ commit: commitToJson(commit) },\n\t\t\t\t200,\n\t\t\t\tcommitMacHeaders(mac, commit),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRepoOps\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\tconst since = c.req.query(\"since\");\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\t\t\tconst after = parseOpsCursor(c.req.query(\"cursor\"));\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListRepoOps({\n\t\t\t\tsince,\n\t\t\t\tafter,\n\t\t\t\tlimit,\n\t\t\t\texcludeValues,\n\t\t\t});\n\t\t\tconst ops = page.ops.map((op) => ({\n\t\t\t\trev: op.rev,\n\t\t\t\tcollection: op.collection,\n\t\t\t\trkey: op.rkey,\n\t\t\t\tcid: op.cid,\n\t\t\t\tprev: op.prev,\n\t\t\t\t...(op.bytes\n\t\t\t\t\t? { value: recordBytesToJson(new Uint8Array(op.bytes)) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\t// Never written: no commit to answer with.\n\t\t\tif (!page.head) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The commit, with its MAC, is on every page. A full page carries a\n\t\t\t// cursor, so the last page may be empty.\n\t\t\tconst last = page.ops[page.ops.length - 1];\n\t\t\tconst cursor =\n\t\t\t\tlast && page.ops.length === limit\n\t\t\t\t\t? `${last.rev}/${last.idx}`\n\t\t\t\t\t: undefined;\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: {\n\t\t\t\t\tsetHash: new Uint8Array(page.head.setHash),\n\t\t\t\t\trev: page.head.rev,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn c.json(\n\t\t\t\t{ ops, commit: commitToJson(commit), ...(cursor ? { cursor } : {}) },\n\t\t\t\t200,\n\t\t\t\tcommitMacHeaders(mac, commit),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getRepo\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\n\t\t\t// The archive streams page by page. Each page reports the repo\n\t\t\t// state it was read at; a page from a later state means a write\n\t\t\t// landed mid-export, and the stream errors rather than serve\n\t\t\t// records that don't match the commit. The syncer's verification\n\t\t\t// would refuse such an archive anyway; failing loudly lets it\n\t\t\t// retry at once.\n\t\t\tconst PAGE = 500;\n\t\t\tconst first = await stub.rpcListRecordsByPath({ limit: PAGE });\n\t\t\tconst state = first.state;\n\t\t\tif (!state) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: { setHash: new Uint8Array(state.setHash), rev: state.rev },\n\t\t\t});\n\t\t\tasync function* records() {\n\t\t\t\tlet page = first;\n\t\t\t\tfor (;;) {\n\t\t\t\t\tfor (const record of page.records) {\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\tcollection: record.collection as never,\n\t\t\t\t\t\t\trkey: record.rkey as never,\n\t\t\t\t\t\t\tbytes: new Uint8Array(record.bytes),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst last = page.records[page.records.length - 1];\n\t\t\t\t\tif (!page.hasMore || !last) return;\n\t\t\t\t\tpage = await stub.rpcListRecordsByPath({\n\t\t\t\t\t\tafterPath: `${last.collection}/${last.rkey}`,\n\t\t\t\t\t\tlimit: PAGE,\n\t\t\t\t\t});\n\t\t\t\t\tif (page.state?.rev !== state!.rev) {\n\t\t\t\t\t\tthrow new Error(\"The repo changed during export; retry getRepo\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst star = writeRepoStar(\n\t\t\t\tcommit as Parameters<typeof writeRepoStar>[0],\n\t\t\t\trecords(),\n\t\t\t);\n\t\t\treturn c.body(asyncIterableToStream(star), 200, {\n\t\t\t\t\"Content-Type\": STAR_CONTENT_TYPE,\n\t\t\t\t...commitMacHeaders(mac, commit),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listBlobs\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 500, 1000);\n\t\t\tconst afterCid = c.req.query(\"cursor\");\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListBlobs({ limit, afterCid });\n\t\t\tconst last = page.cids[page.cids.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tcids: page.cids,\n\t\t\t\t...(page.hasMore && last ? { cursor: last } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getBlob\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst cid = c.req.query(\"cid\");\n\t\t\trequireString(cid, \"cid\");\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\t// Refuse before touching the blobstore: do not reveal whether an\n\t\t\t// unreferenced blob exists.\n\t\t\tif (!(await stub.rpcHasSpaceBlob(cid!))) {\n\t\t\t\tthrow new SpaceError(\"BlobNotFound\", `Blob not found: ${cid}`);\n\t\t\t}\n\t\t\tif (!host.blobs) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"ServiceUnavailable\",\n\t\t\t\t\t\tmessage: \"Blob storage is not configured\",\n\t\t\t\t\t},\n\t\t\t\t\t503,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = spaceBlobKey(host.operatorDid, await spaceId(ref.uri), cid!);\n\t\t\tlet blob = await host.blobs.get(key);\n\t\t\tif (!blob) {\n\t\t\t\t// Referenced but never promoted (an imported record whose blob\n\t\t\t\t// arrived through another path): promote on first read.\n\t\t\t\tif (\n\t\t\t\t\tawait promoteStagedBlobToSpace(\n\t\t\t\t\t\thost.blobs,\n\t\t\t\t\t\thost.operatorDid,\n\t\t\t\t\t\tref.uri,\n\t\t\t\t\t\tcid!,\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tblob = await host.blobs.get(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!blob) {\n\t\t\t\tthrow new SpaceError(\"BlobNotFound\", `Blob not found: ${cid}`);\n\t\t\t}\n\t\t\treturn new Response(blob.body, {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\":\n\t\t\t\t\t\tblob.httpMetadata?.contentType ?? \"application/octet-stream\",\n\t\t\t\t\t\"Content-Length\": blob.size.toString(),\n\t\t\t\t\t// A shared cache in front of the PDS must never store a\n\t\t\t\t\t// response whose authorisation was per-credential.\n\t\t\t\t\t\"Cache-Control\": \"private, no-store\",\n\t\t\t\t\tVary: \"Authorization\",\n\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t\t\"Content-Disposition\": `attachment; filename=\"${cid}\"`,\n\t\t\t\t\t\"Content-Security-Policy\": \"default-src 'none'; sandbox\",\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Space host endpoints (authority role)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.authorizeSpaceSync\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\tcredentialKey?: string;\n\t\t\t\tdelegationToken?: string;\n\t\t\t\tclientAttestation?: string;\n\t\t\t\tnotify?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.credentialKey, \"credentialKey\");\n\t\t\tif (!isP256DidKey(body.credentialKey!)) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"credentialKey must be a P-256 did:key\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst notify =\n\t\t\t\tbody.notify === undefined ? undefined : parseNotify(body.notify);\n\n\t\t\t// Before anything touches the space DO: a space this host doesn't\n\t\t\t// govern must not get one created for it by a well-formed request.\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst { meta, policy } = await stub.rpcGetAuthorityState();\n\t\t\t// The durable signal that a space is gone: a syncer that missed\n\t\t\t// its deletion notice learns it here, the next time it\n\t\t\t// reauthorises, whatever the request's authorisation.\n\t\t\tif (meta?.deletedAt) {\n\t\t\t\tthrow new SpaceError(\"SpaceDeleted\", `Space deleted: ${ref.uri}`);\n\t\t\t}\n\n\t\t\t// Absent when the request carries no delegation token, which only\n\t\t\t// a space that does not gate on the account accepts.\n\t\t\tlet repo: string | undefined;\n\t\t\tif (body.delegationToken) {\n\t\t\t\t({ userDid: repo } = await verifyDelegationToken(\n\t\t\t\t\tbody.delegationToken,\n\t\t\t\t\tref,\n\t\t\t\t\t{\n\t\t\t\t\t\tgetSigningKey: host.getSigningKey,\n\t\t\t\t\t\tcheckReplay: (kind, key, exp) =>\n\t\t\t\t\t\t\tstub.rpcCheckReplay(kind, key, exp),\n\t\t\t\t\t},\n\t\t\t\t));\n\t\t\t}\n\n\t\t\tlet clientId: string | undefined;\n\t\t\tif (body.clientAttestation) {\n\t\t\t\tclientId = await verifyClientAttestation(body.clientAttestation, {\n\t\t\t\t\texpectedAud: spaceHostAud(ref.authority as `did:${string}:${string}`),\n\t\t\t\t\t// Checked pre-verification inside, so a client the space could\n\t\t\t\t\t// never authorise never triggers network I/O.\n\t\t\t\t\tallowedClientIds:\n\t\t\t\t\t\tpolicy?.$type === MEMBERSPACE_POLICY\n\t\t\t\t\t\t\t? policy.allowedApps\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tcheckReplay: (kind, key, exp) => stub.rpcCheckReplay(kind, key, exp),\n\t\t\t\t\tfetch: host.outboundFetch,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!meta || !policy) {\n\t\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// The account goes first, and one the policy refuses is answered\n\t\t\t\t// as though the space does not exist, so that a refusal\n\t\t\t\t// discloses nothing to someone without access to it.\n\t\t\t\tconst authorized = await authorizeRepo({\n\t\t\t\t\tpolicy,\n\t\t\t\t\tref,\n\t\t\t\t\trepo,\n\t\t\t\t\taccess: \"read\",\n\t\t\t\t\tclientId,\n\t\t\t\t\tstub,\n\t\t\t\t});\n\t\t\t\tif (!authorized) {\n\t\t\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t\t\t}\n\t\t\t\tif (!isAppAuthorized(policy, clientId)) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"AppNotAuthorized\",\n\t\t\t\t\t\t\"Application not authorized for this space\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// A refusal withdraws the registration the request carries, so a\n\t\t\t\t// syncer that has lost access stops being notified. A failure to\n\t\t\t\t// decide, such as an unreachable managing app, is not a refusal.\n\t\t\t\tif (notify && parseSpaceErrorCode(err)?.code !== \"UpstreamFailure\") {\n\t\t\t\t\tawait stub.rpcRemoveNotifyRegistration(notify);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\tif (notify && !(await stub.rpcGetNotifyRegistration(notify))) {\n\t\t\t\tawait confirmRegistration(ref, notify);\n\t\t\t}\n\n\t\t\tconst credential = await createSpaceCredential({\n\t\t\t\tiss: host.operatorDid as `did:${string}:${string}`,\n\t\t\t\tsub: ref.uri as never,\n\t\t\t\tkeyId: body.credentialKey as `did:${string}:${string}`,\n\t\t\t\tkeypair: (await host.getKeypair()) as never,\n\t\t\t});\n\n\t\t\tif (notify) {\n\t\t\t\t// Renewed by each authorisation, to the credential's expiry, so a\n\t\t\t\t// syncer that keeps reauthorising stays registered.\n\t\t\t\tconst { exp } = parseSpaceToken(\"credential\", credential).payload;\n\t\t\t\tawait stub.rpcPutNotifyRegistration(notify, exp * 1000);\n\t\t\t}\n\t\t\t// Read after registering, so any update past this revision is\n\t\t\t// notified.\n\t\t\tconst spaceRev = await stub.rpcGetSpaceRev();\n\t\t\treturn c.json({ credential, ...(spaceRev ? { spaceRev } : {}) });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listWriters\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tawait credentialAuth(c, ref);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requirePolicy(stub, ref);\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 500, 1000);\n\t\t\tconst writers = await stub.rpcListWriters({\n\t\t\t\tlimit,\n\t\t\t\tcursor: c.req.query(\"cursor\") || undefined,\n\t\t\t});\n\t\t\tconst last = writers[writers.length - 1];\n\t\t\treturn c.json({\n\t\t\t\trepos: writers.map((writer) =>\n\t\t\t\t\twriter.removed\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t$type: \"com.atproto.space.defs#repoRemoved\",\n\t\t\t\t\t\t\t\trepo: writer.did,\n\t\t\t\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t$type: \"com.atproto.space.defs#repoWrite\",\n\t\t\t\t\t\t\t\trepo: writer.did,\n\t\t\t\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\t\t\t\tdata: bytesToJson(new Uint8Array(writer.data)),\n\t\t\t\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\t// Nonempty pages carry a cursor and empty pages omit it.\n\t\t\t\t...(last ? { cursor: last.spaceRev } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.notifyRepoUpdate\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\trepoRev?: string;\n\t\t\t\tdata?: { $bytes?: string };\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.repo, \"repo\");\n\t\t\trequireString(body.repoRev, \"repoRev\");\n\t\t\tif (typeof body.data?.$bytes !== \"string\") {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"Missing data bytes\");\n\t\t\t}\n\n\t\t\tconst serviceAuth = await requireServiceAuth(c, NOTIFY_REPO_UPDATE_LXM);\n\t\t\tif (serviceAuth instanceof Response) return serviceAuth;\n\t\t\t// iss is the signer, so requiring it to match keeps a PDS from\n\t\t\t// notifying on another account's behalf.\n\t\t\tif (serviceAuth.iss !== body.repo) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"notifyRepoUpdate iss does not match the repo\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tserviceAuth.aud !== ref.authority &&\n\t\t\t\tserviceAuth.aud !==\n\t\t\t\t\tspaceHostAud(ref.authority as `did:${string}:${string}`)\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"notifyRepoUpdate aud does not match the space authority\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tassertSpaceHost(ref);\n\t\t\tlet revMs: number;\n\t\t\ttry {\n\t\t\t\trevMs = tidTimestampMs(body.repoRev!);\n\t\t\t} catch {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"repoRev must be a TID\");\n\t\t\t}\n\t\t\tif (revMs > Date.now() + MAX_REV_CLOCK_SKEW_MS) {\n\t\t\t\tthrow new SpaceError(\"FutureRev\", \"Repo revision is in the future\");\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst policy = await requirePolicy(stub, ref);\n\t\t\t// The same account perimeter used when minting credentials. The\n\t\t\t// notification comes from a PDS rather than an app, so there is no\n\t\t\t// attestation. An unreachable managing app is an UpstreamFailure,\n\t\t\t// which the repo host retries.\n\t\t\tconst authorized = await authorizeRepo({\n\t\t\t\tpolicy,\n\t\t\t\tref,\n\t\t\t\trepo: body.repo!,\n\t\t\t\taccess: \"write\",\n\t\t\t\tstub,\n\t\t\t});\n\t\t\tif (!authorized) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Repo is not authorized to write to the space\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Sequenced, and queued for registered syncers, in one transaction.\n\t\t\t// A delayed or replayed notification with an older rev changes\n\t\t\t// nothing.\n\t\t\tawait stub.rpcRecordWriter(\n\t\t\t\tbody.repo!,\n\t\t\t\tbody.repoRev!,\n\t\t\t\tfromBase64(body.data.$bytes),\n\t\t\t);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.notifyCredentialsRevoked\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\tcredentials?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst credentials = body.credentials;\n\t\t\tif (\n\t\t\t\t!Array.isArray(credentials) ||\n\t\t\t\tcredentials.length < 1 ||\n\t\t\t\tcredentials.length > 100 ||\n\t\t\t\tcredentials.some((jti) => typeof jti !== \"string\" || jti.length === 0)\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"credentials must be 1 to 100 credential jti strings\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst serviceAuth = await requireServiceAuth(c, CREDENTIALS_REVOKED_LXM);\n\t\t\tif (serviceAuth instanceof Response) return serviceAuth;\n\t\t\tif (serviceAuth.iss !== ref.authority) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Revocation issuer is not the space authority\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Addressed to the repo DID, which here is always the operator.\n\t\t\tif (serviceAuth.aud !== host.operatorDid) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Revocation audience does not match a repo hosted here\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait host\n\t\t\t\t.getSpaceDO(ref.uri)\n\t\t\t\t.rpcRevokeCredentials(\n\t\t\t\t\tcredentials as string[],\n\t\t\t\t\tMath.floor(Date.now() / 1000) + REVOCATION_TTL_SEC,\n\t\t\t\t);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Space management (authority role, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.createSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspaceType?: string;\n\t\t\t\tskey?: string;\n\t\t\t\tpolicy?: unknown;\n\t\t\t}>();\n\t\t\trequireString(body.spaceType, \"spaceType\");\n\t\t\tconst skey = body.skey ?? tidNow();\n\t\t\tconst ref = requireSpaceUri(\n\t\t\t\tformatSpaceUri(host.operatorDid, body.spaceType!, skey),\n\t\t\t);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: host.operatorDid,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"create\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst policy = normalizePolicy(body.policy);\n\n\t\t\t// Two-step creation: index entry `pending`, then the DO, then\n\t\t\t// `active`. Reads never depend on the index, so a crash between\n\t\t\t// steps leaves only a pending entry for the alarm to reap.\n\t\t\tconst index = host.getIndexDO();\n\t\t\tawait index.rpcRegister({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t});\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcInit({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t\tpolicy,\n\t\t\t});\n\t\t\tawait index.rpcActivate(ref.uri);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({ space: ref.uri });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.updateSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; policy?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst policy = normalizePolicy(body.policy);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcUpdatePolicy(policy);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.deleteSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"delete\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\t// Credential issuance stops with the tombstone, and every registered\n\t\t\t// syncer, lapsed or not, is queued a deletion notice delivered\n\t\t\t// reliably for 72 hours. Then reap the blob prefix.\n\t\t\tawait stub.rpcDeleteSpace();\n\t\t\tawait host.getIndexDO().rpcMarkDeleted(ref.uri);\n\t\t\tif (host.blobs) {\n\t\t\t\twaitUntil(\n\t\t\t\t\tc,\n\t\t\t\t\tdeleteR2Prefix(\n\t\t\t\t\t\thost.blobs,\n\t\t\t\t\t\tspaceBlobPrefix(host.operatorDid, await spaceId(ref.uri)),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst policy = await requirePolicy(host.getSpaceDO(ref.uri), ref);\n\t\t\treturn c.json({ space: ref.uri, policy });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.removeWriter\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; repo?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireDid(body.repo, \"repo\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\t// Sequenced and announced to syncers as a repoRemoved.\n\t\t\tawait host.getSpaceDO(ref.uri).rpcRemoveWriter(body.repo!);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.exportSpaceMeta\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst exported = await host.getSpaceDO(ref.uri).rpcExportMeta();\n\t\t\tconst star = writeSpaceMetaStar({\n\t\t\t\tspace: ref.uri as never,\n\t\t\t\tpolicy: exported.policy as never,\n\t\t\t\tpolicyState: exported.members.map((member) => ({\n\t\t\t\t\tkey: `${MEMBER_COLLECTION}/${didToRecordKey(member.did)}`,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\t$type: MEMBER_COLLECTION,\n\t\t\t\t\t\tread: member.read,\n\t\t\t\t\t\twrite: member.write,\n\t\t\t\t\t},\n\t\t\t\t})),\n\t\t\t\twriters: exported.writers.map((writer) => ({\n\t\t\t\t\tdid: writer.did as never,\n\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\tdata: new Uint8Array(writer.data),\n\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t})),\n\t\t\t});\n\t\t\treturn c.body(asyncIterableToStream(star), 200, {\n\t\t\t\t\"Content-Type\": STAR_CONTENT_TYPE,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.importSpaceMeta\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst bytes = await readBody(c);\n\t\t\tlet archive;\n\t\t\ttry {\n\t\t\t\tarchive = await readSpaceMetaStar([bytes]);\n\t\t\t} catch (err) {\n\t\t\t\tthrow invalidArchive(err, \"InvalidSpaceMeta\");\n\t\t\t}\n\t\t\tconst ref = requireSpaceUri(archive.space);\n\t\t\t// Importing both creates the space here and sets its configuration.\n\t\t\tfor (const manage of [\"create\", \"update\"] as const) {\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\tmanage,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\t\t\tif (ref.authority !== session.did || ref.authority !== host.operatorDid) {\n\t\t\t\tthrow new SpaceError(\"NotAuthorized\", \"Not the space authority\");\n\t\t\t}\n\t\t\tconst policy = normalizePolicy(archive.policy);\n\t\t\tconst members = parsePolicyState(policy, archive.policyState);\n\n\t\t\tconst index = host.getIndexDO();\n\t\t\tawait index.rpcRegister({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t});\n\t\t\tawait host.getSpaceDO(ref.uri).rpcImportMeta({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tpolicy,\n\t\t\t\tmembers,\n\t\t\t\twriters: archive.writers.map((writer) => ({\n\t\t\t\t\tdid: writer.did,\n\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\tdata: writer.data,\n\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\tremoved: false,\n\t\t\t\t})),\n\t\t\t});\n\t\t\tawait index.rpcActivate(ref.uri);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listSpaces\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst type = c.req.query(\"spaceType\") || undefined;\n\t\t\tconst authority = c.req.query(\"spaceDid\") || undefined;\n\t\t\t// No one space to check against, so the filters are the target:\n\t\t\t// an unfiltered listing needs a wildcard grant. It lists only the\n\t\t\t// caller's own spaces, so read_self is the grant that fits.\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: type ?? \"*\",\n\t\t\t\tauthority: authority ?? \"*\",\n\t\t\t\tskey: \"*\",\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 50, 100);\n\t\t\tconst cursor = c.req.query(\"cursor\") || undefined;\n\t\t\tif (cursor && !parseSpaceUri(cursor)) {\n\t\t\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t\t\t}\n\t\t\tconst page = await host.getIndexDO().rpcList({\n\t\t\t\ttype,\n\t\t\t\tauthority,\n\t\t\t\tstate: \"active\",\n\t\t\t\tlimit,\n\t\t\t\tafterUri: cursor,\n\t\t\t});\n\t\t\t// The caller's repo state in each space, and the space's revision\n\t\t\t// where the caller is its authority.\n\t\t\tconst spaces = await Promise.all(\n\t\t\t\tpage.spaces.map(async (space) => {\n\t\t\t\t\tconst view = await host.getSpaceDO(space.uri).rpcGetSpaceView();\n\t\t\t\t\treturn {\n\t\t\t\t\t\tspace: space.uri,\n\t\t\t\t\t\t...(view?.repoRev ? { repoRev: view.repoRev } : {}),\n\t\t\t\t\t\t...(view?.data\n\t\t\t\t\t\t\t? { data: bytesToJson(new Uint8Array(view.data)) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(view?.spaceRev ? { spaceRev: view.spaceRev } : {}),\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst last = page.spaces[page.spaces.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tspaces,\n\t\t\t\t...(page.hasMore && last ? { cursor: last.uri } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// memberspace (authority role, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.memberspace.putMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; members?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst members = parseMemberBatch(body.members);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcPutMembers(members);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.memberspace.removeMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; dids?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst dids = body.dids;\n\t\t\tif (\n\t\t\t\t!Array.isArray(dids) ||\n\t\t\t\tdids.length > MAX_MEMBER_BATCH ||\n\t\t\t\tdids.some((did) => typeof did !== \"string\" || !did.startsWith(\"did:\"))\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`dids must be an array of at most ${MAX_MEMBER_BATCH} DIDs`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcRemoveMembers(dids as string[]);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.memberspace.listMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\t// The cursor is the last member DID of the previous page.\n\t\t\tconst cursor = c.req.query(\"cursor\");\n\t\t\tif (cursor !== undefined && !isDid(cursor)) {\n\t\t\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t\t\t}\n\t\t\tconst page = await host.getSpaceDO(ref.uri).rpcListMembers({\n\t\t\t\tlimit,\n\t\t\t\tafterDid: cursor,\n\t\t\t});\n\t\t\tconst last = page.members[page.members.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tmembers: page.members.map((member) => ({\n\t\t\t\t\tdid: member.did,\n\t\t\t\t\tread: member.read,\n\t\t\t\t\twrite: member.write,\n\t\t\t\t})),\n\t\t\t\t...(page.hasMore && last ? { cursor: last.did } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Helpers that need the host\n\t// ---------------------------------------------------------------\n\n\t/**\n\t * Before registering a webhook, check it asked to be: the endpoint must\n\t * recognise the token as one it issued for this space and echo back a\n\t * random challenge. The endpoint is the requester's choice, so it is\n\t * fetched as untrusted: https only, no redirects, bounded in time.\n\t */\n\tasync function confirmRegistration(\n\t\tref: SpaceRef,\n\t\tnotify: NotifyRegistration,\n\t): Promise<void> {\n\t\tconst challenge = crypto.randomUUID();\n\t\ttry {\n\t\t\tconst res = await doFetch(\n\t\t\t\t`${notify.endpoint.replace(/\\/$/, \"\")}/xrpc/${CONFIRM_REGISTRATION_LXM}`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tspace: ref.uri,\n\t\t\t\t\t\ttoken: notify.token,\n\t\t\t\t\t\tchallenge,\n\t\t\t\t\t}),\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (res.ok) {\n\t\t\t\tconst body = (await res.json()) as { challenge?: unknown };\n\t\t\t\tif (body.challenge === challenge) return;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconsole.warn(`registration for ${ref.uri} not confirmed:`, err);\n\t\t}\n\t\tthrow new SpaceError(\n\t\t\t\"RegistrationNotConfirmed\",\n\t\t\t\"Notify endpoint did not confirm the registration\",\n\t\t);\n\t}\n\n\t/** Service auth for inbound notifications; a Response on failure. */\n\tasync function requireServiceAuth(\n\t\tc: Context,\n\t\tlxm: string,\n\t): Promise<{ iss: string; aud: string } | Response> {\n\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: \"AuthenticationRequired\", message: \"Service auth required\" },\n\t\t\t\t401,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\treturn await host.verifyServiceJwt(authHeader.slice(7), lxm);\n\t\t} catch (err) {\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"AuthenticationRequired\",\n\t\t\t\t\tmessage: err instanceof Error ? err.message : \"Invalid service auth\",\n\t\t\t\t},\n\t\t\t\t401,\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction isOwnAudience(aud: string): boolean {\n\t\treturn aud === host.operatorDid || aud.startsWith(`${host.operatorDid}#`);\n\t}\n\n\t/**\n\t * A repo exists in a space once the operator has written into it (or\n\t * the space was created here). RepoNotFound deliberately covers both\n\t * \"no such repo\" and \"space unknown to this host\".\n\t */\n\tasync function requireRepoExists(\n\t\tstub: SpaceStub,\n\t\tref: SpaceRef,\n\t): Promise<void> {\n\t\tconst meta = await stub.rpcGetMeta();\n\t\tif (meta?.deletedAt) {\n\t\t\t// After deletion, reads against the space fail with SpaceNotFound.\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoNotFound\",\n\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn app;\n}\n\n// ---------------------------------------------------------------------\n// Small parsing helpers\n// ---------------------------------------------------------------------\n\nfunction requireString(value: unknown, name: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`Missing required parameter: ${name}`,\n\t\t);\n\t}\n}\n\n/**\n * An authorizeSpaceSync `notify`: an https base URL the space host calls\n * XRPC methods against, and the opaque token that authenticates them.\n */\nfunction parseNotify(input: unknown): NotifyRegistration {\n\tconst notify = input as { endpoint?: unknown; token?: unknown } | null;\n\tconst endpoint = notify?.endpoint;\n\tconst token = notify?.token;\n\tif (typeof endpoint !== \"string\" || typeof token !== \"string\") {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t\"notify requires an endpoint and a token\",\n\t\t);\n\t}\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(endpoint);\n\t} catch {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"notify endpoint must be a URL\");\n\t}\n\tif (url.protocol !== \"https:\" || url.username || url.password) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t\"notify endpoint must be a plain https URL\",\n\t\t);\n\t}\n\tif (token.length === 0 || token.length > MAX_NOTIFY_TOKEN_LENGTH) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`notify token must be 1 to ${MAX_NOTIFY_TOKEN_LENGTH} characters`,\n\t\t);\n\t}\n\treturn { endpoint, token };\n}\n\nfunction requireDid(value: unknown, name: string): asserts value is string {\n\trequireString(value, name);\n\tif (!value.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `${name} must be a DID`);\n\t}\n}\n\nfunction clampLimit(\n\traw: string | undefined,\n\tfallback: number,\n\tmax: number,\n): number {\n\tconst parsed = raw ? Number.parseInt(raw, 10) : fallback;\n\tif (Number.isNaN(parsed) || parsed < 1) return fallback;\n\treturn Math.min(parsed, max);\n}\n\nfunction parseRecordCursor(\n\tcursor: string | undefined,\n): { collection: string; rkey: string } | undefined {\n\tif (!cursor) return undefined;\n\tconst slash = cursor.lastIndexOf(\"/\");\n\tif (slash <= 0 || slash === cursor.length - 1) {\n\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t}\n\treturn { collection: cursor.slice(0, slash), rkey: cursor.slice(slash + 1) };\n}\n\nfunction parseOpsCursor(\n\tcursor: string | undefined,\n): { rev: string; idx: number } | undefined {\n\tif (!cursor) return undefined;\n\tconst slash = cursor.indexOf(\"/\");\n\tconst idx = slash === -1 ? NaN : Number.parseInt(cursor.slice(slash + 1), 10);\n\tif (slash <= 0 || Number.isNaN(idx)) {\n\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t}\n\treturn { rev: cursor.slice(0, slash), idx };\n}\n\n/**\n * Read the members out of a space meta archive's policy state. A key the\n * policy doesn't define is refused rather than dropped, since dropping it\n * would quietly change who has access to the space.\n */\nfunction parsePolicyState(\n\tpolicy: SpacePolicy,\n\tentries: Array<{ key: string; value: Record<string, unknown> }>,\n): SpaceMember[] {\n\tconst prefix = `${MEMBER_COLLECTION}/`;\n\treturn entries.map(({ key, value }) => {\n\t\tconst did = key.startsWith(prefix)\n\t\t\t? recordKeyToDid(key.slice(prefix.length))\n\t\t\t: undefined;\n\t\tif (policy.$type !== MEMBERSPACE_POLICY || !did?.startsWith(\"did:\")) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Unrecognized policy state: ${key}`,\n\t\t\t);\n\t\t}\n\t\tif (typeof value.read !== \"boolean\" || typeof value.write !== \"boolean\") {\n\t\t\tthrow new SpaceError(\"InvalidRequest\", `Invalid member at ${key}`);\n\t\t}\n\t\treturn { did, read: value.read, write: value.write };\n\t});\n}\n\n/**\n * A malformed archive in a request body is the caller's error, reported\n * under the error name the method declares for it.\n */\nfunction invalidArchive(\n\terr: unknown,\n\tcode: \"InvalidRepoFile\" | \"InvalidSpaceMeta\",\n): unknown {\n\tif (parseSpaceErrorCode(err)) return err;\n\treturn new SpaceError(\n\t\tcode,\n\t\t`Invalid archive: ${err instanceof Error ? err.message : String(err)}`,\n\t);\n}\n\n/** A putMembers batch: at most 100 `{did, read, write}` entries. */\nfunction parseMemberBatch(input: unknown): SpaceMember[] {\n\tif (!Array.isArray(input) || input.length > MAX_MEMBER_BATCH) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`members must be an array of at most ${MAX_MEMBER_BATCH} entries`,\n\t\t);\n\t}\n\treturn input.map((entry, i) => {\n\t\tconst member = entry as { did?: unknown; read?: unknown; write?: unknown };\n\t\tif (\n\t\t\ttypeof member?.did !== \"string\" ||\n\t\t\t!member.did.startsWith(\"did:\") ||\n\t\t\ttypeof member.read !== \"boolean\" ||\n\t\t\ttypeof member.write !== \"boolean\"\n\t\t) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`members[${i}] must be {did, read, write}`,\n\t\t\t);\n\t\t}\n\t\treturn { did: member.did, read: member.read, write: member.write };\n\t});\n}\n\nasync function readBody(c: Context): Promise<Uint8Array> {\n\tconst contentType = c.req.header(\"Content-Type\")?.split(\";\")[0]?.trim();\n\tif (contentType !== STAR_CONTENT_TYPE) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`Content-Type must be ${STAR_CONTENT_TYPE}`,\n\t\t);\n\t}\n\tconst declared = Number.parseInt(c.req.header(\"Content-Length\") ?? \"\", 10);\n\tif (declared > MAX_IMPORT_BYTES) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Archive is too large\");\n\t}\n\tconst bytes = new Uint8Array(await c.req.arrayBuffer());\n\tif (bytes.length === 0) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Empty archive\");\n\t}\n\tif (bytes.length > MAX_IMPORT_BYTES) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Archive is too large\");\n\t}\n\treturn bytes;\n}\n\n/** A pull-based stream over an async iterable, cancelling it on abort. */\nfunction asyncIterableToStream(\n\titerable: AsyncIterable<Uint8Array>,\n): ReadableStream<Uint8Array> {\n\tconst iterator = iterable[Symbol.asyncIterator]();\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { value, done } = await iterator.next();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (err) {\n\t\t\t\tcontroller.error(err);\n\t\t\t}\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait iterator.return?.();\n\t\t},\n\t});\n}\n\nasync function deleteR2Prefix(bucket: R2Bucket, prefix: string): Promise<void> {\n\tlet cursor: string | undefined;\n\tdo {\n\t\tconst listed = await bucket.list({ prefix, cursor, limit: 500 });\n\t\tif (listed.objects.length > 0) {\n\t\t\tawait bucket.delete(listed.objects.map((object) => object.key));\n\t\t}\n\t\tcursor = listed.truncated ? listed.cursor : undefined;\n\t} while (cursor);\n}\n","/**\n * Delegation tokens, minted by the user's PDS for a space hosted anywhere.\n *\n * Thin wrappers over `@atproto/space`, which is bundled into this package\n * (consumers must never resolve its alpha dependency ranges), so a host\n * gets them without depending on that build or its types.\n */\n\nimport {\n\tcreateDelegationToken as upstreamCreateDelegationToken,\n\tspaceHostAud as upstreamSpaceHostAud,\n} from \"@atproto/space\";\nimport type { SpaceSigningKeypair } from \"./types.js\";\n\n/**\n * How a space authority is addressed as the space host: its `#atproto_pds`\n * service entry, the audience of delegation tokens and client attestations.\n */\nexport function spaceHostAud(authority: string): string {\n\treturn upstreamSpaceHostAud(authority as `did:${string}:${string}`);\n}\n\n/**\n * Mint a delegation token: the user's PDS vouching, for 60 seconds and one\n * use, that `iss` wants a credential for `space` from its authority.\n */\nexport function createDelegationToken(\n\tparams: { iss: string; space: string; authority: string },\n\tkeypair: SpaceSigningKeypair,\n): Promise<string> {\n\treturn upstreamCreateDelegationToken({\n\t\tiss: params.iss as `did:${string}:${string}`,\n\t\tsub: params.space as never,\n\t\taud: spaceHostAud(params.authority) as never,\n\t\tkeypair: keypair as never,\n\t});\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,151,152,153,154],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,kBAAkB,IAAI,WAAW,CAAC,KAAM,GAAK,CAAC;AAC3D,MAAa,uBAAuB,IAAI,WAAW,CAAC,KAAM,EAAK,CAAC;AAChE,MAAa,0BAA0B;AACvC,MAAa,iBAAiB;AAC9B,MAAa,eAAe;AAC5B,MAAa,oBAAoB;;;;;;;ACFjC,SAAgBA,SAAO,GAAG,GAAG;AACzB,KAAI,MAAM,EACN,QAAO;AAEX,KAAI,EAAE,eAAe,EAAE,WACnB,QAAO;AAEX,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,YAAY,IAC9B,KAAI,EAAE,OAAO,EAAE,GACX,QAAO;AAGf,QAAO;;;;;;;;;;ACHX,SAAgB,YAAY,OAAO,GAAG;AAClC,QAAO,IAAI,WAAW,KAAK;;;;;;;;;ACT/B,SAAgBC,eAAa,KAAK;AAC9B,QAAO;;;;;;;;ACAX,SAAgBC,SAAO,QAAQ,UAAQ;AACnC,KAAIC,YAAU,KACV,YAAS,OAAO,QAA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AO,QAAQ,SAAS,EAC3B,OAAM,OAAO,OAAO,OAAO,QAAQ,KAAK,aAAWC,SAAO,IAAI,CAAC;AAEhE,WAAS,OAAO,YAAY,OAAO,SAAS;UACpC;;;;;;;;;;;;;;;;ACj1EV,SAAgB,aAAa,WAA2B;AACvD,QAAOC,eAAqB,UAAuC;;;;;;AAOpE,SAAgB,sBACf,QACA,SACkB;AAClB,QAAOC,wBAA8B;EACpC,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,aAAa,OAAO,UAAU;EAC1B;EACT,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["CODE_SET: ReadonlySet<string>","ERROR_STATUS: Partial<Record<SpaceErrorCode, number>>","code: SpaceErrorCode","PUBLISHED_COLLECTIONS: readonly string[]","blobCids: string[]","tidNow","payload: Record<string, unknown>","results: ApplyWritesResult[\"results\"]","args: unknown[]","ops: OplogEntry[]","writes: PreparedSpaceWrite[]","sequence","now","headers: Record<string, string>","now","args: unknown[]","spaceHostAud","clientUrl: URL","metadata: { jwks?: unknown; jwks_uri?: string }","jwksUrl: URL","doFetch: typeof fetch","kemKeypair: Promise<P256Keypair | null> | null","missing: string[]","spaceHostAud","retry: NotifyItem","prepared: PreparedSpaceWrite[]","statuses: Array<string | undefined>","tidNow","records: ImportedRecord[]","space: string","repo: string","blobCids: string[]","ref","repo: string | undefined","clientId: string | undefined","revMs: number","url: URL","cursor: string | undefined","upstreamSpaceHostAud","upstreamCreateDelegationToken"],"sources":["../src/errors.ts","../src/types.ts","../src/policy.ts","../src/records.ts","../src/schema.ts","../src/mac.ts","../src/tid.ts","../src/service-jwt.ts","../src/space-do.ts","../src/index-do.ts","../src/space-uri.ts","../src/blob-keys.ts","../src/auth.ts","../src/attestation.ts","../src/routes.ts","../src/tokens.ts"],"sourcesContent":["/**\n * Typed errors for the spaces engine.\n *\n * Durable Object RPC flattens thrown errors into a wrapper `Error` whose\n * message is `\"${name}: ${message}\"`, so every error here encodes its\n * protocol error name as a message prefix. Worker-side handlers recover the\n * name with {@link parseSpaceErrorCode} and map it onto the lexicon error\n * shape.\n */\n\n/** Protocol error names used across the space and policy endpoints. */\nexport const SPACE_ERROR_CODES = [\n\t\"SpaceNotFound\",\n\t\"SpaceDeleted\",\n\t\"SpaceAlreadyExists\",\n\t\"RepoNotFound\",\n\t\"RepoDeactivated\",\n\t\"RepoTakendown\",\n\t\"RecordNotFound\",\n\t\"RecordAlreadyExists\",\n\t\"BlobNotFound\",\n\t\"AppNotAuthorized\",\n\t\"NotAuthorized\",\n\t\"AccountNotAuthorized\",\n\t\"InvalidDelegationToken\",\n\t\"InvalidClientAttestation\",\n\t\"InvalidCredential\",\n\t\"PolicyMismatch\",\n\t\"UnsupportedPolicy\",\n\t\"ServiceNotResolvable\",\n\t\"InvalidCursor\",\n\t\"InvalidRequest\",\n\t\"FutureRev\",\n\t\"InvalidSpaceMac\",\n\t\"InvalidRepoFile\",\n\t\"RepoMismatch\",\n\t\"InvalidSpaceMeta\",\n\t\"RegistrationNotConfirmed\",\n\t\"UpstreamFailure\",\n\t// Space credential authentication failures, named as the reference\n\t// names them (all 401).\n\t\"MissingJwt\",\n\t\"BadJwt\",\n\t\"BadJwtType\",\n\t\"BadJwtIss\",\n\t\"BadJwtSub\",\n\t\"BadJwtAudience\",\n\t\"BadJwtCnf\",\n\t\"BadJwtSignature\",\n\t\"JwtExpired\",\n\t\"BadSpaceSignature\",\n\t\"BadSpaceAudience\",\n\t\"CredentialRevoked\",\n\t\"Forbidden\",\n\t\"KemKeyUnavailable\",\n\t\"SpacesSchemaOutdated\",\n] as const;\n\nexport type SpaceErrorCode = (typeof SPACE_ERROR_CODES)[number];\n\nconst CODE_SET: ReadonlySet<string> = new Set(SPACE_ERROR_CODES);\n\n/** HTTP status for each error name when it isn't the default 400. */\nconst ERROR_STATUS: Partial<Record<SpaceErrorCode, number>> = {\n\tSpaceNotFound: 404,\n\tRepoNotFound: 404,\n\tBlobNotFound: 404,\n\tRecordAlreadyExists: 409,\n\tSpaceAlreadyExists: 409,\n\tAppNotAuthorized: 403,\n\t// NotAuthorized is the management methods' \"not the space authority\",\n\t// a 400 as the reference answers it.\n\tAccountNotAuthorized: 403,\n\tForbidden: 403,\n\tUpstreamFailure: 502,\n\tInvalidClientAttestation: 401,\n\tMissingJwt: 401,\n\tBadJwt: 401,\n\tBadJwtType: 401,\n\tBadJwtIss: 401,\n\tBadJwtSub: 401,\n\tBadJwtAudience: 401,\n\tBadJwtCnf: 401,\n\tBadJwtSignature: 401,\n\tJwtExpired: 401,\n\tBadSpaceSignature: 401,\n\tBadSpaceAudience: 401,\n\tCredentialRevoked: 401,\n\tKemKeyUnavailable: 503,\n\tSpacesSchemaOutdated: 503,\n};\n\nexport class SpaceError extends Error {\n\toverride name = \"SpaceError\";\n\tconstructor(\n\t\treadonly code: SpaceErrorCode,\n\t\tmessage: string,\n\t) {\n\t\t// The `${code}: ` prefix survives the DO RPC boundary.\n\t\tsuper(`${code}: ${message}`);\n\t}\n\n\tget status(): number {\n\t\treturn ERROR_STATUS[this.code] ?? 400;\n\t}\n\n\t/** The human message without the code prefix. */\n\tget detail(): string {\n\t\treturn this.message.slice(this.code.length + 2);\n\t}\n}\n\n/**\n * Recover the space error name from an error that may have crossed a DO RPC\n * boundary. Returns null for errors that aren't space errors.\n */\nexport function parseSpaceErrorCode(\n\terr: unknown,\n): { code: SpaceErrorCode; message: string } | null {\n\tif (err instanceof SpaceError) {\n\t\treturn { code: err.code, message: err.detail };\n\t}\n\tif (err instanceof Error) {\n\t\t// Durable Object RPC re-throws errors with the class name folded into\n\t\t// the message (\"SpaceError: RecordNotFound: ...\"), so scan the first\n\t\t// few prefix segments for a known code.\n\t\tlet message = err.message;\n\t\tfor (let hop = 0; hop < 3; hop++) {\n\t\t\tconst colon = message.indexOf(\": \");\n\t\t\tif (colon <= 0) break;\n\t\t\tconst code = message.slice(0, colon);\n\t\t\tif (CODE_SET.has(code)) {\n\t\t\t\treturn {\n\t\t\t\t\tcode: code as SpaceErrorCode,\n\t\t\t\t\tmessage: message.slice(colon + 2),\n\t\t\t\t};\n\t\t\t}\n\t\t\tmessage = message.slice(colon + 2);\n\t\t}\n\t}\n\treturn null;\n}\n\n/** HTTP status for a recovered space error name. */\nexport function spaceErrorStatus(code: SpaceErrorCode): number {\n\treturn ERROR_STATUS[code] ?? 400;\n}\n","/**\n * Shared types crossing the Worker โ Durable Object RPC boundary.\n */\n\n/**\n * The minimal keypair shape the engine signs with: the account's\n * `#atproto` key, for space tokens and service-auth JWTs. Structural, so a\n * host can pass any `@atproto/crypto` keypair without the engine's public\n * types depending on a particular build of that package.\n */\nexport interface SpaceSigningKeypair {\n\tjwtAlg: string;\n\tdid(): string;\n\tsign(msg: Uint8Array): Promise<Uint8Array>;\n}\n\n/** A write prepared by the Worker: validated, CBOR-encoded, CID computed. */\nexport type PreparedSpaceWrite =\n\t| {\n\t\t\taction: \"create\" | \"update\";\n\t\t\tcollection: string;\n\t\t\trkey: string;\n\t\t\tcid: string;\n\t\t\tbytes: Uint8Array;\n\t\t\t/** Blob CIDs referenced by the record. */\n\t\t\tblobCids: string[];\n\t }\n\t| {\n\t\t\taction: \"delete\";\n\t\t\tcollection: string;\n\t\t\trkey: string;\n\t };\n\n/** A repo revision that is owed a write notification. */\nexport interface RepoCommitResult {\n\trev: string;\n\t/** sha256 digest of the LtHash state: the commit's `data`. */\n\tdata: Uint8Array;\n}\n\nexport interface ApplyWritesResult extends RepoCommitResult {\n\tresults: Array<{\n\t\taction: \"create\" | \"update\" | \"delete\";\n\t\tcollection: string;\n\t\trkey: string;\n\t\tcid: string | null;\n\t}>;\n}\n\nexport interface SpaceMeta {\n\turi: string;\n\tauthority: string;\n\ttype: string;\n\tskey: string;\n\tisAuthority: boolean;\n\tcreatedAt: string;\n\tdeletedAt: string | null;\n}\n\nexport const PERSONALSPACE_POLICY = \"com.atproto.personalspace.policy\";\nexport const MEMBERSPACE_POLICY = \"com.atproto.memberspace.policy\";\nexport const MANAGEDSPACE_POLICY = \"com.atproto.managedspace.policy\";\n\n/**\n * A space policy as stored and enforced: one of the three baseline\n * policies, normalised with its defaults filled in. The wire shape and the\n * stored shape are the same object.\n */\nexport type SpacePolicy =\n\t| { $type: typeof PERSONALSPACE_POLICY }\n\t| {\n\t\t\t$type: typeof MEMBERSPACE_POLICY;\n\t\t\tpublicRead: boolean;\n\t\t\tpublicWrite: boolean;\n\t\t\tallowedApps?: string[];\n\t\t\tpublishPolicy: boolean;\n\t\t\tpublishMembers: boolean;\n\t }\n\t| {\n\t\t\t$type: typeof MANAGEDSPACE_POLICY;\n\t\t\tmanagingApp: string;\n\t\t\tpublishPolicy: boolean;\n\t };\n\nexport interface SpaceMember {\n\tdid: string;\n\tread: boolean;\n\twrite: boolean;\n}\n\nexport interface SpaceWriter {\n\tdid: string;\n\trepoRev: string;\n\tdata: Uint8Array;\n\tspaceRev: string;\n\t/** Removed from the writer set at `spaceRev`, until it writes again. */\n\tremoved: boolean;\n}\n\n/** A syncer's webhook registration (`authorizeSpaceSync`'s `notify`). */\nexport interface NotifyRegistration {\n\tendpoint: string;\n\ttoken: string;\n}\n\n/** The space sequence position assigned to an accepted repo update. */\nexport interface SpaceSequence {\n\tspaceRev: string;\n\tprevSpaceRev?: string;\n}\n\nexport interface RepoState {\n\tsetHash: Uint8Array;\n\trev: string;\n}\n\nexport interface SpaceRecordRow {\n\tcollection: string;\n\trkey: string;\n\tcid: string;\n\tbytes?: Uint8Array;\n}\n\nexport interface OplogEntry {\n\trev: string;\n\tidx: number;\n\tcollection: string;\n\trkey: string;\n\tcid: string | null;\n\tprev: string | null;\n\t/** Current record bytes for creates/updates that are not stale. */\n\tbytes?: Uint8Array;\n}\n\n/** A record imported from a repo archive, prepared by the Worker. */\nexport interface ImportedRecord {\n\tcollection: string;\n\trkey: string;\n\tcid: string;\n\tbytes: Uint8Array;\n\tblobCids: string[];\n}\n\nexport interface NotifyItem {\n\tservice: string;\n\tendpoint: string;\n\tlxm: string;\n\tbody: Record<string, unknown>;\n\t/**\n\t * Pending items sharing a key are coalesced: a newer one replaces the\n\t * older, resetting its backoff and deadline โ unless `keepPending`, when\n\t * a pending item wins.\n\t */\n\tcoalesceKey?: string;\n\tkeepPending?: boolean;\n\t/** Give up retrying after this time (ms since epoch). */\n\tdeadline?: number;\n\t/**\n\t * Retry schedule: `fanout` (best effort, a few attempts), `repo` (a repo\n\t * host's notifyRepoUpdate, exponential up to the deadline) or `syncer`\n\t * (a syncer's deletion or expiry notice, 1 minute to 12 hours).\n\t */\n\tpolicy?: \"fanout\" | \"repo\" | \"syncer\";\n\t/** `service` signs a service JWT; `none` sends a token-bearing webhook. */\n\tauth?: \"service\" | \"none\";\n}\n\n/**\n * Host configuration for the space engine's Durable Objects. Supplied by\n * the host Worker's subclass โ the engine never reads env vars itself, so\n * the same class can later serve a dedicated authority DID with no account\n * attached.\n */\nexport interface SpaceHostConfig {\n\t/** The DID whose permissioned repos this engine serves. */\n\toperatorDid: string;\n\t/** Signing keypair provider (service JWTs for notification delivery). */\n\tgetKeypair(): Promise<SpaceSigningKeypair>;\n}\n","/**\n * Space policies: the three baseline policies every PDS supports, as\n * `com.atproto.space.createSpace` / `updateSpace` take them. A policy is an\n * open union discriminated by `$type` that both selects the policy and\n * carries its configuration.\n *\n * What is stored is exactly what is enforced: {@link normalizePolicy}\n * refuses a policy this host doesn't implement and fills in every default.\n * Unknown fields are dropped, as Lexicon evolution allows.\n */\n\nimport { SpaceError } from \"./errors.js\";\nimport {\n\tMANAGEDSPACE_POLICY,\n\tMEMBERSPACE_POLICY,\n\tPERSONALSPACE_POLICY,\n\ttype SpacePolicy,\n} from \"./types.js\";\n\n/** The collection a published policy record lives in (rkey `self`). */\nexport const POLICY_COLLECTION = \"com.atproto.space.policy\";\nexport const POLICY_RKEY = \"self\";\n/** The collection published member records live in (rkey = member DID). */\nexport const MEMBER_COLLECTION = \"com.atproto.memberspace.member\";\n/** The collections the host publishes a space's configuration to. */\nexport const PUBLISHED_COLLECTIONS: readonly string[] = [\n\tPOLICY_COLLECTION,\n\tMEMBER_COLLECTION,\n];\n\nconst isBool = (value: unknown): value is boolean => typeof value === \"boolean\";\n\nfunction isUri(value: unknown): value is string {\n\tif (typeof value !== \"string\") return false;\n\ttry {\n\t\tnew URL(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction optionalBool(input: Record<string, unknown>, key: string): boolean {\n\tconst value = input[key];\n\tif (value === undefined) return false;\n\tif (!isBool(value)) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `Policy ${key} must be a boolean`);\n\t}\n\treturn value;\n}\n\n/** Validate and normalise a policy from a request or an archive. */\nexport function normalizePolicy(input: unknown): SpacePolicy {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"policy must be an object\");\n\t}\n\tconst policy = input as Record<string, unknown>;\n\tswitch (policy.$type) {\n\t\tcase PERSONALSPACE_POLICY:\n\t\t\treturn { $type: PERSONALSPACE_POLICY };\n\t\tcase MEMBERSPACE_POLICY: {\n\t\t\tconst allowedApps = policy.allowedApps;\n\t\t\tif (\n\t\t\t\tallowedApps !== undefined &&\n\t\t\t\t(!Array.isArray(allowedApps) || allowedApps.some((app) => !isUri(app)))\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"allowedApps must be an array of OAuth client ID URIs\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t$type: MEMBERSPACE_POLICY,\n\t\t\t\tpublicRead: optionalBool(policy, \"publicRead\"),\n\t\t\t\tpublicWrite: optionalBool(policy, \"publicWrite\"),\n\t\t\t\t...(allowedApps !== undefined\n\t\t\t\t\t? { allowedApps: [...(allowedApps as string[])] }\n\t\t\t\t\t: {}),\n\t\t\t\tpublishPolicy: optionalBool(policy, \"publishPolicy\"),\n\t\t\t\tpublishMembers: optionalBool(policy, \"publishMembers\"),\n\t\t\t};\n\t\t}\n\t\tcase MANAGEDSPACE_POLICY: {\n\t\t\tconst managingApp = policy.managingApp;\n\t\t\t// A did#serviceId reference: the app's service entry, which a bare\n\t\t\t// DID (an account's #atproto_pds) is not.\n\t\t\tconst [did, fragment, extra] =\n\t\t\t\ttypeof managingApp === \"string\" ? managingApp.split(\"#\") : [];\n\t\t\tif (!did?.startsWith(\"did:\") || !fragment || extra !== undefined) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`managingApp must be a did#serviceId reference, got: ${String(managingApp)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t$type: MANAGEDSPACE_POLICY,\n\t\t\t\tmanagingApp: managingApp as string,\n\t\t\t\tpublishPolicy: optionalBool(policy, \"publishPolicy\"),\n\t\t\t};\n\t\t}\n\t\tdefault:\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"UnsupportedPolicy\",\n\t\t\t\t`Unsupported policy: ${String(policy.$type)}`,\n\t\t\t);\n\t}\n}\n\n/** The member list and its methods belong to the memberspace policy. */\nexport function assertMemberspace(\n\tpolicy: SpacePolicy,\n): asserts policy is Extract<\n\tSpacePolicy,\n\t{ $type: typeof MEMBERSPACE_POLICY }\n> {\n\tif (policy.$type !== MEMBERSPACE_POLICY) {\n\t\tthrow new SpaceError(\n\t\t\t\"PolicyMismatch\",\n\t\t\t\"Space is not governed by the memberspace policy\",\n\t\t);\n\t}\n}\n\n/**\n * Whether any user may read. Only then can a credential be minted without\n * a delegation token saying who the user is.\n */\nexport function isPublicRead(policy: SpacePolicy): boolean {\n\treturn policy.$type === MEMBERSPACE_POLICY && policy.publicRead;\n}\n\nexport function isPolicyPublished(policy: SpacePolicy): boolean {\n\treturn policy.$type !== PERSONALSPACE_POLICY && policy.publishPolicy;\n}\n\nexport function areMembersPublished(policy: SpacePolicy): boolean {\n\treturn policy.$type === MEMBERSPACE_POLICY && policy.publishMembers;\n}\n\n/**\n * Only memberspace restricts apps, against the attested client_id, so an\n * app that presents no attestation is never one of the allowed apps.\n */\nexport function isAppAuthorized(\n\tpolicy: SpacePolicy,\n\tclientId: string | undefined,\n): boolean {\n\tif (policy.$type !== MEMBERSPACE_POLICY || !policy.allowedApps) return true;\n\treturn clientId !== undefined && policy.allowedApps.includes(clientId);\n}\n\n/**\n * A DID as a record key, for published member records. A record key can't\n * contain `%`, so the percent-encoded port of a localhost did:web is left\n * unencoded, as the reference does. Unambiguous because the unencoded form\n * would otherwise be a did:web path, which atproto doesn't support.\n */\nexport function didToRecordKey(did: string): string {\n\treturn did.replace(\"%3A\", \":\");\n}\n\nexport function recordKeyToDid(rkey: string): string {\n\treturn rkey.replace(/^(did:web:[^:]+):(\\d+)$/, \"$1%3A$2\");\n}\n\n/** Records published from a space's configuration are the host's to write. */\nexport function assertNotPublishedCollection(collection: string): void {\n\tif (PUBLISHED_COLLECTIONS.includes(collection)) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`${collection} records are published by the PDS from a space's configuration and cannot be written directly`,\n\t\t);\n\t}\n}\n","/**\n * Record preparation and serialization for the Worker side of the write\n * and read paths. Records are stored as dag-cbor bytes with their CID,\n * computed here โ the same encoding path the reference uses.\n */\n\nimport { encode, decode, cidForLex } from \"@atproto/lex-cbor\";\nimport { enumBlobRefs, getBlobCidString } from \"@atproto/lex-data\";\nimport type { LexValue } from \"@atproto/lex-data\";\nimport { jsonToLex, lexToJson } from \"@atproto/lex-json\";\nimport type { JsonValue } from \"@atproto/lex-json\";\n\nexport interface PreparedRecord {\n\tcid: string;\n\tbytes: Uint8Array;\n\tblobCids: string[];\n\t/** The lex-normalised record, for echoing back in responses. */\n\tjson: unknown;\n}\n\n/**\n * Convert a client-supplied JSON record into its stored form: lex value โ\n * dag-cbor bytes โ CID, with blob references enumerated for the space's\n * blob tracking.\n */\nexport async function prepareRecord(record: unknown): Promise<PreparedRecord> {\n\tconst lex = jsonToLex(record as JsonValue) as LexValue;\n\tconst bytes = encode(lex);\n\tconst cid = await cidForLex(lex);\n\tconst blobCids: string[] = [];\n\tfor (const ref of enumBlobRefs(lex)) {\n\t\tblobCids.push(getBlobCidString(ref));\n\t}\n\treturn { cid: cid.toString(), bytes, blobCids, json: lexToJson(lex) };\n}\n\n/** Decode stored record bytes back into response JSON. */\nexport function recordBytesToJson(bytes: Uint8Array): unknown {\n\treturn lexToJson(decode(bytes));\n}\n","/**\n * SQLite schema for SpaceDurableObject.\n *\n * Mirrors the reference PDS's `002-space` migration table for table, minus\n * the `space` column on every row โ one DO per space makes it redundant.\n *\n * There is no migration path between alpha schema versions: bumping\n * {@link SPACE_SCHEMA_VERSION} puts existing DOs into a refusing state until\n * `pds spaces reset` wipes them. That is the alpha policy, applied honestly.\n */\n\n/**\n * Bump on any breaking change to the tables below.\n *\n * 2: baseline policies replace simplespace config; members carry\n * read/write access; writers carry space revisions; revoked\n * credentials; coalescing notification queue.\n * 3: webhook registrations (endpoint + token) replace registerNotify;\n * writers keep a removal marker; queue rows carry their retry policy\n * and authentication.\n * 4: space URIs move to `at:space/{did}/{type}/{skey}`. Space DOs are\n * named by URI, so spaces stored under the old form are unreachable.\n */\nexport const SPACE_SCHEMA_VERSION = 4;\n\nexport const SPACE_DO_SCHEMA = `\n\t-- One row. schema_version is checked on every open.\n\tCREATE TABLE IF NOT EXISTS meta (\n\t\turi TEXT NOT NULL,\n\t\tauthority TEXT NOT NULL,\n\t\ttype TEXT NOT NULL,\n\t\tskey TEXT NOT NULL,\n\t\tis_authority INTEGER NOT NULL,\n\t\tcreated_at TEXT NOT NULL,\n\t\tdeleted_at TEXT,\n\t\tschema_version INTEGER NOT NULL\n\t);\n\n\t-- Operator's permissioned repo in this space.\n\tCREATE TABLE IF NOT EXISTS record (\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tcid TEXT NOT NULL,\n\t\tbytes BLOB NOT NULL,\n\t\trev TEXT NOT NULL,\n\t\tindexed_at TEXT NOT NULL,\n\t\tPRIMARY KEY (collection, rkey)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_record_rev ON record(rev);\n\n\tCREATE TABLE IF NOT EXISTS record_blob (\n\t\tblob_cid TEXT NOT NULL,\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tPRIMARY KEY (blob_cid, collection, rkey)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_record_blob_record ON record_blob(collection, rkey);\n\n\tCREATE TABLE IF NOT EXISTS repo_state (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tset_hash BLOB NOT NULL,\n\t\trev TEXT NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS oplog (\n\t\trev TEXT NOT NULL,\n\t\tidx INTEGER NOT NULL,\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tcid TEXT,\n\t\tprev TEXT,\n\t\tPRIMARY KEY (rev, idx)\n\t);\n\n\t-- Authority role only. The policy is stored as its normalised lexicon\n\t-- object (com.atproto.{personal,member,managed}space.policy).\n\tCREATE TABLE IF NOT EXISTS config (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tpolicy TEXT NOT NULL\n\t);\n\n\t-- memberspace member list.\n\tCREATE TABLE IF NOT EXISTS member (\n\t\tdid TEXT PRIMARY KEY,\n\t\tcan_read INTEGER NOT NULL,\n\t\tcan_write INTEGER NOT NULL\n\t);\n\n\t-- The writer set, sequenced by space revision. A removed writer keeps\n\t-- its row, marked removed at the revision of its removal, so listWriters\n\t-- can report the removal until it writes again.\n\tCREATE TABLE IF NOT EXISTS writer (\n\t\tdid TEXT PRIMARY KEY,\n\t\trepo_rev TEXT NOT NULL,\n\t\tdata BLOB NOT NULL,\n\t\tspace_rev TEXT NOT NULL,\n\t\tremoved_at INTEGER\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_writer_space_rev ON writer(space_rev);\n\n\t-- Syncer webhook registrations, made through authorizeSpaceSync. Active\n\t-- until the credential of their latest authorization expires\n\t-- (expires_at, ms); expiry_notified marks a lapse already announced.\n\tCREATE TABLE IF NOT EXISTS notify_registration (\n\t\tendpoint TEXT NOT NULL,\n\t\ttoken TEXT NOT NULL,\n\t\texpires_at INTEGER NOT NULL,\n\t\texpiry_notified INTEGER NOT NULL DEFAULT 0,\n\t\tPRIMARY KEY (endpoint, token)\n\t);\n\n\t-- Outbound notifications, both roles. A row with a coalesce_key is\n\t-- replaced by a newer one with the same key; deadline (ms) is when\n\t-- retrying stops. policy picks the retry schedule ('fanout' | 'repo' |\n\t-- 'syncer'); auth is 'service' (a service JWT from the operator) or\n\t-- 'none' (a syncer webhook, authenticated by the token in its body).\n\tCREATE TABLE IF NOT EXISTS notify_queue (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tservice TEXT NOT NULL,\n\t\tbody TEXT NOT NULL,\n\t\tattempts INTEGER NOT NULL DEFAULT 0,\n\t\tnext_at INTEGER NOT NULL,\n\t\tdeadline INTEGER,\n\t\tcoalesce_key TEXT UNIQUE,\n\t\tpolicy TEXT NOT NULL DEFAULT 'fanout',\n\t\tauth TEXT NOT NULL DEFAULT 'service'\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_notify_queue_next ON notify_queue(next_at);\n\n\t-- Credentials for this space revoked by its authority (repo-host role).\n\tCREATE TABLE IF NOT EXISTS revoked_credential (\n\t\tjti TEXT PRIMARY KEY,\n\t\texpires_at INTEGER NOT NULL\n\t);\n\n\t-- Replay protection, both roles.\n\tCREATE TABLE IF NOT EXISTS replay (\n\t\tkind TEXT NOT NULL,\n\t\tkey TEXT NOT NULL,\n\t\texpires_at INTEGER NOT NULL,\n\t\tPRIMARY KEY (kind, key)\n\t);\n`;\n\n/** Retain oplog entries for at most this many days. */\nexport const OPLOG_RETENTION_DAYS = 30;\n/** Retain at most this many oplog entries. */\nexport const OPLOG_RETENTION_OPS = 10_000;\n/**\n * Give up delivering a notification without its own deadline after this\n * many attempts: syncer fan-out is reasonable-effort, and a syncer that\n * misses one recovers through listRepos.\n */\nexport const NOTIFY_MAX_ATTEMPTS = 5;\n/** A repo host retries its write notification to the authority this long. */\nexport const NOTIFY_WRITE_RETRY_MS = 24 * 60 * 60 * 1000;\n/**\n * A syncer's deletion or expiry notice is retried after each of these\n * delays in turn, repeating the last, for at least\n * {@link SYNCER_NOTICE_RETRY_WINDOW_MS}.\n */\nexport const SYNCER_NOTICE_RETRY_DELAYS_MS = [\n\t60_000,\n\t10 * 60_000,\n\t60 * 60_000,\n\t6 * 60 * 60_000,\n\t12 * 60 * 60_000,\n];\nexport const SYNCER_NOTICE_RETRY_WINDOW_MS = 72 * 60 * 60 * 1000;\n/** The largest notify token a syncer may register. */\nexport const MAX_NOTIFY_TOKEN_LENGTH = 512;\n/** Cap on the backoff between notification retries. */\nexport const NOTIFY_BACKOFF_MAX_MS = 60 * 60 * 1000;\n/** notifyWrite refuses repo revisions this far ahead of the clock. */\nexport const MAX_REV_CLOCK_SKEW_MS = 5 * 60 * 1000;\n/** The largest record a space repo accepts, as its DRISL encoding. */\nexport const MAX_SPACE_RECORD_BYTES = 1024 * 1024;\n/** Base delay for notification retry backoff, in milliseconds. */\nexport const NOTIFY_BACKOFF_BASE_MS = 30_000;\n\nexport const INDEX_DO_SCHEMA = `\n\tCREATE TABLE IF NOT EXISTS space (\n\t\turi TEXT PRIMARY KEY,\n\t\tauthority TEXT NOT NULL,\n\t\ttype TEXT NOT NULL,\n\t\tskey TEXT NOT NULL,\n\t\tis_authority INTEGER NOT NULL,\n\t\tstate TEXT NOT NULL, -- 'pending' | 'active' | 'deleted'\n\t\tcreated_at TEXT NOT NULL,\n\t\tupdated_at TEXT NOT NULL,\n\t\tschema_version INTEGER NOT NULL\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_space_state ON space(state);\n\n\t-- Blobs referenced by an imported space repo that had not been uploaded\n\t-- yet. uploadBlob claims them and promotes the staged copy into each\n\t-- space's blob prefix.\n\tCREATE TABLE IF NOT EXISTS pending_blob (\n\t\tcid TEXT NOT NULL,\n\t\turi TEXT NOT NULL,\n\t\tcreated_at INTEGER NOT NULL,\n\t\tPRIMARY KEY (cid, uri)\n\t);\n`;\n\n/** Forget pending imported-space blobs that were never uploaded. */\nexport const PENDING_BLOB_TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Remove `pending` index entries that never activated after this long. */\nexport const PENDING_ENTRY_TTL_MS = 24 * 60 * 60 * 1000;\n","/**\n * Commits and MACs.\n *\n * A space repo commit carries no signature. A syncer authenticates what a\n * repo host serves with a MAC instead: an HTTP message signature (RFC 9421)\n * using `hmac-sha256`, keyed by a per-request secret both sides derive with\n * HPKE secret export against the account's `#atproto_kem` key. The syncer\n * asks with `Accept-Signature`, naming its ephemeral key and a profile tag;\n * the host answers with a header describing the commit or record\n * (`Atproto-Space-Commit` / `Atproto-Space-Record`) and a MAC covering it.\n * A leaked response proves nothing to a third party. The KEM key is the only\n * secret here, and it lives with the Worker.\n */\n\nimport {\n\tCOMMIT_MAC_PROFILE,\n\tMAC_COVERED_HEADER,\n\tRECORD_MAC_PROFILE,\n\tRepoCommit,\n\tSpaceKemError,\n\tSpaceMacError,\n\tcreateCommitMacHeaders,\n\tcreateRecordMacHeaders,\n\tdecapsulate,\n\tparseMacRequest,\n} from \"@atproto/space\";\nimport type { CreateMacParams, MacProfile } from \"@atproto/space\";\nimport { P256Keypair } from \"@atproto/crypto\";\nimport { parseCid, toBase64 } from \"@atproto/lex-data\";\nimport { SpaceError } from \"./errors.js\";\nimport type { RepoState } from \"./types.js\";\n\nexport { COMMIT_MAC_PROFILE, RECORD_MAC_PROFILE };\nexport type { MacProfile };\n\n/** The MAC profiles, as plain strings for the public API. */\nexport type SpaceMacProfile = \"atproto-space-commit\" | \"atproto-space-record\";\n\n/** The request header a syncer asks for a MAC with. */\nexport const MAC_REQUEST_HEADER = \"accept-signature\";\n\n/** The response headers a browser syncer must read to check a MAC. */\nexport function macExposedHeaders(profile: SpaceMacProfile): string[] {\n\treturn [\n\t\tMAC_COVERED_HEADER[profile as MacProfile],\n\t\t\"signature-input\",\n\t\t\"signature\",\n\t];\n}\n\n/** A space repo commit (`com.atproto.space.defs#commit`). */\nexport interface SpaceCommit {\n\tver: number;\n\trepo: string;\n\tspace: string;\n\trev: string;\n\t/** sha256 digest of the LtHash state. */\n\tdata: Uint8Array;\n}\n\n/** The commit over a repo's persisted state. */\nexport function buildCommit(params: {\n\tspaceUri: string;\n\t/** The repo author (the operator DID for every repo Cirrus serves). */\n\trepo: string;\n\tstate: RepoState;\n}): SpaceCommit {\n\treturn RepoCommit.fromState(params.state.setHash).toCommit({\n\t\tspace: params.spaceUri as never,\n\t\trepo: params.repo as never,\n\t\trev: params.state.rev as never,\n\t});\n}\n\n/**\n * Lexicon JSON form of a commit (`com.atproto.space.defs#commit`): bytes\n * fields encode as `{\"$bytes\": \"<base64>\"}`.\n */\nexport function commitToJson(commit: SpaceCommit): Record<string, unknown> {\n\treturn {\n\t\tver: commit.ver,\n\t\trepo: commit.repo,\n\t\tspace: commit.space,\n\t\trev: commit.rev,\n\t\tdata: bytesToJson(commit.data),\n\t};\n}\n\n/** Lexicon JSON form of a bare bytes value. */\nexport function bytesToJson(bytes: Uint8Array): { $bytes: string } {\n\treturn { $bytes: toBase64(bytes) };\n}\n\n/** Import the account's `#atproto_kem` keypair from its hex private key. */\nexport async function importKemKeypair(\n\tprivateKeyHex: string,\n): Promise<P256Keypair> {\n\treturn P256Keypair.import(privateKeyHex);\n}\n\n/** Generate a fresh `#atproto_kem` keypair. */\nexport async function generateKemKey(): Promise<{\n\tprivateKeyHex: string;\n\t/** The public key as a did:key. */\n\tdidKey: string;\n\t/** The public key multibase, for a DID document verification method. */\n\tpublicKeyMultibase: string;\n}> {\n\tconst keypair = await P256Keypair.create({ exportable: true });\n\tconst exported = await keypair.export();\n\tconst didKey = keypair.did();\n\treturn {\n\t\tprivateKeyHex: Array.from(exported, (b) =>\n\t\t\tb.toString(16).padStart(2, \"0\"),\n\t\t).join(\"\"),\n\t\tdidKey,\n\t\tpublicKeyMultibase: didKey.slice(\"did:key:\".length),\n\t};\n}\n\n/** The public half of a KEM private key, as a did:key. */\nexport async function kemDidKey(privateKeyHex: string): Promise<string> {\n\treturn (await importKemKeypair(privateKeyHex)).did();\n}\n\nexport interface MacRequestInput {\n\t/** The `Accept-Signature` request header, if any. */\n\tacceptSignature: string | undefined;\n\t/** Whether the request was authorised by a space credential. */\n\tcredential: boolean;\n\tprofile: MacProfile;\n\tgetKemKeypair: () => Promise<P256Keypair | null>;\n}\n\n/** What a MAC is computed with, once requested and decapsulated. */\nexport type MacParams = CreateMacParams;\n\n/**\n * The MAC owed by a read that returns a commit or record. A space\n * credential must ask for one with the profile's tag; an account reading its\n * own data gets one only if it asks. Requests with other tags are ignored.\n * Returns undefined when no MAC is owed.\n */\nexport async function macRequest(\n\treq: MacRequestInput,\n): Promise<MacParams | undefined> {\n\tlet request;\n\ttry {\n\t\trequest = parseMacRequest(req.acceptSignature, req.profile);\n\t} catch (err) {\n\t\tthrow invalidMac(err);\n\t}\n\tif (!request) {\n\t\tif (!req.credential) return undefined;\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidSpaceMac\",\n\t\t\t`A MAC must be requested with tag \"${req.profile}\"`,\n\t\t);\n\t}\n\tconst keypair = await req.getKemKeypair();\n\tif (!keypair) {\n\t\tthrow new SpaceError(\n\t\t\t\"KemKeyUnavailable\",\n\t\t\t\"This host has no #atproto_kem key configured, so it cannot authenticate space data to syncers\",\n\t\t);\n\t}\n\ttry {\n\t\treturn { ...request, sharedSecret: decapsulate(keypair, request.keyShare) };\n\t} catch (err) {\n\t\tthrow invalidMac(err);\n\t}\n}\n\nfunction invalidMac(err: unknown): SpaceError {\n\tif (err instanceof SpaceMacError || err instanceof SpaceKemError) {\n\t\treturn new SpaceError(\"InvalidSpaceMac\", err.message);\n\t}\n\treturn new SpaceError(\"InvalidSpaceMac\", \"Invalid Accept-Signature header\");\n}\n\n/** The MAC response headers for a commit, when one is owed. */\nexport function commitMacHeaders(\n\tmac: MacParams | undefined,\n\tcommit: SpaceCommit,\n): Record<string, string> {\n\tif (!mac) return {};\n\treturn createCommitMacHeaders(\n\t\tcommit as Parameters<typeof createCommitMacHeaders>[0],\n\t\tmac,\n\t).headers;\n}\n\n/** The MAC response headers for a record, when one is owed. */\nexport function recordMacHeaders(\n\tmac: MacParams | undefined,\n\turi: string,\n\tcid: string,\n): Record<string, string> {\n\tif (!mac) return {};\n\treturn createRecordMacHeaders(uri as never, parseCid(cid), mac).headers;\n}\n","/**\n * Revision (TID) helpers for the space repo.\n */\n\nimport { now as tidNow } from \"@atcute/tid\";\n\nconst S32_CHAR = \"234567abcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Next revision: a fresh TID guaranteed strictly greater than `prev`.\n * `@atcute/tid`'s clock is monotonic within an isolate, but the previous\n * rev may come from a different isolate's clock (e.g. after a DO restart),\n * so bump lexicographically when needed.\n */\nexport function nextRev(prev: string | null | undefined): string {\n\tconst candidate = tidNow();\n\tif (!prev || candidate > prev) return candidate;\n\t// Increment the previous TID by one in s32 space.\n\tconst chars = prev.split(\"\");\n\tfor (let i = chars.length - 1; i >= 0; i--) {\n\t\tconst idx = S32_CHAR.indexOf(chars[i]!);\n\t\tif (idx < S32_CHAR.length - 1) {\n\t\t\tchars[i] = S32_CHAR[idx + 1]!;\n\t\t\treturn chars.join(\"\");\n\t\t}\n\t\tchars[i] = S32_CHAR[0]!;\n\t}\n\t// prev was the maximal TID; not reachable with real clocks.\n\treturn candidate;\n}\n\n/**\n * The smallest TID whose timestamp is `ms` milliseconds in the past, with a\n * zero clockid. Used as a deletion cutoff for oplog compaction.\n */\nexport function tidCutoff(msAgo: number): string {\n\tconst micros = BigInt(Math.max(0, Date.now() - msAgo)) * 1000n;\n\t// TID layout: 53 bits of microseconds followed by 10 bits of clockid,\n\t// encoded as 13 sortable-base32 characters.\n\tlet value = (micros << 10n) & ((1n << 63n) - 1n);\n\tlet out = \"\";\n\tfor (let i = 12; i >= 0; i--) {\n\t\tout = S32_CHAR[Number(value & 31n)] + out;\n\t\tvalue >>= 5n;\n\t}\n\treturn out;\n}\n\n/** The timestamp a TID encodes, in milliseconds since the epoch. */\nexport function tidTimestampMs(tid: string): number {\n\tlet value = 0n;\n\tfor (const char of tid) {\n\t\tconst idx = S32_CHAR.indexOf(char);\n\t\tif (idx === -1) throw new Error(`Invalid TID: ${tid}`);\n\t\tvalue = (value << 5n) | BigInt(idx);\n\t}\n\treturn Number(value >> 10n) / 1000;\n}\n","/**\n * Minimal atproto service-auth JWT creation, used for outbound\n * `com.atproto.space.notifyWrite` / `notifySpaceDeleted` calls. Matches the\n * shape `verifyServiceJwt` implementations expect: `{iss, aud, lxm?, jti,\n * iat, exp}` signed with the account signing key (alg from the keypair).\n */\n\nimport type { SpaceSigningKeypair } from \"./types.js\";\n\nconst encoder = new TextEncoder();\n\nfunction base64url(bytes: Uint8Array): string {\n\tlet bin = \"\";\n\tfor (const b of bytes) bin += String.fromCharCode(b);\n\treturn btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nexport interface ServiceJwtParams {\n\tiss: string;\n\taud: string;\n\tlxm?: string;\n\t/** Lifetime in seconds (default 60). */\n\texpiresInSec?: number;\n}\n\nexport async function createServiceJwt(\n\tparams: ServiceJwtParams,\n\tkeypair: SpaceSigningKeypair,\n): Promise<string> {\n\tconst iat = Math.floor(Date.now() / 1000);\n\tconst header = { typ: \"JWT\", alg: keypair.jwtAlg };\n\tconst payload: Record<string, unknown> = {\n\t\tiat,\n\t\tiss: params.iss,\n\t\taud: params.aud,\n\t\texp: iat + (params.expiresInSec ?? 60),\n\t\tjti: crypto.randomUUID(),\n\t};\n\tif (params.lxm) payload.lxm = params.lxm;\n\n\tconst signingInput = `${base64url(encoder.encode(JSON.stringify(header)))}.${base64url(\n\t\tencoder.encode(JSON.stringify(payload)),\n\t)}`;\n\tconst sig = await keypair.sign(encoder.encode(signingInput));\n\treturn `${signingInput}.${base64url(sig)}`;\n}\n","/**\n * SpaceDurableObject โ one instance per space, addressed by\n * `idFromName(spaceUri)`.\n *\n * Holds everything Cirrus knows about that space: the operator's\n * permissioned repo (records, oplog, LtHash state, blob references) and,\n * when the operator is the authority, the space's policy, member list,\n * writer set (sequenced by space revision) and notification registrations.\n * Both roles share the outbound notification queue, and the replay and\n * revocation tables for tokens presented against the space.\n *\n * Constraints inherited from the Cirrus architecture:\n * - No R2 I/O in here, ever. Blobs are the Worker's job.\n * - No key material in here except through\n * {@link SpaceHostConfig.getKeypair}, used only for outbound notification\n * service JWTs from the alarm. Commits are unsigned and MACs are the\n * Worker's, so the KEM key never enters this class.\n * - The host supplies its identity via {@link getHostConfig}; this class\n * must not read `env.DID`. If it ever contains a branch on which host is\n * running it, the boundary has failed.\n */\n\nimport { DurableObject } from \"cloudflare:workers\";\nimport { RepoCommit } from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport {\n\tMEMBER_COLLECTION,\n\tPOLICY_COLLECTION,\n\tPOLICY_RKEY,\n\tPUBLISHED_COLLECTIONS,\n\tareMembersPublished,\n\tassertMemberspace,\n\tdidToRecordKey,\n\tisPolicyPublished,\n} from \"./policy.js\";\nimport { prepareRecord } from \"./records.js\";\nimport {\n\tNOTIFY_BACKOFF_BASE_MS,\n\tNOTIFY_BACKOFF_MAX_MS,\n\tNOTIFY_MAX_ATTEMPTS,\n\tOPLOG_RETENTION_DAYS,\n\tOPLOG_RETENTION_OPS,\n\tSPACE_DO_SCHEMA,\n\tSPACE_SCHEMA_VERSION,\n\tSYNCER_NOTICE_RETRY_DELAYS_MS,\n\tSYNCER_NOTICE_RETRY_WINDOW_MS,\n} from \"./schema.js\";\nimport { bytesToJson } from \"./mac.js\";\nimport { nextRev, tidCutoff } from \"./tid.js\";\nimport { createServiceJwt } from \"./service-jwt.js\";\nimport type {\n\tApplyWritesResult,\n\tImportedRecord,\n\tNotifyItem,\n\tNotifyRegistration,\n\tOplogEntry,\n\tPreparedSpaceWrite,\n\tRepoCommitResult,\n\tRepoState,\n\tSpaceHostConfig,\n\tSpaceMember,\n\tSpaceMeta,\n\tSpacePolicy,\n\tSpaceRecordRow,\n\tSpaceSequence,\n\tSpaceWriter,\n} from \"./types.js\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** Interval between maintenance passes (compaction, replay cleanup). */\nconst MAINTENANCE_INTERVAL_MS = DAY_MS;\n/** How many queued notifications to attempt per alarm invocation. */\nconst NOTIFY_BATCH = 20;\n\ninterface QueueRow {\n\tid: number;\n\tservice: string;\n\tbody: string;\n\tattempts: number;\n\tnext_at: number;\n\tdeadline: number | null;\n\tpolicy: \"fanout\" | \"repo\" | \"syncer\";\n\tauth: \"service\" | \"none\";\n}\n\nconst NOTIFY_SPACE_UPDATE_LXM = \"com.atproto.space.notifySpaceUpdate\";\nconst REPO_WRITE = \"com.atproto.space.defs#repoWrite\";\nconst REPO_REMOVED = \"com.atproto.space.defs#repoRemoved\";\nconst SPACE_DELETED = \"com.atproto.space.notifySpaceUpdate#spaceDeleted\";\nconst REGISTRATION_EXPIRED =\n\t\"com.atproto.space.notifySpaceUpdate#registrationExpired\";\n\n/** 50-100% of a delay, so retries from many spaces don't align. */\nfunction jitter(delay: number): number {\n\treturn Math.floor(delay * (0.5 + Math.random() / 2));\n}\n\n/** HTTP statuses worth retrying; anything else is a permanent refusal. */\nexport function isRetryableStatus(status: number): boolean {\n\treturn status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\nexport abstract class SpaceDurableObject<\n\tEnv = unknown,\n> extends DurableObject<Env> {\n\tprivate sql: SqlStorage;\n\tprivate initialized = false;\n\tprivate outdated = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.sql = ctx.storage.sql;\n\t}\n\n\t/**\n\t * Host identity and signing configuration. Implemented by the host\n\t * Worker's subclass; see {@link SpaceHostConfig}.\n\t */\n\tprotected abstract getHostConfig():\n\t\t| SpaceHostConfig\n\t\t| Promise<SpaceHostConfig>;\n\n\t// ------------------------------------------------------------------\n\t// Initialisation and schema versioning\n\t// ------------------------------------------------------------------\n\n\tprivate async ensureInitialized(): Promise<void> {\n\t\tif (this.initialized) return;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tif (this.initialized) return;\n\t\t\tconst hasMeta =\n\t\t\t\tthis.sql\n\t\t\t\t\t.exec(\n\t\t\t\t\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'\",\n\t\t\t\t\t)\n\t\t\t\t\t.toArray().length > 0;\n\t\t\tif (hasMeta) {\n\t\t\t\tconst row = this.sql\n\t\t\t\t\t.exec(\"SELECT schema_version FROM meta LIMIT 1\")\n\t\t\t\t\t.toArray()[0];\n\t\t\t\tif (row && (row.schema_version as number) !== SPACE_SCHEMA_VERSION) {\n\t\t\t\t\t// Alpha policy: no migrations between schema versions. The DO\n\t\t\t\t\t// refuses every RPC until `pds spaces reset` wipes it.\n\t\t\t\t\tthis.outdated = true;\n\t\t\t\t\tthis.initialized = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.sql.exec(SPACE_DO_SCHEMA);\n\t\t\tthis.initialized = true;\n\t\t});\n\t}\n\n\t/**\n\t * Gate every RPC: initialise storage and refuse when the stored schema\n\t * belongs to a different alpha build.\n\t */\n\tprivate async ensureOpen(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpacesSchemaOutdated\",\n\t\t\t\t\"Space data was written by an incompatible alpha build. Run `pds spaces reset` to wipe space data (the public repo is unaffected).\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate readMeta(): SpaceMeta | null {\n\t\tconst row = this.sql.exec(\"SELECT * FROM meta LIMIT 1\").toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\turi: row.uri as string,\n\t\t\tauthority: row.authority as string,\n\t\t\ttype: row.type as string,\n\t\t\tskey: row.skey as string,\n\t\t\tisAuthority: (row.is_authority as number) === 1,\n\t\t\tcreatedAt: row.created_at as string,\n\t\t\tdeletedAt: (row.deleted_at as string | null) ?? null,\n\t\t};\n\t}\n\n\t/** Meta for an existing, non-deleted space, or throw. */\n\tprivate requireLiveMeta(): SpaceMeta {\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space is not initialised\");\n\t\t}\n\t\tif (meta.deletedAt) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space has been deleted\");\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** The policy of a live space this host governs, or SpaceNotFound. */\n\tprivate requirePolicy(): { meta: SpaceMeta; policy: SpacePolicy } {\n\t\tconst meta = this.requireLiveMeta();\n\t\tconst policy = this.readPolicy();\n\t\tif (!policy) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space not found\");\n\t\t}\n\t\treturn { meta, policy };\n\t}\n\n\tasync rpcGetMeta(): Promise<SpaceMeta | null> {\n\t\tawait this.ensureOpen();\n\t\treturn this.readMeta();\n\t}\n\n\t/**\n\t * Initialise this DO as the operator's repo in a space (either role).\n\t * For the authority role a policy creates the space: refused when a live\n\t * space already has one. A deleted space may be created again; its\n\t * tables were wiped at deletion, so reviving is a fresh start. Returns\n\t * the commit when publishing the policy wrote to the repo.\n\t */\n\tasync rpcInit(params: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tisAuthority: boolean;\n\t\tpolicy?: SpacePolicy;\n\t}): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst existing = this.readMeta();\n\t\tif (existing && existing.uri !== params.uri) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Space DO already holds ${existing.uri}`,\n\t\t\t);\n\t\t}\n\t\tif (existing && !existing.deletedAt && params.policy && this.readPolicy()) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpaceAlreadyExists\",\n\t\t\t\t`Space already exists: ${params.uri}`,\n\t\t\t);\n\t\t}\n\t\tconst publishWrites = params.policy\n\t\t\t? await this.preparePolicyRecordWrites(params.policy)\n\t\t\t: [];\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tif (!existing) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)\n\t\t\t\t\t VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`,\n\t\t\t\t\tparams.uri,\n\t\t\t\t\tparams.authority,\n\t\t\t\t\tparams.type,\n\t\t\t\t\tparams.skey,\n\t\t\t\t\tparams.isAuthority ? 1 : 0,\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tSPACE_SCHEMA_VERSION,\n\t\t\t\t);\n\t\t\t} else if (existing.deletedAt) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"UPDATE meta SET deleted_at = NULL, created_at = ?, is_authority = ?\",\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tparams.isAuthority ? 1 : 0,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!params.policy) return null;\n\t\t\tthis.writePolicy(params.policy);\n\t\t\treturn this.applyWritesSync(publishWrites);\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Permissioned repo: writes\n\t// ------------------------------------------------------------------\n\n\tasync rpcApplyWrites(\n\t\twrites: PreparedSpaceWrite[],\n\t): Promise<ApplyWritesResult> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(\n\t\t\t() => this.applyWritesSync(writes)!,\n\t\t);\n\t}\n\n\t/**\n\t * Apply a batch as one commit sharing a single rev. Must run in a\n\t * transaction. Returns null for an empty batch. Each write lands before\n\t * the next is read, so a batch can create and then update a record, and\n\t * a repeated create is refused rather than counted twice.\n\t */\n\tprivate applyWritesSync(\n\t\twrites: PreparedSpaceWrite[],\n\t): ApplyWritesResult | null {\n\t\tif (writes.length === 0) return null;\n\t\tconst state = this.readRepoState();\n\t\tconst commit = RepoCommit.fromState(state?.setHash ?? null);\n\t\tconst rev = nextRev(state?.rev ?? null);\n\t\tconst indexedAt = new Date().toISOString();\n\t\tconst results: ApplyWritesResult[\"results\"] = [];\n\t\tlet idx = 0;\n\n\t\tfor (const write of writes) {\n\t\t\tconst prevRow = this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT cid FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t)\n\t\t\t\t.toArray()[0];\n\t\t\tconst prev = prevRow ? (prevRow.cid as string) : null;\n\n\t\t\tif (write.action === \"create\" && prev) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordAlreadyExists\",\n\t\t\t\t\t`Record already exists: ${write.collection}/${write.rkey}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (write.action !== \"create\" && !prev) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordNotFound\",\n\t\t\t\t\t`Record not found: ${write.collection}/${write.rkey}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (write.action === \"delete\") {\n\t\t\t\tthis.deleteRecordRow(write.collection, write.rkey);\n\t\t\t\tcommit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);\n\t\t\t\tthis.appendOplog(rev, idx++, write.collection, write.rkey, null, prev);\n\t\t\t\tresults.push({\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\tcid: null,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT OR REPLACE INTO record (collection, rkey, cid, bytes, rev, indexed_at)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\t\twrite.collection,\n\t\t\t\twrite.rkey,\n\t\t\t\twrite.cid,\n\t\t\t\twrite.bytes,\n\t\t\t\trev,\n\t\t\t\tindexedAt,\n\t\t\t);\n\t\t\tthis.replaceRecordBlobs(write.collection, write.rkey, write.blobCids);\n\t\t\tif (prev) {\n\t\t\t\tcommit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);\n\t\t\t}\n\t\t\tcommit.setHash.add(`${write.collection}/${write.rkey}/${write.cid}`);\n\t\t\tthis.appendOplog(\n\t\t\t\trev,\n\t\t\t\tidx++,\n\t\t\t\twrite.collection,\n\t\t\t\twrite.rkey,\n\t\t\t\twrite.cid,\n\t\t\t\tprev,\n\t\t\t);\n\t\t\tresults.push({\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t\trkey: write.rkey,\n\t\t\t\tcid: write.cid,\n\t\t\t});\n\t\t}\n\n\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\treturn { rev, data: commit.setHash.digest(), results };\n\t}\n\n\tprivate deleteRecordRow(collection: string, rkey: string): void {\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record_blob WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t}\n\n\tprivate replaceRecordBlobs(\n\t\tcollection: string,\n\t\trkey: string,\n\t\tblobCids: string[],\n\t): void {\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record_blob WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t\tfor (const blobCid of blobCids) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"INSERT OR IGNORE INTO record_blob (blob_cid, collection, rkey) VALUES (?, ?, ?)\",\n\t\t\t\tblobCid,\n\t\t\t\tcollection,\n\t\t\t\trkey,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate writeRepoState(setHash: Uint8Array, rev: string): void {\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO repo_state (id, set_hash, rev) VALUES (1, ?, ?)\n\t\t\t ON CONFLICT (id) DO UPDATE SET set_hash = excluded.set_hash, rev = excluded.rev`,\n\t\t\tsetHash,\n\t\t\trev,\n\t\t);\n\t}\n\n\tprivate appendOplog(\n\t\trev: string,\n\t\tidx: number,\n\t\tcollection: string,\n\t\trkey: string,\n\t\tcid: string | null,\n\t\tprev: string | null,\n\t): void {\n\t\tthis.sql.exec(\n\t\t\t\"INSERT INTO oplog (rev, idx, collection, rkey, cid, prev) VALUES (?, ?, ?, ?, ?, ?)\",\n\t\t\trev,\n\t\t\tidx,\n\t\t\tcollection,\n\t\t\trkey,\n\t\t\tcid,\n\t\t\tprev,\n\t\t);\n\t}\n\n\t/** The collections the repo holds records in, for clearRecords' grants. */\n\tasync rpcListCollections(): Promise<string[]> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.sql\n\t\t\t.exec(\"SELECT DISTINCT collection FROM record ORDER BY collection\")\n\t\t\t.toArray()\n\t\t\t.map((row) => row.collection as string);\n\t}\n\n\t/**\n\t * Delete every record outside `keep` and clear the oplog, leaving the\n\t * repo at a new rev with the digest of what remains. Returns null when\n\t * there was nothing to delete.\n\t */\n\tasync rpcClearRecords(keep: string[]): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst state = this.readRepoState();\n\t\t\tif (!state) return null;\n\t\t\tconst placeholders = keep.map(() => \"?\").join(\", \");\n\t\t\tconst notKept =\n\t\t\t\tkeep.length > 0 ? `collection NOT IN (${placeholders})` : \"1=1\";\n\t\t\tconst doomed = this.sql\n\t\t\t\t.exec(`SELECT COUNT(*) AS n FROM record WHERE ${notKept}`, ...keep)\n\t\t\t\t.toArray()[0]?.n as number;\n\t\t\tif (!doomed) return null;\n\t\t\tthis.sql.exec(`DELETE FROM record_blob WHERE ${notKept}`, ...keep);\n\t\t\tthis.sql.exec(`DELETE FROM record WHERE ${notKept}`, ...keep);\n\t\t\tthis.sql.exec(\"DELETE FROM oplog\");\n\t\t\tconst commit = new RepoCommit();\n\t\t\tfor (const row of this.sql\n\t\t\t\t.exec(\"SELECT collection, rkey, cid FROM record\")\n\t\t\t\t.toArray()) {\n\t\t\t\tcommit.setHash.add(`${row.collection}/${row.rkey}/${row.cid}`);\n\t\t\t}\n\t\t\tconst rev = nextRev(state.rev);\n\t\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\t\treturn { rev, data: commit.setHash.digest() };\n\t\t});\n\t}\n\n\t/**\n\t * Replace the repo with records imported from its previous host. Takes a\n\t * new rev here and none of its history, so the oplog starts empty.\n\t *\n\t * Policy and member records are only ever written by the host, so the\n\t * archive's are left out. In the authority's own repo they are published\n\t * again, in a commit of their own, from the configuration importSpaceMeta\n\t * set, as the reference does.\n\t */\n\tasync rpcImportRepo(records: ImportedRecord[]): Promise<RepoCommitResult> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.requireLiveMeta();\n\t\tconst imported = records.filter(\n\t\t\t(record) => !PUBLISHED_COLLECTIONS.includes(record.collection),\n\t\t);\n\t\tconst policy = meta.isAuthority ? this.readPolicy() : null;\n\t\tconst publishWrites = policy\n\t\t\t? await this.preparePublishedRecordCreates(policy)\n\t\t\t: [];\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst state = this.readRepoState();\n\t\t\tthis.sql.exec(\"DELETE FROM record_blob\");\n\t\t\tthis.sql.exec(\"DELETE FROM record\");\n\t\t\tthis.sql.exec(\"DELETE FROM oplog\");\n\t\t\tconst rev = nextRev(state?.rev ?? null);\n\t\t\tconst indexedAt = new Date().toISOString();\n\t\t\tconst commit = new RepoCommit();\n\t\t\tfor (const record of imported) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO record (collection, rkey, cid, bytes, rev, indexed_at)\n\t\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\t\t\trecord.collection,\n\t\t\t\t\trecord.rkey,\n\t\t\t\t\trecord.cid,\n\t\t\t\t\trecord.bytes,\n\t\t\t\t\trev,\n\t\t\t\t\tindexedAt,\n\t\t\t\t);\n\t\t\t\tthis.replaceRecordBlobs(\n\t\t\t\t\trecord.collection,\n\t\t\t\t\trecord.rkey,\n\t\t\t\t\trecord.blobCids,\n\t\t\t\t);\n\t\t\t\tcommit.setHash.add(`${record.collection}/${record.rkey}/${record.cid}`);\n\t\t\t}\n\t\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\t\tconst published = this.applyWritesSync(publishWrites);\n\t\t\treturn published\n\t\t\t\t? { rev: published.rev, data: published.data }\n\t\t\t\t: { rev, data: commit.setHash.digest() };\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Permissioned repo: reads\n\t// ------------------------------------------------------------------\n\n\tprivate readRepoState(): RepoState | null {\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT set_hash, rev FROM repo_state WHERE id = 1\")\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tsetHash: new Uint8Array(row.set_hash as ArrayBuffer),\n\t\t\trev: row.rev as string,\n\t\t};\n\t}\n\n\tasync rpcGetRecord(\n\t\tcollection: string,\n\t\trkey: string,\n\t): Promise<{ cid: string; bytes: Uint8Array } | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT cid, bytes FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\tcollection,\n\t\t\t\trkey,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tcid: row.cid as string,\n\t\t\tbytes: new Uint8Array(row.bytes as ArrayBuffer),\n\t\t};\n\t}\n\n\t/**\n\t * List records ordered by (collection, rkey) โ equivalent to record-URI\n\t * order since every record shares the space and repo prefix. Descending\n\t * by default, matching the reference; `reverse` flips to ascending.\n\t */\n\tasync rpcListRecords(params: {\n\t\tcollection?: string;\n\t\tlimit: number;\n\t\tafter?: { collection: string; rkey: string };\n\t\treverse?: boolean;\n\t\texcludeValues?: boolean;\n\t}): Promise<{ records: SpaceRecordRow[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst asc = params.reverse === true;\n\t\tconst op = asc ? \">\" : \"<\";\n\t\tconst order = asc ? \"ASC\" : \"DESC\";\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.collection) {\n\t\t\twhere += \" AND collection = ?\";\n\t\t\targs.push(params.collection);\n\t\t}\n\t\tif (params.after) {\n\t\t\twhere += ` AND (collection ${op} ? OR (collection = ? AND rkey ${op} ?))`;\n\t\t\targs.push(\n\t\t\t\tparams.after.collection,\n\t\t\t\tparams.after.collection,\n\t\t\t\tparams.after.rkey,\n\t\t\t);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT collection, rkey, cid${params.excludeValues ? \"\" : \", bytes\"} FROM record\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY collection ${order}, rkey ${order}\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\trecords: page.map((row) => ({\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tcid: row.cid as string,\n\t\t\t\t...(params.excludeValues\n\t\t\t\t\t? {}\n\t\t\t\t\t: { bytes: new Uint8Array(row.bytes as ArrayBuffer) }),\n\t\t\t})),\n\t\t\thasMore,\n\t\t};\n\t}\n\n\t/**\n\t * Records in strict byte order of their `{collection}/{rkey}` path, as a\n\t * repo archive requires โ not (collection, rkey) order, which differs\n\t * when one collection NSID prefixes another. `state` is the repo state\n\t * the page was read at: the page and the state are one snapshot\n\t * (synchronous reads, single-threaded DO), so a streaming export can\n\t * fence against concurrent writes.\n\t */\n\tasync rpcListRecordsByPath(params: {\n\t\tafterPath?: string;\n\t\tlimit: number;\n\t}): Promise<{\n\t\trecords: Array<{ collection: string; rkey: string; bytes: Uint8Array }>;\n\t\thasMore: boolean;\n\t\tstate: RepoState | null;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst state = this.readRepoState();\n\t\t// SQLite's default BINARY collation compares UTF-8 bytes, which is\n\t\t// the archive's order.\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT collection, rkey, bytes FROM record\n\t\t\t\t ${params.afterPath !== undefined ? \"WHERE collection || '/' || rkey > ?\" : \"\"}\n\t\t\t\t ORDER BY collection || '/' || rkey ASC\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...(params.afterPath !== undefined ? [params.afterPath] : []),\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\trecords: page.map((row) => ({\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tbytes: new Uint8Array(row.bytes as ArrayBuffer),\n\t\t\t})),\n\t\t\thasMore,\n\t\t\tstate,\n\t\t};\n\t}\n\n\t/**\n\t * What listSpaces reports for this space: the operator's repo state in\n\t * it and, for a space the operator is the authority of, its revision.\n\t */\n\tasync rpcGetSpaceView(): Promise<{\n\t\trepoRev?: string;\n\t\tdata?: Uint8Array;\n\t\tspaceRev?: string;\n\t} | null> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta || meta.deletedAt) return null;\n\t\tconst state = this.readRepoState();\n\t\tconst spaceRev = meta.isAuthority ? this.currentSpaceRev() : null;\n\t\treturn {\n\t\t\t...(state\n\t\t\t\t? {\n\t\t\t\t\t\trepoRev: state.rev,\n\t\t\t\t\t\tdata: RepoCommit.fromState(state.setHash).setHash.digest(),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(spaceRev ? { spaceRev } : {}),\n\t\t};\n\t}\n\n\tasync rpcGetRepoState(): Promise<RepoState | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.readRepoState();\n\t}\n\n\t/**\n\t * List oplog entries after `since` (a rev) or `after` (an exact cursor\n\t * position). Creates and updates carry the record's current bytes when\n\t * the oplog cid still matches the live record; superseded values are\n\t * omitted. When the page reaches the head, `head` carries the repo\n\t * state read in the same transaction so the Worker can attach the\n\t * commit without a state race.\n\t */\n\tasync rpcListRepoOps(params: {\n\t\tsince?: string;\n\t\tafter?: { rev: string; idx: number };\n\t\tlimit: number;\n\t\texcludeValues?: boolean;\n\t}): Promise<{ ops: OplogEntry[]; hasMore: boolean; head?: RepoState }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst args: unknown[] = [];\n\t\t\tlet where = \"1=1\";\n\t\t\tif (params.after) {\n\t\t\t\twhere += \" AND (o.rev > ? OR (o.rev = ? AND o.idx > ?))\";\n\t\t\t\targs.push(params.after.rev, params.after.rev, params.after.idx);\n\t\t\t} else if (params.since) {\n\t\t\t\twhere += \" AND o.rev > ?\";\n\t\t\t\targs.push(params.since);\n\t\t\t}\n\t\t\tconst values = params.excludeValues ? \"\" : \", r.bytes AS live_bytes\";\n\t\t\tconst rows = this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t`SELECT o.rev, o.idx, o.collection, o.rkey, o.cid, o.prev${values}\n\t\t\t\t\t FROM oplog o\n\t\t\t\t\t ${params.excludeValues ? \"\" : \"LEFT JOIN record r ON r.collection = o.collection AND r.rkey = o.rkey AND r.cid = o.cid\"}\n\t\t\t\t\t WHERE ${where}\n\t\t\t\t\t ORDER BY o.rev ASC, o.idx ASC\n\t\t\t\t\t LIMIT ?`,\n\t\t\t\t\t...args,\n\t\t\t\t\tparams.limit + 1,\n\t\t\t\t)\n\t\t\t\t.toArray();\n\t\t\tconst hasMore = rows.length > params.limit;\n\t\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\t\tconst ops: OplogEntry[] = page.map((row) => ({\n\t\t\t\trev: row.rev as string,\n\t\t\t\tidx: row.idx as number,\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tcid: (row.cid as string | null) ?? null,\n\t\t\t\tprev: (row.prev as string | null) ?? null,\n\t\t\t\t...(row.live_bytes\n\t\t\t\t\t? { bytes: new Uint8Array(row.live_bytes as ArrayBuffer) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\t// The commit is returned on every page, read in the same\n\t\t\t// transaction so it never races the page.\n\t\t\tconst head = this.readRepoState();\n\t\t\treturn { ops, hasMore, ...(head ? { head } : {}) };\n\t\t});\n\t}\n\n\t/** Distinct blob CIDs referenced by records, ascending, paged. */\n\tasync rpcListBlobs(params: {\n\t\tsince?: string;\n\t\tlimit: number;\n\t\tafterCid?: string;\n\t}): Promise<{ cids: string[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.since) {\n\t\t\twhere += \" AND r.rev > ?\";\n\t\t\targs.push(params.since);\n\t\t}\n\t\tif (params.afterCid) {\n\t\t\twhere += \" AND b.blob_cid > ?\";\n\t\t\targs.push(params.afterCid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT DISTINCT b.blob_cid FROM record_blob b\n\t\t\t\t JOIN record r ON r.collection = b.collection AND r.rkey = b.rkey\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY b.blob_cid ASC\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { cids: page.map((r) => r.blob_cid as string), hasMore };\n\t}\n\n\t/** Whether a blob CID is referenced by any record in this space. */\n\tasync rpcHasSpaceBlob(cid: string): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\"SELECT 1 FROM record_blob WHERE blob_cid = ? LIMIT 1\", cid)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Replay protection and revocation\n\t// ------------------------------------------------------------------\n\n\t/**\n\t * Record a single-use key. Returns true when the key was fresh (now\n\t * recorded), false when it was already seen and must be refused.\n\t */\n\tasync rpcCheckReplay(\n\t\tkind: string,\n\t\tkey: string,\n\t\texpiresAtSec: number,\n\t): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tconst result = this.sql.exec(\n\t\t\t\"INSERT OR IGNORE INTO replay (kind, key, expires_at) VALUES (?, ?, ?)\",\n\t\t\tkind,\n\t\t\tkey,\n\t\t\texpiresAtSec,\n\t\t);\n\t\treturn result.rowsWritten > 0;\n\t}\n\n\t/**\n\t * Record credentials the authority revoked (repo-host role). Held until\n\t * any credential with that jti must have expired anyway. Needs no live\n\t * repo: a revocation can precede the first write.\n\t */\n\tasync rpcRevokeCredentials(\n\t\tjtis: string[],\n\t\texpiresAtSec: number,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tfor (const jti of jtis) {\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT INTO revoked_credential (jti, expires_at) VALUES (?, ?)\n\t\t\t\t ON CONFLICT (jti) DO UPDATE SET expires_at = excluded.expires_at`,\n\t\t\t\tjti,\n\t\t\t\texpiresAtSec,\n\t\t\t);\n\t\t}\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tasync rpcIsCredentialRevoked(jti: string): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT 1 FROM revoked_credential WHERE jti = ? AND expires_at > ?\",\n\t\t\t\t\tjti,\n\t\t\t\t\tMath.floor(Date.now() / 1000),\n\t\t\t\t)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Authority role: policy, members, writers, notifications\n\t// ------------------------------------------------------------------\n\n\tprivate writePolicy(policy: SpacePolicy): void {\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO config (id, policy) VALUES (1, ?)\n\t\t\t ON CONFLICT (id) DO UPDATE SET policy = excluded.policy`,\n\t\t\tJSON.stringify(policy),\n\t\t);\n\t}\n\n\tprivate readPolicy(): SpacePolicy | null {\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT policy FROM config WHERE id = 1\")\n\t\t\t.toArray()[0];\n\t\treturn row ? (JSON.parse(row.policy as string) as SpacePolicy) : null;\n\t}\n\n\t/**\n\t * State needed to answer getSpaceCredential and notifyWrite: meta\n\t * (including the deletion tombstone) and the policy. Never throws on a\n\t * deleted space โ a late credential request must get SpaceDeleted, not\n\t * SpaceNotFound, and that mapping is the caller's.\n\t */\n\tasync rpcGetAuthorityState(): Promise<{\n\t\tmeta: SpaceMeta | null;\n\t\tpolicy: SpacePolicy | null;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\treturn { meta: this.readMeta(), policy: this.readPolicy() };\n\t}\n\n\tprivate hasRecord(collection: string, rkey: string): boolean {\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT 1 FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\tcollection,\n\t\t\t\t\trkey,\n\t\t\t\t)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\tprivate async preparePut(\n\t\tcollection: string,\n\t\trkey: string,\n\t\trecord: Record<string, unknown>,\n\t): Promise<PreparedSpaceWrite> {\n\t\tconst prepared = await prepareRecord(record);\n\t\treturn {\n\t\t\taction: this.hasRecord(collection, rkey) ? \"update\" : \"create\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t\tcid: prepared.cid,\n\t\t\tbytes: prepared.bytes,\n\t\t\tblobCids: prepared.blobCids,\n\t\t};\n\t}\n\n\tprivate prepareDeleteIfExists(\n\t\tcollection: string,\n\t\trkey: string,\n\t): PreparedSpaceWrite[] {\n\t\treturn this.hasRecord(collection, rkey)\n\t\t\t? [{ action: \"delete\", collection, rkey }]\n\t\t\t: [];\n\t}\n\n\t/** Publish, update or withdraw the policy record to match the policy. */\n\tprivate async preparePolicyRecordWrites(\n\t\tpolicy: SpacePolicy,\n\t): Promise<PreparedSpaceWrite[]> {\n\t\tif (isPolicyPublished(policy)) {\n\t\t\treturn [\n\t\t\t\tawait this.preparePut(POLICY_COLLECTION, POLICY_RKEY, {\n\t\t\t\t\t$type: POLICY_COLLECTION,\n\t\t\t\t\tpolicy,\n\t\t\t\t}),\n\t\t\t];\n\t\t}\n\t\treturn this.prepareDeleteIfExists(POLICY_COLLECTION, POLICY_RKEY);\n\t}\n\n\t/**\n\t * Publish, update or withdraw a member's record to match their entry.\n\t * `access` is omitted for a DID that is no longer a member.\n\t */\n\tprivate async prepareMemberRecordWrites(\n\t\tpolicy: SpacePolicy,\n\t\tdid: string,\n\t\taccess?: { read: boolean; write: boolean },\n\t): Promise<PreparedSpaceWrite[]> {\n\t\tconst rkey = didToRecordKey(did);\n\t\tif (access && areMembersPublished(policy)) {\n\t\t\treturn [\n\t\t\t\tawait this.preparePut(MEMBER_COLLECTION, rkey, {\n\t\t\t\t\t$type: MEMBER_COLLECTION,\n\t\t\t\t\tread: access.read,\n\t\t\t\t\twrite: access.write,\n\t\t\t\t}),\n\t\t\t];\n\t\t}\n\t\treturn this.prepareDeleteIfExists(MEMBER_COLLECTION, rkey);\n\t}\n\n\t/**\n\t * The policy and member records the policy publishes, as creates into a\n\t * repo that holds none (an import has just cleared it).\n\t */\n\tprivate async preparePublishedRecordCreates(\n\t\tpolicy: SpacePolicy,\n\t): Promise<PreparedSpaceWrite[]> {\n\t\tconst writes = await this.preparePolicyRecordWrites(policy);\n\t\tfor (const member of this.readMembers()) {\n\t\t\twrites.push(\n\t\t\t\t...(await this.prepareMemberRecordWrites(policy, member.did, member)),\n\t\t\t);\n\t\t}\n\t\treturn writes.flatMap((write) =>\n\t\t\twrite.action === \"delete\"\n\t\t\t\t? []\n\t\t\t\t: [{ ...write, action: \"create\" as const }],\n\t\t);\n\t}\n\n\tprivate readMembers(): SpaceMember[] {\n\t\treturn this.sql\n\t\t\t.exec(\"SELECT did, can_read, can_write FROM member ORDER BY did\")\n\t\t\t.toArray()\n\t\t\t.map((row) => ({\n\t\t\t\tdid: row.did as string,\n\t\t\t\tread: (row.can_read as number) === 1,\n\t\t\t\twrite: (row.can_write as number) === 1,\n\t\t\t}));\n\t}\n\n\t/**\n\t * Replace the policy wholesale. A different `$type` migrates the space:\n\t * state held by the previous policy (the member list) is discarded, and\n\t * a published member list is withdrawn with it.\n\t */\n\tasync rpcUpdatePolicy(next: SpacePolicy): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy: current } = this.requirePolicy();\n\t\tconst writes = await this.preparePolicyRecordWrites(next);\n\t\tif (areMembersPublished(current) !== areMembersPublished(next)) {\n\t\t\tfor (const member of this.readMembers()) {\n\t\t\t\twrites.push(\n\t\t\t\t\t...(await this.prepareMemberRecordWrites(next, member.did, member)),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tthis.writePolicy(next);\n\t\t\tif (current.$type !== next.$type) {\n\t\t\t\tthis.sql.exec(\"DELETE FROM member\");\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t}\n\n\t/**\n\t * Add members or replace their access, in one commit. A DID listed twice\n\t * takes its last entry. Revoking write access removes the member from\n\t * the writer set, sequenced and announced like any removal.\n\t */\n\tasync rpcPutMembers(\n\t\tmembers: SpaceMember[],\n\t): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst byDid = new Map(members.map((m) => [m.did, m]));\n\t\tconst writes: PreparedSpaceWrite[] = [];\n\t\tfor (const member of byDid.values()) {\n\t\t\twrites.push(\n\t\t\t\t...(await this.prepareMemberRecordWrites(policy, member.did, member)),\n\t\t\t);\n\t\t}\n\t\tconst commit = this.ctx.storage.transactionSync(() => {\n\t\t\tfor (const member of byDid.values()) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)\n\t\t\t\t\t ON CONFLICT (did) DO UPDATE SET can_read = excluded.can_read, can_write = excluded.can_write`,\n\t\t\t\t\tmember.did,\n\t\t\t\t\tmember.read ? 1 : 0,\n\t\t\t\t\tmember.write ? 1 : 0,\n\t\t\t\t);\n\t\t\t\tif (!member.write) this.removeWriterSync(member.did);\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t\treturn commit;\n\t}\n\n\t/**\n\t * Remove members, in one commit, and from the writer set. DIDs that are\n\t * not members are ignored, leaving any writer set entry alone.\n\t */\n\tasync rpcRemoveMembers(dids: string[]): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst members = [...new Set(dids)].filter(\n\t\t\t(did) =>\n\t\t\t\tthis.sql.exec(\"SELECT 1 FROM member WHERE did = ?\", did).toArray()\n\t\t\t\t\t.length > 0,\n\t\t);\n\t\tconst writes: PreparedSpaceWrite[] = [];\n\t\tfor (const did of members) {\n\t\t\twrites.push(...(await this.prepareMemberRecordWrites(policy, did)));\n\t\t}\n\t\tconst commit = this.ctx.storage.transactionSync(() => {\n\t\t\tfor (const did of members) {\n\t\t\t\tthis.sql.exec(\"DELETE FROM member WHERE did = ?\", did);\n\t\t\t\tthis.removeWriterSync(did);\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t\treturn commit;\n\t}\n\n\tasync rpcGetMember(did: string): Promise<SpaceMember | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT did, can_read, can_write FROM member WHERE did = ?\", did)\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tdid: row.did as string,\n\t\t\tread: (row.can_read as number) === 1,\n\t\t\twrite: (row.can_write as number) === 1,\n\t\t};\n\t}\n\n\tasync rpcListMembers(params: {\n\t\tlimit: number;\n\t\tafterDid?: string;\n\t}): Promise<{ members: SpaceMember[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.afterDid) {\n\t\t\twhere += \" AND did > ?\";\n\t\t\targs.push(params.afterDid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT did, can_read, can_write FROM member WHERE ${where} ORDER BY did ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\tmembers: page.map((row) => ({\n\t\t\t\tdid: row.did as string,\n\t\t\t\tread: (row.can_read as number) === 1,\n\t\t\t\twrite: (row.can_write as number) === 1,\n\t\t\t})),\n\t\t\thasMore,\n\t\t};\n\t}\n\n\t/** The space's current revision: the latest in its writer set, removals included. */\n\tprivate currentSpaceRev(): string | null {\n\t\treturn (\n\t\t\t(this.sql.exec(\"SELECT MAX(space_rev) AS rev FROM writer\").toArray()[0]\n\t\t\t\t?.rev as string | null) ?? null\n\t\t);\n\t}\n\n\tasync rpcGetSpaceRev(): Promise<string | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\treturn this.currentSpaceRev();\n\t}\n\n\t/**\n\t * Record a writer's latest (repoRev, data), from notifyRepoUpdate or own\n\t * writes, advance the space sequence, and queue the update for the\n\t * registered syncers in the same transaction. Monotonic per writer: a\n\t * delayed or replayed notification with an older (or equal) rev changes\n\t * nothing and returns null. A newer write from a removed writer re-adds\n\t * it.\n\t */\n\tasync rpcRecordWriter(\n\t\tdid: string,\n\t\trepoRev: string,\n\t\tdata: Uint8Array,\n\t): Promise<SpaceSequence | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { meta } = this.requirePolicy();\n\t\tconst sequence = this.ctx.storage.transactionSync(() => {\n\t\t\tconst existing = this.sql\n\t\t\t\t.exec(\"SELECT repo_rev FROM writer WHERE did = ?\", did)\n\t\t\t\t.toArray()[0];\n\t\t\tif (existing && (existing.repo_rev as string) >= repoRev) return null;\n\t\t\tconst prevSpaceRev = this.currentSpaceRev();\n\t\t\tconst spaceRev = nextRev(prevSpaceRev);\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)\n\t\t\t\t ON CONFLICT (did) DO UPDATE SET repo_rev = excluded.repo_rev, data = excluded.data,\n\t\t\t\t\tspace_rev = excluded.space_rev, removed_at = NULL`,\n\t\t\t\tdid,\n\t\t\t\trepoRev,\n\t\t\t\tdata,\n\t\t\t\tspaceRev,\n\t\t\t);\n\t\t\tconst sequence = { spaceRev, ...(prevSpaceRev ? { prevSpaceRev } : {}) };\n\t\t\tthis.queueSpaceUpdate(meta.uri, {\n\t\t\t\t$type: REPO_WRITE,\n\t\t\t\trepo: did,\n\t\t\t\trepoRev,\n\t\t\t\tdata: bytesToJson(data),\n\t\t\t\t...sequence,\n\t\t\t});\n\t\t\treturn sequence;\n\t\t});\n\t\tif (sequence) await this.scheduleNextAlarm();\n\t\treturn sequence;\n\t}\n\n\t/**\n\t * Remove a repo from the writer set at a new space revision, keeping its\n\t * row marked removed so listWriters reports the removal, and announce it.\n\t * Returns false when the repo is not in the writer set. Must run in a\n\t * transaction.\n\t */\n\tprivate removeWriterSync(did: string): boolean {\n\t\tconst meta = this.readMeta();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT removed_at FROM writer WHERE did = ?\", did)\n\t\t\t.toArray()[0];\n\t\tif (!meta || !row || row.removed_at !== null) return false;\n\t\tconst prevSpaceRev = this.currentSpaceRev();\n\t\tconst spaceRev = nextRev(prevSpaceRev);\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE writer SET space_rev = ?, removed_at = ? WHERE did = ?\",\n\t\t\tspaceRev,\n\t\t\tDate.now(),\n\t\t\tdid,\n\t\t);\n\t\tthis.queueSpaceUpdate(meta.uri, {\n\t\t\t$type: REPO_REMOVED,\n\t\t\trepo: did,\n\t\t\tspaceRev,\n\t\t\t...(prevSpaceRev ? { prevSpaceRev } : {}),\n\t\t});\n\t\treturn true;\n\t}\n\n\t/**\n\t * Drop an account from the writer set. It is tracked again if it later\n\t * writes while still authorised. Idempotent.\n\t */\n\tasync rpcRemoveWriter(did: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\tthis.ctx.storage.transactionSync(() => this.removeWriterSync(did));\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate readWriter(row: Record<string, SqlStorageValue>): SpaceWriter {\n\t\treturn {\n\t\t\tdid: row.did as string,\n\t\t\trepoRev: row.repo_rev as string,\n\t\t\tdata: new Uint8Array(row.data as ArrayBuffer),\n\t\t\tspaceRev: row.space_rev as string,\n\t\t\tremoved: row.removed_at !== null,\n\t\t};\n\t}\n\n\t/** The writer set, removals included, in ascending space revision after `cursor`. */\n\tasync rpcListWriters(params: {\n\t\tlimit: number;\n\t\tcursor?: string;\n\t}): Promise<SpaceWriter[]> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\treturn this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT did, repo_rev, data, space_rev, removed_at FROM writer\n\t\t\t\t ${params.cursor ? \"WHERE space_rev > ?\" : \"\"}\n\t\t\t\t ORDER BY space_rev ASC LIMIT ?`,\n\t\t\t\t...(params.cursor ? [params.cursor] : []),\n\t\t\t\tparams.limit,\n\t\t\t)\n\t\t\t.toArray()\n\t\t\t.map((row) => this.readWriter(row));\n\t}\n\n\t/** The space's host-side state, for migrating its authority's account. */\n\tasync rpcExportMeta(): Promise<{\n\t\tpolicy: SpacePolicy;\n\t\tmembers: SpaceMember[];\n\t\twriters: SpaceWriter[];\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\t// Removed writers stay behind: the archive carries only the writer\n\t\t// set itself.\n\t\tconst writers = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT did, repo_rev, data, space_rev, removed_at FROM writer WHERE removed_at IS NULL ORDER BY did\",\n\t\t\t)\n\t\t\t.toArray()\n\t\t\t.map((row) => this.readWriter(row));\n\t\treturn { policy, members: this.readMembers(), writers };\n\t}\n\n\t/**\n\t * Import a space exported by its previous host, replacing whatever this\n\t * host held for it, so a migration step can be retried. Nothing is\n\t * published here: the authority's repo arrives afterwards with\n\t * importRepo, which publishes the policy and member records from what is\n\t * set here.\n\t * Registrations, revocations and tombstones are not carried over.\n\t */\n\tasync rpcImportMeta(params: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tpolicy: SpacePolicy;\n\t\tmembers: SpaceMember[];\n\t\twriters: SpaceWriter[];\n\t}): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst existing = this.readMeta();\n\t\tif (existing && existing.uri !== params.uri) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Space DO already holds ${existing.uri}`,\n\t\t\t);\n\t\t}\n\t\tthis.ctx.storage.transactionSync(() => {\n\t\t\tif (!existing) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)\n\t\t\t\t\t VALUES (?, ?, ?, ?, 1, ?, NULL, ?)`,\n\t\t\t\t\tparams.uri,\n\t\t\t\t\tparams.authority,\n\t\t\t\t\tparams.type,\n\t\t\t\t\tparams.skey,\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tSPACE_SCHEMA_VERSION,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis.sql.exec(\"UPDATE meta SET deleted_at = NULL, is_authority = 1\");\n\t\t\t}\n\t\t\tthis.writePolicy(params.policy);\n\t\t\tthis.sql.exec(\"DELETE FROM member\");\n\t\t\tfor (const member of params.members) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)\",\n\t\t\t\t\tmember.did,\n\t\t\t\t\tmember.read ? 1 : 0,\n\t\t\t\t\tmember.write ? 1 : 0,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.sql.exec(\"DELETE FROM writer\");\n\t\t\tfor (const writer of params.writers) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)\",\n\t\t\t\t\twriter.did,\n\t\t\t\t\twriter.repoRev,\n\t\t\t\t\twriter.data,\n\t\t\t\t\twriter.spaceRev,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\tasync rpcGetNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t): Promise<{ expiresAt: number } | null> {\n\t\tawait this.ensureOpen();\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\t\tregistration.endpoint,\n\t\t\t\tregistration.token,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\treturn row ? { expiresAt: row.expires_at as number } : null;\n\t}\n\n\t/**\n\t * Register a syncer's webhook, or renew it, to the expiry of the\n\t * credential it was authorised with. Renewal clears a lapse already\n\t * announced, so the next lapse is announced too.\n\t */\n\tasync rpcPutNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t\texpiresAt: number,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) throw new SpaceError(\"SpaceNotFound\", \"Space not found\");\n\t\tif (meta.deletedAt) {\n\t\t\tthrow new SpaceError(\"SpaceDeleted\", \"Space has been deleted\");\n\t\t}\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO notify_registration (endpoint, token, expires_at, expiry_notified) VALUES (?, ?, ?, 0)\n\t\t\t ON CONFLICT (endpoint, token) DO UPDATE SET expires_at = excluded.expires_at, expiry_notified = 0`,\n\t\t\tregistration.endpoint,\n\t\t\tregistration.token,\n\t\t\texpiresAt,\n\t\t);\n\t}\n\n\t/** Withdraw a registration, as when its syncer is denied access. */\n\tasync rpcRemoveNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\tregistration.endpoint,\n\t\t\tregistration.token,\n\t\t);\n\t}\n\n\t/**\n\t * Queue a sequenced writer-set change for the registered syncers: best\n\t * effort to each active registration, and in place of the update an\n\t * expiry notice, delivered reliably, to each registration that has\n\t * lapsed since the last one. Each lapse is claimed once. Must run in a\n\t * transaction.\n\t */\n\tprivate queueSpaceUpdate(\n\t\tspace: string,\n\t\tupdate: Record<string, unknown>,\n\t): void {\n\t\tconst now = Date.now();\n\t\tconst registrations = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT endpoint, token, expires_at, expiry_notified FROM notify_registration\",\n\t\t\t)\n\t\t\t.toArray();\n\t\tfor (const row of registrations) {\n\t\t\tconst endpoint = row.endpoint as string;\n\t\t\tconst token = row.token as string;\n\t\t\tif ((row.expires_at as number) > now) {\n\t\t\t\tthis.insertNotify({\n\t\t\t\t\tservice: endpoint,\n\t\t\t\t\tendpoint,\n\t\t\t\t\tlxm: NOTIFY_SPACE_UPDATE_LXM,\n\t\t\t\t\tbody: { space, token, update },\n\t\t\t\t\tpolicy: \"fanout\",\n\t\t\t\t\tauth: \"none\",\n\t\t\t\t});\n\t\t\t} else if ((row.expiry_notified as number) === 0) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"UPDATE notify_registration SET expiry_notified = 1 WHERE endpoint = ? AND token = ?\",\n\t\t\t\t\tendpoint,\n\t\t\t\t\ttoken,\n\t\t\t\t);\n\t\t\t\tthis.queueSyncerNotice({ endpoint, token }, space, {\n\t\t\t\t\t$type: REGISTRATION_EXPIRED,\n\t\t\t\t\tspaceRev: update.spaceRev,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/** A deletion or expiry notice, delivered reliably for 72 hours. */\n\tprivate queueSyncerNotice(\n\t\tregistration: NotifyRegistration,\n\t\tspace: string,\n\t\tnotice: Record<string, unknown>,\n\t): void {\n\t\tthis.insertNotify({\n\t\t\tservice: registration.endpoint,\n\t\t\tendpoint: registration.endpoint,\n\t\t\tlxm: NOTIFY_SPACE_UPDATE_LXM,\n\t\t\tbody: { space, token: registration.token, update: notice },\n\t\t\tpolicy: \"syncer\",\n\t\t\tauth: \"none\",\n\t\t\t// A deletion notice replaces whatever is pending; an expiry notice\n\t\t\t// never replaces one, so a deletion notice is never lost.\n\t\t\tcoalesceKey: `syncer\\n${registration.endpoint}\\n${registration.token}`,\n\t\t\tkeepPending: notice.$type !== SPACE_DELETED,\n\t\t\tdeadline: Date.now() + SYNCER_NOTICE_RETRY_WINDOW_MS,\n\t\t});\n\t}\n\n\t/**\n\t * Queue outbound notifications for the alarm to deliver with bounded\n\t * retries. An item with a coalesce key replaces any pending item with\n\t * the same key, resetting its backoff and deadline.\n\t */\n\tasync rpcEnqueueNotify(\n\t\titems: NotifyItem[],\n\t\topts: { delayMs?: number } = {},\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tif (items.length === 0) return;\n\t\tconst nextAt = Date.now() + (opts.delayMs ?? 0);\n\t\tfor (const item of items) this.insertNotify(item, nextAt);\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate insertNotify(item: NotifyItem, nextAt = Date.now()): void {\n\t\tconst body = JSON.stringify({\n\t\t\tendpoint: item.endpoint,\n\t\t\tlxm: item.lxm,\n\t\t\tbody: item.body,\n\t\t});\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO notify_queue (service, body, attempts, next_at, deadline, coalesce_key, policy, auth)\n\t\t\t VALUES (?, ?, 0, ?, ?, ?, ?, ?)\n\t\t\t ON CONFLICT (coalesce_key) DO ${\n\t\t\t\t\titem.keepPending\n\t\t\t\t\t\t? \"NOTHING\"\n\t\t\t\t\t\t: `UPDATE SET\n\t\t\t\tservice = excluded.service, body = excluded.body, attempts = 0,\n\t\t\t\tnext_at = excluded.next_at, deadline = excluded.deadline,\n\t\t\t\tpolicy = excluded.policy, auth = excluded.auth`\n\t\t\t\t}`,\n\t\t\titem.service,\n\t\t\tbody,\n\t\t\tnextAt,\n\t\t\titem.deadline ?? null,\n\t\t\titem.coalesceKey ?? null,\n\t\t\titem.policy ?? \"fanout\",\n\t\t\titem.auth ?? \"service\",\n\t\t);\n\t}\n\n\t/** Drop a pending coalesced notification, e.g. once a newer one landed. */\n\tasync rpcClearNotify(coalesceKey: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_queue WHERE coalesce_key = ?\",\n\t\t\tcoalesceKey,\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Deletion and status\n\t// ------------------------------------------------------------------\n\n\t/**\n\t * Tombstone the space (authority role), delete the authority's own repo\n\t * in it, and queue a deletion notice to every registered syncer, lapsed\n\t * registrations included. The meta row is retained so a late\n\t * authorizeSpaceSync can answer SpaceDeleted rather than SpaceNotFound.\n\t * Idempotent.\n\t */\n\tasync rpcDeleteSpace(): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space is not initialised\");\n\t\t}\n\t\tif (meta.deletedAt) return;\n\t\tthis.ctx.storage.transactionSync(() => {\n\t\t\tfor (const row of this.sql\n\t\t\t\t.exec(\"SELECT endpoint, token FROM notify_registration\")\n\t\t\t\t.toArray()) {\n\t\t\t\tthis.queueSyncerNotice(\n\t\t\t\t\t{ endpoint: row.endpoint as string, token: row.token as string },\n\t\t\t\t\tmeta.uri,\n\t\t\t\t\t{ $type: SPACE_DELETED },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.sql.exec(\"UPDATE meta SET deleted_at = ?\", new Date().toISOString());\n\t\t\tfor (const table of [\n\t\t\t\t\"record\",\n\t\t\t\t\"record_blob\",\n\t\t\t\t\"repo_state\",\n\t\t\t\t\"oplog\",\n\t\t\t\t\"config\",\n\t\t\t\t\"member\",\n\t\t\t\t\"writer\",\n\t\t\t\t\"notify_registration\",\n\t\t\t\t\"replay\",\n\t\t\t]) {\n\t\t\t\tthis.sql.exec(`DELETE FROM ${table}`);\n\t\t\t}\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\t/** Wipe everything, including queued notifications and alarms. */\n\tasync rpcDestroy(): Promise<void> {\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.initialized = false;\n\t\tthis.outdated = false;\n\t}\n\n\tasync rpcStatus(): Promise<{\n\t\tmeta: SpaceMeta | null;\n\t\toutdated: boolean;\n\t\tpolicyType: string | null;\n\t\trecordCount: number;\n\t\tmemberCount: number;\n\t\twriterCount: number;\n\t\tqueuedNotifications: number;\n\t}> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) {\n\t\t\treturn {\n\t\t\t\tmeta: null,\n\t\t\t\toutdated: true,\n\t\t\t\tpolicyType: null,\n\t\t\t\trecordCount: 0,\n\t\t\t\tmemberCount: 0,\n\t\t\t\twriterCount: 0,\n\t\t\t\tqueuedNotifications: 0,\n\t\t\t};\n\t\t}\n\t\tconst count = (table: string): number =>\n\t\t\t(this.sql.exec(`SELECT COUNT(*) AS n FROM ${table}`).toArray()[0]\n\t\t\t\t?.n as number) ?? 0;\n\t\treturn {\n\t\t\tmeta: this.readMeta(),\n\t\t\toutdated: false,\n\t\t\tpolicyType: this.readPolicy()?.$type ?? null,\n\t\t\trecordCount: count(\"record\"),\n\t\t\tmemberCount: count(\"member\"),\n\t\t\twriterCount: count(\"writer WHERE removed_at IS NULL\"),\n\t\t\tqueuedNotifications: count(\"notify_queue\"),\n\t\t};\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Alarm: notification delivery, oplog compaction, expiry cleanup\n\t// ------------------------------------------------------------------\n\n\toverride async alarm(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) return;\n\n\t\tawait this.deliverQueuedNotifications();\n\t\tthis.runMaintenanceIfDue();\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate async deliverQueuedNotifications(): Promise<void> {\n\t\tconst now = Date.now();\n\t\t// Syncer notices are tried once more after their window closes.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_queue WHERE deadline IS NOT NULL AND deadline <= ? AND policy != 'syncer'\",\n\t\t\tnow,\n\t\t);\n\t\tconst due = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT id, service, body, attempts, next_at, deadline, policy, auth FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?\",\n\t\t\t\tnow,\n\t\t\t\tNOTIFY_BATCH,\n\t\t\t)\n\t\t\t.toArray() as unknown as QueueRow[];\n\t\tif (due.length === 0) return;\n\n\t\tconst host = await this.getHostConfig();\n\t\tconst keypair = await host.getKeypair();\n\n\t\t// In parallel, so a slow endpoint doesn't hold up the others.\n\t\tawait Promise.all(\n\t\t\tdue.map(async (row) => {\n\t\t\t\tconst parsed = JSON.parse(row.body) as {\n\t\t\t\t\tendpoint: string;\n\t\t\t\t\tlxm: string;\n\t\t\t\t\tbody: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tif (\n\t\t\t\t\trow.policy === \"syncer\" &&\n\t\t\t\t\t!this.isSyncerNoticeOwed(parsed.endpoint, parsed.body)\n\t\t\t\t) {\n\t\t\t\t\tthis.sql.exec(\"DELETE FROM notify_queue WHERE id = ?\", row.id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet delivered = false;\n\t\t\t\tlet retryable = true;\n\t\t\t\ttry {\n\t\t\t\t\tconst headers: Record<string, string> = {\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t};\n\t\t\t\t\tif (row.auth === \"service\") {\n\t\t\t\t\t\tconst token = await createServiceJwt(\n\t\t\t\t\t\t\t{ iss: host.operatorDid, aud: row.service, lxm: parsed.lxm },\n\t\t\t\t\t\t\tkeypair,\n\t\t\t\t\t\t);\n\t\t\t\t\t\theaders.Authorization = `Bearer ${token}`;\n\t\t\t\t\t}\n\t\t\t\t\tconst res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tbody: JSON.stringify(parsed.body),\n\t\t\t\t\t\t// A syncer chose this endpoint: never follow it elsewhere.\n\t\t\t\t\t\tredirect: row.auth === \"none\" ? \"manual\" : \"follow\",\n\t\t\t\t\t\tsignal: AbortSignal.timeout(10_000),\n\t\t\t\t\t});\n\t\t\t\t\tdelivered = res.ok;\n\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\tretryable = isRetryableStatus(res.status);\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`notify ${parsed.lxm} to ${row.service} failed: ${res.status}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconsole.warn(`notify to ${row.service} errored:`, err);\n\t\t\t\t}\n\t\t\t\tthis.settleNotify(row, parsed, delivered, retryable);\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** A deletion or expiry notice that no longer applies is dropped unsent. */\n\tprivate isSyncerNoticeOwed(\n\t\tendpoint: string,\n\t\tbody: Record<string, unknown>,\n\t): boolean {\n\t\tconst update = body.update as { $type?: string } | undefined;\n\t\tif (update?.$type === SPACE_DELETED) {\n\t\t\t// Not owed if the space has been recreated since.\n\t\t\treturn Boolean(this.readMeta()?.deletedAt);\n\t\t}\n\t\t// An expiry notice: not owed if the syncer has renewed since.\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\t\tendpoint,\n\t\t\t\tbody.token as string,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\treturn Boolean(row && (row.expires_at as number) <= Date.now());\n\t}\n\n\tprivate settleNotify(\n\t\trow: QueueRow,\n\t\tparsed: { endpoint: string; body: Record<string, unknown> },\n\t\tdelivered: boolean,\n\t\tretryable: boolean,\n\t): void {\n\t\tconst attempts = row.attempts + 1;\n\t\tconst now = Date.now();\n\t\tconst remove = () =>\n\t\t\tthis.sql.exec(\"DELETE FROM notify_queue WHERE id = ?\", row.id);\n\t\tif (delivered) return void remove();\n\t\tif (row.policy === \"syncer\") {\n\t\t\tif (!retryable || (row.deadline !== null && row.deadline <= now)) {\n\t\t\t\tremove();\n\t\t\t\tthis.abandonSyncerNotice(parsed.endpoint, parsed.body);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst delays = SYNCER_NOTICE_RETRY_DELAYS_MS;\n\t\t\tconst delay = delays[Math.min(attempts, delays.length) - 1]!;\n\t\t\tthis.sql.exec(\n\t\t\t\t\"UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?\",\n\t\t\t\tattempts,\n\t\t\t\tnow + jitter(delay),\n\t\t\t\trow.id,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst exhausted =\n\t\t\trow.deadline === null ? attempts >= NOTIFY_MAX_ATTEMPTS : false;\n\t\tif (!retryable || exhausted) return void remove();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?\",\n\t\t\tattempts,\n\t\t\tnow +\n\t\t\t\tjitter(\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\tNOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts,\n\t\t\t\t\t\tNOTIFY_BACKOFF_MAX_MS,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\trow.id,\n\t\t);\n\t}\n\n\t/**\n\t * Give up on a notice. A syncer that rejects its expiry notice, or can't\n\t * be reached, is unregistered, unless it has renewed since.\n\t */\n\tprivate abandonSyncerNotice(\n\t\tendpoint: string,\n\t\tbody: Record<string, unknown>,\n\t): void {\n\t\tconst update = body.update as { $type?: string } | undefined;\n\t\tif (update?.$type !== REGISTRATION_EXPIRED) return;\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_registration WHERE endpoint = ? AND token = ? AND expires_at <= ?\",\n\t\t\tendpoint,\n\t\t\tbody.token as string,\n\t\t\tDate.now(),\n\t\t);\n\t}\n\n\tprivate runMaintenanceIfDue(): void {\n\t\tconst now = Date.now();\n\t\tconst last =\n\t\t\t(this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT expires_at FROM replay WHERE kind = '__maintenance' AND key = 'last' LIMIT 1\",\n\t\t\t\t)\n\t\t\t\t.toArray()[0]?.expires_at as number | undefined) ?? 0;\n\t\tif (now - last < MAINTENANCE_INTERVAL_MS) return;\n\n\t\t// Oplog compaction: 30 days or 10,000 ops, whichever is smaller.\n\t\t// DO SQLite is billed and capped; the reference has no compaction\n\t\t// yet, ours must.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM oplog WHERE rev < ?\",\n\t\t\ttidCutoff(OPLOG_RETENTION_DAYS * DAY_MS),\n\t\t);\n\t\tconst excess = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT rev, idx FROM oplog ORDER BY rev DESC, idx DESC LIMIT 1 OFFSET ?\",\n\t\t\t\tOPLOG_RETENTION_OPS,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tif (excess) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"DELETE FROM oplog WHERE rev < ? OR (rev = ? AND idx <= ?)\",\n\t\t\t\texcess.rev,\n\t\t\t\texcess.rev,\n\t\t\t\texcess.idx,\n\t\t\t);\n\t\t}\n\n\t\tconst nowSec = Math.floor(now / 1000);\n\t\t// Replay and revocation entries expire on their own clock.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM replay WHERE kind != '__maintenance' AND expires_at < ?\",\n\t\t\tnowSec,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM revoked_credential WHERE expires_at <= ?\",\n\t\t\tnowSec,\n\t\t);\n\t\t// Lapsed registrations are kept on purpose: the next update to the\n\t\t// space owes each an expiry notice, and abandoning that notice is what\n\t\t// unregisters it.\n\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO replay (kind, key, expires_at) VALUES ('__maintenance', 'last', ?)\n\t\t\t ON CONFLICT (kind, key) DO UPDATE SET expires_at = excluded.expires_at`,\n\t\t\tnow,\n\t\t);\n\t}\n\n\tprivate async scheduleNextAlarm(): Promise<void> {\n\t\tconst nextQueue = this.sql\n\t\t\t.exec(\"SELECT MIN(next_at) AS next FROM notify_queue\")\n\t\t\t.toArray()[0]?.next as number | null;\n\t\tconst nextMaintenance = Date.now() + MAINTENANCE_INTERVAL_MS;\n\t\tconst next = nextQueue\n\t\t\t? Math.min(Math.max(nextQueue, Date.now() + 1000), nextMaintenance)\n\t\t\t: nextMaintenance;\n\t\tconst current = await this.ctx.storage.getAlarm();\n\t\tif (current === null || next < current) {\n\t\t\tawait this.ctx.storage.setAlarm(next);\n\t\t}\n\t}\n}\n","/**\n * SpaceIndexDurableObject โ singleton registry of space URIs with role\n * flags, timestamps and lifecycle state, addressed by `idFromName(\"spaces\")`.\n *\n * Serves listSpaces, the dashboard, export and reset. Nothing reads it on\n * the hot path: the space DO id is derived from the URI, so reads never\n * depend on the index. Creation is a two-step write โ the index entry is\n * written `pending`, the space DO is initialised, then the entry is marked\n * `active`. A `pending` entry that never activates is cleaned up by this\n * DO's alarm.\n */\n\nimport { DurableObject } from \"cloudflare:workers\";\nimport {\n\tINDEX_DO_SCHEMA,\n\tPENDING_BLOB_TTL_MS,\n\tPENDING_ENTRY_TTL_MS,\n\tSPACE_SCHEMA_VERSION,\n} from \"./schema.js\";\n\nexport type SpaceIndexState = \"pending\" | \"active\" | \"deleted\";\n\nexport interface SpaceIndexEntry {\n\turi: string;\n\tauthority: string;\n\ttype: string;\n\tskey: string;\n\tisAuthority: boolean;\n\tstate: SpaceIndexState;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nconst ALARM_INTERVAL_MS = 6 * 60 * 60 * 1000;\n\nexport class SpaceIndexDurableObject<Env = unknown> extends DurableObject<Env> {\n\tprivate sql: SqlStorage;\n\tprivate initialized = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.sql = ctx.storage.sql;\n\t}\n\n\tprivate async ensureInitialized(): Promise<void> {\n\t\tif (this.initialized) return;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tif (this.initialized) return;\n\t\t\tthis.sql.exec(INDEX_DO_SCHEMA);\n\t\t\tthis.initialized = true;\n\t\t\tconst alarm = await this.ctx.storage.getAlarm();\n\t\t\tif (alarm === null) {\n\t\t\t\tawait this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Register (or revive) an entry in `pending` state. */\n\tasync rpcRegister(entry: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tisAuthority: boolean;\n\t}): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst now = new Date().toISOString();\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO space (uri, authority, type, skey, is_authority, state, created_at, updated_at, schema_version)\n\t\t\t VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)\n\t\t\t ON CONFLICT (uri) DO UPDATE SET\n\t\t\t\tstate = CASE WHEN space.state = 'active' THEN 'active' ELSE 'pending' END,\n\t\t\t\tis_authority = excluded.is_authority,\n\t\t\t\tupdated_at = excluded.updated_at`,\n\t\t\tentry.uri,\n\t\t\tentry.authority,\n\t\t\tentry.type,\n\t\t\tentry.skey,\n\t\t\tentry.isAuthority ? 1 : 0,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\tSPACE_SCHEMA_VERSION,\n\t\t);\n\t}\n\n\tasync rpcActivate(uri: string): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'active', updated_at = ? WHERE uri = ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\turi,\n\t\t);\n\t}\n\n\tasync rpcMarkDeleted(uri: string): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'deleted', updated_at = ? WHERE uri = ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\turi,\n\t\t);\n\t}\n\n\tasync rpcGet(uri: string): Promise<SpaceIndexEntry | null> {\n\t\tawait this.ensureInitialized();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT * FROM space WHERE uri = ?\", uri)\n\t\t\t.toArray()[0];\n\t\treturn row ? toEntry(row) : null;\n\t}\n\n\tasync rpcList(params: {\n\t\ttype?: string;\n\t\tauthority?: string;\n\t\tstate?: SpaceIndexState;\n\t\tlimit: number;\n\t\tafterUri?: string;\n\t}): Promise<{ spaces: SpaceIndexEntry[]; hasMore: boolean }> {\n\t\tawait this.ensureInitialized();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.type) {\n\t\t\twhere += \" AND type = ?\";\n\t\t\targs.push(params.type);\n\t\t}\n\t\tif (params.authority) {\n\t\t\twhere += \" AND authority = ?\";\n\t\t\targs.push(params.authority);\n\t\t}\n\t\tif (params.state) {\n\t\t\twhere += \" AND state = ?\";\n\t\t\targs.push(params.state);\n\t\t}\n\t\tif (params.afterUri) {\n\t\t\twhere += \" AND uri > ?\";\n\t\t\targs.push(params.afterUri);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT * FROM space WHERE ${where} ORDER BY uri ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { spaces: page.map(toEntry), hasMore };\n\t}\n\n\tasync rpcStats(): Promise<{\n\t\ttotal: number;\n\t\tactive: number;\n\t\tpending: number;\n\t\tdeleted: number;\n\t\thosted: number;\n\t}> {\n\t\tawait this.ensureInitialized();\n\t\tconst count = (where: string): number =>\n\t\t\t(this.sql\n\t\t\t\t.exec(`SELECT COUNT(*) AS n FROM space WHERE ${where}`)\n\t\t\t\t.toArray()[0]?.n as number) ?? 0;\n\t\treturn {\n\t\t\ttotal: count(\"1=1\"),\n\t\t\tactive: count(\"state = 'active'\"),\n\t\t\tpending: count(\"state = 'pending'\"),\n\t\t\tdeleted: count(\"state = 'deleted'\"),\n\t\t\thosted: count(\"is_authority = 1 AND state = 'active'\"),\n\t\t};\n\t}\n\n\t/**\n\t * Note blobs an imported space repo references but whose bytes have not\n\t * been uploaded yet, so uploadBlob can promote them when they arrive.\n\t */\n\tasync rpcAddPendingBlobs(uri: string, cids: string[]): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst now = Date.now();\n\t\tfor (const cid of cids) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"INSERT OR REPLACE INTO pending_blob (cid, uri, created_at) VALUES (?, ?, ?)\",\n\t\t\t\tcid,\n\t\t\t\turi,\n\t\t\t\tnow,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Claim a freshly uploaded blob: the spaces whose imported records\n\t * reference it. Claimed entries are removed.\n\t */\n\tasync rpcClaimPendingBlob(cid: string): Promise<string[]> {\n\t\tawait this.ensureInitialized();\n\t\tconst uris = this.sql\n\t\t\t.exec(\"SELECT uri FROM pending_blob WHERE cid = ?\", cid)\n\t\t\t.toArray()\n\t\t\t.map((row) => row.uri as string);\n\t\tif (uris.length > 0) {\n\t\t\tthis.sql.exec(\"DELETE FROM pending_blob WHERE cid = ?\", cid);\n\t\t}\n\t\treturn uris;\n\t}\n\n\t/** Wipe the registry (spaces reset). */\n\tasync rpcDestroy(): Promise<void> {\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.initialized = false;\n\t}\n\n\t/**\n\t * Tombstone `pending` entries that never activated. They become\n\t * `deleted` rather than being removed: a crash between the space DO's\n\t * initialisation and the index activation leaves real DO storage\n\t * behind, and the index row is the only durable manifest `spaces reset`\n\t * has for finding and destroying it.\n\t */\n\toverride async alarm(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst cutoff = new Date(Date.now() - PENDING_ENTRY_TTL_MS).toISOString();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'deleted', updated_at = ? WHERE state = 'pending' AND updated_at < ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\tcutoff,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM pending_blob WHERE created_at < ?\",\n\t\t\tDate.now() - PENDING_BLOB_TTL_MS,\n\t\t);\n\t\tawait this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);\n\t}\n}\n\nfunction toEntry(row: Record<string, unknown>): SpaceIndexEntry {\n\treturn {\n\t\turi: row.uri as string,\n\t\tauthority: row.authority as string,\n\t\ttype: row.type as string,\n\t\tskey: row.skey as string,\n\t\tisAuthority: (row.is_authority as number) === 1,\n\t\tstate: row.state as SpaceIndexState,\n\t\tcreatedAt: row.created_at as string,\n\t\tupdatedAt: row.updated_at as string,\n\t};\n}\n","/**\n * Space URI handling.\n *\n * A space is addressed as `at:space/{authorityDid}/{typeNsid}/{skey}`, and a\n * record in a space appends `/{authorDid}/{collection}/{rkey}`. The\n * `at:space/` prefix tells it apart from a public `at://` URI.\n *\n * Params are parsed strictly: the alpha's earlier `at://{did}/space/...`\n * form is refused, as the reference refuses it. Only record values written\n * during the alpha may still carry it, and the engine never parses those.\n */\n\n/** The prefix of every space URI. */\nexport const SPACE_URI_PREFIX = \"at:space/\";\n\nimport { isDid, isNsid, isRecordKey } from \"@atcute/lexicons/syntax\";\nimport { SpaceError } from \"./errors.js\";\n\nexport interface SpaceRef {\n\t/** The full space URI. */\n\turi: string;\n\t/** The space authority DID. */\n\tauthority: string;\n\t/** The space type NSID. */\n\ttype: string;\n\t/** The space key (record-key syntax). */\n\tskey: string;\n}\n\n/**\n * Parse a space URI. Returns null when the string is not a valid space\n * reference.\n */\nexport function parseSpaceUri(uri: string): SpaceRef | null {\n\tif (!uri.startsWith(SPACE_URI_PREFIX)) return null;\n\tconst parts = uri.slice(SPACE_URI_PREFIX.length).split(\"/\");\n\tif (parts.length !== 3) return null;\n\tconst [authority, type, skey] = parts as [string, string, string];\n\tif (!isDid(authority) || !isNsid(type) || !isRecordKey(skey)) return null;\n\tconst ref = {\n\t\turi: formatSpaceUri(authority, type, skey),\n\t\tauthority,\n\t\ttype,\n\t\tskey,\n\t};\n\t// Round-trip requirement mirrors the reference's SpaceRef.parse.\n\tif (ref.uri !== uri) return null;\n\treturn ref;\n}\n\n/**\n * Parse a space URI or throw. The error is XRPC's generic InvalidRequest, as\n * the reference answers: no lexicon declares a more specific one.\n */\nexport function requireSpaceUri(uri: string | undefined): SpaceRef {\n\tconst ref = uri ? parseSpaceUri(uri) : null;\n\tif (!ref) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `Invalid space URI: ${uri}`);\n\t}\n\treturn ref;\n}\n\nexport function formatSpaceUri(\n\tauthority: string,\n\ttype: string,\n\tskey: string,\n): string {\n\treturn `${SPACE_URI_PREFIX}${authority}/${type}/${skey}`;\n}\n\n/** URI of a record within a space: `{spaceUri}/{repoDid}/{collection}/{rkey}`. */\nexport function spaceRecordUri(\n\tspaceUri: string,\n\trepo: string,\n\tcollection: string,\n\trkey: string,\n): string {\n\treturn `${spaceUri}/${repo}/${collection}/${rkey}`;\n}\n\nconst BASE32_ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/**\n * Stable identifier for a space used in R2 key prefixes: the lowercase,\n * unpadded base32 encoding of the SHA-256 of the space URI. Deterministic,\n * filesystem-safe and free of the URI's slashes and colons.\n */\nexport async function spaceId(spaceUri: string): Promise<string> {\n\tconst digest = new Uint8Array(\n\t\tawait crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(spaceUri)),\n\t);\n\tlet out = \"\";\n\tlet bits = 0;\n\tlet value = 0;\n\tfor (const byte of digest) {\n\t\tvalue = (value << 8) | byte;\n\t\tbits += 8;\n\t\twhile (bits >= 5) {\n\t\t\tout += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];\n\t\t\tbits -= 5;\n\t\t}\n\t}\n\tif (bits > 0) {\n\t\tout += BASE32_ALPHABET[(value << (5 - bits)) & 31];\n\t}\n\treturn out;\n}\n","/**\n * R2 key layout for space blobs.\n *\n * A blob referenced by a record in a space lives at\n * `${did}/space/${spaceId}/${cid}` and is served only by the\n * credential-gated `com.atproto.space.getBlob`. The same blob referenced\n * from two spaces is stored twice: per-space prefixes make space deletion\n * and full reset a prefix delete with no cross-space reference counting.\n */\n\nimport { spaceId } from \"./space-uri.js\";\n\n/**\n * Key for a staged (uploaded, not yet referenced) blob. Must match the\n * host's public blob layout: uploads land here and are promoted to their\n * serving key when a record write references them.\n */\nexport function stagedBlobKey(did: string, cid: string): string {\n\treturn `${did}/staged/${cid}`;\n}\n\n/** Prefix holding every space blob for the account. */\nexport function spaceBlobRootPrefix(did: string): string {\n\treturn `${did}/space/`;\n}\n\n/** Prefix holding one space's blobs. `id` comes from {@link spaceId}. */\nexport function spaceBlobPrefix(did: string, id: string): string {\n\treturn `${did}/space/${id}/`;\n}\n\n/** Key for one blob in one space. */\nexport function spaceBlobKey(did: string, id: string, cid: string): string {\n\treturn `${did}/space/${id}/${cid}`;\n}\n\n/** Convenience: key for a blob given the space URI rather than its id. */\nexport async function spaceBlobKeyForUri(\n\tdid: string,\n\tspaceUri: string,\n\tcid: string,\n): Promise<string> {\n\treturn spaceBlobKey(did, await spaceId(spaceUri), cid);\n}\n\n/**\n * Copy a staged upload into a space's blob prefix. Idempotent; returns\n * whether the blob is now at its destination (false when it was neither\n * there nor staged).\n */\nexport async function promoteStagedBlobToSpace(\n\tbucket: R2Bucket,\n\tdid: string,\n\tspaceUri: string,\n\tcid: string,\n): Promise<boolean> {\n\tconst destKey = await spaceBlobKeyForUri(did, spaceUri, cid);\n\tif (await bucket.head(destKey)) return true;\n\tconst staged = await bucket.get(stagedBlobKey(did, cid));\n\tif (!staged) return false;\n\tawait bucket.put(destKey, staged.body, { httpMetadata: staged.httpMetadata });\n\treturn true;\n}\n\n/**\n * Promote a freshly uploaded blob into every space whose imported records\n * reference it (see `com.atproto.space.importRepo`). The host calls this\n * from `com.atproto.repo.uploadBlob`, mirroring how an imported public repo's\n * blobs are made permanent on upload.\n */\nexport async function promotePendingSpaceBlob(params: {\n\tbucket: R2Bucket;\n\tdid: string;\n\tcid: string;\n\tclaimPendingBlob: (cid: string) => Promise<string[]>;\n}): Promise<number> {\n\tconst uris = await params.claimPendingBlob(params.cid);\n\tfor (const uri of uris) {\n\t\tawait promoteStagedBlobToSpace(params.bucket, params.did, uri, params.cid);\n\t}\n\treturn uris.length;\n}\n","/**\n * Worker-side verification of space credentials and delegation tokens.\n *\n * A space credential is presented as `Authorization: Atproto-Space-Credential\n * <jwt>` (scheme case-insensitive), with an `Atproto-Space-Audience` header\n * naming the service being called and an HTTP message signature over both,\n * by the P-256 key the credential is bound to (`cnf.kid`). A delegation\n * token arrives in the `getSpaceCredential` request body.\n *\n * Everything here is stateless except the revocation and replay checks,\n * which are one RPC each to the space DO. Key resolution goes through the\n * host's DID resolver with a forced refresh on signature failure (handled\n * inside `verifySpaceToken`) so key rotation doesn't strand callers.\n */\n\nimport {\n\tSpaceSignatureError,\n\tSpaceTokenError,\n\tspaceHostAud,\n\tverifyCredentialSig,\n\tverifySpaceToken,\n} from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport type { SpaceErrorCode } from \"./errors.js\";\nimport { parseSpaceUri } from \"./space-uri.js\";\nimport type { SpaceRef } from \"./space-uri.js\";\n\n/** Resolve an issuer DID's `#atproto` key to a did:key string. */\nexport type GetSigningKey = (\n\tiss: string,\n\tforceRefresh: boolean,\n) => Promise<string>;\n\n/** Record a single-use key; false when it was already seen. */\nexport type CheckReplay = (\n\tkind: string,\n\tkey: string,\n\texpiresAtSec: number,\n) => Promise<boolean>;\n\n/** Whether a credential has been revoked by the space's authority. */\nexport type CheckRevoked = (jti: string) => Promise<boolean>;\n\nexport const SPACE_CREDENTIAL_SCHEME = \"Atproto-Space-Credential\";\nexport const SPACE_AUDIENCE_HEADER = \"atproto-space-audience\";\n\n/**\n * Split an Authorization header into scheme and token. The scheme is\n * case-insensitive, as for every HTTP authentication scheme.\n */\nfunction splitAuthorization(\n\tauthorization: string | undefined,\n): { scheme: string; token: string } | null {\n\tif (!authorization) return null;\n\tconst parts = authorization.split(\" \");\n\tif (parts.length !== 2 || !parts[0] || !parts[1]) return null;\n\treturn { scheme: parts[0].toLowerCase(), token: parts[1] };\n}\n\n/** Whether an Authorization header carries a space credential. */\nexport function isSpaceCredentialAuth(\n\tauthorization: string | undefined,\n): boolean {\n\treturn (\n\t\tsplitAuthorization(authorization)?.scheme ===\n\t\tSPACE_CREDENTIAL_SCHEME.toLowerCase()\n\t);\n}\n\nexport interface VerifyCredentialOpts {\n\t/** Request headers, lower-cased names. */\n\theaders: Record<string, string | undefined>;\n\t/**\n\t * The DID this request is addressed to: the repo DID for repo-host\n\t * reads, the authority DID for space-host methods. The signed\n\t * `Atproto-Space-Audience` header must name it.\n\t */\n\taudience: string;\n\tgetSigningKey: GetSigningKey;\n\tcheckRevoked: CheckRevoked;\n}\n\nexport interface SpaceCredentialResult {\n\tkind: \"credential\";\n\t/** The credential issuer: the space's authority DID. */\n\tiss: string;\n\tjti: string;\n}\n\n/**\n * Verify a space credential presented against `space`: the token itself\n * (type, signature against the issuer's `#atproto` key, expiry, lifetime),\n * its issuer being the space's authority and its subject the space, the\n * HTTP message signature by its bound key over the credential and the\n * audience, the audience naming this service, and revocation.\n */\nexport async function verifySpaceCredentialAuth(\n\tspace: SpaceRef,\n\topts: VerifyCredentialOpts,\n): Promise<SpaceCredentialResult> {\n\tconst authorization = splitAuthorization(opts.headers.authorization);\n\tif (\n\t\t!authorization ||\n\t\tauthorization.scheme !== SPACE_CREDENTIAL_SCHEME.toLowerCase()\n\t) {\n\t\tthrow new SpaceError(\"MissingJwt\", \"Missing space credential\");\n\t}\n\n\tlet payload;\n\ttry {\n\t\t({ payload } = await verifySpaceToken(\"credential\", authorization.token, {\n\t\t\tgetSigningKey: opts.getSigningKey,\n\t\t}));\n\t} catch (err) {\n\t\tthrow tokenError(err, \"BadJwt\");\n\t}\n\tconst subject = parseSpaceUri(payload.sub);\n\tif (!subject) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadJwtSub\",\n\t\t\t`Space token subject is not a space URI: ${payload.sub}`,\n\t\t);\n\t}\n\tif (payload.iss !== subject.authority) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadJwtIss\",\n\t\t\t\"Space credential issuer is not the space authority\",\n\t\t);\n\t}\n\n\tconst audience = opts.headers[SPACE_AUDIENCE_HEADER];\n\tif (!audience?.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadSpaceSignature\",\n\t\t\t\"Missing or invalid space audience DID\",\n\t\t);\n\t}\n\ttry {\n\t\tawait verifyCredentialSig(opts.headers, payload.cnf.kid);\n\t} catch (err) {\n\t\tif (err instanceof SpaceSignatureError) {\n\t\t\tthrow new SpaceError(\"BadSpaceSignature\", err.message);\n\t\t}\n\t\tthrow err;\n\t}\n\tif (audience !== opts.audience) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadSpaceAudience\",\n\t\t\t\"Space audience does not match the request\",\n\t\t);\n\t}\n\tif (payload.sub !== space.uri) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidCredential\",\n\t\t\t\"Credential is not scoped to this space\",\n\t\t);\n\t}\n\tif (await opts.checkRevoked(payload.jti)) {\n\t\tthrow new SpaceError(\n\t\t\t\"CredentialRevoked\",\n\t\t\t\"Space credential has been revoked\",\n\t\t);\n\t}\n\treturn { kind: \"credential\", iss: payload.iss, jti: payload.jti };\n}\n\nexport interface DelegationResult {\n\t/** The user the delegation token vouches for. */\n\tuserDid: string;\n}\n\n/**\n * Verify a delegation token from a `getSpaceCredential` body: signature\n * against the issuer's `#atproto` key, audience the space authority's\n * `#atproto_pds`, subject the requested space, single use by `(iss, jti)`.\n * Any failure is `InvalidDelegationToken`: the token arrives in the body\n * rather than as the request's authorization, so it is an invalid request,\n * not an authentication failure.\n */\nexport async function verifyDelegationToken(\n\ttoken: string,\n\tspace: SpaceRef,\n\topts: { getSigningKey: GetSigningKey; checkReplay: CheckReplay },\n): Promise<DelegationResult> {\n\tlet payload;\n\ttry {\n\t\t({ payload } = await verifySpaceToken(\"delegation\", token, {\n\t\t\tgetSigningKey: opts.getSigningKey,\n\t\t}));\n\t} catch (err) {\n\t\tthrow tokenError(err, \"InvalidDelegationToken\", \"InvalidDelegationToken\");\n\t}\n\tif (payload.sub !== space.uri) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token subject does not match requested space\",\n\t\t);\n\t}\n\tif (\n\t\tpayload.aud !== spaceHostAud(space.authority as `did:${string}:${string}`)\n\t) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token audience does not match the space authority\",\n\t\t);\n\t}\n\tif (!payload.iss.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token issuer is not a DID\",\n\t\t);\n\t}\n\tconst fresh = await opts.checkReplay(\n\t\t\"delegation\",\n\t\t`${payload.iss}:${payload.jti}`,\n\t\tpayload.exp,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token has already been used\",\n\t\t);\n\t}\n\treturn { userDid: payload.iss };\n}\n\nfunction tokenError(\n\terr: unknown,\n\tfallback: SpaceErrorCode,\n\toverride?: SpaceErrorCode,\n): SpaceError {\n\t// Server-side detail for operators; clients get the token library's\n\t// message, never infrastructure internals.\n\tconsole.warn(\"space token verification failed:\", err);\n\tif (err instanceof SpaceTokenError) {\n\t\treturn new SpaceError(override ?? err.code, err.message);\n\t}\n\t// DID resolution failures and other infrastructure errors must surface\n\t// as auth errors, never 500s.\n\treturn new SpaceError(override ?? fallback, \"Token verification failed\");\n}\n","/**\n * Client attestation verification (app-identity gating, `allowList` app\n * access). The attestation is a short-lived JWT signed by the OAuth\n * client's published JWKS key, with `iss` = `sub` = client_id and `aud`\n * the space host. Verified against the client's `client-metadata.json`.\n *\n * The client_id in the payload is attacker-controlled until the signature\n * verifies, so nothing is fetched before it has been validated as an\n * https client-metadata URL and checked against the caller's allow-list โ\n * a space gated on an allow-list never performs network I/O for a client\n * that could not be authorized anyway. All fetches are bounded by a\n * timeout.\n */\n\nimport { createLocalJWKSet, jwtVerify } from \"jose\";\nimport { CLIENT_ATTESTATION_TYP, parseSpaceToken } from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport type { CheckReplay } from \"./auth.js\";\n\n/** Upper bound for each outbound metadata/JWKS fetch. */\nconst FETCH_TIMEOUT_MS = 5000;\n\nexport interface VerifyAttestationOpts {\n\t/** Expected audience: `spaceHostAud(authorityDid)`. */\n\texpectedAud: string;\n\t/**\n\t * When set, an (unverified) client_id outside this list is rejected\n\t * before any network I/O. The membership check runs regardless of\n\t * signature state because the caller re-derives authorization from the\n\t * returned client_id after full verification.\n\t */\n\tallowedClientIds?: readonly string[];\n\tcheckReplay: CheckReplay;\n\t/** Fetch override for tests. */\n\tfetch?: typeof fetch;\n}\n\n/**\n * Verify a client attestation and return the attested client_id.\n * Single-use by `(clientId, jti)`.\n */\nexport async function verifyClientAttestation(\n\tattestation: string,\n\topts: VerifyAttestationOpts,\n): Promise<string> {\n\tlet parsed;\n\ttry {\n\t\tparsed = parseSpaceToken(\"clientAttestation\", attestation);\n\t} catch (err) {\n\t\tthrow invalid(err);\n\t}\n\tconst clientId = parsed.payload.iss;\n\tif (parsed.payload.aud !== opts.expectedAud) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation audience does not match this space host\",\n\t\t);\n\t}\n\n\t// Everything below this point costs network I/O, so gate on what can be\n\t// decided statically first: the client_id must be a plausible https\n\t// client-metadata URL, and must be one the space could authorize at all.\n\tlet clientUrl: URL;\n\ttry {\n\t\tclientUrl = new URL(clientId);\n\t} catch {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation client_id is not a URL\",\n\t\t);\n\t}\n\tif (\n\t\tclientUrl.protocol !== \"https:\" ||\n\t\tclientUrl.username ||\n\t\tclientUrl.password\n\t) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation client_id must be a plain https URL\",\n\t\t);\n\t}\n\tif (opts.allowedClientIds && !opts.allowedClientIds.includes(clientId)) {\n\t\tthrow new SpaceError(\n\t\t\t\"AppNotAuthorized\",\n\t\t\t\"App is not authorized for this space\",\n\t\t);\n\t}\n\n\tconst doFetch = opts.fetch ?? fetch;\n\tconst boundedJson = async (url: string): Promise<unknown> => {\n\t\tconst res = await doFetch(url, {\n\t\t\theaders: { Accept: \"application/json\" },\n\t\t\tsignal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n\t\t\t// No redirects. Not \"error\": workerd refuses it outright, so every\n\t\t\t// fetch would throw. A 3xx under \"manual\" fails the ok check.\n\t\t\tredirect: \"manual\",\n\t\t});\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`fetch of ${url} returned ${res.status}`);\n\t\t}\n\t\treturn res.json();\n\t};\n\n\tlet metadata: { jwks?: unknown; jwks_uri?: string };\n\ttry {\n\t\tmetadata = (await boundedJson(clientId)) as typeof metadata;\n\t} catch {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Could not resolve client metadata\",\n\t\t);\n\t}\n\n\tlet jwks = metadata.jwks;\n\tif (!jwks && typeof metadata.jwks_uri === \"string\") {\n\t\tlet jwksUrl: URL;\n\t\ttry {\n\t\t\tjwksUrl = new URL(metadata.jwks_uri);\n\t\t} catch {\n\t\t\tjwksUrl = null as never;\n\t\t}\n\t\tif (!jwksUrl || jwksUrl.protocol !== \"https:\") {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidClientAttestation\",\n\t\t\t\t\"Client metadata jwks_uri must be an https URL\",\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\tjwks = await boundedJson(metadata.jwks_uri);\n\t\t} catch {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidClientAttestation\",\n\t\t\t\t\"Could not resolve client JWKS\",\n\t\t\t);\n\t\t}\n\t}\n\tif (!jwks) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Client metadata declares no JWKS\",\n\t\t);\n\t}\n\n\ttry {\n\t\tconst keySet = createLocalJWKSet(\n\t\t\tjwks as Parameters<typeof createLocalJWKSet>[0],\n\t\t);\n\t\tawait jwtVerify(attestation, keySet, {\n\t\t\tissuer: clientId,\n\t\t\tsubject: clientId,\n\t\t\taudience: opts.expectedAud,\n\t\t\ttyp: CLIENT_ATTESTATION_TYP,\n\t\t\trequiredClaims: [\"jti\", \"exp\"],\n\t\t\tclockTolerance: 5,\n\t\t});\n\t} catch (err) {\n\t\tthrow invalid(err);\n\t}\n\n\tconst fresh = await opts.checkReplay(\n\t\t\"attestation\",\n\t\t`${clientId}:${parsed.payload.jti}`,\n\t\tparsed.payload.exp,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Client attestation has already been used\",\n\t\t);\n\t}\n\treturn clientId;\n}\n\nfunction invalid(err: unknown): SpaceError {\n\treturn new SpaceError(\n\t\t\"InvalidClientAttestation\",\n\t\terr instanceof Error ? err.message : \"Invalid client attestation\",\n\t);\n}\n","/**\n * Hono route factory for `com.atproto.space.*` and\n * `com.atproto.memberspace.*`.\n *\n * The factory is host-agnostic: everything account-specific โ session\n * authentication, DID resolution, record validation, the operator identity\n * and its keys โ arrives through {@link SpaceRoutesHost}. The host mounts\n * the returned app behind its feature flag.\n */\n\nimport { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport {\n\tcreateSpaceCredential,\n\tisP256DidKey,\n\tparseSpaceToken,\n\treadRepoStar,\n\treadSpaceMetaStar,\n\tspaceHostAud,\n\twriteRepoStar,\n\twriteSpaceMetaStar,\n} from \"@atproto/space\";\nimport type { P256Keypair } from \"@atproto/crypto\";\nimport { encode } from \"@atproto/lex-cbor\";\nimport {\n\tcidForCbor,\n\tenumBlobRefs,\n\tfromBase64,\n\tgetBlobCidString,\n} from \"@atproto/lex-data\";\nimport type { LexValue } from \"@atproto/lex-data\";\nimport { now as tidNow } from \"@atcute/tid\";\nimport { isDid } from \"@atcute/lexicons/syntax\";\nimport {\n\tisSpaceCredentialAuth,\n\tverifyDelegationToken,\n\tverifySpaceCredentialAuth,\n\ttype GetSigningKey,\n} from \"./auth.js\";\nimport { verifyClientAttestation } from \"./attestation.js\";\nimport {\n\tCOMMIT_MAC_PROFILE,\n\tMAC_REQUEST_HEADER,\n\tRECORD_MAC_PROFILE,\n\tbuildCommit,\n\tbytesToJson,\n\tcommitMacHeaders,\n\tcommitToJson,\n\timportKemKeypair,\n\tmacExposedHeaders,\n\tmacRequest,\n\trecordMacHeaders,\n\ttype MacParams,\n\ttype MacProfile,\n} from \"./mac.js\";\nimport { SpaceError, parseSpaceErrorCode, spaceErrorStatus } from \"./errors.js\";\nimport {\n\tMEMBER_COLLECTION,\n\tPUBLISHED_COLLECTIONS,\n\tassertNotPublishedCollection,\n\tdidToRecordKey,\n\tisAppAuthorized,\n\tisPublicRead,\n\tnormalizePolicy,\n\trecordKeyToDid,\n} from \"./policy.js\";\nimport { prepareRecord, recordBytesToJson } from \"./records.js\";\nimport {\n\tMAX_NOTIFY_TOKEN_LENGTH,\n\tMAX_REV_CLOCK_SKEW_MS,\n\tMAX_SPACE_RECORD_BYTES,\n\tNOTIFY_BACKOFF_BASE_MS,\n\tNOTIFY_WRITE_RETRY_MS,\n} from \"./schema.js\";\nimport { createServiceJwt } from \"./service-jwt.js\";\nimport {\n\tpromoteStagedBlobToSpace,\n\tspaceBlobKey,\n\tspaceBlobPrefix,\n} from \"./blob-keys.js\";\nimport {\n\tformatSpaceUri,\n\tparseSpaceUri,\n\trequireSpaceUri,\n\tspaceId,\n\tspaceRecordUri,\n} from \"./space-uri.js\";\nimport type { SpaceRef } from \"./space-uri.js\";\nimport { isRetryableStatus } from \"./space-do.js\";\nimport type { SpaceDurableObject } from \"./space-do.js\";\nimport type { SpaceIndexDurableObject } from \"./index-do.js\";\nimport { tidTimestampMs } from \"./tid.js\";\nimport {\n\tMANAGEDSPACE_POLICY,\n\tMEMBERSPACE_POLICY,\n\tPERSONALSPACE_POLICY,\n\ttype ImportedRecord,\n\ttype NotifyItem,\n\ttype NotifyRegistration,\n\ttype PreparedSpaceWrite,\n\ttype RepoCommitResult,\n\ttype SpaceMember,\n\ttype SpacePolicy,\n\ttype SpaceSigningKeypair,\n} from \"./types.js\";\n\nconst NOTIFY_REPO_UPDATE_LXM = \"com.atproto.space.notifyRepoUpdate\";\nconst CREDENTIALS_REVOKED_LXM = \"com.atproto.space.notifyCredentialsRevoked\";\nconst CONFIRM_REGISTRATION_LXM = \"com.atproto.space.confirmRegistration\";\nconst CHECK_ACCESS_LXM = \"com.atproto.managedspace.checkAccess\";\n/** A managing app or syncer endpoint that doesn't answer in this window fails. */\nconst UPSTREAM_TIMEOUT_MS = 10_000;\n/** The queue key for this repo's pending update notification to a foreign authority. */\nconst NOTIFY_REPO_UPDATE_COALESCE_KEY = \"notifyRepoUpdate:authority\";\n/** Upper bound on archives accepted by importRepo / importSpaceMeta. */\nconst MAX_IMPORT_BYTES = 100 * 1024 * 1024;\n/** Revocations are held until any credential they name has expired. */\nconst REVOCATION_TTL_SEC = 3600 + 2 * 5;\n/** The media type of STAR archives (repos and space meta). */\nconst STAR_CONTENT_TYPE = \"application/vnd.dasl.star\";\n/** Batched member changes take at most this many entries. */\nconst MAX_MEMBER_BATCH = 100;\n\nexport type SpaceStub = DurableObjectStub<SpaceDurableObject>;\nexport type SpaceIndexStub = DurableObjectStub<SpaceIndexDurableObject>;\n\n/** The operation shapes checked against a session's `space:` grants. */\nexport type SpaceScopeMatch = {\n\ttype: string;\n\tauthority: string;\n\tskey: string;\n} & (\n\t| { action: \"read\" | \"read_self\" }\n\t| { action: \"create\" | \"update\" | \"delete\"; collection: string }\n\t| { manage: \"create\" | \"update\" | \"delete\" }\n);\n\n/**\n * The narrowest `space:` scope that covers an operation, written as\n * `@atproto/oauth-scopes` writes it (`SpacePermission.scopeNeededFor`), so a\n * refusal can tell the app what to ask for. A manage op adds the narrowest\n * action, `read_self`, since a scope with no action defaults to all of them.\n */\nexport function spaceScopeNeededFor(match: SpaceScopeMatch): string {\n\tconst scope = `space:${match.type}?authority=${match.authority}&skey=${match.skey}`;\n\tif (\"manage\" in match) {\n\t\treturn `${scope}&action=read_self&manage=${match.manage}`;\n\t}\n\tif (\"collection\" in match) {\n\t\treturn `${scope}&collection=${match.collection}&action=${match.action}`;\n\t}\n\treturn `${scope}&action=${match.action}`;\n}\n\n/**\n * A host session (OAuth token with `space:` grants, or a fully-trusted\n * operator session). App passwords are excluded in the alpha โ the host's\n * authenticate() must not produce one of these for them.\n */\nexport interface SpaceSessionAuth {\n\tdid: string;\n\t/** Fully-trusted operator session: skips scope checks. */\n\tfullTrust: boolean;\n\tallowsSpace(match: SpaceScopeMatch): boolean;\n}\n\nexport interface SpaceRoutesHost {\n\toperatorDid: string;\n\t/** R2 bucket for blobs; space blob endpoints 503 without it. */\n\tblobs?: R2Bucket;\n\t/** The account's `#atproto` keypair: space tokens and service auth. */\n\tgetKeypair(): Promise<SpaceSigningKeypair>;\n\t/**\n\t * The account's `#atproto_kem` P-256 private key (hex), which MACs space\n\t * data for syncers. Null when unconfigured: reads that owe a MAC then\n\t * answer KemKeyUnavailable.\n\t */\n\tgetKemPrivateKey(): string | null | Promise<string | null>;\n\t/** DID-doc `#atproto` key resolution for foreign issuers. */\n\tgetSigningKey: GetSigningKey;\n\t/**\n\t * Resolve a service identifier to an HTTPS endpoint: `did#fragment`\n\t * names that service entry, a bare DID its `#atproto_pds`. Null when\n\t * unresolvable.\n\t */\n\tresolveServiceEndpoint(service: string): Promise<string | null>;\n\t/** Verify an inbound service-auth JWT bound to `lxm`. */\n\tverifyServiceJwt(\n\t\ttoken: string,\n\t\tlxm: string,\n\t): Promise<{ iss: string; aud: string }>;\n\t/**\n\t * Host session authentication (OAuth / operator sessions). Returns a\n\t * Response for authentication failures.\n\t */\n\tauthenticate(c: Context): Promise<SpaceSessionAuth | Response>;\n\t/**\n\t * Whether the operator's account is active. A deactivated authority\n\t * issues no credentials and lists no repos. Treated as active when\n\t * absent.\n\t */\n\tisAccountActive?(): Promise<boolean>;\n\t/**\n\t * Lexicon validation with the host's validator. Throws on invalid\n\t * records; the thrown message is surfaced as an InvalidRecord error.\n\t */\n\tvalidateRecord(input: {\n\t\tcollection: string;\n\t\trecord: unknown;\n\t\trkey: string;\n\t\tvalidate?: boolean;\n\t}): { record: unknown; status?: \"valid\" | \"unknown\" };\n\tgetSpaceDO(uri: string): SpaceStub;\n\tgetIndexDO(): SpaceIndexStub;\n\t/** Fetch override for outbound calls (tests). */\n\toutboundFetch?: typeof fetch;\n}\n\n// ---------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------\n\nfunction errorResponse(c: Context, err: unknown): Response {\n\tconst parsed = parseSpaceErrorCode(err);\n\tif (parsed) {\n\t\treturn c.json(\n\t\t\t{ error: parsed.code, message: parsed.message },\n\t\t\tspaceErrorStatus(parsed.code) as 400,\n\t\t);\n\t}\n\tthrow err;\n}\n\nfunction waitUntil(c: Context, promise: Promise<unknown>): void {\n\ttry {\n\t\tc.executionCtx.waitUntil(promise);\n\t} catch {\n\t\t// No execution context (tests): let it float.\n\t\tvoid promise.catch((err) => console.warn(\"background task failed\", err));\n\t}\n}\n\n/** Request headers as a plain object with lower-cased names. */\nfunction headerRecord(c: Context): Record<string, string | undefined> {\n\treturn Object.fromEntries(c.req.raw.headers);\n}\n\n/** Append to a comma-separated response header without clobbering it. */\nfunction appendHeader(c: Context, name: string, value: string): void {\n\tc.header(name, value, { append: true });\n}\n\ninterface AuthedRead {\n\tkind: \"credential\" | \"session\";\n}\n\ntype ScopeResult = Response | null;\n\nexport function createSpaceRoutes(host: SpaceRoutesHost): Hono {\n\tconst app = new Hono();\n\t// Looked up per call rather than bound here, so a host's tests can stub\n\t// the global fetch after the routes are built.\n\tconst doFetch: typeof fetch =\n\t\thost.outboundFetch ?? ((input, init) => globalThis.fetch(input, init));\n\n\tlet kemKeypair: Promise<P256Keypair | null> | null = null;\n\tfunction getKemKeypair(): Promise<P256Keypair | null> {\n\t\tkemKeypair ??= Promise.resolve(host.getKemPrivateKey()).then((hex) =>\n\t\t\thex ? importKemKeypair(hex) : null,\n\t\t);\n\t\treturn kemKeypair;\n\t}\n\n\t/** The `repo` param on every repo-host method must be the operator DID. */\n\tfunction requireRepoParam(repo: unknown): void {\n\t\tif (repo !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoNotFound\",\n\t\t\t\t`Repository not found: ${String(repo)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Verify a space credential addressed to this host. Every audience is\n\t * the operator DID: Cirrus serves only the operator's repos, and hosts\n\t * only spaces under the operator's authority.\n\t */\n\tasync function credentialAuth(c: Context, ref: SpaceRef): Promise<void> {\n\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\tawait verifySpaceCredentialAuth(ref, {\n\t\t\theaders: headerRecord(c),\n\t\t\taudience: host.operatorDid,\n\t\t\tgetSigningKey: host.getSigningKey,\n\t\t\tcheckRevoked: (jti) => stub.rpcIsCredentialRevoked(jti),\n\t\t});\n\t}\n\n\t/**\n\t * Authenticate a read: a space credential for the requested space, or a\n\t * host session covering `read_self` on it. The `repo` param on every\n\t * repo-host method must be the operator DID โ anything else is\n\t * RepoNotFound, deliberately indistinguishable from an absent repo.\n\t */\n\tasync function readAuth(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\trepo: string | undefined,\n\t): Promise<AuthedRead | Response> {\n\t\trequireRepoParam(repo);\n\t\tif (isSpaceCredentialAuth(c.req.header(\"Authorization\"))) {\n\t\t\tawait credentialAuth(c, ref);\n\t\t\treturn { kind: \"credential\" };\n\t\t}\n\t\tconst session = await host.authenticate(c);\n\t\tif (session instanceof Response) return session;\n\t\tconst scopeError = assertScope(c, session, {\n\t\t\ttype: ref.type,\n\t\t\tauthority: ref.authority,\n\t\t\tskey: ref.skey,\n\t\t\taction: \"read_self\",\n\t\t});\n\t\tif (scopeError) return scopeError;\n\t\treturn { kind: \"session\" };\n\t}\n\n\t/**\n\t * The MAC owed by a read that returns a commit or record, with the\n\t * response headers a browser syncer needs to read the MAC.\n\t */\n\tasync function readMac(\n\t\tc: Context,\n\t\tauth: AuthedRead,\n\t\tprofile: MacProfile,\n\t): Promise<MacParams | undefined> {\n\t\tappendHeader(c, \"Vary\", \"Accept-Signature\");\n\t\tconst mac = await macRequest({\n\t\t\tacceptSignature: c.req.header(MAC_REQUEST_HEADER),\n\t\t\tcredential: auth.kind === \"credential\",\n\t\t\tprofile,\n\t\t\tgetKemKeypair,\n\t\t});\n\t\tif (mac) {\n\t\t\tfor (const header of macExposedHeaders(profile)) {\n\t\t\t\tappendHeader(c, \"Access-Control-Expose-Headers\", header);\n\t\t\t}\n\t\t}\n\t\treturn mac;\n\t}\n\n\tfunction assertScope(\n\t\tc: Context,\n\t\tsession: SpaceSessionAuth,\n\t\tmatch: SpaceScopeMatch,\n\t): ScopeResult {\n\t\tif (session.fullTrust) return null;\n\t\tif (session.allowsSpace(match)) return null;\n\t\treturn c.json(\n\t\t\t{\n\t\t\t\terror: \"InsufficientScope\",\n\t\t\t\tmessage: `Missing required scope: ${spaceScopeNeededFor(match)}`,\n\t\t\t},\n\t\t\t403,\n\t\t);\n\t}\n\n\t/** The operator hosts this space, or SpaceNotFound. */\n\tfunction assertSpaceHost(ref: SpaceRef): void {\n\t\tif (ref.authority !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t}\n\n\t/** As assertSpaceHost, and the authority's account must be active. */\n\tasync function assertActiveSpaceHost(ref: SpaceRef): Promise<void> {\n\t\tassertSpaceHost(ref);\n\t\tif (host.isAccountActive && !(await host.isAccountActive())) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoDeactivated\",\n\t\t\t\t`Repo has been deactivated: ${ref.authority}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * A space created here is anchored on its creator's DID, so ownership\n\t * is a comparison against the space URI, made before anything else.\n\t */\n\tfunction assertOwner(ref: SpaceRef, session: SpaceSessionAuth): void {\n\t\tif (session.did !== ref.authority) {\n\t\t\tthrow new SpaceError(\"NotAuthorized\", \"Not the space authority\");\n\t\t}\n\t\tassertSpaceHost(ref);\n\t}\n\n\t/** The policy of a live space this host governs. */\n\tasync function requirePolicy(\n\t\tstub: SpaceStub,\n\t\tref: SpaceRef,\n\t): Promise<SpacePolicy> {\n\t\tconst { meta, policy } = await stub.rpcGetAuthorityState();\n\t\tif (!meta || meta.deletedAt || !policy) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t\treturn policy;\n\t}\n\n\t/**\n\t * Whether a policy authorises an account to read or write. `repo` is\n\t * absent for a read with no delegation token, which a policy authorises\n\t * only if it does not gate on the account. The authority always passes\n\t * under every policy: it alone can reconfigure the space, so it must not\n\t * be able to lock itself out.\n\t *\n\t * A managing app that can't be reached throws UpstreamFailure rather\n\t * than denying: denying would read as a loss of access, withdrawing a\n\t * syncer's registration and making a repo host drop its notification.\n\t */\n\tasync function authorizeRepo(params: {\n\t\tpolicy: SpacePolicy;\n\t\tref: SpaceRef;\n\t\trepo: string | undefined;\n\t\taccess: \"read\" | \"write\";\n\t\tclientId?: string;\n\t\tstub: SpaceStub;\n\t}): Promise<boolean> {\n\t\tconst { policy, ref, repo, access, clientId, stub } = params;\n\t\tif (repo === ref.authority) return true;\n\t\tswitch (policy.$type) {\n\t\t\tcase PERSONALSPACE_POLICY:\n\t\t\t\treturn false;\n\t\t\tcase MEMBERSPACE_POLICY: {\n\t\t\t\tif (access === \"read\" && policy.publicRead) return true;\n\t\t\t\tif (!repo) return false;\n\t\t\t\tconst member = await stub.rpcGetMember(repo);\n\t\t\t\tif (access === \"read\") return member?.read ?? false;\n\t\t\t\t// A member without write access stays excluded even under\n\t\t\t\t// publicWrite.\n\t\t\t\tif (member) return member.write;\n\t\t\t\treturn policy.publicWrite;\n\t\t\t}\n\t\t\tcase MANAGEDSPACE_POLICY:\n\t\t\t\treturn (await checkAccess(policy.managingApp, ref, repo, clientId))[\n\t\t\t\t\taccess\n\t\t\t\t];\n\t\t}\n\t}\n\n\t/** Ask a managed space's managing app for an account's access. */\n\tasync function checkAccess(\n\t\tmanagingApp: string,\n\t\tref: SpaceRef,\n\t\trepo: string | undefined,\n\t\tclientId: string | undefined,\n\t): Promise<{ read: boolean; write: boolean }> {\n\t\ttry {\n\t\t\tconst endpoint = await host.resolveServiceEndpoint(managingApp);\n\t\t\tif (!endpoint) throw new Error(\"could not resolve the managing app\");\n\t\t\tconst token = await createServiceJwt(\n\t\t\t\t{ iss: host.operatorDid, aud: managingApp, lxm: CHECK_ACCESS_LXM },\n\t\t\t\tawait host.getKeypair(),\n\t\t\t);\n\t\t\tconst url = new URL(`${endpoint}/xrpc/${CHECK_ACCESS_LXM}`);\n\t\t\turl.searchParams.set(\"space\", ref.uri);\n\t\t\tif (repo) url.searchParams.set(\"repo\", repo);\n\t\t\tif (clientId) url.searchParams.set(\"clientId\", clientId);\n\t\t\t// No redirects: the endpoint comes from a DID document, and a\n\t\t\t// 3xx answer is a failure like any other.\n\t\t\tconst res = await doFetch(url.toString(), {\n\t\t\t\theaders: { Authorization: `Bearer ${token}` },\n\t\t\t\tredirect: \"manual\",\n\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (!res.ok) throw new Error(`checkAccess answered ${res.status}`);\n\t\t\tconst body = (await res.json()) as { read?: unknown; write?: unknown };\n\t\t\tif (typeof body.read !== \"boolean\" || typeof body.write !== \"boolean\") {\n\t\t\t\tthrow new Error(\"checkAccess answered without read and write\");\n\t\t\t}\n\t\t\treturn { read: body.read, write: body.write };\n\t\t} catch (err) {\n\t\t\tconsole.warn(`managing app check for ${ref.uri} failed:`, err);\n\t\t\tthrow new SpaceError(\"UpstreamFailure\", \"Managing app did not answer\");\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the space DO exists for a write. The first write into a foreign\n\t * space registers it `pending` in the index, initialises the DO as repo\n\t * host, then activates the entry. The operator's own spaces must already\n\t * exist: a write must neither conjure an ungoverned space nor revive a\n\t * deleted one.\n\t */\n\tasync function ensureSpaceForWrite(\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t): Promise<void> {\n\t\tconst meta = await stub.rpcGetMeta();\n\t\tif (meta && !meta.deletedAt) return;\n\t\tif (ref.authority === host.operatorDid) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpaceNotFound\",\n\t\t\t\t`Space not found: ${ref.uri}. Create it with com.atproto.space.createSpace.`,\n\t\t\t);\n\t\t}\n\t\tconst index = host.getIndexDO();\n\t\tawait index.rpcRegister({\n\t\t\turi: ref.uri,\n\t\t\tauthority: ref.authority,\n\t\t\ttype: ref.type,\n\t\t\tskey: ref.skey,\n\t\t\tisAuthority: false,\n\t\t});\n\t\tawait stub.rpcInit({\n\t\t\turi: ref.uri,\n\t\t\tauthority: ref.authority,\n\t\t\ttype: ref.type,\n\t\t\tskey: ref.skey,\n\t\t\tisAuthority: false,\n\t\t});\n\t\tawait index.rpcActivate(ref.uri);\n\t}\n\n\t/**\n\t * Promote staged blobs to the space's R2 prefix. Runs before the DO\n\t * commit so nothing reacting to the commit sees a 404. Idempotent per\n\t * CID; CIDs that are neither staged nor at the destination are skipped.\n\t */\n\tasync function promoteSpaceBlobs(\n\t\tref: SpaceRef,\n\t\tblobCids: string[],\n\t): Promise<string[]> {\n\t\tconst missing: string[] = [];\n\t\tif (!host.blobs || blobCids.length === 0) return missing;\n\t\tawait Promise.all(\n\t\t\tblobCids.map(async (cid) => {\n\t\t\t\tconst present = await promoteStagedBlobToSpace(\n\t\t\t\t\thost.blobs!,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\tref.uri,\n\t\t\t\t\tcid,\n\t\t\t\t);\n\t\t\t\tif (!present) missing.push(cid);\n\t\t\t}),\n\t\t);\n\t\treturn missing;\n\t}\n\n\t/**\n\t * After a commit: the authority sequences its own update into the writer\n\t * set, which queues it for registered syncers; a repo host in a foreign\n\t * space delivers its latest state to the authority, immediately,\n\t * persisting a retryable failure for the DO's alarm to retry for up to\n\t * 24 hours. Retries coalesce, so only the newest revision is pending.\n\t */\n\tasync function postWrite(\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t\tcommit: RepoCommitResult,\n\t): Promise<void> {\n\t\tif (ref.authority === host.operatorDid) {\n\t\t\tawait stub.rpcRecordWriter(host.operatorDid, commit.rev, commit.data);\n\t\t\treturn;\n\t\t}\n\t\tconst body = {\n\t\t\tspace: ref.uri,\n\t\t\trepo: host.operatorDid,\n\t\t\trepoRev: commit.rev,\n\t\t\tdata: bytesToJson(commit.data),\n\t\t};\n\t\tconst aud = spaceHostAud(ref.authority as `did:${string}:${string}`);\n\t\tconst endpoint = await host.resolveServiceEndpoint(aud).catch(() => null);\n\t\tif (!endpoint) {\n\t\t\tconsole.warn(`notifyRepoUpdate: no endpoint for ${ref.authority}`);\n\t\t\treturn;\n\t\t}\n\t\tconst retry: NotifyItem = {\n\t\t\tservice: aud,\n\t\t\tendpoint,\n\t\t\tlxm: NOTIFY_REPO_UPDATE_LXM,\n\t\t\tbody,\n\t\t\tcoalesceKey: NOTIFY_REPO_UPDATE_COALESCE_KEY,\n\t\t\tdeadline: Date.now() + NOTIFY_WRITE_RETRY_MS,\n\t\t\tpolicy: \"repo\",\n\t\t\tauth: \"service\",\n\t\t};\n\t\ttry {\n\t\t\tconst token = await createServiceJwt(\n\t\t\t\t{ iss: host.operatorDid, aud, lxm: NOTIFY_REPO_UPDATE_LXM },\n\t\t\t\tawait host.getKeypair(),\n\t\t\t);\n\t\t\tconst res = await doFetch(`${endpoint}/xrpc/${NOTIFY_REPO_UPDATE_LXM}`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t// Not re-POSTed elsewhere with service auth: a 3xx is refused.\n\t\t\t\tredirect: \"manual\",\n\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (res.ok || !isRetryableStatus(res.status)) {\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`notifyRepoUpdate to ${ref.authority} refused: ${res.status}; not retrying`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait stub.rpcClearNotify(NOTIFY_REPO_UPDATE_COALESCE_KEY);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.warn(\n\t\t\t\t`notifyRepoUpdate to ${ref.authority} failed: ${res.status}`,\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tconsole.warn(`notifyRepoUpdate to ${ref.authority} errored:`, err);\n\t\t}\n\t\tawait stub.rpcEnqueueNotify([retry], { delayMs: NOTIFY_BACKOFF_BASE_MS });\n\t}\n\n\tinterface WriteInput {\n\t\taction: \"create\" | \"update\" | \"delete\";\n\t\tcollection: string;\n\t\trkey?: string;\n\t\tvalue?: unknown;\n\t}\n\n\t/**\n\t * Common write pipeline for createRecord/putRecord/deleteRecord and\n\t * applyWrites: validate, prepare bytes and CIDs, promote blobs, ensure\n\t * the space DO, apply the batch, notify in the background.\n\t */\n\tasync function runWrites(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\tsession: SpaceSessionAuth,\n\t\twrites: WriteInput[],\n\t\tvalidate: boolean | undefined,\n\t): Promise<\n\t\t| Response\n\t\t| {\n\t\t\t\trev: string;\n\t\t\t\tresults: Array<{\n\t\t\t\t\taction: string;\n\t\t\t\t\tcollection: string;\n\t\t\t\t\trkey: string;\n\t\t\t\t\tcid: string | null;\n\t\t\t\t\tvalidationStatus?: string;\n\t\t\t\t}>;\n\t\t }\n\t> {\n\t\tconst prepared: PreparedSpaceWrite[] = [];\n\t\tconst statuses: Array<string | undefined> = [];\n\t\tconst blobCids = new Set<string>();\n\n\t\tfor (const write of writes) {\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertNotPublishedCollection(write.collection);\n\n\t\t\tif (write.action === \"delete\") {\n\t\t\t\tprepared.push({\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey!,\n\t\t\t\t});\n\t\t\t\tstatuses.push(undefined);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst rkey = write.rkey ?? tidNow();\n\t\t\tlet validated;\n\t\t\ttry {\n\t\t\t\tvalidated = host.validateRecord({\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trecord: write.value,\n\t\t\t\t\trkey,\n\t\t\t\t\tvalidate,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"InvalidRecord\",\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst preparedRecord = await prepareRecord(validated.record);\n\t\t\tif (preparedRecord.bytes.length > MAX_SPACE_RECORD_BYTES) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`Record exceeds the maximum space record size of ${MAX_SPACE_RECORD_BYTES} bytes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const cid of preparedRecord.blobCids) blobCids.add(cid);\n\t\t\tprepared.push({\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t\trkey,\n\t\t\t\tcid: preparedRecord.cid,\n\t\t\t\tbytes: preparedRecord.bytes,\n\t\t\t\tblobCids: preparedRecord.blobCids,\n\t\t\t});\n\t\t\tstatuses.push(validated.status);\n\t\t}\n\n\t\t// The copy completes before the DO commit is applied, so a relay or\n\t\t// syncer reacting to the commit never sees a 404.\n\t\tawait promoteSpaceBlobs(ref, Array.from(blobCids));\n\n\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\tawait ensureSpaceForWrite(ref, stub);\n\t\tconst result = await stub.rpcApplyWrites(prepared);\n\n\t\twaitUntil(c, postWrite(ref, stub, result));\n\n\t\treturn {\n\t\t\trev: result.rev,\n\t\t\tresults: result.results.map((r, i) => ({\n\t\t\t\t...r,\n\t\t\t\t...(statuses[i] !== undefined ? { validationStatus: statuses[i] } : {}),\n\t\t\t})),\n\t\t};\n\t}\n\n\t/** Notify after a configuration change that published to the repo. */\n\tfunction afterConfigCommit(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t\tcommit: RepoCommitResult | null,\n\t): void {\n\t\tif (commit) waitUntil(c, postWrite(ref, stub, commit));\n\t}\n\n\t// ---------------------------------------------------------------\n\t// Write endpoints (repo host, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.createRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\trecord?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"create\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t\tvalue: body.record,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tbody.validate,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\tconst write = result.results[0]!;\n\t\t\treturn c.json({\n\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\tref.uri,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t),\n\t\t\t\tcid: write.cid,\n\t\t\t\t...(write.validationStatus\n\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.putRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\trecord?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\trequireString(body.rkey, \"rkey\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\n\t\t\t// Upsert: the scope asserted is the operation actually performed.\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst meta = await stub.rpcGetMeta();\n\t\t\tconst exists =\n\t\t\t\tmeta && !meta.deletedAt\n\t\t\t\t\t? (await stub.rpcGetRecord(body.collection!, body.rkey!)) !== null\n\t\t\t\t\t: false;\n\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: exists ? \"update\" : \"create\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t\tvalue: body.record,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tbody.validate,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\tconst write = result.results[0]!;\n\t\t\treturn c.json({\n\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\tref.uri,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t),\n\t\t\t\tcid: write.cid,\n\t\t\t\t...(write.validationStatus\n\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.deleteRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\trequireString(body.rkey, \"rkey\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[{ action: \"delete\", collection: body.collection!, rkey: body.rkey }],\n\t\t\t\tundefined,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\t// Deleting an absent record succeeds: nothing committed, nothing\n\t\t\t// notified.\n\t\t\tif (parseSpaceErrorCode(err)?.code === \"RecordNotFound\") {\n\t\t\t\treturn c.json({});\n\t\t\t}\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.applyWrites\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\twrites?: Array<{\n\t\t\t\t\t$type?: string;\n\t\t\t\t\tcollection?: string;\n\t\t\t\t\trkey?: string;\n\t\t\t\t\tvalue?: unknown;\n\t\t\t\t}>;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\tif (!Array.isArray(body.writes)) {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"writes must be an array\");\n\t\t\t}\n\t\t\tif (body.writes.length > 200) {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"Too many writes. Max: 200\");\n\t\t\t}\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\n\t\t\tconst inputs: WriteInput[] = body.writes.map((write, i) => {\n\t\t\t\tconst action =\n\t\t\t\t\twrite.$type === \"com.atproto.space.applyWrites#create\"\n\t\t\t\t\t\t? (\"create\" as const)\n\t\t\t\t\t\t: write.$type === \"com.atproto.space.applyWrites#update\"\n\t\t\t\t\t\t\t? (\"update\" as const)\n\t\t\t\t\t\t\t: write.$type === \"com.atproto.space.applyWrites#delete\"\n\t\t\t\t\t\t\t\t? (\"delete\" as const)\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\tif (!action || !write.collection) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t`Write ${i}: unknown $type or missing collection`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (action !== \"create\" && !write.rkey) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t`Write ${i}: ${action} requires rkey`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\taction,\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\tvalue: write.value,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tconst result = await runWrites(c, ref, session, inputs, body.validate);\n\t\t\tif (result instanceof Response) return result;\n\t\t\treturn c.json({\n\t\t\t\tresults: result.results.map((write) => {\n\t\t\t\t\tif (write.action === \"delete\") {\n\t\t\t\t\t\treturn { $type: \"com.atproto.space.applyWrites#deleteResult\" };\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\t$type: `com.atproto.space.applyWrites#${write.action}Result`,\n\t\t\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\t\t\tref.uri,\n\t\t\t\t\t\t\thost.operatorDid,\n\t\t\t\t\t\t\twrite.collection,\n\t\t\t\t\t\t\twrite.rkey,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tcid: write.cid,\n\t\t\t\t\t\t...(write.validationStatus\n\t\t\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.clearRecords\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; repo?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.repo, \"repo\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tif (body.repo !== session.did) {\n\t\t\t\tthrow new SpaceError(\"Forbidden\", \"repo must match authenticated user\");\n\t\t\t}\n\t\t\trequireRepoParam(body.repo);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst meta = await stub.rpcGetMeta();\n\t\t\tif (!meta || meta.deletedAt) return c.json({});\n\n\t\t\t// In the authority's own repo the published policy and member\n\t\t\t// records are the host's copy of the space's configuration, not\n\t\t\t// the account's records, so they stay, and keeping them takes no\n\t\t\t// grant.\n\t\t\tconst keep =\n\t\t\t\tref.authority === host.operatorDid ? [...PUBLISHED_COLLECTIONS] : [];\n\t\t\tfor (const collection of await stub.rpcListCollections()) {\n\t\t\t\tif (keep.includes(collection)) continue;\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\t\t\tconst commit = await stub.rpcClearRecords(keep);\n\t\t\tif (commit) waitUntil(c, postWrite(ref, stub, commit));\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.importRepo\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst bytes = await readBody(c);\n\n\t\t\tlet records: ImportedRecord[];\n\t\t\tlet space: string;\n\t\t\tlet repo: string;\n\t\t\ttry {\n\t\t\t\tconst archive = await readRepoStar([bytes]);\n\t\t\t\ttry {\n\t\t\t\t\tspace = archive.commit.space;\n\t\t\t\t\trepo = archive.commit.repo;\n\t\t\t\t\trecords = [];\n\t\t\t\t\tfor await (const record of archive.records) {\n\t\t\t\t\t\t// Stored re-encoded, as any other write is. A record that\n\t\t\t\t\t\t// wasn't canonical DRISL in the archive would no longer match\n\t\t\t\t\t\t// its cid, nor the commit data.\n\t\t\t\t\t\tconst encoded = encode(record.record as LexValue);\n\t\t\t\t\t\tconst cid = await cidForCbor(encoded);\n\t\t\t\t\t\tif (!cid.equals(record.cid)) {\n\t\t\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t\t\t`Invalid STAR: record is not canonical DRISL at ${record.collection}/${record.rkey}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst blobCids: string[] = [];\n\t\t\t\t\t\tfor (const ref of enumBlobRefs(record.record as LexValue, {\n\t\t\t\t\t\t\tstrict: false,\n\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\tblobCids.push(getBlobCidString(ref));\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecords.push({\n\t\t\t\t\t\t\tcollection: record.collection,\n\t\t\t\t\t\t\trkey: record.rkey,\n\t\t\t\t\t\t\tcid: cid.toString(),\n\t\t\t\t\t\t\tbytes: encoded,\n\t\t\t\t\t\t\tblobCids,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tawait archive[Symbol.asyncDispose]();\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthrow invalidArchive(err, \"InvalidRepoFile\");\n\t\t\t}\n\n\t\t\tif (repo !== host.operatorDid || repo !== session.did) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoMismatch\",\n\t\t\t\t\t\"Repo does not match the authenticated account\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst ref = requireSpaceUri(space);\n\t\t\t// Importing replaces the whole repo, so it takes full access to the\n\t\t\t// space: read, and every write on every collection (\"*\" matches\n\t\t\t// only a grant covering them all), as the reference requires.\n\t\t\tfor (const match of [\n\t\t\t\t{ action: \"read\" },\n\t\t\t\t{ action: \"create\", collection: \"*\" },\n\t\t\t\t{ action: \"update\", collection: \"*\" },\n\t\t\t\t{ action: \"delete\", collection: \"*\" },\n\t\t\t] as const) {\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\t...match,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tif (ref.authority === host.operatorDid) {\n\t\t\t\t// The authority's space must arrive first, via importSpaceMeta.\n\t\t\t\tawait requirePolicy(stub, ref);\n\t\t\t} else {\n\t\t\t\tawait ensureSpaceForWrite(ref, stub);\n\t\t\t}\n\t\t\tawait stub.rpcImportRepo(records);\n\n\t\t\t// Blobs are uploaded separately. Those already staged are promoted\n\t\t\t// now; the rest are claimed by uploadBlob when they arrive.\n\t\t\tconst missing = await promoteSpaceBlobs(\n\t\t\t\tref,\n\t\t\t\tArray.from(new Set(records.flatMap((r) => r.blobCids))),\n\t\t\t);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tawait host.getIndexDO().rpcAddPendingBlobs(ref.uri, missing);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Read and sync endpoints (credential or session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.get(\"/xrpc/com.atproto.space.getRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst collection = c.req.query(\"collection\");\n\t\t\tconst rkey = c.req.query(\"rkey\");\n\t\t\trequireString(collection, \"collection\");\n\t\t\trequireString(rkey, \"rkey\");\n\t\t\tconst mac = await readMac(c, auth, RECORD_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst record = await stub.rpcGetRecord(collection!, rkey!);\n\t\t\tconst uri = spaceRecordUri(ref.uri, host.operatorDid, collection!, rkey!);\n\t\t\tif (!record) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordNotFound\",\n\t\t\t\t\t`Could not locate record: ${uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{ uri, cid: record.cid, value: recordBytesToJson(record.bytes) },\n\t\t\t\t200,\n\t\t\t\trecordMacHeaders(mac, uri, record.cid),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRecords\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst collection = c.req.query(\"collection\");\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 50, 1000);\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\t\t\tconst after = parseRecordCursor(c.req.query(\"cursor\"));\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListRecords({\n\t\t\t\tcollection,\n\t\t\t\tlimit,\n\t\t\t\tafter,\n\t\t\t\texcludeValues,\n\t\t\t});\n\t\t\tconst records = page.records.map((record) => ({\n\t\t\t\tcollection: record.collection,\n\t\t\t\trkey: record.rkey,\n\t\t\t\tcid: record.cid,\n\t\t\t\t...(record.bytes\n\t\t\t\t\t? { value: recordBytesToJson(new Uint8Array(record.bytes)) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\tconst last = page.records[page.records.length - 1];\n\t\t\treturn c.json({\n\t\t\t\trecords,\n\t\t\t\t...(page.hasMore && last\n\t\t\t\t\t? { cursor: `${last.collection}/${last.rkey}` }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getLatestCommit\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst state = await stub.rpcGetRepoState();\n\t\t\tif (!state) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: { setHash: new Uint8Array(state.setHash), rev: state.rev },\n\t\t\t});\n\t\t\treturn c.json(\n\t\t\t\t{ commit: commitToJson(commit) },\n\t\t\t\t200,\n\t\t\t\tcommitMacHeaders(mac, commit),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRepoOps\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\tconst since = c.req.query(\"since\");\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\t\t\tconst after = parseOpsCursor(c.req.query(\"cursor\"));\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListRepoOps({\n\t\t\t\tsince,\n\t\t\t\tafter,\n\t\t\t\tlimit,\n\t\t\t\texcludeValues,\n\t\t\t});\n\t\t\tconst ops = page.ops.map((op) => ({\n\t\t\t\trev: op.rev,\n\t\t\t\tcollection: op.collection,\n\t\t\t\trkey: op.rkey,\n\t\t\t\tcid: op.cid,\n\t\t\t\tprev: op.prev,\n\t\t\t\t...(op.bytes\n\t\t\t\t\t? { value: recordBytesToJson(new Uint8Array(op.bytes)) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\t// Never written: no commit to answer with.\n\t\t\tif (!page.head) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The commit, with its MAC, is on every page. A full page carries a\n\t\t\t// cursor, so the last page may be empty.\n\t\t\tconst last = page.ops[page.ops.length - 1];\n\t\t\tconst cursor =\n\t\t\t\tlast && page.ops.length === limit\n\t\t\t\t\t? `${last.rev}/${last.idx}`\n\t\t\t\t\t: undefined;\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: {\n\t\t\t\t\tsetHash: new Uint8Array(page.head.setHash),\n\t\t\t\t\trev: page.head.rev,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn c.json(\n\t\t\t\t{ ops, commit: commitToJson(commit), ...(cursor ? { cursor } : {}) },\n\t\t\t\t200,\n\t\t\t\tcommitMacHeaders(mac, commit),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getRepo\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\n\t\t\t// The archive streams page by page. Each page reports the repo\n\t\t\t// state it was read at; a page from a later state means a write\n\t\t\t// landed mid-export, and the stream errors rather than serve\n\t\t\t// records that don't match the commit. The syncer's verification\n\t\t\t// would refuse such an archive anyway; failing loudly lets it\n\t\t\t// retry at once.\n\t\t\tconst PAGE = 500;\n\t\t\tconst first = await stub.rpcListRecordsByPath({ limit: PAGE });\n\t\t\tconst state = first.state;\n\t\t\tif (!state) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: { setHash: new Uint8Array(state.setHash), rev: state.rev },\n\t\t\t});\n\t\t\tasync function* records() {\n\t\t\t\tlet page = first;\n\t\t\t\tfor (;;) {\n\t\t\t\t\tfor (const record of page.records) {\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\tcollection: record.collection as never,\n\t\t\t\t\t\t\trkey: record.rkey as never,\n\t\t\t\t\t\t\tbytes: new Uint8Array(record.bytes),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst last = page.records[page.records.length - 1];\n\t\t\t\t\tif (!page.hasMore || !last) return;\n\t\t\t\t\tpage = await stub.rpcListRecordsByPath({\n\t\t\t\t\t\tafterPath: `${last.collection}/${last.rkey}`,\n\t\t\t\t\t\tlimit: PAGE,\n\t\t\t\t\t});\n\t\t\t\t\tif (page.state?.rev !== state!.rev) {\n\t\t\t\t\t\tthrow new Error(\"The repo changed during export; retry getRepo\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst star = writeRepoStar(\n\t\t\t\tcommit as Parameters<typeof writeRepoStar>[0],\n\t\t\t\trecords(),\n\t\t\t);\n\t\t\treturn c.body(asyncIterableToStream(star), 200, {\n\t\t\t\t\"Content-Type\": STAR_CONTENT_TYPE,\n\t\t\t\t...commitMacHeaders(mac, commit),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listBlobs\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 500, 1000);\n\t\t\tconst afterCid = c.req.query(\"cursor\");\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListBlobs({ limit, afterCid });\n\t\t\tconst last = page.cids[page.cids.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tcids: page.cids,\n\t\t\t\t...(page.hasMore && last ? { cursor: last } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getBlob\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst cid = c.req.query(\"cid\");\n\t\t\trequireString(cid, \"cid\");\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\t// Refuse before touching the blobstore: do not reveal whether an\n\t\t\t// unreferenced blob exists.\n\t\t\tif (!(await stub.rpcHasSpaceBlob(cid!))) {\n\t\t\t\tthrow new SpaceError(\"BlobNotFound\", `Blob not found: ${cid}`);\n\t\t\t}\n\t\t\tif (!host.blobs) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"ServiceUnavailable\",\n\t\t\t\t\t\tmessage: \"Blob storage is not configured\",\n\t\t\t\t\t},\n\t\t\t\t\t503,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = spaceBlobKey(host.operatorDid, await spaceId(ref.uri), cid!);\n\t\t\tlet blob = await host.blobs.get(key);\n\t\t\tif (!blob) {\n\t\t\t\t// Referenced but never promoted (an imported record whose blob\n\t\t\t\t// arrived through another path): promote on first read.\n\t\t\t\tif (\n\t\t\t\t\tawait promoteStagedBlobToSpace(\n\t\t\t\t\t\thost.blobs,\n\t\t\t\t\t\thost.operatorDid,\n\t\t\t\t\t\tref.uri,\n\t\t\t\t\t\tcid!,\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tblob = await host.blobs.get(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!blob) {\n\t\t\t\tthrow new SpaceError(\"BlobNotFound\", `Blob not found: ${cid}`);\n\t\t\t}\n\t\t\treturn new Response(blob.body, {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\":\n\t\t\t\t\t\tblob.httpMetadata?.contentType ?? \"application/octet-stream\",\n\t\t\t\t\t\"Content-Length\": blob.size.toString(),\n\t\t\t\t\t// A shared cache in front of the PDS must never store a\n\t\t\t\t\t// response whose authorisation was per-credential.\n\t\t\t\t\t\"Cache-Control\": \"private, no-store\",\n\t\t\t\t\tVary: \"Authorization\",\n\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t\t\"Content-Disposition\": `attachment; filename=\"${cid}\"`,\n\t\t\t\t\t\"Content-Security-Policy\": \"default-src 'none'; sandbox\",\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Space host endpoints (authority role)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.authorizeSpaceSync\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\tcredentialKey?: string;\n\t\t\t\tdelegationToken?: string;\n\t\t\t\tclientAttestation?: string;\n\t\t\t\tnotify?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.credentialKey, \"credentialKey\");\n\t\t\tif (!isP256DidKey(body.credentialKey!)) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"credentialKey must be a P-256 did:key\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst notify =\n\t\t\t\tbody.notify === undefined ? undefined : parseNotify(body.notify);\n\n\t\t\t// Before anything touches the space DO: a space this host doesn't\n\t\t\t// govern must not get one created for it by a well-formed request.\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst { meta, policy } = await stub.rpcGetAuthorityState();\n\t\t\t// The durable signal that a space is gone: a syncer that missed\n\t\t\t// its deletion notice learns it here, the next time it\n\t\t\t// reauthorises, whatever the request's authorisation.\n\t\t\tif (meta?.deletedAt) {\n\t\t\t\tthrow new SpaceError(\"SpaceDeleted\", `Space deleted: ${ref.uri}`);\n\t\t\t}\n\n\t\t\t// Absent when the request carries no delegation token, which only\n\t\t\t// a space that does not gate on the account accepts.\n\t\t\tlet repo: string | undefined;\n\t\t\tif (body.delegationToken) {\n\t\t\t\t({ userDid: repo } = await verifyDelegationToken(\n\t\t\t\t\tbody.delegationToken,\n\t\t\t\t\tref,\n\t\t\t\t\t{\n\t\t\t\t\t\tgetSigningKey: host.getSigningKey,\n\t\t\t\t\t\tcheckReplay: (kind, key, exp) =>\n\t\t\t\t\t\t\tstub.rpcCheckReplay(kind, key, exp),\n\t\t\t\t\t},\n\t\t\t\t));\n\t\t\t}\n\n\t\t\tlet clientId: string | undefined;\n\t\t\tif (body.clientAttestation) {\n\t\t\t\tclientId = await verifyClientAttestation(body.clientAttestation, {\n\t\t\t\t\texpectedAud: spaceHostAud(ref.authority as `did:${string}:${string}`),\n\t\t\t\t\t// Checked pre-verification inside, so a client the space could\n\t\t\t\t\t// never authorise never triggers network I/O.\n\t\t\t\t\tallowedClientIds:\n\t\t\t\t\t\tpolicy?.$type === MEMBERSPACE_POLICY\n\t\t\t\t\t\t\t? policy.allowedApps\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tcheckReplay: (kind, key, exp) => stub.rpcCheckReplay(kind, key, exp),\n\t\t\t\t\tfetch: host.outboundFetch,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!meta || !policy) {\n\t\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// The account goes first, and one the policy refuses is answered\n\t\t\t\t// as though the space does not exist, so that a refusal\n\t\t\t\t// discloses nothing to someone without access to it.\n\t\t\t\tconst authorized = await authorizeRepo({\n\t\t\t\t\tpolicy,\n\t\t\t\t\tref,\n\t\t\t\t\trepo,\n\t\t\t\t\taccess: \"read\",\n\t\t\t\t\tclientId,\n\t\t\t\t\tstub,\n\t\t\t\t});\n\t\t\t\tif (!authorized) {\n\t\t\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t\t\t}\n\t\t\t\tif (!isAppAuthorized(policy, clientId)) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"AppNotAuthorized\",\n\t\t\t\t\t\t\"Application not authorized for this space\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// A refusal withdraws the registration the request carries, so a\n\t\t\t\t// syncer that has lost access stops being notified. A failure to\n\t\t\t\t// decide, such as an unreachable managing app, is not a refusal.\n\t\t\t\tif (notify && parseSpaceErrorCode(err)?.code !== \"UpstreamFailure\") {\n\t\t\t\t\tawait stub.rpcRemoveNotifyRegistration(notify);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\tif (notify && !(await stub.rpcGetNotifyRegistration(notify))) {\n\t\t\t\tawait confirmRegistration(ref, notify);\n\t\t\t}\n\n\t\t\tconst credential = await createSpaceCredential({\n\t\t\t\tiss: host.operatorDid as `did:${string}:${string}`,\n\t\t\t\tsub: ref.uri as never,\n\t\t\t\tkeyId: body.credentialKey as `did:${string}:${string}`,\n\t\t\t\tkeypair: (await host.getKeypair()) as never,\n\t\t\t});\n\n\t\t\tif (notify) {\n\t\t\t\t// Renewed by each authorisation, to the credential's expiry, so a\n\t\t\t\t// syncer that keeps reauthorising stays registered.\n\t\t\t\tconst { exp } = parseSpaceToken(\"credential\", credential).payload;\n\t\t\t\tawait stub.rpcPutNotifyRegistration(notify, exp * 1000);\n\t\t\t}\n\t\t\t// Read after registering, so any update past this revision is\n\t\t\t// notified.\n\t\t\tconst spaceRev = await stub.rpcGetSpaceRev();\n\t\t\treturn c.json({ credential, ...(spaceRev ? { spaceRev } : {}) });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listWriters\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tawait credentialAuth(c, ref);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requirePolicy(stub, ref);\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 500, 1000);\n\t\t\tconst writers = await stub.rpcListWriters({\n\t\t\t\tlimit,\n\t\t\t\tcursor: c.req.query(\"cursor\") || undefined,\n\t\t\t});\n\t\t\tconst last = writers[writers.length - 1];\n\t\t\treturn c.json({\n\t\t\t\trepos: writers.map((writer) =>\n\t\t\t\t\twriter.removed\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t$type: \"com.atproto.space.defs#repoRemoved\",\n\t\t\t\t\t\t\t\trepo: writer.did,\n\t\t\t\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t$type: \"com.atproto.space.defs#repoWrite\",\n\t\t\t\t\t\t\t\trepo: writer.did,\n\t\t\t\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\t\t\t\tdata: bytesToJson(new Uint8Array(writer.data)),\n\t\t\t\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\t// Nonempty pages carry a cursor and empty pages omit it.\n\t\t\t\t...(last ? { cursor: last.spaceRev } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.notifyRepoUpdate\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\trepoRev?: string;\n\t\t\t\tdata?: { $bytes?: string };\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.repo, \"repo\");\n\t\t\trequireString(body.repoRev, \"repoRev\");\n\t\t\tif (typeof body.data?.$bytes !== \"string\") {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"Missing data bytes\");\n\t\t\t}\n\n\t\t\tconst serviceAuth = await requireServiceAuth(c, NOTIFY_REPO_UPDATE_LXM);\n\t\t\tif (serviceAuth instanceof Response) return serviceAuth;\n\t\t\t// iss is the signer, so requiring it to match keeps a PDS from\n\t\t\t// notifying on another account's behalf.\n\t\t\tif (serviceAuth.iss !== body.repo) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"notifyRepoUpdate iss does not match the repo\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tserviceAuth.aud !== ref.authority &&\n\t\t\t\tserviceAuth.aud !==\n\t\t\t\t\tspaceHostAud(ref.authority as `did:${string}:${string}`)\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"notifyRepoUpdate aud does not match the space authority\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tassertSpaceHost(ref);\n\t\t\tlet revMs: number;\n\t\t\ttry {\n\t\t\t\trevMs = tidTimestampMs(body.repoRev!);\n\t\t\t} catch {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"repoRev must be a TID\");\n\t\t\t}\n\t\t\tif (revMs > Date.now() + MAX_REV_CLOCK_SKEW_MS) {\n\t\t\t\tthrow new SpaceError(\"FutureRev\", \"Repo revision is in the future\");\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst policy = await requirePolicy(stub, ref);\n\t\t\t// The same account perimeter used when minting credentials. The\n\t\t\t// notification comes from a PDS rather than an app, so there is no\n\t\t\t// attestation. An unreachable managing app is an UpstreamFailure,\n\t\t\t// which the repo host retries.\n\t\t\tconst authorized = await authorizeRepo({\n\t\t\t\tpolicy,\n\t\t\t\tref,\n\t\t\t\trepo: body.repo!,\n\t\t\t\taccess: \"write\",\n\t\t\t\tstub,\n\t\t\t});\n\t\t\tif (!authorized) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Repo is not authorized to write to the space\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Sequenced, and queued for registered syncers, in one transaction.\n\t\t\t// A delayed or replayed notification with an older rev changes\n\t\t\t// nothing.\n\t\t\tawait stub.rpcRecordWriter(\n\t\t\t\tbody.repo!,\n\t\t\t\tbody.repoRev!,\n\t\t\t\tfromBase64(body.data.$bytes),\n\t\t\t);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.notifyCredentialsRevoked\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\tcredentials?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst credentials = body.credentials;\n\t\t\tif (\n\t\t\t\t!Array.isArray(credentials) ||\n\t\t\t\tcredentials.length < 1 ||\n\t\t\t\tcredentials.length > 100 ||\n\t\t\t\tcredentials.some((jti) => typeof jti !== \"string\" || jti.length === 0)\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"credentials must be 1 to 100 credential jti strings\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst serviceAuth = await requireServiceAuth(c, CREDENTIALS_REVOKED_LXM);\n\t\t\tif (serviceAuth instanceof Response) return serviceAuth;\n\t\t\tif (serviceAuth.iss !== ref.authority) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Revocation issuer is not the space authority\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Addressed to the repo DID, which here is always the operator.\n\t\t\tif (serviceAuth.aud !== host.operatorDid) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Revocation audience does not match a repo hosted here\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait host\n\t\t\t\t.getSpaceDO(ref.uri)\n\t\t\t\t.rpcRevokeCredentials(\n\t\t\t\t\tcredentials as string[],\n\t\t\t\t\tMath.floor(Date.now() / 1000) + REVOCATION_TTL_SEC,\n\t\t\t\t);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Space management (authority role, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.createSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspaceType?: string;\n\t\t\t\tskey?: string;\n\t\t\t\tpolicy?: unknown;\n\t\t\t}>();\n\t\t\trequireString(body.spaceType, \"spaceType\");\n\t\t\tconst skey = body.skey ?? tidNow();\n\t\t\tconst ref = requireSpaceUri(\n\t\t\t\tformatSpaceUri(host.operatorDid, body.spaceType!, skey),\n\t\t\t);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: host.operatorDid,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"create\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst policy = normalizePolicy(body.policy);\n\n\t\t\t// Two-step creation: index entry `pending`, then the DO, then\n\t\t\t// `active`. Reads never depend on the index, so a crash between\n\t\t\t// steps leaves only a pending entry for the alarm to reap.\n\t\t\tconst index = host.getIndexDO();\n\t\t\tawait index.rpcRegister({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t});\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcInit({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t\tpolicy,\n\t\t\t});\n\t\t\tawait index.rpcActivate(ref.uri);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({ space: ref.uri });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.updateSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; policy?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst policy = normalizePolicy(body.policy);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcUpdatePolicy(policy);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.deleteSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"delete\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\t// Credential issuance stops with the tombstone, and every registered\n\t\t\t// syncer, lapsed or not, is queued a deletion notice delivered\n\t\t\t// reliably for 72 hours. Then reap the blob prefix.\n\t\t\tawait stub.rpcDeleteSpace();\n\t\t\tawait host.getIndexDO().rpcMarkDeleted(ref.uri);\n\t\t\tif (host.blobs) {\n\t\t\t\twaitUntil(\n\t\t\t\t\tc,\n\t\t\t\t\tdeleteR2Prefix(\n\t\t\t\t\t\thost.blobs,\n\t\t\t\t\t\tspaceBlobPrefix(host.operatorDid, await spaceId(ref.uri)),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst policy = await requirePolicy(host.getSpaceDO(ref.uri), ref);\n\t\t\treturn c.json({ space: ref.uri, policy });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.removeWriter\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; repo?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireDid(body.repo, \"repo\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\t// Sequenced and announced to syncers as a repoRemoved.\n\t\t\tawait host.getSpaceDO(ref.uri).rpcRemoveWriter(body.repo!);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.exportSpaceMeta\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst exported = await host.getSpaceDO(ref.uri).rpcExportMeta();\n\t\t\tconst star = writeSpaceMetaStar({\n\t\t\t\tspace: ref.uri as never,\n\t\t\t\tpolicy: exported.policy as never,\n\t\t\t\tpolicyState: exported.members.map((member) => ({\n\t\t\t\t\tkey: `${MEMBER_COLLECTION}/${didToRecordKey(member.did)}`,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\t$type: MEMBER_COLLECTION,\n\t\t\t\t\t\tread: member.read,\n\t\t\t\t\t\twrite: member.write,\n\t\t\t\t\t},\n\t\t\t\t})),\n\t\t\t\twriters: exported.writers.map((writer) => ({\n\t\t\t\t\tdid: writer.did as never,\n\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\tdata: new Uint8Array(writer.data),\n\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t})),\n\t\t\t});\n\t\t\treturn c.body(asyncIterableToStream(star), 200, {\n\t\t\t\t\"Content-Type\": STAR_CONTENT_TYPE,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.importSpaceMeta\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst bytes = await readBody(c);\n\t\t\tlet archive;\n\t\t\ttry {\n\t\t\t\tarchive = await readSpaceMetaStar([bytes]);\n\t\t\t} catch (err) {\n\t\t\t\tthrow invalidArchive(err, \"InvalidSpaceMeta\");\n\t\t\t}\n\t\t\tconst ref = requireSpaceUri(archive.space);\n\t\t\t// Importing both creates the space here and sets its configuration.\n\t\t\tfor (const manage of [\"create\", \"update\"] as const) {\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\tmanage,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\t\t\tif (ref.authority !== session.did || ref.authority !== host.operatorDid) {\n\t\t\t\tthrow new SpaceError(\"NotAuthorized\", \"Not the space authority\");\n\t\t\t}\n\t\t\tconst policy = normalizePolicy(archive.policy);\n\t\t\tconst members = parsePolicyState(policy, archive.policyState);\n\n\t\t\tconst index = host.getIndexDO();\n\t\t\tawait index.rpcRegister({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t});\n\t\t\tawait host.getSpaceDO(ref.uri).rpcImportMeta({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tpolicy,\n\t\t\t\tmembers,\n\t\t\t\twriters: archive.writers.map((writer) => ({\n\t\t\t\t\tdid: writer.did,\n\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\tdata: writer.data,\n\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\tremoved: false,\n\t\t\t\t})),\n\t\t\t});\n\t\t\tawait index.rpcActivate(ref.uri);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listSpaces\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst type = c.req.query(\"spaceType\") || undefined;\n\t\t\tconst authority = c.req.query(\"spaceDid\") || undefined;\n\t\t\t// No one space to check against, so the filters are the target:\n\t\t\t// an unfiltered listing needs a wildcard grant. It lists only the\n\t\t\t// caller's own spaces, so read_self is the grant that fits.\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: type ?? \"*\",\n\t\t\t\tauthority: authority ?? \"*\",\n\t\t\t\tskey: \"*\",\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 50, 100);\n\t\t\tconst cursor = c.req.query(\"cursor\") || undefined;\n\t\t\tif (cursor && !parseSpaceUri(cursor)) {\n\t\t\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t\t\t}\n\t\t\tconst page = await host.getIndexDO().rpcList({\n\t\t\t\ttype,\n\t\t\t\tauthority,\n\t\t\t\tstate: \"active\",\n\t\t\t\tlimit,\n\t\t\t\tafterUri: cursor,\n\t\t\t});\n\t\t\t// The caller's repo state in each space, and the space's revision\n\t\t\t// where the caller is its authority.\n\t\t\tconst spaces = await Promise.all(\n\t\t\t\tpage.spaces.map(async (space) => {\n\t\t\t\t\tconst view = await host.getSpaceDO(space.uri).rpcGetSpaceView();\n\t\t\t\t\treturn {\n\t\t\t\t\t\tspace: space.uri,\n\t\t\t\t\t\t...(view?.repoRev ? { repoRev: view.repoRev } : {}),\n\t\t\t\t\t\t...(view?.data\n\t\t\t\t\t\t\t? { data: bytesToJson(new Uint8Array(view.data)) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(view?.spaceRev ? { spaceRev: view.spaceRev } : {}),\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst last = page.spaces[page.spaces.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tspaces,\n\t\t\t\t...(page.hasMore && last ? { cursor: last.uri } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// memberspace (authority role, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.memberspace.putMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; members?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst members = parseMemberBatch(body.members);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcPutMembers(members);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.memberspace.removeMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; dids?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst dids = body.dids;\n\t\t\tif (\n\t\t\t\t!Array.isArray(dids) ||\n\t\t\t\tdids.length > MAX_MEMBER_BATCH ||\n\t\t\t\tdids.some((did) => typeof did !== \"string\" || !did.startsWith(\"did:\"))\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`dids must be an array of at most ${MAX_MEMBER_BATCH} DIDs`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcRemoveMembers(dids as string[]);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.memberspace.listMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\t// The cursor is the last member DID of the previous page.\n\t\t\tconst cursor = c.req.query(\"cursor\");\n\t\t\tif (cursor !== undefined && !isDid(cursor)) {\n\t\t\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t\t\t}\n\t\t\tconst page = await host.getSpaceDO(ref.uri).rpcListMembers({\n\t\t\t\tlimit,\n\t\t\t\tafterDid: cursor,\n\t\t\t});\n\t\t\tconst last = page.members[page.members.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tmembers: page.members.map((member) => ({\n\t\t\t\t\tdid: member.did,\n\t\t\t\t\tread: member.read,\n\t\t\t\t\twrite: member.write,\n\t\t\t\t})),\n\t\t\t\t...(page.hasMore && last ? { cursor: last.did } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Helpers that need the host\n\t// ---------------------------------------------------------------\n\n\t/**\n\t * Before registering a webhook, check it asked to be: the endpoint must\n\t * recognise the token as one it issued for this space and echo back a\n\t * random challenge. The endpoint is the requester's choice, so it is\n\t * fetched as untrusted: https only, no redirects, bounded in time.\n\t */\n\tasync function confirmRegistration(\n\t\tref: SpaceRef,\n\t\tnotify: NotifyRegistration,\n\t): Promise<void> {\n\t\tconst challenge = crypto.randomUUID();\n\t\ttry {\n\t\t\tconst res = await doFetch(\n\t\t\t\t`${notify.endpoint.replace(/\\/$/, \"\")}/xrpc/${CONFIRM_REGISTRATION_LXM}`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tspace: ref.uri,\n\t\t\t\t\t\ttoken: notify.token,\n\t\t\t\t\t\tchallenge,\n\t\t\t\t\t}),\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (res.ok) {\n\t\t\t\tconst body = (await res.json()) as { challenge?: unknown };\n\t\t\t\tif (body.challenge === challenge) return;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconsole.warn(`registration for ${ref.uri} not confirmed:`, err);\n\t\t}\n\t\tthrow new SpaceError(\n\t\t\t\"RegistrationNotConfirmed\",\n\t\t\t\"Notify endpoint did not confirm the registration\",\n\t\t);\n\t}\n\n\t/** Service auth for inbound notifications; a Response on failure. */\n\tasync function requireServiceAuth(\n\t\tc: Context,\n\t\tlxm: string,\n\t): Promise<{ iss: string; aud: string } | Response> {\n\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: \"AuthenticationRequired\", message: \"Service auth required\" },\n\t\t\t\t401,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\treturn await host.verifyServiceJwt(authHeader.slice(7), lxm);\n\t\t} catch (err) {\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"AuthenticationRequired\",\n\t\t\t\t\tmessage: err instanceof Error ? err.message : \"Invalid service auth\",\n\t\t\t\t},\n\t\t\t\t401,\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction isOwnAudience(aud: string): boolean {\n\t\treturn aud === host.operatorDid || aud.startsWith(`${host.operatorDid}#`);\n\t}\n\n\t/**\n\t * A repo exists in a space once the operator has written into it (or\n\t * the space was created here). RepoNotFound deliberately covers both\n\t * \"no such repo\" and \"space unknown to this host\".\n\t */\n\tasync function requireRepoExists(\n\t\tstub: SpaceStub,\n\t\tref: SpaceRef,\n\t): Promise<void> {\n\t\tconst meta = await stub.rpcGetMeta();\n\t\tif (meta?.deletedAt) {\n\t\t\t// After deletion, reads against the space fail with SpaceNotFound.\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoNotFound\",\n\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn app;\n}\n\n// ---------------------------------------------------------------------\n// Small parsing helpers\n// ---------------------------------------------------------------------\n\nfunction requireString(value: unknown, name: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`Missing required parameter: ${name}`,\n\t\t);\n\t}\n}\n\n/**\n * An authorizeSpaceSync `notify`: an https base URL the space host calls\n * XRPC methods against, and the opaque token that authenticates them.\n */\nfunction parseNotify(input: unknown): NotifyRegistration {\n\tconst notify = input as { endpoint?: unknown; token?: unknown } | null;\n\tconst endpoint = notify?.endpoint;\n\tconst token = notify?.token;\n\tif (typeof endpoint !== \"string\" || typeof token !== \"string\") {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t\"notify requires an endpoint and a token\",\n\t\t);\n\t}\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(endpoint);\n\t} catch {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"notify endpoint must be a URL\");\n\t}\n\tif (url.protocol !== \"https:\" || url.username || url.password) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t\"notify endpoint must be a plain https URL\",\n\t\t);\n\t}\n\tif (token.length === 0 || token.length > MAX_NOTIFY_TOKEN_LENGTH) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`notify token must be 1 to ${MAX_NOTIFY_TOKEN_LENGTH} characters`,\n\t\t);\n\t}\n\treturn { endpoint, token };\n}\n\nfunction requireDid(value: unknown, name: string): asserts value is string {\n\trequireString(value, name);\n\tif (!value.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `${name} must be a DID`);\n\t}\n}\n\nfunction clampLimit(\n\traw: string | undefined,\n\tfallback: number,\n\tmax: number,\n): number {\n\tconst parsed = raw ? Number.parseInt(raw, 10) : fallback;\n\tif (Number.isNaN(parsed) || parsed < 1) return fallback;\n\treturn Math.min(parsed, max);\n}\n\nfunction parseRecordCursor(\n\tcursor: string | undefined,\n): { collection: string; rkey: string } | undefined {\n\tif (!cursor) return undefined;\n\tconst slash = cursor.lastIndexOf(\"/\");\n\tif (slash <= 0 || slash === cursor.length - 1) {\n\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t}\n\treturn { collection: cursor.slice(0, slash), rkey: cursor.slice(slash + 1) };\n}\n\nfunction parseOpsCursor(\n\tcursor: string | undefined,\n): { rev: string; idx: number } | undefined {\n\tif (!cursor) return undefined;\n\tconst slash = cursor.indexOf(\"/\");\n\tconst idx = slash === -1 ? NaN : Number.parseInt(cursor.slice(slash + 1), 10);\n\tif (slash <= 0 || Number.isNaN(idx)) {\n\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t}\n\treturn { rev: cursor.slice(0, slash), idx };\n}\n\n/**\n * Read the members out of a space meta archive's policy state. A key the\n * policy doesn't define is refused rather than dropped, since dropping it\n * would quietly change who has access to the space.\n */\nfunction parsePolicyState(\n\tpolicy: SpacePolicy,\n\tentries: Array<{ key: string; value: Record<string, unknown> }>,\n): SpaceMember[] {\n\tconst prefix = `${MEMBER_COLLECTION}/`;\n\treturn entries.map(({ key, value }) => {\n\t\tconst did = key.startsWith(prefix)\n\t\t\t? recordKeyToDid(key.slice(prefix.length))\n\t\t\t: undefined;\n\t\tif (policy.$type !== MEMBERSPACE_POLICY || !did?.startsWith(\"did:\")) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Unrecognized policy state: ${key}`,\n\t\t\t);\n\t\t}\n\t\tif (typeof value.read !== \"boolean\" || typeof value.write !== \"boolean\") {\n\t\t\tthrow new SpaceError(\"InvalidRequest\", `Invalid member at ${key}`);\n\t\t}\n\t\treturn { did, read: value.read, write: value.write };\n\t});\n}\n\n/**\n * A malformed archive in a request body is the caller's error, reported\n * under the error name the method declares for it.\n */\nfunction invalidArchive(\n\terr: unknown,\n\tcode: \"InvalidRepoFile\" | \"InvalidSpaceMeta\",\n): unknown {\n\tif (parseSpaceErrorCode(err)) return err;\n\treturn new SpaceError(\n\t\tcode,\n\t\t`Invalid archive: ${err instanceof Error ? err.message : String(err)}`,\n\t);\n}\n\n/** A putMembers batch: at most 100 `{did, read, write}` entries. */\nfunction parseMemberBatch(input: unknown): SpaceMember[] {\n\tif (!Array.isArray(input) || input.length > MAX_MEMBER_BATCH) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`members must be an array of at most ${MAX_MEMBER_BATCH} entries`,\n\t\t);\n\t}\n\treturn input.map((entry, i) => {\n\t\tconst member = entry as { did?: unknown; read?: unknown; write?: unknown };\n\t\tif (\n\t\t\ttypeof member?.did !== \"string\" ||\n\t\t\t!member.did.startsWith(\"did:\") ||\n\t\t\ttypeof member.read !== \"boolean\" ||\n\t\t\ttypeof member.write !== \"boolean\"\n\t\t) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`members[${i}] must be {did, read, write}`,\n\t\t\t);\n\t\t}\n\t\treturn { did: member.did, read: member.read, write: member.write };\n\t});\n}\n\nasync function readBody(c: Context): Promise<Uint8Array> {\n\tconst contentType = c.req.header(\"Content-Type\")?.split(\";\")[0]?.trim();\n\tif (contentType !== STAR_CONTENT_TYPE) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`Content-Type must be ${STAR_CONTENT_TYPE}`,\n\t\t);\n\t}\n\tconst declared = Number.parseInt(c.req.header(\"Content-Length\") ?? \"\", 10);\n\tif (declared > MAX_IMPORT_BYTES) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Archive is too large\");\n\t}\n\tconst bytes = new Uint8Array(await c.req.arrayBuffer());\n\tif (bytes.length === 0) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Empty archive\");\n\t}\n\tif (bytes.length > MAX_IMPORT_BYTES) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Archive is too large\");\n\t}\n\treturn bytes;\n}\n\n/** A pull-based stream over an async iterable, cancelling it on abort. */\nfunction asyncIterableToStream(\n\titerable: AsyncIterable<Uint8Array>,\n): ReadableStream<Uint8Array> {\n\tconst iterator = iterable[Symbol.asyncIterator]();\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { value, done } = await iterator.next();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (err) {\n\t\t\t\tcontroller.error(err);\n\t\t\t}\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait iterator.return?.();\n\t\t},\n\t});\n}\n\nasync function deleteR2Prefix(bucket: R2Bucket, prefix: string): Promise<void> {\n\tlet cursor: string | undefined;\n\tdo {\n\t\tconst listed = await bucket.list({ prefix, cursor, limit: 500 });\n\t\tif (listed.objects.length > 0) {\n\t\t\tawait bucket.delete(listed.objects.map((object) => object.key));\n\t\t}\n\t\tcursor = listed.truncated ? listed.cursor : undefined;\n\t} while (cursor);\n}\n","/**\n * Delegation tokens, minted by the user's PDS for a space hosted anywhere.\n *\n * Thin wrappers over `@atproto/space`, so a host gets them without\n * depending on that package's types directly.\n */\n\nimport {\n\tcreateDelegationToken as upstreamCreateDelegationToken,\n\tspaceHostAud as upstreamSpaceHostAud,\n} from \"@atproto/space\";\nimport type { SpaceSigningKeypair } from \"./types.js\";\n\n/**\n * How a space authority is addressed as the space host: its `#atproto_pds`\n * service entry, the audience of delegation tokens and client attestations.\n */\nexport function spaceHostAud(authority: string): string {\n\treturn upstreamSpaceHostAud(authority as `did:${string}:${string}`);\n}\n\n/**\n * Mint a delegation token: the user's PDS vouching, for 60 seconds and one\n * use, that `iss` wants a credential for `space` from its authority.\n */\nexport function createDelegationToken(\n\tparams: { iss: string; space: string; authority: string },\n\tkeypair: SpaceSigningKeypair,\n): Promise<string> {\n\treturn upstreamCreateDelegationToken({\n\t\tiss: params.iss as `did:${string}:${string}`,\n\t\tsub: params.space as never,\n\t\taud: spaceHostAud(params.authority) as never,\n\t\tkeypair: keypair as never,\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAWA,MAAa,oBAAoB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAID,MAAMA,WAAgC,IAAI,IAAI,kBAAkB;;AAGhE,MAAMC,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