@openpeepshq/core 0.1.32 → 0.1.34

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 (261) hide show
  1. package/dist/accessTokens/helpers.d.ts +2 -2
  2. package/dist/accessTokens/tokens.js +14 -7
  3. package/dist/accounts/mutations.d.ts +2 -2
  4. package/dist/accounts/mutations.js +33 -35
  5. package/dist/analytics/cache.js +12 -7
  6. package/dist/analytics/compile.js +16 -10
  7. package/dist/analytics/pdfReport.d.ts +1 -0
  8. package/dist/analytics/pdfReport.js +5 -4
  9. package/dist/analytics/privacy.d.ts +18 -0
  10. package/dist/analytics/privacy.js +10 -0
  11. package/dist/analytics/read.js +75 -19
  12. package/dist/analytics/report.d.ts +21 -1
  13. package/dist/analytics/report.js +9 -2
  14. package/dist/backups/index.js +78 -15
  15. package/dist/backups/metadata.d.ts +8 -2
  16. package/dist/backups/metadata.js +6 -2
  17. package/dist/config/defaults/capabilities.js +13 -2
  18. package/dist/config/defaults/community.js +7 -9
  19. package/dist/config/defaults/core.d.ts +1 -1
  20. package/dist/config/defaults/core.js +3 -0
  21. package/dist/config/defaults/db.d.ts +0 -2
  22. package/dist/config/defaults/db.js +0 -2
  23. package/dist/config/index.d.ts +25 -3
  24. package/dist/config/index.js +7 -1
  25. package/dist/db/helpers.d.ts +7 -28
  26. package/dist/db/helpers.js +30 -152
  27. package/dist/db/index.d.ts +3 -1
  28. package/dist/db/index.js +5 -0
  29. package/dist/db/init.js +2 -2
  30. package/dist/db/migration/importCollections.d.ts +15 -10
  31. package/dist/db/migration/importCollections.js +121 -155
  32. package/dist/db/migration/shared.d.ts +2 -37
  33. package/dist/db/migration/shared.js +2 -59
  34. package/dist/db/pg/client.js +4 -0
  35. package/dist/db/pg/collections.d.ts +2 -2
  36. package/dist/db/pg/collections.js +2 -2
  37. package/dist/db/pg/filters/edges.d.ts +1 -1
  38. package/dist/db/pg/filters/edges.js +1 -1
  39. package/dist/db/pg/filters/posts.d.ts +11 -0
  40. package/dist/db/pg/filters/posts.js +37 -3
  41. package/dist/db/pg/filters/profiles.d.ts +1 -0
  42. package/dist/db/pg/filters/profiles.js +2 -1
  43. package/dist/db/pg/map/filters.js +37 -2
  44. package/dist/db/pg/map/mutations.js +13 -8
  45. package/dist/db/pg/map/registry.d.ts +5 -0
  46. package/dist/db/pg/map/registry.js +64 -24
  47. package/dist/db/pg/map/relations.d.ts +1 -1
  48. package/dist/db/pg/map/relations.js +98 -46
  49. package/dist/db/pg/migrate.d.ts +22 -0
  50. package/dist/db/pg/migrate.js +88 -2
  51. package/dist/db/pg/queries/activity.js +3 -3
  52. package/dist/db/pg/queries/sorts.d.ts +1 -0
  53. package/dist/db/pg/queries/sorts.js +4 -0
  54. package/dist/db/pg/schema/documents.d.ts +422 -41
  55. package/dist/db/pg/schema/documents.js +43 -9
  56. package/dist/db/pg/schema/edges.d.ts +117 -7
  57. package/dist/db/pg/schema/edges.js +4 -2
  58. package/dist/db/pg/schema/index.d.ts +505 -15
  59. package/dist/db/pg/sql/0007_shallow_oracle.sql +3 -0
  60. package/dist/db/pg/sql/0008_group_owner_roles.sql +31 -0
  61. package/dist/db/pg/sql/0009_event_occurrences.sql +26 -0
  62. package/dist/db/pg/sql/0010_user_group_membership_roles.sql +16 -0
  63. package/dist/db/pg/sql/0011_drop_data_migrations.sql +1 -0
  64. package/dist/db/pg/sql/0012_posts_last_activity_at.sql +5 -0
  65. package/dist/db/pg/sql/0013_add_blocks_edge.sql +12 -0
  66. package/dist/db/pg/sql/0014_federation_datamodel.sql +59 -0
  67. package/dist/db/pg/sql/0015_profile_hashtags.sql +12 -0
  68. package/dist/db/pg/sql/meta/{0006_snapshot.json → 0015_snapshot.json} +393 -39
  69. package/dist/db/pg/sql/meta/_journal.json +64 -1
  70. package/dist/db/replaceOrigin.js +6 -0
  71. package/dist/db/types.d.ts +0 -4
  72. package/dist/email/render.js +11 -3
  73. package/dist/events/index.d.ts +6 -1
  74. package/dist/events/index.js +55 -33
  75. package/dist/federation/activities.d.ts +17 -0
  76. package/dist/federation/activities.js +26 -0
  77. package/dist/federation/identity.d.ts +16 -0
  78. package/dist/federation/identity.js +52 -0
  79. package/dist/federation/index.d.ts +4 -0
  80. package/dist/federation/index.js +3 -0
  81. package/dist/federation/profiles.d.ts +3 -0
  82. package/dist/federation/profiles.js +14 -0
  83. package/dist/groups/finders.d.ts +3 -2
  84. package/dist/groups/helpers.d.ts +24 -6
  85. package/dist/groups/mapping.d.ts +6 -4
  86. package/dist/groups/mapping.js +2 -2
  87. package/dist/groups/mutations.js +1 -1
  88. package/dist/hashtags/finders.d.ts +6 -3
  89. package/dist/hashtags/finders.js +2 -0
  90. package/dist/hashtags/helpers.d.ts +8 -0
  91. package/dist/hashtags/helpers.js +4 -0
  92. package/dist/hashtags/index.d.ts +2 -0
  93. package/dist/hashtags/index.js +2 -0
  94. package/dist/hashtags/mutations.d.ts +3 -0
  95. package/dist/hashtags/mutations.js +13 -1
  96. package/dist/i18n/index.d.ts +1 -1
  97. package/dist/i18n/index.js +3 -1
  98. package/dist/i18n/pluginLocales.d.ts +6 -0
  99. package/dist/i18n/pluginLocales.js +15 -0
  100. package/dist/inviteLinks/helpers.d.ts +4 -4
  101. package/dist/jams/cache.d.ts +1 -1
  102. package/dist/jams/cache.js +2 -1
  103. package/dist/jams/export.d.ts +19 -0
  104. package/dist/jams/export.js +60 -0
  105. package/dist/jams/finders.d.ts +2 -1
  106. package/dist/jams/finders.js +18 -7
  107. package/dist/jams/health.d.ts +8 -0
  108. package/dist/jams/health.js +46 -0
  109. package/dist/jams/helpers.d.ts +6 -2
  110. package/dist/jams/index.d.ts +6 -3
  111. package/dist/jams/index.js +41 -27
  112. package/dist/jams/jobs.js +1 -1
  113. package/dist/jams/livekit.d.ts +93 -10
  114. package/dist/jams/livekit.js +151 -52
  115. package/dist/jams/mapping.d.ts +17 -7
  116. package/dist/jams/mutations.d.ts +3 -1
  117. package/dist/jams/recording.d.ts +10 -0
  118. package/dist/jams/recording.js +32 -0
  119. package/dist/jams/rtmp.d.ts +5 -0
  120. package/dist/jams/rtmp.js +8 -0
  121. package/dist/jams/token.d.ts +15 -3
  122. package/dist/jams/token.js +30 -16
  123. package/dist/jams/waitingRoom.d.ts +6 -6
  124. package/dist/jams/waitingRoom.js +24 -23
  125. package/dist/jobs/index.d.ts +1 -0
  126. package/dist/jobs/index.js +6 -1
  127. package/dist/jobs/jobDetail.js +1 -6
  128. package/dist/media/index.d.ts +1 -1
  129. package/dist/media/index.js +23 -8
  130. package/dist/media/processing.js +18 -7
  131. package/dist/notifications/defaultNotifications/follow/index.js +2 -2
  132. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +3 -1
  133. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +3 -1
  134. package/dist/notifications/defaultNotifications/index.js +4 -0
  135. package/dist/notifications/defaultNotifications/newGroupPost/index.js +12 -6
  136. package/dist/notifications/defaultNotifications/pollEnded/index.d.ts +19 -0
  137. package/dist/notifications/defaultNotifications/pollEnded/index.js +39 -0
  138. package/dist/notifications/defaultNotifications/pollEnded/recipients.d.ts +3 -0
  139. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +18 -0
  140. package/dist/notifications/defaultNotifications/rsvp/index.d.ts +6 -1
  141. package/dist/notifications/defaultNotifications/rsvp/index.js +7 -0
  142. package/dist/notifications/defaultNotifications/rsvpCanceled/index.d.ts +24 -0
  143. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +75 -0
  144. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.d.ts +4 -0
  145. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.js +11 -0
  146. package/dist/notifications/helpers.js +6 -2
  147. package/dist/notifications/jobs.js +3 -1
  148. package/dist/notifications/mutations.js +4 -0
  149. package/dist/notifications/push.js +11 -4
  150. package/dist/plugins/helpers.d.ts +1 -0
  151. package/dist/plugins/helpers.js +1 -8
  152. package/dist/plugins/index.d.ts +5 -0
  153. package/dist/plugins/index.js +78 -5
  154. package/dist/plugins/install.d.ts +39 -0
  155. package/dist/plugins/install.js +455 -0
  156. package/dist/plugins/pluginAuth.d.ts +1 -1
  157. package/dist/plugins/pluginAuth.js +10 -6
  158. package/dist/plugins/state.d.ts +4 -0
  159. package/dist/plugins/state.js +29 -0
  160. package/dist/posts/activity.d.ts +9 -0
  161. package/dist/posts/activity.js +35 -0
  162. package/dist/posts/contextClosure.d.ts +1 -9
  163. package/dist/posts/contextClosure.js +15 -44
  164. package/dist/posts/conversationQueries.d.ts +7 -0
  165. package/dist/posts/conversationQueries.js +76 -2
  166. package/dist/posts/eventAgenda.d.ts +166 -0
  167. package/dist/posts/eventAgenda.js +126 -0
  168. package/dist/posts/eventOccurrenceJobs.d.ts +4 -0
  169. package/dist/posts/eventOccurrenceJobs.js +28 -0
  170. package/dist/posts/eventOccurrences.d.ts +10 -0
  171. package/dist/posts/eventOccurrences.js +61 -0
  172. package/dist/posts/finders.d.ts +47 -16
  173. package/dist/posts/finders.js +93 -62
  174. package/dist/posts/helpers/filters.js +14 -9
  175. package/dist/posts/helpers/index.d.ts +129 -30
  176. package/dist/posts/helpers/index.js +66 -33
  177. package/dist/posts/index.d.ts +7 -1
  178. package/dist/posts/index.js +7 -1
  179. package/dist/posts/mapping.d.ts +491 -13
  180. package/dist/posts/mapping.js +45 -10
  181. package/dist/posts/mutations.d.ts +441 -4
  182. package/dist/posts/mutations.js +177 -43
  183. package/dist/posts/pollEnd.d.ts +3 -0
  184. package/dist/posts/pollEnd.js +7 -0
  185. package/dist/posts/pollEndJobs.d.ts +8 -0
  186. package/dist/posts/pollEndJobs.js +49 -0
  187. package/dist/posts/replyClosure.d.ts +10 -0
  188. package/dist/posts/replyClosure.js +43 -0
  189. package/dist/posts/rsvpConfirmationEmail.js +14 -15
  190. package/dist/posts/threadPreview.d.ts +8 -0
  191. package/dist/posts/threadPreview.js +44 -0
  192. package/dist/posts/unseenCounts.d.ts +2 -0
  193. package/dist/posts/unseenCounts.js +28 -8
  194. package/dist/profileSettings/cache.js +22 -5
  195. package/dist/profileSettings/mapping.d.ts +2 -0
  196. package/dist/profiles/activityQueries.d.ts +5 -0
  197. package/dist/profiles/activityQueries.js +85 -0
  198. package/dist/profiles/activitySummary.d.ts +3 -0
  199. package/dist/profiles/activitySummary.js +87 -0
  200. package/dist/profiles/blocks.d.ts +12 -0
  201. package/dist/profiles/blocks.js +73 -0
  202. package/dist/profiles/cache.d.ts +4 -1
  203. package/dist/profiles/cache.js +28 -7
  204. package/dist/profiles/finders.d.ts +2 -1
  205. package/dist/profiles/finders.js +8 -3
  206. package/dist/profiles/helpers.d.ts +7 -5
  207. package/dist/profiles/index.d.ts +3 -1
  208. package/dist/profiles/index.js +3 -1
  209. package/dist/profiles/mapping.d.ts +10 -5
  210. package/dist/profiles/mapping.js +13 -1
  211. package/dist/profiles/mutations.d.ts +8 -4
  212. package/dist/profiles/mutations.js +42 -15
  213. package/dist/pushSubscriptions/helpers.d.ts +2 -2
  214. package/dist/pushSubscriptions/mutations.js +13 -1
  215. package/dist/redis/connection.d.ts +2 -0
  216. package/dist/redis/connection.js +25 -6
  217. package/dist/reports/helpers.d.ts +6 -6
  218. package/dist/roles/index.d.ts +1 -1
  219. package/dist/roles/index.js +1 -1
  220. package/dist/roles/mapping.d.ts +1 -0
  221. package/dist/roles/mutations.js +86 -3
  222. package/dist/search/mapping.d.ts +1 -1
  223. package/dist/search/mapping.js +6 -2
  224. package/dist/server/index.d.ts +19 -1
  225. package/dist/server/index.js +37 -18
  226. package/dist/server/stablePublicServerInfo.d.ts +17 -0
  227. package/dist/server/stablePublicServerInfo.js +37 -0
  228. package/dist/server/status.d.ts +25 -0
  229. package/dist/server/status.js +98 -0
  230. package/dist/stats/finders.d.ts +1 -16131
  231. package/dist/stats/finders.js +9 -5
  232. package/dist/stats/mapping.d.ts +21 -1
  233. package/dist/stats/mapping.js +0 -3
  234. package/package.json +6 -12
  235. package/dist/db/arango.d.ts +0 -2
  236. package/dist/db/arango.js +0 -110
  237. package/dist/db/migration/autoMigrate.d.ts +0 -2
  238. package/dist/db/migration/autoMigrate.js +0 -111
  239. package/dist/db/migration/cli.d.ts +0 -1
  240. package/dist/db/migration/cli.js +0 -56
  241. package/dist/db/migration/detect.d.ts +0 -6
  242. package/dist/db/migration/detect.js +0 -87
  243. package/dist/db/migration/exportArango.d.ts +0 -4
  244. package/dist/db/migration/exportArango.js +0 -80
  245. package/dist/db/migration/importPostgres.d.ts +0 -3
  246. package/dist/db/migration/importPostgres.js +0 -18
  247. package/dist/db/migration/transform.d.ts +0 -18
  248. package/dist/db/migration/transform.js +0 -209
  249. package/dist/db/migration/validate.d.ts +0 -18
  250. package/dist/db/migration/validate.js +0 -69
  251. package/dist/db/pg/sql/meta/0000_snapshot.json +0 -3380
  252. package/dist/db/pg/sql/meta/0004_snapshot.json +0 -4114
  253. package/dist/db/pg/sql/meta/0005_snapshot.json +0 -4179
  254. package/dist/mastodon/index.d.ts +0 -4
  255. package/dist/mastodon/index.js +0 -51
  256. package/dist/mastodon/types.d.ts +0 -7579
  257. package/dist/mastodon/types.js +0 -523
  258. package/dist/mastodon/typescript.d.ts +0 -1578
  259. package/dist/mastodon/typescript.js +0 -1
  260. package/dist/roles/defaults.d.ts +0 -2
  261. package/dist/roles/defaults.js +0 -94
