@pkcprotocol/pkc-js 0.0.80 → 0.0.82

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 (173) 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 +3 -2
  21. package/dist/browser/pkc/pkc.js +37 -24
  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 +14 -2
  45. package/dist/browser/rpc/src/index.js.map +1 -1
  46. package/dist/browser/runtime/browser/setup-kubo-http-routers.d.ts +1 -0
  47. package/dist/browser/runtime/browser/setup-kubo-http-routers.js +4 -0
  48. package/dist/browser/runtime/browser/setup-kubo-http-routers.js.map +1 -0
  49. package/dist/browser/runtime/node/community/db-handler.js +3 -2
  50. package/dist/browser/runtime/node/community/db-handler.js.map +1 -1
  51. package/dist/browser/runtime/node/community/local-community/publication-validation.js +15 -0
  52. package/dist/browser/runtime/node/community/local-community/publication-validation.js.map +1 -1
  53. package/dist/browser/runtime/node/community/local-community/reprovide-on-address-change.d.ts +3 -2
  54. package/dist/browser/runtime/node/community/local-community/reprovide-on-address-change.js +19 -10
  55. package/dist/browser/runtime/node/community/local-community/reprovide-on-address-change.js.map +1 -1
  56. package/dist/browser/runtime/node/community/page-generator.d.ts +2 -0
  57. package/dist/browser/runtime/node/setup-kubo-http-routers.d.ts +2 -0
  58. package/dist/browser/runtime/node/{setup-kubo-address-rewriter-and-http-router.js → setup-kubo-http-routers.js} +54 -112
  59. package/dist/browser/runtime/node/setup-kubo-http-routers.js.map +1 -0
  60. package/dist/browser/schema/schema-util.d.ts +17 -0
  61. package/dist/browser/schema/schema-util.js +49 -5
  62. package/dist/browser/schema/schema-util.js.map +1 -1
  63. package/dist/browser/signer/signatures.d.ts +1 -10
  64. package/dist/browser/signer/signatures.js +83 -0
  65. package/dist/browser/signer/signatures.js.map +1 -1
  66. package/dist/browser/test/test-util.d.ts +6 -0
  67. package/dist/browser/util.d.ts +3 -4
  68. package/dist/browser/util.js +7 -3
  69. package/dist/browser/util.js.map +1 -1
  70. package/dist/browser/version.js +1 -1
  71. package/dist/bundled/bundle-manifest.json +78 -93
  72. package/dist/bundled/chunks/{helia-for-pkc-BsYWQ7qS.js → helia-for-pkc-CQY3-UYD.js} +31 -31
  73. package/dist/bundled/chunks/{local-community-EqWKTLxr.js → local-community-AZAEiiht.js} +1 -1
  74. package/dist/bundled/chunks/{local-community-CHzhypCp.js → local-community-DRm3r1-Y.js} +16 -6
  75. package/dist/bundled/chunks/{node-4qAZNuJG.js → node-B1J8psGZ.js} +380 -2372
  76. package/dist/bundled/chunks/{rpc-local-community-Cog5rZLG.js → rpc-local-community-0XmKyOdO.js} +298 -580
  77. package/dist/bundled/chunks/{schema-Iavj-cRD.js → schema-BUUhufdT.js} +26 -11
  78. package/dist/bundled/chunks/{util-CfSUfLkV.js → util-Cct7-RT3.js} +1 -1
  79. package/dist/bundled/index.js +1 -1
  80. package/dist/bundled/rpc/src/index.js +13 -5
  81. package/dist/node/clients/base-client-manager.js +19 -1
  82. package/dist/node/clients/base-client-manager.js.map +1 -1
  83. package/dist/node/clients/rpc-client/rpc-schema-util.d.ts +1 -0
  84. package/dist/node/clients/rpc-client/schema.d.ts +3 -0
  85. package/dist/node/community/schema.d.ts +24 -0
  86. package/dist/node/community/schema.js +6 -1
  87. package/dist/node/community/schema.js.map +1 -1
  88. package/dist/node/errors.d.ts +10 -1
  89. package/dist/node/errors.js +10 -1
  90. package/dist/node/errors.js.map +1 -1
  91. package/dist/node/generated-version.d.ts +1 -1
  92. package/dist/node/generated-version.js +1 -1
  93. package/dist/node/pages/pages.js +8 -0
  94. package/dist/node/pages/pages.js.map +1 -1
  95. package/dist/node/pages/schema.d.ts +4 -0
  96. package/dist/node/pages/util.d.ts +2 -0
  97. package/dist/node/pages/util.js +23 -3
  98. package/dist/node/pages/util.js.map +1 -1
  99. package/dist/node/pkc/pkc.d.ts +3 -2
  100. package/dist/node/pkc/pkc.js +37 -24
  101. package/dist/node/pkc/pkc.js.map +1 -1
  102. package/dist/node/pkc-error.d.ts +1 -1
  103. package/dist/node/publications/comment/comment-client-manager.js +22 -4
  104. package/dist/node/publications/comment/comment-client-manager.js.map +1 -1
  105. package/dist/node/publications/comment/comment.d.ts +2 -1
  106. package/dist/node/publications/comment/comment.js +29 -6
  107. package/dist/node/publications/comment/comment.js.map +1 -1
  108. package/dist/node/publications/comment/crosspost-depth.d.ts +5 -0
  109. package/dist/node/publications/comment/crosspost-depth.js +75 -0
  110. package/dist/node/publications/comment/crosspost-depth.js.map +1 -0
  111. package/dist/node/publications/comment/crosspost-runtime.d.ts +30 -0
  112. package/dist/node/publications/comment/crosspost-runtime.js +133 -0
  113. package/dist/node/publications/comment/crosspost-runtime.js.map +1 -0
  114. package/dist/node/publications/comment/schema.d.ts +20 -2
  115. package/dist/node/publications/comment/schema.js +21 -10
  116. package/dist/node/publications/comment/schema.js.map +1 -1
  117. package/dist/node/publications/comment/types.d.ts +10 -0
  118. package/dist/node/publications/community-edit/schema.d.ts +4 -0
  119. package/dist/node/publications/publication.d.ts +4 -0
  120. package/dist/node/publications/publication.js +80 -5
  121. package/dist/node/publications/publication.js.map +1 -1
  122. package/dist/node/pubsub-messages/schema.d.ts +5 -0
  123. package/dist/node/rpc/src/index.js +14 -2
  124. package/dist/node/rpc/src/index.js.map +1 -1
  125. package/dist/node/runtime/browser/setup-kubo-http-routers.d.ts +1 -0
  126. package/dist/node/runtime/browser/setup-kubo-http-routers.js +4 -0
  127. package/dist/node/runtime/browser/setup-kubo-http-routers.js.map +1 -0
  128. package/dist/node/runtime/node/community/db-handler.js +3 -2
  129. package/dist/node/runtime/node/community/db-handler.js.map +1 -1
  130. package/dist/node/runtime/node/community/local-community/publication-validation.js +15 -0
  131. package/dist/node/runtime/node/community/local-community/publication-validation.js.map +1 -1
  132. package/dist/node/runtime/node/community/local-community/reprovide-on-address-change.d.ts +3 -2
  133. package/dist/node/runtime/node/community/local-community/reprovide-on-address-change.js +19 -10
  134. package/dist/node/runtime/node/community/local-community/reprovide-on-address-change.js.map +1 -1
  135. package/dist/node/runtime/node/community/page-generator.d.ts +2 -0
  136. package/dist/node/runtime/node/setup-kubo-http-routers.d.ts +2 -0
  137. package/dist/node/runtime/node/{setup-kubo-address-rewriter-and-http-router.js → setup-kubo-http-routers.js} +54 -112
  138. package/dist/node/runtime/node/setup-kubo-http-routers.js.map +1 -0
  139. package/dist/node/schema/schema-util.d.ts +17 -0
  140. package/dist/node/schema/schema-util.js +49 -5
  141. package/dist/node/schema/schema-util.js.map +1 -1
  142. package/dist/node/signer/signatures.d.ts +1 -10
  143. package/dist/node/signer/signatures.js +83 -0
  144. package/dist/node/signer/signatures.js.map +1 -1
  145. package/dist/node/test/test-util.d.ts +6 -0
  146. package/dist/node/util.d.ts +3 -4
  147. package/dist/node/util.js +7 -3
  148. package/dist/node/util.js.map +1 -1
  149. package/dist/node/version.js +1 -1
  150. package/package.json +2 -2
  151. package/dist/browser/runtime/browser/setup-kubo-address-rewriter-and-http-router.d.ts +0 -1
  152. package/dist/browser/runtime/browser/setup-kubo-address-rewriter-and-http-router.js +0 -4
  153. package/dist/browser/runtime/browser/setup-kubo-address-rewriter-and-http-router.js.map +0 -1
  154. package/dist/browser/runtime/node/address-rewriter-db.d.ts +0 -33
  155. package/dist/browser/runtime/node/address-rewriter-db.js +0 -156
  156. package/dist/browser/runtime/node/address-rewriter-db.js.map +0 -1
  157. package/dist/browser/runtime/node/addresses-rewriter-proxy-server.d.ts +0 -47
  158. package/dist/browser/runtime/node/addresses-rewriter-proxy-server.js +0 -534
  159. package/dist/browser/runtime/node/addresses-rewriter-proxy-server.js.map +0 -1
  160. package/dist/browser/runtime/node/setup-kubo-address-rewriter-and-http-router.d.ts +0 -4
  161. package/dist/browser/runtime/node/setup-kubo-address-rewriter-and-http-router.js.map +0 -1
  162. package/dist/node/runtime/browser/setup-kubo-address-rewriter-and-http-router.d.ts +0 -1
  163. package/dist/node/runtime/browser/setup-kubo-address-rewriter-and-http-router.js +0 -4
  164. package/dist/node/runtime/browser/setup-kubo-address-rewriter-and-http-router.js.map +0 -1
  165. package/dist/node/runtime/node/address-rewriter-db.d.ts +0 -33
  166. package/dist/node/runtime/node/address-rewriter-db.js +0 -156
  167. package/dist/node/runtime/node/address-rewriter-db.js.map +0 -1
  168. package/dist/node/runtime/node/addresses-rewriter-proxy-server.d.ts +0 -47
  169. package/dist/node/runtime/node/addresses-rewriter-proxy-server.js +0 -534
  170. package/dist/node/runtime/node/addresses-rewriter-proxy-server.js.map +0 -1
  171. package/dist/node/runtime/node/setup-kubo-address-rewriter-and-http-router.d.ts +0 -4
  172. package/dist/node/runtime/node/setup-kubo-address-rewriter-and-http-router.js.map +0 -1
  173. package/dist/bundled/chunks/{src-BEjAH2gY.js → src-WLgFbUwZ.js} +1 -1
@@ -1,15 +1,12 @@
1
1
  import { i as __toESM, n as __exportAll, r as __require, t as __commonJSMin } from "./chunk-2rV9d50f.js";
