@openpeepshq/core 0.28.1 → 0.30.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 (41) hide show
  1. package/dist/analytics/compile.js +15 -7
  2. package/dist/analytics/jamMetrics.d.ts +47 -0
  3. package/dist/analytics/jamMetrics.js +93 -0
  4. package/dist/analytics/pdfReport.js +40 -1
  5. package/dist/analytics/read.js +68 -5
  6. package/dist/analytics/report.d.ts +75 -0
  7. package/dist/analytics/report.js +1 -0
  8. package/dist/auditLog/finders.d.ts +27 -0
  9. package/dist/auditLog/finders.js +40 -0
  10. package/dist/auditLog/index.d.ts +3 -0
  11. package/dist/auditLog/index.js +3 -0
  12. package/dist/auditLog/mapping.d.ts +4 -0
  13. package/dist/auditLog/mapping.js +18 -0
  14. package/dist/auditLog/mutations.d.ts +42 -0
  15. package/dist/auditLog/mutations.js +43 -0
  16. package/dist/db/pg/map/registry.js +11 -1
  17. package/dist/db/pg/schema/analytics.d.ts +68 -0
  18. package/dist/db/pg/schema/analytics.js +10 -0
  19. package/dist/db/pg/schema/auditLogs.d.ts +183 -0
  20. package/dist/db/pg/schema/auditLogs.js +30 -0
  21. package/dist/db/pg/schema/documents.d.ts +17 -0
  22. package/dist/db/pg/schema/documents.js +10 -1
  23. package/dist/db/pg/schema/index.d.ts +263 -0
  24. package/dist/db/pg/schema/index.js +3 -0
  25. package/dist/db/pg/sql/0020_add_audit_logs.sql +16 -0
  26. package/dist/db/pg/sql/0021_jam_occurrence_recurrence_id.sql +10 -0
  27. package/dist/db/pg/sql/meta/0020_snapshot.json +4816 -0
  28. package/dist/db/pg/sql/meta/0021_snapshot.json +4718 -0
  29. package/dist/db/pg/sql/meta/0022_snapshot.json +182 -1
  30. package/dist/db/pg/sql/meta/_journal.json +15 -1
  31. package/dist/jams/export.d.ts +17 -4
  32. package/dist/jams/export.js +36 -6
  33. package/dist/jams/finders.js +5 -1
  34. package/dist/jams/index.js +3 -0
  35. package/dist/jams/livekit.d.ts +18 -3
  36. package/dist/jams/livekit.js +37 -5
  37. package/dist/jams/mapping.d.ts +0 -27
  38. package/dist/jams/mapping.js +0 -15
  39. package/dist/jams/token.js +14 -6
  40. package/dist/stats/finders.js +34 -7
  41. package/package.json +4 -4
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "4a5587e2-755d-42e0-a8e0-4940132dbb19",
3
- "prevId": "cbe40fa6-6a27-404d-82fd-48551e54d6d2",
3
+ "prevId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
4
4
  "version": "7",
5
5
  "dialect": "postgresql",
6
6
  "tables": {
@@ -680,6 +680,12 @@
680
680
  "type": "timestamp with time zone",
681
681
  "primaryKey": false,
682
682
  "notNull": false
683
+ },
684
+ "recurrence_id": {
685
+ "name": "recurrence_id",
686
+ "type": "text",
687
+ "primaryKey": false,
688
+ "notNull": false
683
689
  }
684
690
  },
685
691
  "indexes": {
@@ -697,6 +703,27 @@
697
703
  "concurrently": false,
698
704
  "method": "btree",
699
705
  "with": {}
706
+ },
707
+ "jam_events_post_recurrence_idx": {
708
+ "name": "jam_events_post_recurrence_idx",
709
+ "columns": [
710
+ {
711
+ "expression": "post_id",
712
+ "isExpression": false,
713
+ "asc": true,
714
+ "nulls": "last"
715
+ },
716
+ {
717
+ "expression": "recurrence_id",
718
+ "isExpression": false,
719
+ "asc": true,
720
+ "nulls": "last"
721
+ }
722
+ ],
723
+ "isUnique": false,
724
+ "concurrently": false,
725
+ "method": "btree",
726
+ "with": {}
700
727
  }
