@pkcprotocol/pkc-js 0.0.153 → 0.0.154

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 (96) hide show
  1. package/README.md +21 -1
  2. package/dist/browser/errors.d.ts +4 -2
  3. package/dist/browser/errors.js +4 -2
  4. package/dist/browser/errors.js.map +1 -1
  5. package/dist/browser/generated-version.d.ts +1 -1
  6. package/dist/browser/generated-version.js +1 -1
  7. package/dist/browser/pkc-error.d.ts +1 -1
  8. package/dist/browser/publications/comment/comment.d.ts +1 -0
  9. package/dist/browser/publications/comment/comment.js +57 -12
  10. package/dist/browser/publications/comment/comment.js.map +1 -1
  11. package/dist/browser/publications/publication.d.ts +8 -1
  12. package/dist/browser/publications/publication.js +393 -146
  13. package/dist/browser/publications/publication.js.map +1 -1
  14. package/dist/browser/publications/types.d.ts +1 -0
  15. package/dist/browser/rpc/src/index.js +12 -5
  16. package/dist/browser/rpc/src/index.js.map +1 -1
  17. package/dist/browser/runtime/node/blockstore.d.ts +2 -2
  18. package/dist/browser/runtime/node/blockstore.js +2 -2
  19. package/dist/browser/runtime/node/community/db-handler.d.ts +5 -7
  20. package/dist/browser/runtime/node/community/db-handler.js +79 -82
  21. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  22. package/dist/browser/runtime/node/community/local-community/cleanup.js +62 -12
  23. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  24. package/dist/browser/runtime/node/community/local-community/db-state.d.ts +1 -1
  25. package/dist/browser/runtime/node/community/local-community/db-state.js +31 -39
  26. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  27. package/dist/browser/runtime/node/community/local-community/editing.js +71 -22
  28. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  29. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js +1 -1
  30. package/dist/browser/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  31. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  32. package/dist/browser/runtime/node/community/local-community/lifecycle.js +50 -72
  33. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  34. package/dist/browser/runtime/node/community/local-community.d.ts +4 -2
  35. package/dist/browser/runtime/node/community/local-community.js +11 -7
  36. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  37. package/dist/browser/runtime/node/community/start-lock.d.ts +14 -5
  38. package/dist/browser/runtime/node/community/start-lock.js +153 -10
  39. package/dist/browser/runtime/node/community/start-lock.js.map +1 -1
  40. package/dist/browser/runtime/node/util.js +18 -10
  41. package/dist/browser/runtime/node/util.js.map +1 -1
  42. package/dist/bundled/bundle-manifest.json +35 -44
  43. package/dist/bundled/challenges.js +1 -1
  44. package/dist/bundled/chunks/{helia-for-pkc-COJ3xMF9.js → helia-for-pkc-CG9YohPs.js} +4 -4
  45. package/dist/bundled/chunks/{local-community-BTx2HxIm.js → local-community-CaQmhX8D.js} +1 -1
  46. package/dist/bundled/chunks/{local-community-CflGu_ET.js → local-community-V8_VyEhO.js} +217 -162
  47. package/dist/bundled/chunks/{node-B0b6lAIX.js → node-c4vpD2VN.js} +340 -172
  48. package/dist/bundled/chunks/{page-sort-scoring-DAMnUmDY.js → page-sort-scoring-d1frahfd.js} +1 -1
  49. package/dist/bundled/chunks/{rpc-local-community-Cy03QajY.js → rpc-local-community-DDAibWpE.js} +144 -1431
  50. package/dist/bundled/chunks/{util-C4y8KHmp.js → util-B_dKP7Te.js} +1 -1
  51. package/dist/bundled/chunks/{util-D7AtfLYH.js → util-BwEIge-b.js} +5 -3
  52. package/dist/bundled/chunks/{validate-package-factories-EH9ydbPR.js → validate-package-factories-DfpNf4oq.js} +2 -2
  53. package/dist/bundled/index.js +1 -1
  54. package/dist/bundled/page-sorts.js +1 -1
  55. package/dist/bundled/rpc/src/index.js +14 -9
  56. package/dist/node/errors.d.ts +4 -2
  57. package/dist/node/errors.js +4 -2
  58. package/dist/node/errors.js.map +1 -1
  59. package/dist/node/generated-version.d.ts +1 -1
  60. package/dist/node/generated-version.js +1 -1
  61. package/dist/node/pkc-error.d.ts +1 -1
  62. package/dist/node/publications/comment/comment.d.ts +1 -0
  63. package/dist/node/publications/comment/comment.js +57 -12
  64. package/dist/node/publications/comment/comment.js.map +1 -1
  65. package/dist/node/publications/publication.d.ts +8 -1
  66. package/dist/node/publications/publication.js +393 -146
  67. package/dist/node/publications/publication.js.map +1 -1
  68. package/dist/node/publications/types.d.ts +1 -0
  69. package/dist/node/rpc/src/index.js +12 -5
  70. package/dist/node/rpc/src/index.js.map +1 -1
  71. package/dist/node/runtime/node/blockstore.d.ts +2 -2
  72. package/dist/node/runtime/node/blockstore.js +2 -2
  73. package/dist/node/runtime/node/community/db-handler.d.ts +5 -7
  74. package/dist/node/runtime/node/community/db-handler.js +79 -82
  75. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  76. package/dist/node/runtime/node/community/local-community/cleanup.js +62 -12
  77. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  78. package/dist/node/runtime/node/community/local-community/db-state.d.ts +1 -1
  79. package/dist/node/runtime/node/community/local-community/db-state.js +31 -39
  80. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  81. package/dist/node/runtime/node/community/local-community/editing.js +71 -22
  82. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  83. package/dist/node/runtime/node/community/local-community/ipns-publishing.js +1 -1
  84. package/dist/node/runtime/node/community/local-community/ipns-publishing.js.map +1 -1
  85. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +0 -2
  86. package/dist/node/runtime/node/community/local-community/lifecycle.js +50 -72
  87. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  88. package/dist/node/runtime/node/community/local-community.d.ts +4 -2
  89. package/dist/node/runtime/node/community/local-community.js +11 -7
  90. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  91. package/dist/node/runtime/node/community/start-lock.d.ts +14 -5
  92. package/dist/node/runtime/node/community/start-lock.js +153 -10
  93. package/dist/node/runtime/node/community/start-lock.js.map +1 -1
  94. package/dist/node/runtime/node/util.js +18 -10
  95. package/dist/node/runtime/node/util.js.map +1 -1
  96. package/package.json +1 -2
@@ -1,7 +1,7 @@
1
1
  import { i as __toESM, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $ as retryKuboIpfsAdd, At as ChallengeAnswerMessageSchema, C as hideClassPrivateProps, D as isIpfsCid, Dt as require_sha256, E as isAbortError, Et as untrackUpdatingCommunity, Hr as setErrorMap, In as CommentUpdateForChallengeVerificationSchema, Ir as FailedToFetchPageIpfsFromGatewaysError, It as ChallengeVerificationMessageSchema, Jt as version_default, Lr as PKCError, Mr as FailedToFetchCommentIpfsFromGatewaysError, Mt as ChallengeMessageSchema, Nr as FailedToFetchCommentUpdateFromGatewaysError, Ot as TimeoutError, Pt as ChallengeRequestMessageSchema, Rr as messages, Sr as e$1, St as trackUpdatingComment, T as ipnsNameToIpnsOverPubsubTopic, Tt as untrackUpdatingComment, U as rejectWhenAbortSignalFires, W as rejectWhenCommunityStopsOrAborts, X as replaceXWithY, Y as removeUndefinedValuesRecursively, Z as resolveWhenPredicateIsTrue, _t as listUpdatingCommunities, a as calculateStringSizeSameAsIpfsAddCidV0Sync, at as throwIfAbortSignalAborted, br as t$1, cn as CommunityAnchorSchema, d as deepMergeRuntimeFields, dt as findStartedCommunity, et as retryKuboIpfsAddAndProvide, ft as findUpdatingComment, gr as n$2, gt as listUpdatingComments, hr as isStringDomain, ht as listStartedCommunities, i as calculateStringSizeSameAsIpfsAddCidV0, jn as CommentIpfsSchema, jr as require_retry$1, k as isIpns, kt as pTimeout, ni as en_default, nt as shortifyCid, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsSchema, pt as findUpdatingCommunity, r as calculateIpfsCidV0, rt as sleepUntilTimeoutOrAbort, st as waitForUpdateInCommunityInstanceWithErrorAndTimeout, tt as shortifyAddress, u as createAbortError, vr as n$1, vt as refreshTrackedCommentAliases, wr as r, x as getPostUpdateTimestampRange, xn as PubsubTopicSchema, xr as e, z as linkAbortSignals, zn as CommentUpdateSchema, zr as logger_default } from "./util-D7AtfLYH.js";
