@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 } from "./chunk-2rV9d50f.js";
2
- import { $n as CommentEditsTableRowSchema, At as ChallengeAnswerMessageSchema, B as pubsubTopicToDhtKey, Bt as DecryptedChallengeRequestSchema, C as hideClassPrivateProps, Ct as trackUpdatingCommunity, Dt as require_sha256, En as VotePubsubReservedFields, Et as untrackUpdatingCommunity, F as isLinkOfVideo, G as removeBlocksFromKuboNode, Hn as CommentsTableRowSchema, I as isLinkValid, It as ChallengeVerificationMessageSchema, J as removeNullUndefinedValues, Jt as version_default, K as removeMfsFilesSafely, Lr as PKCError, M as isLinkOfAudio, Mn as CommentPubsubMessageReservedFields, Mt as ChallengeMessageSchema, N as isLinkOfImage, On as VoteTablesRowSchema, Or as t$4, P as isLinkOfMedia, Pt as ChallengeRequestMessageSchema, Q as retryKuboBlockPutPinAndProvidePubsubTopic, Rr as messages, Sr as e, T as ipnsNameToIpnsOverPubsubTopic, Tn as VotePubsubMessagePublicationSchema, Tr as t$3, Vn as CommentUpdateTableRowSchema, Xn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Xt as CommunityEditPublicationPubsubReservedFields, Yn as CommentEditPubsubMessagePublicationSchema, Zn as CommentEditReservedFields, _ as genToArray, _r as t$7, b as getIpnsRecordInLocalKuboNode, br as t$6, bt as syncCommunityRegistryEntry, c as contentContainsMarkdownImages, ct as withSortedKeys, dt as findStartedCommunity, et as retryKuboIpfsAddAndProvide, f as derivePublicationFromChallengeRequest, g as findMalformedUnicodeString, gr as n$3, hr as isStringDomain, i as calculateStringSizeSameAsIpfsAddCidV0, in as CommentModerationsTableRowSchema, ir as AuthorReservedFields, it as statMfsPathSafely, j as isLinkOfAnimatedImage, jn as CommentIpfsSchema, jr as require_retry, kr as t$2, kt as pTimeout, l as contentContainsMarkdownVideos, lt as withSortedKeysDeep, mn as CommunitySignedPropertyNames, nn as CommentModerationReservedFields, o as calculateUnixFsDagSizeCidV0, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsSchema, pt as findUpdatingCommunity, r as calculateIpfsCidV0, rt as sleepUntilTimeoutOrAbort, s as contentContainsMarkdownAudio, ti as ZodError, tn as CommentModerationPubsubMessagePublicationSchema, ut as findCommunityInRegistry, v as getEquivalentCommunityAddresses, vr as n$2, wr as r$1, wt as untrackStartedCommunity, xr as e$1, xt as trackStartedCommunity, y as getErrorCodeFromMessage, yr as t$5, zn as CommentUpdateSchema, zr as logger_default, zt as DecryptedChallengeRequestPublicationSchema } from "./util-D7AtfLYH.js";
3
- import { $ as createSchemaRowParser, $r as require_lodash_merge, An as verifyChallengeAnswer, Ar as removeFileRetryingWhileBusy, Bn as verifyCommunityEdit, Br as t$11, Dt as parseJsonWithPKCErrorIfFails, En as signCommunity, Fn as verifyCommentIpfs, Hn as verifyVote, Hr as t$8, In as verifyCommentModeration, Kn as getAuthorNameFromWire, Kr as t$9, Ln as verifyCommentPubsubMessage, Lr as isCommunityStartLocked, Mn as verifyChallengeRequest, N as MAX_PAGE_SIZE_BYTES, Or as moveCommunityDbToDeletedDirectory, Pn as verifyCommentEdit, Pr as findCommunitiesEntry, Q as collectSchemaRowCoercions, Qn as effectiveMaxCrosspostDepth, Qr as STORAGE_KEYS, Rn as verifyCommentUpdate, Rr as require_src, S as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, Sn as signCommentEdit, Sr as getDefaultCommunityDbConfig, Tn as signCommentUpdateForChallengeVerification, Tr as importSignerIntoKuboNode, Un as buildRuntimeAuthor, Ur as n$5, Vr as r$2, W as pLimit, Wn as cleanWireAuthor, Wr as n$4, X as coerceSchemaRowBoolean, Z as coerceSchemaRowJson, Zn as crosspostChainDepthUpTo, _ as createAuthorIdentityMatcher, _r as deriveCommentIpfsFromCommentTableRow, a as generatePagesReportingFailedSorts, ar as encode, b as KeyvBetterSqlite3, bn as signChallengeVerification, c as resolvePageSortsOrThrow, cn as SignerWithPublicKeyAddress, cr as getPKCAddressFromPublicKey, d as getChallengeVerification, dr as BackupAbortError, dt as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, f as getCommunityChallengeFromCommunityChallengeSettings, fn as decryptEd25519AesGcmPublicKeyBuffer, fr as backupCommunityDb, g as authorNameResolveFailureReason, gn as cleanUpBeforePublishing, gr as deleteOldCommunityInWindows, h as authorIdentityMatcherForRequest, hn as _validateSignatureOfPKCRecord, i as derivePublicPageSorts, ir as decode, j as iterateOverPageCidsToFindAllCids, jr as resolveDbPostsCidRefs, kr as refreshCommunitiesList, lr as getPKCAddressFromPublicKeySync, m as pkcJsChallenges, mn as encryptEd25519AesGcmPublicKeyBuffer, mr as calculateInlineRepliesBudget, nr as getCommunityPublicKeyFromWire, o as loadPageSortsForStartedCommunity, p as loadChallengeFileFromCommunityChallengeSettings, pr as calculateExpectedSignatureSize, pt as parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails, qr as stringify, r as computePageSortsFingerprint, s as lookupPageSortFactories, sr as getIpfsKeyFromPrivateKey, t as RpcLocalCommunity, tr as getCommunityNameFromWire, u as deriveCommunityChallengesOrThrow, ur as getPublicKeyFromPrivateKey, v as TrackedInstanceRegistry, vn as signChallengeMessage, vr as deriveDbPosts, w as TIMEFRAMES_TO_SECONDS, wn as signCommentUpdate, wr as getThumbnailPropsOfLink, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, xn as signComment, xr as forgetCommunityThatFailedToBeDeleted, y as LRUCache, yr as deriveDbReplies, zn as verifyCommunity, zr as t$10 } from "./rpc-local-community-Cy03QajY.js";
4
- import { a as scorePageCommentsWithFile, i as partitionPageCommentsForSort, n as filterRepliesForPageSort, o as stripRepliesFromPageComment, r as orderPageCommentsByScore, t as createDescendantsLookup } from "./page-sort-scoring-DAMnUmDY.js";
2
+ import { $n as CommentEditsTableRowSchema, At as ChallengeAnswerMessageSchema, B as pubsubTopicToDhtKey, Bt as DecryptedChallengeRequestSchema, C as hideClassPrivateProps, Ct as trackUpdatingCommunity, Dt as require_sha256, En as VotePubsubReservedFields, Et as untrackUpdatingCommunity, F as isLinkOfVideo, G as removeBlocksFromKuboNode, Hn as CommentsTableRowSchema, I as isLinkValid, It as ChallengeVerificationMessageSchema, J as removeNullUndefinedValues, Jt as version_default, K as removeMfsFilesSafely, Lr as PKCError, M as isLinkOfAudio, Mn as CommentPubsubMessageReservedFields, Mt as ChallengeMessageSchema, N as isLinkOfImage, On as VoteTablesRowSchema, Or as t$4, P as isLinkOfMedia, Pt as ChallengeRequestMessageSchema, Q as retryKuboBlockPutPinAndProvidePubsubTopic, Rr as messages, Sr as e, T as ipnsNameToIpnsOverPubsubTopic, Tn as VotePubsubMessagePublicationSchema, Tr as t$3, Vn as CommentUpdateTableRowSchema, Xn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Xt as CommunityEditPublicationPubsubReservedFields, Yn as CommentEditPubsubMessagePublicationSchema, Zn as CommentEditReservedFields, _ as genToArray, _r as t$7, b as getIpnsRecordInLocalKuboNode, br as t$6, bt as syncCommunityRegistryEntry, c as contentContainsMarkdownImages, ct as withSortedKeys, dt as findStartedCommunity, et as retryKuboIpfsAddAndProvide, f as derivePublicationFromChallengeRequest, g as findMalformedUnicodeString, gr as n$3, hr as isStringDomain, i as calculateStringSizeSameAsIpfsAddCidV0, in as CommentModerationsTableRowSchema, ir as AuthorReservedFields, it as statMfsPathSafely, j as isLinkOfAnimatedImage, jn as CommentIpfsSchema, jr as require_retry, kr as t$2, kt as pTimeout, l as contentContainsMarkdownVideos, lt as withSortedKeysDeep, mn as CommunitySignedPropertyNames, nn as CommentModerationReservedFields, o as calculateUnixFsDagSizeCidV0, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, pn as CommunityIpfsSchema, pt as findUpdatingCommunity, r as calculateIpfsCidV0, rt as sleepUntilTimeoutOrAbort, s as contentContainsMarkdownAudio, ti as ZodError, tn as CommentModerationPubsubMessagePublicationSchema, ut as findCommunityInRegistry, v as getEquivalentCommunityAddresses, vr as n$2, wr as r$1, wt as untrackStartedCommunity, xr as e$1, xt as trackStartedCommunity, y as getErrorCodeFromMessage, yr as t$5, zn as CommentUpdateSchema, zr as logger_default, zt as DecryptedChallengeRequestPublicationSchema } from "./util-BwEIge-b.js";
3
+ import { $ as createSchemaRowParser, An as verifyChallengeAnswer, Ar as removeFileRetryingWhileBusy, Bn as verifyCommunityEdit, Br as takeStartLock, Dt as parseJsonWithPKCErrorIfFails, En as signCommunity, Fn as verifyCommentIpfs, Gr as n$5, Hn as verifyVote, Hr as t$11, In as verifyCommentModeration, Jr as t$9, Kn as getAuthorNameFromWire, Kr as n$4, Ln as verifyCommentPubsubMessage, Lr as getStartLockPath, Mn as verifyChallengeRequest, N as MAX_PAGE_SIZE_BYTES, Or as moveCommunityDbToDeletedDirectory, Pn as verifyCommentEdit, Pr as findCommunitiesEntry, Q as collectSchemaRowCoercions, Qn as effectiveMaxCrosspostDepth, Rn as verifyCommentUpdate, Rr as isCommunityStartLocked, S as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, Sn as signCommentEdit, Sr as getDefaultCommunityDbConfig, Tn as signCommentUpdateForChallengeVerification, Tr as importSignerIntoKuboNode, Un as buildRuntimeAuthor, Ur as r$2, Vr as t$10, W as pLimit, Wn as cleanWireAuthor, Wr as t$8, X as coerceSchemaRowBoolean, Yr as stringify, Z as coerceSchemaRowJson, Zn as crosspostChainDepthUpTo, _ as createAuthorIdentityMatcher, _r as deriveCommentIpfsFromCommentTableRow, a as generatePagesReportingFailedSorts, ar as encode, b as KeyvBetterSqlite3, bn as signChallengeVerification, c as resolvePageSortsOrThrow, cn as SignerWithPublicKeyAddress, cr as getPKCAddressFromPublicKey, d as getChallengeVerification, dr as BackupAbortError, dt as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, ei as STORAGE_KEYS, f as getCommunityChallengeFromCommunityChallengeSettings, fn as decryptEd25519AesGcmPublicKeyBuffer, fr as backupCommunityDb, g as authorNameResolveFailureReason, gn as cleanUpBeforePublishing, gr as deleteOldCommunityInWindows, h as authorIdentityMatcherForRequest, hn as _validateSignatureOfPKCRecord, i as derivePublicPageSorts, ir as decode, j as iterateOverPageCidsToFindAllCids, jr as resolveDbPostsCidRefs, kr as refreshCommunitiesList, lr as getPKCAddressFromPublicKeySync, m as pkcJsChallenges, mn as encryptEd25519AesGcmPublicKeyBuffer, mr as calculateInlineRepliesBudget, nr as getCommunityPublicKeyFromWire, o as loadPageSortsForStartedCommunity, p as loadChallengeFileFromCommunityChallengeSettings, pr as calculateExpectedSignatureSize, pt as parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails, r as computePageSortsFingerprint, s as lookupPageSortFactories, sr as getIpfsKeyFromPrivateKey, t as RpcLocalCommunity, ti as require_lodash_merge, tr as getCommunityNameFromWire, u as deriveCommunityChallengesOrThrow, ur as getPublicKeyFromPrivateKey, v as TrackedInstanceRegistry, vn as signChallengeMessage, vr as deriveDbPosts, w as TIMEFRAMES_TO_SECONDS, wn as signCommentUpdate, wr as getThumbnailPropsOfLink, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, xn as signComment, xr as forgetCommunityThatFailedToBeDeleted, y as LRUCache, yr as deriveDbReplies, zn as verifyCommunity, zr as releaseStartLock } from "./rpc-local-community-DDAibWpE.js";
4
+ import { a as scorePageCommentsWithFile, i as partitionPageCommentsForSort, n as filterRepliesForPageSort, o as stripRepliesFromPageComment, r as orderPageCommentsByScore, t as createDescendantsLookup } from "./page-sort-scoring-d1frahfd.js";
5
5
  import { c as prepare, n as decode$1, r as encode$1 } from "./src-BSYNGtIQ.js";