701
728
  },
702
729
  "foreignKeys": {},
@@ -4340,6 +4367,34 @@
4340
4367
  "primaryKey": false,
4341
4368
  "notNull": true,
4342
4369
  "default": "now()"
4370
+ },
4371
+ "jam_peak_concurrent": {
4372
+ "name": "jam_peak_concurrent",
4373
+ "type": "integer",
4374
+ "primaryKey": false,
4375
+ "notNull": true,
4376
+ "default": "'0'::integer"
4377
+ },
4378
+ "jam_recordings_completed": {
4379
+ "name": "jam_recordings_completed",
4380
+ "type": "integer",
4381
+ "primaryKey": false,
4382
+ "notNull": true,
4383
+ "default": "'0'::integer"
4384
+ },
4385
+ "jam_minutes": {
4386
+ "name": "jam_minutes",
4387
+ "type": "integer",
4388
+ "primaryKey": false,
4389
+ "notNull": true,
4390
+ "default": "'0'::integer"
4391
+ },
4392
+ "jam_unique_attendees": {
4393
+ "name": "jam_unique_attendees",
4394
+ "type": "integer",
4395
+ "primaryKey": false,
4396
+ "notNull": true,
4397
+ "default": "'0'::integer"
4343
4398
  }
4344
4399
  },
4345
4400
  "indexes": {},
@@ -4712,6 +4767,132 @@
4712
4767
  "policies": {},
4713
4768
  "checkConstraints": {},
4714
4769
  "isRLSEnabled": false
4770
+ },
4771
+ "public.audit_logs": {
4772
+ "name": "audit_logs",
4773
+ "schema": "",
4774
+ "columns": {
4775
+ "id": {
4776
+ "name": "id",
4777
+ "type": "uuid",
4778
+ "primaryKey": true,
4779
+ "notNull": true
4780
+ },
4781
+ "actor_profile_id": {
4782
+ "name": "actor_profile_id",
4783
+ "type": "text",
4784
+ "primaryKey": false,
4785
+ "notNull": true
4786
+ },
4787
+ "actor_account_id": {
4788
+ "name": "actor_account_id",
4789
+ "type": "text",
4790
+ "primaryKey": false,
4791
+ "notNull": false
4792
+ },
4793
+ "actor_ip": {
4794
+ "name": "actor_ip",
4795
+ "type": "text",
4796
+ "primaryKey": false,
4797
+ "notNull": false
4798
+ },
4799
+ "action": {
4800
+ "name": "action",
4801
+ "type": "text",
4802
+ "primaryKey": false,
4803
+ "notNull": true
4804
+ },
4805
+ "target_type": {
4806
+ "name": "target_type",
4807
+ "type": "text",
4808
+ "primaryKey": false,
4809
+ "notNull": true
4810
+ },
4811
+ "target_id": {
4812
+ "name": "target_id",
4813
+ "type": "text",
4814
+ "primaryKey": false,
4815
+ "notNull": false
4816
+ },
4817
+ "target_label": {
4818
+ "name": "target_label",
4819
+ "type": "text",
4820
+ "primaryKey": false,
4821
+ "notNull": false
4822
+ },
4823
+ "metadata": {
4824
+ "name": "metadata",
4825
+ "type": "jsonb",
4826
+ "primaryKey": false,
4827
+ "notNull": false
4828
+ },
4829
+ "created_at": {
4830
+ "name": "created_at",
4831
+ "type": "timestamp with time zone",
4832
+ "primaryKey": false,
4833
+ "notNull": true,
4834
+ "default": "now()"
4835
+ }
4836
+ },
4837
+ "indexes": {
4838
+ "audit_logs_created_at_idx": {
4839
+ "name": "audit_logs_created_at_idx",
4840
+ "columns": [
4841
+ {
4842
+ "expression": "created_at",
4843
+ "isExpression": false,
4844
+ "asc": false,
4845
+ "nulls": "last"
4846
+ }
4847
+ ],
4848
+ "isUnique": false,
4849
+ "concurrently": false,
4850
+ "method": "btree",
4851
+ "with": {}
4852
+ },
4853
+ "audit_logs_actor_profile_idx": {
4854
+ "name": "audit_logs_actor_profile_idx",
4855
+ "columns": [
4856
+ {
4857
+ "expression": "actor_profile_id",
4858
+ "isExpression": false,
4859
+ "asc": true,
4860
+ "nulls": "last"
4861
+ }
4862
+ ],
4863
+ "isUnique": false,
4864
+ "concurrently": false,
4865
+ "method": "btree",
4866
+ "with": {}
4867
+ },
4868
+ "audit_logs_target_idx": {
4869
+ "name": "audit_logs_target_idx",
4870
+ "columns": [
4871
+ {
4872
+ "expression": "target_type",
4873
+ "isExpression": false,
4874
+ "asc": true,
4875
+ "nulls": "last"
4876
+ },
4877
+ {
4878
+ "expression": "target_id",
4879
+ "isExpression": false,
4880
+ "asc": true,
4881
+ "nulls": "last"
4882
+ }
4883
+ ],
4884
+ "isUnique": false,
4885
+ "concurrently": false,
4886
+ "method": "btree",
4887
+ "with": {}
4888
+ }
4889
+ },
4890
+ "foreignKeys": {},
4891
+ "compositePrimaryKeys": {},
4892
+ "uniqueConstraints": {},
4893
+ "policies": {},
4894
+ "checkConstraints": {},
4895
+ "isRLSEnabled": false
4715
4896
  }