2
- import { $ as pubsubTopicToDhtKey, $n as n$9, $t as CommunityChallengeSettingSchema, A as extractNetworkErrorDetails, Ar as object, At as trackStartedCommunity, B as isIpfsCid, Cn as CommentUpdateChallengeReservedFieldNames, Ct as findUpdatingCommunity, D as deepMergeRuntimeFields, Dn as CommentUpdateSchema, Dr as custom, E as createAbortError, En as CommentUpdateReservedFields, Er as boolean, Et as listUpdatingCommunities, Fn as CommentEditChallengeRequestToEncryptSchema, Ft as untrackUpdatingCommunity, Gn as ChallengeAnswersSchema, Gt as CommentModerationPubsubMessagePublicationSchema, H as isIpns, Hn as AuthorAddressSchema, Ht as CommunityEditPubsubMessagePublicationSchema, I as getPostUpdateTimestampRange, It as require_sha256$1, Jn as CommunityAddressSchema, Jt as CommentModerationsTableRowSchema, Kn as CidPathSchema, L as hideClassPrivateProps, Ln as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Mn as GetPageParamSchema, Mr as string, Mt as trackUpdatingCommunity, Nn as ModQueuePageIpfsSchema, Nt as untrackStartedCommunity, O as derivePublicationFromChallengeRequest, On as CommentUpdateSignedPropertyNames, Or as literal, Ot as refreshTrackedCommunityAliases, Pn as PageIpfsSchema, Q as isStringDomain, R as ipnsNameToIpnsOverPubsubTopic, Rt as pTimeout, Sn as CommentSignedPropertyNames, Sr as require_ms$1, St as findUpdatingComment, Tn as CommentUpdateForChallengeVerificationSignedPropertyNames, Tr as array, U as isIpnsPath, Un as AuthorCommentIpfsReservedFields, Ut as CreateCommunityEditPublicationOptionsWithRefinementSchema, V as isIpfsPath, Vn as CreateCommentEditOptionsWithRefinementSchema, Vt as CommunityEditPublicationSignedPropertyNames, Wt as CommentModerationChallengeRequestToEncryptSchema, X as isRequestPubsubPublicationOfPost, Xn as CreateSignerSchema, Xt as ChallengeFileFactorySchema, Yn as CommunityAuthorChallengeReservedFieldNames, Yt as CreateCommentModerationOptionsWithRefinementSchema, Z as isRequestPubsubPublicationOfReply, Zn as n$10, Zt as ChallengeFileSchema, _ as PKCUserOptionBaseSchema, _n as CommentChallengeRequestToEncryptSchema, _r as FailedToFetchPageIpfsFromGatewaysError, _t as timestamp, an as CreateNewLocalCommunityUserOptionsSchema, ar as r$8, b as areEquivalentCommunityAddresses, br as logger_default, c as ChallengeVerificationMessageSignedPropertyNames, cn as ExportCommunityModLogsOptionsSchema, cr as r$7, ct as resolveWhenPredicateIsTrue, dn as CreateVoteUserOptionsWithRefinementSchema, dr as e$4, en as CommunityEditOptionsSchema, f as DecryptedChallengeSchema, fn as VoteChallengeRequestToEncryptSchema, fr as require_retry$1, ft as shortifyAddress, g as PKCParsedOptionsSchema, gr as FailedToFetchGenericIpfsFromGatewaysError, gt as throwIfAbortSignalAborted, h as NameResolverSerializedSchema, hn as VoteSignedPropertyNames, hr as FailedToFetchCommunityFromGatewaysError, i as ChallengeMessageSignedPropertyNames, in as CommunitySignedPropertyNames, ir as t$11, it as removeNullUndefinedEmptyObjectsValuesRecursively, j as fetchAndValidateIpnsRecordFromGateway, jn as CreateCommentOptionsWithRefinementSchema, jr as record, k as doesDomainAddressHaveCapitalLetter, kr as number, l as DecryptedChallengeAnswerSchema, lr as t$10, m as NameResolveCacheOptionsSchema, mr as FailedToFetchCommentUpdateFromGatewaysError, mt as sleepUntilTimeoutOrAbort, n as ChallengeAnswerMessageSignedPropertyNames, nn as CommunityIpfsReservedFields, nr as e$6, o as ChallengeRequestMessageSignedPropertyNames, on as CreateRemoteCommunityFunctionArgumentSchema, or as t$12, p as DecryptedChallengeVerificationSchema, pn as VotePubsubMessagePublicationSchema, pr as FailedToFetchCommentIpfsFromGatewaysError, pt as shortifyCid, qn as CidStringSchema, qt as CommentModerationSignedPropertyNames, rn as CommunityIpfsSchema, rr as e$5, sn as CreateRpcCommunityFunctionArgumentSchema, sr as n$8, tn as CommunityExportRecordsSchema, tr as t$13, tt as raceAgainstAbort, un as RpcRemoteCommunityUpdateEventResultSchema, ur as t$9, v as PKCUserOptionsSchema, vn as CommentIpfsReservedFields, vr as PKCError, vt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, wr as _enum, wt as listStartedCommunities, x as calculateIpfsCidV0, xn as CommentPubsubMessageWithFlexibleAuthorRefinementSchema, xr as require_supports_color, xt as findStartedCommunity, yn as CommentIpfsSchema, yr as messages, z as isAbortError, zn as CommentEditSignedPropertyNames, zt as CommunityEditPublicationChallengeRequestToEncryptSchema } from "./schema-Iavj-cRD.js";
2
+ import { $ as pubsubTopicToDhtKey, $n as n$9, $t as CommunityChallengeSettingSchema, A as extractNetworkErrorDetails, Ar as object, At as trackStartedCommunity, B as isIpfsCid, Cn as CommentUpdateChallengeReservedFieldNames, Ct as findUpdatingCommunity, D as deepMergeRuntimeFields, Dn as CommentUpdateSchema, Dr as custom, E as createAbortError, En as CommentUpdateReservedFields, Er as boolean, Et as listUpdatingCommunities, Fn as CommentEditChallengeRequestToEncryptSchema, Ft as untrackUpdatingCommunity, Gn as ChallengeAnswersSchema, Gt as CommentModerationPubsubMessagePublicationSchema, H as isIpns, Hn as AuthorAddressSchema, Ht as CommunityEditPubsubMessagePublicationSchema, I as getPostUpdateTimestampRange, It as require_sha256$1, Jn as CommunityAddressSchema, Jt as CommentModerationsTableRowSchema, Kn as CidPathSchema, L as hideClassPrivateProps, Ln as CommentEditPubsubMessagePublicationWithFlexibleAuthorSchema, Mn as GetPageParamSchema, Mr as string, Mt as trackUpdatingCommunity, Nn as ModQueuePageIpfsSchema, Nt as untrackStartedCommunity, O as derivePublicationFromChallengeRequest, On as CommentUpdateSignedPropertyNames, Or as literal, Ot as refreshTrackedCommunityAliases, Pn as PageIpfsSchema, Pt as untrackUpdatingComment, Q as isStringDomain, R as ipnsNameToIpnsOverPubsubTopic, Rt as pTimeout, Sn as CommentSignedPropertyNames, Sr as require_ms$1, St as findUpdatingComment, Tn as CommentUpdateForChallengeVerificationSignedPropertyNames, Tr as array, U as isIpnsPath, Un as AuthorCommentIpfsReservedFields, Ut as CreateCommunityEditPublicationOptionsWithRefinementSchema, V as isIpfsPath, Vn as CreateCommentEditOptionsWithRefinementSchema, Vt as CommunityEditPublicationSignedPropertyNames, Wt as CommentModerationChallengeRequestToEncryptSchema, X as isRequestPubsubPublicationOfPost, Xn as CreateSignerSchema, Xt as ChallengeFileFactorySchema, Yn as CommunityAuthorChallengeReservedFieldNames, Yt as CreateCommentModerationOptionsWithRefinementSchema, Z as isRequestPubsubPublicationOfReply, Zn as n$10, Zt as ChallengeFileSchema, _ as PKCUserOptionBaseSchema, _n as CommentChallengeRequestToEncryptSchema, _r as FailedToFetchPageIpfsFromGatewaysError, _t as timestamp, an as CreateNewLocalCommunityUserOptionsSchema, ar as r$8, b as areEquivalentCommunityAddresses, br as logger_default, c as ChallengeVerificationMessageSignedPropertyNames, cn as ExportCommunityModLogsOptionsSchema, cr as r$7, ct as resolveWhenPredicateIsTrue, dn as CreateVoteUserOptionsWithRefinementSchema, dr as e$4, en as CommunityEditOptionsSchema, f as DecryptedChallengeSchema, fn as VoteChallengeRequestToEncryptSchema, fr as require_retry$1, ft as shortifyAddress, g as PKCParsedOptionsSchema, gr as FailedToFetchGenericIpfsFromGatewaysError, gt as throwIfAbortSignalAborted, h as NameResolverSerializedSchema, hn as VoteSignedPropertyNames, hr as FailedToFetchCommunityFromGatewaysError, i as ChallengeMessageSignedPropertyNames, in as CommunitySignedPropertyNames, ir as t$11, it as removeNullUndefinedEmptyObjectsValuesRecursively, j as fetchAndValidateIpnsRecordFromGateway, jn as CreateCommentOptionsWithRefinementSchema, jr as record, k as doesDomainAddressHaveCapitalLetter, kr as number, l as DecryptedChallengeAnswerSchema, lr as t$10, m as NameResolveCacheOptionsSchema, mr as FailedToFetchCommentUpdateFromGatewaysError, mt as sleepUntilTimeoutOrAbort, n as ChallengeAnswerMessageSignedPropertyNames, nn as CommunityIpfsReservedFields, nr as e$6, o as ChallengeRequestMessageSignedPropertyNames, on as CreateRemoteCommunityFunctionArgumentSchema, or as t$12, p as DecryptedChallengeVerificationSchema, pn as VotePubsubMessagePublicationSchema, pr as FailedToFetchCommentIpfsFromGatewaysError, pt as shortifyCid, qn as CidStringSchema, qt as CommentModerationSignedPropertyNames, rn as CommunityIpfsSchema, rr as e$5, sn as CreateRpcCommunityFunctionArgumentSchema, sr as n$8, tn as CommunityExportRecordsSchema, tr as t$13, tt as raceAgainstAbort, un as RpcRemoteCommunityUpdateEventResultSchema, ur as t$9, v as PKCUserOptionsSchema, vn as CommentIpfsReservedFields, vr as PKCError, vt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, wr as _enum, wt as listStartedCommunities, x as calculateIpfsCidV0, xn as CommentPubsubMessageWithFlexibleAuthorRefinementSchema, xr as require_supports_color, xt as findStartedCommunity, yn as CommentIpfsSchema, yr as messages, z as isAbortError, zn as CommentEditSignedPropertyNames, zt as CommunityEditPublicationChallengeRequestToEncryptSchema } from "./schema-BUUhufdT.js";
3
3
  import { t as all } from "./src-CYIMjhjK.js";
4
- import http from "node:http";
5
4
  import { createHash } from "node:crypto";
6
5
  import { pathToFileURL } from "node:url";
7
- import fs from "node:fs/promises";
8
- import path from "node:path";
9
6
  import dns from "node:dns";
10
7
  import os from "os";
11
8
  import { closeSync, createReadStream, existsSync, openSync, promises, readSync, readdirSync, rm, watch } from "node:fs";
12
- import path$1 from "path";
9
+ import path from "path";
13
10
  import assert from "assert";
14
11
  import { Agent } from "https";
15
12
  import { Agent as Agent$1 } from "http";
@@ -24,7 +21,6 @@ import { fromString } from "uint8arrays/from-string";
24
21
  import { bases } from "multiformats/basics";
25
22
  import { EventEmitter as EventEmitter$1 } from "events";
26
23
  import { concat } from "uint8arrays/concat";
27
- import https from "node:https";
28
24
  import { performance as performance$1 } from "perf_hooks";
29
25
  //#region node_modules/undici/lib/core/symbols.js
30
26
  var require_symbols = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -7643,7 +7639,7 @@ var require_client_h2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7643
7639
  var require_client = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7644
7640
  const assert$23 = __require("node:assert");
7645
7641
  const net$2 = __require("node:net");
7646
- const http$4 = __require("node:http");
7642
+ const http$3 = __require("node:http");
7647
7643
  const util = require_util$6();
7648
7644
  const { ClientStats } = require_stats();
7649
7645
  const { channels } = require_diagnostics();
@@ -7655,7 +7651,7 @@ var require_client = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7655
7651
  const connectH1 = require_client_h1();
7656
7652
  const connectH2 = require_client_h2();
7657
7653
  const kClosedResolve = Symbol("kClosedResolve");
