@openpeepshq/core 0.1.31 → 0.1.33

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 (167) 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/analytics/cache.js +12 -7
  5. package/dist/analytics/clicks.d.ts +20 -0
  6. package/dist/analytics/clicks.js +194 -0
  7. package/dist/analytics/index.d.ts +1 -0
  8. package/dist/analytics/index.js +1 -0
  9. package/dist/analytics/metrics.d.ts +1 -0
  10. package/dist/analytics/metrics.js +5 -0
  11. package/dist/analytics/pdfReport.d.ts +1 -0
  12. package/dist/analytics/pdfReport.js +7 -5
  13. package/dist/analytics/privacy.d.ts +18 -0
  14. package/dist/analytics/privacy.js +10 -0
  15. package/dist/analytics/read.js +74 -16
  16. package/dist/analytics/report.d.ts +32 -1
  17. package/dist/analytics/report.js +9 -2
  18. package/dist/backups/index.js +13 -5
  19. package/dist/backups/metadata.d.ts +7 -0
  20. package/dist/config/defaults/community.js +0 -6
  21. package/dist/config/defaults/core.js +1 -0
  22. package/dist/config/defaults/db.d.ts +0 -2
  23. package/dist/config/defaults/db.js +0 -2
  24. package/dist/config/index.d.ts +20 -9
  25. package/dist/db/helpers.d.ts +6 -28
  26. package/dist/db/helpers.js +19 -149
  27. package/dist/db/index.d.ts +2 -0
  28. package/dist/db/index.js +4 -0
  29. package/dist/db/init.js +3 -2
  30. package/dist/db/migration/detect.d.ts +0 -3
  31. package/dist/db/migration/detect.js +0 -54
  32. package/dist/db/migration/importCollections.d.ts +1 -1
  33. package/dist/db/migration/importCollections.js +22 -6
  34. package/dist/db/migration/shared.d.ts +0 -4
  35. package/dist/db/migration/shared.js +0 -7
  36. package/dist/db/migration/transform.d.ts +2 -0
  37. package/dist/db/migration/transform.js +23 -0
  38. package/dist/db/pg/client.js +4 -0
  39. package/dist/db/pg/filters/edges.d.ts +1 -1
  40. package/dist/db/pg/filters/edges.js +1 -1
  41. package/dist/db/pg/filters/posts.d.ts +1 -0
  42. package/dist/db/pg/filters/posts.js +11 -1
  43. package/dist/db/pg/map/filters.js +5 -0
  44. package/dist/db/pg/map/relations.d.ts +1 -1
  45. package/dist/db/pg/map/relations.js +89 -41
  46. package/dist/db/pg/migrate.d.ts +23 -0
  47. package/dist/db/pg/migrate.js +87 -1
  48. package/dist/db/pg/queries/derived.d.ts +5 -0
  49. package/dist/db/pg/queries/derived.js +21 -0
  50. package/dist/db/pg/schema/analytics.d.ts +76 -0
  51. package/dist/db/pg/schema/analytics.js +11 -1
  52. package/dist/db/pg/schema/documents.d.ts +143 -0
  53. package/dist/db/pg/schema/documents.js +22 -1
  54. package/dist/db/pg/schema/edges.d.ts +1 -0
  55. package/dist/db/pg/schema/edges.js +1 -0
  56. package/dist/db/pg/schema/index.d.ts +218 -0
  57. package/dist/db/pg/sql/0005_open_power_man.sql +9 -0
  58. package/dist/db/pg/sql/0006_fine_trish_tilby.sql +8 -0
  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/meta/0004_snapshot.json +1 -1
  63. package/dist/db/pg/sql/meta/0005_snapshot.json +4179 -0
  64. package/dist/db/pg/sql/meta/0006_snapshot.json +4200 -0
  65. package/dist/db/pg/sql/meta/0007_snapshot.json +4179 -0
  66. package/dist/db/pg/sql/meta/0009_snapshot.json +4299 -0
  67. package/dist/db/pg/sql/meta/_journal.json +35 -0
  68. package/dist/db/replaceOrigin.d.ts +11 -0
  69. package/dist/db/replaceOrigin.js +116 -0
  70. package/dist/db/types.d.ts +0 -4
  71. package/dist/events/index.d.ts +2 -1
  72. package/dist/events/index.js +54 -33
  73. package/dist/groups/finders.d.ts +2 -2
  74. package/dist/groups/helpers.d.ts +6 -6
  75. package/dist/groups/mapping.d.ts +4 -4
  76. package/dist/groups/mapping.js +2 -2
  77. package/dist/groups/mutations.js +1 -1
  78. package/dist/inviteLinks/helpers.d.ts +4 -4
  79. package/dist/jams/cache.d.ts +1 -1
  80. package/dist/jams/cache.js +2 -1
  81. package/dist/jams/finders.d.ts +2 -1
  82. package/dist/jams/finders.js +18 -7
  83. package/dist/jams/helpers.d.ts +8 -4
  84. package/dist/jams/index.d.ts +4 -3
  85. package/dist/jams/index.js +23 -12
  86. package/dist/jams/livekit.d.ts +46 -8
  87. package/dist/jams/livekit.js +103 -21
  88. package/dist/jams/mapping.d.ts +14 -4
  89. package/dist/jams/mutations.d.ts +2 -0
  90. package/dist/jams/rtmp.d.ts +5 -0
  91. package/dist/jams/rtmp.js +8 -0
  92. package/dist/jams/token.d.ts +3 -3
  93. package/dist/jams/token.js +15 -12
  94. package/dist/jams/waitingRoom.d.ts +6 -4
  95. package/dist/jams/waitingRoom.js +33 -24
  96. package/dist/migration/index.d.ts +4 -0
  97. package/dist/migration/index.js +4 -0
  98. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +3 -1
  99. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +3 -1
  100. package/dist/notifications/helpers.js +6 -2
  101. package/dist/notifications/jobs.js +13 -2
  102. package/dist/notifications/push.js +11 -4
  103. package/dist/plugins/helpers.d.ts +6 -2
  104. package/dist/plugins/helpers.js +22 -10
  105. package/dist/plugins/index.d.ts +6 -1
  106. package/dist/plugins/index.js +54 -13
  107. package/dist/plugins/install.d.ts +20 -0
  108. package/dist/plugins/install.js +223 -0
  109. package/dist/plugins/state.d.ts +4 -0
  110. package/dist/plugins/state.js +29 -0
  111. package/dist/posts/contextClosure.d.ts +2 -1
  112. package/dist/posts/contextClosure.js +6 -1
  113. package/dist/posts/conversationQueries.d.ts +23 -0
  114. package/dist/posts/conversationQueries.js +135 -0
  115. package/dist/posts/eventAgenda.d.ts +165 -0
  116. package/dist/posts/eventAgenda.js +120 -0
  117. package/dist/posts/eventOccurrenceJobs.d.ts +4 -0
  118. package/dist/posts/eventOccurrenceJobs.js +23 -0
  119. package/dist/posts/eventOccurrences.d.ts +4 -0
  120. package/dist/posts/eventOccurrences.js +40 -0
  121. package/dist/posts/finders.d.ts +39 -13
  122. package/dist/posts/finders.js +51 -66
  123. package/dist/posts/helpers/filters.js +1 -1
  124. package/dist/posts/helpers/index.d.ts +120 -34
  125. package/dist/posts/helpers/index.js +34 -21
  126. package/dist/posts/index.d.ts +4 -0
  127. package/dist/posts/index.js +4 -0
  128. package/dist/posts/mapping.d.ts +454 -0
  129. package/dist/posts/mapping.js +43 -9
  130. package/dist/posts/mutations.d.ts +4 -2
  131. package/dist/posts/mutations.js +49 -16
  132. package/dist/posts/rsvpConfirmationEmail.js +2 -1
  133. package/dist/posts/unseenCounts.d.ts +12 -0
  134. package/dist/posts/unseenCounts.js +98 -0
  135. package/dist/profiles/cache.d.ts +5 -1
  136. package/dist/profiles/cache.js +27 -1
  137. package/dist/profiles/helpers.d.ts +5 -5
  138. package/dist/profiles/index.d.ts +1 -0
  139. package/dist/profiles/index.js +1 -0
  140. package/dist/profiles/mapping.d.ts +45 -4
  141. package/dist/profiles/mapping.js +24 -0
  142. package/dist/profiles/mutations.js +12 -14
  143. package/dist/pushSubscriptions/helpers.d.ts +2 -2
  144. package/dist/pushSubscriptions/mutations.js +13 -1
  145. package/dist/reports/helpers.d.ts +6 -6
  146. package/dist/reports/helpers.js +2 -1
  147. package/dist/reports/mapping.js +6 -2
  148. package/dist/roles/defaults.js +1 -0
  149. package/dist/roles/mutations.d.ts +3 -3
  150. package/dist/roles/mutations.js +5 -3
  151. package/dist/server/index.d.ts +15 -7
  152. package/dist/server/index.js +15 -8
  153. package/dist/session/index.d.ts +28 -0
  154. package/dist/session/index.js +79 -0
  155. package/dist/stats/finders.d.ts +1912 -362
  156. package/dist/stats/mapping.d.ts +26 -5
  157. package/package.json +7 -12
  158. package/dist/db/arango.d.ts +0 -2
  159. package/dist/db/arango.js +0 -110
  160. package/dist/db/migration/autoMigrate.d.ts +0 -2
  161. package/dist/db/migration/autoMigrate.js +0 -111
  162. package/dist/db/migration/cli.d.ts +0 -1
  163. package/dist/db/migration/cli.js +0 -56
  164. package/dist/db/migration/exportArango.d.ts +0 -4
  165. package/dist/db/migration/exportArango.js +0 -80
  166. package/dist/db/replaceHostname.d.ts +0 -1
  167. package/dist/db/replaceHostname.js +0 -88