@@ -3,9 +3,9 @@ export declare const profileAccessTokenConnector: (db: PgDb, from: {
3
3
  id: string;
4
4
  }, to: {
5
5
  id: string;
6
- }, data?: {
6
+ }, data?: object & {
7
7
  id?: string;
8
- }) => Promise<import("../db/pg/map").WithId<{
8
+ }) => Promise<import("../db/pg/map").WithId<object & {
9
9
  _from: string;
10
10
  _to: string;
11
11
  }>>;
@@ -67,10 +67,22 @@ export const createSignedServiceToken = async ({ scopes, name, description, expi
67
67
  expirationTime,
68
68
  });
69
69
  export const createSignedGuestPass = async (profile, expirationTime = '1d') => {
70
- var _a, _b;
70
+ var _a;
71
71
  if (!((_a = profile.guestData) === null || _a === void 0 ? void 0 : _a.resource)) {
72
72
  throw new Error('Guest pass requires a resource');
73
73
  }
74
+ const resource = profile.guestData.resource;
75
+ // Jam chat resolves message authors via profile GET; guests need a profiles
76
+ // read scope so ensureProfileCapabilities succeeds after ensureAccess.
77
+ const scopes = resource.type === 'jams'
78
+ ? [
79
+ { scopeLevel: 'read', resource },
80
+ {
81
+ scopeLevel: 'read',
82
+ resource: { type: 'profiles', id: '*' },
83
+ },
84
+ ]
85
+ : [{ scopeLevel: 'read', resource }];
74
86
  return createSignedAccessToken({
75
87
  profile,
76
88
  name: profile.handle,
@@ -78,12 +90,7 @@ export const createSignedGuestPass = async (profile, expirationTime = '1d') => {
78
90
  identities: {
79
91
  profile: profile.id,
80
92
  },
81
- scopes: [
82
- {
83
- scopeLevel: 'read',
84
- resource: (_b = profile.guestData) === null || _b === void 0 ? void 0 : _b.resource,
85
- },
86
- ],
93
+ scopes,
87
94
  },
88
95
  expirationTime,
89
96
  });
@@ -13,9 +13,9 @@ export declare const giveControl: (db: import("../db").PgDb, from: {
13
13
  id: string;
14
14
  }, to: {
15
15
  id: string;
16
- }, data?: {
16
+ }, data?: object & {
17
17
  id?: string;
18
- }) => Promise<import("../db/pg/map").WithId<{
18
+ }) => Promise<import("../db/pg/map").WithId<object & {
19
19
  _from: string;
20
20
  _to: string;
21
21
  }>>;