7658
- const getDefaultNodeMaxHeaderSize = http$4 && http$4.maxHeaderSize && Number.isInteger(http$4.maxHeaderSize) && http$4.maxHeaderSize > 0 ? () => http$4.maxHeaderSize : () => {
7654
+ const getDefaultNodeMaxHeaderSize = http$3 && http$3.maxHeaderSize && Number.isInteger(http$3.maxHeaderSize) && http$3.maxHeaderSize > 0 ? () => http$3.maxHeaderSize : () => {
7659
7655
  throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
7660
7656
  };
7661
7657
  const noop = () => {};
@@ -11928,8 +11924,8 @@ var require_snapshot_utils = /* @__PURE__ */ __commonJSMin(((exports, module) =>
11928
11924
  //#endregion
11929
11925
  //#region node_modules/undici/lib/mock/snapshot-recorder.js
11930
11926
  var require_snapshot_recorder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
11931
- const { writeFile: writeFile$1, readFile: readFile$1, mkdir } = __require("node:fs/promises");
11932
- const { dirname: dirname$1, resolve } = __require("node:path");
11927
+ const { writeFile, readFile: readFile$1, mkdir } = __require("node:fs/promises");
11928
+ const { dirname, resolve } = __require("node:path");
11933
11929
  const { setTimeout: setTimeout$1, clearTimeout: clearTimeout$1 } = __require("node:timers");
11934
11930
  const { InvalidArgumentError, UndiciError } = require_errors();
11935
11931
  const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require_snapshot_utils();
@@ -12215,12 +12211,12 @@ var require_snapshot_recorder = /* @__PURE__ */ __commonJSMin(((exports, module)
12215
12211
  const path = filePath || this.#snapshotPath;
12216
12212
  if (!path) throw new InvalidArgumentError("Snapshot path is required");
12217
12213
  const resolvedPath = resolve(path);
12218
- await mkdir(dirname$1(resolvedPath), { recursive: true });
12214
+ await mkdir(dirname(resolvedPath), { recursive: true });
12219
12215
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
12220
12216
  hash,
12221
12217
  snapshot
12222
12218
  }));
12223
- await writeFile$1(resolvedPath, JSON.stringify(data, null, 2), { flush: true });
12219
+ await writeFile(resolvedPath, JSON.stringify(data, null, 2), { flush: true });
12224
12220
  }
12225
12221
  /**
12226
12222
  * Clears all recorded snapshots
@@ -75532,10 +75528,10 @@ var require_esm = /* @__PURE__ */ __commonJSMin(((exports, module) => {
75532
75528
  //#endregion
75533
75529
  //#region node_modules/hpagent/index.js
75534
75530
  var require_hpagent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
75535
- const https$2 = __require("https");
75536
- const http$3 = __require("http");
75531
+ const https$1 = __require("https");
75532
+ const http$2 = __require("http");
75537
75533
  const { URL: URL$2 } = __require("url");
75538
- var HttpProxyAgent = class extends http$3.Agent {
75534
+ var HttpProxyAgent = class extends http$2.Agent {
75539
75535
  constructor(options) {
75540
75536
  const { proxy, proxyRequestOptions, ...opts } = options;
75541
75537
  super(opts);
@@ -75563,7 +75559,7 @@ var require_hpagent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
75563
75559
  requestOptions.headers["proxy-authorization"] = `Basic ${base64}`;
75564
75560
  }
75565
75561
  if (this.proxy.protocol === "https:") requestOptions.servername = this.proxy.hostname;
75566
- const request = (this.proxy.protocol === "http:" ? http$3 : https$2).request(requestOptions);
75562
+ const request = (this.proxy.protocol === "http:" ? http$2 : https$1).request(requestOptions);
75567
75563
  request.once("connect", (response, socket, head) => {
75568
75564
  request.removeAllListeners();
75569
75565
  socket.removeAllListeners();
@@ -75583,7 +75579,7 @@ var require_hpagent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
75583
75579
  request.end();
75584
75580
  }
75585
75581
  };
75586
- var HttpsProxyAgent = class extends https$2.Agent {
75582
+ var HttpsProxyAgent = class extends https$1.Agent {
75587
75583
  constructor(options) {
75588
75584
  const { proxy, proxyRequestOptions, ...opts } = options;
75589
75585
  super(opts);
@@ -75611,7 +75607,7 @@ var require_hpagent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
75611
75607
  requestOptions.headers["proxy-authorization"] = `Basic ${base64}`;
75612
75608
  }
75613
75609
  if (this.proxy.protocol === "https:") requestOptions.servername = this.proxy.hostname;
75614
- const request = (this.proxy.protocol === "http:" ? http$3 : https$2).request(requestOptions);
75610
+ const request = (this.proxy.protocol === "http:" ? http$2 : https$1).request(requestOptions);
75615
75611
  request.once("connect", (response, socket, head) => {
75616
75612
  request.removeAllListeners();
75617
75613
  socket.removeAllListeners();
@@ -78248,7 +78244,7 @@ var require_querystring = /* @__PURE__ */ __commonJSMin(((exports) => {
78248
78244
  //#endregion
78249
78245
  //#region node_modules/needle/lib/multipart.js
78250
78246
  var require_multipart = /* @__PURE__ */ __commonJSMin(((exports) => {
78251
- var readFile = __require("fs").readFile, basename$1 = __require("path").basename;
78247
+ var readFile = __require("fs").readFile, basename = __require("path").basename;
78252
78248
  exports.build = function(data, boundary, callback) {
78253
78249
  if (typeof data != "object" || typeof data.pipe == "function") return callback(/* @__PURE__ */ new Error("Multipart builder expects data as key/val object."));
78254
78250
  var body = "", object = flatten(data), count = Object.keys(object).length;
@@ -78287,7 +78283,7 @@ var require_multipart = /* @__PURE__ */ __commonJSMin(((exports) => {
78287
78283
  callback(null, return_part + "\r\n");
78288
78284
  }
78289
78285
  if ((part.file || part.buffer) && part.content_type) {
78290
- var filename = part.filename ? part.filename : part.file ? basename$1(part.file) : name;
78286
+ var filename = part.filename ? part.filename : part.file ? basename(part.file) : name;
78291
78287
  if (part.buffer) return append(part.buffer, filename);
78292
78288
  readFile(part.file, function(err, data) {
78293
78289
  if (err) return callback(err);
@@ -88345,12 +88341,12 @@ var require_package$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88345
88341
  //#endregion
88346
88342
  //#region node_modules/needle/lib/needle.js
88347
88343
  var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88348
- var fs$1 = __require("fs"), http$2 = __require("http"), https$1 = __require("https"), url = __require("url"), stream = __require("stream"), debug$2 = require_src()("needle"), stringify$1 = require_querystring().build, multipart = require_multipart(), auth = require_auth(), cookies = require_cookies(), parsers = require_parsers(), decoder = require_decoder();
88344
+ var fs = __require("fs"), http$1 = __require("http"), https = __require("https"), url = __require("url"), stream = __require("stream"), debug = require_src()("needle"), stringify$1 = require_querystring().build, multipart = require_multipart(), auth = require_auth(), cookies = require_cookies(), parsers = require_parsers(), decoder = require_decoder();
88349
88345
  var version = require_package$1().version;
88350
88346
  var user_agent = "Needle/" + version;
88351
88347
  user_agent += " (Node.js " + process.version + "; " + process.platform + " " + process.arch + ")";
88352
88348
  var tls_options = "agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol checkServerIdentity family";
88353
- var close_by_default = !http$2.Agent || http$2.Agent.defaultMaxSockets != Infinity;
88349
+ var close_by_default = !http$1.Agent || http$1.Agent.defaultMaxSockets != Infinity;
88354
88350
  var extend = Object.assign ? Object.assign : __require("util")._extend;
88355
88351
  var redirect_codes = [
88356
88352
  301,
@@ -88437,7 +88433,7 @@ var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88437
88433
  function get_stream_length(stream, given_length, cb) {
88438
88434
  if (given_length > 0) return cb(given_length);
88439
88435
  if (stream.end !== void 0 && stream.end !== Infinity && stream.start !== void 0) return cb(stream.end + 1 - (stream.start || 0));
88440
- fs$1.stat(stream.path, function(err, stat) {
88436
+ fs.stat(stream.path, function(err, stat) {
88441
88437
  cb(stat ? stat.size - (stream.start || 0) : null);
88442
88438
  });
88443
88439
  }
@@ -88597,12 +88593,12 @@ var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88597
88593
  Needle.prototype.send_request = function(count, method, uri, config, post_data, out, callback) {
88598
88594
  if (typeof config.uri_modifier === "function") {
88599
88595
  var modified_uri = config.uri_modifier(uri);
88600
- debug$2("Modifying request URI", uri + " => " + modified_uri);
88596
+ debug("Modifying request URI", uri + " => " + modified_uri);
88601
88597
  uri = modified_uri;
88602
88598
  }
88603
- var request, timer, returned = 0, self = this, request_opts = this.get_request_opts(method, uri, config), protocol = request_opts.protocol == "https:" ? https$1 : http$2;
88599
+ var request, timer, returned = 0, self = this, request_opts = this.get_request_opts(method, uri, config), protocol = request_opts.protocol == "https:" ? https : http$1;
88604
88600
  function done(err, resp) {
88605
- if (returned++ > 0) return debug$2("Already finished, stopping here.");
88601
+ if (returned++ > 0) return debug("Already finished, stopping here.");
88606
88602
  if (timer) clearTimeout(timer);
88607
88603
  request.removeListener("error", had_error);
88608
88604
  out.done = true;
@@ -88615,7 +88611,7 @@ var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88615
88611
  });
88616
88612
  }
88617
88613
  function had_error(err) {
88618
- debug$2("Request error", err);
88614
+ debug("Request error", err);
88619
88615
  out.emit("err", err);
88620
88616
  done(err || /* @__PURE__ */ new Error("Unknown error when making request."));
88621
88617
  }
@@ -88634,15 +88630,15 @@ var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88634
88630
  had_error(/* @__PURE__ */ new Error("Remote end closed socket abruptly."));
88635
88631
  }
88636
88632
  }
88637
- debug$2("Making request #" + count, request_opts);
88633
+ debug("Making request #" + count, request_opts);
88638
88634
  request = protocol.request(request_opts, function(resp) {
88639
88635
  var headers = resp.headers;
88640
- debug$2("Got response", resp.statusCode, headers);
88636
+ debug("Got response", resp.statusCode, headers);
88641
88637
  out.emit("response", resp);
88642
88638
  set_timeout("read", config.read_timeout);
88643
88639
  if (config.parse_cookies && (headers["set-cookie"] || config.previous_resp_cookies)) {
88644
88640
  resp.cookies = extend(config.previous_resp_cookies || {}, cookies.read(headers["set-cookie"]));
88645
- debug$2("Got cookies", resp.cookies);
88641
+ debug("Got cookies", resp.cookies);
88646
88642
  }
88647
88643
  if (redirect_codes.indexOf(resp.statusCode) !== -1 && self.should_follow(headers.location, config, uri)) {
88648
88644
  clearTimeout(timer);
@@ -88658,13 +88654,13 @@ var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88658
88654
  config.previous_resp_cookies = resp.cookies;
88659
88655
  if (Object.keys(request_cookies).length || Object.keys(resp.cookies || {}).length) config.headers["cookie"] = cookies.write(extend(request_cookies, resp.cookies));
88660
88656
  } else if (config.headers["cookie"]) {
88661
- debug$2("Clearing original request cookie", config.headers["cookie"]);
88657
+ debug("Clearing original request cookie", config.headers["cookie"]);
88662
88658
  delete config.headers["cookie"];
88663
88659
  }
88664
88660
  if (config.follow_set_referer) config.headers["referer"] = encodeURI(uri);
88665
88661
  config.headers["host"] = null;
88666
88662
  var redirect_url = resolve_url(headers.location, uri);
88667
- debug$2("Redirecting to " + redirect_url.toString());
88663
+ debug("Redirecting to " + redirect_url.toString());
88668
88664
  return self.send_request(++count, method, redirect_url.toString(), config, post_data, out, callback);
88669
88665
  } else if (config.follow_max > 0) return done(/* @__PURE__ */ new Error("Max redirects reached. Possible loop in: " + headers.location));
88670
88666
  }
@@ -88696,11 +88692,11 @@ var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88696
88692
  } else if (text_response && config.decode_response && mime.charset) pipeline.push(decoder(mime.charset));
88697
88693
  pipeline.push(out);
88698
88694
  pump_streams([resp].concat(pipeline), function(err) {
88699
- if (err) debug$2(err);
88695
+ if (err) debug(err);
88700
88696
  if (err && err.message == "write after end") request.destroy();
88701
88697
  });
88702
88698
  if (config.output && resp.statusCode == 200) {
88703
- var file = fs$1.createWriteStream(config.output);
88699
+ var file = fs.createWriteStream(config.output);
88704
88700
  file.on("error", had_error);
88705
88701
  out.on("end", function() {
88706
88702
  if (file.writable) file.end();
@@ -88730,7 +88726,7 @@ var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88730
88726
  }
88731
88727
  });
88732
88728
  pump_streams([resp, clean_pipe], function(err) {
88733
- if (err) debug$2(err);
88729
+ if (err) debug(err);
88734
88730
  });
88735
88731
  if (!config.output || resp.statusCode != 200) out.on("readable", function() {
88736
88732
  var chunk;
@@ -88775,7 +88771,7 @@ var require_needle = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88775
88771
  }
88776
88772
  });
88777
88773
  if (post_data) if (is_stream(post_data)) pump_streams([post_data, request], function(err) {
88778
- if (err) debug$2(err);
88774
+ if (err) debug(err);
88779
88775
  });
88780
88776
  else {
88781
88777
  request.write(post_data, config.encoding);
@@ -91644,8 +91640,51 @@ function t(n) {
91644
91640
  return r;
91645
91641
  }
91646
91642
  //#endregion
91643
+ //#region dist/node/publications/comment/crosspost-depth.js
91644
+ const MAX_CROSSPOST_DEPTH = 10;
91645
+ function crosspostChainDepthUpTo(record, stopAt = 11) {
91646
+ let depth = 0;
91647
+ let level = _prop(record, "crosspost");
91648
+ while (_isObject(level) && depth < stopAt) {
91649
+ depth++;
91650
+ level = _prop(_prop(level, "comment"), "crosspost");
91651
+ }
91652
+ return depth;
91653
+ }
91654
+ function deepestCrosspostChainInPageUpTo(pageJson, stopAt = 11) {
91655
+ return _deepestCrosspostChainInPagesUpTo([pageJson], stopAt);
91656
+ }
91657
+ function deepestCrosspostChainInCommentUpdateUpTo(commentUpdateJson, stopAt = 11) {
91658
+ const replyPages = _prop(_prop(commentUpdateJson, "replies"), "pages");
91659
+ return _isObject(replyPages) ? _deepestCrosspostChainInPagesUpTo(Object.values(replyPages), stopAt) : 0;
91660
+ }
91661
+ function _deepestCrosspostChainInPagesUpTo(pages, stopAt) {
91662
+ let deepest = 0;
91663
+ const pagesToWalk = [...pages];
91664
+ while (pagesToWalk.length > 0) {
91665
+ const comments = _prop(pagesToWalk.pop(), "comments");
91666
+ if (!Array.isArray(comments)) continue;
91667
+ for (const pageComment of comments) {
91668
+ deepest = Math.max(deepest, crosspostChainDepthUpTo(_prop(pageComment, "comment"), stopAt));
91669
+ if (deepest >= stopAt) return deepest;
91670
+ const replyPages = _prop(_prop(_prop(pageComment, "commentUpdate"), "replies"), "pages");
91671
+ if (_isObject(replyPages)) pagesToWalk.push(...Object.values(replyPages));
91672
+ }
91673
+ }
91674
+ return deepest;
91675
+ }
91676
+ function effectiveMaxCrosspostDepth(maxCrosspostDepthFeature) {
91677
+ if (typeof maxCrosspostDepthFeature !== "number" || !Number.isInteger(maxCrosspostDepthFeature) || maxCrosspostDepthFeature < 0) return 10;
91678
+ return Math.min(maxCrosspostDepthFeature, 10);
91679
+ }
91680
+ function _isObject(value) {
91681
+ return typeof value === "object" && value !== null;
91682
+ }
91683
+ function _prop(value, key) {
91684
+ return _isObject(value) ? value[key] : void 0;
91685
+ }
91686
+ //#endregion
91647
91687
  //#region dist/node/clients/rpc-client/schema.js
91648
- var import_retry = /* @__PURE__ */ __toESM(require_retry$1(), 1);
91649
91688
  var import_sha256 = require_sha256$1();
91650
91689
  const SubscriptionIdSchema = number().positive().int();
91651
91690
  const RpcCommentEventResultSchema = object({
@@ -91744,6 +91783,28 @@ const PKCWsServerSettingsSerializedSchema = object({
91744
91783
  });
91745
91784
  //#endregion
91746
91785
  //#region dist/node/schema/schema-util.js
91786
+ function _throwIfCrosspostChainExceedsMaxDepth(record, details) {
91787
+ if (crosspostChainDepthUpTo(record) > 10) throw new PKCError("ERR_CROSSPOST_CHAIN_EXCEEDS_MAX_DEPTH", {
91788
+ ...details,
91789
+ maxCrosspostDepth: 10
91790
+ });
91791
+ }
91792
+ function _throwIfPageCrosspostChainsExceedMaxDepth(pageJson, details) {
91793
+ if (deepestCrosspostChainInPageUpTo(pageJson) > 10) throw new PKCError("ERR_CROSSPOST_CHAIN_EXCEEDS_MAX_DEPTH", {
91794
+ ...details,
91795
+ maxCrosspostDepth: 10
91796
+ });
91797
+ }
91798
+ function _safeParseWithoutLettingNonZodThrowsEscape(schema, json, code, details) {
91799
+ try {
91800
+ return schema.safeParse(json);
91801
+ } catch (e) {
91802
+ throw new PKCError(code, {
91803
+ ...details,
91804
+ error: e
91805
+ });
91806
+ }
91807
+ }
91747
91808
  function parseJsonWithPKCErrorIfFails(x) {
91748
91809
  try {
91749
91810
  return JSON.parse(x);
@@ -91764,7 +91825,8 @@ function parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails(communityIpfs)
91764
91825
  else return communityIpfs;
91765
91826
  }
91766
91827
  function parseCommentIpfsSchemaWithPKCErrorIfItFails(commentIpfsJson) {
91767
- const parseRes = CommentIpfsSchema.loose().safeParse(commentIpfsJson);
91828
+ _throwIfCrosspostChainExceedsMaxDepth(commentIpfsJson, { commentIpfsJson });
91829
+ const parseRes = _safeParseWithoutLettingNonZodThrowsEscape(CommentIpfsSchema.loose(), commentIpfsJson, "ERR_INVALID_COMMENT_IPFS_SCHEMA", { commentIpfsJson });
91768
91830
  if (!parseRes.success) throw new PKCError("ERR_INVALID_COMMENT_IPFS_SCHEMA", {
91769
91831
  zodError: parseRes.error,
91770
91832
  commentIpfsJson
@@ -91772,7 +91834,11 @@ function parseCommentIpfsSchemaWithPKCErrorIfItFails(commentIpfsJson) {
91772
91834
  else return commentIpfsJson;
91773
91835
  }
91774
91836
  function parseCommentUpdateSchemaWithPKCErrorIfItFails(commentUpdateJson) {
91775
- const parseRes = CommentUpdateSchema.loose().safeParse(commentUpdateJson);
91837
+ if (deepestCrosspostChainInCommentUpdateUpTo(commentUpdateJson) > 10) throw new PKCError("ERR_CROSSPOST_CHAIN_EXCEEDS_MAX_DEPTH", {
91838
+ commentUpdateJson,
91839
+ maxCrosspostDepth: 10
91840
+ });
91841
+ const parseRes = _safeParseWithoutLettingNonZodThrowsEscape(CommentUpdateSchema.loose(), commentUpdateJson, "ERR_INVALID_COMMENT_UPDATE_SCHEMA", { commentUpdateJson });
91776
91842
  if (!parseRes.success) throw new PKCError("ERR_INVALID_COMMENT_UPDATE_SCHEMA", {
91777
91843
  zodError: parseRes.error,
91778
91844
  commentUpdateJson
@@ -91780,7 +91846,8 @@ function parseCommentUpdateSchemaWithPKCErrorIfItFails(commentUpdateJson) {
91780
91846
  else return commentUpdateJson;
91781
91847
  }
91782
91848
  function parsePageIpfsSchemaWithPKCErrorIfItFails(pageIpfsJson) {
91783
- const parseRes = PageIpfsSchema.safeParse(pageIpfsJson);
91849
+ _throwIfPageCrosspostChainsExceedMaxDepth(pageIpfsJson, { pageIpfsJson });
91850
+ const parseRes = _safeParseWithoutLettingNonZodThrowsEscape(PageIpfsSchema, pageIpfsJson, "ERR_INVALID_PAGE_IPFS_SCHEMA", { pageIpfsJson });
91784
91851
  if (!parseRes.success) throw new PKCError("ERR_INVALID_PAGE_IPFS_SCHEMA", {
91785
91852
  zodError: parseRes.error,
91786
91853
  pageIpfsJson
@@ -91788,7 +91855,8 @@ function parsePageIpfsSchemaWithPKCErrorIfItFails(pageIpfsJson) {
91788
91855
  else return pageIpfsJson;
91789
91856
  }
91790
91857
  function parseModQueuePageIpfsSchemaWithPKCErrorIfItFails(modQueuePageIpfsJson) {
91791
- const parseRes = ModQueuePageIpfsSchema.safeParse(modQueuePageIpfsJson);
91858
+ _throwIfPageCrosspostChainsExceedMaxDepth(modQueuePageIpfsJson, { modQueuePageIpfsJson });
91859
+ const parseRes = _safeParseWithoutLettingNonZodThrowsEscape(ModQueuePageIpfsSchema, modQueuePageIpfsJson, "ERR_INVALID_MODQUEUE_PAGE_IPFS_SCHEMA", { modQueuePageIpfsJson });
91792
91860
  if (!parseRes.success) throw new PKCError("ERR_INVALID_MODQUEUE_PAGE_IPFS_SCHEMA", {
91793
91861
  zodError: parseRes.error,
91794
91862
  modQueuePageIpfsJson
@@ -91838,6 +91906,7 @@ function parseRpcCommentUpdateEventWithPKCErrorIfItFails(updateResult) {
91838
91906
  else return updateResult;
91839
91907
  }
91840
91908
  function parseRpcCommentEventWithPKCErrorIfItFails(updateResult) {
91909
+ _throwIfCrosspostChainExceedsMaxDepth(updateResult?.comment, { updateResult });
91841
91910
  const parseRes = RpcCommentEventResultSchema.safeParse(updateResult);
91842
91911
  if (!parseRes.success) throw new PKCError("ERR_INVALID_RPC_COMMENT_SCHEMA", {
91843
91912
  zodError: parseRes.error,
@@ -92022,7 +92091,14 @@ function parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails(args
92022
92091
  else return args;
92023
92092
  }
92024
92093
  function parseCommentPubsubMessagePublicationWithPKCErrorIfItFails(args) {
92025
- const parseRes = CommentPubsubMessageWithFlexibleAuthorRefinementSchema.safeParse(args);
92094
+ _throwIfCrosspostChainExceedsMaxDepth(args, {
92095
+ args,
92096
+ type: "CommentPubsubMessagePublication"
92097
+ });
92098
+ const parseRes = _safeParseWithoutLettingNonZodThrowsEscape(CommentPubsubMessageWithFlexibleAuthorRefinementSchema, args, "ERR_INVALID_CREATE_COMMENT_ARGS_SCHEMA", {
92099
+ args,
92100
+ type: "CommentPubsubMessagePublication"
92101
+ });
92026
92102
  if (!parseRes.success) throw new PKCError("ERR_INVALID_CREATE_COMMENT_ARGS_SCHEMA", {
92027
92103
  zodError: parseRes.error,
92028
92104
  args,
@@ -92031,6 +92107,10 @@ function parseCommentPubsubMessagePublicationWithPKCErrorIfItFails(args) {
92031
92107
  else return args;
92032
92108
  }
92033
92109
  function parseCreateCommentOptionsSchemaWithPKCErrorIfItFails(args) {
92110
+ _throwIfCrosspostChainExceedsMaxDepth(args, {
92111
+ args,
92112
+ type: "CreateCommentOptions"
92113
+ });
92034
92114
  const parseRes = CreateCommentOptionsWithRefinementSchema.safeParse(args);
92035
92115
  if (!parseRes.success) throw new PKCError("ERR_INVALID_CREATE_COMMENT_ARGS_SCHEMA", {
92036
92116
  zodError: parseRes.error,
@@ -97773,6 +97853,40 @@ async function verifyCommentModeration({ moderation, resolveAuthorNames, clients
97773
97853
  if (!res.valid) return res;
97774
97854
  return { valid: true };
97775
97855
  }
97856
+ async function _verifyCrosspost({ crosspost, resolveAuthorNames, clientsManager, abortSignal }) {
97857
+ if (await of(stringify(crosspost.comment)) !== crosspost.cid) return {
97858
+ valid: false,
97859
+ reason: messages.ERR_CROSSPOST_CID_DOES_NOT_MATCH_EMBEDDED_COMMENT
97860
+ };
97861
+ if (_isThereReservedFieldInRecord(crosspost.comment, CommentIpfsReservedFields)) return {
97862
+ valid: false,
97863
+ reason: messages.ERR_CROSSPOST_COMMENT_INCLUDES_RESERVED_FIELD
97864
+ };
97865
+ if (crosspost.comment.author && r(Object.keys(crosspost.comment.author), AuthorCommentIpfsReservedFields).length > 0) return {
97866
+ valid: false,
97867
+ reason: messages.ERR_CROSSPOST_COMMENT_AUTHOR_INCLUDES_RESERVED_FIELD
97868
+ };
97869
+ if (_isThereUnsignedSignableFieldInRecord(crosspost.comment)) return {
97870
+ valid: false,
97871
+ reason: messages.ERR_CROSSPOST_COMMENT_INCLUDES_SIGNABLE_FIELD_NOT_IN_SIGNED_PROPERTY_NAMES
97872
+ };
97873
+ const keysCasted = crosspost.comment.signature.signedPropertyNames;
97874
+ if (!(await verifyCommentPubsubMessage({
97875
+ comment: t$2(crosspost.comment, ["signature", ...keysCasted]),
97876
+ resolveAuthorNames,
97877
+ clientsManager,
97878
+ abortSignal
97879
+ })).valid) return {
97880
+ valid: false,
97881
+ reason: messages.ERR_CROSSPOST_COMMENT_SIGNATURE_IS_INVALID
97882
+ };
97883
+ return { valid: true };
97884
+ }
97885
+ function _isThereUnsignedSignableFieldInRecord(record) {
97886
+ const fields = record;
97887
+ for (const name of CommentSignedPropertyNames) if (fields[name] !== void 0 && !record.signature.signedPropertyNames.includes(name)) return true;
97888
+ return false;
97889
+ }
97776
97890
  async function verifyCommentPubsubMessage({ comment, resolveAuthorNames, clientsManager, abortSignal }) {
97777
97891
  if (!_allFieldsOfRecordInSignedPropertyNames(comment)) return {
97778
97892
  valid: false,
@@ -97780,6 +97894,19 @@ async function verifyCommentPubsubMessage({ comment, resolveAuthorNames, clients
97780
97894
  };
97781
97895
  const validation = await _verifyPublicationSignatureAndAuthor({ publicationJson: comment });
97782
97896
  if (!validation.valid) return validation;
97897
+ if (comment.crosspost) {
97898
+ if (crosspostChainDepthUpTo(comment) > 10) return {
97899
+ valid: false,
97900
+ reason: messages.ERR_CROSSPOST_CHAIN_EXCEEDS_MAX_DEPTH
97901
+ };
97902
+ const crosspostValidation = await _verifyCrosspost({
97903
+ crosspost: comment.crosspost,
97904
+ resolveAuthorNames,
97905
+ clientsManager,
97906
+ abortSignal
97907
+ });
97908
+ if (!crosspostValidation.valid) return crosspostValidation;
97909
+ }
97783
97910
  return validation;
97784
97911
  }
97785
97912
  async function verifyCommentIpfs(opts) {
@@ -97798,6 +97925,10 @@ async function verifyCommentIpfs(opts) {
97798
97925
  valid: false,
97799
97926
  reason: messages.ERR_COMMENT_IPFS_AUTHOR_INCLUDES_RESERVED_FIELD
97800
97927
  };
97928
+ if (_isThereUnsignedSignableFieldInRecord(opts.comment)) return {
97929
+ valid: false,
97930
+ reason: messages.ERR_COMMENT_IPFS_RECORD_INCLUDES_SIGNABLE_FIELD_NOT_IN_SIGNED_PROPERTY_NAMES
97931
+ };
97801
97932
  const keysCasted = opts.comment.signature.signedPropertyNames;
97802
97933
  const validRes = await verifyCommentPubsubMessage({
97803
97934
  comment: t$2(opts.comment, ["signature", ...keysCasted]),
@@ -98162,6 +98293,7 @@ var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
98162
98293
  }));
98163
98294
  //#endregion
98164
98295
  //#region dist/node/clients/pkc-typed-emitter.js
98296
+ var import_retry = /* @__PURE__ */ __toESM(require_retry$1(), 1);
98165
98297
  var import_lib$1 = require_lib$1();
98166
98298
  var PKCTypedEmitter = class extends import_lib$1.TypedEmitter {
98167
98299
  constructor() {
@@ -98601,6 +98733,7 @@ const createUrlFromSubdomainResolution = (gateway, opts) => {
98601
98733
  return `${gatewayUrl.protocol}//${root}.${opts.recordIpfsType}.${gatewayUrl.host}${opts.path ? "/" + opts.path : ""}`;
98602
98734
  };
98603
98735
  const GATEWAYS_THAT_SUPPORT_SUBDOMAIN_RESOLUTION = {};
98736
+ const MAX_CONCURRENT_AUTHOR_NAME_RESOLUTIONS = 100;
98604
98737
  var BaseClientsManager = class BaseClientsManager {
98605
98738
  constructor(pkc) {
98606
98739
  this.pubsubProviderSubscriptions = {};
@@ -99299,7 +99432,7 @@ var BaseClientsManager = class BaseClientsManager {
99299
99432
  });
99300
99433
  }
99301
99434
  if (toResolve.length === 0) return;
99302
- const limit = pLimit(5);
99435
+ const limit = pLimit(MAX_CONCURRENT_AUTHOR_NAME_RESOLUTIONS);
99303
99436
  const resolveOne = async (entry) => {
99304
99437
  if (abortSignal?.aborted) return false;
99305
99438
  try {
@@ -100023,6 +100156,88 @@ var CommunityModQueueClientsManager = class extends BasePagesClientsManager {
100023
100156
  //#region dist/node/pages/schema-util.js
100024
100157
  const parsePageCidParams = (params) => GetPageParamSchema.parse(params);
100025
100158
  //#endregion
100159
+ //#region dist/node/publications/comment/crosspost-runtime.js
100160
+ function _chainOf(crosspost) {
100161
+ const chain = [];
100162
+ for (let level = crosspost; level; level = level.comment.crosspost) chain.push(level);
100163
+ return chain;
100164
+ }
100165
+ function cloneCrosspostForRuntime(crosspost) {
100166
+ const chain = _chainOf(crosspost);
100167
+ let child;
100168
+ for (let i = chain.length - 1; i >= 0; i--) {
100169
+ const level = chain[i];
100170
+ const comment = { ...level.comment };
100171
+ if (level.comment.author) comment.author = { ...level.comment.author };
100172
+ if (child) comment.crosspost = child;
100173
+ child = {
100174
+ cid: level.cid,
100175
+ comment
100176
+ };
100177
+ }
100178
+ return child;
100179
+ }
100180
+ const CROSSPOST_LEVELS_TO_RESOLVE_AUTHOR_NAMES_FOR = 10;
100181
+ function collectCrosspostAuthorsToResolve({ crosspost, maxLevels = CROSSPOST_LEVELS_TO_RESOLVE_AUTHOR_NAMES_FOR }) {
100182
+ const authors = [];
100183
+ const chain = _chainOf(crosspost).slice(0, maxLevels);
100184
+ for (const level of chain) {
100185
+ if (typeof level.comment.author?.nameResolved === "boolean") continue;
100186
+ const authorName = getAuthorNameFromWire(level.comment.author);
100187
+ if (!authorName) continue;
100188
+ authors.push({
100189
+ authorName,
100190
+ signaturePublicKey: level.comment.signature.publicKey
100191
+ });
100192
+ }
100193
+ return authors;
100194
+ }
100195
+ function applyNameResolvedCacheToCrosspost({ crosspost, cache }) {
100196
+ let changed = false;
100197
+ for (const level of _chainOf(crosspost)) {
100198
+ const author = level.comment.author;
100199
+ if (!author) continue;
100200
+ const authorName = getAuthorNameFromWire(author);
100201
+ if (!authorName) continue;
100202
+ const cached = cache.get((0, import_sha256.sha256)(authorName + level.comment.signature.publicKey));
100203
+ if (typeof cached !== "boolean" || author.nameResolved === cached) continue;
100204
+ author.nameResolved = cached;
100205
+ changed = true;
100206
+ }
100207
+ return changed;
100208
+ }
100209
+ function _buildCrosspostRuntimeFields(crosspost, nameResolvedOf) {
100210
+ const chain = _chainOf(crosspost);
100211
+ let child;
100212
+ let anyLevelHasAVerdict = false;
100213
+ for (let i = chain.length - 1; i >= 0; i--) {
100214
+ const nameResolved = nameResolvedOf(chain[i]);
100215
+ if (nameResolved === void 0 && !child) continue;
100216
+ const comment = {};
100217
+ if (nameResolved !== void 0) {
100218
+ comment.author = { nameResolved };
100219
+ anyLevelHasAVerdict = true;
100220
+ }
100221
+ if (child) comment.crosspost = child;
100222
+ child = { comment };
100223
+ }
100224
+ return anyLevelHasAVerdict ? child : void 0;
100225
+ }
100226
+ function buildCrosspostRuntimeFieldsFromCache({ crosspost, cache }) {
100227
+ return _buildCrosspostRuntimeFields(crosspost, (level) => {
100228
+ const authorName = getAuthorNameFromWire(level.comment.author);
100229
+ if (!authorName) return void 0;
100230
+ const cached = cache.get((0, import_sha256.sha256)(authorName + level.comment.signature.publicKey));
100231
+ return typeof cached === "boolean" ? cached : void 0;
100232
+ });
100233
+ }
100234
+ function extractCrosspostRuntimeFields(crosspost) {
100235
+ return _buildCrosspostRuntimeFields(crosspost, (level) => typeof level.comment.author?.nameResolved === "boolean" ? level.comment.author.nameResolved : void 0);
100236
+ }
100237
+ function stripNameResolvedFromCrosspost(crosspost) {
100238
+ for (const level of _chainOf(crosspost)) if (level.comment.author?.nameResolved !== void 0) delete level.comment.author.nameResolved;
100239
+ }
100240
+ //#endregion
100026
100241
  //#region dist/node/pages/pages.js
100027
100242
  var BasePages = class {
100028
100243
  constructor(props) {
@@ -100047,6 +100262,10 @@ var BasePages = class {
100047
100262
  _applyNameResolvedCacheToPage(page) {
100048
100263
  const cache = this._clientsManager._pkc._memCaches.nameResolvedCache;
100049
100264
  for (const comment of page.comments) {
100265
+ if (comment.crosspost) applyNameResolvedCacheToCrosspost({
100266
+ crosspost: comment.crosspost,
100267
+ cache
100268
+ });
100050
100269
  const domain = getAuthorNameFromRuntime(comment.author);
100051
100270
  if (!domain) continue;
100052
100271
  const cacheKey = (0, import_sha256.sha256)(domain + comment.signature.publicKey);
@@ -100412,6 +100631,7 @@ function mapModqueuePageIpfsCommentToModQueuePageJsonComment(pageComment) {
100412
100631
  shortCid: shortifyCid(pageComment.commentUpdate.cid),
100413
100632
  shortCommunityAddress: shortifyAddress(communityAddr),
100414
100633
  postCid,
100634
+ ...pageComment.comment.crosspost ? { crosspost: cloneCrosspostForRuntime(pageComment.comment.crosspost) } : {},
100415
100635
  raw: {
100416
100636
  comment: pageComment.comment,
100417
100637
  commentUpdate: pageComment.commentUpdate
@@ -100458,6 +100678,7 @@ function mapPageIpfsCommentToPageJsonComment(pageComment) {
100458
100678
  nsfw,
100459
100679
  flairs: pageComment.commentUpdate.flairs || pageComment.commentUpdate.edit?.flairs || pageComment.comment.flairs,
100460
100680
  postCid,
100681
+ ...pageComment.comment.crosspost ? { crosspost: cloneCrosspostForRuntime(pageComment.comment.crosspost) } : {},
100461
100682
  raw: {
100462
100683
  comment: pageComment.comment,
100463
100684
  commentUpdate: pageComment.commentUpdate
@@ -100527,12 +100748,19 @@ function findCommentInHierarchicalPageIpfsRecursively(page, targetCid) {
100527
100748
  }
100528
100749
  }
100529
100750
  function _buildCommentRuntimeFields(comment, cache) {
100751
+ const fields = {};
100752
+ const crosspost = comment.comment.crosspost ? buildCrosspostRuntimeFieldsFromCache({
100753
+ crosspost: comment.comment.crosspost,
100754
+ cache
100755
+ }) : void 0;
100756
+ if (crosspost) fields.crosspost = crosspost;
100530
100757
  const domain = getAuthorNameFromWire(comment.comment.author);
100531
- if (!domain) return {};
100758
+ if (!domain) return fields;
100532
100759
  const key = (0, import_sha256.sha256)(domain + comment.comment.signature.publicKey);
100533
100760
  const cached = cache.get(key);
100534
- if (typeof cached !== "boolean") return {};
100535
- return { author: { nameResolved: cached } };
100761
+ if (typeof cached !== "boolean") return fields;
100762
+ fields.author = { nameResolved: cached };
100763
+ return fields;
100536
100764
  }
100537
100765
  function buildPageRuntimeFields(page, cache) {
100538
100766
  return { comments: page.comments.map((c) => {
@@ -100553,6 +100781,10 @@ function buildPagesRuntimeFields(pages, cache) {
100553
100781
  function extractCommentRuntimeFieldsFromParsedComment(comment) {
100554
100782
  const runtimeFields = {};
100555
100783
  if (typeof comment.author?.nameResolved === "boolean") runtimeFields.author = { nameResolved: comment.author.nameResolved };
100784
+ if (comment.crosspost) {
100785
+ const crosspost = extractCrosspostRuntimeFields(comment.crosspost);
100786
+ if (crosspost) runtimeFields.crosspost = crosspost;
100787
+ }
100556
100788
  const repliesPages = "replies" in comment ? comment.replies?.pages : void 0;
100557
100789
  if (repliesPages) {
100558
100790
  const replyRuntimeFields = extractParsedPagesRuntimeFields(repliesPages);
@@ -101602,6 +101834,7 @@ var CommentClientsManager = class extends PublicationClientsManager {
101602
101834
  this._postForUpdating.comment.on("update", this._postForUpdating.update);
101603
101835
  this._postForUpdating.comment.on("updatingstatechange", this._postForUpdating.updatingstatechange);
101604
101836
  this._postForUpdating.comment.on("error", this._postForUpdating.error);
101837
+ this._postForUpdating.comment._numOfListenersForUpdatingInstance++;
101605
101838
  return this._postForUpdating;
101606
101839
  }
101607
101840
  async cleanUpUpdatingPostInstance() {
@@ -101625,21 +101858,25 @@ var CommentClientsManager = class extends PublicationClientsManager {
101625
101858
  this._postForUpdating.comment.removeListener("updatingstatechange", this._postForUpdating.updatingstatechange);
101626
101859
  this._postForUpdating.comment.removeListener("error", this._postForUpdating.error);
101627
101860
  this._postForUpdating.comment.removeListener("update", this._postForUpdating.update);
101628
- if (this._postForUpdating.comment._updatingCommentInstance) await this._postForUpdating.comment.stop();
101861
+ const postForUpdating = this._postForUpdating.comment;
101862
+ postForUpdating._numOfListenersForUpdatingInstance--;
101863
+ if (postForUpdating._updatingCommentInstance) await postForUpdating.stop();
101864
+ else if (postForUpdating._numOfListenersForUpdatingInstance === 0 && postForUpdating.state !== "stopped") await postForUpdating.stop();
101865
+ else if (postForUpdating._numOfListenersForUpdatingInstance === 0 && postForUpdating.state === "stopped" && postForUpdating.cid && findUpdatingComment(this._pkc, { cid: postForUpdating.cid }) === postForUpdating) untrackUpdatingComment(this._pkc, postForUpdating);
101629
101866
  this._parentFirstPageCidsAlreadyLoaded.clear();
101630
101867
  this._postForUpdating = void 0;
101631
101868
  }
101632
101869
  };
101633
101870
  //#endregion
101634
101871
  //#region dist/node/runtime/node/util.js
101635
- const getDefaultDataPath = () => path$1.join(process.cwd(), ".pkc");
101872
+ const getDefaultDataPath = () => path.join(process.cwd(), ".pkc");
101636
101873
  const getDefaultCommunityDbConfig = async (communityAddress, pkc) => {
101637
101874
  let filename;
101638
101875
  if (pkc.noData) filename = ":memory:";
101639
101876
  else {
101640
101877
  assert(typeof pkc.dataPath === "string", "pkc.dataPath need to be defined to get default community db config");
101641
- filename = path$1.join(pkc.dataPath, "communities", communityAddress);
101642
- await promises.mkdir(path$1.dirname(filename), { recursive: true });
101878
+ filename = path.join(pkc.dataPath, "communities", communityAddress);
101879
+ await promises.mkdir(path.dirname(filename), { recursive: true });
101643
101880
  }
101644
101881
  return {
101645
101882
  filename,
@@ -101738,7 +101975,7 @@ const setNativeFunctions = (newNativeFunctions) => {
101738
101975
  };
101739
101976
  const deleteOldCommunityInWindows = async (subPath, pkc) => {
101740
101977
  const log = logger_default("pkc-js:community:deleteStaleCommunityInWindows");
101741
- const communityAddress = path$1.basename(subPath);
101978
+ const communityAddress = path.basename(subPath);
101742
101979
  await new Promise((resolve) => setTimeout(resolve, 1e4));
101743
101980
  try {
101744
101981
  await promises.rm(subPath, { force: true });
@@ -101762,7 +101999,7 @@ async function tryToDeleteCommunitiesThatFailedToBeDeletedBefore(pkc, log) {
101762
101999
  }
101763
102000
  const communitiesThatWereDeletedSuccessfully = [];
101764
102001
  for (const communityAddress of deletedPersistentCommunities) {
101765
- const communityPath = path$1.join(pkc.dataPath, "communities", communityAddress);
102002
+ const communityPath = path.join(pkc.dataPath, "communities", communityAddress);
101766
102003
  try {
101767
102004
  await promises.rm(communityPath, { force: true });
101768
102005
  log(`Succeeded in deleting old db path (${communityAddress})`);
@@ -101786,7 +102023,7 @@ async function tryToDeleteCommunitiesThatFailedToBeDeletedBefore(pkc, log) {
101786
102023
  function listCommunitiesSync(pkc) {
101787
102024
  logger_default("pkc-js:listCommunitiesSync");
101788
102025
  if (typeof pkc.dataPath !== "string") throw Error("pkc.dataPath needs to be defined to listCommunities");
101789
- const communitiesPath = path$1.join(pkc.dataPath, "communities");
102026
+ const communitiesPath = path.join(pkc.dataPath, "communities");
101790
102027
  const files = readdirSync(communitiesPath, {
101791
102028
  recursive: false,
101792
102029
  withFileTypes: false
@@ -101794,7 +102031,7 @@ function listCommunitiesSync(pkc) {
101794
102031
  const communityFilesWeDontNeedToCheck = pkc.communities ? files.filter((address) => pkc.communities.includes(address)) : [];
101795
102032
  const sqliteFiles = files.filter((address) => !communityFilesWeDontNeedToCheck.includes(address)).filter((address) => {
101796
102033
  try {
101797
- const filePath = path$1.join(communitiesPath, address);
102034
+ const filePath = path.join(communitiesPath, address);
101798
102035
  if (!existsSync(filePath)) return false;
101799
102036
  const fd = openSync(filePath, "r");
101800
102037
  const buffer = Buffer.alloc(16);
@@ -101875,7 +102112,7 @@ var BackupAbortError = class extends Error {
101875
102112
  async function backupCommunityDb(opts) {
101876
102113
  const { sourcePath, destPath, includePrivateKey, onProgress, signal } = opts;
101877
102114
  if (signal?.aborted) throw new BackupAbortError();
101878
- await promises.mkdir(path$1.dirname(destPath), { recursive: true });
102115
+ await promises.mkdir(path.dirname(destPath), { recursive: true });
101879
102116
  const partialPath = destPath + ".partial";
101880
102117
  try {
101881
102118
  await promises.unlink(partialPath);
@@ -101959,9 +102196,9 @@ async function statAndHashFile(filePath) {
101959
102196
  }
101960
102197
  async function moveCommunityDbToDeletedDirectory(communityAddress, pkc) {
101961
102198
  if (typeof pkc.dataPath !== "string") throw Error("pkc.dataPath is not defined");
101962
- const oldPath = path$1.join(pkc.dataPath, "communities", communityAddress);
101963
- const newPath = path$1.join(pkc.dataPath, "communities", "deleted", communityAddress);
101964
- await promises.mkdir(path$1.join(pkc.dataPath, "communities", "deleted"), { recursive: true });
102199
+ const oldPath = path.join(pkc.dataPath, "communities", communityAddress);
102200
+ const newPath = path.join(pkc.dataPath, "communities", "deleted", communityAddress);
102201
+ await promises.mkdir(path.join(pkc.dataPath, "communities", "deleted"), { recursive: true });
101965
102202
  if (!existsSync(oldPath)) throw Error(`Source database ${oldPath} does not exist`);
101966
102203
  try {
101967
102204
  const sourceDb = new Database(oldPath, { fileMustExist: true });
@@ -101982,7 +102219,7 @@ async function moveCommunityDbToDeletedDirectory(communityAddress, pkc) {
101982
102219
  }
101983
102220
  async function createKuboRpcClient(kuboRpcClientOptions) {
101984
102221
  logger_default("pkc-js:pkc:createKuboRpcClient").trace("Creating a new kubo client on node with options", kuboRpcClientOptions);
101985
- const { create: CreateKuboRpcClient } = await import("./src-BEjAH2gY.js");
102222
+ const { create: CreateKuboRpcClient } = await import("./src-WLgFbUwZ.js");
101986
102223
  const Agent$2 = typeof kuboRpcClientOptions.url === "string" && kuboRpcClientOptions.url.startsWith("https") || kuboRpcClientOptions?.protocol === "https" || kuboRpcClientOptions.url instanceof URL && kuboRpcClientOptions?.url?.protocol === "https:" || kuboRpcClientOptions.url?.toString()?.includes("https") ? Agent : Agent$1;
101987
102224
  const onehourMs = 1e3 * 60 * 60;
101988
102225
  return CreateKuboRpcClient({
@@ -101997,7 +102234,7 @@ async function createKuboRpcClient(kuboRpcClientOptions) {
101997
102234
  }
101998
102235
  async function monitorCommunitiesDirectory(pkc) {
101999
102236
  const watchAbortController = new AbortController();
102000
- const communitiesPath = path$1.join(pkc.dataPath, "communities");
102237
+ const communitiesPath = path.join(pkc.dataPath, "communities");
102001
102238
  await promises.mkdir(communitiesPath, { recursive: true });
102002
102239
  const extensionsToIgnore = [
102003
102240
  ".lock",
@@ -125976,525 +126213,6 @@ var RemoteCommunity = class extends import_lib$1.TypedEmitter {
125976
126213
  }
125977
126214
  };
125978
126215
  //#endregion
125979
- //#region dist/node/runtime/node/address-rewriter-db.js
125980
- const debug$1 = logger_default("pkc-js:address-rewriter-db");
125981
- var AddressRewriterDatabase = class {
125982
- constructor(dataPath, kuboConfig, proxyTarget) {
125983
- this._db = null;
125984
- this._dbPath = this._initializeDbPath(dataPath, kuboConfig, proxyTarget);
125985
- }
125986
- _initializeDbPath(dataPath, kuboConfig, proxyTarget) {
125987
- if (!dataPath) throw new Error("dataPath must be defined for request logging");
125988
- let kuboIdentifier = "unknown";
125989
- if (kuboConfig && typeof kuboConfig === "object" && "host" in kuboConfig && "port" in kuboConfig) kuboIdentifier = `${kuboConfig.host}_${kuboConfig.port}`;
125990
- const proxyIdentifier = `${proxyTarget.hostname}_${proxyTarget.port || (proxyTarget.protocol === "https:" ? "443" : "80")}`;
125991
- const fileName = `address_rewriter_${kuboIdentifier}_${proxyIdentifier}.db`;
125992
- return path.join(dataPath, ".address-rewriter", fileName);
125993
- }
125994
- async initialize() {
125995
- try {
125996
- const dbDir = path.dirname(this._dbPath);
125997
- await fs.mkdir(dbDir, { recursive: true });
125998
- this._db = new Database(this._dbPath);
125999
- this._db.exec(`
126000
- CREATE TABLE IF NOT EXISTS request_logs (
126001
- id INTEGER PRIMARY KEY AUTOINCREMENT,
126002
- keys TEXT NOT NULL,
126003
- received_at INTEGER NOT NULL,
126004
- transmitted_at INTEGER,
126005
- success INTEGER NOT NULL,
126006
- status_code INTEGER,
126007
- method TEXT NOT NULL,
126008
- url TEXT NOT NULL,
126009
- error TEXT,
126010
- retry_count INTEGER DEFAULT 0,
126011
- body_preview TEXT,
126012
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
126013
- )
126014
- `);
126015
- this._db.exec(`
126016
- CREATE TABLE IF NOT EXISTS reprovide_logs (
126017
- id INTEGER PRIMARY KEY AUTOINCREMENT,
126018
- key TEXT NOT NULL,
126019
- timestamp INTEGER NOT NULL,
126020
- success INTEGER NOT NULL,
126021
- error TEXT,
126022
- block_not_local INTEGER DEFAULT 0,
126023
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
126024
- )
126025
- `);
126026
- this._db.exec(`
126027
- CREATE TABLE IF NOT EXISTS failed_keys (
126028
- key TEXT PRIMARY KEY,
126029
- added_at INTEGER NOT NULL,
126030
- created_at DATETIME DEFAULT CURRENT_TIMESTAMP
126031
- )
126032
- `);
126033
- this._db.exec(`
126034
- CREATE INDEX IF NOT EXISTS idx_request_logs_received_at ON request_logs(received_at);
126035
- CREATE INDEX IF NOT EXISTS idx_reprovide_logs_timestamp ON reprovide_logs(timestamp);
126036
- CREATE INDEX IF NOT EXISTS idx_reprovide_logs_key ON reprovide_logs(key);
126037
- `);
126038
- try {
126039
- this._db.exec("ALTER TABLE request_logs ADD COLUMN body_preview TEXT");
126040
- } catch (error) {
126041
- if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column name")) throw error;
126042
- }
126043
- debug$1(`Initialized SQLite database at ${this._dbPath}`);
126044
- } catch (error) {
126045
- debug$1.error(`Failed to initialize database at ${this._dbPath}:`, error);
126046
- throw error;
126047
- }
126048
- }
126049
- close() {
126050
- if (this._db) {
126051
- this._db.close();
126052
- this._db = null;
126053
- }
126054
- }
126055
- insertRequestLogs(logs) {
126056
- if (!this._db) throw new Error("Database not initialized");
126057
- const insertStmt = this._db.prepare(`
126058
- INSERT INTO request_logs (
126059
- keys, received_at, transmitted_at, success, status_code,
126060
- method, url, error, retry_count, body_preview
126061
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
126062
- `);
126063
- this._db.transaction(() => {
126064
- for (const log of logs) insertStmt.run(JSON.stringify(log.keys), log.receivedAt, log.transmittedAt || null, log.success ? 1 : 0, log.statusCode || null, log.method, log.url, log.error || null, log.retryCount || 0, log.bodyPreview || null);
126065
- })();
126066
- }
126067
- insertReprovideLog(key, success, error, blockNotLocal) {
126068
- if (!this._db) throw new Error("Database not initialized");
126069
- this._db.prepare(`
126070
- INSERT INTO reprovide_logs (key, timestamp, success, error, block_not_local)
126071
- VALUES (?, ?, ?, ?, ?)
126072
- `).run(key, Date.now(), success ? 1 : 0, error || null, blockNotLocal ? 1 : 0);
126073
- }
126074
- loadFailedKeys() {
126075
- if (!this._db) return [];
126076
- try {
126077
- return this._db.prepare("SELECT key FROM failed_keys").all().map((row) => row.key);
126078
- } catch (error) {
126079
- debug$1.error("Failed to load failed keys from database:", error);
126080
- return [];
126081
- }
126082
- }
126083
- saveFailedKeys(keys) {
126084
- if (!this._db) throw new Error("Database not initialized");
126085
- this._db.transaction(() => {
126086
- this._db.exec("DELETE FROM failed_keys");
126087
- if (keys.length > 0) {
126088
- const insertStmt = this._db.prepare("INSERT INTO failed_keys (key, added_at) VALUES (?, ?)");
126089
- const now = Date.now();
126090
- for (const key of keys) insertStmt.run(key, now);
126091
- }
126092
- })();
126093
- }
126094
- };
126095
- //#endregion
126096
- //#region dist/node/runtime/node/addresses-rewriter-proxy-server.js
126097
- const debug = logger_default("pkc-js:addresses-rewriter");
126098
- const MAX_BODY_PREVIEW_BYTES = 4096;
126099
- function normalizeSelfAddrsForProvider(addrs, peerId) {
126100
- const suffix = `/p2p/${peerId}`;
126101
- return n$10(addrs.map((addr) => addr.endsWith(suffix) ? addr.slice(0, -suffix.length) : addr));
126102
- }
126103
- var AddressesRewriterProxyServer = class {
126104
- constructor({ kuboClients: kuboClient, port, hostname, proxyTargetUrl, pkc }) {
126105
- this._requestLogBuffer = [];
126106
- this._isWritingLogs = false;
126107
- this._failedKeys = /* @__PURE__ */ new Set();
126108
- this._isRetrying = false;
126109
- this.addresses = {};
126110
- this.kuboClients = kuboClient;
126111
- this.port = port;
126112
- this.hostname = hostname || "127.0.0.1";
126113
- this.proxyTarget = new URL(proxyTargetUrl);
126114
- this.server = http.createServer((req, res) => this._proxyRequestRewrite(req, res));
126115
- this._storageKeyName = `httprouter_proxy_${proxyTargetUrl}`;
126116
- this._pkc = pkc;
126117
- const envValue = process.env.ENABLE_LOGGING_OF_ADDRESS_REWRITER_PROXY;
126118
- this._loggingEnabled = envValue === "1" || envValue?.toLowerCase() === "true";
126119
- if (this._loggingEnabled) {
126120
- const kuboConfig = this.kuboClients?.[0]?.getEndpointConfig();
126121
- this._db = new AddressRewriterDatabase(this._pkc.dataPath, kuboConfig, this.proxyTarget);
126122
- } else this._db = null;
126123
- this._httpAgent = new http.Agent({
126124
- keepAlive: true,
126125
- keepAliveMsecs: 3e4,
126126
- maxSockets: 50,
126127
- timeout: 1e4
126128
- });
126129
- this._httpsAgent = new https.Agent({
126130
- keepAlive: true,
126131
- keepAliveMsecs: 3e4,
126132
- maxSockets: 50,
126133
- timeout: 1e4
126134
- });
126135
- hideClassPrivateProps(this);
126136
- }
126137
- async listen(callback) {
126138
- if (this._loggingEnabled && this._db) {
126139
- await this._db.initialize();
126140
- debug("Request logging enabled for addresses rewriter proxy");
126141
- } else debug("Request logging disabled for addresses rewriter proxy");
126142
- await this._startUpdateAddressesLoop();
126143
- if (this._loggingEnabled) this._startRequestLogging();
126144
- await this._startFailedKeysRetry();
126145
- this.server.on("error", (err) => debug.error("Error with address rewriter proxy", this.server.address(), "Proxy target", this.proxyTarget, err));
126146
- this.server.listen(this.port, this.hostname, callback);
126147
- debug("Addresses rewriter proxy at", this.hostname + ":" + this.port, "started listening to forward requests to", this.proxyTarget.host, `- request logging ${this._loggingEnabled ? "enabled" : "disabled"}`);
126148
- await this._pkc._storage.setItem(this._storageKeyName, `http://${this.hostname}:${this.port}`);
126149
- }
126150
- async destroy() {
126151
- this.server.close();
126152
- if (this._updateAddressesInterval) clearInterval(this._updateAddressesInterval);
126153
- if (this._logWriteInterval) clearInterval(this._logWriteInterval);
126154
- if (this._retryInterval) clearInterval(this._retryInterval);
126155
- await this._writeRequestLogs();
126156
- this._db?.close();
126157
- this._httpAgent.destroy();
126158
- this._httpsAgent.destroy();
126159
- await this._pkc._storage.removeItem(this._storageKeyName);
126160
- }
126161
- _proxyRequestRewrite(req, res) {
126162
- let reqBody = "";
126163
- req.on("data", (chunk) => {
126164
- reqBody += chunk.toString();
126165
- });
126166
- req.on("end", () => {
126167
- const shouldRewrite = req.method === "PUT" || req.method === "POST";
126168
- let requestLogEntry = null;
126169
- if (shouldRewrite) {
126170
- const keys = this._extractKeysFromRequestBody(reqBody);
126171
- const shouldLogRequest = this._loggingEnabled;
126172
- if (keys.length > 0 || shouldLogRequest) {
126173
- requestLogEntry = {
126174
- keys,
126175
- receivedAt: Date.now(),
126176
- success: false,
126177
- method: req.method || "UNKNOWN",
126178
- url: req.url || "/",
126179
- retryCount: 0,
126180
- bodyPreview: shouldLogRequest ? this._createBodyPreview(reqBody) : void 0
126181
- };
126182
- if (shouldLogRequest) this._requestLogBuffer.push(requestLogEntry);
126183
- }
126184
- }
126185
- let rewrittenBody = reqBody;
126186
- if (shouldRewrite && rewrittenBody) try {
126187
- const json = JSON.parse(rewrittenBody);
126188
- if (json.Providers && Array.isArray(json.Providers)) {
126189
- for (const provider of json.Providers) {
126190
- const peerId = provider?.Payload?.ID;
126191
- if (peerId && this.addresses[peerId]) provider.Payload.Addrs = this.addresses[peerId];
126192
- }
126193
- rewrittenBody = JSON.stringify(json);
126194
- }
126195
- } catch (e) {
126196
- debug("proxy body rewrite error:", e, "body", rewrittenBody, req.url, req.method);
126197
- }
126198
- this._proxyRequest(req, res, rewrittenBody, requestLogEntry);
126199
- });
126200
- req.on("error", (err) => {
126201
- debug.trace("Request error:", req.url, req.method, req.headers, reqBody, err);
126202
- if (!res.headersSent) {
126203
- debug.trace("Request error:", req.url, req.method, req.headers, reqBody, err);
126204
- res.writeHead(500);
126205
- res.end("Internal Server Error");
126206
- }
126207
- });
126208
- }
126209
- _proxyRequest(req, res, rewrittenBody, requestLogEntry) {
126210
- if (requestLogEntry) {
126211
- requestLogEntry.retryCount = 0;
126212
- requestLogEntry.transmittedAt = Date.now();
126213
- }
126214
- const { request: httpRequest } = this.proxyTarget.protocol === "https:" ? https : http;
126215
- const agent = this.proxyTarget.protocol === "https:" ? this._httpsAgent : this._httpAgent;
126216
- const requestOptions = {
126217
- hostname: this.proxyTarget.hostname,
126218
- protocol: this.proxyTarget.protocol,
126219
- path: req.url,
126220
- method: req.method,
126221
- headers: {
126222
- ...req.headers,
126223
- "content-length": Buffer.byteLength(rewrittenBody),
126224
- host: this.proxyTarget.host
126225
- },
126226
- agent,
126227
- timeout: 1e4
126228
- };
126229
- if (this.proxyTarget.port) requestOptions.port = this.proxyTarget.port;
126230
- const proxyReq = httpRequest(requestOptions);
126231
- proxyReq.setTimeout(1e4, () => {
126232
- debug.trace("Proxy request timed out", requestOptions);
126233
- if (requestLogEntry) {
126234
- requestLogEntry.success = false;
126235
- requestLogEntry.statusCode = 504;
126236
- requestLogEntry.error = "Request timeout";
126237
- requestLogEntry.completed = true;
126238
- if (requestLogEntry.keys) {
126239
- const sizeBefore = this._failedKeys.size;
126240
- requestLogEntry.keys.forEach((key) => this._failedKeys.add(key));
126241
- if (this._failedKeys.size > sizeBefore) this._saveFailedKeysToDatabase();
126242
- }
126243
- }
126244
- proxyReq.destroy();
126245
- if (!res.headersSent) {
126246
- res.writeHead(504);
126247
- res.end("Gateway Timeout");
126248
- }
126249
- });
126250
- proxyReq.on("error", (e) => {
126251
- proxyReq.destroy();
126252
- if (requestLogEntry) {
126253
- requestLogEntry.success = false;
126254
- requestLogEntry.statusCode = 500;
126255
- requestLogEntry.error = `Proxy error: ${e.message}`;
126256
- requestLogEntry.completed = true;
126257
- debug.trace(`Updated log entry with error for keys: ${requestLogEntry.keys.join(", ")}`);
126258
- if (requestLogEntry.keys) {
126259
- const sizeBefore = this._failedKeys.size;
126260
- requestLogEntry.keys.forEach((key) => this._failedKeys.add(key));
126261
- if (this._failedKeys.size > sizeBefore) this._saveFailedKeysToDatabase();
126262
- }
126263
- }
126264
- if (!res.headersSent) {
126265
- debug.trace("address rewriter proxy error:", e, "Request options", requestOptions);
126266
- res.writeHead(500);
126267
- res.end("Internal Server Error");
126268
- }
126269
- });
126270
- proxyReq.on("response", (proxyRes) => {
126271
- const statusCode = proxyRes.statusCode || 500;
126272
- const isSuccess = statusCode >= 200 && statusCode < 300;
126273
- if (requestLogEntry) {
126274
- requestLogEntry.success = isSuccess;
126275
- requestLogEntry.statusCode = statusCode;
126276
- requestLogEntry.completed = true;
126277
- if (!isSuccess) {
126278
- requestLogEntry.error = `HTTP ${statusCode}`;
126279
- if (requestLogEntry.keys) {
126280
- const sizeBefore = this._failedKeys.size;
126281
- requestLogEntry.keys.forEach((key) => this._failedKeys.add(key));
126282
- if (this._failedKeys.size > sizeBefore) this._saveFailedKeysToDatabase();
126283
- }
126284
- }
126285
- }
126286
- proxyRes.on("error", (err) => {
126287
- debug.trace("Proxy response error:", err);
126288
- if (!res.headersSent) {
126289
- res.writeHead(500);
126290
- res.end("Proxy Response Error");
126291
- }
126292
- if (requestLogEntry) {
126293
- requestLogEntry.success = false;
126294
- requestLogEntry.statusCode = 500;
126295
- requestLogEntry.error = `Proxy response error: ${err.message}`;
126296
- requestLogEntry.completed = true;
126297
- }
126298
- proxyRes.destroy(err);
126299
- });
126300
- if (!res.headersSent) {
126301
- res.writeHead(statusCode, proxyRes.headers);
126302
- proxyRes.pipe(res);
126303
- }
126304
- res.on("finish", () => {
126305
- proxyRes.resume();
126306
- });
126307
- });
126308
- proxyReq.write(rewrittenBody);
126309
- proxyReq.end();
126310
- }
126311
- async _startUpdateAddressesLoop() {
126312
- if (!this.kuboClients?.length) throw Error("should have a defined kubo rpc client option to start the address rewriter");
126313
- const isRetriableError = (error) => {
126314
- if (typeof error !== "object" || error === null) return false;
126315
- const err = error;
126316
- return err.response?.status === 500 || err.status === 500 || err.statusCode === 500;
126317
- };
126318
- const tryUpdateAddressesForClient = async (kuboClient) => {
126319
- return new Promise((resolve) => {
126320
- const operation = import_retry.operation({
126321
- retries: 3,
126322
- factor: 2,
126323
- minTimeout: 1e3,
126324
- maxTimeout: 8e3
126325
- });
126326
- operation.attempt(async (currentAttempt) => {
126327
- try {
126328
- const idRes = await kuboClient.id();
126329
- const swarmAddrsRes = await kuboClient.swarm.addrs();
126330
- const peerId = idRes.id.toString();
126331
- if (typeof peerId !== "string") throw Error("Failed to get Peer ID of kubo node");
126332
- const swarmListeningAddresses = swarmAddrsRes.filter((swarmAddr) => swarmAddr.id.toString() === peerId);
126333
- const addresses = normalizeSelfAddrsForProvider([...idRes.addresses.map((addr) => addr.toString()), ...n$5(swarmListeningAddresses.map((swarmAddr) => swarmAddr.addrs.map((addr) => addr.toString())))], peerId);
126334
- if (addresses.length === 0) throw Error(`Failed to get any addresses for peer ${peerId}`);
126335
- this.addresses[peerId] = addresses;
126336
- resolve();
126337
- } catch (e) {
126338
- const error = e;
126339
- if (isRetriableError(error)) {
126340
- debug(`tryUpdateAddresses attempt ${currentAttempt}/4 failed with 500 error:`, error.message, { kuboConfig: kuboClient.getEndpointConfig() });
126341
- if (operation.retry(error)) return;
126342
- }
126343
- debug("tryUpdateAddresses error:", error.message, { kuboConfig: kuboClient.getEndpointConfig() });
126344
- resolve();
126345
- }
126346
- });
126347
- });
126348
- };
126349
- const tryUpdateAddresses = async () => {
126350
- const promises = this.kuboClients.map(tryUpdateAddressesForClient);
126351
- await Promise.allSettled(promises);
126352
- };
126353
- await tryUpdateAddresses();
126354
- this._updateAddressesInterval = setInterval(tryUpdateAddresses, 1e3 * 60);
126355
- }
126356
- _extractKeysFromRequestBody(body) {
126357
- try {
126358
- const json = JSON.parse(body);
126359
- const keys = [];
126360
- if (json.Providers && Array.isArray(json.Providers)) {
126361
- for (const provider of json.Providers) if (provider?.Payload?.Keys) keys.push(...provider.Payload.Keys);
126362
- }
126363
- return keys;
126364
- } catch {
126365
- return [];
126366
- }
126367
- }
126368
- _createBodyPreview(body) {
126369
- const buffer = Buffer.from(body, "utf8");
126370
- if (buffer.length <= MAX_BODY_PREVIEW_BYTES) return body;
126371
- return `${buffer.subarray(0, MAX_BODY_PREVIEW_BYTES).toString("utf8")}...[truncated ${buffer.length - MAX_BODY_PREVIEW_BYTES} bytes]`;
126372
- }
126373
- async _writeRequestLogs() {
126374
- if (!this._loggingEnabled || !this._db) return;
126375
- if (this._requestLogBuffer.length === 0 || this._isWritingLogs) return;
126376
- this._isWritingLogs = true;
126377
- const logsToWrite = this._requestLogBuffer.filter((entry) => entry.completed);
126378
- if (logsToWrite.length === 0) {
126379
- this._isWritingLogs = false;
126380
- return;
126381
- }
126382
- const inFlightLogs = this._requestLogBuffer.filter((entry) => !entry.completed);
126383
- this._requestLogBuffer = inFlightLogs;
126384
- try {
126385
- this._db.insertRequestLogs(logsToWrite);
126386
- debug.trace(`Wrote ${logsToWrite.length} new request log entries to SQLite database`);
126387
- } catch (error) {
126388
- debug.error(`Failed to write request logs to SQLite database:`, error);
126389
- this._requestLogBuffer.unshift(...logsToWrite);
126390
- } finally {
126391
- this._isWritingLogs = false;
126392
- }
126393
- }
126394
- _startRequestLogging() {
126395
- if (!this._loggingEnabled || !this._db) return;
126396
- const writeInterval = 5 * 1e3;
126397
- this._logWriteInterval = setInterval(async () => {
126398
- await this._writeRequestLogs();
126399
- }, writeInterval);
126400
- }
126401
- async _startFailedKeysRetry() {
126402
- this._loadFailedKeysFromDatabase();
126403
- const retryInterval = 120 * 1e3;
126404
- this._retryInterval = setInterval(async () => {
126405
- if (this._isRetrying) {
126406
- debug.trace("Previous failed-keys retry still running, skipping this tick");
126407
- return;
126408
- }
126409
- this._isRetrying = true;
126410
- try {
126411
- await this._retryFailedKeys();
126412
- } finally {
126413
- this._isRetrying = false;
126414
- }
126415
- }, retryInterval);
126416
- debug(`Started failed keys retry with ${this._failedKeys.size} keys from previous sessions`);
126417
- }
126418
- _loadFailedKeysFromDatabase() {
126419
- if (!this._loggingEnabled || !this._db) return;
126420
- try {
126421
- const keys = this._db.loadFailedKeys();
126422
- keys.forEach((key) => this._failedKeys.add(key));
126423
- debug(`Loaded ${keys.length} failed keys from database`);
126424
- } catch (error) {
126425
- debug.error("Failed to load failed keys from database:", error);
126426
- throw error;
126427
- }
126428
- }
126429
- _saveFailedKeysToDatabase() {
126430
- if (!this._loggingEnabled || !this._db) return;
126431
- try {
126432
- const keys = Array.from(this._failedKeys);
126433
- this._db.saveFailedKeys(keys);
126434
- if (keys.length === 0) debug.trace(`All keys successfully provided - no failed keys to save`);
126435
- else debug.trace(`Saved ${keys.length} failed keys to database`);
126436
- } catch (error) {
126437
- debug.error("Failed to save failed keys to database:", error);
126438
- throw error;
126439
- }
126440
- }
126441
- async _retryFailedKeys() {
126442
- if (this._failedKeys.size === 0) {
126443
- debug.trace(`No failed keys to retry - all keys successfully provided`);
126444
- return;
126445
- }
126446
- debug(`Retrying ${this._failedKeys.size} failed keys`);
126447
- const keysToRetry = Array.from(this._failedKeys);
126448
- const kuboClient = this.kuboClients?.[0];
126449
- if (!kuboClient) {
126450
- debug.error("No kubo client available for retry");
126451
- return;
126452
- }
126453
- const successfulKeys = [];
126454
- const stillFailedKeys = [];
126455
- const keysToDiscard = [];
126456
- for (const key of keysToRetry) try {
126457
- debug.trace(`Providing key to HTTP routers: ${key}`);
126458
- const events = [];
126459
- for await (const event of kuboClient.routing.provide(key, {
126460
- recursive: true,
126461
- verbose: true
126462
- })) {
126463
- events.push(event);
126464
- debug(`Routing provide event for ${key}:`, event);
126465
- }
126466
- successfulKeys.push(key);
126467
- debug.trace(`Successfully provided key: ${key}`);
126468
- this._logReprovideAttempt(key, true, void 0, false);
126469
- } catch (error) {
126470
- const errorMessage = error instanceof Error ? error.message : String(error);
126471
- const isBlockNotLocal = errorMessage.includes("block") && errorMessage.includes("not found locally");
126472
- this._logReprovideAttempt(key, false, errorMessage, isBlockNotLocal);
126473
- if (isBlockNotLocal) {
126474
- keysToDiscard.push(key);
126475
- debug.trace(`Discarding key ${key} - block not found locally, will not retry`);
126476
- } else {
126477
- stillFailedKeys.push(key);
126478
- debug.trace(`Failed to provide key ${key}:`, error);
126479
- }
126480
- }
126481
- successfulKeys.forEach((key) => this._failedKeys.delete(key));
126482
- keysToDiscard.forEach((key) => this._failedKeys.delete(key));
126483
- this._saveFailedKeysToDatabase();
126484
- debug.trace(`Retry completed: ${successfulKeys.length} successful, ${stillFailedKeys.length} still failed, ${keysToDiscard.length} discarded`);
126485
- }
126486
- _logReprovideAttempt(key, success, error, blockNotLocal) {
126487
- if (!this._loggingEnabled || !this._db) return;
126488
- try {
126489
- this._db.insertReprovideLog(key, success, error, blockNotLocal);
126490
- debug.trace(`Logged reprovide attempt for key ${key}: success=${success}, blockNotLocal=${blockNotLocal}`);
126491
- } catch (error) {
126492
- debug.error(`Failed to log reprovide attempt for key ${key}:`, error);
126493
- throw error;
126494
- }
126495
- }
126496
- };
126497
- //#endregion
126498
126216
  //#region node_modules/lru-cache/dist/esm/index.js
126499
126217
  /**
126500
126218
  * @module LRUCache
@@ -129875,4 +129593,4 @@ var RpcLocalCommunity = class extends RpcRemoteCommunity {
129875
129593
  }
129876
129594
  };
129877
129595
  //#endregion
129878
- export { parseRawPages as $, t$5 as $n, parseCommentEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as $t, deriveCommentIpfsFromCommentTableRow as A, RpcAuthorNameParamSchema as An, verifyCommunity as At, resolveDbPostsCidRefs as B, RpcExportCommunityResultSchema as Bn, getCommunityNameFromWire$1 as Bt, encryptEd25519AesGcmPublicKeyBuffer as C, parsePKCUserOptionsSchemaWithPKCErrorIfItFails as Cn, verifyChallengeRequest as Ct, calculateInlineRepliesBudget as D, parseVoteChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as Dn, verifyCommentModeration as Dt, calculateExpectedSignatureSize as E, parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails as En, verifyCommentIpfs as Et, getThumbnailPropsOfLink as F, RpcCommunityPageParamSchema as Fn, getAuthorNameFromRuntime as Ft, POST_REPLIES_SORT_TYPES as G, RpcPublishedAnchorRecordResultSchema as Gn, getBufferedPKCAddressFromPublicKey as Gt, tryToDeleteCommunitiesThatFailedToBeDeletedBefore as H, RpcFetchCidResultSchema as Hn, normalizeCommunityInputFromCommunity as Ht, importSignerIntoKuboNode as I, RpcEditCommunityParamSchema as In, getAuthorNameFromWire as It, buildPageRuntimeFields as J, RpcSuccessResultSchema as Jn, getPKCAddressFromPublicKeySync as Jt, REPLY_REPLIES_SORT_TYPES as K, RpcResolveAuthorNameResultSchema as Kn, getIpfsKeyFromPrivateKey as Kt, listCommunitiesSync as L, RpcExportCommunityModLogsParamSchema as Ln, normalizeCreatePublicationAuthor as Lt, deriveDbReplies as M, RpcCidParamSchema as Mn, verifyVote as Mt, getDefaultCommunityDbConfig as N, RpcCommentRepliesPageParamSchema as Nn, buildRuntimeAuthor as Nt, createKuboRpcClient as O, parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails as On, verifyCommentPubsubMessage as Ot, getDefaultDataPath as P, RpcCommunityIdentifierParamSchema as Pn, cleanWireAuthor as Pt, iterateOverPageCidsToFindAllCids as Q, r as Qn, parseCommentChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as Qt, monitorCommunitiesDirectory as R, RpcExportCommunityModLogsResultSchema as Rn, buildRuntimeCommunityFields as Rt, encryptEd25519AesGcm as S, parseJsonWithPKCErrorIfFails as Sn, verifyChallengeMessage as St, backupCommunityDb as T, parseRpcCommentUpdateEventWithPKCErrorIfItFails as Tn, verifyCommentEdit as Tt, CommentClientsManager as U, RpcPublishAnchorRecordParamSchema as Un, decode as Ut, setNativeFunctions as V, RpcFetchCidParamSchema as Vn, getCommunityPublicKeyFromWire as Vt, POSTS_SORT_TYPES as W, RpcPublishChallengeAnswersParamSchema as Wn, encode as Wt, extractCommunityRuntimeFieldsFromParsedPages as X, t$2 as Xn, createSchemaRowParser as Xt, buildPagesRuntimeFields as Y, RpcUnsubscribeParamSchema as Yn, getPublicKeyFromPrivateKey as Yt, findCommentInPageInstanceRecursively as Z, t$4 as Zn, parseCidStringSchemaWithPKCErrorIfItFails as Zt, SignerWithPublicKeyAddress as _, parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails as _n, signCommentUpdateForChallengeVerification as _t, pkcJsChallenges as a, parseCommunityAddressWithPKCErrorIfItFails as an, STORAGE_KEYS as ar, pLimit as at, decryptEd25519AesGcm as b, parseDecryptedChallengeVerification as bn, signVote as bt, AddressesRewriterProxyServer as c, parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails as cn, require_undici as cr, cleanUpBeforePublishing as ct, MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS as d, parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails as dn, signChallengeRequest as dt, parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails as en, n$5 as er, RepliesPages as et, KeyvBetterSqlite3 as f, parseCreateCommentOptionsSchemaWithPKCErrorIfItFails as fn, signChallengeVerification as ft, decodeRpcChallengeVerificationPubsubMsg as g, parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails as gn, signCommentUpdate as gt, decodeRpcChallengeRequestPubsubMsg as h, parseCreatePKCWsServerOptionsSchemaWithPKCErrorIfItFails as hn, signCommentModeration as ht, getCommunityChallengeFromCommunityChallengeSettings as i, parseCommentPubsubMessagePublicationWithPKCErrorIfItFails as in, stringify as ir, pRetry as it, deriveDbPosts as j, RpcCancelExportParamSchema as jn, verifyCommunityEdit as jt, deleteOldCommunityInWindows as k, RpcAnchorPublishPreparationResultSchema as kn, verifyCommentUpdate as kt, normalizeSelfAddrsForProvider as l, parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails as ln, signChallengeAnswer as lt, decodeRpcChallengePubsubMsg as m, parseCreateNewLocalCommunityUserOptionsSchemaWithPKCErrorIfItFails as mn, signCommentEdit as mt, RpcRemoteCommunity as n, parseCommentModerationChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as nn, t$7 as nr, PKCClientsManager as nt, TrackedInstanceRegistry as o, parseCommunityEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as on, require_lodash_merge as or, PKCTypedEmitter as ot, decodeRpcChallengeAnswerPubsubMsg as p, parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails as pn, signComment as pt, TIMEFRAMES_TO_SECONDS as q, RpcSubscriptionIdResultSchema as qn, getPKCAddressFromPublicKey as qt, getChallengeVerification as r, parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails as rn, t$8 as rr, InflightFetchManager as rt, LRUCache as s, parseCommunityEditOptionsSchemaWithPKCErrorIfItFails as sn, nativeFunctions$1 as sr, require_lib$1 as st, RpcLocalCommunity as t, parseCommentIpfsSchemaWithPKCErrorIfItFails as tn, n$6 as tr, PublicationClientsManager as tt, RemoteCommunity as u, parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails as un, signChallengeMessage as ut, createSigner as v, parseCreateVoteOptionsSchemaWithPKCErrorIfItFails as vn, signCommunity as vt, BackupAbortError as w, parseRpcCommentEventWithPKCErrorIfItFails as wn, verifyChallengeVerification as wt, decryptEd25519AesGcmPublicKeyBuffer as x, parseDecryptedChallengeWithPKCErrorIfItFails as xn, verifyChallengeAnswer as xt, createAnchorIpnsRecord as y, parseDecryptedChallengeAnswerWithPKCErrorIfItFails as yn, signCommunityEdit as yt, moveCommunityDbToDeletedDirectory as z, RpcExportCommunityParamSchema as zn, getCommunityAddressFromRecord as zt };
129596
+ export { applyNameResolvedCacheToCrosspost as $, crosspostChainDepthUpTo as $n, createSchemaRowParser as $t, deriveDbReplies as A, parseVoteChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as An, verifyCommentModeration as At, tryToDeleteCommunitiesThatFailedToBeDeletedBefore as B, RpcExportCommunityModLogsParamSchema as Bn, normalizeCreatePublicationAuthor as Bt, backupCommunityDb as C, parseDecryptedChallengeVerification as Cn, signVote as Ct, deleteOldCommunityInWindows as D, parseRpcCommentEventWithPKCErrorIfItFails as Dn, verifyChallengeVerification as Dt, createKuboRpcClient as E, parsePKCUserOptionsSchemaWithPKCErrorIfItFails as En, verifyChallengeRequest as Et, listCommunitiesSync as F, RpcCidParamSchema as Fn, verifyVote as Ft, TIMEFRAMES_TO_SECONDS as G, RpcFetchCidResultSchema as Gn, normalizeCommunityInputFromCommunity as Gt, POSTS_SORT_TYPES as H, RpcExportCommunityParamSchema as Hn, getCommunityAddressFromRecord as Ht, monitorCommunitiesDirectory as I, RpcCommentRepliesPageParamSchema as In, buildRuntimeAuthor as It, extractCommunityRuntimeFieldsFromParsedPages as J, RpcPublishedAnchorRecordResultSchema as Jn, getBufferedPKCAddressFromPublicKey as Jt, buildPageRuntimeFields as K, RpcPublishAnchorRecordParamSchema as Kn, decode as Kt, moveCommunityDbToDeletedDirectory as L, RpcCommunityIdentifierParamSchema as Ln, cleanWireAuthor as Lt, getDefaultDataPath as M, RpcAnchorPublishPreparationResultSchema as Mn, verifyCommentUpdate as Mt, getThumbnailPropsOfLink as N, RpcAuthorNameParamSchema as Nn, verifyCommunity as Nt, deriveCommentIpfsFromCommentTableRow as O, parseRpcCommentUpdateEventWithPKCErrorIfItFails as On, verifyCommentEdit as Ot, importSignerIntoKuboNode as P, RpcCancelExportParamSchema as Pn, verifyCommunityEdit as Pt, RepliesPages as Q, RpcUnsubscribeParamSchema as Qn, getPublicKeyFromPrivateKey as Qt, resolveDbPostsCidRefs as R, RpcCommunityPageParamSchema as Rn, getAuthorNameFromRuntime as Rt, BackupAbortError as S, parseDecryptedChallengeAnswerWithPKCErrorIfItFails as Sn, signCommunityEdit as St, calculateInlineRepliesBudget as T, parseJsonWithPKCErrorIfFails as Tn, verifyChallengeMessage as Tt, POST_REPLIES_SORT_TYPES as U, RpcExportCommunityResultSchema as Un, getCommunityNameFromWire$1 as Ut, CommentClientsManager as V, RpcExportCommunityModLogsResultSchema as Vn, buildRuntimeCommunityFields as Vt, REPLY_REPLIES_SORT_TYPES as W, RpcFetchCidParamSchema as Wn, getCommunityPublicKeyFromWire as Wt, iterateOverPageCidsToFindAllCids as X, RpcSubscriptionIdResultSchema as Xn, getPKCAddressFromPublicKey as Xt, findCommentInPageInstanceRecursively as Y, RpcResolveAuthorNameResultSchema as Yn, getIpfsKeyFromPrivateKey as Yt, parseRawPages as Z, RpcSuccessResultSchema as Zn, getPKCAddressFromPublicKeySync as Zt, createAnchorIpnsRecord as _, parseCreateNewLocalCommunityUserOptionsSchemaWithPKCErrorIfItFails as _n, signCommentEdit as _t, pkcJsChallenges as a, parseCommentModerationChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as an, n$5 as ar, PKCClientsManager as at, encryptEd25519AesGcm as b, parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails as bn, signCommentUpdateForChallengeVerification as bt, RemoteCommunity as c, parseCommunityAddressWithPKCErrorIfItFails as cn, t$8 as cr, pLimit as ct, decodeRpcChallengeAnswerPubsubMsg as d, parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails as dn, require_lodash_merge as dr, cleanUpBeforePublishing as dt, parseCidStringSchemaWithPKCErrorIfItFails as en, effectiveMaxCrosspostDepth as er, cloneCrosspostForRuntime as et, decodeRpcChallengePubsubMsg as f, parseCommunityIpfsSchemaPassthroughWithPKCErrorIfItFails as fn, nativeFunctions$1 as fr, signChallengeAnswer as ft, createSigner as g, parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails as gn, signComment as gt, SignerWithPublicKeyAddress as h, parseCreateCommentOptionsSchemaWithPKCErrorIfItFails as hn, signChallengeVerification as ht, getCommunityChallengeFromCommunityChallengeSettings as i, parseCommentIpfsSchemaWithPKCErrorIfItFails as in, t$5 as ir, PublicationClientsManager as it, getDefaultCommunityDbConfig as j, parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails as jn, verifyCommentPubsubMessage as jt, deriveDbPosts as k, parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails as kn, verifyCommentIpfs as kt, MAX_FILE_SIZE_BYTES_FOR_COMMUNITY_IPFS as l, parseCommunityEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as ln, stringify as lr, PKCTypedEmitter as lt, decodeRpcChallengeVerificationPubsubMsg as m, parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails as mn, signChallengeRequest as mt, RpcRemoteCommunity as n, parseCommentEditChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as nn, t$4 as nr, extractCrosspostRuntimeFields as nt, TrackedInstanceRegistry as o, parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails as on, n$6 as or, InflightFetchManager as ot, decodeRpcChallengeRequestPubsubMsg as p, parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails as pn, require_undici as pr, signChallengeMessage as pt, buildPagesRuntimeFields as q, RpcPublishChallengeAnswersParamSchema as qn, encode as qt, getChallengeVerification as r, parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails as rn, r as rr, stripNameResolvedFromCrosspost as rt, LRUCache as s, parseCommentPubsubMessagePublicationWithPKCErrorIfItFails as sn, t$7 as sr, pRetry as st, RpcLocalCommunity as t, parseCommentChallengeRequestToEncryptSchemaWithPKCErrorIfItFails as tn, t$2 as tr, collectCrosspostAuthorsToResolve as tt, KeyvBetterSqlite3 as u, parseCommunityEditOptionsSchemaWithPKCErrorIfItFails as un, STORAGE_KEYS as ur, require_lib$1 as ut, decryptEd25519AesGcm as v, parseCreatePKCWsServerOptionsSchemaWithPKCErrorIfItFails as vn, signCommentModeration as vt, calculateExpectedSignatureSize as w, parseDecryptedChallengeWithPKCErrorIfItFails as wn, verifyChallengeAnswer as wt, encryptEd25519AesGcmPublicKeyBuffer as x, parseCreateVoteOptionsSchemaWithPKCErrorIfItFails as xn, signCommunity as xt, decryptEd25519AesGcmPublicKeyBuffer as y, parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails as yn, signCommentUpdate as yt, setNativeFunctions as z, RpcEditCommunityParamSchema as zn, getAuthorNameFromWire as zt };