4716
4897
  },
4717
4898
  "enums": {},
@@ -142,6 +142,20 @@
142
142
  "tag": "0019_posts_published_at",
143
143
  "breakpoints": true
144
144
  },
145
+ {
146
+ "idx": 20,
147
+ "version": "7",
148
+ "when": 1795347885884,
149
+ "tag": "0020_add_audit_logs",
150
+ "breakpoints": true
151
+ },
152
+ {
153
+ "idx": 21,
154
+ "version": "7",
155
+ "when": 1795496571664,
156
+ "tag": "0021_jam_occurrence_recurrence_id",
157
+ "breakpoints": true
158
+ },
145
159
  {
146
160
  "idx": 22,
147
161
  "version": "7",
@@ -150,4 +164,4 @@
150
164
  "breakpoints": true
151
165
  }
152
166
  ]
153
- }
167
+ }
@@ -3,19 +3,32 @@ export type JamAttendanceKind = 'community' | 'public';
3
3
  export type JamAttendanceExportRow = {
4
4
  kind: JamAttendanceKind | '';
5
5
  name: string;
6
- email: string;
7
6
  handle: string;
8
7
  joinedAt: string;
8
+ recurrenceId: string;
9
9
  };
10
- type JoinRecord = {
10
+ export type JoinRecord = {
11
11
  profileId: string;
12
12
  createdAt: string;
13
+ recurrenceId: string | undefined;
13
14
  };
14
- type AttendanceProfile = Pick<Profile, 'type' | 'displayName' | 'handle' | 'guestData'>;
15
- export declare const jamAttendanceExportHeaders: readonly ["Type", "Name", "Email", "Handle", "Joined At"];
15
+ type AttendanceProfile = Pick<Profile, 'type' | 'displayName' | 'handle'>;
16
+ export declare const jamAttendanceExportHeaders: readonly ["Type", "Name", "Handle", "Joined At", "Recurrence Id"];
17
+ /**
18
+ * Build one attendance row from a join event. The export carries no email
19
+ * column at all: community profiles can be controlled by multiple accounts
20
+ * (no single email is representative) and guest emails are personal data
21
+ * that must not leak into an attendance export.
22
+ */
16
23
  export declare const jamAttendanceRowFromJoin: (join: JoinRecord, profile: AttendanceProfile | undefined) => JamAttendanceExportRow;
17
24
  export declare const jamAttendanceExportCsv: (rows: JamAttendanceExportRow[]) => string;
18
25
  /** Profiles that joined the jam room. Recurring jams share one room. */
19
26
  export declare const listJamAttendeeProfileIds: (jamId: string) => Promise<string[]>;
27
+ /**
28
+ * One row per person: keep each profile's first join, in first-join order.
29
+ * Recurring jams share one room, so the same person rejoining a later
30
+ * occurrence must not produce a second row.
31
+ */
32
+ export declare const firstJoinByProfile: (joins: JoinRecord[]) => JoinRecord[];
20
33
  export declare const exportJamAttendanceCsv: (jamId: string) => Promise<string>;
21
34
  export {};
@@ -7,30 +7,42 @@ import { getProfiles } from '../profiles/index.js';
7
7
  export const jamAttendanceExportHeaders = [
8
8
  'Type',
9
9
  'Name',
10
- 'Email',
11
10
  'Handle',
12
11
  'Joined At',
12
+ 'Recurrence Id',
13
13
  ];
14
+ /**
15
+ * Build one attendance row from a join event. The export carries no email
16
+ * column at all: community profiles can be controlled by multiple accounts
17
+ * (no single email is representative) and guest emails are personal data
18
+ * that must not leak into an attendance export.
19
+ */
14
20
  export const jamAttendanceRowFromJoin = (join, profile) => {
15
21
  const isPublic = profile?.type === 'guest';
16
22
  return {
17
23
  kind: profile ? (isPublic ? 'public' : 'community') : '',
18
24
  name: profile?.displayName || (isPublic ? '' : (profile?.handle ?? '')),
19
- // Community emails aren't here: several accounts can control one profile.
20
- email: isPublic ? (profile?.guestData?.email ?? '') : '',
21
25
  handle: isPublic ? '' : (profile?.handle ?? ''),
22
26
  joinedAt: join.createdAt,
27
+ recurrenceId: join.recurrenceId ?? '',
23
28
  };
24
29
  };
25
30
  export const jamAttendanceExportCsv = (rows) => [
26
31
  toCsvRow([...jamAttendanceExportHeaders]),
27
- ...rows.map((row) => toCsvRow([row.kind, row.name, row.email, row.handle, row.joinedAt])),
32
+ ...rows.map((row) => toCsvRow([
33
+ row.kind,
34
+ row.name,
35
+ row.handle,
36
+ row.joinedAt,
37
+ row.recurrenceId,
38
+ ])),
28
39
  ].join('\n');
29
40
  const listJamJoinEvents = async (jamId) => {
30
41
  const db = await database();
31
42
  const rows = await db
32
43
  .select({
33
44
  createdAt: jamEvents.createdAt,
45
+ recurrenceId: jamEvents.recurrenceId,
34
46
  body: jamEvents.body,
35
47
  })
36
48
  .from(jamEvents)
@@ -45,6 +57,7 @@ const listJamJoinEvents = async (jamId) => {
45
57
  {
46
58
  profileId,
47
59
  createdAt: normalizeIsoDatetime(row.createdAt),
60
+ recurrenceId: row.recurrenceId ?? undefined,
48
61
  },
49
62
  ];
50
63
  });
