@openpeepshq/core 0.1.34 → 0.2.0

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 (192) hide show
  1. package/dist/accessTokens/finders.js +5 -6
  2. package/dist/accessTokens/mutations.js +1 -1
  3. package/dist/accessTokens/tokens.js +8 -11
  4. package/dist/accounts/helpers.js +6 -2
  5. package/dist/accounts/mutations.js +13 -8
  6. package/dist/analytics/cache.js +3 -3
  7. package/dist/analytics/clicks.js +14 -22
  8. package/dist/analytics/compile.js +1 -2
  9. package/dist/analytics/dateRange.js +3 -5
  10. package/dist/analytics/jobs.js +3 -4
  11. package/dist/analytics/pdfReport.js +45 -61
  12. package/dist/analytics/privacy.js +1 -1
  13. package/dist/analytics/read.js +116 -135
  14. package/dist/analytics/report.d.ts +2 -1
  15. package/dist/analytics/report.js +2 -3
  16. package/dist/analytics/settings.js +3 -4
  17. package/dist/backups/index.js +13 -16
  18. package/dist/backups/metadata.js +1 -1
  19. package/dist/config/db.js +2 -4
  20. package/dist/config/defaults/community.js +1 -0
  21. package/dist/config/defaults/core.js +13 -8
  22. package/dist/config/defaults/logs.d.ts +4 -0
  23. package/dist/config/defaults/logs.js +5 -0
  24. package/dist/config/index.d.ts +9 -0
  25. package/dist/config/index.js +9 -11
  26. package/dist/db/explorer/query.js +9 -8
  27. package/dist/db/explorer/sql.js +8 -8
  28. package/dist/db/helpers.js +15 -5
  29. package/dist/db/migration/importCollections.js +15 -18
  30. package/dist/db/migration/shared.js +15 -35
  31. package/dist/db/pg/client.js +4 -7
  32. package/dist/db/pg/filters/index.js +1 -1
  33. package/dist/db/pg/filters/posts.d.ts +2 -0
  34. package/dist/db/pg/filters/posts.js +3 -1
  35. package/dist/db/pg/helpers.js +2 -14
  36. package/dist/db/pg/map/filters.js +8 -8
  37. package/dist/db/pg/map/helpers.js +5 -1
  38. package/dist/db/pg/map/index.js +46 -51
  39. package/dist/db/pg/map/mutations.js +56 -21
  40. package/dist/db/pg/map/registry.js +87 -50
  41. package/dist/db/pg/map/relations.js +67 -63
  42. package/dist/db/pg/map/search.js +15 -37
  43. package/dist/db/pg/mappers.js +13 -7
  44. package/dist/db/pg/migrate.js +2 -3
  45. package/dist/db/pg/queries/activity.js +2 -2
  46. package/dist/db/pg/queries/derived.js +8 -12
  47. package/dist/db/pg/schema/documents.js +119 -18
  48. package/dist/db/pg/schema/edges.js +7 -1
  49. package/dist/db/pg/schema/index.js +5 -1
  50. package/dist/db/pg/sql/0016_posts_search_vector_title_tags_path.sql +54 -0
  51. package/dist/db/pg/sql/meta/_journal.json +8 -1
  52. package/dist/db/replaceOrigin.js +1 -1
  53. package/dist/email/queueStats.js +8 -11
  54. package/dist/email/render.js +7 -4
  55. package/dist/email/send.js +19 -17
  56. package/dist/email/smtpTest.js +10 -6
  57. package/dist/errors/index.js +1 -1
  58. package/dist/events/once.js +2 -4
  59. package/dist/federation/activities.js +1 -2
  60. package/dist/groups/finders.d.ts +2 -2
  61. package/dist/groups/helpers.d.ts +6 -6
  62. package/dist/groups/helpers.js +1 -2
  63. package/dist/groups/mapping.d.ts +4 -4
  64. package/dist/groups/mutations.js +1 -1
  65. package/dist/hashtags/finders.js +2 -2
  66. package/dist/inviteLinks/mutations.js +2 -3
  67. package/dist/jams/export.js +5 -7
  68. package/dist/jams/finders.js +4 -1
  69. package/dist/jams/health.d.ts +6 -4
  70. package/dist/jams/health.js +15 -11
  71. package/dist/jams/helpers.d.ts +2 -2
  72. package/dist/jams/helpers.js +6 -2
  73. package/dist/jams/index.js +2 -2
  74. package/dist/jams/jobs.js +1 -2
  75. package/dist/jams/livekit.d.ts +2 -2
  76. package/dist/jams/livekit.js +8 -8
  77. package/dist/jams/mapping.d.ts +10 -10
  78. package/dist/jams/mutations.d.ts +2 -2
  79. package/dist/jams/recording.js +1 -1
  80. package/dist/jams/token.js +13 -17
  81. package/dist/jobs/index.js +7 -6
  82. package/dist/jobs/jobDetail.js +5 -6
  83. package/dist/jobs/jobLog.js +2 -3
  84. package/dist/lib/streams.js +4 -39
  85. package/dist/lib/zodDeepPartial.d.ts +1 -1
  86. package/dist/lib/zodDeepPartial.js +1 -1
  87. package/dist/log/index.d.ts +1 -0
  88. package/dist/log/index.js +14 -29
  89. package/dist/log/retention.d.ts +9 -0
  90. package/dist/log/retention.js +83 -0
  91. package/dist/log/retentionJobs.d.ts +17 -0
  92. package/dist/log/retentionJobs.js +50 -0
  93. package/dist/media/index.js +127 -4
  94. package/dist/media/jobs.js +1 -2
  95. package/dist/media/openpeeps/index.js +11 -46
  96. package/dist/media/processing.js +7 -4
  97. package/dist/media/streaming.js +5 -5
  98. package/dist/media/streamingCleanupJobs.js +1 -2
  99. package/dist/media/streamingJobs.js +3 -4
  100. package/dist/media/streamingPrewarm.js +7 -11
  101. package/dist/mediaAttachments/index.js +6 -2
  102. package/dist/mediaAttachments/mapping.d.ts +1 -1
  103. package/dist/notifications/defaultNotifications/announcement/index.js +15 -18
  104. package/dist/notifications/defaultNotifications/directMessage/index.js +9 -8
  105. package/dist/notifications/defaultNotifications/follow/index.js +14 -17
  106. package/dist/notifications/defaultNotifications/groupAdded/index.js +14 -17
  107. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +15 -18
  108. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +15 -18
  109. package/dist/notifications/defaultNotifications/jamModerator/index.js +27 -20
  110. package/dist/notifications/defaultNotifications/jamModerator/recipients.d.ts +2 -0
  111. package/dist/notifications/defaultNotifications/jamModerator/recipients.js +5 -0
  112. package/dist/notifications/defaultNotifications/jamSpeaker/index.js +14 -18
  113. package/dist/notifications/defaultNotifications/jamStarted/index.js +18 -22
  114. package/dist/notifications/defaultNotifications/mention/index.js +20 -24
  115. package/dist/notifications/defaultNotifications/newGroupPost/index.js +9 -10
  116. package/dist/notifications/defaultNotifications/newGroupPost/recipients.d.ts +5 -0
  117. package/dist/notifications/defaultNotifications/newGroupPost/recipients.js +23 -0
  118. package/dist/notifications/defaultNotifications/newProfile/index.js +14 -17
  119. package/dist/notifications/defaultNotifications/pollEnded/index.js +21 -21
  120. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +2 -3
  121. package/dist/notifications/defaultNotifications/pollVote/index.js +14 -17
  122. package/dist/notifications/defaultNotifications/reaction/index.js +18 -21
  123. package/dist/notifications/defaultNotifications/reply/index.js +21 -22
  124. package/dist/notifications/defaultNotifications/repost/index.js +16 -20
  125. package/dist/notifications/defaultNotifications/rsvp/index.js +24 -18
  126. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +20 -13
  127. package/dist/notifications/eventIcsAttachment.d.ts +6 -0
  128. package/dist/notifications/eventIcsAttachment.js +32 -0
  129. package/dist/notifications/fcmCredential.js +1 -1
  130. package/dist/notifications/finders.js +1 -1
  131. package/dist/notifications/helpers.d.ts +11 -1
  132. package/dist/notifications/helpers.js +38 -9
  133. package/dist/notifications/jobs.js +16 -7
  134. package/dist/notifications/mutations.js +13 -2
  135. package/dist/notifications/push.js +11 -16
  136. package/dist/performance/index.js +3 -3
  137. package/dist/plugins/helpers.js +3 -6
  138. package/dist/plugins/index.js +2 -3
  139. package/dist/plugins/install.js +31 -17
  140. package/dist/plugins/pluginAuth.js +3 -4
  141. package/dist/plugins/state.js +2 -3
  142. package/dist/posts/activity.d.ts +1 -1
  143. package/dist/posts/activity.js +2 -3
  144. package/dist/posts/contextClosure.js +1 -2
  145. package/dist/posts/conversationQueries.js +2 -4
  146. package/dist/posts/eventAgenda.js +12 -7
  147. package/dist/posts/eventOccurrences.js +2 -2
  148. package/dist/posts/finders.d.ts +46 -6
  149. package/dist/posts/finders.js +21 -9
  150. package/dist/posts/helpers/filters.js +2 -3
  151. package/dist/posts/helpers/index.d.ts +170 -18
  152. package/dist/posts/helpers/index.js +43 -27
  153. package/dist/posts/mapping.d.ts +616 -84
  154. package/dist/posts/mapping.js +60 -18
  155. package/dist/posts/mutations.d.ts +85 -9
  156. package/dist/posts/mutations.js +47 -34
  157. package/dist/posts/pollEnd.js +3 -6
  158. package/dist/posts/rsvpConfirmationEmail.js +18 -8
  159. package/dist/posts/threadPreview.js +1 -1
  160. package/dist/processingStats/queries.js +6 -7
  161. package/dist/profileSettings/cache.js +1 -2
  162. package/dist/profileSettings/mapping.d.ts +1 -0
  163. package/dist/profiles/activitySummary.js +23 -28
  164. package/dist/profiles/cache.js +15 -8
  165. package/dist/profiles/export.js +30 -39
  166. package/dist/profiles/finders.js +7 -5
  167. package/dist/profiles/mapping.d.ts +10 -10
  168. package/dist/profiles/mutations.js +3 -5
  169. package/dist/redis/connection.js +1 -1
  170. package/dist/reports/helpers.js +7 -3
  171. package/dist/reports/mapping.d.ts +1 -1
  172. package/dist/roles/mutations.js +20 -21
  173. package/dist/search/finders.js +15 -3
  174. package/dist/search/helpers.js +1 -1
  175. package/dist/sentry/index.js +9 -11
  176. package/dist/seo/index.d.ts +50 -0
  177. package/dist/seo/index.js +145 -0
  178. package/dist/seo/route.d.ts +18 -0
  179. package/dist/seo/route.js +19 -0
  180. package/dist/server/index.d.ts +1 -0
  181. package/dist/server/index.js +16 -11
  182. package/dist/server/status.js +6 -7
  183. package/dist/session/index.js +2 -2
  184. package/dist/stats/finders.js +13 -4
  185. package/dist/stats/helpers.js +4 -1
  186. package/dist/stats/mapping.d.ts +43 -5
  187. package/dist/stats/mapping.js +9 -2
  188. package/dist/stripe/cache.js +5 -6
  189. package/dist/stripe/connection.js +3 -4
  190. package/dist/stripe/helpers.js +15 -20
  191. package/package.json +5 -6
  192. package/LICENSE +0 -674
