@pkcprotocol/pkc-js 0.0.146 → 0.0.147

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 (80) hide show
  1. package/README.md +88 -55
  2. package/dist/browser/clients/base-client-manager.js +14 -2
  3. package/dist/browser/clients/base-client-manager.js.map +1 -1
  4. package/dist/browser/errors.d.ts +3 -0
  5. package/dist/browser/errors.js +3 -0
  6. package/dist/browser/errors.js.map +1 -1
  7. package/dist/browser/generated-version.d.ts +1 -1
  8. package/dist/browser/generated-version.js +1 -1
  9. package/dist/browser/pkc-error.d.ts +1 -1
  10. package/dist/browser/publications/comment/comment-client-manager.d.ts +15 -3
  11. package/dist/browser/publications/comment/comment-client-manager.js +221 -10
  12. package/dist/browser/publications/comment/comment-client-manager.js.map +1 -1
  13. package/dist/browser/publications/comment/comment.js +1 -0
  14. package/dist/browser/publications/comment/comment.js.map +1 -1
  15. package/dist/browser/runtime/node/community/db-handler.d.ts +5 -1
  16. package/dist/browser/runtime/node/community/db-handler.js +64 -12
  17. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  18. package/dist/browser/runtime/node/community/local-community/db-state.js +95 -13
  19. package/dist/browser/runtime/node/community/local-community/db-state.js.map +1 -1
  20. package/dist/browser/runtime/node/community/local-community/editing.js +92 -22
  21. package/dist/browser/runtime/node/community/local-community/editing.js.map +1 -1
  22. package/dist/browser/runtime/node/community/local-community/lifecycle.d.ts +2 -0
  23. package/dist/browser/runtime/node/community/local-community/lifecycle.js +72 -20
  24. package/dist/browser/runtime/node/community/local-community/lifecycle.js.map +1 -1
  25. package/dist/browser/runtime/node/community/local-community.d.ts +1 -0
  26. package/dist/browser/runtime/node/community/local-community.js +3 -0
  27. package/dist/browser/runtime/node/community/local-community.js.map +1 -1
  28. package/dist/browser/runtime/node/util.d.ts +9 -0
  29. package/dist/browser/runtime/node/util.js +141 -25
  30. package/dist/browser/runtime/node/util.js.map +1 -1
  31. package/dist/browser/test/test-util.d.ts +7 -1
  32. package/dist/browser/test/test-util.js +45 -16
  33. package/dist/browser/test/test-util.js.map +1 -1
  34. package/dist/bundled/bundle-manifest.json +47 -47
  35. package/dist/bundled/challenges.js +1 -1
  36. package/dist/bundled/chunks/{helia-for-pkc-PaZmkxgn.js → helia-for-pkc-jM3y3OXF.js} +2 -2
  37. package/dist/bundled/chunks/{local-community-BY1ouP1-.js → local-community-5X7bvOoN.js} +247 -52
  38. package/dist/bundled/chunks/{local-community-CeuVhBBn.js → local-community-P9e5jksW.js} +1 -1
  39. package/dist/bundled/chunks/{node-BXilwSVE.js → node-By3og2hw.js} +162 -16
  40. package/dist/bundled/chunks/{page-sort-scoring-DgSzIxmE.js → page-sort-scoring-DwYGP_0d.js} +1 -1
  41. package/dist/bundled/chunks/{rpc-local-community-BK_HGb_u.js → rpc-local-community-WnhiTbxm.js} +122 -29
  42. package/dist/bundled/chunks/{util-DRSzW-LU.js → util-7QtFMzpc.js} +1 -1
  43. package/dist/bundled/chunks/{util-Bnqvxk-6.js → util-DMr7Hj-w.js} +4 -1
  44. package/dist/bundled/chunks/{validate-package-factories-MG5ehoSU.js → validate-package-factories-TwRblx9f.js} +2 -2
  45. package/dist/bundled/index.js +1 -1
  46. package/dist/bundled/page-sorts.js +1 -1
  47. package/dist/bundled/rpc/src/index.js +4 -4
  48. package/dist/node/clients/base-client-manager.js +14 -2
  49. package/dist/node/clients/base-client-manager.js.map +1 -1
  50. package/dist/node/errors.d.ts +3 -0
  51. package/dist/node/errors.js +3 -0
  52. package/dist/node/errors.js.map +1 -1
  53. package/dist/node/generated-version.d.ts +1 -1
  54. package/dist/node/generated-version.js +1 -1
  55. package/dist/node/pkc-error.d.ts +1 -1
  56. package/dist/node/publications/comment/comment-client-manager.d.ts +15 -3
  57. package/dist/node/publications/comment/comment-client-manager.js +221 -10
  58. package/dist/node/publications/comment/comment-client-manager.js.map +1 -1
  59. package/dist/node/publications/comment/comment.js +1 -0
  60. package/dist/node/publications/comment/comment.js.map +1 -1
  61. package/dist/node/runtime/node/community/db-handler.d.ts +5 -1
  62. package/dist/node/runtime/node/community/db-handler.js +64 -12
  63. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  64. package/dist/node/runtime/node/community/local-community/db-state.js +95 -13
  65. package/dist/node/runtime/node/community/local-community/db-state.js.map +1 -1
  66. package/dist/node/runtime/node/community/local-community/editing.js +92 -22
  67. package/dist/node/runtime/node/community/local-community/editing.js.map +1 -1
  68. package/dist/node/runtime/node/community/local-community/lifecycle.d.ts +2 -0
  69. package/dist/node/runtime/node/community/local-community/lifecycle.js +72 -20
  70. package/dist/node/runtime/node/community/local-community/lifecycle.js.map +1 -1
  71. package/dist/node/runtime/node/community/local-community.d.ts +1 -0
  72. package/dist/node/runtime/node/community/local-community.js +3 -0
  73. package/dist/node/runtime/node/community/local-community.js.map +1 -1
  74. package/dist/node/runtime/node/util.d.ts +9 -0
  75. package/dist/node/runtime/node/util.js +141 -25
  76. package/dist/node/runtime/node/util.js.map +1 -1
  77. package/dist/node/test/test-util.d.ts +7 -1
  78. package/dist/node/test/test-util.js +45 -16
  79. package/dist/node/test/test-util.js.map +1 -1
  80. package/package.json +1 -1