3
- import { $n as buildRuntimeCommunityFields, $t as RpcPublishCommunityListParamSchema, A as findCommentInParsedPages, At as parseRpcCommentUpdateEventWithPKCErrorIfItFails, B as GenericStateClient, Bn as verifyCommunityEdit, Bt as RpcCommunityIdentifierParamSchema, C as RepliesPages, Cn as signCommentModeration, Cr as getDefaultDataPath, Ct as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, D as extractCommunityRuntimeFieldsFromParsedPages, Dn as signCommunityEdit, Dr as monitorCommunitiesDirectory, Dt as parseJsonWithPKCErrorIfFails, Er as listCommunitiesSync, Et as parseDecryptedChallengeWithPKCErrorIfItFails, F as cloneCrosspostForRuntime, Fn as verifyCommentIpfs, Fr as toCommunitiesEntry, Ft as RpcAuthorNameParamSchema, G as PKCTypedEmitter, Gn as getAuthorNameFromRuntime, Gr as t$2, Gt as RpcExportCommunityParamSchema, H as InflightResourceTypes, Hn as verifyVote, Hr as t$3, Ht as RpcEditCommunityParamSchema, I as collectCrosspostAuthorsToResolve, In as verifyCommentModeration, It as RpcCancelExportParamSchema, J as decodeRpcChallengeRequestPubsubMsg, Jn as CreateCommunityListWithCidOptionsSchema, Jr as MAX_FILE_SIZE_BYTES_FOR_COMMENT_UPDATE, Jt as RpcFetchCidResultSchema, K as decodeRpcChallengeAnswerPubsubMsg, Kn as getAuthorNameFromWire, Kr as t$4, Kt as RpcExportCommunityResultSchema, Ln as verifyCommentPubsubMessage, Lt as RpcCidParamSchema, M as parseRawPages, Mr as setNativeFunctions$1, Nn as verifyChallengeVerification, Nr as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, Nt as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, O as findCommentInPageInstance, On as signCommunityList, Ot as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, P as applyNameResolvedCacheToCrosspost, Pn as verifyCommentEdit, Pr as findCommunitiesEntry, Pt as RpcAnchorPublishPreparationResultSchema, Qt as RpcPublishChallengeAnswersParamSchema, R as stripNameResolvedFromCrosspost, Rn as verifyCommentUpdate, Rt as RpcCommentRepliesPageParamSchema, Sn as signCommentEdit, St as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, Tt as parseDecryptedChallengeVerification, Un as buildRuntimeAuthor, Ur as n$3, Ut as RpcExportCommunityModLogsParamSchema, V as InflightFetchManager, Vn as verifyCommunityList, Vt as RpcCommunityPageParamSchema, Wn as cleanWireAuthor, Wt as RpcExportCommunityModLogsResultSchema, Xn as MAX_COMMUNITY_LIST_SIZE_BYTES, Xr as NAME_RESOLVED_TRUE_TTL_MS, Xt as RpcFetchCommunityListResultSchema, Y as decodeRpcChallengeVerificationPubsubMsg, Yn as CreateNewCommunityListOptionsSchema, Yr as NAME_RESOLVED_FALSE_TTL_MS, Yt as RpcFetchCommunityListParamSchema, Zr as NAME_RESOLVE_FAILED_RETRY_FLOOR_MS, Zt as RpcPublishAnchorRecordParamSchema, _n as signChallengeAnswer, _t as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, an as RpcUnsubscribeParamSchema, b as KeyvBetterSqlite3, br as findLocalCommunityAddress, ct as parseCommentUpdateSchemaWithPKCErrorIfItFails, dn as decryptEd25519AesGcm, ei as nativeFunctions$2, en as RpcPublishCommunityListResultSchema, er as getCommunityAddressFromRecord, et as parseCidStringSchemaWithPKCErrorIfItFails, ft as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, gn as cleanUpBeforePublishing, gt as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, hr as createKuboRpcClient, ht as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, in as RpcSuccessResultSchema, ir as decode, it as parseCommentIpfsSchemaWithPKCErrorIfItFails, jn as verifyChallengeMessage, jt as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, k as findCommentInPageInstanceRecursively, kn as signVote, kt as parseRpcCommentEventWithPKCErrorIfItFails, l as pkcJsPageSorts, ln as createSigner, lr as getPKCAddressFromPublicKeySync, lt as parseCommunityAddressWithPKCErrorIfItFails, m as pkcJsChallenges, mt as parseCommunityListSchemaWithPKCErrorIfItFails, n as RpcRemoteCommunity, nn as RpcResolveAuthorNameResultSchema, nr as getCommunityPublicKeyFromWire, on as findCommunityRecordNameMismatch, or as getBufferedPKCAddressFromPublicKey, ot as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, pn as encryptEd25519AesGcm, q as decodeRpcChallengePubsubMsg, qn as normalizeCreatePublicationAuthor, qt as RpcFetchCidParamSchema, rn as RpcSubscriptionIdResultSchema, rr as normalizeCommunityInputFromCommunity, rt as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, sn as require_lib$1, st as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, t as RpcLocalCommunity, tn as RpcPublishedAnchorRecordResultSchema, tr as getCommunityNameFromWire, un as createAnchorIpnsRecord$1, v as TrackedInstanceRegistry, vt as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, x as RemoteCommunity, xn as signComment, xt as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, y as LRUCache, yn as signChallengeRequest, z as PKCClientsManager, zr as t$5, zt as RpcCommunitiesChangeEventResultSchema } from "./rpc-local-community-Cy03QajY.js";
4
- import { s as getHeliaDebugContext } from "./util-C4y8KHmp.js";
2
+ import { $ as retryKuboIpfsAdd, At as ChallengeAnswerMessageSchema, C as hideClassPrivateProps, D as isIpfsCid, Dt as require_sha256, E as isAbortError, Et as untrackUpdatingCommunity, Hr as setErrorMap, In as CommentUpdateForChallengeVerificationSchema, Ir as FailedToFetchPageIpfsFromGatewaysError, It as ChallengeVerificationMessageSchema, Jt as version_default, Lr as PKCError, Mr as FailedToFetchCommentIpfsFromGatewaysError, Mt as ChallengeMessageSchema, Nr as FailedToFetchCommentUpdateFromGatewaysError, Ot as TimeoutError, Pt as ChallengeRequestMessageSchema, Rr as messages, Sr as e$1, St as trackUpdatingComment, T as ipnsNameToIpnsOverPubsubTopic, Tt as untrackUpdatingComment, U as rejectWhenAbortSignalFires, W as rejectWhenCommunityStopsOrAborts, X as replaceXWithY, Y as removeUndefinedValuesRecursively, Z as resolveWhenPredicateIsTrue, _t as listUpdatingCommunities, a as calculateStringSizeSameAsIpfsAddCidV0Sync, at as throwIfAbortSignalAborted, br as t$1, cn as CommunityAnchorSchema, d as deepMergeRuntimeFields, dt as findStartedCommunity, et as retryKuboIpfsAddAndProvide, ft as findUpdatingComment, gr as n$2, gt as listUpdatingComments, hr as isStringDomain, ht as listStartedCommunities, i as calculateStringSizeSameAsIpfsAddCidV0, jn as CommentIpfsSchema, jr as require_retry$1, k as isIpns, kt as pTimeout, ni as en_default, nt as shortifyCid, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsSchema, pt as findUpdatingCommunity, r as calculateIpfsCidV0, rt as sleepUntilTimeoutOrAbort, st as waitForUpdateInCommunityInstanceWithErrorAndTimeout, tt as shortifyAddress, u as createAbortError, vr as n$1, vt as refreshTrackedCommentAliases, wr as r, x as getPostUpdateTimestampRange, xn as PubsubTopicSchema, xr as e, z as linkAbortSignals, zn as CommentUpdateSchema, zr as logger_default } from "./util-BwEIge-b.js";
3
+ import { $n as buildRuntimeCommunityFields, $r as NAME_RESOLVE_FAILED_RETRY_FLOOR_MS, $t as RpcPublishCommunityListParamSchema, A as findCommentInParsedPages, At as parseRpcCommentUpdateEventWithPKCErrorIfItFails, B as GenericStateClient, Bn as verifyCommunityEdit, Bt as RpcCommunityIdentifierParamSchema, C as RepliesPages, Cn as signCommentModeration, Cr as getDefaultDataPath, Ct as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, D as extractCommunityRuntimeFieldsFromParsedPages, Dn as signCommunityEdit, Dr as monitorCommunitiesDirectory, Dt as parseJsonWithPKCErrorIfFails, Er as listCommunitiesSync, Et as parseDecryptedChallengeWithPKCErrorIfItFails, F as cloneCrosspostForRuntime, Fn as verifyCommentIpfs, Fr as toCommunitiesEntry, Ft as RpcAuthorNameParamSchema, G as PKCTypedEmitter, Gn as getAuthorNameFromRuntime, Gr as n$3, Gt as RpcExportCommunityParamSchema, H as InflightResourceTypes, Hn as verifyVote, Ht as RpcEditCommunityParamSchema, I as collectCrosspostAuthorsToResolve, In as verifyCommentModeration, It as RpcCancelExportParamSchema, J as decodeRpcChallengeRequestPubsubMsg, Jn as CreateCommunityListWithCidOptionsSchema, Jr as t$4, Jt as RpcFetchCidResultSchema, K as decodeRpcChallengeAnswerPubsubMsg, Kn as getAuthorNameFromWire, Kt as RpcExportCommunityResultSchema, Ln as verifyCommentPubsubMessage, Lt as RpcCidParamSchema, M as parseRawPages, Mr as setNativeFunctions$1, Nn as verifyChallengeVerification, Nr as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, Nt as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, O as findCommentInPageInstance, On as signCommunityList, Ot as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, P as applyNameResolvedCacheToCrosspost, Pn as verifyCommentEdit, Pr as findCommunitiesEntry, Pt as RpcAnchorPublishPreparationResultSchema, Qr as NAME_RESOLVED_TRUE_TTL_MS, Qt as RpcPublishChallengeAnswersParamSchema, R as stripNameResolvedFromCrosspost, Rn as verifyCommentUpdate, Rt as RpcCommentRepliesPageParamSchema, Sn as signCommentEdit, St as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, Tt as parseDecryptedChallengeVerification, Un as buildRuntimeAuthor, Ut as RpcExportCommunityModLogsParamSchema, V as InflightFetchManager, Vn as verifyCommunityList, Vr as t$5, Vt as RpcCommunityPageParamSchema, Wn as cleanWireAuthor, Wr as t$3, Wt as RpcExportCommunityModLogsResultSchema, Xn as MAX_COMMUNITY_LIST_SIZE_BYTES, Xr as MAX_FILE_SIZE_BYTES_FOR_COMMENT_UPDATE, Xt as RpcFetchCommunityListResultSchema, Y as decodeRpcChallengeVerificationPubsubMsg, Yn as CreateNewCommunityListOptionsSchema, Yt as RpcFetchCommunityListParamSchema, Zr as NAME_RESOLVED_FALSE_TTL_MS, Zt as RpcPublishAnchorRecordParamSchema, _n as signChallengeAnswer, _t as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, an as RpcUnsubscribeParamSchema, b as KeyvBetterSqlite3, br as findLocalCommunityAddress, ct as parseCommentUpdateSchemaWithPKCErrorIfItFails, dn as decryptEd25519AesGcm, en as RpcPublishCommunityListResultSchema, er as getCommunityAddressFromRecord, et as parseCidStringSchemaWithPKCErrorIfItFails, ft as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, gn as cleanUpBeforePublishing, gt as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, hr as createKuboRpcClient, ht as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, in as RpcSuccessResultSchema, ir as decode, it as parseCommentIpfsSchemaWithPKCErrorIfItFails, jn as verifyChallengeMessage, jt as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, k as findCommentInPageInstanceRecursively, kn as signVote, kt as parseRpcCommentEventWithPKCErrorIfItFails, l as pkcJsPageSorts, ln as createSigner, lr as getPKCAddressFromPublicKeySync, lt as parseCommunityAddressWithPKCErrorIfItFails, m as pkcJsChallenges, mt as parseCommunityListSchemaWithPKCErrorIfItFails, n as RpcRemoteCommunity, ni as nativeFunctions$2, nn as RpcResolveAuthorNameResultSchema, nr as getCommunityPublicKeyFromWire, on as findCommunityRecordNameMismatch, or as getBufferedPKCAddressFromPublicKey, ot as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, pn as encryptEd25519AesGcm, q as decodeRpcChallengePubsubMsg, qn as normalizeCreatePublicationAuthor, qr as t$2, qt as RpcFetchCidParamSchema, rn as RpcSubscriptionIdResultSchema, rr as normalizeCommunityInputFromCommunity, rt as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, sn as require_lib$1, st as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, t as RpcLocalCommunity, tn as RpcPublishedAnchorRecordResultSchema, tr as getCommunityNameFromWire, un as createAnchorIpnsRecord$1, v as TrackedInstanceRegistry, vt as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, x as RemoteCommunity, xn as signComment, xt as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, y as LRUCache, yn as signChallengeRequest, z as PKCClientsManager, zt as RpcCommunitiesChangeEventResultSchema } from "./rpc-local-community-DDAibWpE.js";
4
+ import { s as getHeliaDebugContext } from "./util-B_dKP7Te.js";
5
5
  import path from "path";