@@ -54,10 +67,27 @@ export const listJamAttendeeProfileIds = async (jamId) => {
54
67
  const joins = await listJamJoinEvents(jamId);
55
68
  return [...new Set(joins.map((join) => join.profileId))];
56
69
  };
70
+ /**
71
+ * One row per person: keep each profile's first join, in first-join order.
72
+ * Recurring jams share one room, so the same person rejoining a later
73
+ * occurrence must not produce a second row.
74
+ */
75
+ export const firstJoinByProfile = (joins) => {
76
+ const seen = new Set();
77
+ const firstJoins = [];
78
+ for (const join of joins) {
79
+ if (!seen.has(join.profileId)) {
80
+ seen.add(join.profileId);
81
+ firstJoins.push(join);
82
+ }
83
+ }
84
+ return firstJoins;
85
+ };
57
86
  export const exportJamAttendanceCsv = async (jamId) => {
58
87
  const joins = await listJamJoinEvents(jamId);
59
- const profileIds = [...new Set(joins.map((join) => join.profileId))];
88
+ const firstJoins = firstJoinByProfile(joins);
89
+ const profileIds = firstJoins.map((join) => join.profileId);
60
90
  const profiles = profileIds.length ? await getProfiles(profileIds) : [];
61
91
  const profilesById = new Map(profiles.map((profile) => [profile.id, profile]));
62
- return jamAttendanceExportCsv(joins.map((join) => jamAttendanceRowFromJoin(join, profilesById.get(join.profileId))));
92
+ return jamAttendanceExportCsv(firstJoins.map((join) => jamAttendanceRowFromJoin(join, profilesById.get(join.profileId))));
63
93
  };
