@bitsocial/bitsocial-react-hooks 0.2.2 → 0.2.3

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 (117) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +2 -0
  3. package/dist/hooks/accounts/accounts.d.ts.map +1 -1
  4. package/dist/hooks/accounts/accounts.js +35 -10
  5. package/dist/hooks/accounts/accounts.js.map +1 -1
  6. package/dist/hooks/actions/actions.d.ts.map +1 -1
  7. package/dist/hooks/actions/actions.js +166 -93
  8. package/dist/hooks/actions/actions.js.map +1 -1
  9. package/dist/hooks/authors/author-avatars.d.ts +2 -2
  10. package/dist/hooks/authors/author-avatars.d.ts.map +1 -1
  11. package/dist/hooks/authors/author-avatars.js +48 -20
  12. package/dist/hooks/authors/author-avatars.js.map +1 -1
  13. package/dist/hooks/authors/authors.d.ts.map +1 -1
  14. package/dist/hooks/authors/authors.js +68 -22
  15. package/dist/hooks/authors/authors.js.map +1 -1
  16. package/dist/hooks/comments.d.ts.map +1 -1
  17. package/dist/hooks/comments.js +54 -3
  18. package/dist/hooks/comments.js.map +1 -1
  19. package/dist/hooks/communities.d.ts.map +1 -1
  20. package/dist/hooks/communities.js +41 -12
  21. package/dist/hooks/communities.js.map +1 -1
  22. package/dist/hooks/feeds/feeds.d.ts.map +1 -1
  23. package/dist/hooks/feeds/feeds.js +47 -11
  24. package/dist/hooks/feeds/feeds.js.map +1 -1
  25. package/dist/hooks/pkc-rpc.d.ts.map +1 -1
  26. package/dist/hooks/pkc-rpc.js +33 -20
  27. package/dist/hooks/pkc-rpc.js.map +1 -1
  28. package/dist/hooks/replies.d.ts.map +1 -1
  29. package/dist/hooks/replies.js +30 -4
  30. package/dist/hooks/replies.js.map +1 -1
  31. package/dist/index.d.ts +6 -4
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +4 -2
  34. package/dist/index.js.map +1 -1
  35. package/dist/lib/debug-utils.d.ts +4 -4
  36. package/dist/lib/debug-utils.d.ts.map +1 -1
  37. package/dist/lib/debug-utils.js +56 -11
  38. package/dist/lib/debug-utils.js.map +1 -1
  39. package/dist/lib/localforage-lru/localforage-lru.d.ts +1 -0
  40. package/dist/lib/localforage-lru/localforage-lru.d.ts.map +1 -1
  41. package/dist/lib/localforage-lru/localforage-lru.js +48 -10
  42. package/dist/lib/localforage-lru/localforage-lru.js.map +1 -1
  43. package/dist/lib/page-sorts.d.ts +6 -0
  44. package/dist/lib/page-sorts.d.ts.map +1 -1
  45. package/dist/lib/page-sorts.js +45 -9
  46. package/dist/lib/page-sorts.js.map +1 -1
  47. package/dist/lib/pkc-js/pkc-js-mock-content.d.ts.map +1 -1
  48. package/dist/lib/pkc-js/pkc-js-mock-content.js +5 -1
  49. package/dist/lib/pkc-js/pkc-js-mock-content.js.map +1 -1
  50. package/dist/lib/utils/utils.d.ts.map +1 -1
  51. package/dist/lib/utils/utils.js +24 -16
  52. package/dist/lib/utils/utils.js.map +1 -1
  53. package/dist/lib/validator.d.ts +1 -1
  54. package/dist/lib/validator.d.ts.map +1 -1
  55. package/dist/lib/validator.js +7 -1
  56. package/dist/lib/validator.js.map +1 -1
  57. package/dist/stores/accounts/account-generator.d.ts +1 -0
  58. package/dist/stores/accounts/account-generator.d.ts.map +1 -1
  59. package/dist/stores/accounts/account-generator.js +12 -4
  60. package/dist/stores/accounts/account-generator.js.map +1 -1
  61. package/dist/stores/accounts/accounts-actions-internal.d.ts.map +1 -1
  62. package/dist/stores/accounts/accounts-actions-internal.js +24 -6
  63. package/dist/stores/accounts/accounts-actions-internal.js.map +1 -1
  64. package/dist/stores/accounts/accounts-actions.d.ts.map +1 -1
  65. package/dist/stores/accounts/accounts-actions.js +339 -98
  66. package/dist/stores/accounts/accounts-actions.js.map +1 -1
  67. package/dist/stores/accounts/accounts-database.d.ts +1 -0
  68. package/dist/stores/accounts/accounts-database.d.ts.map +1 -1
  69. package/dist/stores/accounts/accounts-database.js +82 -15
  70. package/dist/stores/accounts/accounts-database.js.map +1 -1
  71. package/dist/stores/accounts/accounts-store.d.ts +1 -1
  72. package/dist/stores/accounts/accounts-store.d.ts.map +1 -1
  73. package/dist/stores/accounts/accounts-store.js +1 -1
  74. package/dist/stores/accounts/accounts-store.js.map +1 -1
  75. package/dist/stores/accounts/utils.d.ts +5 -1
  76. package/dist/stores/accounts/utils.d.ts.map +1 -1
  77. package/dist/stores/accounts/utils.js +58 -0
  78. package/dist/stores/accounts/utils.js.map +1 -1
  79. package/dist/stores/authors-comments/authors-comments-store.d.ts.map +1 -1
  80. package/dist/stores/authors-comments/authors-comments-store.js +39 -12
  81. package/dist/stores/authors-comments/authors-comments-store.js.map +1 -1
  82. package/dist/stores/comments/comments-store.d.ts +2 -0
  83. package/dist/stores/comments/comments-store.d.ts.map +1 -1
  84. package/dist/stores/comments/comments-store.js +170 -21
  85. package/dist/stores/comments/comments-store.js.map +1 -1
  86. package/dist/stores/communities/communities-store.d.ts.map +1 -1
  87. package/dist/stores/communities/communities-store.js +27 -7
  88. package/dist/stores/communities/communities-store.js.map +1 -1
  89. package/dist/stores/communities-pages/communities-pages-store.d.ts.map +1 -1
  90. package/dist/stores/communities-pages/communities-pages-store.js +60 -8
  91. package/dist/stores/communities-pages/communities-pages-store.js.map +1 -1
  92. package/dist/stores/feeds/feed-sorter.d.ts +5 -2
  93. package/dist/stores/feeds/feed-sorter.d.ts.map +1 -1
  94. package/dist/stores/feeds/feed-sorter.js +15 -4
  95. package/dist/stores/feeds/feed-sorter.js.map +1 -1
  96. package/dist/stores/feeds/feeds-store.d.ts +3 -0
  97. package/dist/stores/feeds/feeds-store.d.ts.map +1 -1
  98. package/dist/stores/feeds/feeds-store.js +36 -26
  99. package/dist/stores/feeds/feeds-store.js.map +1 -1
  100. package/dist/stores/feeds/utils.d.ts +16 -0
  101. package/dist/stores/feeds/utils.d.ts.map +1 -1
  102. package/dist/stores/feeds/utils.js +82 -26
  103. package/dist/stores/feeds/utils.js.map +1 -1
  104. package/dist/stores/replies/replies-store.d.ts.map +1 -1
  105. package/dist/stores/replies/replies-store.js +32 -6
  106. package/dist/stores/replies/replies-store.js.map +1 -1
  107. package/dist/stores/replies/utils.d.ts +3 -2
  108. package/dist/stores/replies/utils.d.ts.map +1 -1
  109. package/dist/stores/replies/utils.js +38 -5
  110. package/dist/stores/replies/utils.js.map +1 -1
  111. package/dist/stores/replies-pages/replies-pages-store.d.ts.map +1 -1
  112. package/dist/stores/replies-pages/replies-pages-store.js +68 -13
  113. package/dist/stores/replies-pages/replies-pages-store.js.map +1 -1
  114. package/dist/types.d.ts +11 -2
  115. package/dist/types.d.ts.map +1 -1
  116. package/dist/types.js.map +1 -1
  117. package/package.json +2 -2