@@ -14,19 +14,18 @@ export const isServiceAccessToken = (token) => {
14
14
  const parsed = authorizationSchema.safeParse(payload);
15
15
  return parsed.success && !!parsed.data.identities.service;
16
16
  }
17
- catch (_a) {
17
+ catch {
18
18
  return false;
19
19
  }
20
20
  };
21
21
  const withCachedOwnerAndScopes = async (token) => {
22
- var _a;
23
- const ownerId = (_a = token.ownedBy) === null || _a === void 0 ? void 0 : _a.id;
22
+ const ownerId = token.ownedBy?.id;
24
23
  const scopes = parseScopesFromJwt(token.signedToken);
25
24
  if (!ownerId) {
26
- return Object.assign(Object.assign({}, token), { ownedBy: undefined, scopes });
25
+ return { ...token, ownedBy: undefined, scopes };
27
26
  }
28
27
  const owner = await getProfile(ownerId);
29
- return Object.assign(Object.assign({}, token), { ownedBy: owner, scopes });
28
+ return { ...token, ownedBy: owner, scopes };
30
29
  };
31
30
  export const findAccessToken = (id) => allpeepDb().then(({ db }) => accessTokensMapping
32
31
  .find(db, id)
@@ -40,4 +39,4 @@ export const listAccessTokensForProfile = (profile) => allpeepDb().then(async ({
40
39
  .all(db)
41
40
  .then((tokens) => Promise.all(tokens.map(withCachedOwnerAndScopes))));
42
41
  export const listServiceAccessTokens = () => listAccessTokens().then((tokens) => tokens.filter(isServiceAccessToken));
43
- export const isRevoked = async (id) => { var _a; return (await isMaybeRevoked(id)) && !!((_a = (await findAccessToken(id))) === null || _a === void 0 ? void 0 : _a.revokedAt); };
42
+ export const isRevoked = async (id) => (await isMaybeRevoked(id)) && !!(await findAccessToken(id))?.revokedAt;
@@ -5,7 +5,7 @@ import { uuidv7 } from 'uuidv7';
5
5
  import { addToBloomFilter } from './revokations.js';
6
6
  export const createAccessToken = (profile, data) => allpeepDb().then(async ({ db }) => {
7
7
  const id = uuidv7();
8
- const accessToken = await accessTokensMapping.create(db, Object.assign(Object.assign({}, data), { id }));
8
+ const accessToken = await accessTokensMapping.create(db, { ...data, id });
9
9
  if (profile) {
10
10
  await profileAccessTokenConnector(db, profile, accessToken);
11
11
  }
@@ -8,8 +8,7 @@ import { createAccessToken, revokeAccessToken } from './mutations.js';
8
8
  export const verifySignedAccessToken = (token) => jwtUtil()
9
9
  .then((jwt) => jwt.verify(token))
10
10
  .then(async (result) => {
11
- var _a;
12
- if (!((_a = result === null || result === void 0 ? void 0 : result.payload) === null || _a === void 0 ? void 0 : _a.jti)) {
11
+ if (!result?.payload?.jti) {
13
12
  return undefined;
14
13
  }
15
14
  const id = result.payload.jti;
@@ -19,7 +18,6 @@ export const verifySignedAccessToken = (token) => jwtUtil()
19
18
  return result.payload;
20
19
  });
21
20
  export const createSignedAccessToken = async ({ profile, authorization, name, description, expirationTime, }) => {
22
- var _a;
23
21
  const id = uuidv7();
24
22
  const jwt = await jwtUtil();
25
23
  const signedToken = await jwt.sign({
@@ -28,7 +26,7 @@ export const createSignedAccessToken = async ({ profile, authorization, name, de
28
26
  id,
29
27
  });
30
28
  const result = await jwt.verify(signedToken);
31
- if (!((_a = result === null || result === void 0 ? void 0 : result.payload) === null || _a === void 0 ? void 0 : _a.exp)) {
29
+ if (!result?.payload?.exp) {
32
30
  throw new Error('Failed to verify signed token');
33
31
  }
34
32
  const expiresAt = new Date(result.payload.exp * 1000).toISOString();
@@ -42,8 +40,8 @@ export const createSignedAccessToken = async ({ profile, authorization, name, de
42
40
  export const createSignedProfileAccessToken = async ({ profile, account, name, description, scopes = [{ scopeLevel: 'admin', resource: { type: '*', id: '*' } }], expirationTime = '1y', }) => {
43
41
  const authorization = {
44
42
  identities: {
45
- profile: profile === null || profile === void 0 ? void 0 : profile.id,
46
- account: account === null || account === void 0 ? void 0 : account.id,
43
+ profile: profile?.id,
44
+ account: account?.id,
47
45
  },
48
46
  scopes,
49
47
  };
@@ -67,8 +65,7 @@ export const createSignedServiceToken = async ({ scopes, name, description, expi
67
65
  expirationTime,
68
66
  });
69
67
  export const createSignedGuestPass = async (profile, expirationTime = '1d') => {
70
- var _a;
71
- if (!((_a = profile.guestData) === null || _a === void 0 ? void 0 : _a.resource)) {
68
+ if (!profile.guestData?.resource) {
72
69
  throw new Error('Guest pass requires a resource');
73
70
  }
74
71
  const resource = profile.guestData.resource;
@@ -122,8 +119,8 @@ export const createSignedDbToken = (profile) => createSignedAccessToken({
122
119
  export const refreshSignedAccessToken = async (token) => {
123
120
  const jwt = await jwtUtil();
124
121
  const verified = await jwt.verify(token);
125
- const rawPayload = verified === null || verified === void 0 ? void 0 : verified.payload;
126
- if (!(rawPayload === null || rawPayload === void 0 ? void 0 : rawPayload.jti) || typeof rawPayload.jti !== 'string') {
122
+ const rawPayload = verified?.payload;
123
+ if (!rawPayload?.jti || typeof rawPayload.jti !== 'string') {
127
124
  return undefined;
128
125
  }
129
126
  const jti = rawPayload.jti;
@@ -138,7 +135,7 @@ export const refreshSignedAccessToken = async (token) => {
138
135
  }
139
136
  const authorization = authParsed.data;
140
137
  const existing = await findAccessToken(jti);
141
- if (!(existing === null || existing === void 0 ? void 0 : existing.signedToken) || existing.revokedAt) {
138
+ if (!existing?.signedToken || existing.revokedAt) {
142
139
  return undefined;
143
140
  }
144
141
  if (authorization.identities.profile) {
@@ -5,7 +5,7 @@ import { logger } from '../log/index.js';
5
5
  import { getProfiles } from '../profiles/cache.js';
6
6
  import { uuidv7 } from 'uuidv7';
7
7
  export const log = logger('core:accounts');
8
- export const normalizeEmailAddress = (email) => email === null || email === void 0 ? void 0 : email.toLowerCase();
8
+ export const normalizeEmailAddress = (email) => email?.toLowerCase();
9
9
  export const createEmailValidationToken = async (account) => {
10
10
  return jwtUtil().then((jwt) => jwt.sign({
11
11
  payload: { email: account.email },
@@ -33,4 +33,8 @@ export const sendEmailValidationMail = async (account) => {
33
33
  });
34
34
  };
35
35
  export const expandAccount = async (account) => account
36
- ? Object.assign(Object.assign({}, account), { profiles: await getProfiles(account.profiles.map((p) => p.id)) }) : undefined;
36
+ ? {
37
+ ...account,
38
+ profiles: await getProfiles(account.profiles.map((p) => p.id)),
39
+ }
40
+ : undefined;
@@ -81,11 +81,18 @@ export const createAccount = async (accountCreationData) => {
81
81
  await assertProfileCapacity();
82
82
  const { handle, displayName, avatar, bot } = accountCreationData.profile;
83
83
  const profileId = uuidv7();
84
- profile = await profilesMapping.create(db, Object.assign(Object.assign(Object.assign({ id: profileId, handle,
84
+ profile = await profilesMapping.create(db, {
85
+ id: profileId,
86
+ handle,
85
87
  displayName,
86
- avatar }, (bot === true ? { bot: true } : {})), { activityPub: {
88
+ avatar,
89
+ ...(bot === true ? { bot: true } : {}),
90
+ activityPub: {
87
91
  domain: coreConfig.activityPub.defaultDomain,
88
- }, type: 'local' }), localActorScalars(profileId, coreConfig.activityPub.defaultDomain)));
92
+ },
93
+ type: 'local',
94
+ ...localActorScalars(profileId, coreConfig.activityPub.defaultDomain),
95
+ });
89
96
  if (firstAccount && profile) {
90
97
  const ownerRole = await findRoleByKey('owner');
91
98
  if (ownerRole) {
@@ -127,9 +134,8 @@ export const createAccount = async (accountCreationData) => {
127
134
  return { account, profile };
128
135
  };
129
136
  export const updateAccount = async (accountData) => {
130
- var _a;
131
137
  const { db } = await allpeepDb();
132
- if (!((_a = accountData === null || accountData === void 0 ? void 0 : accountData.account) === null || _a === void 0 ? void 0 : _a.id)) {
138
+ if (!accountData?.account?.id) {
133
139
  throw new Error('Account ID is missing');
134
140
  }
135
141
  const previousEmail = accountData.account.email;
@@ -178,14 +184,13 @@ export const sendResetPasswordEmail = async (account) => {
178
184
  }));
179
185
  };
180
186
  export const validateEmail = async (token) => {
181
- var _a;
182
187
  const communityConf = await communityConfig();
183
188
  const jwt = await jwtUtil();
184
189
  const { db } = await allpeepDb();
185
190
  try {
186
191
  const validatedToken = await jwt.verify(token);
187
- const email = (_a = validatedToken === null || validatedToken === void 0 ? void 0 : validatedToken.payload) === null || _a === void 0 ? void 0 : _a.email;
188
- const account = await findAccountByEmail(email !== null && email !== void 0 ? email : '');
192
+ const email = validatedToken?.payload?.email;
193
+ const account = await findAccountByEmail(email ?? '');
189
194
  if (account) {
190
195
  await accountsMapping.update(db, account.id, { emailValidated: true });
191
196
  await accountsCache.del(account.id);
@@ -11,17 +11,17 @@ export const getAnalyticsCache = async (key) => {
11
11
  return undefined;
12
12
  return JSON.parse(raw);
13
13
  }
14
- catch (_a) {
14
+ catch {
15
15
  return undefined;
16
16
  }
17
17
  };
18
18
  export const setAnalyticsCache = async (key, value, opts) => {
19
19
  try {
20
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;
21
+ const ttl = opts?.includesToday ? OPEN_DAY_TTL_SEC : CLOSED_RANGE_TTL_SEC;
22
22
  await redis.set(key, JSON.stringify(value), { EX: ttl });
23
23
  }
24
- catch (_a) {
24
+ catch {
25
25
  // Overview still returns; Redis must not 500 the request.
26
26
  }
27
27
  };
@@ -6,7 +6,7 @@ import { analyticsDailyClicks } from '../db/pg/schema/analytics.js';
6
6
  import { resolveAnalyticsRange } from './dateRange.js';
7
7
  const log = logger('app:analytics:clicks');
8
8
  export const MAX_CLICK_TARGET_LENGTH = 512;
9
- export const MAX_DISTINCT_CLICK_TARGETS_PER_DAY = 5000;
9
+ export const MAX_DISTINCT_CLICK_TARGETS_PER_DAY = 5_000;
10
10
  export const TOP_CLICKS_LIMIT = 25;
11
11
  const SKIP_PAGE_PREFIXES = [
12
12
  '/admin',
@@ -41,7 +41,7 @@ export const normalizePageTarget = (raw) => {
41
41
  pathname = new URL(trimmed, 'https://openpeeps.invalid').pathname || '/';
42
42
  }
43
43
  }
44
- catch (_a) {
44
+ catch {
45
45
  return null;
46
46
  }
47
47
  if (!pathname.startsWith('/'))
@@ -67,7 +67,7 @@ export const normalizeLinkTarget = (raw) => {
67
67
  const path = url.pathname || '/';
68
68
  return truncateCheck(`${url.protocol}//${host}${port}${path}`);
69
69
  }
70
- catch (_a) {
70
+ catch {
71
71
  return null;
72
72
  }
73
73
  };
@@ -80,7 +80,6 @@ export const normalizeClickEvent = (event) => {
80
80
  return target ? { kind: 'link', target } : null;
81
81
  };
82
82
  export const tallyNormalizedClicks = (events) => {
83
- var _a;
84
83
  const counts = new Map();
85
84
  const tallies = new Map();
86
85
  for (const event of events) {
@@ -89,16 +88,13 @@ export const tallyNormalizedClicks = (events) => {
89
88
  continue;
90
89
  const key = `${normalized.kind}\0${normalized.target}`;
91
90
  counts.set(key, normalized);
92
- tallies.set(key, ((_a = tallies.get(key)) !== null && _a !== void 0 ? _a : 0) + 1);
91
+ tallies.set(key, (tallies.get(key) ?? 0) + 1);
93
92
  }
94
- return [...counts.entries()].map(([key, { kind, target }]) => {
95
- var _a;
96
- return ({
97
- kind,
98
- target,
99
- clicks: (_a = tallies.get(key)) !== null && _a !== void 0 ? _a : 0,
100
- });
101
- });
93
+ return [...counts.entries()].map(([key, { kind, target }]) => ({
94
+ kind,
95
+ target,
96
+ clicks: tallies.get(key) ?? 0,
97
+ }));
102
98
  };
103
99
  const incrementExisting = async (day, kind, target, clicks) => {
104
100
  const db = await database();
@@ -124,13 +120,12 @@ const upsertClick = async (day, kind, target, clicks) => {
124
120
  });
125
121
  };
126
122
  const distinctTargetCount = async (day) => {
127
- var _a, _b;
128
123
  const db = await database();
129
124
  const rows = await db
130
125
  .select({ n: count() })
131
126
  .from(analyticsDailyClicks)
132
127
  .where(eq(analyticsDailyClicks.day, day));
133
- return Number((_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.n) !== null && _b !== void 0 ? _b : 0);
128
+ return Number(rows[0]?.n ?? 0);
134
129
  };
135
130
  /** Live increment. Does not accept or persist a profile id. */
136
131
  export const recordClickEvents = async (events) => {
@@ -165,13 +160,10 @@ const topClicks = async (from, to, kind) => {
165
160
  .groupBy(analyticsDailyClicks.target)
166
161
  .orderBy(desc(sum(analyticsDailyClicks.clicks)))
167
162
  .limit(TOP_CLICKS_LIMIT);
168
- return rows.map((row) => {
169
- var _a;
170
- return ({
171
- target: row.target,
172
- clicks: Number((_a = row.clicks) !== null && _a !== void 0 ? _a : 0),
173
- });
174
- });
163
+ return rows.map((row) => ({
164
+ target: row.target,
165
+ clicks: Number(row.clicks ?? 0),
166
+ }));
175
167
  };
176
168
  export const getAnalyticsClicks = async (query = {}) => {
177
169
  const range = resolveAnalyticsRange(query);
@@ -13,10 +13,9 @@ const dayBounds = (day) => {
13
13
  return { start, end };
14
14
  };
15
15
  const countScalar = async (db, query) => {
16
- var _a, _b;
17
16
  const result = await db.execute(query);
18
17
  const rows = result.rows;
19
- return Number((_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.c) !== null && _b !== void 0 ? _b : 0);
18
+ return Number(rows[0]?.c ?? 0);
20
19
  };
21
20
  export const compileAnalyticsDay = async (day) => {
22
21
  const db = await database();
@@ -18,8 +18,7 @@ const presetBounds = (preset, now) => {
18
18
  }
19
19
  };
20
20
  export const resolveAnalyticsRange = (query = {}, now = new Date()) => {
21
- var _a;
22
- const preset = (_a = query.preset) !== null && _a !== void 0 ? _a : (!query.from && !query.to ? '30d' : undefined);
21
+ const preset = query.preset ?? (!query.from && !query.to ? '30d' : undefined);
23
22
  let fromDate;
24
23
  let toDate;
25
24
  if (query.from && query.to) {
@@ -27,7 +26,7 @@ export const resolveAnalyticsRange = (query = {}, now = new Date()) => {
27
26
  toDate = startOfDay(parseISO(query.to));
28
27
  }
29
28
  else {
30
- const bounds = presetBounds(preset !== null && preset !== void 0 ? preset : '30d', now);
29
+ const bounds = presetBounds(preset ?? '30d', now);
31
30
  fromDate = bounds.from;
32
31
  toDate = bounds.to;
33
32
  }
@@ -166,10 +165,9 @@ export const selectChartBuckets = (from, to) => {
166
165
  export const aggregateSeriesIntoBuckets = (series, buckets) => {
167
166
  const byDay = new Map(series.map((p) => [p.day, p.value]));
168
167
  return buckets.map((bucket) => {
169
- var _a;
170
168
  let value = 0;
171
169
  for (const day of eachUtcDay(bucket.from, bucket.to)) {
172
- value += (_a = byDay.get(day)) !== null && _a !== void 0 ? _a : 0;
170
+ value += byDay.get(day) ?? 0;
173
171
  }
174
172
  return { day: bucket.key, label: bucket.label, value };
175
173
  });
@@ -44,11 +44,10 @@ const [analyticsCompileQueue, analyticsCompileWorker] = queueAndWorker(ANALYTICS
44
44
  },
45
45
  });
46
46
  const maybeEnqueueInitialBackfill = async () => {
47
- var _a;
48
47
  const db = await database();
49
48
  const result = await db.execute(sql `select exists(select 1 from analytics_daily_totals limit 1) as has_rows`);
50
49
  const rows = result.rows;
51
- if ((_a = rows[0]) === null || _a === void 0 ? void 0 : _a.has_rows)
50
+ if (rows[0]?.has_rows)
52
51
  return;
53
52
  const queue = analyticsCompileQueue();
54
53
  const existing = await queue.getJob(INITIAL_BACKFILL_JOB_ID);
@@ -72,8 +71,8 @@ export const ensureAnalyticsSchedules = async () => {
72
71
  };
73
72
  export const enqueueAnalyticsBackfill = async (from, to) => {
74
73
  const defaults = defaultBackfillRange();
75
- const start = from !== null && from !== void 0 ? from : defaults.from;
76
- const end = to !== null && to !== void 0 ? to : defaults.to;
74
+ const start = from ?? defaults.from;
75
+ const end = to ?? defaults.to;
77
76
  const job = await analyticsCompileQueue().add('backfill', {
78
77
  type: 'backfill',
79
78
  from: start,
@@ -29,6 +29,7 @@ const POST_TYPE_META = [
29
29
  { key: 'note', label: 'Notes', color: '#9ca3af' },
30
30
  { key: 'poll', label: 'Polls', color: '#d1d5db' },
31
31
  { key: 'event', label: 'Events', color: '#6b7280' },
32
+ { key: 'resource', label: 'Resources', color: '#374151' },
32
33
  ];
33
34
  const ENGAGEMENT_SERIES = [
34
35
  { key: 'likes', label: 'Likes', color: '#111827' },
@@ -39,8 +40,11 @@ const ENGAGEMENT_SERIES = [
39
40
  ];
40
41
  /** Single-line text that must not trigger pdfkit auto page-breaks. */
41
42
  const writeText = (doc, text, x, y, options = {}) => {
42
- var _a;
43
- doc.text(text, x, y, Object.assign(Object.assign({ lineBreak: false }, options), { height: (_a = options.height) !== null && _a !== void 0 ? _a : 12 }));
43
+ doc.text(text, x, y, {
44
+ lineBreak: false,
45
+ ...options,
46
+ height: options.height ?? 12,
47
+ });
44
48
  };
45
49
  const formatNum = (n) => Number.isFinite(n) ? Math.round(n).toLocaleString('en-US') : '0';
46
50
  const formatDelta = (deltaPct) => {
@@ -50,7 +54,7 @@ const formatDelta = (deltaPct) => {
50
54
  return `${sign}${deltaPct}%`;
51
55
  };
52
56
  const averageSeries = (series) => {
53
- if (!(series === null || series === void 0 ? void 0 : series.length))
57
+ if (!series?.length)
54
58
  return 0;
55
59
  return (Math.round((series.reduce((acc, p) => acc + p.value, 0) / series.length) * 10) / 10);
56
60
  };
@@ -59,18 +63,17 @@ const utcDayCount = (from, to) => {
59
63
  const end = Date.parse(`${to}T00:00:00.000Z`);
60
64
  if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
61
65
  return 1;
62
- return Math.round((end - start) / 86400000) + 1;
66
+ return Math.round((end - start) / 86_400_000) + 1;
63
67
  };
64
68
  const ratePct = (numerator, denominator) => denominator <= 0 ? 0 : Math.round((numerator / denominator) * 1000) / 10;
65
69
  const truncate = (text, max) => text.length <= max ? text : `${text.slice(0, max - 1)}…`;
66
70
  const cumulativeGrowth = (points, series) => {
67
71
  const running = Object.fromEntries(series.map((s) => [s.key, 0]));
68
72
  return points.map((p) => {
69
- var _a, _b;
70
73
  for (const s of series) {
71
- running[s.key] = ((_a = running[s.key]) !== null && _a !== void 0 ? _a : 0) + ((_b = p.values[s.key]) !== null && _b !== void 0 ? _b : 0);
74
+ running[s.key] = (running[s.key] ?? 0) + (p.values[s.key] ?? 0);
72
75
  }
73
- return { label: p.label, values: Object.assign({}, running) };
76
+ return { label: p.label, values: { ...running } };
74
77
  });
75
78
  };
76
79
  const createDoc = (communityName) => new PDFDocument({
@@ -147,7 +150,6 @@ const drawMetricCards = (layout, cards) => {
147
150
  const rows = Math.ceil(cards.length / cols);
148
151
  ensureSpace(layout, rows * (cardH + gap));
149
152
  cards.forEach((card, i) => {
150
- var _a;
151
153
  const col = i % cols;
152
154
  const row = Math.floor(i / cols);
153
155
  const x = MARGIN + col * (cardW + gap);
@@ -166,7 +168,7 @@ const drawMetricCards = (layout, cards) => {
166
168
  height: 18,
167
169
  });
168
170
  const delta = formatDelta(card.deltaPct);
169
- const sub = (_a = card.subtitle) !== null && _a !== void 0 ? _a : '';
171
+ const sub = card.subtitle ?? '';
170
172
  const line = [delta, sub].filter(Boolean).join(' | ');
171
173
  if (line) {
172
174
  layout.doc
@@ -234,7 +236,7 @@ const drawStackedBarChart = (layout, points, height = 170) => {
234
236
  const pad = { t: 16, r: 12, b: 40, l: 36 };
235
237
  const plotW = frame.w - pad.l - pad.r;
236
238
  const plotH = frame.h - pad.t - pad.b;
237
- const totals = points.map((p) => p.jam + p.article + p.note + p.poll + p.event);
239
+ const totals = points.map((p) => p.jam + p.article + p.note + p.poll + p.event + p.resource);
238
240
  const max = Math.max(1, ...totals);
239
241
  const barGap = 4;
240
242
  const barW = points.length
@@ -313,7 +315,7 @@ const drawMultiLineChart = (layout, points, series, height = 180) => {
313
315
  const pad = { t: 16, r: 12, b: 44, l: 36 };
314
316
  const plotW = frame.w - pad.l - pad.r;
315
317
  const plotH = frame.h - pad.t - pad.b;
316
- const max = Math.max(1, ...points.flatMap((p) => series.map((s) => { var _a; return (_a = p.values[s.key]) !== null && _a !== void 0 ? _a : 0; })));
318
+ const max = Math.max(1, ...points.flatMap((p) => series.map((s) => p.values[s.key] ?? 0)));
317
319
  layout.doc
318
320
  .moveTo(frame.x + pad.l, frame.y + pad.t + plotH)
319
321
  .lineTo(frame.x + pad.l + plotW, frame.y + pad.t + plotH)
@@ -324,11 +326,10 @@ const drawMultiLineChart = (layout, points, series, height = 180) => {
324
326
  return;
325
327
  for (const s of series) {
326
328
  const coords = points.map((p, i) => {
327
- var _a;
328
329
  const x = frame.x +
329
330
  pad.l +
330
331
  (points.length === 1 ? plotW / 2 : (i / (points.length - 1)) * plotW);
331
- const y = frame.y + pad.t + plotH - (((_a = p.values[s.key]) !== null && _a !== void 0 ? _a : 0) / max) * plotH;
332
+ const y = frame.y + pad.t + plotH - ((p.values[s.key] ?? 0) / max) * plotH;
332
333
  return { x, y };
333
334
  });
334
335
  layout.doc
@@ -409,7 +410,6 @@ const drawStackedAreaAsBars = (layout, points, height = 170) => {
409
410
  }
410
411
  };
411
412
  const drawHorizontalBars = (layout, rows) => {
412
- var _a;
413
413
  const max = Math.max(1, ...rows.map((r) => r.value));
414
414
  const rowH = 22;
415
415
  ensureSpace(layout, rows.length * rowH + 20);
@@ -424,7 +424,7 @@ const drawHorizontalBars = (layout, rows) => {
424
424
  .roundedRect(barX, layout.y + 2, (row.value / max) * barW, 10, 3)
425
425
  .fill(row.color);
426
426
  layout.doc.fontSize(9).fillColor(COLORS.muted);
427
- writeText(layout.doc, `${formatNum(row.value)}${(_a = row.suffix) !== null && _a !== void 0 ? _a : ''}`, barX + barW + 8, layout.y, { width: 60, align: 'right' });
427
+ writeText(layout.doc, `${formatNum(row.value)}${row.suffix ?? ''}`, barX + barW + 8, layout.y, { width: 60, align: 'right' });
428
428
  layout.y += rowH;
429
429
  }
430
430
  layout.y += 8;
@@ -460,19 +460,17 @@ const drawDayHeatmap = (layout, cells) => {
460
460
  layout.y += 16;
461
461
  };
462
462
  const drawTable = (layout, columns, rows) => {
463
- var _a, _b;
464
463
  const headerH = 18;
465
464
  const rowH = 16;
466
465
  ensureSpace(layout, headerH + rowH * Math.min(rows.length, 3) + 8);
467
466
  const drawHeader = () => {
468
- var _a;
469
467
  layout.doc.rect(MARGIN, layout.y, CONTENT_WIDTH, headerH).fill(COLORS.soft);
470
468
  let x = MARGIN + 6;
471
469
  for (const col of columns) {
472
470
  layout.doc.fontSize(8).fillColor(COLORS.muted).font('Helvetica-Bold');
473
471
  writeText(layout.doc, col.header.toUpperCase(), x, layout.y + 5, {
474
472
  width: col.width - 8,
475
- align: (_a = col.align) !== null && _a !== void 0 ? _a : 'left',
473
+ align: col.align ?? 'left',
476
474
  });
477
475
  x += col.width;
478
476
  }
@@ -488,9 +486,9 @@ const drawTable = (layout, columns, rows) => {
488
486
  let x = MARGIN + 6;
489
487
  for (const col of columns) {
490
488
  layout.doc.fontSize(8).fillColor(COLORS.ink);
491
- writeText(layout.doc, (_a = row[col.key]) !== null && _a !== void 0 ? _a : '', x, layout.y + 3, {
489
+ writeText(layout.doc, row[col.key] ?? '', x, layout.y + 3, {
492
490
  width: col.width - 8,
493
- align: (_b = col.align) !== null && _b !== void 0 ? _b : 'left',
491
+ align: col.align ?? 'left',
494
492
  ellipsis: true,
495
493
  });
496
494
  x += col.width;
@@ -550,31 +548,24 @@ const drawOverviewPage = (layout, overview) => {
550
548
  { key: 'role', header: 'Role', width: 100 },
551
549
  { key: 'joined', header: 'Joined', width: 100 },
552
550
  { key: 'contrib', header: 'Contributions', width: 152, align: 'right' },
553
- ], overview.topMembers.slice(0, 8).map((m) => {
554
- var _a, _b;
555
- return ({
556
- member: truncate((_a = m.displayName) !== null && _a !== void 0 ? _a : m.handle, 28),
557
- role: (_b = m.role) !== null && _b !== void 0 ? _b : 'member',
558
- joined: m.joinedAt.slice(0, 10),
559
- contrib: formatNum(m.contributions),
560
- });
561
- }));
551
+ ], overview.topMembers.slice(0, 8).map((m) => ({
552
+ member: truncate(m.displayName ?? m.handle, 28),
553
+ role: m.role ?? 'member',
554
+ joined: m.joinedAt.slice(0, 10),
555
+ contrib: formatNum(m.contributions),
556
+ })));
562
557
  drawSectionTitle(layout, 'Top posts');
563
558
  drawTable(layout, [
564
559
  { key: 'post', header: 'Post', width: 260 },
565
560
  { key: 'author', header: 'Author', width: 140 },
566
561
  { key: 'views', header: 'Viewers', width: 132, align: 'right' },
567
- ], overview.topPosts.slice(0, 8).map((p) => {
568
- var _a, _b, _c;
569
- return ({
570
- post: truncate((_a = p.snippet) !== null && _a !== void 0 ? _a : p.postId, 42),
571
- author: truncate((_c = (_b = p.authorDisplayName) !== null && _b !== void 0 ? _b : p.authorHandle) !== null && _c !== void 0 ? _c : '—', 22),
572
- views: formatNum(p.uniqueViewers),
573
- });
574
- }));
562
+ ], overview.topPosts.slice(0, 8).map((p) => ({
563
+ post: truncate(p.snippet ?? p.postId, 42),
564
+ author: truncate(p.authorDisplayName ?? p.authorHandle ?? '—', 22),
565
+ views: formatNum(p.uniqueViewers),
566
+ })));
575
567
  };
576
568
  const drawMembersPage = (layout, overview, growth) => {
577
- var _a;
578
569
  startSection(layout, 'Members');
579
570
  const engagementRate = averageSeries(overview.engagementRateSeries);
580
571
  drawMetricCards(layout, [
@@ -605,7 +596,7 @@ const drawMembersPage = (layout, overview, growth) => {
605
596
  drawSectionTitle(layout, 'Signups by day');
606
597
  const signupsByDay = growth.signupsByDay.length > 0
607
598
  ? growth.signupsByDay
608
- : ((_a = growth.metrics.newSignups.series) !== null && _a !== void 0 ? _a : []).map((p) => ({
599
+ : (growth.metrics.newSignups.series ?? []).map((p) => ({
609
600
  day: p.day,
610
601
  value: p.value,
611
602
  }));
@@ -615,14 +606,11 @@ const drawMembersPage = (layout, overview, growth) => {
615
606
  { key: 'member', header: 'Member', width: 180 },
616
607
  { key: 'channel', header: 'Channel', width: 140 },
617
608
  { key: 'joined', header: 'Joined', width: 212 },
618
- ], growth.recentSignups.slice(0, 12).map((s) => {
619
- var _a;
620
- return ({
621
- member: truncate((_a = s.displayName) !== null && _a !== void 0 ? _a : s.handle, 28),
622
- channel: s.channel,
623
- joined: s.joinedAt.slice(0, 10),
624
- });
625
- }));
609
+ ], growth.recentSignups.slice(0, 12).map((s) => ({
610
+ member: truncate(s.displayName ?? s.handle, 28),
611
+ channel: s.channel,
612
+ joined: s.joinedAt.slice(0, 10),
613
+ })));
626
614
  };
627
615
  const drawContentPage = (layout, overview) => {
628
616
  startSection(layout, 'Content');
@@ -651,15 +639,14 @@ const drawContentPage = (layout, overview) => {
651
639
  drawSectionTitle(layout, 'Posts by period');
652
640
  drawBarChart(layout, overview.postsOverTime.map((p) => ({
653
641
  label: p.label,
654
- value: p.jam + p.article + p.note + p.poll + p.event,
642
+ value: p.jam + p.article + p.note + p.poll + p.event + p.resource,
655
643
  })));
656
644
  drawSectionTitle(layout, 'Content distribution');
657
645
  const typeRows = POST_TYPE_META.map((meta) => {
658
- var _a;
659
646
  const found = overview.postTypes.find((p) => p.type === meta.key);
660
647
  return {
661
648
  label: meta.label,
662
- value: (_a = found === null || found === void 0 ? void 0 : found.count) !== null && _a !== void 0 ? _a : 0,
649
+ value: found?.count ?? 0,
663
650
  color: meta.color,
664
651
  };
665
652
  }).filter((r) => r.value > 0);
@@ -759,17 +746,14 @@ const drawGroupsPage = (layout, overview) => {
759
746
  { key: 'posts', header: 'Posts', width: 60, align: 'right' },
760
747
  { key: 'engagement', header: 'Engagement', width: 80, align: 'right' },
761
748
  { key: 'growth', header: 'Growth', width: 72, align: 'right' },
762
- ], overview.topGroups.map((g) => {
763
- var _a, _b;
764
- return ({
765
- group: truncate((_b = (_a = g.name) !== null && _a !== void 0 ? _a : g.handle) !== null && _b !== void 0 ? _b : g.groupId, 24),
766
- visibility: g.visibility === 'public' ? 'Public' : 'Private',
767
- members: `${formatNum(g.members)} / ${formatNum(g.activeMembers)}`,
768
- posts: formatNum(g.posts),
769
- engagement: `${g.engagementRate}%`,
770
- growth: g.growth > 0 ? `+${g.growth}` : String(g.growth),
771
- });
772
- }));
749
+ ], overview.topGroups.map((g) => ({
750
+ group: truncate(g.name ?? g.handle ?? g.groupId, 24),
751
+ visibility: g.visibility === 'public' ? 'Public' : 'Private',
752
+ members: `${formatNum(g.members)} / ${formatNum(g.activeMembers)}`,
753
+ posts: formatNum(g.posts),
754
+ engagement: `${g.engagementRate}%`,
755
+ growth: g.growth > 0 ? `+${g.growth}` : String(g.growth),
756
+ })));
773
757
  drawSectionTitle(layout, 'Group growth (new members, cumulative)');
774
758
  const series = overview.groupGrowthSeries.map((s, i) => ({
775
759
  key: s.key,
@@ -2,7 +2,7 @@
2
2
  * Public groups grant `core-groups-read` to role `none`. Missing capabilities
3
3
  * means private — same rule as the analytics group tables.
4
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'); };
5
+ export const isPublicAnalyticsGroup = (body) => (body.capabilities?.none?.add ?? []).includes('core-groups-read');
6
6
  /**
7
7
  * Top-posts cards show author + snippet. Exclude DMs and any post linked to a
8
8
  * private group. A post with no group links is eligible when not `direct`.