6
6
  import { t as UnixFS } from "./src-CAvdjq_i.js";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -1006,19 +1006,14 @@ async function importCommunitySignerIntoIpfsIfNeeded(community) {
1006
1006
  headers: community._pkc.kuboRpcClientsOptions[0].headers
1007
1007
  });
1008
1008
  }
1009
- async function getDbInternalState(community, lock) {
1009
+ function getDbInternalState(community) {
1010
1010
  const log = logger_default("pkc-js:local-community:_getDbInternalState");
1011
1011
  if (!community._dbHandler.keyvHas(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY])) throw new PKCError("ERR_COMMUNITY_HAS_NO_INTERNAL_STATE", {
1012
1012
  address: community.address,
1013
1013
  dataPath: community._pkc.dataPath
1014
1014
  });
1015
- let lockedIt = false;
1016
1015
  try {
1017
- if (lock) {
1018
- await community._dbHandler.lockCommunityState();
1019
- lockedIt = true;
1020
- }
1021
- const internalState = await community._dbHandler.keyvGet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY]);
1016
+ const internalState = community._dbHandler.keyvGet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY]);
1022
1017
  if (!internalState) throw new PKCError("ERR_COMMUNITY_HAS_NO_INTERNAL_STATE", {
1023
1018
  address: community.address,
1024
1019
  dataPath: community._pkc.dataPath
@@ -1027,8 +1022,6 @@ async function getDbInternalState(community, lock) {
1027
1022
  } catch (e) {
1028
1023
  log.error("Failed to get community", community.address, "internal state from db", e);
1029
1024
  throw e;
1030
- } finally {
1031
- if (lockedIt) await community._dbHandler.unlockCommunityState();
1032
1025
  }
1033
1026
  }
1034
1027
  async function updateDbInternalState(community, propsOrBuildProps) {
@@ -1036,26 +1029,27 @@ async function updateDbInternalState(community, propsOrBuildProps) {
1036
1029
  if (typeof propsOrBuildProps !== "function" && e(propsOrBuildProps)) throw Error("props to update DB internal state should not be empty");
1037
1030
  await community._dbHandler.initDbIfNeeded();
1038
1031
  let props = typeof propsOrBuildProps === "function" ? {} : propsOrBuildProps;
1039
- let lockedIt = false;
1040
1032
  try {
1041
- await community._dbHandler.lockCommunityState();
1042
- lockedIt = true;
1043
- if (typeof propsOrBuildProps === "function") props = propsOrBuildProps();
1044
- props._internalStateUpdateId = v4();
1045
- const internalStateBefore = await community._getDbInternalState(false);
1046
- const propsToStore = "posts" in props && props.posts ? {
1047
- ...props,
1048
- posts: deriveDbPosts({
1049
- posts: props.posts,
1050
- allPageCids: community._postsAllPageCids
1051
- })
1052
- } : props;
1053
- const mergedInternalState = {
1054
- ...internalStateBefore,
1055
- ...propsToStore
1056
- };
1057
- await community._dbHandler.keyvSet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY], mergedInternalState);
1058
- community._internalStateUpdateId = props._internalStateUpdateId;
1033
+ const internalStateUpdateId = v4();
1034
+ const mergedInternalState = community._dbHandler.runInWriteTransaction(() => {
1035
+ if (typeof propsOrBuildProps === "function") props = Object.assign(propsOrBuildProps(), ...community._editsStoredNotApplied);
1036
+ props._internalStateUpdateId = internalStateUpdateId;
1037
+ const internalStateBefore = community._getDbInternalState();
1038
+ const propsToStore = "posts" in props && props.posts ? {
1039
+ ...props,
1040
+ posts: deriveDbPosts({
1041
+ posts: props.posts,
1042
+ allPageCids: community._postsAllPageCids
1043
+ })
1044
+ } : props;
1045
+ const merged = {
1046
+ ...internalStateBefore,
1047
+ ...propsToStore
1048
+ };
1049
+ community._dbHandler.keyvSet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY], merged);
1050
+ return merged;
1051
+ });
1052
+ community._internalStateUpdateId = internalStateUpdateId;
1059
1053
  log.trace("Updated community", community.address, "internal state in db with new props", Object.keys(props));