@@ -7,7 +7,11 @@ import { getJamState } from './cache.js';
7
7
  import { transformJamRecordingData } from './helpers.js';
8
8
  export const baseListJam = (props, { start, limit = 100 }) => addStartLimit(jamEventsMapping.filter({ matches: props }), start, limit);
9
9
  export const listJamEvents = (jamId, { start, limit } = {}) => allpeepDb().then(({ db }) => baseListJam({ jamId }, { start, limit }).all(db));
10
- export const listJamStarts = (jamId) => allpeepDb().then(({ db }) => baseListJam({ jamId, type: 'start' }, { limit: 200 }).all(db));
10
+ export const listJamStarts = (jamId) => allpeepDb().then(({ db }) =>
11
+ // baseListJam orders by idDesc — the unique primary key is a total order,
12
+ // so bulk-inserted rows (same createdAt in one transaction) cannot flip
13
+ // order and a downstream start/close pairing stays stable.
14
+ baseListJam({ jamId, type: 'start' }, { limit: 200 }).all(db));
11
15
  export const listAttendance = (jamId, { start, limit } = {}) => allpeepDb().then(({ db }) => baseListJam({ jamId, type: 'join' }, { start, limit }).all(db));
12
16
  export const findJamState = async (jam, hideParticipants, recurrenceId) => {
13
17
  const state = await getJamState(jam, recurrenceId);
@@ -129,6 +129,9 @@ export const closeJam = async (profile, jamEvent, recurrenceId) => {
129
129
  if (rs === undefined) {
130
130
  return undefined;
131
131
  }
132
+ // jamRoomName drops the occurrence (recurring jams share one LiveKit room
133
+ // per event), so stopRecording/stopRtmpStream/deleteRoom resolve the same
134
+ // room as the live jam while this close event keeps its own recurrenceId.
132
135
  await stopRecording(jamEvent, recurrenceId);
133
136
  await stopRtmpStream(jamEvent);
134
137
  return rs
@@ -108,10 +108,25 @@ export declare const stopRecording: (jamPost: PostWithMeta, recurrenceId?: strin
108
108
  post: PostWithMeta;
109
109
  } | undefined>;
110
110
  /**
111
- * Stops leftover egress and deletes an egress-only LiveKit room.
111
+ * Record the best-effort 'close' for a reclaimed (crashed) session so the
112
+ * start…close duration is not left dangling.
113
+ *
114
+ * The room name does not carry the occurrence (`jamRoomName` collapses it), so
115
+ * when the caller has no occurrence it is resolved from the jam's most recent
116
+ * persisted 'start' — the start of the crashed session. `computeJamStats`
117
+ * pairs a close with the start of the same occurrence, so a close written
118
+ * without the occurrence would latch onto the wrong one (or none) for a
119
+ * recurring series.
120
+ */
121
+ export declare const writeReclaimClose: (jam: PostWithMeta, recurrenceId?: string) => Promise<void>;
122
+ /**
123
+ * Stops leftover egress, deletes an egress-only LiveKit room, and emits a
124
+ * 'close' session event so an abandoned session (participants crashed before
125
+ * closeJam ran) still gets a duration in analytics instead of hanging open.
112
126
  * Do not call this for a room with zero participants — that room is still
113
- * inside emptyTimeout or departureTimeout. Safe to call repeatedly.
127
+ * inside emptyTimeout or departureTimeout. Safe to call repeatedly; a session
128
+ * with no matching 'start' simply records no duration.
114
129
  */
115
- export declare const reclaimOrphanJamRoom: (jam: PostWithMeta, roomName?: string) => Promise<void>;
130
+ export declare const reclaimOrphanJamRoom: (jam: PostWithMeta, roomName?: string, recurrenceId?: string) => Promise<void>;
116
131
  export declare const finishRecording: (jamRecording: JamRecordingWithMeta) => Promise<void>;
117
132
  export declare const jamState: (jam: PostWithMeta, hideParticipants?: boolean, recurrenceId?: string) => Promise<JamState>;
@@ -6,7 +6,7 @@ import { allpeepDb } from '../db/index.js';
6
6
  import { serverRootUrl } from '../server/index.js';
7
7
  import { uuidv7 } from 'uuidv7';
8
8
  import { createJamEvent, updateJamRecording } from './mutations.js';
9
- import { findActiveRecording, findActiveRtmpStream } from './finders.js';
9
+ import { findActiveRecording, findActiveRtmpStream, listJamStarts, } from './finders.js';
10
10
  import { cancelRecordingAutoStop, scheduleRecordingAutoStop } from './jobs.js';
11
11
  import { finalizeJamRecording } from './recording.js';
12
12
  import { jamRecordingUploadSecret } from './recordingUploadAuth.js';
@@ -276,11 +276,35 @@ export const stopRecording = async (jamPost, recurrenceId) => {
276
276
  return { ...jamRecording, status: 'finalizing' };
277
277
  };
278
278
  /**
279
- * Stops leftover egress and deletes an egress-only LiveKit room.
279
+ * Record the best-effort 'close' for a reclaimed (crashed) session so the
280
+ * start…close duration is not left dangling.
281
+ *
282
+ * The room name does not carry the occurrence (`jamRoomName` collapses it), so
283
+ * when the caller has no occurrence it is resolved from the jam's most recent
284
+ * persisted 'start' — the start of the crashed session. `computeJamStats`
285
+ * pairs a close with the start of the same occurrence, so a close written
286
+ * without the occurrence would latch onto the wrong one (or none) for a
287
+ * recurring series.
288
+ */
289
+ export const writeReclaimClose = async (jam, recurrenceId) => {
290
+ const closeRecurrenceId = recurrenceId ?? (await listJamStarts(jam.id))[0]?.recurrenceId;
291
+ await createJamEvent({
292
+ id: uuidv7(),
293
+ jamId: jam.id,
294
+ type: 'close',
295
+ profileId: 'system',
296
+ recurrenceId: closeRecurrenceId,
297
+ });
298
+ };
299
+ /**
300
+ * Stops leftover egress, deletes an egress-only LiveKit room, and emits a
301
+ * 'close' session event so an abandoned session (participants crashed before
302
+ * closeJam ran) still gets a duration in analytics instead of hanging open.
280
303
  * Do not call this for a room with zero participants — that room is still
281
- * inside emptyTimeout or departureTimeout. Safe to call repeatedly.
304
+ * inside emptyTimeout or departureTimeout. Safe to call repeatedly; a session
305
+ * with no matching 'start' simply records no duration.
282
306
  */
283
- export const reclaimOrphanJamRoom = async (jam, roomName = jam.id) => {
307
+ export const reclaimOrphanJamRoom = async (jam, roomName = jam.id, recurrenceId) => {
284
308
  try {
285
309
  await stopRecording(jam);
286
310
  }
@@ -300,6 +324,14 @@ export const reclaimOrphanJamRoom = async (jam, roomName = jam.id) => {
300
324
  catch (e) {
301
325
  log.warn(`Failed to delete orphan jam room ${roomName}: ${e.message}`);
302
326
  }
327
+ // Best-effort: a crashed session still records a close so the start…close
328
+ // duration is not left dangling. Never fail the reclaim on this.
329
+ try {
330
+ await writeReclaimClose(jam, recurrenceId);
331
+ }
332
+ catch (e) {
333
+ log.warn(`Failed to record close for reclaimed jam ${jam.id}: ${e.message}`);
334
+ }
303
335
  };
304
336
  export const finishRecording = async (jamRecording) => {
305
337
  const jamEvent = await createJamEvent({
@@ -333,7 +365,7 @@ export const jamState = async (jam, hideParticipants, recurrenceId) => {
333
365
  const identities = await listParticipantIdentities(roomName);
334
366
  const { humans, observers } = splitJamParticipants(identities);
335
367
  if (shouldReclaimJamRoom(room.numParticipants, humans.length)) {
336
- void reclaimOrphanJamRoom(jam, roomName);
368
+ void reclaimOrphanJamRoom(jam, roomName, recurrenceId);
337
369
  return inactive;
338
370
  }
339
371
  return {
@@ -13,33 +13,6 @@ export declare const jamEventsMapping: import("../db/pg/map").Mapping<{
13
13
  reaction?: string | undefined;
14
14
  recurrenceId?: string | undefined;
15
15
  }, JamEvent, JamEvent>;
16
- export declare const jamSessionStartsMapping: import("../db/pg/map").Mapping<{
17
- id: string;
18
- jamId: string;
19
- type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "kicked" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
20
- profileId: string;
21
- content?: string | undefined;
22
- reaction?: string | undefined;
23
- recurrenceId?: string | undefined;
24
- }, JamEvent, JamEvent>;
25
- export declare const jamSessionClosesMapping: import("../db/pg/map").Mapping<{
26
- id: string;
27
- jamId: string;
28
- type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "kicked" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
29
- profileId: string;
30
- content?: string | undefined;
31
- reaction?: string | undefined;
32
- recurrenceId?: string | undefined;
33
- }, JamEvent, JamEvent>;
34
- export declare const jamParticipantsMapping: import("../db/pg/map").Mapping<{
35
- id: string;
36
- jamId: string;
37
- type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "kicked" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
38
- profileId: string;
39
- content?: string | undefined;
40
- reaction?: string | undefined;
41
- recurrenceId?: string | undefined;
42
- }, JamEvent, JamEvent>;
43
16
  export declare const jamRecordingRelation: RelationWithMapping<PostWithMeta, JamRecording>;
44
17
  export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
45
18
  status: "completed" | "failed" | "active" | "requested" | "finalizing";
@@ -3,21 +3,6 @@ import { collectionInfos } from '../db/index.js';
3
3
  export const jamEventsMapping = map({
4
4
  collection: collectionInfos.jamEventsCollection.name,
5
5
  });
6
- export const jamSessionStartsMapping = jamEventsMapping.filter({
7
- matches: {
8
- type: 'start',
9
- },
10
- });
11
- export const jamSessionClosesMapping = jamEventsMapping.filter({
12
- matches: {
13
- type: 'close',
14
- },
15
- });
16
- export const jamParticipantsMapping = jamEventsMapping.filter({
17
- matches: {
18
- type: 'join',
19
- },
20
- });
21
6
  export const jamRecordingRelation = {
22
7
  alias: 'profile',
23
8
  edgeCollection: 'jamRecordings',
@@ -64,6 +64,14 @@ export const createJamToken = async (event, profile, { external = false, recurre
64
64
  const jamId = event.id;
65
65
  const roomName = jamRoomName(event.id, recurrenceId);
66
66
  const jam = event.data?.type === 'event' && event.data?.jam;
67
+ const eventData = event.data?.type === 'event' ? event.data : undefined;
68
+ // Recurring jams resolve the occurrence from the event schedule so a
69
+ // re-opened occurrence is stamped with that occurrence (not whatever the
70
+ // query param carried); one-off jams have no schedule, so the raw param —
71
+ // the room key — stands in.
72
+ const startedOccurrenceId = eventData && eventData.recurrence
73
+ ? occurrenceForJamStart(eventData, { recurrenceId })?.recurrenceId
74
+ : recurrenceId;
67
75
  if (!jam) {
68
76
  throw notFound({ errorKey: 'error.jamNotFound', parameters: { jamId } });
69
77
  }
@@ -111,7 +119,7 @@ export const createJamToken = async (event, profile, { external = false, recurre
111
119
  jamId,
112
120
  type: 'start',
113
121
  profileId: profile.id,
114
- recurrenceId,
122
+ recurrenceId: startedOccurrenceId,
115
123
  });
116
124
  }
117
125
  const { apiKey, apiSecret } = (await config()).jams.livekit;
@@ -136,11 +144,11 @@ export const createJamToken = async (event, profile, { external = false, recurre
136
144
  canUpdateOwnMetadata: true,
137
145
  });
138
146
  if (!jamOpen) {
139
- const eventData = event.data?.type === 'event' ? event.data : undefined;
140
- const startedOccurrenceId = eventData
141
- ? occurrenceForJamStart(eventData, { recurrenceId })?.recurrenceId
142
- : undefined;
143
- hub.emit('jamStarted', profile, event, startedOccurrenceId);
147
+ // The same resolved occurrence the persisted start row carries. The one
148
+ // difference: a one-off jam's raw room key is not an occurrence, so the
149
+ // notification omits it for those (a recurring jam's resolution is the
150
+ // identical value the start event was stamped with).
151
+ hub.emit('jamStarted', profile, event, eventData?.recurrence ? startedOccurrenceId : undefined);
144
152
  }
145
153
  return accessToken.toJwt();
146
154
  };
@@ -1,12 +1,12 @@
1
1
  import { publicProfileWithActivityScoreSchema, publicPostWithActivityScoreSchema, } from '@openpeepshq/common/types';
2
2
  import { sub } from 'date-fns';
3
+ import { sql } from 'drizzle-orm';
3
4
  import { hostResources } from '../server/status.js';
4
5
  import { baseProfilesMapping } from '../profiles/index.js';
5
6
  import { allpeepDb } from '../db/index.js';
6
7
  import { postsMapping, postsWithReplyCountMapping, postsWithReplyToCountMapping, transformPost, } from '../posts/index.js';
7
8
  import { entriesMapping, followsMapping, postsWithActivityScoreMapping, profileWithActivityScoreMapping, repostsMapping, } from './mapping.js';
8
9
  import { compileStatsWithAll, createdAtFilter } from './helpers.js';
9
- import { jamParticipantsMapping, jamSessionStartsMapping, } from '../jams/mapping.js';
10
10
  import { edgeFilters, postFilters, profileFilters } from '../db/pg/filters/index.js';
11
11
  import { sorts } from '../db/pg/queries/index.js';
12
12
  import { entries, follows, repost } from '../db/pg/schema/edges.js';
@@ -69,13 +69,40 @@ export const serverCounts = async () => allpeepDb().then(async ({ db }) => {
69
69
  rsvps,
70
70
  };
71
71
  });
72
- const jamSessionStarts = (db, start, end) => jamSessionStartsMapping
73
- .filter(createdAtFilter(jamEvents, start, end))
74
- .count(db);
72
+ // Distinct (post, occurrence): a recurring series counts N sessions, not 1.
73
+ // The time bounds come from the shared createdAtFilter so day/week/month
74
+ // windows behave like every other stat.
75
+ const jamSessionStarts = (db, start, end) => {
76
+ const bounds = createdAtFilter(jamEvents, start, end);
77
+ return db
78
+ .select({
79
+ value: sql `count(distinct (post_id, coalesce(recurrence_id, '')))::int`,
80
+ })
81
+ .from(jamEvents)
82
+ .where(bounds
83
+ ? sql `deleted_at is null and body->>'type' = 'start' and ${bounds.where}`
84
+ : sql `deleted_at is null and body->>'type' = 'start'`)
85
+ .then((rows) => Number(rows[0]?.value ?? 0));
86
+ };
75
87
  export const jamSessionsStats = () => compileStatsWithAll(jamSessionStarts);
76
- const jamParticipants = (db, start, end) => jamParticipantsMapping
77
- .filter(createdAtFilter(jamEvents, start, end))
78
- .count(db);
88
+ // Distinct profiles who joined: reconnects/tabs no longer inflate the count.
89
+ // Joins profiles to count only live local profiles — guests and deleted
90
+ // profiles are excluded, matching the analytics dashboard's computeJamStats
91
+ // so both admin surfaces show the same number for the same window.
92
+ const jamParticipants = (db, start, end) => {
93
+ const bounds = createdAtFilter(jamEvents, start, end);
94
+ const scope = sql `jam_events.deleted_at is null
95
+ and jam_events.body->>'type' = 'join'
96
+ and profiles.type = 'local' and profiles.deleted_at is null`;
97
+ return db
98
+ .select({
99
+ value: sql `count(distinct jam_events.body->>'profileId')::int`,
100
+ })
101
+ .from(jamEvents)
102
+ .innerJoin(profiles, sql `${profiles.id}::text = ${jamEvents.body}->>'profileId'`)
103
+ .where(bounds ? sql `${scope} and ${bounds.where}` : scope)
104
+ .then((rows) => Number(rows[0]?.value ?? 0));
105
+ };
79
106
  export const jamParticipantsStats = () => compileStatsWithAll(jamParticipants);
80
107
  const topPosts = (db, start) => postsWithActivityScoreMapping
81
108
  .filter(createdAtFilter(posts, start))