@pkcprotocol/pkc-js 0.0.81 → 0.0.83

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 (128) hide show
  1. package/README.md +3 -1
  2. package/dist/browser/clients/base-client-manager.js +19 -1
  3. package/dist/browser/clients/base-client-manager.js.map +1 -1
  4. package/dist/browser/clients/rpc-client/rpc-schema-util.d.ts +1 -0
  5. package/dist/browser/clients/rpc-client/schema.d.ts +3 -0
  6. package/dist/browser/community/schema.d.ts +24 -0
  7. package/dist/browser/community/schema.js +6 -1
  8. package/dist/browser/community/schema.js.map +1 -1
  9. package/dist/browser/errors.d.ts +10 -1
  10. package/dist/browser/errors.js +10 -1
  11. package/dist/browser/errors.js.map +1 -1
  12. package/dist/browser/generated-version.d.ts +1 -1
  13. package/dist/browser/generated-version.js +1 -1
  14. package/dist/browser/pages/pages.js +8 -0
  15. package/dist/browser/pages/pages.js.map +1 -1
  16. package/dist/browser/pages/schema.d.ts +4 -0
  17. package/dist/browser/pages/util.d.ts +2 -0
  18. package/dist/browser/pages/util.js +23 -3
  19. package/dist/browser/pages/util.js.map +1 -1
  20. package/dist/browser/pkc/pkc.d.ts +2 -0
  21. package/dist/browser/pkc/pkc.js +20 -0
  22. package/dist/browser/pkc/pkc.js.map +1 -1
  23. package/dist/browser/pkc-error.d.ts +1 -1
  24. package/dist/browser/publications/comment/comment-client-manager.js +22 -4
  25. package/dist/browser/publications/comment/comment-client-manager.js.map +1 -1
  26. package/dist/browser/publications/comment/comment.d.ts +2 -1
  27. package/dist/browser/publications/comment/comment.js +29 -6
  28. package/dist/browser/publications/comment/comment.js.map +1 -1
  29. package/dist/browser/publications/comment/crosspost-depth.d.ts +5 -0
  30. package/dist/browser/publications/comment/crosspost-depth.js +75 -0
  31. package/dist/browser/publications/comment/crosspost-depth.js.map +1 -0
  32. package/dist/browser/publications/comment/crosspost-runtime.d.ts +30 -0
  33. package/dist/browser/publications/comment/crosspost-runtime.js +133 -0
  34. package/dist/browser/publications/comment/crosspost-runtime.js.map +1 -0
  35. package/dist/browser/publications/comment/schema.d.ts +20 -2
  36. package/dist/browser/publications/comment/schema.js +21 -10
  37. package/dist/browser/publications/comment/schema.js.map +1 -1
  38. package/dist/browser/publications/comment/types.d.ts +10 -0
  39. package/dist/browser/publications/community-edit/schema.d.ts +4 -0
  40. package/dist/browser/publications/publication.d.ts +4 -0
  41. package/dist/browser/publications/publication.js +80 -5
  42. package/dist/browser/publications/publication.js.map +1 -1
  43. package/dist/browser/pubsub-messages/schema.d.ts +5 -0
  44. package/dist/browser/rpc/src/index.js +13 -1
  45. package/dist/browser/rpc/src/index.js.map +1 -1
  46. package/dist/browser/runtime/node/community/db-handler.d.ts +2 -0
  47. package/dist/browser/runtime/node/community/db-handler.js +24 -6
  48. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  49. package/dist/browser/runtime/node/community/local-community/publication-validation.js +15 -0
  50. package/dist/browser/runtime/node/community/local-community/publication-validation.js.map +1 -1
  51. package/dist/browser/runtime/node/community/page-generator.d.ts +2 -0
  52. package/dist/browser/schema/schema-util.d.ts +17 -0
  53. package/dist/browser/schema/schema-util.js +49 -5
  54. package/dist/browser/schema/schema-util.js.map +1 -1
  55. package/dist/browser/signer/signatures.d.ts +1 -10
  56. package/dist/browser/signer/signatures.js +83 -0
  57. package/dist/browser/signer/signatures.js.map +1 -1
  58. package/dist/browser/test/test-util.d.ts +6 -0
  59. package/dist/browser/version.js +1 -1
  60. package/dist/bundled/bundle-manifest.json +27 -25
  61. package/dist/bundled/chunks/{helia-for-pkc-BcNF-orO.js → helia-for-pkc-BtjQ8rfd.js} +33 -33
  62. package/dist/bundled/chunks/{local-community-B6-jaMsn.js → local-community-B_Yg8LQH.js} +1 -1
  63. package/dist/bundled/chunks/{local-community-CyX1HwD0.js → local-community-DJM47U8C.js} +47 -32
  64. package/dist/bundled/chunks/{node-BCXmIYLQ.js → node-lb4SvdBh.js} +67 -14
  65. package/dist/bundled/chunks/{rpc-local-community-BOiy8BX1.js → rpc-local-community-a464veDe.js} +253 -12
  66. package/dist/bundled/chunks/{schema-DZyEx0YQ.js → schema-mdv9_FG5.js} +23 -8
  67. package/dist/bundled/chunks/{util-BTPlI1yF.js → util-y9-A9BnM.js} +1 -1
  68. package/dist/bundled/index.js +1 -1
  69. package/dist/bundled/rpc/src/index.js +13 -5
  70. package/dist/node/clients/base-client-manager.js +19 -1
  71. package/dist/node/clients/base-client-manager.js.map +1 -1
  72. package/dist/node/clients/rpc-client/rpc-schema-util.d.ts +1 -0
  73. package/dist/node/clients/rpc-client/schema.d.ts +3 -0
  74. package/dist/node/community/schema.d.ts +24 -0
  75. package/dist/node/community/schema.js +6 -1
  76. package/dist/node/community/schema.js.map +1 -1
  77. package/dist/node/errors.d.ts +10 -1
  78. package/dist/node/errors.js +10 -1
  79. package/dist/node/errors.js.map +1 -1
  80. package/dist/node/generated-version.d.ts +1 -1
  81. package/dist/node/generated-version.js +1 -1
  82. package/dist/node/pages/pages.js +8 -0
  83. package/dist/node/pages/pages.js.map +1 -1
  84. package/dist/node/pages/schema.d.ts +4 -0
  85. package/dist/node/pages/util.d.ts +2 -0
  86. package/dist/node/pages/util.js +23 -3
  87. package/dist/node/pages/util.js.map +1 -1
  88. package/dist/node/pkc/pkc.d.ts +2 -0
  89. package/dist/node/pkc/pkc.js +20 -0
  90. package/dist/node/pkc/pkc.js.map +1 -1
  91. package/dist/node/pkc-error.d.ts +1 -1
  92. package/dist/node/publications/comment/comment-client-manager.js +22 -4
  93. package/dist/node/publications/comment/comment-client-manager.js.map +1 -1
  94. package/dist/node/publications/comment/comment.d.ts +2 -1
  95. package/dist/node/publications/comment/comment.js +29 -6
  96. package/dist/node/publications/comment/comment.js.map +1 -1
  97. package/dist/node/publications/comment/crosspost-depth.d.ts +5 -0
  98. package/dist/node/publications/comment/crosspost-depth.js +75 -0
  99. package/dist/node/publications/comment/crosspost-depth.js.map +1 -0
  100. package/dist/node/publications/comment/crosspost-runtime.d.ts +30 -0
  101. package/dist/node/publications/comment/crosspost-runtime.js +133 -0
  102. package/dist/node/publications/comment/crosspost-runtime.js.map +1 -0
  103. package/dist/node/publications/comment/schema.d.ts +20 -2
  104. package/dist/node/publications/comment/schema.js +21 -10
  105. package/dist/node/publications/comment/schema.js.map +1 -1
  106. package/dist/node/publications/comment/types.d.ts +10 -0
  107. package/dist/node/publications/community-edit/schema.d.ts +4 -0
  108. package/dist/node/publications/publication.d.ts +4 -0
  109. package/dist/node/publications/publication.js +80 -5
  110. package/dist/node/publications/publication.js.map +1 -1
  111. package/dist/node/pubsub-messages/schema.d.ts +5 -0
  112. package/dist/node/rpc/src/index.js +13 -1
  113. package/dist/node/rpc/src/index.js.map +1 -1
  114. package/dist/node/runtime/node/community/db-handler.d.ts +2 -0
  115. package/dist/node/runtime/node/community/db-handler.js +24 -6
  116. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  117. package/dist/node/runtime/node/community/local-community/publication-validation.js +15 -0
  118. package/dist/node/runtime/node/community/local-community/publication-validation.js.map +1 -1
  119. package/dist/node/runtime/node/community/page-generator.d.ts +2 -0
  120. package/dist/node/schema/schema-util.d.ts +17 -0
  121. package/dist/node/schema/schema-util.js +49 -5
  122. package/dist/node/schema/schema-util.js.map +1 -1
  123. package/dist/node/signer/signatures.d.ts +1 -10
  124. package/dist/node/signer/signatures.js +83 -0
  125. package/dist/node/signer/signatures.js.map +1 -1
  126. package/dist/node/test/test-util.d.ts +6 -0
  127. package/dist/node/version.js +1 -1
  128. package/package.json +1 -1