1060
1054
  if (community.updateCid && community.raw.communityIpfs) community.raw.localCommunity = community.toJSONInternalRpcAfterFirstUpdate();
1061
1055
  else if (community.settings) community.raw.localCommunity = community.toJSONInternalRpcBeforeFirstUpdate();
@@ -1063,12 +1057,10 @@ async function updateDbInternalState(community, propsOrBuildProps) {
1063
1057
  } catch (e) {
1064
1058
  log.error("Failed to update community", community.address, "internal state in db with new props", Object.keys(props), e);
1065
1059
  throw e;
1066
- } finally {
1067
- if (lockedIt) await community._dbHandler.unlockCommunityState();
1068
1060
  }
1069
1061
  }
1070
1062
  async function updateInstanceStateWithDbState(community) {
1071
- const currentDbState = await community._getDbInternalState(false);
1063
+ const currentDbState = community._getDbInternalState();
1072
1064
  if ("updatedAt" in currentDbState) {
1073
1065
  if (currentDbState.posts && !("pages" in currentDbState.posts)) if (community._dbHandler.hasCommentsAndCommentUpdatesTables()) {
1074
1066
  const dbPosts = currentDbState.posts;
@@ -1443,7 +1435,6 @@ function createPositionalCommentRowMapper(cols) {
1443
1435
  }
1444
1436
  //#endregion
1445
1437
  //#region dist/node/runtime/node/community/db-handler.js
1446
- var import_src = /* @__PURE__ */ __toESM(require_src(), 1);
1447
1438
  const createCommunityAuthorMemo = () => ({
1448
1439
  writeGeneration: -1,
1449
1440
  authors: /* @__PURE__ */ new Map(),
@@ -1469,7 +1460,7 @@ var DbHandler = class {
1469
1460
  constructor(community) {
1470
1461
  this._transactionGeneration = 0;
1471
1462
  this._publicationWriteGeneration = 0;
1472
- this._heldStartLock = void 0;
1463
+ this._startLockAddress = void 0;
1473
1464
  this._community = community;
1474
1465
  this._transactionDepth = 0;
1475
1466
  this._createdTables = false;
@@ -1538,7 +1529,7 @@ var DbHandler = class {
1538
1529
  } catch (e) {
1539
1530
  await this.initDbIfNeeded();
1540
1531
  log.error(`Community (${this._community.address}) failed to create/migrate tables. Current db version (${this.getDbVersion()}), latest db version (${version_default.DB_VERSION}). Error`, e);
1541
- await this.destoryConnection();
1532
+ if (this._startLockAddress === void 0) this.destoryConnection();
1542
1533
  throw e;
1543
1534
  }
1544
1535
  hideClassPrivateProps(this);
@@ -1568,6 +1559,13 @@ var DbHandler = class {
1568
1559
  }
1569
1560
  destoryConnection() {
1570
1561
  const log = logger_default("pkc-js:local-community:dbHandler:destroyConnection");
1562
+ if (this.holdsStartLock()) {
1563
+ const error = /* @__PURE__ */ new Error(`Refused to close the DB connection of community (${this._startLockAddress}) while it holds the community's start lock (issue #561)`);
1564
+ log.error(error);
1565
+ if (process.env["VITEST"]) throw error;
1566
+ return;
1567
+ }
1568
+ this._startLockAddress = void 0;
1571
1569
  this._preparedStatements.clear();
1572
1570
  if (this._db && this._db.open) try {
1573
1571
  if (!this._db.readonly) this._db.exec("PRAGMA wal_checkpoint");
@@ -1836,15 +1834,10 @@ var DbHandler = class {
1836
1834
  const dbExistsAlready = fs$1.existsSync(dbPath);
1837
1835
  if (needToMigrate) {
1838
1836
  if (dbExistsAlready && currentDbVersion > 0) {
1839
- this.destoryConnection();
1840
1837
  backupDbPath = path$1.join(path$1.dirname(dbPath), ".backup_before_migration", `${path$1.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
1841
1838
  log(`Copying db ${path$1.basename(dbPath)} to ${backupDbPath} before migration`);
1842
1839
  if (!fs$1.existsSync(path$1.dirname(backupDbPath))) await fs$1.promises.mkdir(path$1.dirname(backupDbPath), { recursive: true });
1843
- const sourceDb = new Database(dbPath, { fileMustExist: true });
1844
- await sourceDb.backup(backupDbPath);
1845
- sourceDb.close();
1846
- this._db = new Database(dbPath);
1847
- this._db.pragma("journal_mode = WAL");
1840
+ await this._db.backup(backupDbPath);
1848
1841
  }
1849
1842
  this._db.exec("PRAGMA foreign_keys = OFF");
1850
1843
  for (const tableName of [
@@ -3927,6 +3920,10 @@ var DbHandler = class {
3927
3920
  });
3928
3921
  if (os.type() === "Windows_NT") await deleteOldCommunityInWindows(oldPathString, this._community._pkc);
3929
3922
  else await fs$1.promises.rm(oldPathString, { force: true });
3923
+ if (!fs$1.existsSync(oldPathString)) await fs$1.promises.rm(getStartLockPath({
3924
+ dataPath,
3925
+ communityAddress: oldDbName
3926
+ }), { force: true });
3930
3927
  }
3931
3928
  } catch (error) {
3932
3929
  log.error(`Failed to backup/rename database from ${oldPathString} to ${newPathString}: `, error);
@@ -3938,49 +3935,53 @@ var DbHandler = class {
3938
3935
  };
3939
3936
  log(`Changed db path from (${oldPathString}) to (${newPathString})`);
3940
3937
  }
3941
- async lockCommunityStart({ onCompromised }) {
3938
+ async lockCommunityStart() {
3942
3939
  const log = logger_default("pkc-js:local-community:db-handler:lock:start");
3943
3940
  const communityAddress = this._community.address;
3944
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3945
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3946
- const startLock = {};
3947
- try {
3948
- await import_src.default.lock(communityDbPath, {
3949
- lockfilePath,
3950
- onCompromised: (error) => {
3951
- if (this._heldStartLock !== startLock) return;
3952
- this._heldStartLock = void 0;
3953
- log.error(`Lost the start lock of community (${communityAddress}), taken over or removed`, error);
3954
- onCompromised(error);
3955
- }
3941
+ const dataPath = this._community._pkc.dataPath;
3942
+ await this.initDbIfNeeded();
3943
+ await fs$1.promises.rm(path$1.join(dataPath, "communities", `${communityAddress}.start.lock`), {
3944
+ recursive: true,
3945
+ force: true
3946
+ });
3947
+ if (!takeStartLock({
3948
+ db: this._db,
3949
+ dataPath,
3950
+ communityAddress
3951
+ })) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { communityAddress });
3952
+ if (!fs$1.existsSync(path$1.join(dataPath, "communities", communityAddress))) {
3953
+ releaseStartLock({
3954
+ db: this._db,
3955
+ dataPath,
3956
+ communityAddress
3956
3957
  });
3957
- this._heldStartLock = startLock;
3958
- log(`Locked the start of community (${communityAddress}) successfully`);
3959
- } catch (e) {
3960
- if (e instanceof Error && e.message === "Lock file is already being held") throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", {
3958
+ fs$1.rmSync(getStartLockPath({
3959
+ dataPath,
3960
+ communityAddress
3961
+ }), { force: true });
3962
+ throw new PKCError("CAN_NOT_LOAD_LOCAL_COMMUNITY_IF_DB_DOES_NOT_EXIST", {
3961
3963
  communityAddress,
3962
- error: e
3964
+ dataPath
3963
3965
  });
3964
- else {
3965
- log(`Error while trying to lock start of community (${communityAddress}): ${e}`);
3966
- throw e;
3967
- }
3968
3966
  }
3967
+ this._startLockAddress = communityAddress;
3968
+ log(`Locked the start of community (${communityAddress}) successfully`);
3969
+ }
3970
+ holdsStartLock() {
3971
+ return this._startLockAddress !== void 0 && this._db?.open === true;
3969
3972
  }
3970
- async unlockCommunityStart(communityAddress = this._community.address) {
3973
+ async unlockCommunityStart() {
3971
3974
  const log = logger_default("pkc-js:local-community:db-handler:unlock:start");
3972
- log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3973
- this._heldStartLock = void 0;
3974
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3975
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3976
- if (!fs$1.existsSync(lockfilePath) || !fs$1.existsSync(communityDbPath)) return;
3977
- try {
3978
- await import_src.default.unlock(communityDbPath, { lockfilePath });
3979
- log(`Unlocked start of community (${communityAddress})`);
3980
- } catch (e) {
3981
- log(`Error while trying to unlock start of community (${communityAddress}): ${e}`);
3982
- throw e;
3983
- }
3975
+ const communityAddress = this._startLockAddress;
3976
+ if (communityAddress === void 0) return;
3977
+ this._startLockAddress = void 0;
3978
+ if (!this._db?.open) return;
3979
+ releaseStartLock({
3980
+ db: this._db,
3981
+ dataPath: this._community._pkc.dataPath,
3982
+ communityAddress
3983
+ });
3984
+ log(`Unlocked start of community (${communityAddress})`);
3984
3985
  }
3985
3986
  async isCommunityStartLocked(communityAddress = this._community.address) {
3986
3987
  return isCommunityStartLocked({
@@ -3988,34 +3989,24 @@ var DbHandler = class {
3988
3989
  communityAddress
3989
3990
  });
3990
3991
  }
3991
- async lockCommunityState() {
3992
- const log = logger_default("pkc-js:local-community:db-handler:lock:lockCommunityState");
3993
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
3994
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
3992
+ runInWriteTransaction(write) {
3993
+ if (this._db.inTransaction) return write();
3995
3994
  try {
3996
- await import_src.default.lock(communityDbPath, {
3997
- lockfilePath,
3998
- retries: 5,
3999
- onCompromised: () => {}
4000
- });
3995
+ this._db.exec("BEGIN IMMEDIATE");
4001
3996
  } catch (e) {
4002
- log.error(`Error when attempting to lock community state`, this._community.address, e);
4003
- if (e instanceof Error && e.message === "Lock file is already being held") throw new PKCError("ERR_COMMUNITY_STATE_LOCKED", {
3997
+ if (typeof e.code === "string" && e.code.startsWith("SQLITE_BUSY")) throw new PKCError("ERR_COMMUNITY_STATE_LOCKED", {
4004
3998
  communityAddress: this._community.address,
4005
3999
  error: e
4006
4000
  });
4001
+ throw e;
4007
4002
  }
4008
- }
4009
- async unlockCommunityState() {
4010
- const log = logger_default("pkc-js:local-community:db-handler:lock:unlockCommunityState");
4011
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
4012
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
4013
- if (!fs$1.existsSync(lockfilePath)) return;
4014
4003
  try {
4015
- await import_src.default.unlock(communityDbPath, { lockfilePath });
4004
+ const result = write();
4005
+ this._db.exec("COMMIT");
4006
+ return result;
4016
4007
  } catch (e) {
4017
- log.error(`Error when attempting to unlock community state`, this._community.address, e);
4018
- if (e instanceof Error && "code" in e && e.code !== "ENOTACQUIRED") throw e;
4008
+ if (this._db.inTransaction) this._db.exec("ROLLBACK");
4009
+ throw e;
4019
4010
  }
4020
4011
  }
4021
4012
  communityDbExists() {
@@ -4968,8 +4959,49 @@ async function repinCommentUpdateIfNeeded(community) {
4968
4959
  community._dbHandler.forceUpdateOnAllComments();
4969
4960
  }
4970
4961
  const MIN_MS_BETWEEN_GC = 3600 * 1e3;
4971
- const lastGcFinishedAtByKuboUrl = /* @__PURE__ */ new Map();
4962
+ const intervalStartedAtByKuboUrl = /* @__PURE__ */ new Map();
4972
4963
  const inFlightGcByKuboUrl = /* @__PURE__ */ new Map();
4964
+ const gcIntervalStorageKey = (kuboUrl) => `repoGcIntervalStartedAt:${kuboUrl}`;
4965
+ async function _readStoredGcIntervalStart({ community, kuboUrl, log }) {
4966
+ try {
4967
+ const stored = await community._pkc._storage.getItem(gcIntervalStorageKey(kuboUrl));
4968
+ return typeof stored === "number" ? stored : void 0;
4969
+ } catch (e) {
4970
+ log.error("Failed to read when the GC interval of the kubo node", kuboUrl, "started", e);
4971
+ return;
4972
+ }
4973
+ }
4974
+ async function _startGcInterval({ community, kuboUrl, log }) {
4975
+ const now = Date.now();
4976
+ intervalStartedAtByKuboUrl.set(kuboUrl, now);
4977
+ try {
4978
+ await community._pkc._storage.setItem(gcIntervalStorageKey(kuboUrl), now);
4979
+ } catch (e) {
4980
+ log.error("Failed to store when the GC interval of the kubo node", kuboUrl, "started", e);
4981
+ }
4982
+ }
4983
+ async function _isRepoGcDue({ community, kuboUrl, log }) {
4984
+ const isRunning = (startedAt) => typeof startedAt === "number" && startedAt <= Date.now() && Date.now() - startedAt < MIN_MS_BETWEEN_GC;
4985
+ const inMemory = intervalStartedAtByKuboUrl.get(kuboUrl);
4986
+ if (isRunning(inMemory)) return false;
4987
+ const stored = await _readStoredGcIntervalStart({
4988
+ community,
4989
+ kuboUrl,
4990
+ log
4991
+ });
4992
+ const startedAt = typeof stored === "number" && typeof inMemory === "number" ? Math.max(stored, inMemory) : stored ?? inMemory;
4993
+ if (isRunning(startedAt)) {
4994
+ intervalStartedAtByKuboUrl.set(kuboUrl, startedAt);
4995
+ return false;
4996
+ }
4997
+ if (typeof startedAt === "number" && startedAt <= Date.now()) return true;
4998
+ await _startGcInterval({
4999
+ community,
5000
+ kuboUrl,
5001
+ log
5002
+ });
5003
+ return false;
5004
+ }
4973
5005
  async function cleanUpIpfsRepoIfDue(community, force = false) {
4974
5006
  const log = logger_default("pkc-js:local-community:syncIpnsWithDb:_cleanUpIpfsRepoIfDue");
4975
5007
  const kuboRpc = community._clientsManager.getDefaultKuboRpcClient();
@@ -5015,10 +5047,11 @@ function _describeReclaimedSpace({ before, after }) {
5015
5047
  }
5016
5048
  async function _runRepoGcIfDue({ community, kuboUrl, force, log }) {
5017
5049
  const kuboRpc = community._clientsManager.getDefaultKuboRpcClient();
5018
- if (!force) {
5019
- const lastGcFinishedAt = lastGcFinishedAtByKuboUrl.get(kuboUrl);
5020
- if (typeof lastGcFinishedAt === "number" && Date.now() - lastGcFinishedAt < MIN_MS_BETWEEN_GC) return;
5021
- }
5050
+ if (!force && !await _isRepoGcDue({
5051
+ community,
5052
+ kuboUrl,
5053
+ log
5054
+ })) return;
5022
5055
  const repoSizeBefore = await _readRepoSizeSafely({
5023
5056
  kuboRpc,
5024
5057
  kuboUrl,
@@ -5032,7 +5065,11 @@ async function _runRepoGcIfDue({ community, kuboUrl, force, log }) {
5032
5065
  log.error("Failed to GC ipfs repo due to error", e);
5033
5066
  return;
5034
5067
  } finally {
5035
- lastGcFinishedAtByKuboUrl.set(kuboUrl, Date.now());
5068
+ await _startGcInterval({
5069
+ community,
5070
+ kuboUrl,
5071
+ log
5072
+ });
5036
5073
  }
5037
5074
  const repoSizeAfter = await _readRepoSizeSafely({
5038
5075
  kuboRpc,
@@ -6962,7 +6999,7 @@ async function publishLoop(community, syncIntervalMs) {
6962
6999
  const log = logger_default("pkc-js:local-community:_publishLoop");
6963
7000
  let syncFailedSinceStop = false;
6964
7001
  const shouldStopPublishLoop = () => {
6965
- return community.state !== "started" || community._startLockLost || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
7002
+ return community.state !== "started" || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
6966
7003
  };
6967
7004
  const waitUntilNextSync = async ({ lastSyncFailed }) => {
6968
7005
  const doneWithLoopTime = Date.now();
@@ -7056,6 +7093,7 @@ async function runAsStartOrUpdateInFlight({ community, setUp }) {
7056
7093
  async function start(community) {
7057
7094
  if (community.state === "updating") throw new PKCError("ERR_NEED_TO_STOP_UPDATING_COMMUNITY_BEFORE_STARTING", { address: community.address });
7058
7095
  if (community.state === "started" || community._startOrUpdateInFlight) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
7096
+ if (community._deleteInFlight) throw new PKCError("ERR_COMMUNITY_IS_BEING_DELETED", { address: community.address });
7059
7097
  await runAsStartOrUpdateInFlight({
7060
7098
  community,
7061
7099
  setUp: (releaseMark) => startCommunity({
@@ -7066,6 +7104,7 @@ async function start(community) {
7066
7104
  }
7067
7105
  async function startCommunity({ community, releaseMark }) {
7068
7106
  const log = logger_default("pkc-js:local-community:start");
7107
+ while (community._stoppedEditsInFlight.size > 0) await Promise.allSettled([...community._stoppedEditsInFlight]);
7069
7108
  community._stopHasBeenCalled = false;
7070
7109
  community._lastProvidedBrowserDialableSelfAddrs = void 0;
7071
7110
  community._lastAddressReprovideCheckAt = void 0;
@@ -7076,9 +7115,6 @@ async function startCommunity({ community, releaseMark }) {
7076
7115
  publicKey: community.publicKey,
7077
7116
  name: community.name
7078
7117
  }) || findProcessStartedCommunity(community)) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
7079
- community._startLockLost = false;
7080
- let startLockLostDuringStart;
7081
- let startFinished = false;
7082
7118
  try {
7083
7119
  await initBeforeStarting(community);
7084
7120
  if (community.anchor && !getPersistedAnchorRecordBytes(community)) throw new PKCError("ERR_DELEGATED_COMMUNITY_HAS_NO_ANCHOR_RECORD", {
@@ -7091,15 +7127,7 @@ async function startCommunity({ community, releaseMark }) {
7091
7127
  pkc: community._pkc,
7092
7128
  communityAddress: community.address
7093
7129
  });
7094
- await community._dbHandler.lockCommunityStart({ onCompromised: (error) => {
7095
- community._startLockLost = true;
7096
- const lostLockError = new PKCError("ERR_COMMUNITY_START_LOCK_COMPROMISED", {
7097
- communityAddress: community.address,
7098
- error
7099
- });
7100
- if (startFinished) stopAfterLosingStartLock(community, lostLockError);
7101
- else startLockLostDuringStart = lostLockError;
7102
- } });
7130
+ await community._dbHandler.lockCommunityStart();
7103
7131
  community._setState("started");
7104
7132
  await community._updateStartedValue();
7105
7133
  trackStartedCommunity(community._pkc, community);
@@ -7122,14 +7150,11 @@ async function startCommunity({ community, releaseMark }) {
7122
7150
  community._setStartedStateWithEmission("publishing-ipns");
7123
7151
  await community._repinCommentsIPFSIfNeeded();
7124
7152
  await repinCommentUpdateIfNeeded(community);
7125
- if (startLockLostDuringStart) throw startLockLostDuringStart;
7126
7153
  await community._listenToIncomingRequests();
7127
7154
  await emitChallengeSettingsValidationErrors(community, log);
7128
7155
  community._pageSorts = void 0;
7129
7156
  community._pageSortFactories = void 0;
7130
7157
  await syncPageSortsWithRegistry(community);
7131
- if (startLockLostDuringStart) throw startLockLostDuringStart;
7132
- startFinished = true;
7133
7158
  } catch (e) {
7134
7159
  releaseMark();
7135
7160
  await community.stop();
@@ -7145,12 +7170,6 @@ async function startCommunity({ community, releaseMark }) {
7145
7170
  community.emit("error", err);
7146
7171
  });
7147
7172
  }
7148
- function stopAfterLosingStartLock(community, error) {
7149
- const log = logger_default("pkc-js:local-community:stopAfterLosingStartLock");
7150
- if (community.state !== "started") return;
7151
- if (!community._stopHasBeenCalled) community.stop().catch((e) => log.error(`Failed to stop community (${community.address}) after losing its start lock`, e));
7152
- community.emit("error", error);
7153
- }
7154
7173
  async function initMirroringStartedOrUpdatingCommunity(community, startedCommunity) {
7155
7174
  const updatingStateChangeListener = (newState) => {
7156
7175
  community._setUpdatingStateWithEventEmissionIfNewState(newState);
@@ -7319,23 +7338,20 @@ async function stopCommunity(community) {
7319
7338
  }
7320
7339
  community._publishLoopPromise = void 0;
7321
7340
  }
7322
- if (community._startLockLost) log(`Community (${community.address}) lost its start lock, stopping without writing its state, unpinning or unlocking`);
7323
- else {
7324
- try {
7325
- await unpinStaleCids(community, { bypassGracePeriod: true });
7326
- } catch (e) {
7327
- log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
7328
- }
7329
- try {
7330
- await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
7331
- } catch (e) {
7332
- log.error("Failed to update db internal state before stopping", e);
7333
- }
7334
- try {
7335
- await community._dbHandler.unlockCommunityStart();
7336
- } catch (e) {
7337
- log.error(`Failed to unlock start lock on community (${community.address})`, e);
7338
- }
7341
+ try {
7342
+ await unpinStaleCids(community, { bypassGracePeriod: true });
7343
+ } catch (e) {
7344
+ log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
7345
+ }
7346
+ try {
7347
+ await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
7348
+ } catch (e) {
7349
+ log.error("Failed to update db internal state before stopping", e);
7350
+ }
7351
+ try {
7352
+ await community._dbHandler.unlockCommunityStart();
7353
+ } catch (e) {
7354
+ log.error(`Failed to unlock start lock on community (${community.address})`, e);
7339
7355
  }
7340
7356
  const kuboRpcClient = community._clientsManager.getDefaultKuboRpcClient();
7341
7357
  community._setStartedStateWithEmission("stopped");
@@ -7344,7 +7360,6 @@ async function stopCommunity(community) {
7344
7360
  community._duplicatePublicationAttempts?.clear();
7345
7361
  community._inFlightPublicationExchanges.clear();
7346
7362
  await community._dbHandler.rollbackAllTransactions();
7347
- await community._dbHandler.unlockCommunityState();
7348
7363
  await community._updateStartedValue();
7349
7364
  community._clientsManager.updateKuboRpcState("stopped", kuboRpcClient.url);
7350
7365
  community._clientsManager.updateKuboRpcPubsubStateIfProviderExists("stopped");
@@ -7370,7 +7385,19 @@ async function stopCommunity(community) {
7370
7385
  }
7371
7386
  const DELETE_UNPIN_SLICE_SIZE = 5e3;
7372
7387
  async function deleteCommunity(community) {
7388
+ let settle;
7389
+ const inFlight = new Promise((resolve) => settle = resolve);
7390
+ community._deleteInFlight = inFlight;
7391
+ try {
7392
+ await deleteCommunityWhileMarked(community);
7393
+ } finally {
7394
+ if (community._deleteInFlight === inFlight) community._deleteInFlight = void 0;
7395
+ settle();
7396
+ }
7397
+ }
7398
+ async function deleteCommunityWhileMarked(community) {
7373
7399
  const log = logger_default("pkc-js:local-community:delete");
7400
+ while (community._startOrUpdateInFlight) await community._startOrUpdateInFlight;
7374
7401
  log.trace(`Attempting to stop the community (${community.address}) before deleting, if needed`);
7375
7402
  const startedCommunity = findStartedCommunity(community._pkc, {
7376
7403
  publicKey: community.publicKey,
@@ -7641,6 +7668,7 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7641
7668
  const log = logger_default("pkc-js:local-community:start:editPropsOnStartedCommunity");
7642
7669
  const oldAddress = t$9(community.address);
7643
7670
  const uniqueEditId = (0, import_sha256.sha256)(stringify(parsedEditOptions));
7671
+ let storedEdit;
7644
7672
  if (typeof parsedEditOptions.address === "string" && community.address !== parsedEditOptions.address) {
7645
7673
  const newAddress = parsedEditOptions.address;
7646
7674
  await validateNewAddressBeforeEditing(community, newAddress, log);
@@ -7691,10 +7719,18 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7691
7719
  await community.start();
7692
7720
  } else {
7693
7721
  if (!e(parsedEditOptions)) {
7694
- const store = updateDbInternalState(community, { ...parsedEditOptions });
7722
+ const editToStore = { ...parsedEditOptions };
7723
+ const store = updateDbInternalState(community, () => {
7724
+ community._editsStoredNotApplied.add(editToStore);
7725
+ return { ...parsedEditOptions };
7726
+ });
7727
+ storedEdit = editToStore;
7695
7728
  community._editStoresInFlight.add(store);
7696
7729
  try {
7697
7730
  await store;
7731
+ } catch (e) {
7732
+ community._editsStoredNotApplied.delete(editToStore);
7733
+ throw e;
7698
7734
  } finally {
7699
7735
  community._editStoresInFlight.delete(store);
7700
7736
  }
@@ -7704,16 +7740,20 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7704
7740
  editId: uniqueEditId
7705
7741
  });
7706
7742
  }
7707
- if (community.updateCid) await community.initInternalCommunityAfterFirstUpdateNoMerge({
7708
- ...community.toJSONInternalAfterFirstUpdate(),
7709
- ...parsedEditOptions,
7710
- _internalStateUpdateId: uniqueEditId
7711
- });
7712
- else await community.initInternalCommunityBeforeFirstUpdateNoMerge({
7713
- ...community.toJSONInternalBeforeFirstUpdate(),
7714
- ...parsedEditOptions,
7715
- _internalStateUpdateId: uniqueEditId
7716
- });
7743
+ try {
7744
+ if (community.updateCid) await community.initInternalCommunityAfterFirstUpdateNoMerge({
7745
+ ...community.toJSONInternalAfterFirstUpdate(),
7746
+ ...parsedEditOptions,
7747
+ _internalStateUpdateId: uniqueEditId
7748
+ });
7749
+ else await community.initInternalCommunityBeforeFirstUpdateNoMerge({
7750
+ ...community.toJSONInternalBeforeFirstUpdate(),
7751
+ ...parsedEditOptions,
7752
+ _internalStateUpdateId: uniqueEditId
7753
+ });
7754
+ } finally {
7755
+ if (storedEdit) community._editsStoredNotApplied.delete(storedEdit);
7756
+ }
7717
7757
  await applyPagesEdit(community, pagesEdit);
7718
7758
  community._communityUpdateTrigger = true;
7719
7759
  log(`Community (${community.address}) props (${t$6(parsedEditOptions)}) has been edited. Will be including edited props in next update: `, t$10(community, t$6(parsedEditOptions)));
@@ -7725,6 +7765,17 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7725
7765
  return community;
7726
7766
  }
7727
7767
  async function editPropsOnNotStartedCommunity(community, parsedEditOptions, pagesEdit) {
7768
+ let settle;
7769
+ const inFlight = new Promise((resolve) => settle = resolve);
7770
+ community._stoppedEditsInFlight.add(inFlight);
7771
+ try {
7772
+ return await editPropsOnNotStartedCommunityWhileMarked(community, parsedEditOptions, pagesEdit);
7773
+ } finally {
7774
+ community._stoppedEditsInFlight.delete(inFlight);
7775
+ settle();
7776
+ }
7777
+ }
7778
+ async function editPropsOnNotStartedCommunityWhileMarked(community, parsedEditOptions, pagesEdit) {
7728
7779
  const log = logger_default("pkc-js:local-community:edit:editPropsOnNotStartedCommunity");
7729
7780
  const oldAddress = t$9(community.address);
7730
7781
  await community.initDbHandlerIfNeeded();
@@ -7755,12 +7806,13 @@ async function editPropsOnNotStartedCommunity(community, parsedEditOptions, page
7755
7806
  if ("updatedAt" in mergedInternalState && mergedInternalState.updatedAt) await community.initInternalCommunityAfterFirstUpdateNoMerge(mergedInternalState);
7756
7807
  else await community.initInternalCommunityBeforeFirstUpdateNoMerge(mergedInternalState);
7757
7808
  await applyPagesEdit(community, pagesEdit);
7758
- await community._dbHandler.destoryConnection();
7809
+ community._dbHandler.destoryConnection();
7759
7810
  community.emit("update", community);
7760
7811
  return community;
7761
7812
  }
7813
+ const isStartInFlight = (community) => community.state === "stopped" && community._startOrUpdateInFlight !== void 0;
7762
7814
  async function edit(community, newCommunityOptions) {
7763
- while (community._stopInFlight) await community._stopInFlight;
7815
+ while (community._stopInFlight || isStartInFlight(community)) await (community._stopInFlight ?? community._startOrUpdateInFlight);
7764
7816
  const startedCommunity = findStartedCommunity(community._pkc, {
7765
7817
  publicKey: community.publicKey,
7766
7818
  name: community.name
@@ -7773,6 +7825,7 @@ async function edit(community, newCommunityOptions) {
7773
7825
  }
7774
7826
  await community.initDbHandlerIfNeeded();
7775
7827
  await community._updateStartedValue();
7828
+ if (isStartInFlight(community)) return edit(community, newCommunityOptions);
7776
7829
  if (community.started && community.state !== "started") {
7777
7830
  community._dbHandler.destoryConnection();
7778
7831
  throw new PKCError("ERR_CAN_NOT_EDIT_A_LOCAL_COMMUNITY_THAT_IS_ALREADY_STARTED_IN_ANOTHER_PROCESS", {
@@ -7791,7 +7844,7 @@ async function edit(community, newCommunityOptions) {
7791
7844
  ...n$2(editWithDerivedName, ["roles"]),
7792
7845
  ...newInternalProps
7793
7846
  };
7794
- if (community._stopInFlight) return edit(community, newCommunityOptions);
7847
+ if (community._stopInFlight || isStartInFlight(community)) return edit(community, newCommunityOptions);
7795
7848
  if (!community.started && !startedCommunity) return editPropsOnNotStartedCommunity(community, newProps, pagesEdit);
7796
7849
  if (findStartedCommunity(community._pkc, {
7797
7850
  publicKey: community.publicKey,
@@ -8023,12 +8076,14 @@ var LocalCommunity = class extends RpcLocalCommunity {
8023
8076
  this._pageSorts = void 0;
8024
8077
  this._pageSortFactories = void 0;
8025
8078
  this._reportedChallengeLoadFailures = void 0;
8026
- this._startLockLost = false;
8027
8079
  this._publishLoopPromise = void 0;
8028
8080
  this._updateLoopPromise = void 0;
8029
8081
  this._startOrUpdateInFlight = void 0;
8030
8082
  this._stopInFlight = void 0;
8083
+ this._deleteInFlight = void 0;
8084
+ this._stoppedEditsInFlight = /* @__PURE__ */ new Set();
8031
8085
  this._editStoresInFlight = /* @__PURE__ */ new Set();
8086
+ this._editsStoredNotApplied = /* @__PURE__ */ new Set();
8032
8087
  this._internalStateUpdateId = "";
8033
8088
  this._lastPubsubTopicRoutingProvideAt = void 0;
8034
8089
  this._subscribedChallengePubsubTopic = void 0;
@@ -8282,7 +8337,7 @@ var LocalCommunity = class extends RpcLocalCommunity {
8282
8337
  try {
8283
8338
  return { moderations: this._dbHandler.queryAllCommentModerations(opts) };
8284
8339
  } finally {
8285
- if (this.state === "stopped") this._dbHandler.destoryConnection();
8340
+ if (this.state === "stopped" && !this._startOrUpdateInFlight) this._dbHandler.destoryConnection();
8286
8341
  }
8287
8342
  }
8288
8343
  async _cancelExport(exportId) {
@@ -8294,8 +8349,8 @@ var LocalCommunity = class extends RpcLocalCommunity {
8294
8349
  async _loadExportsFromKeyv() {
8295
8350
  return loadAndPruneExportsFromKeyv(this);
8296
8351
  }
8297
- async _getDbInternalState(includeMutable = false) {
8298
- return getDbInternalState(this, includeMutable);
8352
+ _getDbInternalState() {
8353
+ return getDbInternalState(this);
8299
8354
  }
8300
8355
  async _listenToIncomingRequests() {
8301
8356
  return listenToIncomingRequests(this);