@pkcprotocol/pkc-js 0.0.92 → 0.0.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +5 -0
  2. package/dist/browser/clients/rpc-client/pkc-rpc-client.d.ts +15 -0
  3. package/dist/browser/clients/rpc-client/pkc-rpc-client.js +70 -0
  4. package/dist/browser/clients/rpc-client/pkc-rpc-client.js.map +1 -1
  5. package/dist/browser/community/rpc-local-community.js +43 -15
  6. package/dist/browser/community/rpc-local-community.js.map +1 -1
  7. package/dist/browser/community/rpc-remote-community.js +30 -10
  8. package/dist/browser/community/rpc-remote-community.js.map +1 -1
  9. package/dist/browser/errors.d.ts +1 -0
  10. package/dist/browser/errors.js +1 -0
  11. package/dist/browser/errors.js.map +1 -1
  12. package/dist/browser/generated-version.d.ts +1 -1
  13. package/dist/browser/generated-version.js +1 -1
  14. package/dist/browser/pkc-error.d.ts +1 -1
  15. package/dist/browser/publications/comment/comment.js +30 -11
  16. package/dist/browser/publications/comment/comment.js.map +1 -1
  17. package/dist/browser/publications/publication.js +46 -17
  18. package/dist/browser/publications/publication.js.map +1 -1
  19. package/dist/browser/rpc/src/schema.js +3 -1
  20. package/dist/browser/rpc/src/schema.js.map +1 -1
  21. package/dist/browser/util.js +1 -1
  22. package/dist/browser/util.js.map +1 -1
  23. package/dist/bundled/bundle-manifest.json +25 -25
  24. package/dist/bundled/chunks/{helia-for-pkc-COFAbh3C.js → helia-for-pkc-C8tOPlIj.js} +2 -2
  25. package/dist/bundled/chunks/{local-community-CyA7I22X.js → local-community-DYEWq5rq.js} +1 -1
  26. package/dist/bundled/chunks/{local-community-DLeQ8V3i.js → local-community-DgbMuVAA.js} +2 -2
  27. package/dist/bundled/chunks/{node-i4Twbtvv.js → node-BrLiC0qX.js} +82 -20
  28. package/dist/bundled/chunks/{rpc-local-community-CZSOMq_6.js → rpc-local-community-DOSee621.js} +38 -15
  29. package/dist/bundled/chunks/{schema-Bbq796q3.js → schema-HH2zeH-j.js} +2 -1
  30. package/dist/bundled/chunks/{util-DdrJVp4E.js → util-DSIDv1Cb.js} +1 -1
  31. package/dist/bundled/index.js +1 -1
  32. package/dist/bundled/rpc/src/index.js +4 -4
  33. package/dist/node/clients/rpc-client/pkc-rpc-client.d.ts +15 -0
  34. package/dist/node/clients/rpc-client/pkc-rpc-client.js +70 -0
  35. package/dist/node/clients/rpc-client/pkc-rpc-client.js.map +1 -1
  36. package/dist/node/community/rpc-local-community.js +43 -15
  37. package/dist/node/community/rpc-local-community.js.map +1 -1
  38. package/dist/node/community/rpc-remote-community.js +30 -10
  39. package/dist/node/community/rpc-remote-community.js.map +1 -1
  40. package/dist/node/errors.d.ts +1 -0
  41. package/dist/node/errors.js +1 -0
  42. package/dist/node/errors.js.map +1 -1
  43. package/dist/node/generated-version.d.ts +1 -1
  44. package/dist/node/generated-version.js +1 -1
  45. package/dist/node/pkc-error.d.ts +1 -1
  46. package/dist/node/publications/comment/comment.js +30 -11
  47. package/dist/node/publications/comment/comment.js.map +1 -1
  48. package/dist/node/publications/publication.js +46 -17
  49. package/dist/node/publications/publication.js.map +1 -1
  50. package/dist/node/rpc/src/schema.js +3 -1
  51. package/dist/node/rpc/src/schema.js.map +1 -1
  52. package/dist/node/util.js +1 -1
  53. package/dist/node/util.js.map +1 -1
  54. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { i as __toESM, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $ as pubsubTopicToDhtKey, $n as n$4, Bn as CommentEditReservedFields, C as contentContainsMarkdownAudio, Ct as findStartedCommunity, F as getIpnsRecordInLocalKuboNode, Fr as ZodError, Ft as untrackStartedCommunity, G as isLinkOfAudio, Hn as CommentEditsTableRowSchema, Ht as CommunityEditPublicationPubsubReservedFields, J as isLinkOfVideo, Jt as CommentModerationReservedFields, K as isLinkOfImage, Kn as AuthorReservedFields, L as hideClassPrivateProps, Lt as untrackUpdatingCommunity, M as genToArray, Mn as CommentsTableRowSchema, Mt as trackStartedCommunity, N as getEquivalentCommunityAddresses, O as derivePublicationFromChallengeRequest, P as getErrorCodeFromMessage, Pt as trackUpdatingCommunity, Q as isStringDomain, R as ipnsNameToIpnsOverPubsubTopic, Rn as CommentEditPubsubMessagePublicationSchema, Rt as require_sha256, S as calculateStringSizeSameAsIpfsAddCidV0, Sn as CommentPubsubMessageReservedFields, Sr as logger_default, St as findCommunityInRegistry, T as contentContainsMarkdownVideos, Tt as findUpdatingCommunity, W as isLinkOfAnimatedImage, Xt as CommentModerationsTableRowSchema, Y as isLinkValid, _t as statMfsPathSafely, a as ChallengeRequestMessageSchema, an as CommunityIpfsSchema, ar as e$1, at as removeMfsFilesSafely, b as areEquivalentCommunityAddresses, br as PKCError, cr as t$4, d as DecryptedChallengeRequestSchema, dr as t$5, dt as retryKuboBlockPutPinAndProvidePubsubTopic, er as t$8, fr as t$3, gn as VotePubsubReservedFields, gt as sleepUntilTimeoutOrAbort, hn as VotePubsubMessagePublicationSchema, ir as e, it as removeBlocksFromKuboNode, jn as CommentUpdateTableRowSchema, jt as syncCommunityRegistryEntry, k as doesDomainAddressHaveCapitalLetter, kn as CommentUpdateSchema, mr as require_retry, nr as t$7, on as CommunitySignedPropertyNames, pt as retryKuboIpfsAddAndProvide, q as isLinkOfMedia, qt as CommentModerationPubsubMessagePublicationSchema, r as ChallengeMessageSchema, rr as t$6, s as ChallengeVerificationMessageSchema, sr as r$1, st as removeNullUndefinedValues, t as ChallengeAnswerMessageSchema, tr as n$3, u as DecryptedChallengeRequestPublicationSchema, vn as VoteTablesRowSchema, w as contentContainsMarkdownImages, x as calculateIpfsCidV0, xn as CommentIpfsSchema, xr as messages, xt as writeKuboFilesWithTimeout, y as version_default, yt as timestamp, zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema } from "./schema-Bbq796q3.js";