@@ -30,12 +30,21 @@ import assert from "../../lib/assert.js";
30
30
  const log = Logger("bitsocial-react-hooks:accounts:stores");
31
31
  import * as accountsActionsInternal from "./accounts-actions-internal.js";
32
32
  import { backfillPublicationCommunityAddress, createPkcCommunity, createPkcCommunityEdit, getPkcCommunityAddresses, normalizeCommunityEditOptionsForPkc, normalizePublicationOptionsForStore, normalizePublicationOptionsForPkc, withPublishChallengeAnswersCompat, } from "../../lib/pkc-compat.js";
33
- import { getAccountCommentsIndex, getAccountCommunities, getCommentCidsToAccountsComments, COMMENT_MODERATION_AUTHOR_SUMMARY_KEY, getAccountEditPropertySummary, fetchCommentLinkDimensions, getAccountCommentDepth, addShortAddressesToAccountComment, sanitizeAccountCommentForState, sanitizeStoredAccountComment, getFreshestLoadedComment, getInitAccountCommentsToUpdate, } from "./utils.js";
33
+ import { getAccountCommentsIndex, getAccountCommunities, getCommentCidsToAccountsComments, COMMENT_MODERATION_AUTHOR_SUMMARY_KEY, getAccountEditPropertySummary, fetchCommentLinkDimensions, getAccountCommentDepth, getAccountCommentPostCid, addShortAddressesToAccountComment, sanitizeAccountCommentForState, sanitizeStoredAccountComment, getFreshestLoadedComment, getInitAccountCommentsToUpdate, } from "./utils.js";
34
34
  import isEqual from "../../lib/is-equal.js";
35
35
  import { v4 as uuid } from "uuid";
36
36
  import utils from "../../lib/utils/index.js";
37
37
  import { addOptimisticVoteMetadata } from "../../lib/utils/optimistic-vote-counts.js";
38
38
  import { applyCommunityWordfilters } from "../../lib/wordfilters.js";
39
+ import { doesAddressMatchCommunityRef } from "../../lib/community-ref.js";
40
+ const getAccountCommentByCid = (commentCid) => {
41
+ var _a;
42
+ const { commentCidsToAccountsComments, accountsComments } = accountsStore.getState();
43
+ const accountCommentInfo = commentCid ? commentCidsToAccountsComments[commentCid] : undefined;
44
+ return accountCommentInfo
45
+ ? (_a = accountsComments[accountCommentInfo.accountId]) === null || _a === void 0 ? void 0 : _a[accountCommentInfo.accountCommentIndex]
46
+ : undefined;
47
+ };
39
48
  const PUBLICATION_COMMUNITY_LOAD_TIMEOUT_MS = 30000;
40
49
  const COMMENT_AUTHOR_LOAD_TIMEOUT_MS = 10000;
41
50
  const communityHasPublicationConfig = (community) => community &&
@@ -208,6 +217,20 @@ const createPublishSession = (accountId, index) => {
208
217
  });
209
218
  return sessionId;
210
219
  };
220
+ // A pending comment takes the next row of its account's live comment list, so the first saves of
221
+ // an account's pending comments run one at a time: two overlapping publishComment calls that read
222
+ // the length before either saved its row would get the same index and overwrite each other.
223
+ const accountCommentAppendQueues = new Map();
224
+ const queueAccountCommentAppend = (accountId, append) => {
225
+ const previousAppend = accountCommentAppendQueues.get(accountId) || Promise.resolve();
226
+ const queuedAppend = previousAppend.catch(() => { }).then(append);
227
+ accountCommentAppendQueues.set(accountId, queuedAppend);
228
+ return queuedAppend.finally(() => {
229
+ if (accountCommentAppendQueues.get(accountId) === queuedAppend) {
230
+ accountCommentAppendQueues.delete(accountId);
231
+ }
232
+ });
233
+ };
211
234
  const updatePublishSessionComment = (sessionId, comment) => {
212
235
  const session = activePublishSessions.get(sessionId);
213
236
  if (!session) {
@@ -231,6 +254,30 @@ const abandonAndStopPublishSession = (accountId, index) => {
231
254
  }
232
255
  activePublishSessions.delete(session.sessionId);
233
256
  };
257
+ // deleteAccount only abandons the publish sessions that exist when it starts, so a publication that
258
+ // reaches its first save later checks that its account is still there
259
+ const deletingAccountIds = new Set();
260
+ const isAccountDeleted = (accountId) => { var _a; return deletingAccountIds.has(accountId) || !((_a = accountsStore.getState().accounts) === null || _a === void 0 ? void 0 : _a[accountId]); };
261
+ // a deleted account's pending comments and votes would otherwise keep publishing and write their
262
+ // results for an account that no longer exists
263
+ const abandonAccountPublishSessions = (accountId) => {
264
+ for (const session of activePublishSessions.values()) {
265
+ if (session.accountId === accountId) {
266
+ abandonAndStopPublishSession(accountId, session.currentIndex);
267
+ }
268
+ }
269
+ const votePublishSessionKeyPrefix = getVotePublishSessionKey(accountId, "");
270
+ for (const [key, session] of activeVotePublishSessions) {
271
+ if (!key.startsWith(votePublishSessionKeyPrefix))
272
+ continue;
273
+ activeVotePublishSessions.delete(key);
274
+ for (const publication of session.publications) {
275
+ Promise.resolve()
276
+ .then(() => { var _a; return (_a = publication === null || publication === void 0 ? void 0 : publication.stop) === null || _a === void 0 ? void 0 : _a.call(publication); })
277
+ .catch((error) => log.error("vote.stop() error during account delete", { accountId, error }));
278
+ }
279
+ }
280
+ };
234
281
  const startVotePublishSession = (accountId, commentCid, previousAccountVote) => {
235
282
  const key = getVotePublishSessionKey(accountId, commentCid);
236
283
  const session = activeVotePublishSessions.get(key);
@@ -293,6 +340,15 @@ const shiftPublishSessionIndicesAfterDelete = (accountId, deletedIndex) => {
293
340
  }
294
341
  }
295
342
  };