6
6
  import assert from "assert";
7
7
  import fs from "fs";
@@ -27366,6 +27366,7 @@ var PublicationClientsManager = class extends PKCClientsManager {
27366
27366
  };
27367
27367
  //#endregion
27368
27368
  //#region dist/node/publications/publication.js
27369
+ const LOCAL_COMMUNITY_PROVIDER = "publishing directly to local community instance";
27369
27370
  var Publication = class extends import_lib.TypedEmitter {
27370
27371
  constructor(pkc) {
27371
27372
  super();
@@ -27373,6 +27374,9 @@ var Publication = class extends import_lib.TypedEmitter {
27373
27374
  this._community = void 0;
27374
27375
  this._signedWithKnownCommunityFields = void 0;
27375
27376
  this._challengeExchanges = {};
27377
+ this._isPublishSpent = false;
27378
+ this._isPublishCallRunning = false;
27379
+ this._publishEndedBy = void 0;
27376
27380
  this._rpcPublishSubscriptionId = void 0;
27377
27381
  this._pkc = pkc;
27378
27382
  this._updatePublishingStateWithEmission("stopped");
@@ -27486,8 +27490,13 @@ var Publication = class extends import_lib.TypedEmitter {
27486
27490
  };
27487
27491
  }
27488
27492
  async _handleRpcChallengeVerification(verification, runtimeFields) {
27489
- const log = logger_default("pkc-js:publication:_handleRpcChallengeVerification");
27490
- if (verification.comment) await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(verification);
27493
+ if (verification.comment) try {
27494
+ await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(verification);
27495
+ } catch (e) {
27496
+ logger_default("pkc-js:publication:_handleRpcChallengeVerification").error("The comment in a successful challenge verification does not verify", e);
27497
+ await this._tearDownThenWriteFailure(e);
27498
+ return;
27499
+ }
27491
27500
  if (this instanceof Comment && runtimeFields) deepMergeRuntimeFields(this, runtimeFields);
27492
27501
  this._setRpcClientState("stopped");
27493
27502
  const newPublishingState = verification.challengeSuccess ? "succeeded" : "failed";
@@ -27499,16 +27508,7 @@ var Publication = class extends import_lib.TypedEmitter {
27499
27508
  args: [verification, this instanceof Comment && verification.comment ? this : void 0]
27500
27509
  }
27501
27510
  });
27502
- this._unregisterFromPkcOncePublishWorkSettles();
27503
- if (this._rpcPublishSubscriptionId) {
27504
- const subscriptionId = this._rpcPublishSubscriptionId;
27505
- this._rpcPublishSubscriptionId = void 0;
27506
- try {
27507
- await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
27508
- } catch (e) {
27509
- log.error("Failed to unsubscribe from publication publish", e);
27510
- }
27511
- }
27511
+ await this._postSucessOrFailurePublishing();
27512
27512
  }
27513
27513
  async _handleIncomingChallengePubsubMessage(msg) {
27514
27514
  const log = logger_default("pkc-js:publication:_handleIncomingChallengePubsubMessage");
@@ -27518,19 +27518,13 @@ var Publication = class extends import_lib.TypedEmitter {
27518
27518
  communityChallengeSignerAddress: this._communityChallengeMsgSignerAddress(),
27519
27519
  validateTimestampRange: true
27520
27520
  });
27521
+ if (this._hasPublishEnded()) return;
27521
27522
  if (!challengeMsgValidity.valid) {
27522
27523
  const error = new PKCError("ERR_CHALLENGE_SIGNATURE_IS_INVALID", {
27523
27524
  pubsubMsg: msg,
27524
27525
  reason: challengeMsgValidity.reason
27525
27526
  });
27526
- log.error("received challenge message with invalid signature", error.toString());
27527
- this._changePublicationStateEmitEventEmitStateChangeEvent({
27528
- newPublishingState: "failed",
27529
- event: {
27530
- name: "error",
27531
- args: [error]
27532
- }
27533
- });
27527
+ log.error("Dropping a challenge message with an invalid signature", error.toString());
27534
27528
  return;
27535
27529
  }
27536
27530
  log(`Received encrypted challenges. Will decrypt and emit them on "challenge" event. User shoud publish solution by calling publishChallengeAnswers`);