3
- import { $t as getPublicKeyFromPrivateKey, A as deriveDbPosts, At as verifyCommentIpfs, Bt as getAuthorNameFromWire, C as BackupAbortError, Cn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, Dt as verifyChallengeRequest, E as calculateInlineRepliesBudget, En as parseJsonWithPKCErrorIfFails, F as importSignerIntoKuboNode, Ft as verifyCommunityEdit, G as REPLY_REPLIES_SORT_TYPES, Gt as getCommunityPublicKeyFromWire, It as verifyVote, Jt as encode, K as TIMEFRAMES_TO_SECONDS, Lt as buildRuntimeAuthor, M as getDefaultCommunityDbConfig, Mt as verifyCommentPubsubMessage, Nt as verifyCommentUpdate, O as deleteOldCommunityInWindows, P as getThumbnailPropsOfLink, Pt as verifyCommunity, Qt as getPKCAddressFromPublicKeySync, R as moveCommunityDbToDeletedDirectory, Rt as cleanWireAuthor, S as encryptEd25519AesGcmPublicKeyBuffer, St as signCommunity, T as calculateExpectedSignatureSize, Tt as verifyChallengeAnswer, U as POSTS_SORT_TYPES, W as POST_REPLIES_SORT_TYPES, Wt as getCommunityNameFromWire, Xt as getIpfsKeyFromPrivateKey, Z as iterateOverPageCidsToFindAllCids, Zt as getPKCAddressFromPublicKey, _t as signComment, a as loadChallengeFileFromCommunityChallengeSettings, ar as t$11, b as decryptEd25519AesGcmPublicKeyBuffer, bt as signCommentUpdate, c as LRUCache, d as KeyvBetterSqlite3, dn as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, dr as STORAGE_KEYS, en as createSchemaRowParser, er as crosspostChainDepthUpTo, fr as require_lodash_merge, ft as cleanUpBeforePublishing, g as SignerWithPublicKeyAddress, gt as signChallengeVerification, i as getCommunityChallengeFromCommunityChallengeSettings, ir as r$2, j as deriveDbReplies, jt as verifyCommentModeration, k as deriveCommentIpfsFromCommentTableRow, kt as verifyCommentEdit, lr as t$10, lt as pLimit, mt as signChallengeMessage, nr as t$9, o as pkcJsChallenges, or as n$6, pn as parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails, qt as decode, r as getChallengeVerification, rr as t$12, s as TrackedInstanceRegistry, sr as n$5, t as RpcLocalCommunity, tr as effectiveMaxCrosspostDepth, u as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, ur as stringify, vt as signCommentEdit, w as backupCommunityDb, xt as signCommentUpdateForChallengeVerification, z as resolveDbPostsCidRefs } from "./rpc-local-community-CZSOMq_6.js";
2
+ import { $ as pubsubTopicToDhtKey, $n as n$4, Bn as CommentEditReservedFields, C as contentContainsMarkdownAudio, Ct as findStartedCommunity, F as getIpnsRecordInLocalKuboNode, Fr as ZodError, Ft as untrackStartedCommunity, G as isLinkOfAudio, Hn as CommentEditsTableRowSchema, Ht as CommunityEditPublicationPubsubReservedFields, J as isLinkOfVideo, Jt as CommentModerationReservedFields, K as isLinkOfImage, Kn as AuthorReservedFields, L as hideClassPrivateProps, Lt as untrackUpdatingCommunity, M as genToArray, Mn as CommentsTableRowSchema, Mt as trackStartedCommunity, N as getEquivalentCommunityAddresses, O as derivePublicationFromChallengeRequest, P as getErrorCodeFromMessage, Pt as trackUpdatingCommunity, Q as isStringDomain, R as ipnsNameToIpnsOverPubsubTopic, Rn as CommentEditPubsubMessagePublicationSchema, Rt as require_sha256, S as calculateStringSizeSameAsIpfsAddCidV0, Sn as CommentPubsubMessageReservedFields, Sr as logger_default, St as findCommunityInRegistry, T as contentContainsMarkdownVideos, Tt as findUpdatingCommunity, W as isLinkOfAnimatedImage, Xt as CommentModerationsTableRowSchema, Y as isLinkValid, _t as statMfsPathSafely, a as ChallengeRequestMessageSchema, an as CommunityIpfsSchema, ar as e$1, at as removeMfsFilesSafely, b as areEquivalentCommunityAddresses, br as PKCError, cr as t$4, d as DecryptedChallengeRequestSchema, dr as t$5, dt as retryKuboBlockPutPinAndProvidePubsubTopic, er as t$8, fr as t$3, gn as VotePubsubReservedFields, gt as sleepUntilTimeoutOrAbort, hn as VotePubsubMessagePublicationSchema, ir as e, it as removeBlocksFromKuboNode, jn as CommentUpdateTableRowSchema, jt as syncCommunityRegistryEntry, k as doesDomainAddressHaveCapitalLetter, kn as CommentUpdateSchema, mr as require_retry, nr as t$7, on as CommunitySignedPropertyNames, pt as retryKuboIpfsAddAndProvide, q as isLinkOfMedia, qt as CommentModerationPubsubMessagePublicationSchema, r as ChallengeMessageSchema, rr as t$6, s as ChallengeVerificationMessageSchema, sr as r$1, st as removeNullUndefinedValues, t as ChallengeAnswerMessageSchema, tr as n$3, u as DecryptedChallengeRequestPublicationSchema, vn as VoteTablesRowSchema, w as contentContainsMarkdownImages, x as calculateIpfsCidV0, xn as CommentIpfsSchema, xr as messages, xt as writeKuboFilesWithTimeout, y as version_default, yt as timestamp, zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema } from "./schema-HH2zeH-j.js";
3
+ import { $t as getPublicKeyFromPrivateKey, A as deriveDbPosts, At as verifyCommentIpfs, Bt as getAuthorNameFromWire, C as BackupAbortError, Cn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, Dt as verifyChallengeRequest, E as calculateInlineRepliesBudget, En as parseJsonWithPKCErrorIfFails, F as importSignerIntoKuboNode, Ft as verifyCommunityEdit, G as REPLY_REPLIES_SORT_TYPES, Gt as getCommunityPublicKeyFromWire, It as verifyVote, Jt as encode, K as TIMEFRAMES_TO_SECONDS, Lt as buildRuntimeAuthor, M as getDefaultCommunityDbConfig, Mt as verifyCommentPubsubMessage, Nt as verifyCommentUpdate, O as deleteOldCommunityInWindows, P as getThumbnailPropsOfLink, Pt as verifyCommunity, Qt as getPKCAddressFromPublicKeySync, R as moveCommunityDbToDeletedDirectory, Rt as cleanWireAuthor, S as encryptEd25519AesGcmPublicKeyBuffer, St as signCommunity, T as calculateExpectedSignatureSize, Tt as verifyChallengeAnswer, U as POSTS_SORT_TYPES, W as POST_REPLIES_SORT_TYPES, Wt as getCommunityNameFromWire, Xt as getIpfsKeyFromPrivateKey, Z as iterateOverPageCidsToFindAllCids, Zt as getPKCAddressFromPublicKey, _t as signComment, a as loadChallengeFileFromCommunityChallengeSettings, ar as t$11, b as decryptEd25519AesGcmPublicKeyBuffer, bt as signCommentUpdate, c as LRUCache, d as KeyvBetterSqlite3, dn as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, dr as STORAGE_KEYS, en as createSchemaRowParser, er as crosspostChainDepthUpTo, fr as require_lodash_merge, ft as cleanUpBeforePublishing, g as SignerWithPublicKeyAddress, gt as signChallengeVerification, i as getCommunityChallengeFromCommunityChallengeSettings, ir as r$2, j as deriveDbReplies, jt as verifyCommentModeration, k as deriveCommentIpfsFromCommentTableRow, kt as verifyCommentEdit, lr as t$10, lt as pLimit, mt as signChallengeMessage, nr as t$9, o as pkcJsChallenges, or as n$6, pn as parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails, qt as decode, r as getChallengeVerification, rr as t$12, s as TrackedInstanceRegistry, sr as n$5, t as RpcLocalCommunity, tr as effectiveMaxCrosspostDepth, u as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, ur as stringify, vt as signCommentEdit, w as backupCommunityDb, xt as signCommentUpdateForChallengeVerification, z as resolveDbPostsCidRefs } from "./rpc-local-community-DOSee621.js";
4
4
  import { randomFillSync, randomUUID } from "node:crypto";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import path from "node:path";
@@ -1,7 +1,7 @@
1
1
  import { i as __toESM, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $n as n$2, B as isIpfsCid, Bt as pTimeout, Ct as findStartedCommunity, D as deepMergeRuntimeFields, Dt as listUpdatingComments, E as createAbortError, En as CommentUpdateForChallengeVerificationSchema, Et as listStartedCommunities, H as isIpns, Ir as joinValues, It as untrackUpdatingComment, L as hideClassPrivateProps, Lr as parsedType, Nt as trackUpdatingComment, Ot as listUpdatingCommunities, Q as isStringDomain, R as ipnsNameToIpnsOverPubsubTopic, Rr as stringifyPrimitive, Rt as require_sha256, Sr as logger_default, Tr as setErrorMap, Tt as findUpdatingCommunity, a as ChallengeRequestMessageSchema, an as CommunityIpfsSchema, ar as e$1, b as areEquivalentCommunityAddresses, br as PKCError, bt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, ct as removeUndefinedValuesRecursively, dn as PubsubTopicSchema, en as CommunityAnchorSchema, ft as retryKuboIpfsAdd, gt as sleepUntilTimeoutOrAbort, hr as FailedToFetchCommentIpfsFromGatewaysError, ht as shortifyCid, ir as e, k as doesDomainAddressHaveCapitalLetter, kn as CommentUpdateSchema, kt as refreshTrackedCommentAliases, lt as replaceXWithY, mr as require_retry, mt as shortifyAddress, nt as rejectWhenAbortSignalFires, r as ChallengeMessageSchema, rr as t$1, rt as rejectWhenCommunityStopsOrAborts, s as ChallengeVerificationMessageSchema, sr as r, t as ChallengeAnswerMessageSchema, tr as n$1, ut as resolveWhenPredicateIsTrue, vt as throwIfAbortSignalAborted, wt as findUpdatingComment, xn as CommentIpfsSchema, xr as messages, y as version_default, yt as timestamp, z as isAbortError, zt as TimeoutError } from "./schema-Bbq796q3.js";