@@ -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
  }>>;
@@ -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();
@@ -0,0 +1,20 @@
1
+ import type { AnalyticsClickEvent, AnalyticsClickKind, AnalyticsClicks, AnalyticsDateQuery } from '@openpeepshq/common/types';
2
+ export declare const MAX_CLICK_TARGET_LENGTH = 512;
3
+ export declare const MAX_DISTINCT_CLICK_TARGETS_PER_DAY = 5000;
4
+ export declare const TOP_CLICKS_LIMIT = 25;
5
+ /** Pathname only; drop query/hash; skip admin/api/auth routes. */
6
+ export declare const normalizePageTarget: (raw: string) => string | null;
7
+ /** origin + pathname, lowercase host, no query/hash. http(s) only. */
8
+ export declare const normalizeLinkTarget: (raw: string) => string | null;
9
+ export declare const normalizeClickEvent: (event: AnalyticsClickEvent) => {
10
+ kind: AnalyticsClickKind;
11
+ target: string;
12
+ } | null;
13
+ export declare const tallyNormalizedClicks: (events: AnalyticsClickEvent[]) => Array<{
14
+ kind: AnalyticsClickKind;
15
+ target: string;
16
+ clicks: number;
17
+ }>;
18
+ /** Live increment. Does not accept or persist a profile id. */
19
+ export declare const recordClickEvents: (events: AnalyticsClickEvent[]) => Promise<void>;
20
+ export declare const getAnalyticsClicks: (query?: AnalyticsDateQuery) => Promise<AnalyticsClicks>;
@@ -0,0 +1,194 @@
1
+ import { and, count, desc, eq, gte, lte, sql, sum } from 'drizzle-orm';
2
+ import { formatISO, startOfDay } from 'date-fns';
3
+ import { logger } from '../log/index.js';
4
+ import { database } from '../db/index.js';
5
+ import { analyticsDailyClicks } from '../db/pg/schema/analytics.js';
6
+ import { resolveAnalyticsRange } from './dateRange.js';
7
+ const log = logger('app:analytics:clicks');
8
+ export const MAX_CLICK_TARGET_LENGTH = 512;
9
+ export const MAX_DISTINCT_CLICK_TARGETS_PER_DAY = 5000;
10
+ export const TOP_CLICKS_LIMIT = 25;
11
+ const SKIP_PAGE_PREFIXES = [
12
+ '/admin',
13
+ '/api',
14
+ '/login',
15
+ '/signup',
16
+ '/register',
17
+ '/auth',
18
+ '/oauth',
19
+ '/sso',
20
+ '/health',
21
+ '/_db',
22
+ ];
23
+ const todayString = () => formatISO(startOfDay(new Date()), { representation: 'date' });
24
+ const skipPagePath = (pathname) => SKIP_PAGE_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
25
+ const truncateCheck = (value) => value.length === 0 || value.length > MAX_CLICK_TARGET_LENGTH ? null : value;
26
+ /** Pathname only; drop query/hash; skip admin/api/auth routes. */
27
+ export const normalizePageTarget = (raw) => {
28
+ const trimmed = raw.trim();
29
+ if (!trimmed)
30
+ return null;
31
+ let pathname;
32
+ try {
33
+ if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed)) {
34
+ const url = new URL(trimmed);
35
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
36
+ return null;
37
+ }
38
+ pathname = url.pathname || '/';
39
+ }
40
+ else {
41
+ pathname = new URL(trimmed, 'https://openpeeps.invalid').pathname || '/';
42
+ }
43
+ }
44
+ catch (_a) {
45
+ return null;
46
+ }
47
+ if (!pathname.startsWith('/'))
48
+ return null;
49
+ if (skipPagePath(pathname))
50
+ return null;
51
+ return truncateCheck(pathname);
52
+ };
53
+ /** origin + pathname, lowercase host, no query/hash. http(s) only. */
54
+ export const normalizeLinkTarget = (raw) => {
55
+ const trimmed = raw.trim();
56
+ if (!trimmed)
57
+ return null;
58
+ if (/^(javascript|data|mailto|tel|blob):/i.test(trimmed))
59
+ return null;
60
+ try {
61
+ const url = new URL(trimmed);
62
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
63
+ return null;
64
+ }
65
+ const host = url.hostname.toLowerCase();
66
+ const port = url.port ? `:${url.port}` : '';
67
+ const path = url.pathname || '/';
68
+ return truncateCheck(`${url.protocol}//${host}${port}${path}`);
69
+ }
70
+ catch (_a) {
71
+ return null;
72
+ }
73
+ };
74
+ export const normalizeClickEvent = (event) => {
75
+ if (event.kind === 'page') {
76
+ const target = normalizePageTarget(event.target);
77
+ return target ? { kind: 'page', target } : null;
78
+ }
79
+ const target = normalizeLinkTarget(event.target);
80
+ return target ? { kind: 'link', target } : null;
81
+ };
82
+ export const tallyNormalizedClicks = (events) => {
83
+ var _a;
84
+ const counts = new Map();
85
+ const tallies = new Map();
86
+ for (const event of events) {
87
+ const normalized = normalizeClickEvent(event);
88
+ if (!normalized)
89
+ continue;
90
+ const key = `${normalized.kind}\0${normalized.target}`;
91
+ counts.set(key, normalized);
92
+ tallies.set(key, ((_a = tallies.get(key)) !== null && _a !== void 0 ? _a : 0) + 1);
93
+ }
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
+ });
102
+ };
103
+ const incrementExisting = async (day, kind, target, clicks) => {
104
+ const db = await database();
105
+ await db
106
+ .update(analyticsDailyClicks)
107
+ .set({
108
+ clicks: sql `${analyticsDailyClicks.clicks} + ${clicks}`,
109
+ })
110
+ .where(and(eq(analyticsDailyClicks.day, day), eq(analyticsDailyClicks.kind, kind), eq(analyticsDailyClicks.target, target)));
111
+ };
112
+ const upsertClick = async (day, kind, target, clicks) => {
113
+ const db = await database();
114
+ await db
115
+ .insert(analyticsDailyClicks)
116
+ .values({ day, kind, target, clicks })
117
+ .onConflictDoUpdate({
118
+ target: [
119
+ analyticsDailyClicks.day,
120
+ analyticsDailyClicks.kind,
121
+ analyticsDailyClicks.target,
122
+ ],
123
+ set: { clicks: sql `${analyticsDailyClicks.clicks} + ${clicks}` },
124
+ });
125
+ };
126
+ const distinctTargetCount = async (day) => {
127
+ var _a, _b;
128
+ const db = await database();
129
+ const rows = await db
130
+ .select({ n: count() })
131
+ .from(analyticsDailyClicks)
132
+ .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);
134
+ };
135
+ /** Live increment. Does not accept or persist a profile id. */
136
+ export const recordClickEvents = async (events) => {
137
+ const tallied = tallyNormalizedClicks(events);
138
+ if (tallied.length === 0)
139
+ return;
140
+ const day = todayString();
141
+ let distinct = await distinctTargetCount(day);
142
+ let loggedCap = false;
143
+ for (const row of tallied) {
144
+ if (distinct >= MAX_DISTINCT_CLICK_TARGETS_PER_DAY) {
145
+ if (!loggedCap) {
146
+ log.warn('Dropping new click targets; day %s already has %s distinct targets', day, distinct);
147
+ loggedCap = true;
148
+ }
149
+ await incrementExisting(day, row.kind, row.target, row.clicks);
150
+ continue;
151
+ }
152
+ await upsertClick(day, row.kind, row.target, row.clicks);
153
+ distinct += 1;
154
+ }
155
+ };
156
+ const topClicks = async (from, to, kind) => {
157
+ const db = await database();
158
+ const rows = await db
159
+ .select({
160
+ target: analyticsDailyClicks.target,
161
+ clicks: sum(analyticsDailyClicks.clicks),
162
+ })
163
+ .from(analyticsDailyClicks)
164
+ .where(and(gte(analyticsDailyClicks.day, from), lte(analyticsDailyClicks.day, to), eq(analyticsDailyClicks.kind, kind)))
165
+ .groupBy(analyticsDailyClicks.target)
166
+ .orderBy(desc(sum(analyticsDailyClicks.clicks)))
167
+ .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
+ });
175
+ };
176
+ export const getAnalyticsClicks = async (query = {}) => {
177
+ const range = resolveAnalyticsRange(query);
178
+ const [pages, links] = await Promise.all([
179
+ topClicks(range.from, range.to, 'page'),
180
+ topClicks(range.from, range.to, 'link'),
181
+ ]);
182
+ return {
183
+ range: {
184
+ from: range.from,
185
+ to: range.to,
186
+ previousFrom: range.previousFrom,
187
+ previousTo: range.previousTo,
188
+ preset: range.preset,
189
+ compiledAt: null,
190
+ },
191
+ pages,
192
+ links,
193
+ };
194
+ };
@@ -2,6 +2,7 @@ export { resolveAnalyticsRange, eachUtcDay, type ResolvedAnalyticsRange, } from
2
2
  export { analyticsCacheKey, getAnalyticsCache, setAnalyticsCache, invalidateAnalyticsCache, } from './cache';