@@ -1,11 +1,11 @@
1
1
  import { i as __toESM } from "./chunk-2rV9d50f.js";
2
- import { Ar as t$2, At as pTimeout, B as pubsubTopicToDhtKey, Bn as CommentUpdateSchema, Br as logger_default, Bt as DecryptedChallengeRequestPublicationSchema, C as hideClassPrivateProps, Cr as e, Dn as VotePubsubReservedFields, Dt as untrackUpdatingCommunity, En as VotePubsubMessagePublicationSchema, Er as t$3, F as isLinkOfVideo, Ft as ChallengeRequestMessageSchema, G as removeBlocksFromKuboNode, Hn as CommentUpdateTableRowSchema, I as isLinkValid, J as removeNullUndefinedValues, K as removeMfsFilesSafely, Lt as ChallengeVerificationMessageSchema, M as isLinkOfAudio, Mn as CommentIpfsSchema, Mr as require_retry, N as isLinkOfImage, Nn as CommentPubsubMessageReservedFields, Nt as ChallengeMessageSchema, Ot as require_sha256, P as isLinkOfMedia, Q as retryKuboBlockPutPinAndProvidePubsubTopic, Qn as CommentEditReservedFields, Rr as PKCError, Sr as e$1, St as trackStartedCommunity, T as ipnsNameToIpnsOverPubsubTopic, Tr as r$1, Tt as untrackStartedCommunity, Un as CommentsTableRowSchema, Vt as DecryptedChallengeRequestSchema, Xn as CommentEditPubsubMessagePublicationSchema, Yt as version_default, Zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Zt as CommunityEditPublicationPubsubReservedFields, _ as genToArray, _r as n$3, an as CommentModerationsTableRowSchema, ar as AuthorReservedFields, b as getIpnsRecordInLocalKuboNode, br as t$5, c as contentContainsMarkdownImages, ct as withSortedKeys, dt as findCommunityInRegistry, er as CommentEditsTableRowSchema, et as retryKuboIpfsAddAndProvide, f as derivePublicationFromChallengeRequest, ft as findStartedCommunity, g as findMalformedUnicodeString, gr as isStringDomain, hn as CommunitySignedPropertyNames, i as calculateStringSizeSameAsIpfsAddCidV0, it as statMfsPathSafely, j as isLinkOfAnimatedImage, jt as ChallengeAnswerMessageSchema, kn as VoteTablesRowSchema, kr as t$4, l as contentContainsMarkdownVideos, lt as withSortedKeysDeep, mn as CommunityIpfsSchema, mt as findUpdatingCommunity, ni as ZodError, nn as CommentModerationPubsubMessagePublicationSchema, o as calculateUnixFsDagSizeCidV0, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, r as calculateIpfsCidV0, rn as CommentModerationReservedFields, rt as sleepUntilTimeoutOrAbort, s as contentContainsMarkdownAudio, ut as writeKuboFilesWithTimeout, v as getEquivalentCommunityAddresses, vr as t$7, wt as trackUpdatingCommunity, xr as t$6, xt as syncCommunityRegistryEntry, y as getErrorCodeFromMessage, yr as n$2, zr as messages } from "./util-Bnqvxk-6.js";
3
- import { $ as createSchemaRowParser, An as verifyChallengeAnswer, Bn as verifyCommunityEdit, Br as t$8, Cr as getThumbnailPropsOfLink, Dr as moveCommunityDbToDeletedDirectory, Dt as parseJsonWithPKCErrorIfFails, En as signCommunity, Fn as verifyCommentIpfs, Fr as isCommunityStartLocked, Gr as stringify, Hn as verifyVote, Hr as n$4, In as verifyCommentModeration, Ir as require_src, Kn as getAuthorNameFromWire, Ln as verifyCommentPubsubMessage, Lr as t$10, Mn as verifyChallengeRequest, Mr as findCommunitiesEntry, N as MAX_PAGE_SIZE_BYTES, Or as refreshCommunitiesList, Pn as verifyCommentEdit, Q as collectSchemaRowCoercions, Qn as effectiveMaxCrosspostDepth, Rn as verifyCommentUpdate, Rr as t$11, S as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, Sn as signCommentEdit, Tn as signCommentUpdateForChallengeVerification, Un as buildRuntimeAuthor, Vr as n$5, W as pLimit, Wn as cleanWireAuthor, Wr as t$9, X as coerceSchemaRowBoolean, Xr as STORAGE_KEYS, Z as coerceSchemaRowJson, Zn as crosspostChainDepthUpTo, Zr as require_lodash_merge, _ 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, kr as resolveDbPostsCidRefs, 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, 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 importSignerIntoKuboNode, wt as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, xn as signComment, xr as getDefaultCommunityDbConfig, y as LRUCache, yr as deriveDbReplies, zn as verifyCommunity, zr as r$2 } from "./rpc-local-community-BK_HGb_u.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-DgSzIxmE.js";
2
+ import { Ar as t$2, At as pTimeout, B as pubsubTopicToDhtKey, Bn as CommentUpdateSchema, Br as logger_default, Bt as DecryptedChallengeRequestPublicationSchema, C as hideClassPrivateProps, Cr as e, Dn as VotePubsubReservedFields, Dt as untrackUpdatingCommunity, En as VotePubsubMessagePublicationSchema, Er as t$3, F as isLinkOfVideo, Ft as ChallengeRequestMessageSchema, G as removeBlocksFromKuboNode, Hn as CommentUpdateTableRowSchema, I as isLinkValid, J as removeNullUndefinedValues, K as removeMfsFilesSafely, Lt as ChallengeVerificationMessageSchema, M as isLinkOfAudio, Mn as CommentIpfsSchema, Mr as require_retry, N as isLinkOfImage, Nn as CommentPubsubMessageReservedFields, Nt as ChallengeMessageSchema, Ot as require_sha256, P as isLinkOfMedia, Q as retryKuboBlockPutPinAndProvidePubsubTopic, Qn as CommentEditReservedFields, Rr as PKCError, Sr as e$1, St as trackStartedCommunity, T as ipnsNameToIpnsOverPubsubTopic, Tr as r$1, Tt as untrackStartedCommunity, Un as CommentsTableRowSchema, Vt as DecryptedChallengeRequestSchema, Xn as CommentEditPubsubMessagePublicationSchema, Yt as version_default, Zn as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Zt as CommunityEditPublicationPubsubReservedFields, _ as genToArray, _r as n$3, an as CommentModerationsTableRowSchema, ar as AuthorReservedFields, b as getIpnsRecordInLocalKuboNode, br as t$5, c as contentContainsMarkdownImages, ct as withSortedKeys, dt as findCommunityInRegistry, er as CommentEditsTableRowSchema, et as retryKuboIpfsAddAndProvide, f as derivePublicationFromChallengeRequest, ft as findStartedCommunity, g as findMalformedUnicodeString, gr as isStringDomain, hn as CommunitySignedPropertyNames, i as calculateStringSizeSameAsIpfsAddCidV0, it as statMfsPathSafely, j as isLinkOfAnimatedImage, jt as ChallengeAnswerMessageSchema, kn as VoteTablesRowSchema, kr as t$4, l as contentContainsMarkdownVideos, lt as withSortedKeysDeep, mn as CommunityIpfsSchema, mt as findUpdatingCommunity, ni as ZodError, nn as CommentModerationPubsubMessagePublicationSchema, o as calculateUnixFsDagSizeCidV0, ot as timestamp, p as doesDomainAddressHaveCapitalLetter, r as calculateIpfsCidV0, rn as CommentModerationReservedFields, rt as sleepUntilTimeoutOrAbort, s as contentContainsMarkdownAudio, ut as writeKuboFilesWithTimeout, v as getEquivalentCommunityAddresses, vr as t$7, wt as trackUpdatingCommunity, xr as t$6, xt as syncCommunityRegistryEntry, y as getErrorCodeFromMessage, yr as n$2, zr as messages } from "./util-DMr7Hj-w.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-WnhiTbxm.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-DwYGP_0d.js";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import path from "node:path";
7
7
  import os from "os";