343
+ // the sessions shifted by a deletion are the ones now at or after the deleted index
344
+ const notifyShiftedPublishSessions = (accountId, deletedIndex) => {
345
+ var _a;
346
+ for (const session of activePublishSessions.values()) {
347
+ if (session.accountId === accountId && session.currentIndex >= deletedIndex) {
348
+ (_a = session.onIndexChange) === null || _a === void 0 ? void 0 : _a.call(session, session.currentIndex);
349
+ }
350
+ }
351
+ };
296
352
  const cleanupPublishSessionOnTerminal = (sessionId) => {
297
353
  activePublishSessions.delete(sessionId);
298
354
  abandonedPublishSessionIds.delete(sessionId);
@@ -475,7 +531,8 @@ export const createAccount = (accountName) => __awaiter(void 0, void 0, void 0,
475
531
  log("accountsActions.createAccount", { accountName, account: newAccount });
476
532
  });
477
533
  export const deleteAccount = (accountName) => __awaiter(void 0, void 0, void 0, function* () {
478
- const { accounts, accountNamesToAccountIds, activeAccountId, accountsComments, accountsCommentsIndexes, accountsVotes, accountsEdits, accountsEditsSummaries, accountsEditsLoaded, } = accountsStore.getState();
534
+ var _a;
535
+ const { accounts, accountNamesToAccountIds, activeAccountId } = accountsStore.getState();
479
536
  assert(accounts && accountNamesToAccountIds && activeAccountId, `can't use accountsStore.accountActions before initialized`);
480
537
  let account = accounts[activeAccountId];
481
538
  if (accountName) {
@@ -483,40 +540,46 @@ export const deleteAccount = (accountName) => __awaiter(void 0, void 0, void 0,
483
540
  account = accounts[accountId];
484
541
  }
485
542
  assert(account === null || account === void 0 ? void 0 : account.id, `accountsActions.deleteAccount account.id '${account === null || account === void 0 ? void 0 : account.id}' doesn't exist, activeAccountId '${activeAccountId}' accountName '${accountName}'`);
486
- yield accountsDatabase.removeAccount(account);
487
- const newAccounts = Object.assign({}, accounts);
488
- delete newAccounts[account.id];
489
- const [newAccountIds, newActiveAccountId, newAccountNamesToAccountIds] = yield Promise.all([
490
- accountsDatabase.accountsMetadataDatabase.getItem("accountIds"),
491
- accountsDatabase.accountsMetadataDatabase.getItem("activeAccountId"),
492
- accountsDatabase.accountsMetadataDatabase.getItem("accountNamesToAccountIds"),
493
- ]);
494
- const newAccountsComments = Object.assign({}, accountsComments);
495
- delete newAccountsComments[account.id];
496
- const newAccountsCommentsIndexes = Object.assign({}, accountsCommentsIndexes);
497
- delete newAccountsCommentsIndexes[account.id];
498
- const newCommentCidsToAccountsComments = getCommentCidsToAccountsComments(newAccountsComments);
499
- const newAccountsVotes = Object.assign({}, accountsVotes);
500
- delete newAccountsVotes[account.id];
501
- const newAccountsEdits = Object.assign({}, accountsEdits);
502
- delete newAccountsEdits[account.id];
503
- const newAccountsEditsSummaries = Object.assign({}, accountsEditsSummaries);
504
- delete newAccountsEditsSummaries[account.id];
505
- const newAccountsEditsLoaded = Object.assign({}, accountsEditsLoaded);
506
- delete newAccountsEditsLoaded[account.id];
507
- accountsStore.setState({
508
- accounts: newAccounts,
509
- accountIds: newAccountIds,
510
- activeAccountId: newActiveAccountId,
511
- accountNamesToAccountIds: newAccountNamesToAccountIds,
512
- accountsComments: newAccountsComments,
513
- accountsCommentsIndexes: newAccountsCommentsIndexes,
514
- commentCidsToAccountsComments: newCommentCidsToAccountsComments,
515
- accountsVotes: newAccountsVotes,
516
- accountsEdits: newAccountsEdits,
517
- accountsEditsSummaries: newAccountsEditsSummaries,
518
- accountsEditsLoaded: newAccountsEditsLoaded,
519
- });
543
+ // until the store drops the account, a publication that has not started yet must not start
544
+ deletingAccountIds.add(account.id);
545
+ try {
546
+ abandonAccountPublishSessions(account.id);
547
+ // a pending comment already saving its first row finishes before the account is cleared
548
+ yield ((_a = accountCommentAppendQueues.get(account.id)) === null || _a === void 0 ? void 0 : _a.catch(() => { }));
549
+ yield accountsDatabase.removeAccount(account);
550
+ const [newAccountIds, newActiveAccountId, newAccountNamesToAccountIds] = yield Promise.all([
551
+ accountsDatabase.accountsMetadataDatabase.getItem("accountIds"),
552
+ accountsDatabase.accountsMetadataDatabase.getItem("activeAccountId"),
553
+ accountsDatabase.accountsMetadataDatabase.getItem("accountNamesToAccountIds"),
554
+ ]);
555
+ // from the live state: other accounts may have saved comments, votes, edits or replies during
556
+ // the awaits above
557
+ accountsStore.setState((state) => {
558
+ const withoutAccount = (map) => {
559
+ const newMap = Object.assign({}, map);
560
+ delete newMap[account.id];
561
+ return newMap;
562
+ };
563
+ const newAccountsComments = withoutAccount(state.accountsComments);
564
+ return {
565
+ accounts: withoutAccount(state.accounts),
566
+ accountIds: newAccountIds,
567
+ activeAccountId: newActiveAccountId,
568
+ accountNamesToAccountIds: newAccountNamesToAccountIds,
569
+ accountsComments: newAccountsComments,
570
+ accountsCommentsIndexes: withoutAccount(state.accountsCommentsIndexes),
571
+ commentCidsToAccountsComments: getCommentCidsToAccountsComments(newAccountsComments),
572
+ accountsVotes: withoutAccount(state.accountsVotes),
573
+ accountsEdits: withoutAccount(state.accountsEdits),
574
+ accountsEditsSummaries: withoutAccount(state.accountsEditsSummaries),
575
+ accountsEditsLoaded: withoutAccount(state.accountsEditsLoaded),
576
+ accountsCommentsReplies: withoutAccount(state.accountsCommentsReplies),
577
+ };
578
+ });
579
+ }
580
+ finally {
581
+ deletingAccountIds.delete(account.id);
582
+ }
520
583
  });
521
584
  export const setActiveAccount = (accountName) => __awaiter(void 0, void 0, void 0, function* () {
522
585
  const { accountNamesToAccountIds } = accountsStore.getState();
@@ -921,7 +984,7 @@ const omitPublishCommentCallbacks = (options) => {
921
984
  return publicationOptions;
922
985
  };
923
986
  export const publishComment = (publishCommentOptions, accountName) => __awaiter(void 0, void 0, void 0, function* () {
924
- var _a, _b;
987
+ var _a;
925
988
  const { accounts, accountsComments, accountNamesToAccountIds, activeAccountId } = accountsStore.getState();
926
989
  assert(accounts && accountNamesToAccountIds && activeAccountId, `can't use accountsStore.accountActions before initialized`);
927
990
  let account = accounts[activeAccountId];
@@ -985,7 +1048,11 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
985
1048
  });
986
1049
  const createAccountComment = (createCommentOptions, index) => addShortAddressesToAccountComment(sanitizeAccountCommentForState(Object.assign(Object.assign({}, normalizePublicationOptionsForStore(createCommentOptions)), {
987
1050
  // try to get comment depth needed for custom depth flat account replies
988
- depth: getAccountCommentDepth(createCommentOptions), index, accountId: account.id })));
1051
+ depth: getAccountCommentDepth(createCommentOptions),
1052
+ // try to get the post cid so a pending reply can link to its thread
1053
+ postCid: getAccountCommentPostCid(createCommentOptions,
1054
+ // the parent can be a comment of a local account that only the accounts store has so far
1055
+ getAccountCommentByCid(createCommentOptions.parentCid)), index, accountId: account.id })));
989
1056
  const commentLinkDimensionsPromises = new Map();