3
3
  export { compileAnalyticsDay, compileRetentionCohorts, compileRecentAnalytics, backfillAnalytics, } from './compile';
4
4
  export { getAnalyticsOverview, getAnalyticsGrowth, getAnalyticsEngagement, getAnalyticsRetention, exportAnalyticsCsv, } from './read';
5
+ export { recordClickEvents, getAnalyticsClicks, normalizeClickEvent, } from './clicks';
5
6
  export { getAnalyticsReportSettings, setAnalyticsReportSettings, } from './settings';
6
7
  export { sendMonthlyAnalyticsReport, buildSimplePdf, buildAnalyticsBoardReport, } from './report';
7
8
  export { buildAnalyticsPdf, type AnalyticsPdfData } from './pdfReport';
@@ -2,6 +2,7 @@ export { resolveAnalyticsRange, eachUtcDay, } from './dateRange.js';
2
2
  export { analyticsCacheKey, getAnalyticsCache, setAnalyticsCache, invalidateAnalyticsCache, } from './cache.js';
3
3
  export { compileAnalyticsDay, compileRetentionCohorts, compileRecentAnalytics, backfillAnalytics, } from './compile.js';
4
4
  export { getAnalyticsOverview, getAnalyticsGrowth, getAnalyticsEngagement, getAnalyticsRetention, exportAnalyticsCsv, } from './read.js';