@@ -27540,6 +27534,7 @@ var Publication = class extends import_lib.TypedEmitter {
27540
27534
  try {
27541
27535
  decryptedRawString = await decryptEd25519AesGcm(msg.encrypted, pubsubSigner.privateKey, this._community.encryption.publicKey);
27542
27536
  } catch (e) {
27537
+ if (this._hasPublishEnded()) return;
27543
27538
  const pkcError = new PKCError("ERR_PUBLICATION_FAILED_TO_DECRYPT_CHALLENGE", { decryptErr: e });
27544
27539
  log.error("could not decrypt challengemessage.encrypted", pkcError.toString());
27545
27540
  this._changePublicationStateEmitEventEmitStateChangeEvent({
@@ -27555,6 +27550,7 @@ var Publication = class extends import_lib.TypedEmitter {
27555
27550
  try {
27556
27551
  decryptedJson = await parseJsonWithPKCErrorIfFails(decryptedRawString);
27557
27552
  } catch (e) {
27553
+ if (this._hasPublishEnded()) return;
27558
27554
  log.error("could not parse decrypted challengemessage.encrypted as a json", String(e));
27559
27555
  this._changePublicationStateEmitEventEmitStateChangeEvent({
27560
27556
  newPublishingState: "failed",
@@ -27569,6 +27565,7 @@ var Publication = class extends import_lib.TypedEmitter {
27569
27565
  try {
27570
27566
  decryptedChallenge = parseDecryptedChallengeWithPKCErrorIfItFails(decryptedJson);
27571
27567
  } catch (e) {
27568
+ if (this._hasPublishEnded()) return;
27572
27569
  log.error("could not parse z challengemessage.encrypted as a json", String(e));
27573
27570
  this._changePublicationStateEmitEventEmitStateChangeEvent({
27574
27571
  newPublishingState: "failed",
@@ -27587,6 +27584,7 @@ var Publication = class extends import_lib.TypedEmitter {
27587
27584
  log.trace("Received a copy of a challenge that was already handled, ignoring it");
27588
27585
  return;
27589
27586
  }
27587
+ if (this._hasPublishEnded()) return;
27590
27588
  this._challengeExchanges[msg.challengeRequestId.toString()].challenge = decryptedChallengeMsg;
27591
27589
  this._updatePublishingStateWithEmission("waiting-challenge-answers");
27592
27590
  const challengeTopic = this._community?.pubsubTopic;
@@ -27601,19 +27599,13 @@ var Publication = class extends import_lib.TypedEmitter {
27601
27599
  communityChallengeSignerAddress: this._communityChallengeMsgSignerAddress(),
27602
27600
  validateTimestampRange: true
27603
27601
  });
27602
+ if (this._hasPublishEnded()) return;
27604
27603
  if (!signatureValidation.valid) {
27605
27604
  const error = new PKCError("ERR_CHALLENGE_VERIFICATION_SIGNATURE_IS_INVALID", {
27606
27605
  pubsubMsg: msg,
27607
27606
  reason: signatureValidation.reason
27608
27607
  });
27609
- log.error("Publication received a challenge verification with invalid signature", error);
27610
- this._changePublicationStateEmitEventEmitStateChangeEvent({
27611
- newPublishingState: "failed",
27612
- event: {
27613
- name: "error",
27614
- args: [error]
27615
- }
27616
- });
27608
+ log.error("Dropping a challenge verification with an invalid signature", error);
27617
27609
  return;
27618
27610
  }
27619
27611
  let decryptedChallengeVerification;
@@ -27633,7 +27625,10 @@ var Publication = class extends import_lib.TypedEmitter {
27633
27625
  challenegVerificationMsg: msg
27634
27626
  });
27635
27627
  log.error("could not decrypt challengeverification.encrypted", pkcError);
27636
- this.emit("error", pkcError);
27628
+ await this._endExchangeWithUnreadableChallengeVerification({
27629
+ verification: msg,
27630
+ error: pkcError
27631
+ });
27637
27632
  return;
27638
27633
  }
27639
27634
  let decryptedJson;
@@ -27641,14 +27636,20 @@ var Publication = class extends import_lib.TypedEmitter {
27641
27636
  decryptedJson = await parseJsonWithPKCErrorIfFails(decryptedRawString);
27642
27637
  } catch (e) {
27643
27638
  log.error("could not parse decrypted challengeverification.encrypted as a json", e);
27644
- this.emit("error", e);
27639
+ await this._endExchangeWithUnreadableChallengeVerification({
27640
+ verification: msg,
27641
+ error: e
27642
+ });
27645
27643
  return;
27646
27644
  }
27647
27645
  try {
27648
27646
  decryptedChallengeVerification = parseDecryptedChallengeVerification(decryptedJson);
27649
27647
  } catch (e) {
27650
27648
  log.error("could not parse challengeverification.encrypted due to invalid schema", e);
27651
- this.emit("error", e);
27649
+ await this._endExchangeWithUnreadableChallengeVerification({
27650
+ verification: msg,
27651
+ error: e
27652
+ });
27652
27653
  return;
27653
27654
  }
27654
27655
  }
@@ -27664,9 +27665,16 @@ var Publication = class extends import_lib.TypedEmitter {
27664
27665
  log.trace("Received a copy of a challenge verification that was already handled, ignoring it");
27665
27666
  return;
27666
27667
  }
27668
+ if (!this._claimPublishEnd("verification")) return;
27667
27669
  this._challengeExchanges[msg.challengeRequestId.toString()].challengeVerification = challengeVerificationMsg;
27668
27670
  if (decryptedChallengeVerification?.comment) {
27669
- await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(decryptedChallengeVerification);
27671
+ try {
27672
+ await this._verifyDecryptedChallengeVerificationAndUpdateCommentProps(decryptedChallengeVerification);
27673
+ } catch (e) {
27674
+ log.error("The comment in a successful challenge verification does not verify", e);
27675
+ await this._tearDownThenWriteFailure(e);
27676
+ return;
27677
+ }
27670
27678
  log("Updated the props of this instance with challengeverification.encrypted");
27671
27679
  }
27672
27680
  Object.values(this._challengeExchanges).forEach((exchange) => this._updatePubsubState("stopped", exchange.providerUrl));
@@ -27680,6 +27688,41 @@ var Publication = class extends import_lib.TypedEmitter {
27680
27688
  });
27681
27689
  await this._postSucessOrFailurePublishing();
27682
27690
  }
27691
+ async _endExchangeWithUnreadableChallengeVerification({ verification, error }) {
27692
+ const exchange = this._challengeExchanges[verification.challengeRequestId.toString()];
27693
+ if (exchange.challengeVerification || this._hasPublishEnded()) return;
27694
+ exchange.challengeVerification = verification;
27695
+ await this._endPublishWithFailure(() => this._changePublicationStateEmitEventEmitStateChangeEvent({
27696
+ newPublishingState: "failed",
27697
+ event: {
27698
+ name: "error",
27699
+ args: [error]
27700
+ }
27701
+ }));
27702
+ }
27703
+ _claimPublishEnd(endedBy) {
27704
+ if (this._publishEndedBy) return false;
27705
+ this._publishEndedBy = endedBy;
27706
+ return true;
27707
+ }
27708
+ _hasPublishEnded() {
27709
+ return this._publishEndedBy !== void 0 || this._pkc.destroyed;
27710
+ }
27711
+ async _endPublishWithFailure(writeFailure) {
27712
+ if (!this._claimPublishEnd("failure")) return void 0;
27713
+ await this._postSucessOrFailurePublishing();
27714
+ return writeFailure();
27715
+ }
27716
+ async _tearDownThenWriteFailure(error) {
27717
+ await this._postSucessOrFailurePublishing();
27718
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
27719
+ newPublishingState: "failed",
27720
+ event: {
27721
+ name: "error",
27722
+ args: [error]
27723
+ }
27724
+ });
27725
+ }
27683
27726
  async _handleChallengeExchange(pubsubMsg) {
27684
27727
  const log = logger_default("pkc-js:publication:handleChallengeExchange");
27685
27728
  let decodedJson;
@@ -27727,6 +27770,12 @@ var Publication = class extends import_lib.TypedEmitter {
27727
27770
  challengeAnswers: toEncryptAnswers.challengeAnswers
27728
27771
  });
27729
27772
  }
27773
+ if (this._publishEndedBy) throw new PKCError("ERR_PUBLICATION_CHALLENGE_EXCHANGE_ENDED", {
27774
+ publicationType: this.getType(),
27775
+ state: this.state,
27776
+ publishingState: this.publishingState,
27777
+ endedBy: this._publishEndedBy
27778
+ });
27730
27779
  const challengeExchangesWithChallenge = Object.values(this._challengeExchanges).filter((exchange) => exchange.challenge);
27731
27780
  if (challengeExchangesWithChallenge.length === 0) throw Error("No challenge exchanges with challenge");
27732
27781
  if (challengeExchangesWithChallenge.length > 1) throw Error("We should only have one challenge exchange with challenge");
@@ -27761,15 +27810,29 @@ var Publication = class extends import_lib.TypedEmitter {
27761
27810
  challengeExchange.challengeAnswerPublishInFlight = false;
27762
27811
  throw e;
27763
27812
  }
27813
+ const throwIfExchangeEnded = () => {
27814
+ if (!this._publishEndedBy) return;
27815
+ challengeExchange.challengeAnswerPublishInFlight = false;
27816
+ throw new PKCError("ERR_PUBLICATION_CHALLENGE_EXCHANGE_ENDED", {
27817
+ publicationType: this.getType(),
27818
+ state: this.state,
27819
+ publishingState: this.publishingState,
27820
+ endedBy: this._publishEndedBy
27821
+ });
27822
+ };
27823
+ throwIfExchangeEnded();
27764
27824
  this._updatePublishingStateWithEmission("publishing-challenge-answer");
27825
+ throwIfExchangeEnded();
27765
27826
  this._updatePubsubState("publishing-challenge-answer", challengeExchange.providerUrl);
27766
27827
  if (this._publishingToLocalCommunity) try {
27767
27828
  await this._publishingToLocalCommunity.handleChallengeAnswer(answerMsgToPublish);
27768
27829
  } catch (e) {
27769
27830
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishError = e;
27770
27831
  challengeExchange.challengeAnswerPublishInFlight = false;
27771
- this._updatePublishingStateWithEmission("failed");
27772
- this._updatePubsubState("stopped", challengeExchange.providerUrl);
27832
+ if (!this._publishEndedBy) {
27833
+ this._updatePublishingStateWithEmission("failed");
27834
+ this._updatePubsubState("stopped", challengeExchange.providerUrl);
27835
+ }
27773
27836
  throw e;
27774
27837
  }
27775
27838
  else try {
@@ -27777,8 +27840,10 @@ var Publication = class extends import_lib.TypedEmitter {
27777
27840
  } catch (e) {
27778
27841
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishError = e;
27779
27842
  challengeExchange.challengeAnswerPublishInFlight = false;
27780
- this._updatePublishingStateWithEmission("failed");
27781
- this._updatePubsubState("stopped", challengeExchange.providerUrl);
27843
+ if (!this._publishEndedBy) {
27844
+ this._updatePublishingStateWithEmission("failed");
27845
+ this._updatePubsubState("stopped", challengeExchange.providerUrl);
27846
+ }
27782
27847
  throw e;
27783
27848
  }
27784
27849
  const decryptedChallengeAnswer = {
@@ -27787,9 +27852,12 @@ var Publication = class extends import_lib.TypedEmitter {
27787
27852
  };
27788
27853
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswer = decryptedChallengeAnswer;
27789
27854
  this._challengeExchanges[challengeExchange.challengeRequest.challengeRequestId.toString()].challengeAnswerPublishTimestamp = timestamp();
27790
- this._updatePublishingStateWithEmission("waiting-challenge-verification");
27791
- const challengeTopic = this._community?.pubsubTopic;
27792
- Object.entries(this._clientsManager.pubsubProviderSubscriptions).filter(([, pubsubTopics]) => typeof challengeTopic === "string" && pubsubTopics.includes(challengeTopic)).map(([provider]) => provider).forEach((provider) => this._updatePubsubState("waiting-challenge-verification", provider));
27855
+ if (this._publishEndedBy === "stop") return;
27856
+ if (!this._publishEndedBy) {
27857
+ this._updatePublishingStateWithEmission("waiting-challenge-verification");
27858
+ const challengeTopic = this._community?.pubsubTopic;
27859
+ Object.entries(this._clientsManager.pubsubProviderSubscriptions).filter(([, pubsubTopics]) => typeof challengeTopic === "string" && pubsubTopics.includes(challengeTopic)).map(([provider]) => provider).forEach((provider) => this._updatePubsubState("waiting-challenge-verification", provider));
27860
+ }
27793
27861
  log(`Responded to challenge with answers`, challengeAnswers);
27794
27862
  this.emit("challengeanswer", decryptedChallengeAnswer);
27795
27863
  }
@@ -27875,8 +27943,9 @@ var Publication = class extends import_lib.TypedEmitter {
27875
27943
  publicationType: this.getType(),
27876
27944
  communityAddress: this.communityAddress
27877
27945
  }));
27878
- if (this._backgroundCommunityRefresh) await this._backgroundCommunityRefresh;
27946
+ const refresh = this._backgroundCommunityRefresh;
27879
27947
  this._resetCommunityFetchAbortSignal();
27948
+ if (refresh) await refresh;
27880
27949
  }
27881
27950
  _resetCommunityFetchAbortSignal() {
27882
27951
  this._communityFetchAbortController = void 0;
@@ -27890,9 +27959,6 @@ var Publication = class extends import_lib.TypedEmitter {
27890
27959
  if (!this._publishRunWaitSignal) this._beginPublishRun();
27891
27960
  return this._publishRunWaitSignal;
27892
27961
  }
27893
- _isPublishRunOver(runSignal) {
27894
- return this._pkc.destroyed || runSignal.aborted;
27895
- }
27896
27962
  _getCommunityCache() {
27897
27963
  const cache = this._pkc._memCaches.communityForPublishing;
27898
27964
  if (cache.has(this.communityAddress)) return cache.get(this.communityAddress);
@@ -27954,20 +28020,26 @@ var Publication = class extends import_lib.TypedEmitter {
27954
28020
  } else return this._clientsManager.fetchCommunityForPublishingWithCacheGuard();
27955
28021
  }
27956
28022
  async stop() {
28023
+ const wasPublishCalled = this._isPublishSpent || this._isPublishCallRunning;
28024
+ if (wasPublishCalled) this._isPublishSpent = true;
28025
+ const endedByThisStop = wasPublishCalled ? this._claimPublishEnd("stop") : true;
27957
28026
  this._communityFetchAbortController?.abort(new PKCError("ERR_GET_COMMUNITY_ABORTED", {
27958
28027
  publicationType: this.getType(),
27959
28028
  communityAddress: this.communityAddress
27960
28029
  }));
28030
+ if (!wasPublishCalled) this._resetCommunityFetchAbortSignal();
27961
28031
  try {
27962
28032
  await this._postSucessOrFailurePublishing();
27963
28033
  } finally {
27964
- if (this._backgroundCommunityRefresh) await this._backgroundCommunityRefresh;
27965
- this._updatePublishingStateWithEmission("stopped");
28034
+ if (wasPublishCalled && this._backgroundCommunityRefresh) await this._backgroundCommunityRefresh;
28035
+ const publishStartedSinceThisStop = !wasPublishCalled && (this._isPublishSpent || this._isPublishCallRunning);
28036
+ if (endedByThisStop && !publishStartedSinceThisStop) this._updatePublishingStateWithEmission("stopped");
27966
28037
  }
27967
28038
  }
27968
28039
  _isAllAttemptsExhausted(maxNumOfChallengeExchanges) {
27969
- if (Object.keys(this._challengeExchanges).length !== maxNumOfChallengeExchanges) return false;
27970
- return Object.values(this._challengeExchanges).every((exchange) => {
28040
+ const challengeExchanges = Object.values(this._challengeExchanges);
28041
+ if (challengeExchanges.length !== maxNumOfChallengeExchanges) return false;
28042
+ return challengeExchanges.every((exchange) => {
27971
28043
  if (exchange.challenge || exchange.challengeVerification) return false;
27972
28044
  if (exchange.challengeRequestPublishError || exchange.challengeAnswerPublishError) return true;
27973
28045
  return typeof exchange.challengeRequestPublishTimestamp === "number" && exchange.challengeRequestPublishTimestamp + this._setProviderFailureThresholdSeconds <= timestamp();
@@ -27977,7 +28049,7 @@ var Publication = class extends import_lib.TypedEmitter {
27977
28049
  return Object.values(this._challengeExchanges).some((exchange) => typeof exchange.challengeRequestPublishTimestamp === "number" && !exchange.challengeRequestPublishError);
27978
28050
  }
27979
28051
  async _abandonProviderIfStoppedWhileSubscribing(providerUrl) {
27980
- if (!this._pkc.destroyed && this.state !== "stopped") return false;
28052
+ if (!this._hasPublishEnded() && this.state !== "stopped") return false;
27981
28053
  const log = logger_default("pkc-js:publication:publish:_abandonProviderIfStoppedWhileSubscribing");
27982
28054
  log("Publication was stopped while subscribing to pubsub, will not publish a challenge request", providerUrl);
27983
28055
  try {
@@ -27997,7 +28069,7 @@ var Publication = class extends import_lib.TypedEmitter {
27997
28069
  const log = logger_default("pkc-js:publication:_postSucessOrFailurePublishing");
27998
28070
  this._publishRunAbortController?.abort();
27999
28071
  this._unregisterFromPkcOncePublishWorkSettles();
28000
- this._setStateWithEmission("stopped");
28072
+ if (this.state === "publishing") this._setStateWithEmission("stopped");
28001
28073
  if (this._rpcPublishSubscriptionId) {
28002
28074
  const subscriptionId = this._rpcPublishSubscriptionId;
28003
28075
  this._rpcPublishSubscriptionId = void 0;
@@ -28046,6 +28118,7 @@ var Publication = class extends import_lib.TypedEmitter {
28046
28118
  async _handleIncomingChallengeVerificationFromRpc(args) {
28047
28119
  const { challengeVerification: encoded, runtimeFields } = args.params.result;
28048
28120
  const decoded = decodeRpcChallengeVerificationPubsubMsg(encoded);
28121
+ if (!this._claimPublishEnd("verification")) return;
28049
28122
  this._challengeExchanges[decoded.challengeRequestId.toString()] = {
28050
28123
  ...this._challengeExchanges[decoded.challengeRequestId.toString()],
28051
28124
  challengeVerification: decoded
@@ -28064,11 +28137,23 @@ var Publication = class extends import_lib.TypedEmitter {
28064
28137
  async _handleIncomingErrorFromRpc(args) {
28065
28138
  const log = logger_default("pkc-js:publication:publish:_publishWithRpc:_handleIncomingErrorFromRpc");
28066
28139
  const error = args.params.result;
28067
- if (error.details?.newPublishingState) this._updatePublishingStateNoEmission(error.details.newPublishingState);
28068
- if (error.details?.publishThrowError) {
28069
- log.error("RPC server threw an error on publish(), will stop publication", error);
28140
+ if (error.details?.publishThrowError || error.details?.newState === "stopped") {
28141
+ if (!this._claimPublishEnd("failure")) {
28142
+ if (!error.details?.publishThrowError) this.emit("error", error);
28143
+ return;
28144
+ }
28145
+ log.error("The publication failed on the RPC server, will stop publication", error);
28070
28146
  await this._postSucessOrFailurePublishing();
28147
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28148
+ newPublishingState: error.details?.newPublishingState ?? "failed",
28149
+ event: {
28150
+ name: "error",
28151
+ args: [error]
28152
+ }
28153
+ });
28154
+ return;
28071
28155
  }
28156
+ if (error.details?.newPublishingState) this._updatePublishingStateNoEmission(error.details.newPublishingState);
28072
28157
  this.emit("error", error);
28073
28158
  }
28074
28159
  async _publishWithRpc() {
@@ -28082,11 +28167,22 @@ var Publication = class extends import_lib.TypedEmitter {
28082
28167
  commentModeration: rpcClient.publishCommentModeration,
28083
28168
  communityEdit: rpcClient.publishCommunityEdit
28084
28169
  }[this.getType()].bind(rpcClient)(this.toJSONPubsubRequestToEncrypt());
28170
+ if (this._hasPublishEnded()) {
28171
+ try {
28172
+ await rpcClient.unsubscribe(subscriptionId);
28173
+ } catch (e) {
28174
+ logger_default("pkc-js:publication:publish:_publishWithRpc").error("Failed to unsubscribe from a publish stopped while starting", e);
28175
+ }
28176
+ return;
28177
+ }
28085
28178
  this._rpcPublishSubscriptionId = subscriptionId;
28179
+ const unlessStopped = (handler) => (args) => {
28180
+ if (this._publishEndedBy !== "stop" && this._publishEndedBy !== "failure") return handler(args);
28181
+ };
28086
28182
  rpcClient.attachSubscriptionHandlersDeferred({
28087
28183
  subscriptionId,
28088
28184
  isStale: () => this._rpcPublishSubscriptionId !== subscriptionId,
28089
- 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)),
28185
+ attach: (subscription) => subscription.on("challengerequest", unlessStopped(this._handleIncomingChallengeRequestFromRpc.bind(this))).on("challenge", unlessStopped(this._handleIncomingChallengeFromRpc.bind(this))).on("challengeanswer", unlessStopped(this._handleIncomingChallengeAnswerFromRpc.bind(this))).on("challengeverification", unlessStopped(this._handleIncomingChallengeVerificationFromRpc.bind(this))).on("publishingstatechange", unlessStopped(this._handleIncomingPublishingStateFromRpc.bind(this))).on("statechange", unlessStopped(this._handleIncomingStateFromRpc.bind(this))).on("error", unlessStopped(this._handleIncomingErrorFromRpc.bind(this))),
28090
28186
  replayErrorContainment: {
28091
28187
  entityName: "publication",
28092
28188
  log: logger_default("pkc-js:publication:publish:_publishWithRpc"),
@@ -28150,8 +28246,10 @@ var Publication = class extends import_lib.TypedEmitter {
28150
28246
  this._community = await this._fetchCommunityForPublishing();
28151
28247
  this._validateCommunityFields();
28152
28248
  } catch (e) {
28153
- this._setStateWithEmission("stopped");
28154
- this._updatePublishingStateWithEmission("failed");
28249
+ if (!this._hasPublishEnded()) {
28250
+ this._setStateWithEmission("stopped");
28251
+ this._updatePublishingStateWithEmission("failed");
28252
+ }
28155
28253
  throw e;
28156
28254
  }
28157
28255
  }
@@ -28190,7 +28288,7 @@ var Publication = class extends import_lib.TypedEmitter {
28190
28288
  async _handleNotReceivingResponseToChallengeRequest({ providers, currentPubsubProviderIndex, acceptedChallengeTypes }) {
28191
28289
  const runSignal = this._getPublishRunWaitSignal();
28192
28290
  await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1e3, runSignal);
28193
- if (this._isPublishRunOver(runSignal)) return;
28291
+ if (this._hasPublishEnded()) return;
28194
28292
  if (this._didWeReceiveChallengeOrChallengeVerification()) return;
28195
28293
  const currentPubsubProvider = providers[currentPubsubProviderIndex];
28196
28294
  this._pkc._stats.recordGatewayFailure(currentPubsubProvider, "pubsub-publish");
@@ -28198,59 +28296,62 @@ var Publication = class extends import_lib.TypedEmitter {
28198
28296
  const log = logger_default("pkc-js:publication:publish:_handleNotReceivingResponseToChallengeRequest");
28199
28297
  if (this._isAllAttemptsExhausted(providers.length)) {
28200
28298
  log.error(`Failed to receive any response for publication`, this.getType());
28201
- await this._postSucessOrFailurePublishing();
28202
- const error = new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
28203
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
28204
- publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
28205
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28206
- });
28207
- this._changePublicationStateEmitEventEmitStateChangeEvent({
28208
- newPublishingState: "failed",
28209
- event: {
28210
- name: "error",
28211
- args: [error]
28212
- }
28299
+ await this._endPublishWithFailure(() => {
28300
+ const error = new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
28301
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
28302
+ publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
28303
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28304
+ });
28305
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28306
+ newPublishingState: "failed",
28307
+ event: {
28308
+ name: "error",
28309
+ args: [error]
28310
+ }
28311
+ });
28213
28312
  });
28214
28313
  } else if (this.state === "stopped") {
28215
28314
  log.error(`Publication is stopped, will not re-publish`);
28216
28315
  await this._postSucessOrFailurePublishing();
28217
- } else if (currentPubsubProviderIndex + 1 === providers.length) {
28218
- log.error(`Failed to receive any response for publication`, this.getType(), "after publishing to all providers", providers);
28219
- await this._postSucessOrFailurePublishing();
28220
28316
  } else {
28221
- log(`Re-publishing publication after ${this._publishToDifferentProviderThresholdSeconds}s of not receiving challenge from provider (${currentPubsubProvider})`);
28222
- currentPubsubProviderIndex += 1;
28223
- while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
28224
- const providerUrl = providers[currentPubsubProviderIndex];
28225
- if (this._isPublishRunOver(runSignal)) return;
28226
- const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, acceptedChallengeTypes);
28227
- this._updatePublishingStateWithEmission("publishing-challenge-request");
28228
- this._updatePubsubState("subscribing-pubsub", providerUrl);
28229
- try {
28230
- await this._clientsManager.pubsubSubscribeOnProvider(this._communityChallengePubsubExchangeTopic(), this._handleChallengeExchange, providerUrl);
28231
- if (await this._abandonProviderIfStoppedWhileSubscribing(providerUrl)) return;
28232
- this._updatePubsubState("publishing-challenge-request", providerUrl);
28233
- await this._clientsManager.pubsubPublishOnProvider(this._communityChallengePubsubExchangeTopic(), challengeRequest, providerUrl);
28234
- this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
28235
- } catch (e) {
28236
- log.error("Failed to publish challenge request using provider ", providerUrl, e);
28237
- this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
28238
- continue;
28239
- } finally {
28240
- currentPubsubProviderIndex += 1;
28241
- }
28242
- const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
28243
- if (!this._didWeReceiveChallengeOrChallengeVerification()) {
28244
- this._updatePubsubState("waiting-challenge", providerUrl);
28245
- this._updatePublishingStateWithEmission("waiting-challenge");
28317
+ if (currentPubsubProviderIndex + 1 < providers.length) {
28318
+ log(`Re-publishing publication after ${this._publishToDifferentProviderThresholdSeconds}s of not receiving challenge from provider (${currentPubsubProvider})`);
28319
+ currentPubsubProviderIndex += 1;
28320
+ while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
28321
+ const providerUrl = providers[currentPubsubProviderIndex];
28322
+ if (this._hasPublishEnded()) return;
28323
+ const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, acceptedChallengeTypes);
28324
+ if (this._hasPublishEnded()) return;
28325
+ this._updatePublishingStateWithEmission("publishing-challenge-request");
28326
+ this._updatePubsubState("subscribing-pubsub", providerUrl);
28327
+ try {
28328
+ await this._clientsManager.pubsubSubscribeOnProvider(this._communityChallengePubsubExchangeTopic(), this._handleChallengeExchange, providerUrl);
28329
+ if (await this._abandonProviderIfStoppedWhileSubscribing(providerUrl)) return;
28330
+ this._updatePubsubState("publishing-challenge-request", providerUrl);
28331
+ await this._clientsManager.pubsubPublishOnProvider(this._communityChallengePubsubExchangeTopic(), challengeRequest, providerUrl);
28332
+ this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
28333
+ } catch (e) {
28334
+ if (this._hasPublishEnded()) return;
28335
+ log.error("Failed to publish challenge request using provider ", providerUrl, e);
28336
+ this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
28337
+ continue;
28338
+ } finally {
28339
+ currentPubsubProviderIndex += 1;
28340
+ }
28341
+ if (this._hasPublishEnded()) return;
28342
+ const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
28343
+ if (!this._didWeReceiveChallengeOrChallengeVerification()) {
28344
+ this._updatePubsubState("waiting-challenge", providerUrl);
28345
+ this._updatePublishingStateWithEmission("waiting-challenge");
28346
+ }
28347
+ log(`Published a challenge request of publication`, this.getType(), "with provider", providerUrl);
28348
+ this.emit("challengerequest", decryptedRequest);
28349
+ if (currentPubsubProviderIndex !== providers.length) await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1e3, runSignal);
28350
+ if (this._hasPublishEnded()) return;
28246
28351
  }
28247
- log(`Published a challenge request of publication`, this.getType(), "with provider", providerUrl);
28248
- this.emit("challengerequest", decryptedRequest);
28249
- if (currentPubsubProviderIndex !== providers.length) await sleepUntilTimeoutOrAbort(this._publishToDifferentProviderThresholdSeconds * 1e3, runSignal);
28250
- if (this._isPublishRunOver(runSignal)) return;
28251
- }
28352
+ } else log(`No response from the last provider (${currentPubsubProvider}), will wait for it until the failure threshold`);
28252
28353
  await sleepUntilTimeoutOrAbort(this._setProviderFailureThresholdSeconds * 1e3, runSignal);
28253
- if (this._isPublishRunOver(runSignal)) return;
28354
+ if (this._hasPublishEnded()) return;
28254
28355
  if (this.state === "stopped") return;
28255
28356
  if (this._didWeReceiveChallengeOrChallengeVerification()) {
28256
28357
  log(`Received a challenge or challenge verification while waiting for retried providers, will keep the exchange alive`);
@@ -28258,25 +28359,26 @@ var Publication = class extends import_lib.TypedEmitter {
28258
28359
  }
28259
28360
  if (this._isAllAttemptsExhausted(providers.length)) {
28260
28361
  const aRequestWasPublished = this._wasAnyChallengeRequestPublished();
28261
- await this._postSucessOrFailurePublishing();
28262
- const allAttemptsFailedError = aRequestWasPublished ? new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
28263
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
28264
- pubsubTopic: this._community?.pubsubTopic,
28265
- publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
28266
- setProviderFailureThresholdSeconds: this._setProviderFailureThresholdSeconds,
28267
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28268
- }) : new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
28269
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
28270
- pubsubTopic: this._community?.pubsubTopic,
28271
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28272
- });
28273
- log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
28274
- this._changePublicationStateEmitEventEmitStateChangeEvent({
28275
- newPublishingState: "failed",
28276
- event: {
28277
- name: "error",
28278
- args: [allAttemptsFailedError]
28279
- }
28362
+ await this._endPublishWithFailure(() => {
28363
+ const allAttemptsFailedError = aRequestWasPublished ? new PKCError("ERR_PUBSUB_DID_NOT_RECEIVE_RESPONSE_AFTER_PUBLISHING_CHALLENGE_REQUEST", {
28364
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
28365
+ pubsubTopic: this._community?.pubsubTopic,
28366
+ publishToDifferentProviderThresholdSeconds: this._publishToDifferentProviderThresholdSeconds,
28367
+ setProviderFailureThresholdSeconds: this._setProviderFailureThresholdSeconds,
28368
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28369
+ }) : new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
28370
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
28371
+ pubsubTopic: this._community?.pubsubTopic,
28372
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28373
+ });
28374
+ log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
28375
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28376
+ newPublishingState: "failed",
28377
+ event: {
28378
+ name: "error",
28379
+ args: [allAttemptsFailedError]
28380
+ }
28381
+ });
28280
28382
  });
28281
28383
  return;
28282
28384
  }
@@ -28293,6 +28395,7 @@ var Publication = class extends import_lib.TypedEmitter {
28293
28395
  const log = logger_default("pkc-js:publication:publish:_publishWithLocalCommunity");
28294
28396
  log("Community is local, will not publish over pubsub, and instead will publish directly to the community by accessing pkc._startedCommunities");
28295
28397
  const communityChallengeListener = async (challenge) => {
28398
+ if (this._hasPublishEnded()) return;
28296
28399
  if (challenge.challengeRequestId.toString() === challengeRequest.challengeRequestId.toString()) {
28297
28400
  const encryptedFields = ["challenges"];
28298
28401
  log("Received a challenge from the local community", challenge);
@@ -28300,10 +28403,13 @@ var Publication = class extends import_lib.TypedEmitter {
28300
28403
  }
28301
28404
  };
28302
28405
  community.on("challenge", communityChallengeListener);
28406
+ let verificationHandling;
28303
28407
  const communityChallengeVerificationListener = async (decryptedChallengeVerification) => {
28408
+ if (this._hasPublishEnded()) return;
28304
28409
  if (decryptedChallengeVerification.challengeRequestId.toString() === challengeRequest.challengeRequestId.toString()) {
28305
28410
  log("Received a challenge verification from the local community", decryptedChallengeVerification);
28306
- await this._handleIncomingChallengeVerificationPubsubMessage(n$1(decryptedChallengeVerification, ["comment", "commentUpdate"]));
28411
+ verificationHandling = this._handleIncomingChallengeVerificationPubsubMessage(n$1(decryptedChallengeVerification, ["comment", "commentUpdate"]));
28412
+ await verificationHandling;
28307
28413
  }
28308
28414
  };
28309
28415
  community.on("challengeverification", communityChallengeVerificationListener);
@@ -28313,17 +28419,40 @@ var Publication = class extends import_lib.TypedEmitter {
28313
28419
  ...this._challengeExchanges[challengeRequest.challengeRequestId.toString()],
28314
28420
  challengeRequestPublishTimestamp: timestamp()
28315
28421
  };
28316
- }).catch((e) => {
28422
+ }).catch(async (e) => {
28317
28423
  log.error("Failed to handle challenge request with local community", e);
28318
- this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
28319
- throw e;
28424
+ const challengeRequestId = challengeRequest.challengeRequestId.toString();
28425
+ this._challengeExchanges[challengeRequestId].challengeRequestPublishError = e;
28426
+ await verificationHandling?.catch(() => {});
28427
+ try {
28428
+ await this._endPublishWithFailure(() => this._changePublicationStateEmitEventEmitStateChangeEvent({
28429
+ newPublishingState: "failed",
28430
+ event: {
28431
+ name: "error",
28432
+ args: [e]
28433
+ }
28434
+ }));
28435
+ } catch (endError) {
28436
+ log.error("Failed to end the exchange the local community rejected", endError);
28437
+ }
28320
28438
  }).finally(() => {
28321
28439
  community.removeListener("challenge", communityChallengeListener);
28322
28440
  community.removeListener("challengeverification", communityChallengeVerificationListener);
28323
28441
  });
28324
28442
  }
28325
28443
  async publish() {
28444
+ if (this._isPublishSpent || this._isPublishCallRunning) {
28445
+ const exchanges = Object.values(this._challengeExchanges);
28446
+ throw new PKCError("ERR_PUBLICATION_PUBLISH_ALREADY_CALLED", {
28447
+ publicationType: this.getType(),
28448
+ state: this.state,
28449
+ publishingState: this.publishingState,
28450
+ receivedChallenge: exchanges.some((exchange) => exchange.challenge),
28451
+ receivedChallengeVerification: exchanges.some((exchange) => exchange.challengeVerification)
28452
+ });
28453
+ }
28326
28454
  this._validatePublicationFields();
28455
+ this._isPublishCallRunning = true;
28327
28456
  if (this._getCommunityFetchAbortSignal().aborted) this._resetCommunityFetchAbortSignal();
28328
28457
  this._beginPublishRun();
28329
28458
  this._pkc._publishingPublications.add(this);
@@ -28333,6 +28462,8 @@ var Publication = class extends import_lib.TypedEmitter {
28333
28462
  this._unregisterFromPkcOncePublishWorkSettles();
28334
28463
  this._publishRunAbortController?.abort();
28335
28464
  throw e;
28465
+ } finally {
28466
+ this._isPublishCallRunning = false;
28336
28467
  }
28337
28468
  }
28338
28469
  async _publishAfterRegistering() {
@@ -28347,36 +28478,46 @@ var Publication = class extends import_lib.TypedEmitter {
28347
28478
  await this._signPublicationWithCommunityFields();
28348
28479
  }
28349
28480
  await this._validateSignatureHook();
28481
+ if (this._hasPublishEnded()) return;
28482
+ this._isPublishSpent = true;
28350
28483
  if (this._pkc._pkcRpcClient) return this._publishWithRpc();
28351
28484
  const options = { acceptedChallengeTypes: [] };
28352
28485
  const startedCommunity = findStartedCommunity(this._pkc, {
28353
28486
  publicKey: this.communityPublicKey,
28354
28487
  name: this.communityName
28355
28488
  });
28356
- if (startedCommunity) return this._publishWithLocalCommunity(startedCommunity, await this._generateChallengeRequestToPublish("publishing directly to local community instance", options.acceptedChallengeTypes));
28489
+ if (startedCommunity) {
28490
+ const challengeRequest = await this._generateChallengeRequestToPublish(LOCAL_COMMUNITY_PROVIDER, options.acceptedChallengeTypes);
28491
+ if (this._hasPublishEnded()) return;
28492
+ return this._publishWithLocalCommunity(startedCommunity, challengeRequest);
28493
+ }
28357
28494
  if (typeof this._community?.pubsubTopic !== "string") {
28358
- await this._postSucessOrFailurePublishing();
28359
- const error = new PKCError("ERR_COMMUNITY_CHALLENGE_EXCHANGE_DISABLED", {
28360
- communityAddress: this._community?.address ?? this.communityAddress,
28361
- communityName: this._community?.name ?? this.communityName,
28362
- communityPublicKey: this._community?.publicKey ?? this.communityPublicKey,
28363
- publicationType: this.getType()
28364
- });
28365
- log.error("Community has its challenge exchange disabled, will not publish", this.getType(), error);
28366
- this._changePublicationStateEmitEventEmitStateChangeEvent({
28367
- newPublishingState: "failed",
28368
- event: {
28369
- name: "error",
28370
- args: [error]
28371
- }
28495
+ const disabledError = await this._endPublishWithFailure(() => {
28496
+ const error = new PKCError("ERR_COMMUNITY_CHALLENGE_EXCHANGE_DISABLED", {
28497
+ communityAddress: this._community?.address ?? this.communityAddress,
28498
+ communityName: this._community?.name ?? this.communityName,
28499
+ communityPublicKey: this._community?.publicKey ?? this.communityPublicKey,
28500
+ publicationType: this.getType()
28501
+ });
28502
+ log.error("Community has its challenge exchange disabled, will not publish", this.getType(), error);
28503
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28504
+ newPublishingState: "failed",
28505
+ event: {
28506
+ name: "error",
28507
+ args: [error]
28508
+ }
28509
+ });
28510
+ return error;
28372
28511
  });
28373
- throw error;
28512
+ if (disabledError) throw disabledError;
28513
+ return;
28374
28514
  }
28375
28515
  const providers = this._getPubsubProviders();
28376
28516
  let currentPubsubProviderIndex = 0;
28377
28517
  while (!this._didWeReceiveChallengeOrChallengeVerification() && currentPubsubProviderIndex < providers.length) {
28378
28518
  const providerUrl = providers[currentPubsubProviderIndex];
28379
28519
  const challengeRequest = await this._generateChallengeRequestToPublish(providerUrl, options.acceptedChallengeTypes);
28520
+ if (this._hasPublishEnded()) return;
28380
28521
  this._updatePublishingStateWithEmission("publishing-challenge-request");
28381
28522
  this._updatePubsubState("subscribing-pubsub", providerUrl);
28382
28523
  try {
@@ -28386,28 +28527,33 @@ var Publication = class extends import_lib.TypedEmitter {
28386
28527
  await this._clientsManager.pubsubPublishOnProvider(this._communityChallengePubsubExchangeTopic(), challengeRequest, providerUrl);
28387
28528
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
28388
28529
  } catch (e) {
28530
+ if (this._hasPublishEnded()) return;
28389
28531
  this._updatePubsubState("stopped", providerUrl);
28390
28532
  log.error("Failed to publish challenge request using provider ", providerUrl, e);
28391
28533
  currentPubsubProviderIndex += 1;
28392
28534
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishError = e;
28393
28535
  if (this._isAllAttemptsExhausted(providers.length)) {
28394
- await this._postSucessOrFailurePublishing();
28395
- const allAttemptsFailedError = new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
28396
- challengeExchanges: this._challengeExchangesFormattedForErrors(),
28397
- pubsubTopic: this._community?.pubsubTopic,
28398
- providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28399
- });
28400
- log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
28401
- this._changePublicationStateEmitEventEmitStateChangeEvent({
28402
- newPublishingState: "failed",
28403
- event: {
28404
- name: "error",
28405
- args: [allAttemptsFailedError]
28406
- }
28536
+ const failure = await this._endPublishWithFailure(() => {
28537
+ const allAttemptsFailedError = new PKCError("ERR_ALL_PUBSUB_PROVIDERS_THROW_ERRORS", {
28538
+ challengeExchanges: this._challengeExchangesFormattedForErrors(),
28539
+ pubsubTopic: this._community?.pubsubTopic,
28540
+ providerHeliaContexts: this._libp2pJsClientHeliaContexts()
28541
+ });
28542
+ log.error("All attempts to publish", this.getType(), "has failed", allAttemptsFailedError);
28543
+ this._changePublicationStateEmitEventEmitStateChangeEvent({
28544
+ newPublishingState: "failed",
28545
+ event: {
28546
+ name: "error",
28547
+ args: [allAttemptsFailedError]
28548
+ }
28549
+ });
28550
+ return allAttemptsFailedError;
28407
28551
  });
28408
- throw allAttemptsFailedError;
28552
+ if (failure) throw failure;
28553
+ return;
28409
28554
  } else continue;
28410
28555
  }
28556
+ if (this._hasPublishEnded()) return;
28411
28557
  const decryptedRequest = this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequest;
28412
28558
  this._updatePubsubState("waiting-challenge", providerUrl);
28413
28559
  this._updatePublishingStateWithEmission("waiting-challenge");
@@ -29639,6 +29785,7 @@ var Comment = class extends Publication {
29639
29785
  this._updateRpcSubscriptionId = void 0;
29640
29786
  this._stopAbortController = void 0;
29641
29787
  this._numOfListenersForUpdatingInstance = 0;
29788
+ this._updateAttempt = 0;
29642
29789
  this._updatingCommentInstance = void 0;
29643
29790
  this._setUpdatingStateWithEmissionIfNewState("stopped");
29644
29791
  this.publish = this.publish.bind(this);
@@ -29889,7 +30036,6 @@ var Comment = class extends Publication {
29889
30036
  originalPubsubMsg: this.raw.pubsubMessageToPublish
29890
30037
  });
29891
30038
  log.error(error);
29892
- this.emit("error", error);
29893
30039
  return error;
29894
30040
  }
29895
30041
  const calculatedCid = await of(JSON.stringify(decryptedVerification.comment));
@@ -29907,7 +30053,6 @@ var Comment = class extends Publication {
29907
30053
  decryptedChallengeVerification: decryptedVerification
29908
30054
  });
29909
30055
  log.error(error);
29910
- this.emit("error", error);
29911
30056
  return error;
29912
30057
  }
29913
30058
  const commentUpdateValidity = await verifyCommentUpdate({
@@ -29929,7 +30074,6 @@ var Comment = class extends Publication {
29929
30074
  decryptedChallengeVerification: decryptedVerification
29930
30075
  });
29931
30076
  log.error(error);
29932
- this.emit("error", error);
29933
30077
  return error;
29934
30078
  }
29935
30079
  if (calculatedCid !== decryptedVerification.commentUpdate.cid) {
@@ -29939,7 +30083,6 @@ var Comment = class extends Publication {
29939
30083
  decryptedChallengeVerification: decryptedVerification
29940
30084
  });
29941
30085
  log.error(error);
29942
- this.emit("error", error);
29943
30086
  return error;
29944
30087
  }
29945
30088
  }
@@ -29997,7 +30140,8 @@ var Comment = class extends Publication {
29997
30140
  const log = logger_default("pkc-js:comment:publish:_verifyDecryptedChallengeVerificationAndUpdateCommentProps");
29998
30141
  log("Received update props from community after succcessful challenge exchange. Will attempt to validate if not connected to RPC", decryptedVerification);
29999
30142
  if (!this._pkc._pkcRpcClient) {
30000
- if (await this._verifyChallengeVerificationCommentProps(decryptedVerification)) return;
30143
+ const errorInVerificationProps = await this._verifyChallengeVerificationCommentProps(decryptedVerification);
30144
+ if (errorInVerificationProps) throw errorInVerificationProps;
30001
30145
  }
30002
30146
  await this._updateCommentPropsFromDecryptedChallengeVerification(decryptedVerification);
30003
30147
  if (Object.keys(this._pkc.clients.kuboRpcClients).length > 0 || Object.keys(this._pkc.clients.libp2pJsClients).length > 0) this._addOwnCommentToIpfsIfConnectedToIpfsClient(decryptedVerification).catch((err) => log.error(`Failed to add the file of comment ipfs`, this.cid, "to ipfs network due to error", err));
@@ -30290,25 +30434,38 @@ var Comment = class extends Publication {
30290
30434
  const log = logger_default("pkc-js:comment:update:_updateViaRpc");
30291
30435
  if (!this._pkc.pkcRpcClientsOptions[0]) throw Error("Failed to get rpc url");
30292
30436
  if (!this.cid) throw Error("Can't start updating comment without defining this.cid");
30437
+ const updateAttempt = this._updateAttempt;
30438
+ let subscriptionId;
30293
30439
  try {
30294
- const { subscriptionId } = await this._pkc._pkcRpcClient.commentUpdateSubscribe({
30440
+ ({subscriptionId} = await this._pkc._pkcRpcClient.commentUpdateSubscribe({
30295
30441
  cid: this.cid,
30296
30442
  ...this.raw.comment || this.raw.commentUpdate ? { raw: this.raw } : void 0,
30297
30443
  communityName: this.communityName,
30298
30444
  communityPublicKey: this.communityPublicKey,
30299
30445
  parentCid: this.parentCid,
30300
30446
  postCid: this.postCid
30301
- });
30302
- this._updateRpcSubscriptionId = subscriptionId;
30447
+ }));
30303
30448
  } catch (e) {
30449
+ if (updateAttempt !== this._updateAttempt) {
30450
+ log.error("A commentUpdate subscribe that stop() made stale failed", e);
30451
+ return;
30452
+ }
30304
30453
  log.error("Failed to receive commentUpdate from RPC due to error", e);
30305
30454
  await this._stopUpdateLoop();
30306
30455
  this._setStateWithEmission("stopped");
30307
30456
  this._setUpdatingStateWithEmissionIfNewState("failed");
30308
30457
  throw e;
30309
30458
  }
30459
+ if (updateAttempt !== this._updateAttempt) {
30460
+ try {
30461
+ await this._pkc._pkcRpcClient.unsubscribe(subscriptionId);
30462
+ } catch (e) {
30463
+ log.error("Failed to unsubscribe from a commentUpdate subscription stopped while subscribing", e);
30464
+ }
30465
+ return;
30466
+ }
30467
+ this._updateRpcSubscriptionId = subscriptionId;
30310
30468
  this._setStateWithEmission("updating");
30311
- const subscriptionId = this._updateRpcSubscriptionId;
30312
30469
  this._pkc._pkcRpcClient.attachSubscriptionHandlersDeferred({
30313
30470
  subscriptionId,
30314
30471
  isStale: () => this._updateRpcSubscriptionId !== subscriptionId,
@@ -30442,7 +30599,9 @@ var Comment = class extends Publication {
30442
30599
  }
30443
30600
  async _setUpNewUpdatingCommentInstance() {
30444
30601
  const log = logger_default("pkc-js:comment:update:_setUpNewUpdatingCommentInstance");
30602
+ const updateAttempt = this._updateAttempt;
30445
30603
  const updatingCommentInstance = await this._pkc.createComment(this);
30604
+ if (updateAttempt !== this._updateAttempt) return;
30446
30605
  trackUpdatingComment(this._pkc, updatingCommentInstance);
30447
30606
  this._useUpdatingCommentFromPKC(updatingCommentInstance);
30448
30607
  updatingCommentInstance._setStateWithEmission("updating");
@@ -30453,7 +30612,9 @@ var Comment = class extends Publication {
30453
30612
  const log = logger_default("pkc-js:comment:update");
30454
30613
  if (this.state === "updating") return;
30455
30614
  if (!this.cid) throw Error("Can't call comment.update() without defining cid");
30615
+ const updateAttempt = ++this._updateAttempt;
30456
30616
  this._setStateWithEmission("updating");
30617
+ if (updateAttempt !== this._updateAttempt) return;
30457
30618
  const existingUpdatingComment = findUpdatingComment(this._pkc, { cid: this.cid });
30458
30619
  if (existingUpdatingComment) if (existingUpdatingComment === this) if (this._pkc._pkcRpcClient) await this._updateViaRpc();
30459
30620
  else this.loadCommentIpfsAndStartCommentUpdateSubscription().catch((e) => log.error("Failed to update comment", e));
@@ -30510,10 +30671,17 @@ var Comment = class extends Publication {
30510
30671
  this._clearStopAbortController();
30511
30672
  }
30512
30673
  async stop() {
30674
+ const updateAttempt = ++this._updateAttempt;
30513
30675
  this._abortStopOperations(`Aborting comment operations for ${this.cid || this.author?.address || "comment"} because comment.stop() was called`);
30514
- if (this.state === "publishing") await super.stop();
30515
- else await this._cancelBackgroundCommunityRefresh();
30516
- this._setStateWithEmission("stopped");
30676
+ const isPublishing = () => this.state === "publishing";
30677
+ if (isPublishing()) {
30678
+ await super.stop();
30679
+ if (updateAttempt !== this._updateAttempt) return;
30680
+ this._setStateWithEmission("stopped");
30681
+ } else {
30682
+ await this._cancelBackgroundCommunityRefresh();
30683
+ if (!isPublishing()) this._setStateWithEmission("stopped");
30684
+ }
30517
30685
  await this._stopUpdateLoop();
30518
30686
  this.replies._stop();
30519
30687
  this._setUpdatingStateWithEmissionIfNewState("stopped");
@@ -36109,7 +36277,7 @@ var PKC$1 = class extends PKCTypedEmitter {
36109
36277
  this.clients.libp2pJsClients = {};
36110
36278
  if (!this.libp2pJsClientsOptions) return;
36111
36279
  if (!this.httpRoutersOptions) throw Error("httpRoutersOptions is required for libp2pJsClient");
36112
- const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-COJ3xMF9.js");
36280
+ const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-CG9YohPs.js");
36113
36281
  for (const clientOptions of this.libp2pJsClientsOptions) {
36114
36282
  const heliaNode = await createLibp2pJsClientOrUseExistingOne({
36115
36283
  ...clientOptions,
@@ -36486,7 +36654,7 @@ var PKC$1 = class extends PKCTypedEmitter {
36486
36654
  const log = logger_default("pkc-js:pkc:createLocalCommunity");
36487
36655
  log.trace("Received community options to create a local community instance:", options);
36488
36656
  if (!this._canCreateNewLocalCommunity()) throw new PKCError("ERR_CAN_NOT_CREATE_A_LOCAL_COMMUNITY", { pkcOptions: this._userPKCOptions });
36489
- const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-BTx2HxIm.js");
36657
+ const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-CaQmhX8D.js");
36490
36658
  const isLocalCommunity = (await listCommunitiesSync(this)).includes(options.address);
36491
36659
  const community = new LocalCommunity(this);
36492
36660
  if (isLocalCommunity) {