3
- import { $ as RepliesPages, $n as RpcUnsubscribeParamSchema, An as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, At as verifyCommentIpfs, B as setNativeFunctions$1, Bn as RpcEditCommunityParamSchema, Cn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, Ct as signCommunityEdit, D as createKuboRpcClient, Dn as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, En as parseJsonWithPKCErrorIfFails, Et as verifyChallengeMessage, Fn as RpcCancelExportParamSchema, Ft as verifyCommunityEdit, Gn as RpcFetchCidParamSchema, Gt as getCommunityPublicKeyFromWire, H as CommentClientsManager, Hn as RpcExportCommunityModLogsResultSchema, Ht as buildRuntimeCommunityFields, I as listCommunitiesSync, In as RpcCidParamSchema, It as verifyVote, Jn as RpcPublishChallengeAnswersParamSchema, Kn as RpcFetchCidResultSchema, Kt as normalizeCommunityInputFromCommunity, L as monitorCommunitiesDirectory, Ln as RpcCommentRepliesPageParamSchema, Lt as buildRuntimeAuthor, Mn as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, Mt as verifyCommentPubsubMessage, N as getDefaultDataPath, Nn as RpcAnchorPublishPreparationResultSchema, Nt as verifyCommentUpdate, On as parseRpcCommentEventWithPKCErrorIfItFails, Ot as verifyChallengeVerification, Pn as RpcAuthorNameParamSchema, Q as parseRawPages, Qn as RpcSuccessResultSchema, Qt as getPKCAddressFromPublicKeySync, Rn as RpcCommunityIdentifierParamSchema, Rt as cleanWireAuthor, Sn as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, Tn as parseDecryptedChallengeWithPKCErrorIfItFails, Un as RpcExportCommunityParamSchema, Ut as getCommunityAddressFromRecord, V as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, Vn as RpcExportCommunityModLogsParamSchema, Vt as normalizeCreatePublicationAuthor, Wn as RpcExportCommunityResultSchema, Wt as getCommunityNameFromWire, X as findCommentInPageInstanceRecursively, Xn as RpcResolveAuthorNameResultSchema, Y as extractCommunityRuntimeFieldsFromParsedPages, Yn as RpcPublishedAnchorRecordResultSchema, Yt as getBufferedPKCAddressFromPublicKey, Zn as RpcSubscriptionIdResultSchema, _ as createSigner, _n as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, _t as signComment, an as parseCommentIpfsSchemaWithPKCErrorIfItFails, ar as t$3, at as PublicationClientsManager, bn as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, c as LRUCache, cn as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, cr as t$2, d as KeyvBetterSqlite3, dt as require_lib$1, et as applyNameResolvedCacheToCrosspost, f as decodeRpcChallengeAnswerPubsubMsg, fn as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, ft as cleanUpBeforePublishing, gn as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, h as decodeRpcChallengeVerificationPubsubMsg, hn as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, ht as signChallengeRequest, in as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, it as stripNameResolvedFromCrosspost, jt as verifyCommentModeration, kn as parseRpcCommentUpdateEventWithPKCErrorIfItFails, kt as verifyCommentEdit, l as RemoteCommunity, ln as parseCommunityAddressWithPKCErrorIfItFails, lr as t$5, m as decodeRpcChallengeRequestPubsubMsg, mn as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, mr as require_undici, n as RpcRemoteCommunity, nr as t$4, nt as collectCrosspostAuthorsToResolve, o as pkcJsChallenges, or as n$3, ot as PKCClientsManager, p as decodeRpcChallengePubsubMsg, pr as nativeFunctions$2, pt as signChallengeAnswer, qn as RpcPublishAnchorRecordParamSchema, qt as decode, s as TrackedInstanceRegistry, sn as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, st as InflightFetchManager, t as RpcLocalCommunity, tn as parseCidStringSchemaWithPKCErrorIfItFails, tt as cloneCrosspostForRuntime, ut as PKCTypedEmitter, v as createAnchorIpnsRecord$1, vt as signCommentEdit, wn as parseDecryptedChallengeVerification, wt as signVote, x as encryptEd25519AesGcm, xn as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, y as decryptEd25519AesGcm, yt as signCommentModeration, zn as RpcCommunityPageParamSchema, zt as getAuthorNameFromRuntime } from "./rpc-local-community-CZSOMq_6.js";
4
- import { o as getHeliaDebugContext } from "./util-DdrJVp4E.js";
2
+ import { $n as n$2, B as isIpfsCid, Bt as pTimeout, Ct as findStartedCommunity, D as deepMergeRuntimeFields, Dt as listUpdatingComments, E as createAbortError, En as CommentUpdateForChallengeVerificationSchema, Et as listStartedCommunities, H as isIpns, Ir as joinValues, It as untrackUpdatingComment, L as hideClassPrivateProps, Lr as parsedType, Nt as trackUpdatingComment, Ot as listUpdatingCommunities, Q as isStringDomain, R as ipnsNameToIpnsOverPubsubTopic, Rr as stringifyPrimitive, Rt as require_sha256, Sr as logger_default, Tr as setErrorMap, Tt as findUpdatingCommunity, a as ChallengeRequestMessageSchema, an as CommunityIpfsSchema, ar as e$1, b as areEquivalentCommunityAddresses, br as PKCError, bt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, ct as removeUndefinedValuesRecursively, dn as PubsubTopicSchema, en as CommunityAnchorSchema, ft as retryKuboIpfsAdd, gt as sleepUntilTimeoutOrAbort, hr as FailedToFetchCommentIpfsFromGatewaysError, ht as shortifyCid, ir as e, k as doesDomainAddressHaveCapitalLetter, kn as CommentUpdateSchema, kt as refreshTrackedCommentAliases, lt as replaceXWithY, mr as require_retry, mt as shortifyAddress, nt as rejectWhenAbortSignalFires, r as ChallengeMessageSchema, rr as t$1, rt as rejectWhenCommunityStopsOrAborts, s as ChallengeVerificationMessageSchema, sr as r, t as ChallengeAnswerMessageSchema, tr as n$1, ut as resolveWhenPredicateIsTrue, vt as throwIfAbortSignalAborted, wt as findUpdatingComment, xn as CommentIpfsSchema, xr as messages, y as version_default, yt as timestamp, z as isAbortError, zt as TimeoutError } from "./schema-HH2zeH-j.js";
3
+ import { $ as RepliesPages, $n as RpcUnsubscribeParamSchema, An as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, At as verifyCommentIpfs, B as setNativeFunctions$1, Bn as RpcEditCommunityParamSchema, Cn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, Ct as signCommunityEdit, D as createKuboRpcClient, Dn as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, En as parseJsonWithPKCErrorIfFails, Et as verifyChallengeMessage, Fn as RpcCancelExportParamSchema, Ft as verifyCommunityEdit, Gn as RpcFetchCidParamSchema, Gt as getCommunityPublicKeyFromWire, H as CommentClientsManager, Hn as RpcExportCommunityModLogsResultSchema, Ht as buildRuntimeCommunityFields, I as listCommunitiesSync, In as RpcCidParamSchema, It as verifyVote, Jn as RpcPublishChallengeAnswersParamSchema, Kn as RpcFetchCidResultSchema, Kt as normalizeCommunityInputFromCommunity, L as monitorCommunitiesDirectory, Ln as RpcCommentRepliesPageParamSchema, Lt as buildRuntimeAuthor, Mn as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, Mt as verifyCommentPubsubMessage, N as getDefaultDataPath, Nn as RpcAnchorPublishPreparationResultSchema, Nt as verifyCommentUpdate, On as parseRpcCommentEventWithPKCErrorIfItFails, Ot as verifyChallengeVerification, Pn as RpcAuthorNameParamSchema, Q as parseRawPages, Qn as RpcSuccessResultSchema, Qt as getPKCAddressFromPublicKeySync, Rn as RpcCommunityIdentifierParamSchema, Rt as cleanWireAuthor, Sn as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, Tn as parseDecryptedChallengeWithPKCErrorIfItFails, Un as RpcExportCommunityParamSchema, Ut as getCommunityAddressFromRecord, V as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, Vn as RpcExportCommunityModLogsParamSchema, Vt as normalizeCreatePublicationAuthor, Wn as RpcExportCommunityResultSchema, Wt as getCommunityNameFromWire, X as findCommentInPageInstanceRecursively, Xn as RpcResolveAuthorNameResultSchema, Y as extractCommunityRuntimeFieldsFromParsedPages, Yn as RpcPublishedAnchorRecordResultSchema, Yt as getBufferedPKCAddressFromPublicKey, Zn as RpcSubscriptionIdResultSchema, _ as createSigner, _n as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, _t as signComment, an as parseCommentIpfsSchemaWithPKCErrorIfItFails, ar as t$3, at as PublicationClientsManager, bn as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, c as LRUCache, cn as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, cr as t$2, d as KeyvBetterSqlite3, dt as require_lib$1, et as applyNameResolvedCacheToCrosspost, f as decodeRpcChallengeAnswerPubsubMsg, fn as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, ft as cleanUpBeforePublishing, gn as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, h as decodeRpcChallengeVerificationPubsubMsg, hn as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, ht as signChallengeRequest, in as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, it as stripNameResolvedFromCrosspost, jt as verifyCommentModeration, kn as parseRpcCommentUpdateEventWithPKCErrorIfItFails, kt as verifyCommentEdit, l as RemoteCommunity, ln as parseCommunityAddressWithPKCErrorIfItFails, lr as t$5, m as decodeRpcChallengeRequestPubsubMsg, mn as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, mr as require_undici, n as RpcRemoteCommunity, nr as t$4, nt as collectCrosspostAuthorsToResolve, o as pkcJsChallenges, or as n$3, ot as PKCClientsManager, p as decodeRpcChallengePubsubMsg, pr as nativeFunctions$2, pt as signChallengeAnswer, qn as RpcPublishAnchorRecordParamSchema, qt as decode, s as TrackedInstanceRegistry, sn as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, st as InflightFetchManager, t as RpcLocalCommunity, tn as parseCidStringSchemaWithPKCErrorIfItFails, tt as cloneCrosspostForRuntime, ut as PKCTypedEmitter, v as createAnchorIpnsRecord$1, vt as signCommentEdit, wn as parseDecryptedChallengeVerification, wt as signVote, x as encryptEd25519AesGcm, xn as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, y as decryptEd25519AesGcm, yt as signCommentModeration, zn as RpcCommunityPageParamSchema, zt as getAuthorNameFromRuntime } from "./rpc-local-community-DOSee621.js";
4
+ import { o as getHeliaDebugContext } from "./util-DSIDv1Cb.js";
5
5
  import path from "path";