@@ -1,12 +1,12 @@
1
1
  import { i as __toESM, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $ as pubsubTopicToDhtKey, $n as n$3, An as CommentsTableRowSchema, At as trackStartedCommunity, Bn as CommentEditsTableRowSchema, Bt as CommunityEditPublicationPubsubReservedFields, C as contentContainsMarkdownAudio, Ct as findUpdatingCommunity, Dn as CommentUpdateSchema, F as getIpnsRecordInLocalKuboNode, Ft as untrackUpdatingCommunity, G as isLinkOfAudio, Gt as CommentModerationPubsubMessagePublicationSchema, In as CommentEditPubsubMessagePublicationSchema, It as require_sha256, J as isLinkOfVideo, Jt as CommentModerationsTableRowSchema, K as isLinkOfImage, Kt as CommentModerationReservedFields, L as hideClassPrivateProps, Ln as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, M as genToArray, Mt as trackUpdatingCommunity, N as getEquivalentCommunityAddresses, Nr as ZodError, Nt as untrackStartedCommunity, O as derivePublicationFromChallengeRequest, P as getErrorCodeFromMessage, Q as isStringDomain, Qn as t$8, R as ipnsNameToIpnsOverPubsubTopic, Rn as CommentEditReservedFields, S as calculateStringSizeSameAsIpfsAddCidV0, T as contentContainsMarkdownVideos, W as isLinkOfAnimatedImage, Wn as AuthorReservedFields, Y as isLinkValid, Zn as n$4, _t as timestamp, a as ChallengeRequestMessageSchema, ar as r$1, at as removeNullUndefinedValues, b as areEquivalentCommunityAddresses, bn as CommentPubsubMessageReservedFields, br as logger_default, bt as findCommunityInRegistry, d as DecryptedChallengeRequestSchema, dt as retryKuboIpfsAddAndProvide, er as t$7, fr as require_retry, gn as VoteTablesRowSchema, ht as statMfsPathSafely, in as CommunitySignedPropertyNames, k as doesDomainAddressHaveCapitalLetter, kn as CommentUpdateTableRowSchema, kt as syncCommunityRegistryEntry, lr as t$5, lt as retryKuboBlockPutPinAndProvidePubsubTopic, mn as VotePubsubReservedFields, mt as sleepUntilTimeoutOrAbort, nr as e, nt as removeBlocksFromKuboNode, or as t$4, pn as VotePubsubMessagePublicationSchema, q as isLinkOfMedia, r as ChallengeMessageSchema, rn as CommunityIpfsSchema, rr as e$1, rt as removeMfsFilesSafely, s as ChallengeVerificationMessageSchema, t as ChallengeAnswerMessageSchema, tr as t$6, u as DecryptedChallengeRequestPublicationSchema, ur as t$3, vr as PKCError, w as contentContainsMarkdownImages, x as calculateIpfsCidV0, xt as findStartedCommunity, y as version_default, yn as CommentIpfsSchema, yr as messages, yt as writeKuboFilesWithTimeout } from "./schema-DZyEx0YQ.js";