990
1057
  const getCommentLinkDimensions = (link) => {
991
1058
  if (!commentLinkDimensionsPromises.has(link)) {
@@ -1007,9 +1074,9 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1007
1074
  publishingState: "fetching-link-dimensions",
1008
1075
  };
1009
1076
  }
1010
- // save comment to db
1011
- let accountCommentIndex = accountsComments[account.id].length;
1012
- const publishSessionId = createPublishSession(account.id, accountCommentIndex);
1077
+ // save comment to db: the row index and the publish session are set by the queued first save
1078
+ let accountCommentIndex;
1079
+ let publishSessionId;
1013
1080
  let savedOnce = false;
1014
1081
  const saveCreatedAccountComment = (accountComment) => __awaiter(void 0, void 0, void 0, function* () {
1015
1082
  var _a;
@@ -1045,7 +1112,7 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1045
1112
  });
1046
1113
  return persistedIndex;
1047
1114
  });
1048
- let createdAccountComment = createAccountComment(createCommentOptions, accountCommentIndex);
1115
+ let createdAccountComment;
1049
1116
  const reportOnPendingCommentError = (error, pendingCommentIndex) => {
1050
1117
  log.error("accountsActions.publishComment onPendingComment callback error", {
1051
1118
  accountId: account.id,
@@ -1063,8 +1130,17 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1063
1130
  reportOnPendingCommentError(error, pendingCommentIndex);
1064
1131
  }
1065
1132
  };
1066
- notifyPendingComment(accountCommentIndex, createdAccountComment);
1067
- const pendingCommentIndex = yield saveCreatedAccountComment(createdAccountComment);
1133
+ const pendingCommentIndex = yield queueAccountCommentAppend(account.id, () => {
1134
+ if (isAccountDeleted(account.id)) {
1135
+ throw Error(`accountsActions.publishComment account '${account.id}' was deleted`);
1136
+ }
1137
+ // read the live list, not the state from before the awaits above
1138
+ accountCommentIndex = accountsStore.getState().accountsComments[account.id].length;
1139
+ publishSessionId = createPublishSession(account.id, accountCommentIndex);
1140
+ createdAccountComment = createAccountComment(createCommentOptions, accountCommentIndex);
1141
+ notifyPendingComment(accountCommentIndex, createdAccountComment);
1142
+ return saveCreatedAccountComment(createdAccountComment);
1143
+ });
1068
1144
  if (pendingCommentIndex === undefined) {
1069
1145
  return createdAccountComment;
1070
1146
  }
@@ -1072,7 +1148,15 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1072
1148
  if (pendingCommentIndex !== accountCommentIndex) {
1073
1149
  notifyPendingComment(pendingCommentIndex, createdAccountComment);
1074
1150
  }
1075
- (_b = publishCommentOptions._onPendingCommentIndex) === null || _b === void 0 ? void 0 : _b.call(publishCommentOptions, pendingCommentIndex, createdAccountComment);
1151
+ // the hooks abandon the pending comment with abandonPendingComment, and learn its new index when a
1152
+ // deletion of an earlier account comment shifts it
1153
+ const abandonPendingComment = () => abandonPublishSession(publishSessionId);
1154
+ const onPendingCommentIndex = publishCommentOptions._onPendingCommentIndex;
1155
+ onPendingCommentIndex === null || onPendingCommentIndex === void 0 ? void 0 : onPendingCommentIndex(pendingCommentIndex, createdAccountComment, abandonPendingComment);
1156
+ const pendingPublishSession = getPublishSession(publishSessionId);
1157
+ if (onPendingCommentIndex && pendingPublishSession) {
1158
+ pendingPublishSession.onIndexChange = (index) => onPendingCommentIndex(index, Object.assign(Object.assign({}, createdAccountComment), { index }), abandonPendingComment);
1159
+ }
1076
1160
  let comment;
1077
1161
  (() => __awaiter(void 0, void 0, void 0, function* () {
1078
1162
  // fetch comment.link dimensions
@@ -1131,12 +1215,16 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1131
1215
  }));
1132
1216
  return error;
1133
1217
  };
1134
- const reportActivePublishCommentError = (rawError, activeComment) => {
1218
+ const reportActivePublishCommentError = (rawError, activeComment, publicationStopped) => {
1135
1219
  var _a;
1136
1220
  if (!getActiveSessionForComment(activeComment))
1137
1221
  return;
1138
1222
  const error = recordPublishCommentError(rawError, activeComment);
1139
- queueCleanupFailedPublishSession(activeComment);
1223
+ // pkc-js also emits errors it recovers from, e.g. a challenge with an invalid signature, and
1224
+ // keeps processing the exchange, so only an error that stopped the publication ends the session
1225
+ if (publicationStopped) {
1226
+ queueCleanupFailedPublishSession(activeComment);
1227
+ }
1140
1228
  (_a = publishCommentOptions.onError) === null || _a === void 0 ? void 0 : _a.call(publishCommentOptions, error, activeComment);
1141
1229
  };
1142
1230
  // the options onBeforeRepublish returns go through the same pipeline as the first publish; resolves
@@ -1176,7 +1264,7 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1176
1264
  ac[session.currentIndex] = Object.assign(Object.assign({}, acc), { state: "stopped", publishingState: "failed" });
1177
1265
  }));
1178
1266
  (_a = publishCommentOptions.onPublishingStateChange) === null || _a === void 0 ? void 0 : _a.call(publishCommentOptions, "failed");
1179
- reportActivePublishCommentError(error, failedComment);
1267
+ reportActivePublishCommentError(error, failedComment, true);
1180
1268
  };