6
6
  import assert from "assert";
7
7
  import fs from "fs";
@@ -276,12 +276,13 @@ var Publication = class extends import_lib.TypedEmitter {
276
276
  }
277
277
  });
278
278
  if (this._rpcPublishSubscriptionId) {
279
+ const subscriptionId = this._rpcPublishSubscriptionId;
280
+ this._rpcPublishSubscriptionId = void 0;
279
281
  try {
280
- await this._pkc._pkcRpcClient.unsubscribe(this._rpcPublishSubscriptionId);
282
+ await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
281
283
  } catch (e) {
282
284
  log.error("Failed to unsubscribe from publication publish", e);
283
285
  }
284
- this._rpcPublishSubscriptionId = void 0;
285
286
  }
286
287
  }
287
288
  async _handleIncomingChallengePubsubMessage(msg) {
@@ -486,10 +487,13 @@ var Publication = class extends import_lib.TypedEmitter {
486
487
  async publishChallengeAnswers({ challengeAnswers }) {
487
488
  const log = logger_default("pkc-js:publication:publishChallengeAnswers");
488
489
  const toEncryptAnswers = parseDecryptedChallengeAnswerWithPKCErrorIfItFails({ challengeAnswers });
489
- if (this._pkc._pkcRpcClient && typeof this._rpcPublishSubscriptionId === "number") return this._pkc._pkcRpcClient.publishChallengeAnswers({
490
- subscriptionId: this._rpcPublishSubscriptionId,
491
- challengeAnswers: toEncryptAnswers.challengeAnswers
492
- });
490
+ if (this._pkc._pkcRpcClient) {
491
+ if (typeof this._rpcPublishSubscriptionId !== "number") throw new PKCError("ERR_RPC_CLIENT_NO_ACTIVE_PUBLISH_SUBSCRIPTION", { publishingState: this.publishingState });
492
+ return this._pkc._pkcRpcClient.publishChallengeAnswers({
493
+ subscriptionId: this._rpcPublishSubscriptionId,
494
+ challengeAnswers: toEncryptAnswers.challengeAnswers
495
+ });
496
+ }
493
497
  const challengeExchangesWithChallenge = Object.values(this._challengeExchanges).filter((exchange) => exchange.challenge);
494
498
  if (challengeExchangesWithChallenge.length === 0) throw Error("No challenge exchanges with challenge");
495
499
  if (challengeExchangesWithChallenge.length > 1) throw Error("We should only have one challenge exchange with challenge");
@@ -704,14 +708,15 @@ var Publication = class extends import_lib.TypedEmitter {
704
708
  this._unregisterFromPkcOncePublishWorkSettles();
705
709
  this._setStateWithEmission("stopped");
706
710
  if (this._rpcPublishSubscriptionId) {
711
+ const subscriptionId = this._rpcPublishSubscriptionId;
712
+ this._rpcPublishSubscriptionId = void 0;
707
713
  try {
708
- await this._pkc._pkcRpcClient.unsubscribe(this._rpcPublishSubscriptionId);
714
+ await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
709
715
  } catch (e) {
710
716
  log.error("Failed to unsubscribe from publication publish", e);
711
717
  }
712
- this._rpcPublishSubscriptionId = void 0;
713
718
  this._setRpcClientState("stopped");
714
- } else if (typeof this._community?.pubsubTopic === "string") {
719
+ } else if (!this._pkc._pkcRpcClient && typeof this._community?.pubsubTopic === "string") {
715
720
  await this._clientsManager.pubsubUnsubscribe(this._community.pubsubTopic, this._handleChallengeExchange);
716
721
  Object.values(this._challengeExchanges).forEach((exchange) => this._updatePubsubState("stopped", exchange.providerUrl));
717
722
  }
@@ -787,8 +792,17 @@ var Publication = class extends import_lib.TypedEmitter {
787
792
  communityEdit: rpcClient.publishCommunityEdit
788
793
  }[this.getType()].bind(rpcClient)(this.toJSONPubsubRequestToEncrypt());
789
794
  this._rpcPublishSubscriptionId = subscriptionId;
790
- this._pkc._pkcRpcClient.getSubscription(this._rpcPublishSubscriptionId).on("challengerequest", this._handleIncomingChallengeRequestFromRpc.bind(this)).on("challenge", this._handleIncomingChallengeFromRpc.bind(this)).on("challengeanswer", this._handleIncomingChallengeAnswerFromRpc.bind(this)).on("challengeverification", this._handleIncomingChallengeVerificationFromRpc.bind(this)).on("publishingstatechange", this._handleIncomingPublishingStateFromRpc.bind(this)).on("statechange", this._handleIncomingStateFromRpc.bind(this)).on("error", this._handleIncomingErrorFromRpc.bind(this));
791
- this._pkc._pkcRpcClient.emitAllPendingMessages(this._rpcPublishSubscriptionId);
795
+ rpcClient.attachSubscriptionHandlersDeferred({
796
+ subscriptionId,
797
+ isStale: () => this._rpcPublishSubscriptionId !== subscriptionId,
798
+ attach: (subscription) => subscription.on("challengerequest", this._handleIncomingChallengeRequestFromRpc.bind(this)).on("challenge", this._handleIncomingChallengeFromRpc.bind(this)).on("challengeanswer", this._handleIncomingChallengeAnswerFromRpc.bind(this)).on("challengeverification", this._handleIncomingChallengeVerificationFromRpc.bind(this)).on("publishingstatechange", this._handleIncomingPublishingStateFromRpc.bind(this)).on("statechange", this._handleIncomingStateFromRpc.bind(this)).on("error", this._handleIncomingErrorFromRpc.bind(this)),
799
+ replayErrorContainment: {
800
+ entityName: "publication",
801
+ log: logger_default("pkc-js:publication:publish:_publishWithRpc"),
802
+ emitError: (error) => this.emit("error", error),
803
+ stop: () => this.stop()
804
+ }
805
+ });
792
806
  }
793
807
  _changePublicationStateEmitEventEmitStateChangeEvent(opts) {
794
808
  const shouldEmitStateChange = opts.newState && opts.newState !== this.state;
@@ -1764,8 +1778,18 @@ var Comment = class extends Publication {
1764
1778
  throw e;
1765
1779
  }
1766
1780
  this._setStateWithEmission("updating");
1767
- this._pkc._pkcRpcClient.getSubscription(this._updateRpcSubscriptionId).on("update", this._handleUpdateEventFromRpc.bind(this)).on("comment", this._handleCommentEventFromRpc.bind(this)).on("runtimeupdate", this._handleRuntimeUpdateEventFromRpc.bind(this)).on("updatingstatechange", this._handleUpdatingStateChangeFromRpc.bind(this)).on("statechange", this._handleStateChangeFromRpc.bind(this)).on("error", this._handleErrorEventFromRpc.bind(this));
1768
- this._pkc._pkcRpcClient.emitAllPendingMessages(this._updateRpcSubscriptionId);
1781
+ const subscriptionId = this._updateRpcSubscriptionId;
1782
+ this._pkc._pkcRpcClient.attachSubscriptionHandlersDeferred({
1783
+ subscriptionId,
1784
+ isStale: () => this._updateRpcSubscriptionId !== subscriptionId,
1785
+ attach: (subscription) => subscription.on("update", this._handleUpdateEventFromRpc.bind(this)).on("comment", this._handleCommentEventFromRpc.bind(this)).on("runtimeupdate", this._handleRuntimeUpdateEventFromRpc.bind(this)).on("updatingstatechange", this._handleUpdatingStateChangeFromRpc.bind(this)).on("statechange", this._handleStateChangeFromRpc.bind(this)).on("error", this._handleErrorEventFromRpc.bind(this)),
1786
+ replayErrorContainment: {
1787
+ entityName: "comment",
1788
+ log,
1789
+ emitError: (error) => this.emit("error", error),
1790
+ stop: () => this.stop()
1791
+ }
1792
+ });
1769
1793
  }
1770
1794
  _useUpdatePropsFromUpdatingStartedCommunityIfPossible() {
1771
1795
  if (!this.cid) throw Error("Need to have comment.cid defined");
@@ -1912,12 +1936,13 @@ var Comment = class extends Publication {
1912
1936
  if (!this.cid) return;
1913
1937
  this._commentIpfsloadingOperation?.stop();
1914
1938
  if (this._updateRpcSubscriptionId) {
1939
+ const subscriptionId = this._updateRpcSubscriptionId;
1940
+ this._updateRpcSubscriptionId = void 0;
1915
1941
  try {
1916
- await this._pkc._pkcRpcClient.unsubscribe(this._updateRpcSubscriptionId);
1942
+ await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
1917
1943
  } catch (e) {
1918
1944
  log.error("Failed to unsubscribe from commentUpdate", e);
1919
1945
  }
1920
- this._updateRpcSubscriptionId = void 0;
1921
1946
  this._setRpcClientState("stopped");
1922
1947
  untrackUpdatingComment(this._pkc, this);
1923
1948
  }
@@ -2196,6 +2221,7 @@ const parseRpcExportCommunityModLogsResult = (result) => RpcExportCommunityModLo
2196
2221
  //#endregion
2197
2222
  //#region dist/node/clients/rpc-client/pkc-rpc-client.js
2198
2223
  const log = logger_default("pkc-js:PKCRpcClient");
2224
+ const scheduleMacrotask = setTimeout.bind(globalThis);
2199
2225
  var PKCRpcClient = class extends import_lib.TypedEmitter {
2200
2226
  constructor(rpcServerUrl) {
2201
2227
  super();
@@ -2400,7 +2426,43 @@ var PKCRpcClient = class extends import_lib.TypedEmitter {
2400
2426
  _assignAdditionalProps(target, rest) {
2401
2427
  if (rest && Object.keys(rest).length > 0) Object.assign(target, rest);
2402
2428
  }
2429
+ subscriptionActive(subscriptionId) {
2430
+ return Boolean(this._subscriptionEvents[subscriptionId]);
2431
+ }
2432
+ attachSubscriptionHandlersDeferred(opts) {
2433
+ scheduleMacrotask(() => {
2434
+ const ownsSubscription = () => !opts.isStale() && this.subscriptionActive(opts.subscriptionId);
2435
+ if (!ownsSubscription()) return;
2436
+ try {
2437
+ opts.attach(this.getSubscription(opts.subscriptionId));
2438
+ this._emitPendingMessagesWhile(opts.subscriptionId, ownsSubscription);
2439
+ } catch (e) {
2440
+ this._containReplayError(e, opts.replayErrorContainment);
2441
+ }
2442
+ }, 0);
2443
+ }
2444
+ _containReplayError(e, containment) {
2445
+ const { entityName, log: siteLog, emitError, stop } = containment;
2446
+ siteLog.error(`Error thrown while replaying buffered subscribe-time notifications, stopping the ${entityName}`, e);
2447
+ try {
2448
+ emitError(e instanceof Error ? e : new Error(String(e)));
2449
+ } catch (emitFailure) {
2450
+ siteLog.error("No listener received the replay error", emitFailure);
2451
+ }
2452
+ stop().catch((stopError) => siteLog.error(`Failed to stop the ${entityName} after a replay error`, stopError));
2453
+ }
2454
+ _emitPendingMessagesWhile(subscriptionId, shouldDeliver) {
2455
+ const pendingMessages = this._pendingSubscriptionMsgs[subscriptionId];
2456
+ if (!pendingMessages) return;
2457
+ while (pendingMessages.length > 0) {
2458
+ if (!shouldDeliver()) return;
2459
+ const message = pendingMessages.shift();
2460
+ this._subscriptionEvents[subscriptionId].emit(message?.params?.event, message);
2461
+ }
2462
+ delete this._pendingSubscriptionMsgs[subscriptionId];
2463
+ }
2403
2464
  emitAllPendingMessages(subscriptionId) {
2465
+ if (!this._pendingSubscriptionMsgs[subscriptionId]) return;
2404
2466
  this._pendingSubscriptionMsgs[subscriptionId].forEach((message) => this._subscriptionEvents[subscriptionId].emit(message?.params?.event, message));
2405
2467
  delete this._pendingSubscriptionMsgs[subscriptionId];
2406
2468
  }
@@ -6948,7 +7010,7 @@ var PKC$1 = class extends PKCTypedEmitter {
6948
7010
  this.clients.libp2pJsClients = {};
6949
7011
  if (!this.libp2pJsClientsOptions) return;
6950
7012
  if (!this.httpRoutersOptions) throw Error("httpRoutersOptions is required for libp2pJsClient");
6951
- const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-COFAbh3C.js");
7013
+ const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-C8tOPlIj.js");
6952
7014
  for (const clientOptions of this.libp2pJsClientsOptions) {
6953
7015
  const heliaNode = await createLibp2pJsClientOrUseExistingOne({
6954
7016
  ...clientOptions,
@@ -7227,7 +7289,7 @@ var PKC$1 = class extends PKCTypedEmitter {
7227
7289
  const log = logger_default("pkc-js:pkc:createLocalCommunity");
7228
7290
  log.trace("Received community options to create a local community instance:", options);
7229
7291
  if (!this._canCreateNewLocalCommunity()) throw new PKCError("ERR_CAN_NOT_CREATE_A_LOCAL_COMMUNITY", { pkcOptions: this._userPKCOptions });
7230
- const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-CyA7I22X.js");
7292
+ const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-DYEWq5rq.js");
7231
7293
  const isLocalCommunity = (await listCommunitiesSync(this)).includes(options.address);
7232
7294
  const community = new LocalCommunity(this);
7233
7295
  if (isLocalCommunity) {
@@ -1,5 +1,5 @@
1
1
  import { i as __toESM, n as __exportAll, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $ as pubsubTopicToDhtKey, $n as n$10, $t as ChallengeFileSchema, A as extractNetworkErrorDetails, An as CommentUpdateSignedPropertyNames, Ar as literal, At as refreshTrackedCommunityAliases, B as isIpfsCid, Bt as pTimeout, Cn as CommentPubsubMessageWithFlexibleAuthorRefinementSchema, Cr as require_supports_color, Ct as findStartedCommunity, D as deepMergeRuntimeFields, Dn as CommentUpdateForChallengeVerificationSignedPropertyNames, Dr as array, E as createAbortError, Er as _enum, Et as listStartedCommunities, Fn as ModQueuePageIpfsSchema, Ft as untrackStartedCommunity, Gn as AuthorCommentIpfsReservedFields, Gt as CreateCommunityEditPublicationOptionsWithRefinementSchema, H as isIpns, I as getPostUpdateTimestampRange, In as PageIpfsSchema, It as untrackUpdatingComment, Jn as CidPathSchema, Kt as CommentModerationChallengeRequestToEncryptSchema, L as hideClassPrivateProps, Ln as CommentEditChallengeRequestToEncryptSchema, Lt as untrackUpdatingCommunity, Mr as object, Mt as trackStartedCommunity, Nn as CreateCommentOptionsWithRefinementSchema, Nr as record, O as derivePublicationFromChallengeRequest, On as CommentUpdateReservedFields, Or as boolean, Ot as listUpdatingCommunities, Pn as GetPageParamSchema, Pr as string, Pt as trackUpdatingCommunity, Q as isStringDomain, Qn as CreateSignerSchema, Qt as ChallengeFileFactorySchema, R as ipnsNameToIpnsOverPubsubTopic, Rt as require_sha256$1, Sr as logger_default, Tn as CommentUpdateChallengeReservedFieldNames, Tt as findUpdatingCommunity, U as isIpnsPath, Un as CreateCommentEditOptionsWithRefinementSchema, Ut as CommunityEditPublicationSignedPropertyNames, V as isIpfsPath, Vn as CommentEditSignedPropertyNames, Vt as CommunityEditPublicationChallengeRequestToEncryptSchema, Wn as AuthorAddressSchema, Wt as CommunityEditPubsubMessagePublicationSchema, X as isRequestPubsubPublicationOfPost, Xn as CommunityAddressSchema, Xt as CommentModerationsTableRowSchema, Yn as CidStringSchema, Yt as CommentModerationSignedPropertyNames, Z as isRequestPubsubPublicationOfReply, Zn as CommunityAuthorChallengeReservedFieldNames, Zt as CreateCommentModerationOptionsWithRefinementSchema, _ as PKCUserOptionBaseSchema, _n as VoteSignedPropertyNames, _r as FailedToFetchCommunityFromGatewaysError, an as CommunityIpfsSchema, ar as e$5, b as areEquivalentCommunityAddresses, bn as CommentIpfsReservedFields, br as PKCError, bt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, c as ChallengeVerificationMessageSignedPropertyNames, cn as CreateRemoteCommunityFunctionArgumentSchema, cr as t$12, dr as t$10, f as DecryptedChallengeSchema, fn as RpcRemoteCommunityUpdateEventResultSchema, fr as t$9, g as PKCParsedOptionsSchema, gr as FailedToFetchCommentUpdateFromGatewaysError, gt as sleepUntilTimeoutOrAbort, h as NameResolverSerializedSchema, hn as VotePubsubMessagePublicationSchema, hr as FailedToFetchCommentIpfsFromGatewaysError, ht as shortifyCid, i as ChallengeMessageSignedPropertyNames, in as CommunityIpfsReservedFields, ir as e$6, j as fetchAndValidateIpnsRecordFromGateway, jr as number, k as doesDomainAddressHaveCapitalLetter, kn as CommentUpdateSchema, kr as custom, l as DecryptedChallengeAnswerSchema, ln as CreateRpcCommunityFunctionArgumentSchema, lr as n$8, m as NameResolveCacheOptionsSchema, mn as VoteChallengeRequestToEncryptSchema, mr as require_retry$1, mt as shortifyAddress, n as ChallengeAnswerMessageSignedPropertyNames, nn as CommunityEditOptionsSchema, o as ChallengeRequestMessageSignedPropertyNames, on as CommunitySignedPropertyNames, or as t$11, ot as removeNullUndefinedEmptyObjectsValuesRecursively, p as DecryptedChallengeVerificationSchema, pn as CreateVoteUserOptionsWithRefinementSchema, pr as e$4, qn as ChallengeAnswersSchema, qt as CommentModerationPubsubMessagePublicationSchema, rn as CommunityExportRecordsSchema, rr as t$13, sn as CreateNewLocalCommunityUserOptionsSchema, sr as r$8, tn as CommunityChallengeSettingSchema, tr as n$9, tt as raceAgainstAbort, un as ExportCommunityModLogsOptionsSchema, ur as r$7, ut as resolveWhenPredicateIsTrue, v as PKCUserOptionsSchema, vr as FailedToFetchGenericIpfsFromGatewaysError, vt as throwIfAbortSignalAborted, wn as CommentSignedPropertyNames, wr as require_ms$1, wt as findUpdatingComment, x as calculateIpfsCidV0, xn as CommentIpfsSchema, xr as messages, yn as CommentChallengeRequestToEncryptSchema, yr as FailedToFetchPageIpfsFromGatewaysError, yt as timestamp, z as isAbortError, zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema } from "./schema-Bbq796q3.js";
2
+ import { $ as pubsubTopicToDhtKey, $n as n$10, $t as ChallengeFileSchema, A as extractNetworkErrorDetails, An as CommentUpdateSignedPropertyNames, Ar as literal, At as refreshTrackedCommunityAliases, B as isIpfsCid, Bt as pTimeout, Cn as CommentPubsubMessageWithFlexibleAuthorRefinementSchema, Cr as require_supports_color, Ct as findStartedCommunity, D as deepMergeRuntimeFields, Dn as CommentUpdateForChallengeVerificationSignedPropertyNames, Dr as array, E as createAbortError, Er as _enum, Et as listStartedCommunities, Fn as ModQueuePageIpfsSchema, Ft as untrackStartedCommunity, Gn as AuthorCommentIpfsReservedFields, Gt as CreateCommunityEditPublicationOptionsWithRefinementSchema, H as isIpns, I as getPostUpdateTimestampRange, In as PageIpfsSchema, It as untrackUpdatingComment, Jn as CidPathSchema, Kt as CommentModerationChallengeRequestToEncryptSchema, L as hideClassPrivateProps, Ln as CommentEditChallengeRequestToEncryptSchema, Lt as untrackUpdatingCommunity, Mr as object, Mt as trackStartedCommunity, Nn as CreateCommentOptionsWithRefinementSchema, Nr as record, O as derivePublicationFromChallengeRequest, On as CommentUpdateReservedFields, Or as boolean, Ot as listUpdatingCommunities, Pn as GetPageParamSchema, Pr as string, Pt as trackUpdatingCommunity, Q as isStringDomain, Qn as CreateSignerSchema, Qt as ChallengeFileFactorySchema, R as ipnsNameToIpnsOverPubsubTopic, Rt as require_sha256$1, Sr as logger_default, Tn as CommentUpdateChallengeReservedFieldNames, Tt as findUpdatingCommunity, U as isIpnsPath, Un as CreateCommentEditOptionsWithRefinementSchema, Ut as CommunityEditPublicationSignedPropertyNames, V as isIpfsPath, Vn as CommentEditSignedPropertyNames, Vt as CommunityEditPublicationChallengeRequestToEncryptSchema, Wn as AuthorAddressSchema, Wt as CommunityEditPubsubMessagePublicationSchema, X as isRequestPubsubPublicationOfPost, Xn as CommunityAddressSchema, Xt as CommentModerationsTableRowSchema, Yn as CidStringSchema, Yt as CommentModerationSignedPropertyNames, Z as isRequestPubsubPublicationOfReply, Zn as CommunityAuthorChallengeReservedFieldNames, Zt as CreateCommentModerationOptionsWithRefinementSchema, _ as PKCUserOptionBaseSchema, _n as VoteSignedPropertyNames, _r as FailedToFetchCommunityFromGatewaysError, an as CommunityIpfsSchema, ar as e$5, b as areEquivalentCommunityAddresses, bn as CommentIpfsReservedFields, br as PKCError, bt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, c as ChallengeVerificationMessageSignedPropertyNames, cn as CreateRemoteCommunityFunctionArgumentSchema, cr as t$12, dr as t$10, f as DecryptedChallengeSchema, fn as RpcRemoteCommunityUpdateEventResultSchema, fr as t$9, g as PKCParsedOptionsSchema, gr as FailedToFetchCommentUpdateFromGatewaysError, gt as sleepUntilTimeoutOrAbort, h as NameResolverSerializedSchema, hn as VotePubsubMessagePublicationSchema, hr as FailedToFetchCommentIpfsFromGatewaysError, ht as shortifyCid, i as ChallengeMessageSignedPropertyNames, in as CommunityIpfsReservedFields, ir as e$6, j as fetchAndValidateIpnsRecordFromGateway, jr as number, k as doesDomainAddressHaveCapitalLetter, kn as CommentUpdateSchema, kr as custom, l as DecryptedChallengeAnswerSchema, ln as CreateRpcCommunityFunctionArgumentSchema, lr as n$8, m as NameResolveCacheOptionsSchema, mn as VoteChallengeRequestToEncryptSchema, mr as require_retry$1, mt as shortifyAddress, n as ChallengeAnswerMessageSignedPropertyNames, nn as CommunityEditOptionsSchema, o as ChallengeRequestMessageSignedPropertyNames, on as CommunitySignedPropertyNames, or as t$11, ot as removeNullUndefinedEmptyObjectsValuesRecursively, p as DecryptedChallengeVerificationSchema, pn as CreateVoteUserOptionsWithRefinementSchema, pr as e$4, qn as ChallengeAnswersSchema, qt as CommentModerationPubsubMessagePublicationSchema, rn as CommunityExportRecordsSchema, rr as t$13, sn as CreateNewLocalCommunityUserOptionsSchema, sr as r$8, tn as CommunityChallengeSettingSchema, tr as n$9, tt as raceAgainstAbort, un as ExportCommunityModLogsOptionsSchema, ur as r$7, ut as resolveWhenPredicateIsTrue, v as PKCUserOptionsSchema, vr as FailedToFetchGenericIpfsFromGatewaysError, vt as throwIfAbortSignalAborted, wn as CommentSignedPropertyNames, wr as require_ms$1, wt as findUpdatingComment, x as calculateIpfsCidV0, xn as CommentIpfsSchema, xr as messages, yn as CommentChallengeRequestToEncryptSchema, yr as FailedToFetchPageIpfsFromGatewaysError, yt as timestamp, z as isAbortError, zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema } from "./schema-HH2zeH-j.js";
3
3
  import { t as all } from "./src-CYIMjhjK.js";
4
4
  import { createHash } from "node:crypto";
5
5
  import { pathToFileURL } from "node:url";
@@ -92191,7 +92191,7 @@ const RpcExportCommunityModLogsResultSchema = object({ moderations: array(Commen
92191
92191
  //#endregion
92192
92192
  //#region dist/node/rpc/src/schema.js
92193
92193
  const WsServerClassOptions = object({
92194
- port: number().int().positive().optional(),
92194
+ port: number().int().nonnegative().optional(),
92195
92195
  server: custom().optional()
92196
92196
  });
92197
92197
  const CreatePKCWsServerOptionsSchema = object({
@@ -129652,11 +129652,12 @@ var RpcRemoteCommunity = class extends RemoteCommunity {
129652
129652
  async _initRpcUpdateSubscription() {
129653
129653
  const log = logger_default("pkc-js:rpc-remote-community:_initRpcUpdateSubscription");
129654
129654
  this._setState("updating");
129655
+ let subscriptionId;
129655
129656
  try {
129656
- const { subscriptionId } = await this._pkc._pkcRpcClient.communityUpdateSubscribe({
129657
+ ({subscriptionId} = await this._pkc._pkcRpcClient.communityUpdateSubscribe({
129657
129658
  name: this.name,
129658
129659
  publicKey: this.publicKey
129659
- });
129660
+ }));
129660
129661
  this._updateRpcSubscriptionId = subscriptionId;
129661
129662
  } catch (e) {
129662
129663
  log.error("Failed to receive communityUpdate from RPC due to error", e);
@@ -129664,8 +129665,17 @@ var RpcRemoteCommunity = class extends RemoteCommunity {
129664
129665
  this._setUpdatingStateWithEventEmissionIfNewState("failed");
129665
129666
  throw e;
129666
129667
  }
129667
- this._pkc._pkcRpcClient.getSubscription(this._updateRpcSubscriptionId).on("update", this._processUpdateEventFromRpcUpdate.bind(this)).on("updatingstatechange", this._handleUpdatingStateChangeFromRpcUpdate.bind(this)).on("error", this._handleRpcErrorEvent.bind(this));
129668
- this._pkc._pkcRpcClient.emitAllPendingMessages(this._updateRpcSubscriptionId);
129668
+ this._pkc._pkcRpcClient.attachSubscriptionHandlersDeferred({
129669
+ subscriptionId,
129670
+ isStale: () => this._updateRpcSubscriptionId !== subscriptionId,
129671
+ attach: (subscription) => subscription.on("update", this._processUpdateEventFromRpcUpdate.bind(this)).on("updatingstatechange", this._handleUpdatingStateChangeFromRpcUpdate.bind(this)).on("error", this._handleRpcErrorEvent.bind(this)),
129672
+ replayErrorContainment: {
129673
+ entityName: "community",
129674
+ log,
129675
+ emitError: (error) => this.emit("error", error),
129676
+ stop: () => this.stop()
129677
+ }
129678
+ });
129669
129679
  }
129670
129680
  async _createAndSubscribeToNewUpdatingCommunity(updatingCommunity) {
129671
129681
  const log = logger_default("pkc-js:rpc-remote-community:_createNewUpdatingCommunity");
@@ -129730,12 +129740,13 @@ var RpcRemoteCommunity = class extends RemoteCommunity {
129730
129740
  if (this._updatingRpcCommunityInstanceWithListeners) await this._cleanupMirroringUpdatingCommunity();
129731
129741
  else {
129732
129742
  if (this._updateRpcSubscriptionId) {
129743
+ const subscriptionId = this._updateRpcSubscriptionId;
129744
+ this._updateRpcSubscriptionId = void 0;
129733
129745
  try {
129734
- await this._pkc._pkcRpcClient.unsubscribe(this._updateRpcSubscriptionId);
129746
+ await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
129735
129747
  } catch (e) {
129736
129748
  log.error("Failed to unsubscribe from communityUpdate", e);
129737
129749
  }
129738
- this._updateRpcSubscriptionId = void 0;
129739
129750
  log.trace(`Stopped the update of remote community (${this.address}) via RPC`);
129740
129751
  }
129741
129752
  untrackUpdatingCommunity(this._pkc, this);
@@ -129926,19 +129937,29 @@ var RpcLocalCommunity = class extends RpcRemoteCommunity {
129926
129937
  }
129927
129938
  trackStartedCommunity(this._pkc, this);
129928
129939
  this.started = true;
129929
- this._pkc._pkcRpcClient.getSubscription(this._startRpcSubscriptionId).on("update", this._handleRpcUpdateEventFromStart.bind(this)).on("startedstatechange", this._handleRpcStartedStateChangeEvent.bind(this)).on("challengerequest", this._handleRpcChallengeRequestEvent.bind(this)).on("challenge", this._handleRpcChallengeEvent.bind(this)).on("challengeanswer", this._handleRpcChallengeAnswerEvent.bind(this)).on("challengeverification", this._handleRpcChallengeVerificationEvent.bind(this)).on("error", this._handleRpcErrorEvent.bind(this));
129930
- this._pkc._pkcRpcClient.emitAllPendingMessages(this._startRpcSubscriptionId);
129940
+ const subscriptionId = this._startRpcSubscriptionId;
129941
+ this._pkc._pkcRpcClient.attachSubscriptionHandlersDeferred({
129942
+ subscriptionId,
129943
+ isStale: () => this._startRpcSubscriptionId !== subscriptionId,
129944
+ attach: (subscription) => subscription.on("update", this._handleRpcUpdateEventFromStart.bind(this)).on("startedstatechange", this._handleRpcStartedStateChangeEvent.bind(this)).on("challengerequest", this._handleRpcChallengeRequestEvent.bind(this)).on("challenge", this._handleRpcChallengeEvent.bind(this)).on("challengeanswer", this._handleRpcChallengeAnswerEvent.bind(this)).on("challengeverification", this._handleRpcChallengeVerificationEvent.bind(this)).on("error", this._handleRpcErrorEvent.bind(this)),
129945
+ replayErrorContainment: {
129946
+ entityName: "community",
129947
+ log,
129948
+ emitError: (error) => this.emit("error", error),
129949
+ stop: () => this.stopWithoutRpcCall()
129950
+ }
129951
+ });
129931
129952
  }
129932
- async _cleanUpRpcConnection(log) {
129933
- if (this._startRpcSubscriptionId) try {
129934
- await this._pkc._pkcRpcClient.unsubscribe(this._startRpcSubscriptionId);
129953
+ async _cleanUpRpcConnection(log, subscriptionId = this._startRpcSubscriptionId) {
129954
+ this._startRpcSubscriptionId = void 0;
129955
+ if (subscriptionId) try {
129956
+ await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
129935
129957
  } catch (e) {
129936
129958
  log.error("Failed to unsubscribe from communityStart", e);
129937
129959
  }
129938
129960
  this._setStartedStateWithEmission("stopped");
129939
129961
  this._setRpcClientStateWithEmission("stopped");
129940
129962
  this.started = false;
129941
- this._startRpcSubscriptionId = void 0;
129942
129963
  log(`Stopped the running of local community (${this.address}) via RPC`);
129943
129964
  this._setState("stopped");
129944
129965
  }
@@ -129972,6 +129993,8 @@ var RpcLocalCommunity = class extends RpcRemoteCommunity {
129972
129993
  if (this.state === "updating") return super.stop();
129973
129994
  else if (this.state === "started") {
129974
129995
  const log = logger_default("pkc-js:rpc-local-community:stop");
129996
+ const subscriptionId = this._startRpcSubscriptionId;
129997
+ this._startRpcSubscriptionId = void 0;
129975
129998
  try {
129976
129999
  await this._pkc._pkcRpcClient.stopCommunity({
129977
130000
  name: this.name,
@@ -129980,7 +130003,7 @@ var RpcLocalCommunity = class extends RpcRemoteCommunity {
129980
130003
  } catch (e) {
129981
130004
  log.error("RPC client received an error when asking rpc server to stop community", e);
129982
130005
  }
129983
- await this._cleanUpRpcConnection(log);
130006
+ await this._cleanUpRpcConnection(log, subscriptionId);
129984
130007
  untrackStartedCommunity(this._pkc, this);
129985
130008
  }
129986
130009
  }
@@ -5536,6 +5536,7 @@ var messages;
5536
5536
  messages["ERR_RPC_CLIENT_TRYING_TO_EDIT_REMOTE_COMMUNITY"] = "RPC client is attempting to edit remote community";
5537
5537
  messages["ERR_RPC_CLIENT_TRYING_TO_DELETE_REMOTE_COMMUNITY"] = "RPC client is attempting to delete remote community";
5538
5538
  messages["ERR_RPC_CLIENT_TRYING_TO_USE_ANCHOR_METHOD_ON_NON_LOCAL_COMMUNITY"] = "RPC client is attempting to prepare or publish an anchor record for a community this node does not host locally";
5539
+ messages["ERR_RPC_CLIENT_NO_ACTIVE_PUBLISH_SUBSCRIPTION"] = "Cannot publish challenge answers over PKC RPC: there is no active publish subscription. The challenge exchange has concluded, the publication was stopped, or publish() was never called";
5539
5540
  messages["ERR_GENERIC_RPC_CLIENT_CALL_ERROR"] = "RPC client received an unknown error when executing call over websocket";
5540
5541
  messages["ERR_RPC_CALL_TIMED_OUT"] = "RPC client call timed out without receiving a response from the RPC server";
5541
5542
  messages["ERR_RPC_CLIENT_CHALLENGE_NAME_NOT_AVAILABLE_ON_SERVER"] = "The challenge name is not available on the RPC server. Available challenges are listed in details.availableChallenges";
@@ -16205,7 +16206,7 @@ function extractNetworkErrorDetails(err, depth = 0) {
16205
16206
  }
16206
16207
  //#endregion
16207
16208
  //#region dist/node/generated-version.js
16208
- const version = "0.0.92";
16209
+ const version = "0.0.93";
16209
16210
  //#endregion
16210
16211
  //#region dist/node/version.js
16211
16212
  const protocolVersion = ProtocolVersionSchema.parse("1.0.0");
@@ -1,4 +1,4 @@
1
- import { br as PKCError, et as pubsubTopicToDhtKeyCid } from "./schema-Bbq796q3.js";
1
+ import { br as PKCError, et as pubsubTopicToDhtKeyCid } from "./schema-HH2zeH-j.js";
2
2
  import { ipnsSelector } from "ipns/selector";
3
3
  import { ipnsValidator } from "ipns/validator";
4
4
  import { unmarshalIPNSRecord } from "ipns";
@@ -1,2 +1,2 @@
1
- import { a as getShortCid, i as getShortAddress, n as challenges, o as nativeFunctions, r as createAnchorIpnsRecord, s as setNativeFunctions, t as PKC } from "./chunks/node-i4Twbtvv.js";
1
+ import { a as getShortCid, i as getShortAddress, n as challenges, o as nativeFunctions, r as createAnchorIpnsRecord, s as setNativeFunctions, t as PKC } from "./chunks/node-BrLiC0qX.js";
2
2
  export { challenges, createAnchorIpnsRecord, PKC as default, getShortAddress, getShortCid, nativeFunctions, setNativeFunctions };
@@ -1,7 +1,7 @@
1
- import { Ct as findStartedCommunity, L as hideClassPrivateProps, Sr as logger_default, br as PKCError, lt as replaceXWithY, rr as t, tr as n } from "../../chunks/schema-Bbq796q3.js";
2
- import { _ as parseRpcPublishAnchorRecordParam, c as parseRpcAuthorNameParam, d as parseRpcCommentRepliesPageParam, f as parseRpcCommunityIdentifierParam, g as parseRpcExportCommunityParam, h as parseRpcExportCommunityModLogsParam, l as parseRpcCancelExportParam, m as parseRpcEditCommunityParam, p as parseRpcCommunityPageParam, t as PKC, u as parseRpcCidParam, v as parseRpcPublishChallengeAnswersParam, y as parseRpcUnsubscribeParam } from "../../chunks/node-i4Twbtvv.js";
3
- import { An as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, Cn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, J as buildPagesRuntimeFields, ct as pRetry, dn as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, dt as require_lib, jn as parseVoteChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, lt as pLimit, nn as parseCommentChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, on as parseCommentModerationChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, q as buildPageRuntimeFields, rn as parseCommentEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, rr as t$1, rt as extractCrosspostRuntimeFields, un as parseCommunityEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, ur as stringify, vn as parseCreateNewLocalCommunityUserOptionsSchemaWithPKCErrorIfItFails, yn as parseCreatePKCWsServerOptionsSchemaWithPKCErrorIfItFails } from "../../chunks/rpc-local-community-CZSOMq_6.js";
4
- import { t as LocalCommunity } from "../../chunks/local-community-DLeQ8V3i.js";
1
+ import { Ct as findStartedCommunity, L as hideClassPrivateProps, Sr as logger_default, br as PKCError, lt as replaceXWithY, rr as t, tr as n } from "../../chunks/schema-HH2zeH-j.js";
2
+ import { _ as parseRpcPublishAnchorRecordParam, c as parseRpcAuthorNameParam, d as parseRpcCommentRepliesPageParam, f as parseRpcCommunityIdentifierParam, g as parseRpcExportCommunityParam, h as parseRpcExportCommunityModLogsParam, l as parseRpcCancelExportParam, m as parseRpcEditCommunityParam, p as parseRpcCommunityPageParam, t as PKC, u as parseRpcCidParam, v as parseRpcPublishChallengeAnswersParam, y as parseRpcUnsubscribeParam } from "../../chunks/node-BrLiC0qX.js";
3
+ import { An as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, Cn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, J as buildPagesRuntimeFields, ct as pRetry, dn as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, dt as require_lib, jn as parseVoteChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, lt as pLimit, nn as parseCommentChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, on as parseCommentModerationChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, q as buildPageRuntimeFields, rn as parseCommentEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, rr as t$1, rt as extractCrosspostRuntimeFields, un as parseCommunityEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails, ur as stringify, vn as parseCreateNewLocalCommunityUserOptionsSchemaWithPKCErrorIfItFails, yn as parseCreatePKCWsServerOptionsSchemaWithPKCErrorIfItFails } from "../../chunks/rpc-local-community-DOSee621.js";
4
+ import { t as LocalCommunity } from "../../chunks/local-community-DgbMuVAA.js";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import path from "path";
7
7
  import assert from "assert";
@@ -1,3 +1,4 @@
1
+ import Logger from "../../logger.js";
1
2
  import EventEmitter from "events";
2
3
  import type { CreateNewLocalCommunityUserOptions } from "../../community/types.js";
3
4
  import type { CommentChallengeRequestToEncryptType } from "../../publications/comment/types.js";
@@ -34,6 +35,20 @@ export default class PKCRpcClient extends TypedEmitter<PKCRpcClientEvents> {
34
35
  private _deserializeRpcError;
35
36
  private _setErrorName;
36
37
  private _assignAdditionalProps;
38
+ subscriptionActive(subscriptionId: number): boolean;
39
+ attachSubscriptionHandlersDeferred(opts: {
40
+ subscriptionId: number;
41
+ isStale: () => boolean;
42
+ attach: (subscription: EventEmitter) => void;
43
+ replayErrorContainment: {
44
+ entityName: string;
45
+ log: ReturnType<typeof Logger>;
46
+ emitError: (error: Error) => void;
47
+ stop: () => Promise<void>;
48
+ };
49
+ }): void;
50
+ private _containReplayError;
51
+ private _emitPendingMessagesWhile;
37
52
  emitAllPendingMessages(subscriptionId: number): void;
38
53
  getComment(args: CidRpcParam): Promise<CommentIpfsType>;
39
54
  getCommentPage(page: CommentPageRpcParam): Promise<RpcCommentPageResult>;
@@ -10,6 +10,13 @@ import { TypedEmitter } from "tiny-typed-emitter";
10
10
  import { messages } from "../../errors.js";
11
11
  import { parseRpcCommunityIdentifierParam, parseRpcAuthorNameParam, parseRpcCidParam, parseRpcFetchCidParam, parseRpcEditCommunityParam, parseRpcCommentRepliesPageParam, parseRpcCommunityPageParam, parseRpcResolveAuthorNameResult, parseRpcFetchCidResult, parseRpcSuccessResult, parseRpcSubscriptionIdResult, parseRpcExportCommunityParam, parseRpcCancelExportParam, parseRpcExportCommunityResult, parseRpcExportCommunityModLogsParam, parseRpcExportCommunityModLogsResult, parseRpcPublishAnchorRecordParam, parseRpcAnchorPublishPreparationResult, parseRpcPublishedAnchorRecordResult } from "./rpc-schema-util.js";
12
12
  const log = Logger("pkc-js:PKCRpcClient");
13
+ // Captured at module load so the deferred attach-and-replay (attachSubscriptionHandlersDeferred)
14
+ // keeps working when a downstream app enables fake timers: vitest/jest replace the GLOBAL
15
+ // setTimeout after modules are imported, so this bound reference stays the real timer and
16
+ // subscriptions never become silently inert under un-advanced fake timers. The deferral still
17
+ // runs on a macrotask, so environments that throttle timers (e.g. hidden browser tabs) may delay
18
+ // the attach and the buffered replay accordingly.
19
+ const scheduleMacrotask = setTimeout.bind(globalThis);
13
20
  export default class PKCRpcClient extends TypedEmitter {
14
21
  constructor(rpcServerUrl) {
15
22
  super();
@@ -264,7 +271,70 @@ export default class PKCRpcClient extends TypedEmitter {
264
271
  if (rest && Object.keys(rest).length > 0)
265
272
  Object.assign(target, rest);
266
273
  }
274
+ subscriptionActive(subscriptionId) {
275
+ return Boolean(this._subscriptionEvents[subscriptionId]);
276
+ }
277
+ // Attach a subscription's notification handlers and replay its buffered notifications in a
278
+ // macrotask, so events the server emitted at subscribe time (before the JSON-RPC subscribe
279
+ // response) still reach a listener attached synchronously after the subscribing call resolves
280
+ // (#299/#314). A microtask is not enough: it is enqueued before the promise-resolution jobs
281
+ // that unwind the awaits, so it would still run before the caller's continuation. Attaching
282
+ // the handlers inside the same deferred task keeps delivery ordered: notifications arriving in
283
+ // the window find no listeners, so they are buffered and the replay drains everything in
284
+ // arrival order. Opt-in per call site because some subscribers (e.g. the exports subscription
285
+ // in rpc-local-community.ts) deliberately rely on the synchronous replay ordering.
286
+ attachSubscriptionHandlersDeferred(opts) {
287
+ scheduleMacrotask(() => {
288
+ const ownsSubscription = () => !opts.isStale() && this.subscriptionActive(opts.subscriptionId);
289
+ // The subscription may have been unsubscribed or the connection destroyed in the meantime
290
+ if (!ownsSubscription())
291
+ return;
292
+ try {
293
+ opts.attach(this.getSubscription(opts.subscriptionId));
294
+ this._emitPendingMessagesWhile(opts.subscriptionId, ownsSubscription);
295
+ }
296
+ catch (e) {
297
+ this._containReplayError(e, opts.replayErrorContainment);
298
+ }
299
+ }, 0);
300
+ }
301
+ _containReplayError(e, containment) {
302
+ const { entityName, log: siteLog, emitError, stop } = containment;
303
+ siteLog.error(`Error thrown while replaying buffered subscribe-time notifications, stopping the ${entityName}`, e);
304
+ // Surface the contained throw before stopping: without the emit the only signal is a
305
+ // debug-namespace log and a silent stop. The emit itself can throw (with no listeners
306
+ // anywhere the pkc bubbling re-throws), so it stays contained too.
307
+ try {
308
+ emitError(e instanceof Error ? e : new Error(String(e)));
309
+ }
310
+ catch (emitFailure) {
311
+ siteLog.error("No listener received the replay error", emitFailure);
312
+ }
313
+ stop().catch((stopError) => siteLog.error(`Failed to stop the ${entityName} after a replay error`, stopError));
314
+ }
315
+ // Replay the buffered notifications one message at a time, re-checking ownership between
316
+ // messages: a replayed handler may call stop(), whose synchronous prefix clears the caller's
317
+ // subscription id (directly, or through the mirror cleanup chain), and the remaining buffered
318
+ // notifications must then be dropped instead of delivered into a stopping instance. The
319
+ // messages delivered before the stop are consumed; the leftovers stay buffered for
320
+ // unsubscribe() to discard.
321
+ _emitPendingMessagesWhile(subscriptionId, shouldDeliver) {
322
+ const pendingMessages = this._pendingSubscriptionMsgs[subscriptionId];
323
+ if (!pendingMessages)
324
+ return;
325
+ while (pendingMessages.length > 0) {
326
+ if (!shouldDeliver())
327
+ return;
328
+ const message = pendingMessages.shift();
329
+ this._subscriptionEvents[subscriptionId].emit(message?.params?.event, message);
330
+ }
331
+ delete this._pendingSubscriptionMsgs[subscriptionId];
332
+ }
267
333
  emitAllPendingMessages(subscriptionId) {
334
+ // The replay may be deferred to a later task (#299), so the subscription can be
335
+ // unsubscribed or the connection destroyed before it runs
336
+ if (!this._pendingSubscriptionMsgs[subscriptionId])
337
+ return;
268
338
  this._pendingSubscriptionMsgs[subscriptionId].forEach((message) => this._subscriptionEvents[subscriptionId].emit(message?.params?.event, message));
269
339
  delete this._pendingSubscriptionMsgs[subscriptionId];
270
340
  }