3
- import { $n as n$5, A as deriveDbReplies, At as verifyVote, C as backupCommunityDb, Ct as verifyCommentEdit, D as deleteOldCommunityInWindows, Dt as verifyCommentUpdate, Et as verifyCommentPubsubMessage, G as TIMEFRAMES_TO_SECONDS, Gt as getPKCAddressFromPublicKey, H as POSTS_SORT_TYPES, Ht as encode, Jn as t$9, Jt as createSchemaRowParser, Kt as getPKCAddressFromPublicKeySync, L as moveCommunityDbToDeletedDirectory, Mt as cleanWireAuthor, N as getThumbnailPropsOfLink, O as deriveCommentIpfsFromCommentTableRow, Ot as verifyCommunity, P as importSignerIntoKuboNode, Pt as getAuthorNameFromWire, Qn as n$6, R as resolveDbPostsCidRefs, Rt as getCommunityNameFromWire, S as BackupAbortError, T as calculateInlineRepliesBudget, Tt as verifyCommentModeration, U as POST_REPLIES_SORT_TYPES, Vt as decode, W as REPLY_REPLIES_SORT_TYPES, Wt as getIpfsKeyFromPrivateKey, X as iterateOverPageCidsToFindAllCids, Xn as r$2, Yn as t$12, Zn as t$11, _n as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, a as pkcJsChallenges, an as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, bn as parseJsonWithPKCErrorIfFails, ct as signChallengeMessage, dt as signComment, ft as signCommentEdit, gt as signCommunity, h as SignerWithPublicKeyAddress, ht as signCommentUpdateForChallengeVerification, i as getCommunityChallengeFromCommunityChallengeSettings, ir as require_lodash_merge, j as getDefaultCommunityDbConfig, jt as buildRuntimeAuthor, k as deriveDbPosts, kt as verifyCommunityEdit, l as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, mt as signCommentUpdate, nr as stringify, o as TrackedInstanceRegistry, ot as cleanUpBeforePublishing, qt as getPublicKeyFromPrivateKey, r as getChallengeVerification, rr as STORAGE_KEYS, rt as pLimit, s as LRUCache, sn as parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails, t as RpcLocalCommunity, tr as t$10, u as KeyvBetterSqlite3, ut as signChallengeVerification, w as calculateExpectedSignatureSize, wt as verifyCommentIpfs, x as encryptEd25519AesGcmPublicKeyBuffer, xt as verifyChallengeRequest, y as decryptEd25519AesGcmPublicKeyBuffer, yt as verifyChallengeAnswer, zt as getCommunityPublicKeyFromWire } from "./rpc-local-community-BOiy8BX1.js";
2
+ import { $ as pubsubTopicToDhtKey, $n as n$3, An as CommentsTableRowSchema, At as trackStartedCommunity, Bn as CommentEditsTableRowSchema, Bt as CommunityEditPublicationPubsubReservedFields, C as contentContainsMarkdownAudio, Ct as findUpdatingCommunity, Dn as CommentUpdateSchema, F as getIpnsRecordInLocalKuboNode, Ft as untrackUpdatingCommunity, G as isLinkOfAudio, Gt as CommentModerationPubsubMessagePublicationSchema, In as CommentEditPubsubMessagePublicationSchema, It as require_sha256, J as isLinkOfVideo, Jt as CommentModerationsTableRowSchema, K as isLinkOfImage, Kt as CommentModerationReservedFields, L as hideClassPrivateProps, Ln as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, M as genToArray, Mt as trackUpdatingCommunity, N as getEquivalentCommunityAddresses, Nr as ZodError, Nt as untrackStartedCommunity, O as derivePublicationFromChallengeRequest, P as getErrorCodeFromMessage, Q as isStringDomain, Qn as t$8, R as ipnsNameToIpnsOverPubsubTopic, Rn as CommentEditReservedFields, S as calculateStringSizeSameAsIpfsAddCidV0, T as contentContainsMarkdownVideos, W as isLinkOfAnimatedImage, Wn as AuthorReservedFields, Y as isLinkValid, Zn as n$4, _t as timestamp, a as ChallengeRequestMessageSchema, ar as r$1, at as removeNullUndefinedValues, b as areEquivalentCommunityAddresses, bn as CommentPubsubMessageReservedFields, br as logger_default, bt as findCommunityInRegistry, d as DecryptedChallengeRequestSchema, dt as retryKuboIpfsAddAndProvide, er as t$7, fr as require_retry, gn as VoteTablesRowSchema, ht as statMfsPathSafely, in as CommunitySignedPropertyNames, k as doesDomainAddressHaveCapitalLetter, kn as CommentUpdateTableRowSchema, kt as syncCommunityRegistryEntry, lr as t$5, lt as retryKuboBlockPutPinAndProvidePubsubTopic, mn as VotePubsubReservedFields, mt as sleepUntilTimeoutOrAbort, nr as e, nt as removeBlocksFromKuboNode, or as t$4, pn as VotePubsubMessagePublicationSchema, q as isLinkOfMedia, r as ChallengeMessageSchema, rn as CommunityIpfsSchema, rr as e$1, rt as removeMfsFilesSafely, s as ChallengeVerificationMessageSchema, t as ChallengeAnswerMessageSchema, tr as t$6, u as DecryptedChallengeRequestPublicationSchema, ur as t$3, vr as PKCError, w as contentContainsMarkdownImages, x as calculateIpfsCidV0, xt as findStartedCommunity, y as version_default, yn as CommentIpfsSchema, yr as messages, yt as writeKuboFilesWithTimeout } from "./schema-mdv9_FG5.js";
3
+ import { $n as crosspostChainDepthUpTo, $t as createSchemaRowParser, A as deriveDbReplies, At as verifyCommentModeration, C as backupCommunityDb, D as deleteOldCommunityInWindows, Et as verifyChallengeRequest, Ft as verifyVote, G as TIMEFRAMES_TO_SECONDS, H as POSTS_SORT_TYPES, It as buildRuntimeAuthor, Kt as decode, L as moveCommunityDbToDeletedDirectory, Lt as cleanWireAuthor, Mt as verifyCommentUpdate, N as getThumbnailPropsOfLink, Nt as verifyCommunity, O as deriveCommentIpfsFromCommentTableRow, Ot as verifyCommentEdit, P as importSignerIntoKuboNode, Pt as verifyCommunityEdit, Qt as getPublicKeyFromPrivateKey, R as resolveDbPostsCidRefs, S as BackupAbortError, Sn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, T as calculateInlineRepliesBudget, Tn as parseJsonWithPKCErrorIfFails, U as POST_REPLIES_SORT_TYPES, Ut as getCommunityNameFromWire, W as REPLY_REPLIES_SORT_TYPES, Wt as getCommunityPublicKeyFromWire, X as iterateOverPageCidsToFindAllCids, Xt as getPKCAddressFromPublicKey, Yt as getIpfsKeyFromPrivateKey, Zt as getPKCAddressFromPublicKeySync, _t as signCommentEdit, a as pkcJsChallenges, ar as n$6, bt as signCommentUpdateForChallengeVerification, cr as t$10, ct as pLimit, dr as require_lodash_merge, dt as cleanUpBeforePublishing, er as effectiveMaxCrosspostDepth, fn as parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails, gt as signComment, h as SignerWithPublicKeyAddress, ht as signChallengeVerification, i as getCommunityChallengeFromCommunityChallengeSettings, ir as t$11, j as getDefaultCommunityDbConfig, jt as verifyCommentPubsubMessage, k as deriveDbPosts, kt as verifyCommentIpfs, l as MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS, lr as stringify, nr as t$12, o as TrackedInstanceRegistry, or as n$5, pt as signChallengeMessage, qt as encode, r as getChallengeVerification, rr as r$2, s as LRUCache, t as RpcLocalCommunity, tr as t$9, u as KeyvBetterSqlite3, un as parseCommunityEditOptionsSchemaWithPKCErrorIfItFails, ur as STORAGE_KEYS, w as calculateExpectedSignatureSize, wt as verifyChallengeAnswer, x as encryptEd25519AesGcmPublicKeyBuffer, xt as signCommunity, y as decryptEd25519AesGcmPublicKeyBuffer, yt as signCommentUpdate, zt as getAuthorNameFromWire } from "./rpc-local-community-a464veDe.js";
4
4
  import { randomFillSync, randomUUID } from "node:crypto";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
- import path from "node:path";
6
+ import Path from "node:path";
7
7
  import os from "os";
8
8
  import { existsSync, promises } from "node:fs";
9
- import path$1 from "path";
9
+ import path from "path";
10
10
  import assert from "assert";
11
11
  import fs from "fs";
12
12
  import Database from "better-sqlite3";
@@ -1304,6 +1304,11 @@ async function checkCommentPublication(community, request) {
1304
1304
  const parentsOfComment = community._dbHandler.queryParentsCids({ parentCid: commentPublication.parentCid });
1305
1305
  if (parentsOfComment[parentsOfComment.length - 1].cid !== commentPublication.postCid) return messages.ERR_REPLY_POST_CID_IS_NOT_PARENT_OF_REPLY;
1306
1306
  }