5
+ export { recordClickEvents, getAnalyticsClicks, normalizeClickEvent, } from './clicks.js';
5
6
  export { getAnalyticsReportSettings, setAnalyticsReportSettings, } from './settings.js';
6
7
  export { sendMonthlyAnalyticsReport, buildSimplePdf, buildAnalyticsBoardReport, } from './report.js';
7
8
  export { buildAnalyticsPdf } from './pdfReport.js';
@@ -2,3 +2,4 @@ import type { AnalyticsMetricCard, AnalyticsSeriesPoint } from '@openpeepshq/com
2
2
  export declare const deltaPct: (current: number, previous: number) => number | null;
3
3
  export declare const metricCard: (key: string, value: number, previousValue: number, series?: AnalyticsSeriesPoint[]) => AnalyticsMetricCard;
4
4
  export declare const sumSeries: (series: AnalyticsSeriesPoint[]) => number;
5
+ export declare const averageSeries: (series: AnalyticsSeriesPoint[]) => number;
@@ -11,3 +11,8 @@ export const metricCard = (key, value, previousValue, series) => ({
11
11
  series,
12
12
  });
13
13
  export const sumSeries = (series) => series.reduce((acc, p) => acc + p.value, 0);
14
+ export const averageSeries = (series) => {
15
+ if (series.length === 0)
16
+ return 0;
17
+ return Math.round((sumSeries(series) / series.length) * 10) / 10;
18
+ };
@@ -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;
@@ -35,6 +35,7 @@ const ENGAGEMENT_SERIES = [
35
35
  { key: 'reposts', label: 'Shares', color: '#4b5563' },
36
36
  { key: 'bookmarks', label: 'Bookmarks', color: '#6b7280' },
37
37
  { key: 'comments', label: 'Replies', color: '#9ca3af' },
38
+ { key: 'dms', label: 'DMs', color: '#d97706' },
38
39
  ];