@@ -10,6 +10,8 @@ import { assignRole, unassignRole } from '../profiles/mutations.js';
10
10
  import { hash } from 'bcrypt';
11
11
  import { profilesMapping } from '../profiles/mapping.js';
12
12
  import { assertProfileCapacity } from '../profiles/capacity.js';
13
+ import { localActorScalars } from '../federation/identity.js';
14
+ import { uuidv7 } from 'uuidv7';
13
15
  import { findRoleByKey } from '../roles/index.js';
14
16
  import { log, normalizeEmailAddress, sendEmailValidationMail, sendWelcomeEmail, } from './helpers.js';
15
17
  import { findAccountByEmail } from './finders.js';
@@ -19,6 +21,26 @@ import { conflict } from '../errors/index.js';
19
21
  import { connector } from '../db/helpers.js';
20
22
  import { hub } from '../events/index.js';
21
23
  import { deletePushSubscription, listPushSubscriptionsByAccount, } from '../pushSubscriptions/index.js';
24
+ const applyCommunityRoleChanges = async (profile, changes) => {
25
+ for (const roleKey of changes.add) {
26
+ const role = await findRoleByKey(roleKey);
27
+ if (role) {
28
+ await assignRole(profile, role);
29
+ }
30
+ else {
31
+ log.error(`Role ${roleKey} missing`);
32
+ }
33
+ }
34
+ for (const roleKey of changes.remove) {
35
+ const role = await findRoleByKey(roleKey);
36
+ if (role) {
37
+ await unassignRole(profile, role);
38
+ }
39
+ else {
40
+ log.error(`Role ${roleKey} missing`);
41
+ }
42
+ }
43
+ };
22
44
  export const createAccount = async (accountCreationData) => {
23
45
  const { db } = await allpeepDb();
24
46
  const coreConfig = await config();
@@ -57,16 +79,13 @@ export const createAccount = async (accountCreationData) => {
57
79
  let profile;
58
80
  if (accountCreationData.profile) {
59
81
  await assertProfileCapacity();
60
- const { handle, displayName, avatar } = accountCreationData.profile;
61
- profile = await profilesMapping.create(db, {
62
- handle,
82
+ const { handle, displayName, avatar, bot } = accountCreationData.profile;
83
+ const profileId = uuidv7();
84
+ profile = await profilesMapping.create(db, Object.assign(Object.assign(Object.assign({ id: profileId, handle,
63
85
  displayName,
64
- avatar,
65
- activityPub: {
86
+ avatar }, (bot === true ? { bot: true } : {})), { activityPub: {
66
87
  domain: coreConfig.activityPub.defaultDomain,
67
- },
68
- type: 'local',
69
- });
88
+ }, type: 'local' }), localActorScalars(profileId, coreConfig.activityPub.defaultDomain)));
70
89
  if (firstAccount && profile) {
71
90
  const ownerRole = await findRoleByKey('owner');
72
91
  if (ownerRole) {
@@ -78,15 +97,11 @@ export const createAccount = async (accountCreationData) => {
78
97
  }
79
98
  else {
80
99
  await hub.emit('profileCreated', profile);
81
- const registrationRoleKeys = communityConf.roles.onRegistration.add;
82
- for (const roleKey of registrationRoleKeys) {
83
- const role = await findRoleByKey(roleKey);
84
- if (role) {
85
- await assignRole(profile, role);
86
- }
87
- else {
88
- log.error(`Role ${roleKey} missing`);
89
- }
100
+ await applyCommunityRoleChanges(profile, communityConf.roles.onRegistration);
101
+ // Authorized/SSO creates skip the validation email, so apply the
102
+ // same promotion humans get after confirming.
103
+ if (emailValidated) {
104
+ await applyCommunityRoleChanges(profile, communityConf.roles.onEmailValidation);
90
105
  }
91
106
  }
92
107
  if (inviteCode) {
@@ -175,24 +190,7 @@ export const validateEmail = async (token) => {
175
190
  await accountsMapping.update(db, account.id, { emailValidated: true });
176
191
  await accountsCache.del(account.id);
177
192
  await accountsCache.del(account.email);
178
- for (const roleKey of communityConf.roles.onEmailValidation.add) {
179
- const role = await findRoleByKey(roleKey);
180
- if (role) {
181
- await assignRole(account.profiles[0], role);
182
- }
183
- else {
184
- log.error(`Role ${roleKey} missing`);
185
- }
186
- }
187
- for (const roleKey of communityConf.roles.onEmailValidation.remove) {
188
- const role = await findRoleByKey(roleKey);
189
- if (role) {
190
- await unassignRole(account.profiles[0], role);
191
- }
192
- else {
193
- log.error(`Role ${roleKey} missing`);
194
- }
195
- }
193
+ await applyCommunityRoleChanges(account.profiles[0], communityConf.roles.onEmailValidation);
196
194
  return true;
197
195
  }
198
196
  }
@@ -4,11 +4,11 @@ const OPEN_DAY_TTL_SEC = 60 * 60;
4
4
  const CLOSED_RANGE_TTL_SEC = 60 * 60 * 6;
5
5
  export const analyticsCacheKey = (section, from, to) => `${KEY_PREFIX}${section}:${from}:${to}`;
6
6
  export const getAnalyticsCache = async (key) => {
7
- const redis = await getSharedConnection();
8
- const raw = await redis.get(key);
9
- if (!raw)
10
- return undefined;
11
7
  try {
8
+ const redis = await getSharedConnection();
9
+ const raw = await redis.get(key);
10
+ if (!raw)
11
+ return undefined;
12
12
  return JSON.parse(raw);
13
13
  }
14
14
  catch (_a) {
@@ -16,9 +16,14 @@ export const getAnalyticsCache = async (key) => {
16
16
  }
17
17
  };
18
18
  export const setAnalyticsCache = async (key, value, opts) => {
19
- const redis = await getSharedConnection();
20
- const ttl = (opts === null || opts === void 0 ? void 0 : opts.includesToday) ? OPEN_DAY_TTL_SEC : CLOSED_RANGE_TTL_SEC;
21
- await redis.set(key, JSON.stringify(value), { EX: ttl });
19
+ try {
20
+ const redis = await getSharedConnection();
21
+ const ttl = (opts === null || opts === void 0 ? void 0 : opts.includesToday) ? OPEN_DAY_TTL_SEC : CLOSED_RANGE_TTL_SEC;
22
+ await redis.set(key, JSON.stringify(value), { EX: ttl });
23
+ }
24
+ catch (_a) {
25
+ // Overview still returns; Redis must not 500 the request.
26
+ }
22
27
  };
23
28
  export const invalidateAnalyticsCache = async () => {
24
29
  const redis = await getSharedConnection();
@@ -24,14 +24,16 @@ export const compileAnalyticsDay = async (day) => {
24
24
  const now = new Date().toISOString();
25
25
  const newMembers = await countScalar(db, sql `select count(*)::int as c from profiles
26
26
  where deleted_at is null
27
+ and type = 'local'
27
28
  and created_at >= ${start} and created_at < ${end}`);
28
29
  const posts = await countScalar(db, sql `select count(*)::int as c from posts
29
30
  where deleted_at is null and visibility <> 'direct'
30
31
  and created_at >= ${start} and created_at < ${end}`);
31
32
  const replies = await countScalar(db, sql `select count(*)::int as c from reply_to
32
33
  where created_at >= ${start} and created_at < ${end}`);
33
- const likes = await countScalar(db, sql `select count(*)::int as c from reactions
34
- where created_at >= ${start} and created_at < ${end}`);
34
+ const likes = await countScalar(db, sql `select count(*)::int as c from entries
35
+ where body->>'type' = 'reaction'
36
+ and created_at >= ${start} and created_at < ${end}`);
35
37
  const reposts = await countScalar(db, sql `select count(*)::int as c from repost
36
38
  where created_at >= ${start} and created_at < ${end}`);
37
39
  const bookmarks = await countScalar(db, sql `select count(*)::int as c from bookmarks
@@ -55,8 +57,9 @@ export const compileAnalyticsDay = async (day) => {
55
57
  where deleted_at is null
56
58
  and created_at >= ${start} and created_at < ${end}
57
59
  union
58
- select from_id from reactions
59
- where created_at >= ${start} and created_at < ${end}
60
+ select from_id from entries
61
+ where body->>'type' in ('reaction', 'unreaction')
62
+ and created_at >= ${start} and created_at < ${end}
60
63
  union
61
64
  select from_id from repost
62
65
  where created_at >= ${start} and created_at < ${end}
@@ -129,10 +132,11 @@ export const compileAnalyticsDay = async (day) => {
129
132
  update analytics_daily_by_group g
130
133
  set
131
134
  likes = coalesce((
132
- select count(*)::int from reactions r
133
- join post_groups pg on pg.from_id = r.to_id
135
+ select count(*)::int from entries e
136
+ join post_groups pg on pg.from_id = e.to_id
134
137
  where pg.to_id = g.group_id
135
- and r.created_at >= ${start} and r.created_at < ${end}
138
+ and e.body->>'type' = 'reaction'
139
+ and e.created_at >= ${start} and e.created_at < ${end}
136
140
  ), 0),
137
141
  comments = coalesce((
138
142
  select count(*)::int from reply_to rt
@@ -164,8 +168,9 @@ export const compileAnalyticsDay = async (day) => {
164
168
  select created_at from posts
165
169
  where deleted_at is null and created_at >= ${start} and created_at < ${end}
166
170
  union all
167
- select created_at from reactions
168
- where created_at >= ${start} and created_at < ${end}
171
+ select created_at from entries
172
+ where body->>'type' in ('reaction', 'unreaction')
173
+ and created_at >= ${start} and created_at < ${end}
169
174
  union all
170
175
  select created_at from reply_to
171
176
  where created_at >= ${start} and created_at < ${end}
@@ -243,7 +248,8 @@ export const compileRetentionCohorts = async () => {
243
248
  from (
244
249
  select creator_id as profile_id, created_at from posts where deleted_at is null
245
250
  union all
246
- select from_id, created_at from reactions
251
+ select from_id, created_at from entries
252
+ where body->>'type' in ('reaction', 'unreaction')
247
253
  union all
248
254
  select from_id, created_at from reply_to
249
255
  union all
@@ -1,5 +1,6 @@
1
1
  import type { AnalyticsEngagement, AnalyticsGrowth, AnalyticsOverview } from '@openpeepshq/common/types';
2
2
  export type AnalyticsPdfData = {
3
+ communityName: string;
3
4
  overview: AnalyticsOverview;
4
5
  growth: AnalyticsGrowth;
5
6
  engagement: AnalyticsEngagement;
@@ -73,12 +73,12 @@ const cumulativeGrowth = (points, series) => {
73
73
  return { label: p.label, values: Object.assign({}, running) };
74
74
  });
75
75
  };
76
- const createDoc = () => new PDFDocument({
76
+ const createDoc = (communityName) => new PDFDocument({
77
77
  size: 'LETTER',
78
78
  margin: MARGIN,
79
79
  compress: false,
80
80
  info: {
81
- Title: 'Community analytics report',
81
+ Title: `${communityName} analytics report`,
82
82
  Author: 'OpenPeeps',
83
83
  },
84
84
  });
@@ -788,7 +788,7 @@ const drawGroupsPage = (layout, overview) => {
788
788
  };
789
789
  /** Multi-page visual PDF mirroring the analytics tabs. */
790
790
  export const buildAnalyticsPdf = async (data) => {
791
- const doc = createDoc();
791
+ const doc = createDoc(data.communityName);
792
792
  const pending = bufferFromDoc(doc);
793
793
  const period = `${data.overview.range.from} to ${data.overview.range.to}`;
794
794
  const layout = {
@@ -800,8 +800,9 @@ export const buildAnalyticsPdf = async (data) => {
800
800
  };
801
801
  // Cover strip on first page before section chrome
802
802
  doc.fontSize(10).fillColor(COLORS.muted).font('Helvetica');
803
- writeText(doc, 'OpenPeeps - Community analytics', MARGIN, layout.y, {
803
+ writeText(doc, `${data.communityName} - Community analytics`, MARGIN, layout.y, {
804
804
  width: CONTENT_WIDTH,
805
+ ellipsis: true,
805
806
  });
806
807
  layout.y += 16;
807
808
  doc.fontSize(22).fillColor(COLORS.ink).font('Helvetica-Bold');
@@ -0,0 +1,18 @@
1
+ /** Group body fields used to decide public vs private for analytics. */
2
+ export type AnalyticsGroupCapabilities = {
3
+ capabilities?: {
4
+ none?: {
5
+ add?: string[];
6
+ };
7
+ };
8
+ };
9
+ /**
10
+ * Public groups grant `core-groups-read` to role `none`. Missing capabilities
11
+ * means private — same rule as the analytics group tables.
12
+ */
13
+ export declare const isPublicAnalyticsGroup: (body: AnalyticsGroupCapabilities) => boolean;
14
+ /**
15
+ * Top-posts cards show author + snippet. Exclude DMs and any post linked to a
16
+ * private group. A post with no group links is eligible when not `direct`.
17
+ */
18
+ export declare const isAnalyticsTopPostEligible: (visibility: string, linkedGroupBodies: AnalyticsGroupCapabilities[]) => boolean;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Public groups grant `core-groups-read` to role `none`. Missing capabilities
3
+ * means private — same rule as the analytics group tables.
4
+ */
5
+ export const isPublicAnalyticsGroup = (body) => { var _a, _b, _c; return ((_c = (_b = (_a = body.capabilities) === null || _a === void 0 ? void 0 : _a.none) === null || _b === void 0 ? void 0 : _b.add) !== null && _c !== void 0 ? _c : []).includes('core-groups-read'); };
6
+ /**
7
+ * Top-posts cards show author + snippet. Exclude DMs and any post linked to a
8
+ * private group. A post with no group links is eligible when not `direct`.
9
+ */
10
+ export const isAnalyticsTopPostEligible = (visibility, linkedGroupBodies) => visibility !== 'direct' && linkedGroupBodies.every(isPublicAnalyticsGroup);
@@ -6,6 +6,7 @@ import { groups, posts, profiles } from '../db/pg/schema/documents.js';
6
6
  import { analyticsCacheKey, getAnalyticsCache, setAnalyticsCache, } from './cache.js';
7
7
  import { aggregateSeriesIntoBuckets, eachUtcDay, resolveAnalyticsRange, selectChartBuckets, } from './dateRange.js';
8
8
  import { metricCard, sumSeries, averageSeries } from './metrics.js';
9
+ import { isPublicAnalyticsGroup } from './privacy.js';
9
10
  const POST_TYPE_KEYS = ['jam', 'article', 'note', 'poll', 'event'];
10
11
  const todayString = () => formatISO(startOfDay(new Date()), { representation: 'date' });
11
12
  const includesToday = (to) => to >= todayString();
@@ -23,8 +24,9 @@ const countDistinctActives = async (from, to) => {
23
24
  where deleted_at is null
24
25
  and created_at >= ${start} and created_at < ${end}
25
26
  union
26
- select from_id from reactions
27
- where created_at >= ${start} and created_at < ${end}
27
+ select from_id from entries
28
+ where body->>'type' in ('reaction', 'unreaction')
29
+ and created_at >= ${start} and created_at < ${end}
28
30
  union
29
31
  select from_id from repost
30
32
  where created_at >= ${start} and created_at < ${end}
@@ -79,7 +81,40 @@ const totalMembersAt = async (day) => {
79
81
  const end = `${day}T23:59:59.999Z`;
80
82
  const result = await db.execute(sql `
81
83
  select count(*)::int as c from profiles
82
- where deleted_at is null and created_at <= ${end}
84
+ where deleted_at is null and type = 'local'
85
+ and created_at <= ${end}
86
+ `);
87
+ const rows = result.rows;
88
+ return Number((_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.c) !== null && _b !== void 0 ? _b : 0);
89
+ };
90
+ const verifiedMembersAt = async (day) => {
91
+ var _a, _b;
92
+ const db = await database();
93
+ const end = `${day}T23:59:59.999Z`;
94
+ const result = await db.execute(sql `
95
+ select count(*)::int as c from profiles p
96
+ join controls c on c.to_id = p.id::text
97
+ join accounts a on a.id::text = c.from_id
98
+ where p.deleted_at is null and p.type = 'local'
99
+ and a.deleted_at is null
100
+ and a.email_validated = true
101
+ and p.created_at <= ${end}
102
+ `);
103
+ const rows = result.rows;
104
+ return Number((_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.c) !== null && _b !== void 0 ? _b : 0);
105
+ };
106
+ const unverifiedMembersAt = async (day) => {
107
+ var _a, _b;
108
+ const db = await database();
109
+ const end = `${day}T23:59:59.999Z`;
110
+ const result = await db.execute(sql `
111
+ select count(*)::int as c from profiles p
112
+ join controls c on c.to_id = p.id::text
113
+ join accounts a on a.id::text = c.from_id
114
+ where p.deleted_at is null and p.type = 'local'
115
+ and a.deleted_at is null
116
+ and a.email_validated = false
117
+ and p.created_at <= ${end}
83
118
  `);
84
119
  const rows = result.rows;
85
120
  return Number((_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.c) !== null && _b !== void 0 ? _b : 0);
@@ -108,12 +143,7 @@ const latestCompiledAt = async (from, to) => {
108
143
  .limit(1);
109
144
  return (_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.compiledAt) !== null && _b !== void 0 ? _b : null;
110
145
  };
111
- const groupVisibility = (body) => {
112
- var _a, _b, _c;
113
- return ((_c = (_b = (_a = body.capabilities) === null || _a === void 0 ? void 0 : _a.none) === null || _b === void 0 ? void 0 : _b.add) !== null && _c !== void 0 ? _c : []).includes('core-groups-read')
114
- ? 'public'
115
- : 'private';
116
- };
146
+ const groupVisibility = (body) => isPublicAnalyticsGroup(body) ? 'public' : 'private';
117
147
  const groupDisplayName = (body, handle) => { var _a, _b, _c; return (_c = (_b = (_a = body.name) !== null && _a !== void 0 ? _a : body.displayName) !== null && _b !== void 0 ? _b : handle) !== null && _c !== void 0 ? _c : undefined; };
118
148
  const enrichGroupRows = async (rows, from, to) => {
119
149
  if (rows.length === 0)
@@ -352,8 +382,9 @@ const topMembers = async (from, to, limit = 10) => {
352
382
  and visibility <> 'direct'
353
383
  and created_at >= ${start} and created_at <= ${end}
354
384
  union all
355
- select from_id from reactions
356
- where created_at >= ${start} and created_at <= ${end}
385
+ select from_id from entries
386
+ where body->>'type' in ('reaction', 'unreaction')
387
+ and created_at >= ${start} and created_at <= ${end}
357
388
  union all
358
389
  select from_id from reply_to
359
390
  where created_at >= ${start} and created_at <= ${end}
@@ -410,6 +441,11 @@ const topMembers = async (from, to, limit = 10) => {
410
441
  });
411
442
  });
412
443
  };
444
+ /**
445
+ * Top posts must not expose DM content or private-group posts (snippets +
446
+ * authors). SQL mirrors {@link isAnalyticsTopPostEligible} /
447
+ * {@link isPublicAnalyticsGroup}.
448
+ */
413
449
  const topPostsByViews = async (from, to, limit = 10) => {
414
450
  const db = await database();
415
451
  const rows = await db
@@ -423,9 +459,18 @@ const topPostsByViews = async (from, to, limit = 10) => {
423
459
  profileBody: profiles.body,
424
460
  })
425
461
  .from(analyticsPostViewsDaily)
426
- .leftJoin(posts, sql `${posts.id}::text = ${analyticsPostViewsDaily.postId}`)
462
+ .innerJoin(posts, sql `${posts.id}::text = ${analyticsPostViewsDaily.postId}`)
427
463
  .leftJoin(profiles, sql `${profiles.id}::text = ${posts.creatorId}`)
428
- .where(and(gte(analyticsPostViewsDaily.day, from), lte(analyticsPostViewsDaily.day, to)))
464
+ .where(and(gte(analyticsPostViewsDaily.day, from), lte(analyticsPostViewsDaily.day, to), sql `${posts.visibility} <> 'direct'`, sql `not exists (
465
+ select 1
466
+ from post_groups pg
467
+ inner join groups g on g.id::text = pg.to_id
468
+ where pg.from_id = ${posts.id}::text
469
+ and not coalesce(
470
+ g.body->'capabilities'->'none'->'add' ? 'core-groups-read',
471
+ false
472
+ )
473
+ )`))
429
474
  .groupBy(analyticsPostViewsDaily.postId, posts.body, posts.type, profiles.handle, profiles.body)
430
475
  .orderBy(desc(sum(analyticsPostViewsDaily.uniqueViewers)))
431
476
  .limit(limit);
@@ -441,7 +486,9 @@ const topPostsByViews = async (from, to, limit = 10) => {
441
486
  const profileBody = ((_h = r.profileBody) !== null && _h !== void 0 ? _h : {});
442
487
  return {
443
488
  postId: r.postId,
444
- snippet: content.slice(0, 120) || undefined,
489
+ snippet: typeof content === 'string'
490
+ ? content.slice(0, 120) || undefined
491
+ : undefined,
445
492
  authorHandle: (_j = r.handle) !== null && _j !== void 0 ? _j : undefined,
446
493
  authorDisplayName: (_l = (_k = profileBody.displayName) !== null && _k !== void 0 ? _k : profileBody.name) !== null && _l !== void 0 ? _l : undefined,
447
494
  postType,
@@ -461,9 +508,11 @@ const withCache = async (section, from, to, build) => {
461
508
  };
462
509
  export const getAnalyticsOverview = async (query = {}) => {
463
510
  const range = await resolveQueryRange(query);
464
- return withCache('overview-v5', range.from, range.to, async () => {
511
+ // Unique people in the window — summing daily rollups would count a
512
+ // member once per day they were active.
513
+ return withCache('overview-v7', range.from, range.to, async () => {
465
514
  var _a, _b;
466
- const [activeMembersSeries, postsSeries, likesSeries, commentsSeries, postsByTypeDaily, topGroupRows, groupGrowth, topPostRows, topMemberRows, compiledAt, totalMembers, totalGroups, allTimePosts, prevActive, prevPosts, prevTotalMembers, prevTotalGroups, prevAllTimePosts,] = await Promise.all([
515
+ const [activeMembersSeries, postsSeries, likesSeries, commentsSeries, postsByTypeDaily, topGroupRows, groupGrowth, topPostRows, topMemberRows, compiledAt, totalMembers, totalGroups, allTimePosts, activeMembers, prevActive, prevPosts, prevTotalMembers, prevTotalGroups, prevAllTimePosts, verifiedMembers, unverifiedMembers, prevVerifiedMembers, prevUnverifiedMembers,] = await Promise.all([
467
516
  loadTotalsSeries(range.from, range.to, 'activeMembers'),
468
517
  loadTotalsSeries(range.from, range.to, 'posts'),
469
518
  loadTotalsSeries(range.from, range.to, 'likes'),
@@ -477,13 +526,17 @@ export const getAnalyticsOverview = async (query = {}) => {
477
526
  totalMembersAt(range.to),
478
527
  totalGroupsAt(range.to),
479
528
  totalPostsAt(range.to),
480
- sumColumn(range.previousFrom, range.previousTo, 'activeMembers'),
529
+ countDistinctActives(range.from, range.to),
530
+ countDistinctActives(range.previousFrom, range.previousTo),
481
531
  sumColumn(range.previousFrom, range.previousTo, 'posts'),
482
532
  totalMembersAt(range.previousTo),
483
533
  totalGroupsAt(range.previousTo),
484
534
  totalPostsAt(range.previousTo),
535
+ verifiedMembersAt(range.to),
536
+ unverifiedMembersAt(range.to),
537
+ verifiedMembersAt(range.previousTo),
538
+ unverifiedMembersAt(range.previousTo),
485
539
  ]);
486
- const activeMembers = sumSeries(activeMembersSeries);
487
540
  const totalPosts = sumSeries(postsSeries);
488
541
  const { buckets } = selectChartBuckets(range.from, range.to);
489
542
  const typeTotals = Object.fromEntries(POST_TYPE_KEYS.map((k) => [k, 0]));
@@ -540,6 +593,8 @@ export const getAnalyticsOverview = async (query = {}) => {
540
593
  totalPosts: metricCard('totalPosts', totalPosts, prevPosts, postsSeries),
541
594
  allTimePosts: metricCard('allTimePosts', allTimePosts, prevAllTimePosts),
542
595
  totalMembers: metricCard('totalMembers', totalMembers, prevTotalMembers),
596
+ verifiedMembers: metricCard('verifiedMembers', verifiedMembers, prevVerifiedMembers),
597
+ unverifiedMembers: metricCard('unverifiedMembers', unverifiedMembers, prevUnverifiedMembers),
543
598
  activeMembers: metricCard('activeMembers', activeMembers, prevActive, activeMembersSeries),
544
599
  totalGroups: metricCard('totalGroups', totalGroups, prevTotalGroups),
545
600
  },
@@ -558,7 +613,7 @@ export const getAnalyticsOverview = async (query = {}) => {
558
613
  };
559
614
  export const getAnalyticsGrowth = async (query = {}) => {
560
615
  const range = await resolveQueryRange(query);
561
- return withCache('growth-v6', range.from, range.to, async () => {
616
+ return withCache('growth-v7', range.from, range.to, async () => {
562
617
  const db = await database();
563
618
  const mauFrom = rollingMauFrom(range.to);
564
619
  const prevMauFrom = rollingMauFrom(range.previousTo);
@@ -576,6 +631,7 @@ export const getAnalyticsGrowth = async (query = {}) => {
576
631
  from profiles p
577
632
  left join invite_link_redeemers r on r.to_id = p.id::text
578
633
  where p.deleted_at is null
634
+ and p.type <> 'guest'
579
635
  and p.created_at >= ${`${range.from}T00:00:00.000Z`}
580
636
  and p.created_at <= ${`${range.to}T23:59:59.999Z`}
581
637
  order by p.created_at desc
@@ -43,6 +43,26 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
43
43
  value: number;
44
44
  }[] | undefined;
45
45
  };
46
+ verifiedMembers: {
47
+ key: string;
48
+ value: number;
49
+ previousValue: number;
50
+ deltaPct: number | null;
51
+ series?: {
52
+ day: string;
53
+ value: number;
54
+ }[] | undefined;
55
+ };
56
+ unverifiedMembers: {
57
+ key: string;
58
+ value: number;
59
+ previousValue: number;
60
+ deltaPct: number | null;
61
+ series?: {
62
+ day: string;
63
+ value: number;
64
+ }[] | undefined;
65
+ };
46
66
  activeMembers: {
47
67
  key: string;
48
68
  value: number;
@@ -74,7 +94,7 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
74
94
  event: number;
75
95
  }[];
76
96
  postTypes: {
77
- type: "jam" | "poll" | "note" | "event" | "article";
97
+ type: "poll" | "note" | "event" | "article" | "jam";
78
98
  count: number;
79
99
  }[];
80
100
  activeUsersSeries: {
@@ -1,6 +1,7 @@
1
1
  import { endOfMonth, formatISO, startOfMonth, subMonths } from 'date-fns';
2
2
  import { eq } from 'drizzle-orm';
3
3
  import { uuidv7 } from 'uuidv7';
4
+ import { communityConfig } from '../config/index.js';
4
5
  import { sendEmailQueue } from '../email/index.js';
5
6
  import { database } from '../db/index.js';
6
7
  import { analyticsReportDeliveries } from '../db/pg/schema/analytics.js';
@@ -25,10 +26,11 @@ const narrativeSentence = (label, value, deltaPct) => {
25
26
  };
26
27
  /** Board-ready report: plain-text email body + visual multi-page PDF. */
27
28
  export const buildAnalyticsBoardReport = async (query = {}) => {
28
- const [overview, growth, engagement] = await Promise.all([
29
+ const [overview, growth, engagement, community] = await Promise.all([
29
30
  getAnalyticsOverview(query),
30
31
  getAnalyticsGrowth(query),
31
32
  getAnalyticsEngagement(query),
33
+ communityConfig(),
32
34
  ]);
33
35
  const from = overview.range.from;
34
36
  const to = overview.range.to;
@@ -51,7 +53,12 @@ export const buildAnalyticsBoardReport = async (query = {}) => {
51
53
  '',
52
54
  ...summary,
53
55
  ].join('\n');
54
- const pdf = await buildAnalyticsPdf({ overview, growth, engagement });
56
+ const pdf = await buildAnalyticsPdf({
57
+ communityName: community.info.name,
58
+ overview,
59
+ growth,
60
+ engagement,
61
+ });
55
62
  return { text, pdf, overview, growth, engagement };
56
63
  };
57
64
  /** @deprecated Prefer buildAnalyticsBoardReport().pdf — kept for tests. */