1307
+ if (commentPublication.crosspost) {
1308
+ if (community.features?.noCrossposts) return messages.ERR_NOT_ALLOWED_TO_PUBLISH_CROSSPOSTS;
1309
+ const maxDepth = effectiveMaxCrosspostDepth(community.features?.maxCrosspostDepth);
1310
+ if (crosspostChainDepthUpTo(commentPublication, maxDepth + 1) > maxDepth) return messages.ERR_CROSSPOST_CHAIN_EXCEEDS_COMMUNITY_MAX_DEPTH;
1311
+ }
1307
1312
  if (commentPublication.quotedCids && commentPublication.quotedCids.length > 0) {
1308
1313
  if (!commentPublication.parentCid) return messages.ERR_POST_CANNOT_HAVE_QUOTED_CIDS;
1309
1314
  const threadPostCid = commentPublication.postCid;
@@ -3169,6 +3174,7 @@ var DbHandler = class {
3169
3174
  this._community = community;
3170
3175
  this._transactionDepth = 0;
3171
3176
  this._createdTables = false;
3177
+ this._columnNamesByTable = {};
3172
3178
  hideClassPrivateProps(this);
3173
3179
  }
3174
3180
  _parsePrefixedComment(row) {
@@ -3209,6 +3215,7 @@ var DbHandler = class {
3209
3215
  await this.initDbConfigIfNeeded();
3210
3216
  const dbFilePath = this._dbConfig.filename;
3211
3217
  if (!this._db || !this._db.open) {
3218
+ this._columnNamesByTable = {};
3212
3219
  this._db = new Database(dbFilePath, {
3213
3220
  ...this._dbConfig,
3214
3221
  ...dbConfigOptions
@@ -3336,6 +3343,7 @@ var DbHandler = class {
3336
3343
  nsfw INTEGER NULLABLE, -- BOOLEAN (0/1)
3337
3344
  pseudonymityMode TEXT NULLABLE,
3338
3345
  quotedCids TEXT NULLABLE, -- JSON array
3346
+ crosspost TEXT NULLABLE, -- JSON: {cid, comment} of the comment this one reposts, stored verbatim so the embedded record keeps reproducing its cid
3339
3347
  extraProps TEXT NULLABLE, -- JSON
3340
3348
  challengeCommentUpdate TEXT NULLABLE, -- JSON: challenge-supplied partial CommentUpdate seeded into queryCalculatedCommentUpdate with lowest priority
3341
3349
  protocolVersion TEXT NOT NULL,
@@ -3473,9 +3481,9 @@ var DbHandler = class {
3473
3481
  if (needToMigrate) {
3474
3482
  if (dbExistsAlready && currentDbVersion > 0) {
3475
3483
  this.destoryConnection();
3476
- backupDbPath = path$1.join(path$1.dirname(dbPath), ".backup_before_migration", `${path$1.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
3477
- log(`Copying db ${path$1.basename(dbPath)} to ${backupDbPath} before migration`);
3478
- if (!fs.existsSync(path$1.dirname(backupDbPath))) await fs.promises.mkdir(path$1.dirname(backupDbPath), { recursive: true });
3484
+ backupDbPath = path.join(path.dirname(dbPath), ".backup_before_migration", `${path.basename(dbPath)}.${currentDbVersion}.${timestamp()}`);
3485
+ log(`Copying db ${path.basename(dbPath)} to ${backupDbPath} before migration`);
3486
+ if (!fs.existsSync(path.dirname(backupDbPath))) await fs.promises.mkdir(path.dirname(backupDbPath), { recursive: true });
3479
3487
  const sourceDb = new Database(dbPath, { fileMustExist: true });
3480
3488
  await sourceDb.backup(backupDbPath);
3481
3489
  sourceDb.close();
@@ -3492,6 +3500,7 @@ var DbHandler = class {
3492
3500
  ]) this._db.exec(`DROP TABLE IF EXISTS ${tableName}`);
3493
3501
  this._db.exec(`DROP TABLE IF EXISTS ${TABLES.COMMENT_UPDATES}`);
3494
3502
  }
3503
+ this._columnNamesByTable = {};
3495
3504
  const createTableFunctions = [
3496
3505
  this._createCommentsTable.bind(this),
3497
3506
  this._createCommentUpdatesTable.bind(this),
@@ -3551,6 +3560,7 @@ var DbHandler = class {
3551
3560
  const newDbVersion = this.getDbVersion();
3552
3561
  assert.equal(newDbVersion, version_default.DB_VERSION);
3553
3562
  this._createdTables = true;
3563
+ this._columnNamesByTable = {};
3554
3564
  if (needToMigrate) log(`Created/migrated the tables to the latest (${newDbVersion}) version and saved to path`, this._dbConfig.filename);
3555
3565
  if (backupDbPath) await fs.promises.rm(backupDbPath);
3556
3566
  }
@@ -3631,6 +3641,11 @@ var DbHandler = class {
3631
3641
  _getColumnNames(tableName) {
3632
3642
  return this._db.pragma(`table_info(${tableName})`).map((col) => col.name);
3633
3643
  }
3644
+ _existingColumns(tableName, columns) {
3645
+ if (!this._columnNamesByTable[tableName]) this._columnNamesByTable[tableName] = this._getColumnNames(tableName);
3646
+ const existing = this._columnNamesByTable[tableName];
3647
+ return columns.filter((column) => existing.includes(column));
3648
+ }
3634
3649
  async _copyTable(srcTable, dstTable, currentDbVersion) {
3635
3650
  const log = logger_default("pkc-js:local-community:db-handler:createTablesIfNeeded:copyTable");
3636
3651
  const dstTableColumns = this._getColumnNames(dstTable);
@@ -3862,8 +3877,8 @@ var DbHandler = class {
3862
3877
  const columnNames = this._getColumnNames(TABLES.COMMENTS);
3863
3878
  const stmt = this._db.prepare(`
3864
3879
  INSERT INTO ${TABLES.COMMENTS}
3865
- (cid, authorSignerAddress, author, link, linkWidth, linkHeight, thumbnailUrl, thumbnailUrlWidth, thumbnailUrlHeight, parentCid, postCid, previousCid, communityPublicKey, communityName, content, timestamp, signature, originalCommentSignatureEncoded, title, depth, linkHtmlTagName, flairs, spoiler, pendingApproval, number, postNumber, nsfw, pseudonymityMode, quotedCids, extraProps, challengeCommentUpdate, protocolVersion, insertedAt)
3866
- VALUES (@cid, @authorSignerAddress, @author, @link, @linkWidth, @linkHeight, @thumbnailUrl, @thumbnailUrlWidth, @thumbnailUrlHeight, @parentCid, @postCid, @previousCid, @communityPublicKey, @communityName, @content, @timestamp, @signature, @originalCommentSignatureEncoded, @title, @depth, @linkHtmlTagName, @flairs, @spoiler, @pendingApproval, @number, @postNumber, @nsfw, @pseudonymityMode, @quotedCids, @extraProps, @challengeCommentUpdate, @protocolVersion, @insertedAt)
3880
+ (cid, authorSignerAddress, author, link, linkWidth, linkHeight, thumbnailUrl, thumbnailUrlWidth, thumbnailUrlHeight, parentCid, postCid, previousCid, communityPublicKey, communityName, content, timestamp, signature, originalCommentSignatureEncoded, title, depth, linkHtmlTagName, flairs, spoiler, pendingApproval, number, postNumber, nsfw, pseudonymityMode, quotedCids, crosspost, extraProps, challengeCommentUpdate, protocolVersion, insertedAt)
3881
+ VALUES (@cid, @authorSignerAddress, @author, @link, @linkWidth, @linkHeight, @thumbnailUrl, @thumbnailUrlWidth, @thumbnailUrlHeight, @parentCid, @postCid, @previousCid, @communityPublicKey, @communityName, @content, @timestamp, @signature, @originalCommentSignatureEncoded, @title, @depth, @linkHtmlTagName, @flairs, @spoiler, @pendingApproval, @number, @postNumber, @nsfw, @pseudonymityMode, @quotedCids, @crosspost, @extraProps, @challengeCommentUpdate, @protocolVersion, @insertedAt)
3867
3882
  `);
3868
3883
  const defaults = t$7(columnNames, (column) => [column, null]);
3869
3884
  this._db.transaction((items) => {
@@ -4176,8 +4191,8 @@ var DbHandler = class {
4176
4191
  }));
4177
4192
  }
4178
4193
  resolveRepliesCidRefsForEntries(entries) {
4179
- const commentUpdateCols = t$6(CommentUpdateSchema.shape);
4180
- const commentIpfsCols = [...t$6(CommentIpfsSchema.shape), "extraProps"];
4194
+ const commentUpdateCols = this._existingColumns(TABLES.COMMENT_UPDATES, t$6(CommentUpdateSchema.shape));
4195
+ const commentIpfsCols = this._existingColumns(TABLES.COMMENTS, [...t$6(CommentIpfsSchema.shape), "extraProps"]);
4181
4196
  const allCids = [];
4182
4197
  for (const entry of entries) {
4183
4198
  const replies = entry.commentUpdate.replies;
@@ -4295,9 +4310,9 @@ var DbHandler = class {
4295
4310
  queryCommentAndCommentUpdateByCids(cids, opts) {
4296
4311
  if (cids.length === 0) return [];
4297
4312
  const placeholders = cids.map(() => "?").join(",");
4298
- const commentUpdateSelects = opts.commentUpdateCols.map((col) => `cu.${col} AS commentUpdate_${col}`);
4313
+ const commentUpdateSelects = this._existingColumns(TABLES.COMMENT_UPDATES, opts.commentUpdateCols).map((col) => `cu.${col} AS commentUpdate_${col}`);
4299
4314
  const queryStr = `
4300
- SELECT ${opts.commentIpfsCols.map((col) => `c.${col} AS commentIpfs_${col}`).join(", ")}, ${commentUpdateSelects.join(", ")}
4315
+ SELECT ${this._existingColumns(TABLES.COMMENTS, opts.commentIpfsCols).map((col) => `c.${col} AS commentIpfs_${col}`).join(", ")}, ${commentUpdateSelects.join(", ")}
4301
4316
  FROM ${TABLES.COMMENTS} c
4302
4317
  INNER JOIN ${TABLES.COMMENT_UPDATES} cu ON c.cid = cu.cid
4303
4318
  WHERE c.cid IN (${placeholders})
@@ -5286,10 +5301,10 @@ var DbHandler = class {
5286
5301
  if (this._db || this._keyv) await this.destoryConnection();
5287
5302
  this._transactionDepth = 0;
5288
5303
  const dataPath = this._community._pkc.dataPath;
5289
- const oldPathString = path$1.join(dataPath, "communities", oldDbName);
5290
- const newPathString = path$1.join(dataPath, "communities", newDbName);
5291
- await fs.promises.mkdir(path$1.dirname(oldPathString), { recursive: true });
5292
- await fs.promises.mkdir(path$1.dirname(newPathString), { recursive: true });
5304
+ const oldPathString = path.join(dataPath, "communities", oldDbName);
5305
+ const newPathString = path.join(dataPath, "communities", newDbName);
5306
+ await fs.promises.mkdir(path.dirname(oldPathString), { recursive: true });
5307
+ await fs.promises.mkdir(path.dirname(newPathString), { recursive: true });
5293
5308
  try {
5294
5309
  if (!fs.existsSync(oldPathString)) log(`Old DB file ${oldPathString} does not exist. Cannot backup/rename.`);
5295
5310
  else {
@@ -5311,8 +5326,8 @@ var DbHandler = class {
5311
5326
  }
5312
5327
  async lockCommunityStart(communityAddress = this._community.address) {
5313
5328
  const log = logger_default("pkc-js:local-community:db-handler:lock:start");
5314
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
5315
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
5329
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
5330
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
5316
5331
  try {
5317
5332
  await import_src.default.lock(communityDbPath, {
5318
5333
  lockfilePath,
@@ -5333,8 +5348,8 @@ var DbHandler = class {
5333
5348
  async unlockCommunityStart(communityAddress = this._community.address) {
5334
5349
  const log = logger_default("pkc-js:local-community:db-handler:unlock:start");
5335
5350
  log.trace(`Attempting to unlock the start of community (${communityAddress})`);
5336
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
5337
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
5351
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
5352
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
5338
5353
  if (!fs.existsSync(lockfilePath) || !fs.existsSync(communityDbPath)) return;
5339
5354
  try {
5340
5355
  await import_src.default.unlock(communityDbPath, { lockfilePath });
@@ -5345,8 +5360,8 @@ var DbHandler = class {
5345
5360
  }
5346
5361
  }
5347
5362
  async isCommunityStartLocked(communityAddress = this._community.address) {
5348
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
5349
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", communityAddress);
5363
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${communityAddress}.start.lock`);
5364
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", communityAddress);
5350
5365
  return await import_src.default.check(communityDbPath, {
5351
5366
  lockfilePath,
5352
5367
  realpath: false,
@@ -5355,8 +5370,8 @@ var DbHandler = class {
5355
5370
  }
5356
5371
  async lockCommunityState() {
5357
5372
  const log = logger_default("pkc-js:local-community:db-handler:lock:lockCommunityState");
5358
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
5359
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
5373
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
5374
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
5360
5375
  try {
5361
5376
  await import_src.default.lock(communityDbPath, {
5362
5377
  lockfilePath,
@@ -5373,8 +5388,8 @@ var DbHandler = class {
5373
5388
  }
5374
5389
  async unlockCommunityState() {
5375
5390
  const log = logger_default("pkc-js:local-community:db-handler:lock:unlockCommunityState");
5376
- const lockfilePath = path$1.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
5377
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
5391
+ const lockfilePath = path.join(this._community._pkc.dataPath, "communities", `${this._community.address}.state.lock`);
5392
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
5378
5393
  if (!fs.existsSync(lockfilePath)) return;
5379
5394
  try {
5380
5395
  await import_src.default.unlock(communityDbPath, { lockfilePath });
@@ -5384,7 +5399,7 @@ var DbHandler = class {
5384
5399
  }
5385
5400
  }
5386
5401
  communityDbExists() {
5387
- const communityDbPath = path$1.join(this._community._pkc.dataPath, "communities", this._community.address);
5402
+ const communityDbPath = path.join(this._community._pkc.dataPath, "communities", this._community.address);
5388
5403
  return fs.existsSync(communityDbPath);
5389
5404
  }
5390
5405
  markCommentsAsPublishedToPostUpdates(commentCids) {
@@ -7103,11 +7118,11 @@ async function edit(community, newCommunityOptions) {
7103
7118
  const EXPORTS_KEY = STORAGE_KEYS[STORAGE_KEYS.EXPORTS];
7104
7119
  function defaultExportPathFor(community, exportId) {
7105
7120
  if (typeof community._pkc.dataPath !== "string") throw new PKCError("ERR_DATA_PATH_IS_NOT_DEFINED", { communityAddress: community.address });
7106
- return path.join(community._pkc.dataPath, "exports", `${exportId}.sqlite`);
7121
+ return Path.join(community._pkc.dataPath, "exports", `${exportId}.sqlite`);
7107
7122
  }
7108
7123
  function sourceDbPathFor(community) {
7109
7124
  if (typeof community._pkc.dataPath !== "string") throw new PKCError("ERR_DATA_PATH_IS_NOT_DEFINED", { communityAddress: community.address });
7110
- return path.join(community._pkc.dataPath, "communities", community.address);
7125
+ return Path.join(community._pkc.dataPath, "communities", community.address);
7111
7126
  }
7112
7127
  async function persistExports(community) {
7113
7128
  if (!community._dbHandler) return;
@@ -7183,9 +7198,9 @@ async function runExportTask(community, exportId, opts) {
7183
7198
  async function exportCommunityEmbedded(community, options = {}) {
7184
7199
  if (options.signal?.aborted) throw options.signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
7185
7200
  const exportId = v4();
7186
- const destPath = options.exportPath ? path.resolve(options.exportPath) : defaultExportPathFor(community, exportId);
7201
+ const destPath = options.exportPath ? Path.resolve(options.exportPath) : defaultExportPathFor(community, exportId);
7187
7202
  const includePrivateKey = options.includePrivateKey === true;
7188
- if (path.resolve(destPath) === path.resolve(sourceDbPathFor(community))) throw new PKCError("ERR_EXPORT_PATH_TARGETS_LIVE_DB", {
7203
+ if (Path.resolve(destPath) === Path.resolve(sourceDbPathFor(community))) throw new PKCError("ERR_EXPORT_PATH_TARGETS_LIVE_DB", {
7189
7204
  communityAddress: community.address,
7190
7205
  exportPath: destPath
7191
7206
  });
@@ -1,7 +1,7 @@
1
1
  import { i as __toESM, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $n as n$1, B as isIpfsCid, Cr as setErrorMap, Ct as findUpdatingCommunity, D as deepMergeRuntimeFields, Dn as CommentUpdateSchema, Dt as refreshTrackedCommentAliases, E as createAbortError, Et as listUpdatingCommunities, Fr as parsedType, H as isIpns, Ir as stringifyPrimitive, It as require_sha256, L as hideClassPrivateProps, Lt as TimeoutError, Pr as joinValues, Pt as untrackUpdatingComment, Q as isStringDomain, Qt as CommunityAnchorSchema, R as ipnsNameToIpnsOverPubsubTopic, Rt as pTimeout, St as findUpdatingComment, Tt as listUpdatingComments, Zn as n$2, _t as timestamp, a as ChallengeRequestMessageSchema, ar as r, b as areEquivalentCommunityAddresses, br as logger_default, ct as resolveWhenPredicateIsTrue, fr as require_retry, ft as shortifyAddress, jt as trackUpdatingComment, k as doesDomainAddressHaveCapitalLetter, ln as PubsubTopicSchema, mt as sleepUntilTimeoutOrAbort, nr as e, ot as removeUndefinedValuesRecursively, pr as FailedToFetchCommentIpfsFromGatewaysError, pt as shortifyCid, r as ChallengeMessageSchema, rn as CommunityIpfsSchema, rr as e$1, s as ChallengeVerificationMessageSchema, st as replaceXWithY, t as ChallengeAnswerMessageSchema, tr as t$1, ut as retryKuboIpfsAdd, vr as PKCError, vt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, wn as CommentUpdateForChallengeVerificationSchema, wt as listStartedCommunities, xt as findStartedCommunity, y as version_default, yn as CommentIpfsSchema, yr as messages, z as isAbortError } from "./schema-DZyEx0YQ.js";
3
- import { $ as PublicationClientsManager, $t as parseCommentIpfsSchemaWithPKCErrorIfItFails, An as RpcCidParamSchema, At as verifyVote, B as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, Bn as RpcFetchCidResultSchema, Bt as normalizeCommunityInputFromCommunity, Cn as parseRpcCommentUpdateEventWithPKCErrorIfItFails, Ct as verifyCommentEdit, Dn as RpcAnchorPublishPreparationResultSchema, Dt as verifyCommentUpdate, E as createKuboRpcClient, En as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, Et as verifyCommentPubsubMessage, F as listCommunitiesSync, Fn as RpcExportCommunityModLogsParamSchema, Ft as normalizeCreatePublicationAuthor, Gn as RpcSubscriptionIdResultSchema, Hn as RpcPublishChallengeAnswersParamSchema, I as monitorCommunitiesDirectory, In as RpcExportCommunityModLogsResultSchema, It as buildRuntimeCommunityFields, J as extractCommunityRuntimeFieldsFromParsedPages, Jn as t$4, Kn as RpcSuccessResultSchema, Kt as getPKCAddressFromPublicKeySync, Ln as RpcExportCommunityParamSchema, Lt as getCommunityAddressFromRecord, M as getDefaultDataPath, Mn as RpcCommunityIdentifierParamSchema, Mt as cleanWireAuthor, Nn as RpcCommunityPageParamSchema, Nt as getAuthorNameFromRuntime, On as RpcAuthorNameParamSchema, Pn as RpcEditCommunityParamSchema, Q as RepliesPages, Qn as n$3, Qt as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, Rn as RpcExportCommunityResultSchema, Rt as getCommunityNameFromWire, Sn as parseRpcCommentEventWithPKCErrorIfItFails, St as verifyChallengeVerification, Tt as verifyCommentModeration, Un as RpcPublishedAnchorRecordResultSchema, Ut as getBufferedPKCAddressFromPublicKey, V as CommentClientsManager, Vn as RpcPublishAnchorRecordParamSchema, Vt as decode, Wn as RpcResolveAuthorNameResultSchema, Y as findCommentInPageInstanceRecursively, Yt as parseCidStringSchemaWithPKCErrorIfItFails, Z as parseRawPages, Zn as t$3, _ as createAnchorIpnsRecord$1, _n as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, _t as signCommunityEdit, a as pkcJsChallenges, ar as nativeFunctions$2, at as require_lib$1, b as encryptEd25519AesGcm, bn as parseJsonWithPKCErrorIfFails, bt as verifyChallengeMessage, c as RemoteCommunity, cn as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, d as decodeRpcChallengeAnswerPubsubMsg, dn as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, dt as signComment, er as t$2, et as PKCClientsManager, f as decodeRpcChallengePubsubMsg, ft as signCommentEdit, g as createSigner, gn as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, hn as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, it as PKCTypedEmitter, jn as RpcCommentRepliesPageParamSchema, jt as buildRuntimeAuthor, kn as RpcCancelExportParamSchema, kt as verifyCommunityEdit, ln as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, lt as signChallengeRequest, m as decodeRpcChallengeVerificationPubsubMsg, mn as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, n as RpcRemoteCommunity, nn as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, o as TrackedInstanceRegistry, on as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, or as require_undici, ot as cleanUpBeforePublishing, p as decodeRpcChallengeRequestPubsubMsg, pt as signCommentModeration, qn as RpcUnsubscribeParamSchema, rn as parseCommunityAddressWithPKCErrorIfItFails, s as LRUCache, st as signChallengeAnswer, t as RpcLocalCommunity, tn as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, tr as t$5, tt as InflightFetchManager, u as KeyvBetterSqlite3, un as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, v as decryptEd25519AesGcm, vn as parseDecryptedChallengeVerification, vt as signVote, wn as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, wt as verifyCommentIpfs, xn as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, yn as parseDecryptedChallengeWithPKCErrorIfItFails, z as setNativeFunctions$1, zn as RpcFetchCidParamSchema, zt as getCommunityPublicKeyFromWire } from "./rpc-local-community-BOiy8BX1.js";
4
- import { o as getHeliaDebugContext } from "./util-BTPlI1yF.js";
2
+ import { $n as n$1, B as isIpfsCid, Cr as setErrorMap, Ct as findUpdatingCommunity, D as deepMergeRuntimeFields, Dn as CommentUpdateSchema, Dt as refreshTrackedCommentAliases, E as createAbortError, Et as listUpdatingCommunities, Fr as parsedType, H as isIpns, Ir as stringifyPrimitive, It as require_sha256, L as hideClassPrivateProps, Lt as TimeoutError, Pr as joinValues, Pt as untrackUpdatingComment, Q as isStringDomain, Qt as CommunityAnchorSchema, R as ipnsNameToIpnsOverPubsubTopic, Rt as pTimeout, St as findUpdatingComment, Tt as listUpdatingComments, Zn as n$2, _t as timestamp, a as ChallengeRequestMessageSchema, ar as r, b as areEquivalentCommunityAddresses, br as logger_default, ct as resolveWhenPredicateIsTrue, fr as require_retry, ft as shortifyAddress, jt as trackUpdatingComment, k as doesDomainAddressHaveCapitalLetter, ln as PubsubTopicSchema, mt as sleepUntilTimeoutOrAbort, nr as e, ot as removeUndefinedValuesRecursively, pr as FailedToFetchCommentIpfsFromGatewaysError, pt as shortifyCid, r as ChallengeMessageSchema, rn as CommunityIpfsSchema, rr as e$1, s as ChallengeVerificationMessageSchema, st as replaceXWithY, t as ChallengeAnswerMessageSchema, tr as t$1, ut as retryKuboIpfsAdd, vr as PKCError, vt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, wn as CommentUpdateForChallengeVerificationSchema, wt as listStartedCommunities, xt as findStartedCommunity, y as version_default, yn as CommentIpfsSchema, yr as messages, z as isAbortError } from "./schema-mdv9_FG5.js";
3
+ import { $ as applyNameResolvedCacheToCrosspost, At as verifyCommentModeration, B as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, Bn as RpcExportCommunityModLogsParamSchema, Bt as normalizeCreatePublicationAuthor, Cn as parseDecryptedChallengeVerification, Ct as signVote, Dn as parseRpcCommentEventWithPKCErrorIfItFails, Dt as verifyChallengeVerification, E as createKuboRpcClient, En as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, F as listCommunitiesSync, Fn as RpcCidParamSchema, Ft as verifyVote, Gn as RpcFetchCidResultSchema, Gt as normalizeCommunityInputFromCommunity, Hn as RpcExportCommunityParamSchema, Ht as getCommunityAddressFromRecord, I as monitorCommunitiesDirectory, In as RpcCommentRepliesPageParamSchema, It as buildRuntimeAuthor, J as extractCommunityRuntimeFieldsFromParsedPages, Jn as RpcPublishedAnchorRecordResultSchema, Jt as getBufferedPKCAddressFromPublicKey, Kn as RpcPublishAnchorRecordParamSchema, Kt as decode, Ln as RpcCommunityIdentifierParamSchema, Lt as cleanWireAuthor, M as getDefaultDataPath, Mn as RpcAnchorPublishPreparationResultSchema, Mt as verifyCommentUpdate, Nn as RpcAuthorNameParamSchema, On as parseRpcCommentUpdateEventWithPKCErrorIfItFails, Ot as verifyCommentEdit, Pn as RpcCancelExportParamSchema, Pt as verifyCommunityEdit, Q as RepliesPages, Qn as RpcUnsubscribeParamSchema, Rn as RpcCommunityPageParamSchema, Rt as getAuthorNameFromRuntime, Sn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, St as signCommunityEdit, Tn as parseJsonWithPKCErrorIfFails, Tt as verifyChallengeMessage, Un as RpcExportCommunityResultSchema, Ut as getCommunityNameFromWire, V as CommentClientsManager, Vn as RpcExportCommunityModLogsResultSchema, Vt as buildRuntimeCommunityFields, Wn as RpcFetchCidParamSchema, Wt as getCommunityPublicKeyFromWire, Xn as RpcSubscriptionIdResultSchema, Y as findCommentInPageInstanceRecursively, Yn as RpcResolveAuthorNameResultSchema, Z as parseRawPages, Zn as RpcSuccessResultSchema, Zt as getPKCAddressFromPublicKeySync, _ as createAnchorIpnsRecord$1, _t as signCommentEdit, a as pkcJsChallenges, ar as n$3, at as PKCClientsManager, b as encryptEd25519AesGcm, bn as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, c as RemoteCommunity, cn as parseCommunityAddressWithPKCErrorIfItFails, cr as t$5, d as decodeRpcChallengeAnswerPubsubMsg, dn as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, dt as cleanUpBeforePublishing, en as parseCidStringSchemaWithPKCErrorIfItFails, et as cloneCrosspostForRuntime, f as decodeRpcChallengePubsubMsg, fr as nativeFunctions$2, ft as signChallengeAnswer, g as createSigner, gn as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, gt as signComment, hn as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, in as parseCommentIpfsSchemaWithPKCErrorIfItFails, ir as t$3, it as PublicationClientsManager, jn as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, jt as verifyCommentPubsubMessage, kn as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, kt as verifyCommentIpfs, lt as PKCTypedEmitter, m as decodeRpcChallengeVerificationPubsubMsg, mn as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, mt as signChallengeRequest, n as RpcRemoteCommunity, o as TrackedInstanceRegistry, on as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, ot as InflightFetchManager, p as decodeRpcChallengeRequestPubsubMsg, pn as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, pr as require_undici, qn as RpcPublishChallengeAnswersParamSchema, rn as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, rt as stripNameResolvedFromCrosspost, s as LRUCache, sn as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, sr as t$2, t as RpcLocalCommunity, tr as t$4, tt as collectCrosspostAuthorsToResolve, u as KeyvBetterSqlite3, ut as require_lib$1, v as decryptEd25519AesGcm, vt as signCommentModeration, wn as parseDecryptedChallengeWithPKCErrorIfItFails, xn as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, yn as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, z as setNativeFunctions$1, zn as RpcEditCommunityParamSchema } from "./rpc-local-community-a464veDe.js";
4
+ import { o as getHeliaDebugContext } from "./util-y9-A9BnM.js";
5
5
  import path from "path";
6
6
  import assert from "assert";
7
7
  import fs from "fs";
@@ -637,17 +637,24 @@ var Publication = class extends import_lib.TypedEmitter {
637
637
  if (cachedCommunity) {
638
638
  if (!this._pkc._memCaches.communityForPublishing.has(this.communityAddress)) {
639
639
  log("The cache of community is stale, we will use the cached and update in the background");
640
- this._pkc.getCommunity({
640
+ const refresh = this._pkc.getCommunity({
641
641
  publicKey: this.communityPublicKey,
642
642
  name: this.communityName
643
- }).catch((e) => log.error("Failed to update cache of community", this.communityAddress, e));
643
+ }).catch((e) => log.error("Failed to update cache of community", this.communityAddress, e)).finally(() => {
644
+ if (this._backgroundCommunityRefresh === refresh) this._backgroundCommunityRefresh = void 0;
645
+ });
646
+ this._backgroundCommunityRefresh = refresh;
644
647
  }
645
648
  return cachedCommunity;
646
649
  } else return this._clientsManager.fetchCommunityForPublishingWithCacheGuard();
647
650
  }
648
651
  async stop() {
649
- await this._postSucessOrFailurePublishing();
650
- this._updatePublishingStateWithEmission("stopped");
652
+ try {
653
+ await this._postSucessOrFailurePublishing();
654
+ } finally {
655
+ if (this._backgroundCommunityRefresh) await this._backgroundCommunityRefresh;
656
+ this._updatePublishingStateWithEmission("stopped");
657
+ }
651
658
  }
652
659
  _isAllAttemptsExhausted(maxNumOfChallengeExchanges) {
653
660
  if (Object.keys(this._challengeExchanges).length !== maxNumOfChallengeExchanges) return false;
@@ -656,8 +663,26 @@ var Publication = class extends import_lib.TypedEmitter {
656
663
  return typeof exchange.challengeRequestPublishTimestamp === "number" && exchange.challengeRequestPublishTimestamp + this._setProviderFailureThresholdSeconds <= timestamp();
657
664
  });
658
665
  }
666
+ async _abandonProviderIfStoppedWhileSubscribing(providerUrl) {
667
+ if (!this._pkc.destroyed && this.state !== "stopped") return false;
668
+ const log = logger_default("pkc-js:publication:publish:_abandonProviderIfStoppedWhileSubscribing");
669
+ log("Publication was stopped while subscribing to pubsub, will not publish a challenge request", providerUrl);
670
+ try {
671
+ await this._clientsManager.pubsubUnsubscribeOnProvider(this._communityChallengePubsubExchangeTopic(), providerUrl, this._handleChallengeExchange);
672
+ } catch (e) {
673
+ log.error("Failed to undo the pubsub subscription that resolved after being stopped", providerUrl, e);
674
+ }
675
+ this._updatePubsubState("stopped", providerUrl);
676
+ return true;
677
+ }
678
+ _unregisterFromPkcOncePublishWorkSettles() {
679
+ const refresh = this._backgroundCommunityRefresh;
680
+ if (refresh) refresh.finally(() => this._pkc._publishingPublications.delete(this));
681
+ else this._pkc._publishingPublications.delete(this);
682
+ }
659
683
  async _postSucessOrFailurePublishing() {
660
684
  const log = logger_default("pkc-js:publication:_postSucessOrFailurePublishing");
685
+ this._unregisterFromPkcOncePublishWorkSettles();
661
686
  this._setStateWithEmission("stopped");
662
687
  if (this._rpcPublishSubscriptionId) {
663
688
  try {
@@ -877,6 +902,7 @@ var Publication = class extends import_lib.TypedEmitter {
877
902
  this._updatePubsubState("subscribing-pubsub", providerUrl);
878
903
  try {
879
904
  await this._clientsManager.pubsubSubscribeOnProvider(this._communityChallengePubsubExchangeTopic(), this._handleChallengeExchange, providerUrl);
905
+ if (await this._abandonProviderIfStoppedWhileSubscribing(providerUrl)) return;
880
906
  this._updatePubsubState("publishing-challenge-request", providerUrl);
881
907
  await this._clientsManager.pubsubPublishOnProvider(this._communityChallengePubsubExchangeTopic(), challengeRequest, providerUrl);
882
908
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
@@ -958,8 +984,17 @@ var Publication = class extends import_lib.TypedEmitter {
958
984
  });
959
985
  }
960
986
  async publish() {
961
- const log = logger_default("pkc-js:publication:publish");
962
987
  this._validatePublicationFields();
988
+ this._pkc._publishingPublications.add(this);
989
+ try {
990
+ return await this._publishAfterRegistering();
991
+ } catch (e) {
992
+ this._unregisterFromPkcOncePublishWorkSettles();
993
+ throw e;
994
+ }
995
+ }
996
+ async _publishAfterRegistering() {
997
+ const log = logger_default("pkc-js:publication:publish");
963
998
  this._setStateWithEmission("publishing");
964
999
  await this._initCommunity();
965
1000
  if (this.raw.unsignedPublicationOptions && !this.raw.pubsubMessageToPublish) await this._signPublicationWithCommunityFields();
@@ -998,6 +1033,7 @@ var Publication = class extends import_lib.TypedEmitter {
998
1033
  this._updatePubsubState("subscribing-pubsub", providerUrl);
999
1034
  try {
1000
1035
  await this._clientsManager.pubsubSubscribeOnProvider(this._communityChallengePubsubExchangeTopic(), this._handleChallengeExchange, providerUrl);
1036
+ if (await this._abandonProviderIfStoppedWhileSubscribing(providerUrl)) return;
1001
1037
  this._updatePubsubState("publishing-challenge-request", providerUrl);
1002
1038
  await this._clientsManager.pubsubPublishOnProvider(this._communityChallengePubsubExchangeTopic(), challengeRequest, providerUrl);
1003
1039
  this._challengeExchanges[challengeRequest.challengeRequestId.toString()].challengeRequestPublishTimestamp = timestamp();
@@ -1105,6 +1141,7 @@ var Comment = class extends Publication {
1105
1141
  this.nsfw = o.nsfw;
1106
1142
  this.flairs = o.flairs;
1107
1143
  this.quotedCids = o.quotedCids;
1144
+ this.crosspost = o.crosspost ? cloneCrosspostForRuntime(o.crosspost) : void 0;
1108
1145
  }
1109
1146
  _initLocalProps(props) {
1110
1147
  this._initPubsubMessageProps(props.comment);
@@ -1134,6 +1171,10 @@ var Comment = class extends Publication {
1134
1171
  this._setAuthorNameResolvedFromCache();
1135
1172
  }
1136
1173
  _setAuthorNameResolvedFromCache() {
1174
+ if (this.crosspost) applyNameResolvedCacheToCrosspost({
1175
+ crosspost: this.crosspost,
1176
+ cache: this._pkc._memCaches.nameResolvedCache
1177
+ });
1137
1178
  const domain = getAuthorNameFromRuntime(this.author);
1138
1179
  if (!domain) return;
1139
1180
  const cached = this._pkc._memCaches.nameResolvedCache.get((0, import_sha256.sha256)(domain + this.signature.publicKey));
@@ -1160,14 +1201,19 @@ var Comment = class extends Publication {
1160
1201
  });
1161
1202
  }
1162
1203
  }
1163
- if (ownAuthor.length === 0 && replyAuthors.length === 0) return;
1204
+ const crosspostAuthors = this.crosspost ? collectCrosspostAuthorsToResolve({ crosspost: this.crosspost }) : [];
1205
+ if (ownAuthor.length === 0 && replyAuthors.length === 0 && crosspostAuthors.length === 0) return;
1164
1206
  const previousNameResolved = this.author.nameResolved;
1165
1207
  const onResolved = () => {
1208
+ const crosspostChanged = this.crosspost ? applyNameResolvedCacheToCrosspost({
1209
+ crosspost: this.crosspost,
1210
+ cache: this._pkc._memCaches.nameResolvedCache
1211
+ }) : false;
1166
1212
  this._setAuthorNameResolvedFromCache();
1167
1213
  if (this.replies?.pages) {
1168
1214
  for (const page of Object.values(this.replies.pages)) if (page) this.replies._applyNameResolvedCacheToPage(page);
1169
1215
  }
1170
- if (this.author.nameResolved !== previousNameResolved) this.emit("update", this);
1216
+ if (this.author.nameResolved !== previousNameResolved || crosspostChanged) this.emit("update", this);
1171
1217
  };
1172
1218
  const abortSignal = this._getStopAbortSignal();
1173
1219
  if (ownAuthor.length > 0) this._clientsManager.resolveAuthorNamesInBackground({
@@ -1175,8 +1221,8 @@ var Comment = class extends Publication {
1175
1221
  onResolved,
1176
1222
  abortSignal
1177
1223
  });
1178
- if (replyAuthors.length > 0) this._pkc._clientsManager.resolveAuthorNamesInBackground({
1179
- authors: replyAuthors,
1224
+ if (replyAuthors.length > 0 || crosspostAuthors.length > 0) this._pkc._clientsManager.resolveAuthorNamesInBackground({
1225
+ authors: [...replyAuthors, ...crosspostAuthors],
1180
1226
  onResolved,
1181
1227
  abortSignal
1182
1228
  });
@@ -1194,6 +1240,7 @@ var Comment = class extends Publication {
1194
1240
  this.title = props.title;
1195
1241
  this.linkHtmlTagName = props.linkHtmlTagName;
1196
1242
  this.quotedCids = props.quotedCids;
1243
+ this.crosspost = props.crosspost ? cloneCrosspostForRuntime(props.crosspost) : void 0;
1197
1244
  if ("depth" in props && typeof props.depth === "number") {
1198
1245
  this.depth = props.depth;
1199
1246
  const postCid = props.postCid ? props.postCid : this.cid && this.depth === 0 ? this.cid : void 0;
@@ -6761,6 +6808,7 @@ var PKC$1 = class extends PKCTypedEmitter {
6761
6808
  this._updatingCommunities = new TrackedInstanceRegistry();
6762
6809
  this._updatingComments = new TrackedInstanceRegistry();
6763
6810
  this._startedCommunities = new TrackedInstanceRegistry();
6811
+ this._publishingPublications = /* @__PURE__ */ new Set();
6764
6812
  this.destroyed = false;
6765
6813
  this._storageLRUs = {};
6766
6814
  this._timeouts = {
@@ -6880,7 +6928,7 @@ var PKC$1 = class extends PKCTypedEmitter {
6880
6928
  this.clients.libp2pJsClients = {};
6881
6929
  if (!this.libp2pJsClientsOptions) return;
6882
6930
  if (!this.httpRoutersOptions) throw Error("httpRoutersOptions is required for libp2pJsClient");
6883
- const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-BcNF-orO.js");
6931
+ const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-BtjQ8rfd.js");
6884
6932
  for (const clientOptions of this.libp2pJsClientsOptions) {
6885
6933
  const heliaNode = await createLibp2pJsClientOrUseExistingOne({
6886
6934
  ...clientOptions,
@@ -6980,6 +7028,7 @@ var PKC$1 = class extends PKCTypedEmitter {
6980
7028
  }
6981
7029
  if (e$1(cleanedAuthor)) cleanedAuthor = void 0;
6982
7030
  }
7031
+ if ("crosspost" in finalOptions && finalOptions.crosspost) stripNameResolvedFromCrosspost(finalOptions.crosspost);
6983
7032
  const filledTimestamp = typeof finalOptions.timestamp !== "number" ? timestamp() : finalOptions.timestamp;
6984
7033
  const filledSigner = await this.createSigner(finalOptions.signer);
6985
7034
  const filledProtocolVersion = finalOptions.protocolVersion || version_default.PROTOCOL_VERSION;
@@ -7028,6 +7077,7 @@ var PKC$1 = class extends PKCTypedEmitter {
7028
7077
  if ("commentUpdateFromChallengeVerification" in options.raw && options.raw.commentUpdateFromChallengeVerification) commentInstance._initCommentUpdateFromChallengeVerificationProps(options.raw.commentUpdateFromChallengeVerification);
7029
7078
  if (options.raw.commentUpdate) commentInstance._initCommentUpdate(options.raw.commentUpdate);
7030
7079
  if (commentInstance.author?.nameResolved !== void 0) delete commentInstance.author.nameResolved;
7080
+ if (commentInstance.crosspost) stripNameResolvedFromCrosspost(commentInstance.crosspost);
7031
7081
  return commentInstance;
7032
7082
  }
7033
7083
  async createComment(options) {
@@ -7046,6 +7096,7 @@ var PKC$1 = class extends PKCTypedEmitter {
7046
7096
  if (!("signature" in options)) Object.assign(commentInstance, options);
7047
7097
  else commentInstance._initIpfsProps(parseCommentIpfsSchemaWithPKCErrorIfItFails(commentIpfs));
7048
7098
  if (commentInstance.author?.nameResolved !== void 0) delete commentInstance.author.nameResolved;
7099
+ if (commentInstance.crosspost) stripNameResolvedFromCrosspost(commentInstance.crosspost);
7049
7100
  } else if ("signature" in options) {
7050
7101
  const parsedOptions = parseCommentPubsubMessagePublicationWithPKCErrorIfItFails(options);
7051
7102
  commentInstance._initPubsubMessageProps(parsedOptions);
@@ -7125,7 +7176,7 @@ var PKC$1 = class extends PKCTypedEmitter {
7125
7176
  const log = logger_default("pkc-js:pkc:createLocalCommunity");
7126
7177
  log.trace("Received community options to create a local community instance:", options);
7127
7178
  if (!this._canCreateNewLocalCommunity()) throw new PKCError("ERR_CAN_NOT_CREATE_A_LOCAL_COMMUNITY", { pkcOptions: this._userPKCOptions });
7128
- const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-B6-jaMsn.js");
7179
+ const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-B_Yg8LQH.js");
7129
7180
  const isLocalCommunity = (await listCommunitiesSync(this)).includes(options.address);
7130
7181
  const community = new LocalCommunity(this);
7131
7182
  if (isLocalCommunity) {
@@ -7499,6 +7550,8 @@ var PKC$1 = class extends PKCTypedEmitter {
7499
7550
  }
7500
7551
  }
7501
7552
  if (exportDonePromises.length) await Promise.all(exportDonePromises);
7553
+ await Promise.all([...this._publishingPublications].map((publication) => publication.stop().catch((e) => log.error("Error stopping publication during destroy", e))));
7554
+ this._publishingPublications.clear();
7502
7555
  for (const comment of listUpdatingComments(this)) await comment.stop();
7503
7556
  for (const community of listUpdatingCommunities(this)) await community.stop();
7504
7557
  await Promise.all(listStartedCommunities(this).map((community) => community.stop()));