1181
1269
  function publishAndRetryFailedChallengeVerification() {
1182
1270
  return __awaiter(this, void 0, void 0, function* () {
@@ -1190,7 +1278,7 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1190
1278
  publishCommentOptions.onChallenge(challenge, withPublishChallengeAnswersCompat(activeComment));
1191
1279
  }));
1192
1280
  activeComment.once("challengeverification", (challengeVerification) => __awaiter(this, void 0, void 0, function* () {
1193
- var _a, _b;
1281
+ var _a;
1194
1282
  applyChallengeVerificationCommentUpdateToPublication(challengeVerification, activeComment);
1195
1283
  publishCommentOptions.onChallengeVerification(challengeVerification, activeComment);
1196
1284
  // a verification with challengeErrors/reason is a terminal rejection of the publication
@@ -1233,11 +1321,16 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1233
1321
  // the challengeverification message of a comment publication should in theory send back the CID
1234
1322
  // of the published comment which is needed to resolve it for replies, upvotes, etc
1235
1323
  const session = getPublishSession(publishSessionId);
1236
- const currentIndex = (_a = session === null || session === void 0 ? void 0 : session.currentIndex) !== null && _a !== void 0 ? _a : accountCommentIndex;
1237
1324
  if (!session || isPublishSessionAbandoned(publishSessionId))
1238
1325
  return;
1239
- queueMicrotask(() => cleanupPublishSessionOnTerminal(publishSessionId));
1240
- if ((_b = challengeVerification === null || challengeVerification === void 0 ? void 0 : challengeVerification.commentUpdate) === null || _b === void 0 ? void 0 : _b.cid) {
1326
+ const hasCid = !!((_a = challengeVerification === null || challengeVerification === void 0 ? void 0 : challengeVerification.commentUpdate) === null || _a === void 0 ? void 0 : _a.cid);
1327
+ // once the publication's last state events ran, they and any later ones are ignored; with a
1328
+ // cid the session stays registered until the cid is saved, so a deleteComment meanwhile still
1329
+ // shifts or abandons its row
1330
+ queueMicrotask(() => hasCid
1331
+ ? updatePublishSessionComment(publishSessionId, undefined)
1332
+ : cleanupPublishSessionOnTerminal(publishSessionId));
1333
+ if (hasCid) {
1241
1334
  const persistedCommentWithCid = addShortAddressesToAccountComment(sanitizeStoredAccountComment(normalizePublicationOptionsForStore(comment)));
1242
1335
  const liveCommentWithCid = addShortAddressesToAccountComment(sanitizeAccountCommentForState(normalizePublicationOptionsForStore(comment)));
1243
1336
  delete persistedCommentWithCid.clients;
@@ -1248,7 +1341,20 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1248
1341
  delete liveCommentWithCid.publishingState;
1249
1342
  delete liveCommentWithCid.error;
1250
1343
  delete liveCommentWithCid.errors;
1251
- yield accountsDatabase.addAccountComment(account.id, persistedCommentWithCid, currentIndex);
1344
+ let savedSession;
1345
+ try {
1346
+ yield accountsDatabase.addAccountComment(account.id, persistedCommentWithCid, session.currentIndex);
1347
+ savedSession = isPublishSessionAbandoned(publishSessionId)
1348
+ ? undefined
1349
+ : getPublishSession(publishSessionId);
1350
+ }
1351
+ finally {
1352
+ cleanupPublishSessionOnTerminal(publishSessionId);
1353
+ }
1354
+ // the comment was deleted during the save
1355
+ if (!savedSession)
1356
+ return;
1357
+ const currentIndex = savedSession.currentIndex;
1252
1358
  accountsStore.setState(({ accountsComments, accountsCommentsIndexes, commentCidsToAccountsComments }) => {
1253
1359
  var _a;
1254
1360
  const updatedAccountComments = [...accountsComments[account.id]];
@@ -1273,7 +1379,7 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1273
1379
  }
1274
1380
  }));
1275
1381
  activeComment.on("error", (error) => {
1276
- reportActivePublishCommentError(error, activeComment);
1382
+ reportActivePublishCommentError(error, activeComment, activeComment.state === "stopped");
1277
1383
  });
1278
1384
  activeComment.on("statechange", (state) => {
1279
1385
  const session = getActiveSessionForComment(activeComment);
@@ -1337,7 +1443,7 @@ export const publishComment = (publishCommentOptions, accountName) => __awaiter(
1337
1443
  yield activeComment.publish();
1338
1444
  }
1339
1445
  catch (error) {
1340
- reportActivePublishCommentError(error, activeComment);
1446
+ reportActivePublishCommentError(error, activeComment, true);
1341
1447
  }
1342
1448
  });
1343
1449
  }
@@ -1363,24 +1469,38 @@ export const deleteComment = (commentCidOrAccountCommentIndex, accountName) => _
1363
1469
  assert(mapping && mapping.accountId === account.id, `accountsActions.deleteComment cid '${commentCidOrAccountCommentIndex}' not found for account`);
1364
1470
  accountCommentIndex = mapping.accountCommentIndex;
1365
1471
  }
1472
+ yield deleteAccountComment(account.id, accountCommentIndex);
1473
+ });
1474
+ const deleteAccountComment = (accountId, accountCommentIndex) => __awaiter(void 0, void 0, void 0, function* () {
1475
+ const { accountsComments } = accountsStore.getState();
1476
+ const accountComments = accountsComments[accountId] || [];
1366
1477
  assert(accountCommentIndex >= 0 && accountCommentIndex < accountComments.length, `accountsActions.deleteComment index '${accountCommentIndex}' out of range`);
1367
- abandonAndStopPublishSession(account.id, accountCommentIndex);
1368
- shiftPublishSessionIndicesAfterDelete(account.id, accountCommentIndex);
1478
+ abandonAndStopPublishSession(accountId, accountCommentIndex);
1479
+ shiftPublishSessionIndicesAfterDelete(accountId, accountCommentIndex);
1369
1480
  const spliced = [...accountComments];
1370
1481
  spliced.splice(accountCommentIndex, 1);
1371
- const reindexed = spliced.map((c, i) => (Object.assign(Object.assign({}, c), { index: i, accountId: account.id })));
1372
- const newAccountsComments = Object.assign(Object.assign({}, accountsComments), { [account.id]: reindexed });
1482
+ const reindexed = spliced.map((c, i) => (Object.assign(Object.assign({}, c), { index: i, accountId })));
1483
+ const newAccountsComments = Object.assign(Object.assign({}, accountsComments), { [accountId]: reindexed });
1373
1484
  const newCommentCidsToAccountsComments = getCommentCidsToAccountsComments(newAccountsComments);
1374
1485
  accountsStore.setState(({ accountsCommentsIndexes }) => ({
1375
1486
  accountsComments: newAccountsComments,
1376
- accountsCommentsIndexes: Object.assign(Object.assign({}, accountsCommentsIndexes), { [account.id]: getAccountCommentsIndex(reindexed) }),
1487
+ accountsCommentsIndexes: Object.assign(Object.assign({}, accountsCommentsIndexes), { [accountId]: getAccountCommentsIndex(reindexed) }),
1377
1488
  commentCidsToAccountsComments: newCommentCidsToAccountsComments,
1378
1489
  }));
1379
- yield accountsDatabase.deleteAccountComment(account.id, accountCommentIndex);
1380
- log("accountsActions.deleteComment", { accountId: account.id, accountCommentIndex });
1490
+ notifyShiftedPublishSessions(accountId, accountCommentIndex);
1491
+ yield accountsDatabase.deleteAccountComment(accountId, accountCommentIndex);
1492
+ log("accountsActions.deleteComment", { accountId, accountCommentIndex });
1493
+ });
1494
+ // deletes a comment that is still publishing from where its session has it now, in the account that
1495
+ // published it, so a deletion that shifted it or a change of the active account can't redirect it
1496
+ const abandonPublishSession = (sessionId) => __awaiter(void 0, void 0, void 0, function* () {
1497
+ const session = getPublishSession(sessionId);
1498
+ if (!session || isPublishSessionAbandoned(sessionId))
1499
+ return;
1500
+ yield deleteAccountComment(session.accountId, session.currentIndex);
1381
1501
  });