8
- import fs, { existsSync, promises } from "node:fs";
8
+ import fs, { closeSync, existsSync, openSync, promises } from "node:fs";
9
9
  import path$1 from "path";
10
10
  import assert from "assert";
11
11
  import { Buffer as Buffer$1 } from "buffer";
@@ -1038,12 +1038,15 @@ async function updateDbInternalState(community, propsOrBuildProps) {
1038
1038
  async function updateInstanceStateWithDbState(community) {
1039
1039
  const currentDbState = await community._getDbInternalState(false);
1040
1040
  if ("updatedAt" in currentDbState) {
1041
- if (currentDbState.posts && !("pages" in currentDbState.posts)) {
1041
+ if (currentDbState.posts && !("pages" in currentDbState.posts)) if (community._dbHandler.hasCommentsAndCommentUpdatesTables()) {
1042
1042
  const dbPosts = currentDbState.posts;
1043
1043
  currentDbState.posts = resolveDbPostsCidRefs({
1044
1044
  dbPosts,
1045
1045
  dbHandler: community._dbHandler
1046
1046
  });
1047
+ } else {
1048
+ logger_default("pkc-js:local-community:updateInstanceStateWithDbState").error(`The DB of community (${community.address}) is missing its comments or commentUpdates table, most likely after an interrupted migration. Loading it without posts, start() will restore them`);
1049
+ delete currentDbState.posts;
1047
1050
  }
1048
1051
  await community.initInternalCommunityAfterFirstUpdateNoMerge(currentDbState);
1049
1052
  } else await community.initInternalCommunityBeforeFirstUpdateNoMerge(currentDbState);
@@ -1107,11 +1110,26 @@ async function setChallengesToDefaultIfNotDefined(community, log) {
1107
1110
  }
1108
1111
  }
1109
1112
  }
1113
+ function doesDbFileHoldInternalState({ dbFilePath, internalStateKey, log }) {
1114
+ if (!existsSync(dbFilePath)) return false;
1115
+ let db;
1116
+ try {
1117
+ db = new Database(dbFilePath, {
1118
+ readonly: true,
1119
+ fileMustExist: true
1120
+ });
1121
+ return db.prepare("SELECT 1 FROM keyv WHERE key = ?").get(`keyv:${internalStateKey}`) !== void 0;
1122
+ } catch (e) {
1123
+ const code = e.code;
1124
+ if (typeof code === "string" && ["SQLITE_NOTADB", "SQLITE_ERROR"].includes(code)) return false;
1125
+ log.error(`Failed to tell whether ${dbFilePath} holds an internal state, leaving the file in place`, e);
1126
+ return;
1127
+ } finally {
1128
+ db?.close();
1129
+ }
1130
+ }
1110
1131
  async function createNewLocalCommunityDb(community) {
1111
1132
  const log = logger_default("pkc-js:local-community:_createNewLocalCommunityDb");
1112
- await community.initDbHandlerIfNeeded();
1113
- await community._dbHandler.initDbIfNeeded({ fileMustExist: false });
1114
- await community._dbHandler.createOrMigrateTablesIfNeeded();
1115
1133
  await initSignerProps(community, community.signer);
1116
1134
  if (!community.pubsubTopic && !community.settings?.disablePubsubChallengeExchange) community.pubsubTopic = t$9(community.signer.address);
1117
1135
  if (typeof community.createdAt !== "number") community.createdAt = timestamp();
@@ -1151,9 +1169,53 @@ async function createNewLocalCommunityDb(community) {
1151
1169
  pagesSettings: community.settings.pages,
1152
1170
  resolved: community._pageSorts
1153
1171
  });
1154
- if (community._dbHandler.keyvHas(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY])) throw Error("Internal state exists already");
1155
- await community._dbHandler.keyvSet(STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY], community.toJSONInternalBeforeFirstUpdate());
1156
- await community._updateStartedValue();
1172
+ await community.initDbHandlerIfNeeded();
1173
+ await forgetCommunityThatFailedToBeDeleted({
1174
+ communityAddress: community.address,
1175
+ pkc: community._pkc
1176
+ });
1177
+ await community._dbHandler.initDbConfigIfNeeded();
1178
+ const dbFilePath = community._dbHandler.getDbConfig().filename;
1179
+ let createdDbFile = false;
1180
+ if (dbFilePath !== ":memory:") try {
1181
+ closeSync(openSync(dbFilePath, "wx"));
1182
+ createdDbFile = true;
1183
+ } catch (e) {
1184
+ if (e.code !== "EEXIST") throw e;
1185
+ }
1186
+ const internalStateKey = STORAGE_KEYS[STORAGE_KEYS.INTERNAL_COMMUNITY];
1187
+ try {
1188
+ await community._dbHandler.initDbIfNeeded({ fileMustExist: false });
1189
+ await community._dbHandler.createOrMigrateTablesIfNeeded();
1190
+ if (community._dbHandler.keyvHas(internalStateKey)) throw Error("Internal state exists already");
1191
+ await community._dbHandler.keyvSet(internalStateKey, community.toJSONInternalBeforeFirstUpdate());
1192
+ } catch (e) {
1193
+ try {
1194
+ community._dbHandler.destoryConnection();
1195
+ } catch (closeError) {
1196
+ log.error(`Failed to close the DB of community (${community.address}) after its creation failed`, closeError);
1197
+ }
1198
+ const isNotKnownToBeStateless = () => doesDbFileHoldInternalState({
1199
+ dbFilePath,
1200
+ internalStateKey,
1201
+ log
1202
+ }) !== false;
1203
+ if (createdDbFile) for (const filePath of [
1204
+ dbFilePath,
1205
+ `${dbFilePath}-wal`,
1206
+ `${dbFilePath}-shm`
1207
+ ]) await removeFileRetryingWhileBusy(filePath, {
1208
+ log,
1209
+ keepIf: isNotKnownToBeStateless
1210
+ }).catch((removeError) => log.error(`Failed to remove ${filePath} after the creation of community (${community.address}) failed`, removeError));
1211
+ throw e;
1212
+ }
1213
+ try {
1214
+ await community._updateStartedValue();
1215
+ } catch (e) {
1216
+ community._dbHandler.destoryConnection();
1217
+ throw e;
1218
+ }
1157
1219
  community._dbHandler.destoryConnection();