39
40
  /** Single-line text that must not trigger pdfkit auto page-breaks. */
40
41
  const writeText = (doc, text, x, y, options = {}) => {
@@ -72,12 +73,12 @@ const cumulativeGrowth = (points, series) => {
72
73
  return { label: p.label, values: Object.assign({}, running) };
73
74
  });
74
75
  };
75
- const createDoc = () => new PDFDocument({
76
+ const createDoc = (communityName) => new PDFDocument({
76
77
  size: 'LETTER',
77
78
  margin: MARGIN,
78
79
  compress: false,
79
80
  info: {
80
- Title: 'Community analytics report',
81
+ Title: `${communityName} analytics report`,
81
82
  Author: 'OpenPeeps',
82
83
  },
83
84
  });
@@ -368,7 +369,7 @@ const drawStackedAreaAsBars = (layout, points, height = 170) => {
368
369
  const pad = { t: 16, r: 12, b: 40, l: 36 };
369
370
  const plotW = frame.w - pad.l - pad.r;
370
371
  const plotH = frame.h - pad.t - pad.b;
371
- const totals = points.map((p) => p.likes + p.comments + p.reposts + p.bookmarks);
372
+ const totals = points.map((p) => p.likes + p.comments + p.reposts + p.bookmarks + p.dms);
372
373
  const max = Math.max(1, ...totals);
373
374
  const barGap = 3;
374
375
  const barW = points.length
@@ -787,7 +788,7 @@ const drawGroupsPage = (layout, overview) => {
787
788
  };
788
789
  /** Multi-page visual PDF mirroring the analytics tabs. */
789
790
  export const buildAnalyticsPdf = async (data) => {
790
- const doc = createDoc();
791
+ const doc = createDoc(data.communityName);
791
792
  const pending = bufferFromDoc(doc);
792
793
  const period = `${data.overview.range.from} to ${data.overview.range.to}`;
793
794
  const layout = {
@@ -799,8 +800,9 @@ export const buildAnalyticsPdf = async (data) => {
799
800
  };
800
801
  // Cover strip on first page before section chrome
801
802
  doc.fontSize(10).fillColor(COLORS.muted).font('Helvetica');
802
- writeText(doc, 'OpenPeeps - Community analytics', MARGIN, layout.y, {
803
+ writeText(doc, `${data.communityName} - Community analytics`, MARGIN, layout.y, {
803
804
  width: CONTENT_WIDTH,
805
+ ellipsis: true,
804
806
  });
805
807
  layout.y += 16;
806
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);
@@ -1,14 +1,45 @@
1
1
  import { and, asc, desc, gte, lte, min, sql, sum } from 'drizzle-orm';
2
- import { formatISO, startOfDay } from 'date-fns';
2
+ import { formatISO, startOfDay, subDays, parseISO, addDays } from 'date-fns';
3
3
  import { database } from '../db/index.js';
4
4
  import { analyticsDailyByGroup, analyticsDailyTotals, analyticsPostViewsDaily, analyticsRetentionCohorts, } from '../db/pg/schema/analytics.js';
5
5
  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
- import { metricCard, sumSeries } from './metrics.js';
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();
13
+ const utcDayStart = (day) => `${day}T00:00:00.000Z`;
14
+ const exclusiveEnd = (day) => `${formatISO(addDays(parseISO(utcDayStart(day)), 1), { representation: 'date' })}T00:00:00.000Z`;
15
+ const rollingMauFrom = (to) => formatISO(subDays(parseISO(utcDayStart(to)), 29), { representation: 'date' });
16
+ const countDistinctActives = async (from, to) => {
17
+ var _a, _b;
18
+ const db = await database();
19
+ const start = utcDayStart(from);
20
+ const end = exclusiveEnd(to);
21
+ const result = await db.execute(sql `
22
+ select count(*)::int as c from (
23
+ select creator_id as profile_id from posts
24
+ where deleted_at is null
25
+ and created_at >= ${start} and created_at < ${end}
26
+ union
27
+ select from_id from reactions
28
+ where created_at >= ${start} and created_at < ${end}
29
+ union
30
+ select from_id from repost
31
+ where created_at >= ${start} and created_at < ${end}
32
+ union
33
+ select from_id from reply_to
34
+ where created_at >= ${start} and created_at < ${end}
35
+ union
36
+ select from_id from bookmarks
37
+ where created_at >= ${start} and created_at < ${end}
38
+ ) active
39
+ `);
40
+ const rows = result.rows;
41
+ return Number((_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.c) !== null && _b !== void 0 ? _b : 0);
42
+ };
12
43
  /** Earliest day with compiled analytics — used to bound the `all` preset. */
13
44
  const earliestAnalyticsDay = async () => {
14
45
  var _a;
@@ -78,12 +109,7 @@ const latestCompiledAt = async (from, to) => {
78
109
  .limit(1);
79
110
  return (_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.compiledAt) !== null && _b !== void 0 ? _b : null;
80
111
  };
81
- const groupVisibility = (body) => {
82
- var _a, _b, _c;
83
- 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')
84
- ? 'public'
85
- : 'private';
86
- };
112
+ const groupVisibility = (body) => isPublicAnalyticsGroup(body) ? 'public' : 'private';
87
113
  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; };
88
114
  const enrichGroupRows = async (rows, from, to) => {
89
115
  if (rows.length === 0)
@@ -380,6 +406,11 @@ const topMembers = async (from, to, limit = 10) => {
380
406
  });
381
407
  });
382
408
  };
409
+ /**
410
+ * Top posts must not expose DM content or private-group posts (snippets +
411
+ * authors). SQL mirrors {@link isAnalyticsTopPostEligible} /
412
+ * {@link isPublicAnalyticsGroup}.
413
+ */
383
414
  const topPostsByViews = async (from, to, limit = 10) => {
384
415
  const db = await database();
385
416
  const rows = await db
@@ -393,9 +424,18 @@ const topPostsByViews = async (from, to, limit = 10) => {
393
424
  profileBody: profiles.body,
394
425
  })
395
426
  .from(analyticsPostViewsDaily)
396
- .leftJoin(posts, sql `${posts.id}::text = ${analyticsPostViewsDaily.postId}`)
427
+ .innerJoin(posts, sql `${posts.id}::text = ${analyticsPostViewsDaily.postId}`)
397
428
  .leftJoin(profiles, sql `${profiles.id}::text = ${posts.creatorId}`)
398
- .where(and(gte(analyticsPostViewsDaily.day, from), lte(analyticsPostViewsDaily.day, to)))
429
+ .where(and(gte(analyticsPostViewsDaily.day, from), lte(analyticsPostViewsDaily.day, to), sql `${posts.visibility} <> 'direct'`, sql `not exists (
430
+ select 1
431
+ from post_groups pg
432
+ inner join groups g on g.id::text = pg.to_id
433
+ where pg.from_id = ${posts.id}::text
434
+ and not coalesce(
435
+ g.body->'capabilities'->'none'->'add' ? 'core-groups-read',
436
+ false
437
+ )
438
+ )`))
399
439
  .groupBy(analyticsPostViewsDaily.postId, posts.body, posts.type, profiles.handle, profiles.body)
400
440
  .orderBy(desc(sum(analyticsPostViewsDaily.uniqueViewers)))
401
441
  .limit(limit);
@@ -411,7 +451,9 @@ const topPostsByViews = async (from, to, limit = 10) => {
411
451
  const profileBody = ((_h = r.profileBody) !== null && _h !== void 0 ? _h : {});
412
452
  return {
413
453
  postId: r.postId,
414
- snippet: content.slice(0, 120) || undefined,
454
+ snippet: typeof content === 'string'
455
+ ? content.slice(0, 120) || undefined
456
+ : undefined,
415
457
  authorHandle: (_j = r.handle) !== null && _j !== void 0 ? _j : undefined,
416
458
  authorDisplayName: (_l = (_k = profileBody.displayName) !== null && _k !== void 0 ? _k : profileBody.name) !== null && _l !== void 0 ? _l : undefined,
417
459
  postType,
@@ -431,7 +473,7 @@ const withCache = async (section, from, to, build) => {
431
473
  };
432
474
  export const getAnalyticsOverview = async (query = {}) => {
433
475
  const range = await resolveQueryRange(query);
434
- return withCache('overview-v5', range.from, range.to, async () => {
476
+ return withCache('overview-v6', range.from, range.to, async () => {
435
477
  var _a, _b;
436
478
  const [activeMembersSeries, postsSeries, likesSeries, commentsSeries, postsByTypeDaily, topGroupRows, groupGrowth, topPostRows, topMemberRows, compiledAt, totalMembers, totalGroups, allTimePosts, prevActive, prevPosts, prevTotalMembers, prevTotalGroups, prevAllTimePosts,] = await Promise.all([
437
479
  loadTotalsSeries(range.from, range.to, 'activeMembers'),
@@ -528,11 +570,17 @@ export const getAnalyticsOverview = async (query = {}) => {
528
570
  };
529
571
  export const getAnalyticsGrowth = async (query = {}) => {
530
572
  const range = await resolveQueryRange(query);
531
- return withCache('growth-v5', range.from, range.to, async () => {
573
+ return withCache('growth-v7', range.from, range.to, async () => {
532
574
  const db = await database();
533
- const [newMembersSeries, prevNew, compiledAt, recentRows] = await Promise.all([
575
+ const mauFrom = rollingMauFrom(range.to);
576
+ const prevMauFrom = rollingMauFrom(range.previousTo);
577
+ const [newMembersSeries, activeMembersSeries, prevNew, prevActiveSeries, mau, prevMau, compiledAt, recentRows,] = await Promise.all([
534
578
  loadTotalsSeries(range.from, range.to, 'newMembers'),
579
+ loadTotalsSeries(range.from, range.to, 'activeMembers'),
535
580
  sumColumn(range.previousFrom, range.previousTo, 'newMembers'),
581
+ loadTotalsSeries(range.previousFrom, range.previousTo, 'activeMembers'),
582
+ countDistinctActives(mauFrom, range.to),
583
+ countDistinctActives(prevMauFrom, range.previousTo),
536
584
  latestCompiledAt(range.from, range.to),
537
585
  db.execute(sql `
538
586
  select p.id, p.handle, p.body, p.created_at,
@@ -540,6 +588,7 @@ export const getAnalyticsGrowth = async (query = {}) => {
540
588
  from profiles p
541
589
  left join invite_link_redeemers r on r.to_id = p.id::text
542
590
  where p.deleted_at is null
591
+ and p.type <> 'guest'
543
592
  and p.created_at >= ${`${range.from}T00:00:00.000Z`}
544
593
  and p.created_at <= ${`${range.to}T23:59:59.999Z`}
545
594
  order by p.created_at desc
@@ -547,6 +596,10 @@ export const getAnalyticsGrowth = async (query = {}) => {
547
596
  `),
548
597
  ]);
549
598
  const newSignups = sumSeries(newMembersSeries);
599
+ const dau = averageSeries(activeMembersSeries);
600
+ const prevDau = averageSeries(prevActiveSeries);
601
+ const dauMau = mau === 0 ? 0 : Math.round((dau / mau) * 1000) / 10;
602
+ const prevDauMau = prevMau === 0 ? 0 : Math.round((prevDau / prevMau) * 1000) / 10;
550
603
  const byDay = new Map(newMembersSeries.map((p) => [p.day, p.value]));
551
604
  const signupsByDay = eachUtcDay(range.from, range.to).map((day) => {
552
605
  var _a;
@@ -569,6 +622,9 @@ export const getAnalyticsGrowth = async (query = {}) => {
569
622
  range: Object.assign(Object.assign({}, range), { compiledAt }),
570
623
  metrics: {
571
624
  newSignups: metricCard('newSignups', newSignups, prevNew, newMembersSeries),
625
+ dau: metricCard('dau', dau, prevDau, activeMembersSeries),
626
+ mau: metricCard('mau', mau, prevMau),
627
+ dauMau: metricCard('dauMau', dauMau, prevDauMau),
572
628
  },
573
629
  signupsByDay,
574
630
  recentSignups,
@@ -577,7 +633,7 @@ export const getAnalyticsGrowth = async (query = {}) => {
577
633
  };
578
634
  export const getAnalyticsEngagement = async (query = {}) => {
579
635
  const range = await resolveQueryRange(query);
580
- return withCache('engagement-v3', range.from, range.to, async () => {
636
+ return withCache('engagement-v4', range.from, range.to, async () => {
581
637
  const [likesSeries, commentsSeries, repostsSeries, bookmarksSeries, dmsSeries, viewersSeries, impressionsSeries, prevLikes, prevComments, prevReposts, prevBookmarks, prevDms, prevViewers, prevImpressions, groups, compiledAt,] = await Promise.all([
582
638
  loadTotalsSeries(range.from, range.to, 'likes'),
583
639
  loadTotalsSeries(range.from, range.to, 'comments'),
@@ -601,9 +657,10 @@ export const getAnalyticsEngagement = async (query = {}) => {
601
657
  const commentsByBucket = aggregateSeriesIntoBuckets(commentsSeries, buckets);
602
658
  const repostsByBucket = aggregateSeriesIntoBuckets(repostsSeries, buckets);
603
659
  const bookmarksByBucket = aggregateSeriesIntoBuckets(bookmarksSeries, buckets);
660
+ const dmsByBucket = aggregateSeriesIntoBuckets(dmsSeries, buckets);
604
661
  const impressionsByPeriod = aggregateSeriesIntoBuckets(impressionsSeries, buckets);
605
662
  const engagementOverTime = buckets.map((bucket, i) => {
606
- var _a, _b, _c, _d, _e, _f, _g, _h;
663
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
607
664
  return ({
608
665
  day: bucket.key,
609
666
  label: bucket.label,
@@ -611,6 +668,7 @@ export const getAnalyticsEngagement = async (query = {}) => {
611
668
  comments: (_d = (_c = commentsByBucket[i]) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : 0,
612
669
  reposts: (_f = (_e = repostsByBucket[i]) === null || _e === void 0 ? void 0 : _e.value) !== null && _f !== void 0 ? _f : 0,
613
670
  bookmarks: (_h = (_g = bookmarksByBucket[i]) === null || _g === void 0 ? void 0 : _g.value) !== null && _h !== void 0 ? _h : 0,
671
+ dms: (_k = (_j = dmsByBucket[i]) === null || _j === void 0 ? void 0 : _j.value) !== null && _k !== void 0 ? _k : 0,
614
672
  });
615
673
  });
616
674
  return {