1382
1502
  export const publishVote = (publishVoteOptions, accountName) => __awaiter(void 0, void 0, void 0, function* () {
1383
- var _a, _b;
1503
+ var _a, _b, _c, _d;
1384
1504
  const { accounts, accountNamesToAccountIds, activeAccountId } = accountsStore.getState();
1385
1505
  assert(accounts && accountNamesToAccountIds && activeAccountId, `can't use accountsStore.accountActions before initialized`);
1386
1506
  let account = accounts[activeAccountId];
@@ -1398,20 +1518,48 @@ export const publishVote = (publishVoteOptions, accountName) => __awaiter(void 0
1398
1518
  delete createVoteOptions.onChallengeVerification;
1399
1519
  delete createVoteOptions.onError;
1400
1520
  delete createVoteOptions.onPublishingStateChange;
1401
- createVoteOptions = yield applyPublicationWordfilters("vote", createVoteOptions, account);
1521
+ delete createVoteOptions._onVotePublishSession;
1522
+ const { commentCid } = createVoteOptions;
1523
+ // started before the community's wordfilters load, so abandoning the vote meanwhile ends it
1524
+ const votePublishSession = startVotePublishSession(account.id, commentCid, (_a = accountsStore.getState().accountsVotes[account.id]) === null || _a === void 0 ? void 0 : _a[commentCid]);
1525
+ const votePublishSessionKey = getVotePublishSessionKey(account.id, commentCid);
1526
+ const isVotePublishSessionActive = () => activeVotePublishSessions.get(votePublishSessionKey) === votePublishSession;
1527
+ // the hooks abandon this vote's session in the account that published it, whichever is active
1528
+ (_b = publishVoteOptions._onVotePublishSession) === null || _b === void 0 ? void 0 : _b.call(publishVoteOptions, () => abandonVotePublishSession(account.id, commentCid, votePublishSession));
1529
+ // counted as a vote being created, so the rest of the burst can't end the session meanwhile
1530
+ votePublishSession.creating++;
1531
+ try {
1532
+ createVoteOptions = yield applyPublicationWordfilters("vote", createVoteOptions, account);
1533
+ }
1534
+ catch (error) {
1535
+ votePublishSession.creating--;
1536
+ if (votePublishSession.publications.size === 0 &&
1537
+ votePublishSession.creating === 0 &&
1538
+ isVotePublishSessionActive()) {
1539
+ endVotePublishSession(account.id, commentCid);
1540
+ }
1541
+ throw error;
1542
+ }
1543
+ votePublishSession.creating--;
1544
+ // abandoned while the wordfilters loaded: nothing was published or written, so stop here
1545
+ if (!isVotePublishSessionActive())
1546
+ return;
1547
+ // the account was deleted while the wordfilters loaded: nothing was published or written. Its
1548
+ // delete only abandoned the sessions that existed when it started, so end this one here
1549
+ if (isAccountDeleted(account.id)) {
1550
+ endVotePublishSession(account.id, commentCid);
1551
+ return;
1552
+ }
1402
1553
  const accountsState = accountsStore.getState();
1403
1554
  const accountCommentInfo = accountsState.commentCidsToAccountsComments[createVoteOptions.commentCid];
1404
1555
  const accountComment = accountCommentInfo
1405
- ? (_a = accountsState.accountsComments[accountCommentInfo.accountId]) === null || _a === void 0 ? void 0 : _a[accountCommentInfo.accountCommentIndex]
1556
+ ? (_c = accountsState.accountsComments[accountCommentInfo.accountId]) === null || _c === void 0 ? void 0 : _c[accountCommentInfo.accountCommentIndex]
1406
1557
  : undefined;
1407
- const previousAccountVote = (_b = accountsState.accountsVotes[account.id]) === null || _b === void 0 ? void 0 : _b[createVoteOptions.commentCid];
1558
+ const previousAccountVote = (_d = accountsState.accountsVotes[account.id]) === null || _d === void 0 ? void 0 : _d[createVoteOptions.commentCid];
1408
1559
  const storedCreateVoteOptions = addOptimisticVoteMetadata(normalizePublicationOptionsForStore(createVoteOptions), previousAccountVote, getFreshestLoadedComment(createVoteOptions.commentCid, accountComment));
1409
1560
  const accountVote = Object.assign(Object.assign({}, storedCreateVoteOptions), {
1410
1561
  // remove signer and author because not needed and they expose private key
1411
1562
  signer: undefined, author: undefined });
1412
- const votePublishSession = startVotePublishSession(account.id, createVoteOptions.commentCid, previousAccountVote);
1413
- const votePublishSessionKey = getVotePublishSessionKey(account.id, createVoteOptions.commentCid);
1414
- const isVotePublishSessionActive = () => activeVotePublishSessions.get(votePublishSessionKey) === votePublishSession;
1415
1563
  const createSessionVote = () => __awaiter(void 0, void 0, void 0, function* () {
1416
1564
  votePublishSession.creating++;
1417
1565
  try {
@@ -1421,19 +1569,65 @@ export const publishVote = (publishVoteOptions, accountName) => __awaiter(void 0
1421
1569
  votePublishSession.creating--;
1422
1570
  }
1423
1571
  });
1424
- let vote = yield createSessionVote();
1572
+ let resolveAccountVoteWritten;
1573
+ const accountVoteWritten = new Promise((resolve) => (resolveAccountVoteWritten = resolve));
1574
+ // a publication is verified, rejected by the community, or failed to publish: it is no longer
1575
+ // abandonable. The session ends only once no other publication of the burst is waiting on its
1576
+ // challenge or still being created, and only if a newer session has not replaced it in the
1577
+ // meantime; if one of them failed, the account vote goes back to the last one verified.
1578
+ const endVotePublication = (endedVote, verified) => __awaiter(void 0, void 0, void 0, function* () {
1579
+ // already ended, e.g. publish() rejecting after its error event
1580
+ if (!votePublishSession.publications.delete(endedVote))
1581
+ return;
1582
+ if (verified) {
1583
+ // the verified vote is the one the account has now, so abandoning the rest of the burst
1584
+ // restores it instead of the vote from before the burst
1585
+ votePublishSession.previousAccountVote = accountVote;
1586
+ }
1587
+ else {
1588
+ votePublishSession.failed = true;
1589
+ }
1590
+ yield endVotePublishSessionIfSettled();
1591
+ });
1592
+ const endVotePublishSessionIfSettled = () => __awaiter(void 0, void 0, void 0, function* () {
1593
+ if (votePublishSession.publications.size !== 0 ||
1594
+ votePublishSession.creating !== 0 ||
1595
+ !isVotePublishSessionActive()) {
1596
+ return;
1597
+ }
1598
+ activeVotePublishSessions.delete(votePublishSessionKey);
1599
+ if (!votePublishSession.failed)
1600
+ return;
1601
+ try {
1602
+ // the optimistic write may still be running when the publication fails fast
1603
+ yield accountVoteWritten;
1604
+ yield restoreAccountVote(account.id, createVoteOptions.commentCid, votePublishSession.previousAccountVote);
1605
+ }
1606
+ catch (error) {
1607
+ log.error("accountsActions.publishVote restore failed vote error", { error });
1608
+ }
1609
+ });
1610
+ let vote = yield createSessionVote().catch((error) => __awaiter(void 0, void 0, void 0, function* () {
1611
+ // nothing was published or written for this vote, but an earlier vote of the burst may have
1612
+ // failed while it was being created and left the session for this one to end
1613
+ resolveAccountVoteWritten();
1614
+ yield endVotePublishSessionIfSettled();
1615
+ throw error;
1616
+ }));
1425
1617
  // abandoned while the vote was being created: nothing was published or written, so stop here
1426
1618
  if (!isVotePublishSessionActive())
1427
1619
  return;
1428
1620
  let lastChallenge;
1429
1621
  const publishAndRetryFailedChallengeVerification = () => __awaiter(void 0, void 0, void 0, function* () {
1430
1622
  var _a;
1623
+ const activeVote = vote;
1431
1624
  votePublishSession.publications.add(vote);
1432
1625
  vote.once("challenge", (challenge) => __awaiter(void 0, void 0, void 0, function* () {
1433
1626
  lastChallenge = challenge;
1434
1627
  publishVoteOptions.onChallenge(challenge, withPublishChallengeAnswersCompat(vote));
1435
1628
  }));
1436
1629
  vote.once("challengeverification", (challengeVerification) => __awaiter(void 0, void 0, void 0, function* () {
1630
+ var _a;
1437
1631
  publishVoteOptions.onChallengeVerification(challengeVerification, vote);
1438
1632
  // same terminal short-circuit as publishComment/publishCommentEdit: never retry a rejection
1439
1633
  if (!challengeVerification.challengeSuccess &&
@@ -1442,30 +1636,34 @@ export const publishVote = (publishVoteOptions, accountName) => __awaiter(void 0
1442
1636
  // publish again automatically on fail
1443
1637
  votePublishSession.publications.delete(vote);
1444
1638
  createVoteOptions = Object.assign(Object.assign({}, createVoteOptions), { timestamp: Math.floor(Date.now() / 1000) });
1445
- vote = yield createSessionVote();
1639
+ try {
1640
+ vote = yield createSessionVote();
1641
+ }
1642
+ catch (error) {
1643
+ // no retry was published, so the failed vote ends the burst like a rejected one
1644
+ votePublishSession.failed = true;
1645
+ yield endVotePublishSessionIfSettled();
1646
+ (_a = publishVoteOptions.onError) === null || _a === void 0 ? void 0 : _a.call(publishVoteOptions, error, activeVote);
1647
+ return;
1648
+ }
1446
1649
  if (!isVotePublishSessionActive())
1447
1650
  return;
1448
1651
  lastChallenge = undefined;
1449
1652
  publishAndRetryFailedChallengeVerification();
1450
1653
  }
1451
1654
  else {
1452
- // terminal: this vote is no longer abandonable
1453
- votePublishSession.publications.delete(vote);
1454
- if (challengeVerification.challengeSuccess) {
1455
- // the verified vote is the one the account has now, so abandoning the rest of the burst
1456
- // restores it instead of the vote from before the burst
1457
- votePublishSession.previousAccountVote = accountVote;
1458
- }
1459
- // the session ends only once no other publication of the burst is waiting on its challenge
1460
- // or still being created, and only if a newer session has not replaced it in the meantime
1461
- if (votePublishSession.publications.size === 0 &&
1462
- votePublishSession.creating === 0 &&
1463
- isVotePublishSessionActive()) {
1464
- activeVotePublishSessions.delete(votePublishSessionKey);
1465
- }
1655
+ yield endVotePublication(activeVote, challengeVerification.challengeSuccess);
1466
1656
  }
1467
1657
  }));
1468
- vote.on("error", (error) => { var _a; return (_a = publishVoteOptions.onError) === null || _a === void 0 ? void 0 : _a.call(publishVoteOptions, error, vote); });
1658
+ vote.on("error", (error) => __awaiter(void 0, void 0, void 0, function* () {
1659
+ var _a;
1660
+ // pkc-js also emits errors it recovers from, e.g. a challenge with an invalid signature, and
1661
+ // stops the publication before emitting the ones that end it
1662
+ if (activeVote.state === "stopped") {
1663
+ yield endVotePublication(activeVote, false);
1664
+ }
1665
+ (_a = publishVoteOptions.onError) === null || _a === void 0 ? void 0 : _a.call(publishVoteOptions, error, vote);
1666
+ }));
1469
1667
  // TODO: add publishingState to account votes
1470
1668
  vote.on("publishingstatechange", (publishingState) => { var _a; return (_a = publishVoteOptions.onPublishingStateChange) === null || _a === void 0 ? void 0 : _a.call(publishVoteOptions, publishingState); });
1471
1669
  listeners.push(vote);
@@ -1475,22 +1673,27 @@ export const publishVote = (publishVoteOptions, accountName) => __awaiter(void 0
1475
1673
  yield vote.publish();
1476
1674
  }
1477
1675
  catch (error) {
1676
+ yield endVotePublication(activeVote, false);
1478
1677
  (_a = publishVoteOptions.onError) === null || _a === void 0 ? void 0 : _a.call(publishVoteOptions, error, vote);
1479
1678
  }
1480
1679
  });
1481
1680
  publishAndRetryFailedChallengeVerification();
1482
- yield accountsDatabase.addAccountVote(account.id, storedCreateVoteOptions);
1483
- log("accountsActions.publishVote", { createVoteOptions });
1484
- accountsStore.setState(({ accountsVotes }) => ({
1485
- accountsVotes: Object.assign(Object.assign({}, accountsVotes), { [account.id]: Object.assign(Object.assign({}, accountsVotes[account.id]), { [storedCreateVoteOptions.commentCid]: accountVote }) }),
1486
- }));
1681
+ try {
1682
+ yield accountsDatabase.addAccountVote(account.id, storedCreateVoteOptions);
1683
+ log("accountsActions.publishVote", { createVoteOptions });
1684
+ accountsStore.setState(({ accountsVotes }) => ({
1685
+ accountsVotes: Object.assign(Object.assign({}, accountsVotes), { [account.id]: Object.assign(Object.assign({}, accountsVotes[account.id]), { [storedCreateVoteOptions.commentCid]: accountVote }) }),
1686
+ }));
1687
+ }
1688
+ finally {
1689
+ resolveAccountVoteWritten();
1690
+ }
1487
1691
  });
1488
1692
  /**
1489
1693
  * Stops the vote publications still waiting on a challenge for a comment and restores the account
1490
1694
  * vote they optimistically replaced. Does nothing once the vote has been verified.
1491
1695
  */
1492
1696
  export const abandonVote = (commentCid, accountName) => __awaiter(void 0, void 0, void 0, function* () {
1493
- var _a;
1494
1697
  const { accounts, accountNamesToAccountIds, activeAccountId } = accountsStore.getState();
1495
1698
  assert(accounts && accountNamesToAccountIds && activeAccountId, `can't use accountsStore.accountActions before initialized`);
1496
1699
  let account = accounts[activeAccountId];
@@ -1500,10 +1703,15 @@ export const abandonVote = (commentCid, accountName) => __awaiter(void 0, void 0
1500
1703
  }
1501
1704
  assert(account === null || account === void 0 ? void 0 : account.id, `accountsActions.abandonVote account.id '${account === null || account === void 0 ? void 0 : account.id}' doesn't exist`);
1502
1705
  assert(commentCid && typeof commentCid === "string", `accountsActions.abandonVote commentCid '${commentCid}' not a string`);
1503
- const session = activeVotePublishSessions.get(getVotePublishSessionKey(account.id, commentCid));
1504
- if (!session)
1706
+ yield abandonVotePublishSession(account.id, commentCid);
1707
+ });
1708
+ // with votePublishSession, abandons only that session, not a newer one for the same comment
1709
+ const abandonVotePublishSession = (accountId, commentCid, votePublishSession) => __awaiter(void 0, void 0, void 0, function* () {
1710
+ var _a;
1711
+ const session = activeVotePublishSessions.get(getVotePublishSessionKey(accountId, commentCid));
1712
+ if (!session || (votePublishSession && session !== votePublishSession))
1505
1713
  return;
1506
- endVotePublishSession(account.id, commentCid);
1714
+ endVotePublishSession(accountId, commentCid);
1507
1715
  for (const publication of session.publications) {
1508
1716
  try {
1509
1717
  const stop = (_a = publication === null || publication === void 0 ? void 0 : publication.stop) === null || _a === void 0 ? void 0 : _a.bind(publication);
@@ -1512,14 +1720,14 @@ export const abandonVote = (commentCid, accountName) => __awaiter(void 0, void 0
1512
1720
  }
1513
1721
  catch (e) {
1514
1722
  log.error("vote.stop() error during abandon", {
1515
- accountId: account.id,
1723
+ accountId,
1516
1724
  commentCid,
1517
1725
  error: e,
1518
1726
  });
1519
1727
  }
1520
1728
  }
1521
- yield restoreAccountVote(account.id, commentCid, session.previousAccountVote);
1522
- log("accountsActions.abandonVote", { accountId: account.id, commentCid });
1729
+ yield restoreAccountVote(accountId, commentCid, session.previousAccountVote);
1730
+ log("accountsActions.abandonVote", { accountId, commentCid });
1523
1731
  });
1524
1732
  export const publishCommentEdit = (publishCommentEditOptions, accountName) => __awaiter(void 0, void 0, void 0, function* () {
1525
1733
  const { accounts, accountNamesToAccountIds, activeAccountId } = accountsStore.getState();
@@ -1840,6 +2048,7 @@ export const createCommunity = (createCommunityOptions, accountName) => __awaite
1840
2048
  return community;
1841
2049
  });
1842
2050
  export const deleteCommunity = (communityAddress, accountName) => __awaiter(void 0, void 0, void 0, function* () {
2051
+ var _a;
1843
2052
  const { accounts, accountNamesToAccountIds, activeAccountId } = accountsStore.getState();
1844
2053
  assert(accounts && accountNamesToAccountIds && activeAccountId, `can't use accountsStore.accountsActions before initialized`);
1845
2054
  let account = accounts[activeAccountId];
@@ -1847,7 +2056,39 @@ export const deleteCommunity = (communityAddress, accountName) => __awaiter(void
1847
2056
  const accountId = accountNamesToAccountIds[accountName];
1848
2057
  account = accounts[accountId];
1849
2058
  }
2059
+ // read the other identifiers of the community (name, public key) before the store forgets them
2060
+ const deletedCommunity = communitiesStore.getState().communities[communityAddress];
1850
2061
  yield communitiesStore.getState().deleteCommunity(communityAddress, account);
2062
+ // remove the deleted community from the deleting account's stored communities, under every
2063
+ // address it is known by, or useAccountCommunities keeps listing it. Other local accounts keep
2064
+ // their entry: they did not delete the community
2065
+ const isDeletedCommunity = (accountCommunityAddress) => doesAddressMatchCommunityRef(accountCommunityAddress, { address: communityAddress }, deletedCommunity);
2066
+ // a saveComment still writing has the database ahead of the store: let it merge first, or the
2067
+ // store snapshot written below drops its saved comment
2068
+ while (savedCommentMutationQueues.has(account.id)) {
2069
+ yield ((_a = savedCommentMutationQueues.get(account.id)) === null || _a === void 0 ? void 0 : _a.catch(() => { }));
2070
+ }
2071
+ // the account was deleted while the community was: writing it would restore its record
2072
+ if (isAccountDeleted(account.id)) {
2073
+ return;
2074
+ }
2075
+ let updatedAccount;
2076
+ accountsStore.setState(({ accounts }) => {
2077
+ const currentAccount = accounts[account.id];
2078
+ const addressesToRemove = Object.keys((currentAccount === null || currentAccount === void 0 ? void 0 : currentAccount.communities) || {}).filter(isDeletedCommunity);
2079
+ if (!addressesToRemove.length) {
2080
+ return {};
2081
+ }
2082
+ const communities = Object.assign({}, currentAccount.communities);
2083
+ for (const address of addressesToRemove) {
2084
+ delete communities[address];
2085
+ }
2086
+ updatedAccount = Object.assign(Object.assign({}, currentAccount), { communities });
2087
+ return { accounts: Object.assign(Object.assign({}, accounts), { [account.id]: updatedAccount }) };
2088
+ });
2089
+ if (updatedAccount) {
2090
+ yield accountsDatabase.addAccount(updatedAccount);
2091
+ }
1851
2092
  log("accountsActions.deleteCommunity", { communityAddress });
1852
2093
  });
1853
2094
  //# sourceMappingURL=accounts-actions.js.map