1158
1220
  community._updateIpnsPubsubPropsIfNeeded({
1159
1221
  ...community.toJSONInternalBeforeFirstUpdate(),
@@ -1363,6 +1425,7 @@ var DbHandler = class {
1363
1425
  constructor(community) {
1364
1426
  this._transactionGeneration = 0;
1365
1427
  this._publicationWriteGeneration = 0;
1428
+ this._heldStartLock = void 0;
1366
1429
  this._community = community;
1367
1430
  this._transactionDepth = 0;
1368
1431
  this._createdTables = false;
@@ -1462,8 +1525,11 @@ var DbHandler = class {
1462
1525
  destoryConnection() {
1463
1526
  const log = logger_default("pkc-js:local-community:dbHandler:destroyConnection");
1464
1527
  this._preparedStatements.clear();
1465
- if (this._db && this._db.open) {
1528
+ if (this._db && this._db.open) try {
1466
1529
  if (!this._db.readonly) this._db.exec("PRAGMA wal_checkpoint");
1530
+ } catch (e) {
1531
+ log.error("Failed to checkpoint the WAL of community", this._community.address, "before closing its DB", e);
1532
+ } finally {
1467
1533
  this._db.close();
1468
1534
  }
1469
1535
  if (this._keyv) this._keyv.disconnect();
@@ -1759,17 +1825,22 @@ var DbHandler = class {
1759
1825
  for (let i = 0; i < tables.length; i++) {
1760
1826
  const tableName = tables[i];
1761
1827
  const tableExists = this._tableExists(tableName);
1762
- if (!tableExists) {
1828
+ const tempTableName = `${tableName}_${version_default.DB_VERSION}_new`;
1829
+ if (!tableExists && needToMigrate && this._tableExists(tempTableName)) {
1830
+ log(`Table ${tableName} is missing but its migrated copy ${tempTableName} exists. Will restore the table from it`);
1831
+ this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
1832
+ } else if (!tableExists) {
1763
1833
  log(`Table ${tableName} does not exist. Will create schema`);
1764
1834
  createTableFunctions[i](tableName);
1765
1835
  } else if (tableExists && needToMigrate) {
1766
1836
  log(`Migrating table ${tableName} to new schema`);
1767
- const tempTableName = `${tableName}_${version_default.DB_VERSION}_new`;
1768
1837
  this._db.exec(`DROP TABLE IF EXISTS ${tempTableName}`);
1769
1838
  createTableFunctions[i](tempTableName);
1770
1839
  await this._copyTable(tableName, tempTableName, currentDbVersion);
1771
- this._db.exec(`DROP TABLE ${tableName}`);
1772
- this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
1840
+ this._db.transaction(() => {
1841
+ this._db.exec(`DROP TABLE ${tableName}`);
1842
+ this._db.exec(`ALTER TABLE ${tempTableName} RENAME TO ${tableName}`);
1843
+ })();
1773
1844
  }
1774
1845
  }
1775
1846
  this._createCommentsIndexes();
@@ -1811,7 +1882,14 @@ var DbHandler = class {
1811
1882
  this._columnNamesByTable = {};
1812
1883
  this._preparedStatements.clear();
1813
1884
  if (needToMigrate) log(`Created/migrated the tables to the latest (${newDbVersion}) version and saved to path`, this._dbConfig.filename);
1814
- if (backupDbPath) await fs$1.promises.rm(backupDbPath);
1885
+ if (backupDbPath) try {
1886
+ await removeFileRetryingWhileBusy(backupDbPath, { log });
1887
+ } catch (e) {
1888
+ log.error(`Failed to remove the pre-migration backup ${backupDbPath}. It is no longer needed and can be deleted`, e);
1889
+ }
1890
+ }
1891
+ hasCommentsAndCommentUpdatesTables() {
1892
+ return this._tableExists(TABLES.COMMENTS) && this._tableExists(TABLES.COMMENT_UPDATES);
1815
1893
  }
1816
1894
  _tableExists(tableName) {
1817
1895
  return !!this._db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?").get(tableName);
@@ -3797,6 +3875,10 @@ var DbHandler = class {
3797
3875
  const sourceDb = new Database(oldPathString, { fileMustExist: true });
3798
3876
  await sourceDb.backup(newPathString);
3799
3877
  sourceDb.close();
3878
+ await forgetCommunityThatFailedToBeDeleted({
3879
+ communityAddress: newDbName,
3880
+ pkc: this._community._pkc
3881
+ });
3800
3882
  if (os.type() === "Windows_NT") await deleteOldCommunityInWindows(oldPathString, this._community._pkc);
3801
3883
  else await fs$1.promises.rm(oldPathString, { force: true });
3802
3884
  }
@@ -3810,15 +3892,23 @@ var DbHandler = class {
3810
3892
  };
3811
3893
  log(`Changed db path from (${oldPathString}) to (${newPathString})`);
3812
3894
  }
3813
- async lockCommunityStart(communityAddress = this._community.address) {
3895
+ async lockCommunityStart({ onCompromised }) {
3814
3896
  const log = logger_default("pkc-js:local-community:db-handler:lock:start");
3897
+ const communityAddress = this._community.address;
3815
3898
  const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3816
3899
  const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3900
+ const startLock = {};
3817
3901
  try {
3818
3902
  await import_src.default.lock(communityDbPath, {
3819
3903
  lockfilePath,
3820
- onCompromised: () => {}
3904
+ onCompromised: (error) => {
3905
+ if (this._heldStartLock !== startLock) return;
3906
+ this._heldStartLock = void 0;
3907
+ log.error(`Lost the start lock of community (${communityAddress}), taken over or removed`, error);
3908
+ onCompromised(error);
3909
+ }
3821
3910
  });
3911
+ this._heldStartLock = startLock;
3822
3912
  log(`Locked the start of community (${communityAddress}) successfully`);
3823
3913
  } catch (e) {
3824
3914
  if (e instanceof Error && e.message === "Lock file is already being held") throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", {
@@ -3834,6 +3924,7 @@ var DbHandler = class {
3834
3924
  async unlockCommunityStart(communityAddress = this._community.address) {
3835
3925
  const log = logger_default("pkc-js:local-community:db-handler:unlock:start");
3836
3926
  log.trace(`Attempting to unlock the start of community (${communityAddress})`);
3927
+ this._heldStartLock = void 0;
3837
3928
  const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
3838
3929
  const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
3839
3930
  if (!fs$1.existsSync(lockfilePath) || !fs$1.existsSync(communityDbPath)) return;
@@ -6589,7 +6680,7 @@ async function publishLoop(community, syncIntervalMs) {
6589
6680
  const log = logger_default("pkc-js:local-community:_publishLoop");
6590
6681
  let syncFailedSinceStop = false;
6591
6682
  const shouldStopPublishLoop = () => {
6592
- return community.state !== "started" || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
6683
+ return community.state !== "started" || community._startLockLost || community._stopHasBeenCalled && (community._pendingEditProps.length === 0 || syncFailedSinceStop);
6593
6684
  };
6594
6685
  const waitUntilNextSync = async ({ lastSyncFailed }) => {
6595
6686
  const doneWithLoopTime = Date.now();
@@ -6704,6 +6795,9 @@ async function startCommunity({ community, releaseMark }) {
6704
6795
  publicKey: community.publicKey,
6705
6796
  name: community.name
6706
6797
  }) || findProcessStartedCommunity(community)) throw new PKCError("ERR_COMMUNITY_ALREADY_STARTED", { address: community.address });
6798
+ community._startLockLost = false;
6799
+ let startLockLostDuringStart;
6800
+ let startFinished = false;
6707
6801
  try {
6708
6802
  await initBeforeStarting(community);
6709
6803
  if (community.anchor && !getPersistedAnchorRecordBytes(community)) throw new PKCError("ERR_DELEGATED_COMMUNITY_HAS_NO_ANCHOR_RECORD", {
@@ -6716,7 +6810,15 @@ async function startCommunity({ community, releaseMark }) {
6716
6810
  pkc: community._pkc,
6717
6811
  communityAddress: community.address
6718
6812
  });
6719
- await community._dbHandler.lockCommunityStart();
6813
+ await community._dbHandler.lockCommunityStart({ onCompromised: (error) => {
6814
+ community._startLockLost = true;
6815
+ const lostLockError = new PKCError("ERR_COMMUNITY_START_LOCK_COMPROMISED", {
6816
+ communityAddress: community.address,
6817
+ error
6818
+ });
6819
+ if (startFinished) stopAfterLosingStartLock(community, lostLockError);
6820
+ else startLockLostDuringStart = lostLockError;
6821
+ } });
6720
6822
  community._setState("started");
6721
6823
  await community._updateStartedValue();
6722
6824
  trackStartedCommunity(community._pkc, community);
@@ -6739,11 +6841,14 @@ async function startCommunity({ community, releaseMark }) {
6739
6841
  community._setStartedStateWithEmission("publishing-ipns");
6740
6842
  await community._repinCommentsIPFSIfNeeded();
6741
6843
  await repinCommentUpdateIfNeeded(community);
6844
+ if (startLockLostDuringStart) throw startLockLostDuringStart;
6742
6845
  await community._listenToIncomingRequests();
6743
6846
  await emitChallengeSettingsValidationErrors(community, log);
6744
6847
  community._pageSorts = void 0;
6745
6848
  community._pageSortFactories = void 0;
6746
6849
  await syncPageSortsWithRegistry(community);
6850
+ if (startLockLostDuringStart) throw startLockLostDuringStart;
6851
+ startFinished = true;
6747
6852
  } catch (e) {
6748
6853
  releaseMark();
6749
6854
  await community.stop();
@@ -6759,6 +6864,12 @@ async function startCommunity({ community, releaseMark }) {
6759
6864
  community.emit("error", err);
6760
6865
  });
6761
6866
  }
6867
+ function stopAfterLosingStartLock(community, error) {
6868
+ const log = logger_default("pkc-js:local-community:stopAfterLosingStartLock");
6869
+ if (community.state !== "started") return;
6870
+ if (!community._stopHasBeenCalled) community.stop().catch((e) => log.error(`Failed to stop community (${community.address}) after losing its start lock`, e));
6871
+ community.emit("error", error);
6872
+ }
6762
6873
  async function initMirroringStartedOrUpdatingCommunity(community, startedCommunity) {
6763
6874
  const updatingStateChangeListener = (newState) => {
6764
6875
  community._setUpdatingStateWithEventEmissionIfNewState(newState);
@@ -6927,20 +7038,23 @@ async function stopCommunity(community) {
6927
7038
  }
6928
7039
  community._publishLoopPromise = void 0;
6929
7040
  }
6930
- try {
6931
- await unpinStaleCids(community, { bypassGracePeriod: true });
6932
- } catch (e) {
6933
- log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
6934
- }
6935
- try {
6936
- await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
6937
- } catch (e) {
6938
- log.error("Failed to update db internal state before stopping", e);
6939
- }
6940
- try {
6941
- await community._dbHandler.unlockCommunityStart();
6942
- } catch (e) {
6943
- log.error(`Failed to unlock start lock on community (${community.address})`, e);
7041
+ if (community._startLockLost) log(`Community (${community.address}) lost its start lock, stopping without writing its state, unpinning or unlocking`);
7042
+ else {
7043
+ try {
7044
+ await unpinStaleCids(community, { bypassGracePeriod: true });
7045
+ } catch (e) {
7046
+ log.error("Failed to unpin stale cids and remove mfs paths before stopping", e);
7047
+ }
7048
+ try {
7049
+ await updateDbInternalState(community, () => community.updateCid ? community.toJSONInternalAfterFirstUpdate() : community.toJSONInternalBeforeFirstUpdate());
7050
+ } catch (e) {
7051
+ log.error("Failed to update db internal state before stopping", e);
7052
+ }
7053
+ try {
7054
+ await community._dbHandler.unlockCommunityStart();
7055
+ } catch (e) {
7056
+ log.error(`Failed to unlock start lock on community (${community.address})`, e);
7057
+ }
6944
7058
  }
6945
7059
  const kuboRpcClient = community._clientsManager.getDefaultKuboRpcClient();
6946
7060
  community._setStartedStateWithEmission("stopped");
@@ -7159,24 +7273,89 @@ function deriveNameAndAddressEdit(community, editOptions) {
7159
7273
  function listRenamedCommunityNow(community) {
7160
7274
  refreshCommunitiesList(community._pkc);
7161
7275
  }
7162
- async function restoreCommunityAfterFailedRename({ community, oldAddress, newAddress, postUpdatesFolderMoved, log }) {
7276
+ async function movePostUpdatesFolderBack({ community, oldAddress, newAddress, log }) {
7277
+ try {
7278
+ await movePostUpdatesFolderToNewAddress(community, newAddress, oldAddress);
7279
+ return;
7280
+ } catch (moveBackError) {
7281
+ log.error(`Failed to move the postUpdates folder of community (${oldAddress}) back from ${newAddress}`, moveBackError);
7282
+ return moveBackError;
7283
+ }
7284
+ }
7285
+ function emitRenameUndoError({ community, error, log }) {
7286
+ try {
7287
+ community.emit("error", error);
7288
+ } catch (emitError) {
7289
+ log.error(`Nothing listens for the errors of community (${community.address}), the error it could not report was`, error);
7290
+ }
7291
+ }
7292
+ async function restartCommunityAfterFailedRename({ community, oldAddress, newAddress, log }) {
7163
7293
  try {
7164
- if (postUpdatesFolderMoved) await movePostUpdatesFolderToNewAddress(community, newAddress, oldAddress);
7165
7294
  await community.start();
7166
- } catch (restoreError) {
7167
- log.error(`Failed to restore community (${oldAddress}) after its rename to ${newAddress} failed`, restoreError);
7168
- community.emit("error", restoreError);
7295
+ } catch (restartError) {
7296
+ log.error(`Failed to restart community (${oldAddress}) after its rename to ${newAddress} failed`, restartError);
7297
+ emitRenameUndoError({
7298
+ community,
7299
+ error: restartError,
7300
+ log
7301
+ });
7169
7302
  }
7170
7303
  }
7171
7304
  async function removePartialDbCopy({ community, oldAddress, newAddress, log }) {
7172
7305
  const communitiesPath = path.join(community._pkc.dataPath, "communities");
7173
- if (!fs.existsSync(path.join(communitiesPath, oldAddress))) return;
7306
+ const partialDbCopyPath = path.join(communitiesPath, newAddress);
7307
+ if (!fs.existsSync(path.join(communitiesPath, oldAddress))) return {
7308
+ removed: false,
7309
+ path: partialDbCopyPath
7310
+ };
7174
7311
  try {
7175
- await fs.promises.rm(path.join(communitiesPath, newAddress), { force: true });
7312
+ await removeFileRetryingWhileBusy(partialDbCopyPath, { log });
7313
+ return { removed: true };
7176
7314
  } catch (e) {
7177
- log.error(`Failed to remove the partial DB copy of community (${oldAddress}) at ${newAddress}`, e);
7315
+ log.error(`Failed to remove the partial DB copy of community (${oldAddress}) at ${partialDbCopyPath}`, e);
7316
+ return {
7317
+ removed: false,
7318
+ path: partialDbCopyPath,
7319
+ error: e
7320
+ };
7178
7321
  }
7179
7322
  }
7323
+ async function undoRenameAfterDbRenameFailed({ community, oldAddress, newAddress, dbRenameError, log }) {
7324
+ const communitiesPath = path.join(community._pkc.dataPath, "communities");
7325
+ const partialDbCopy = await removePartialDbCopy({
7326
+ community,
7327
+ oldAddress,
7328
+ newAddress,
7329
+ log
7330
+ });
7331
+ const moveBackError = await movePostUpdatesFolderBack({
7332
+ community,
7333
+ oldAddress,
7334
+ newAddress,
7335
+ log
7336
+ });
7337
+ const renameError = dbRenameError;
7338
+ return {
7339
+ error: new PKCError("ERR_FAILED_TO_RENAME_COMMUNITY_DB", {
7340
+ oldAddress,
7341
+ newAddress,
7342
+ oldDbPath: path.join(communitiesPath, oldAddress),
7343
+ newDbPath: path.join(communitiesPath, newAddress),
7344
+ error: dbRenameError,
7345
+ errorMessage: renameError?.message,
7346
+ errorName: renameError?.name,
7347
+ errorCode: renameError?.code,
7348
+ partialDbCopyRemoved: partialDbCopy.removed,
7349
+ ...partialDbCopy.removed ? {} : {
7350
+ partialDbCopyPath: partialDbCopy.path,
7351
+ partialDbCopyRemovalError: partialDbCopy.error
7352
+ },
7353
+ postUpdatesFolderMovedBack: moveBackError === void 0,
7354
+ ...moveBackError ? { postUpdatesFolderMoveBackError: moveBackError } : {}
7355
+ }),
7356
+ moveBackError
7357
+ };
7358
+ }
7180
7359
  async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEdit) {
7181
7360
  const log = logger_default("pkc-js:local-community:start:editPropsOnStartedCommunity");
7182
7361
  const oldAddress = t$9(community.address);
@@ -7189,11 +7368,10 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7189
7368
  try {
7190
7369
  await movePostUpdatesFolderToNewAddress(community, oldAddress, newAddress);
7191
7370
  } catch (e) {
7192
- await restoreCommunityAfterFailedRename({
7371
+ await restartCommunityAfterFailedRename({
7193
7372
  community,
7194
7373
  oldAddress,
7195
7374
  newAddress,
7196
- postUpdatesFolderMoved: false,
7197
7375
  log
7198
7376
  });
7199
7377
  throw e;
@@ -7201,20 +7379,25 @@ async function editPropsOnStartedCommunity(community, parsedEditOptions, pagesEd
7201
7379
  try {
7202
7380
  await community._dbHandler.changeDbFilename(oldAddress, newAddress);
7203
7381
  } catch (e) {
7204
- await removePartialDbCopy({
7382
+ const { error, moveBackError } = await undoRenameAfterDbRenameFailed({
7205
7383
  community,
7206
7384
  oldAddress,
7207
7385
  newAddress,
7386
+ dbRenameError: e,
7387
+ log
7388
+ });
7389
+ if (moveBackError) emitRenameUndoError({
7390
+ community,
7391
+ error: moveBackError,
7208
7392
  log
7209
7393
  });
7210
- await restoreCommunityAfterFailedRename({
7394
+ else await restartCommunityAfterFailedRename({
7211
7395
  community,
7212
7396
  oldAddress,
7213
7397
  newAddress,
7214
- postUpdatesFolderMoved: true,
7215
7398
  log
7216
7399
  });
7217
- throw e;
7400
+ throw error;
7218
7401
  }
7219
7402
  listRenamedCommunityNow(community);
7220
7403
  community.setAddress(newAddress);
@@ -7269,9 +7452,20 @@ async function editPropsOnNotStartedCommunity(community, parsedEditOptions, page
7269
7452
  await validateNewAddressBeforeEditing(community, parsedEditOptions.address, log);
7270
7453
  log(`Attempting to edit community.address from ${oldAddress} to ${parsedEditOptions.address}`);
7271
7454
  log("will rename the community", community.address, "db in edit() because the community is not being ran anywhere else");
7272
- await movePostUpdatesFolderToNewAddress(community, community.address, parsedEditOptions.address);
7273
- community._dbHandler.destoryConnection();
7274
- await community._dbHandler.changeDbFilename(community.address, parsedEditOptions.address);
7455
+ const newAddress = parsedEditOptions.address;
7456
+ await movePostUpdatesFolderToNewAddress(community, oldAddress, newAddress);
7457
+ await community._dbHandler.destoryConnection();
7458
+ try {
7459
+ await community._dbHandler.changeDbFilename(oldAddress, newAddress);
7460
+ } catch (e) {
7461
+ throw (await undoRenameAfterDbRenameFailed({
7462
+ community,
7463
+ oldAddress,
7464
+ newAddress,
7465
+ dbRenameError: e,
7466
+ log
7467
+ })).error;
7468
+ }
7275
7469
  listRenamedCommunityNow(community);
7276
7470
  await community._dbHandler.initDbIfNeeded();
7277
7471
  community.setAddress(parsedEditOptions.address);
@@ -7548,6 +7742,7 @@ var LocalCommunity = class extends RpcLocalCommunity {
7548
7742
  this._pageSorts = void 0;
7549
7743
  this._pageSortFactories = void 0;
7550
7744
  this._reportedChallengeLoadFailures = void 0;
7745
+ this._startLockLost = false;
7551
7746
  this._publishLoopPromise = void 0;
7552
7747
  this._updateLoopPromise = void 0;
7553
7748
  this._startOrUpdateInFlight = void 0;
@@ -1,2 +1,2 @@
1
- import { n as createNewLocalCommunityDb, r as updateInstancePropsWithStartedCommunityOrDb, t as LocalCommunity } from "./local-community-BY1ouP1-.js";
1
+ import { n as createNewLocalCommunityDb, r as updateInstancePropsWithStartedCommunityOrDb, t as LocalCommunity } from "./local-community-5X7bvOoN.js";
2
2
  export { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb };