@openpeepshq/core 0.2.0 → 0.2.2

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 (74) hide show
  1. package/LICENSE +674 -0
  2. package/dist/accounts/mutations.js +9 -0
  3. package/dist/analytics/cache.js +1 -1
  4. package/dist/config/index.d.ts +3 -336
  5. package/dist/db/explorer/index.d.ts +1 -1
  6. package/dist/db/explorer/index.js +1 -1
  7. package/dist/db/index.d.ts +1 -1
  8. package/dist/db/index.js +1 -1
  9. package/dist/db/pg/map/registry.js +3 -2
  10. package/dist/federation/actors.d.ts +32 -0
  11. package/dist/federation/actors.js +136 -0
  12. package/dist/federation/identity.d.ts +11 -0
  13. package/dist/federation/identity.js +11 -0
  14. package/dist/federation/index.d.ts +8 -1
  15. package/dist/federation/index.js +5 -1
  16. package/dist/federation/ingest.d.ts +9 -0
  17. package/dist/federation/ingest.js +60 -0
  18. package/dist/federation/notes.d.ts +8 -0
  19. package/dist/federation/notes.js +30 -0
  20. package/dist/federation/peers.d.ts +3 -0
  21. package/dist/federation/peers.js +24 -0
  22. package/dist/jams/export.d.ts +2 -0
  23. package/dist/jams/export.js +5 -0
  24. package/dist/jams/finders.d.ts +1 -0
  25. package/dist/jams/finders.js +1 -0
  26. package/dist/jams/health.d.ts +23 -0
  27. package/dist/jams/health.js +79 -7
  28. package/dist/jams/index.d.ts +1 -1
  29. package/dist/jams/index.js +10 -3
  30. package/dist/jams/token.js +6 -2
  31. package/dist/jams/waitingRoom.js +3 -1
  32. package/dist/media/garbageCollection.d.ts +109 -0
  33. package/dist/media/garbageCollection.js +603 -0
  34. package/dist/media/garbageCollectionJobs.d.ts +14 -0
  35. package/dist/media/garbageCollectionJobs.js +55 -0
  36. package/dist/media/index.d.ts +10 -0
  37. package/dist/media/index.js +39 -15
  38. package/dist/media/streaming.d.ts +2 -0
  39. package/dist/media/streaming.js +8 -0
  40. package/dist/notifications/defaultNotifications/index.js +2 -0
  41. package/dist/notifications/defaultNotifications/jamStarted/index.d.ts +1 -0
  42. package/dist/notifications/defaultNotifications/jamStarted/index.js +61 -13
  43. package/dist/notifications/defaultNotifications/waitlistOffer/index.d.ts +24 -0
  44. package/dist/notifications/defaultNotifications/waitlistOffer/index.js +40 -0
  45. package/dist/notifications/index.d.ts +1 -1
  46. package/dist/notifications/index.js +1 -1
  47. package/dist/plugins/pluginAuth.js +1 -0
  48. package/dist/posts/conversationQueries.d.ts +31 -0
  49. package/dist/posts/conversationQueries.js +150 -24
  50. package/dist/posts/finders.d.ts +9 -0
  51. package/dist/posts/finders.js +23 -3
  52. package/dist/posts/helpers/index.d.ts +10 -2
  53. package/dist/posts/helpers/index.js +6 -0
  54. package/dist/posts/index.d.ts +3 -1
  55. package/dist/posts/index.js +3 -1
  56. package/dist/posts/mapping.d.ts +14 -0
  57. package/dist/posts/mutations.d.ts +13 -6
  58. package/dist/posts/mutations.js +271 -72
  59. package/dist/posts/rsvpExport.d.ts +47 -0
  60. package/dist/posts/rsvpExport.js +178 -0
  61. package/dist/posts/unseenCounts.d.ts +6 -0
  62. package/dist/posts/unseenCounts.js +51 -1
  63. package/dist/posts/waitlist.d.ts +13 -0
  64. package/dist/posts/waitlist.js +75 -0
  65. package/dist/posts/waitlistOfferJobs.d.ts +10 -0
  66. package/dist/posts/waitlistOfferJobs.js +91 -0
  67. package/dist/profiles/index.js +6 -1
  68. package/dist/profiles/mutations.js +6 -3
  69. package/dist/reports/mapping.d.ts +1 -1
  70. package/dist/server/index.d.ts +1 -0
  71. package/dist/stats/mapping.d.ts +1 -0
  72. package/dist/stripe/connection.js +1 -1
  73. package/dist/stripe/helpers.js +7 -3
  74. package/package.json +11 -10
@@ -0,0 +1,9 @@
1
+ import type { Profile } from '@openpeepshq/common/types';
2
+ export declare const ingestIncomingFollow: (follower: Profile, followed: Profile, activityUri: string) => Promise<void>;
3
+ export declare const ingestIncomingUnfollow: (follower: Profile, followed: Profile, activityUri: string) => Promise<void>;
4
+ export type FollowerRecipient = {
5
+ uri: string;
6
+ inboxUrl: string;
7
+ sharedInboxUrl: string | null;
8
+ };
9
+ export declare const listFederatedFollowerRecipients: (followedId: string) => Promise<FollowerRecipient[]>;
@@ -0,0 +1,60 @@
1
+ import { and, eq, isNull, sql } from 'drizzle-orm';
2
+ import { pgDb } from '../db/pg/client.js';
3
+ import { follows } from '../db/pg/schema/edges.js';
4
+ import { profiles } from '../db/pg/schema/documents.js';
5
+ import { follow, unfollow } from '../profiles/mutations.js';
6
+ import { follows as hasFollow } from '../profiles/finders.js';
7
+ import { recordApActivity } from './activities.js';
8
+ export const ingestIncomingFollow = async (follower, followed, activityUri) => {
9
+ if (!(await hasFollow(follower, followed))) {
10
+ await follow(follower, followed, {
11
+ uri: activityUri,
12
+ reblogs: true,
13
+ notify: true,
14
+ });
15
+ }
16
+ await recordApActivity({
17
+ uri: activityUri,
18
+ type: 'Follow',
19
+ actorUri: followerUri(follower),
20
+ objectUri: followerUri(followed),
21
+ direction: 'in',
22
+ });
23
+ };
24
+ export const ingestIncomingUnfollow = async (follower, followed, activityUri) => {
25
+ if (await hasFollow(follower, followed)) {
26
+ await unfollow(follower, followed);
27
+ }
28
+ await recordApActivity({
29
+ uri: activityUri,
30
+ type: 'Undo',
31
+ actorUri: followerUri(follower),
32
+ objectUri: followerUri(followed),
33
+ direction: 'in',
34
+ });
35
+ };
36
+ const followerUri = (profile) => {
37
+ const uri = profile.uri;
38
+ return uri ?? `profile:${profile.id}`;
39
+ };
40
+ export const listFederatedFollowerRecipients = async (followedId) => {
41
+ const db = pgDb();
42
+ const rows = await db
43
+ .select({
44
+ uri: profiles.uri,
45
+ inboxUrl: profiles.inboxUrl,
46
+ sharedInboxUrl: profiles.sharedInboxUrl,
47
+ })
48
+ .from(follows)
49
+ .innerJoin(profiles, sql `${follows.fromId} = ${profiles.id}::text`)
50
+ .where(and(eq(follows.toId, followedId), eq(profiles.type, 'federated'), isNull(profiles.deletedAt)));
51
+ return rows.flatMap((row) => row.uri && row.inboxUrl
52
+ ? [
53
+ {
54
+ uri: row.uri,
55
+ inboxUrl: row.inboxUrl,
56
+ sharedInboxUrl: row.sharedInboxUrl,
57
+ },
58
+ ]
59
+ : []);
60
+ };
@@ -0,0 +1,8 @@
1
+ export type PublicNote = {
2
+ id: string;
3
+ creatorId: string;
4
+ content: string;
5
+ published: string;
6
+ inReplyToUri: string | null;
7
+ };
8
+ export declare const loadPublicNote: (postId: string) => Promise<PublicNote | null>;
@@ -0,0 +1,30 @@
1
+ import { and, eq, isNull } from 'drizzle-orm';
2
+ import { pgDb } from '../db/pg/client.js';
3
+ import { posts } from '../db/pg/schema/documents.js';
4
+ export const loadPublicNote = async (postId) => {
5
+ const db = pgDb();
6
+ const [row] = await db
7
+ .select({
8
+ id: posts.id,
9
+ type: posts.type,
10
+ visibility: posts.visibility,
11
+ creatorId: posts.creatorId,
12
+ body: posts.body,
13
+ inReplyToUri: posts.inReplyToUri,
14
+ createdAt: posts.createdAt,
15
+ deletedAt: posts.deletedAt,
16
+ })
17
+ .from(posts)
18
+ .where(and(eq(posts.id, postId), isNull(posts.deletedAt)))
19
+ .limit(1);
20
+ if (!row || row.type !== 'note' || row.visibility !== 'public')
21
+ return null;
22
+ const body = (row.body ?? {});
23
+ return {
24
+ id: row.id,
25
+ creatorId: row.creatorId,
26
+ content: body.content ?? '',
27
+ published: row.createdAt,
28
+ inReplyToUri: row.inReplyToUri,
29
+ };
30
+ };
@@ -0,0 +1,3 @@
1
+ export declare const hostnameOf: (value: string | URL) => string | null;
2
+ export declare const peerHostAllowed: (value: string | URL | null | undefined) => Promise<boolean>;
3
+ export declare const federationIsActive: () => Promise<boolean>;
@@ -0,0 +1,24 @@
1
+ import { hostIsAllowed } from '@openpeepshq/common/lib';
2
+ import { config } from '../config/index.js';
3
+ export const hostnameOf = (value) => {
4
+ try {
5
+ const host = new URL(value).hostname
6
+ .trim()
7
+ .toLowerCase()
8
+ .replace(/\.$/, '');
9
+ return host || null;
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ };
15
+ export const peerHostAllowed = async (value) => {
16
+ if (value == null)
17
+ return false;
18
+ const host = hostnameOf(value);
19
+ if (!host)
20
+ return false;
21
+ const cfg = await config();
22
+ return hostIsAllowed(host, cfg.federation.allowedHosts);
23
+ };
24
+ export const federationIsActive = async () => (await config()).federation.active;
@@ -15,5 +15,7 @@ type AttendanceProfile = Pick<Profile, 'type' | 'displayName' | 'handle' | 'gues
15
15
  export declare const jamAttendanceExportHeaders: readonly ["Type", "Name", "Email", "Handle", "Joined At"];
16
16
  export declare const jamAttendanceRowFromJoin: (join: JoinRecord, profile: AttendanceProfile | undefined) => JamAttendanceExportRow;
17
17
  export declare const jamAttendanceExportCsv: (rows: JamAttendanceExportRow[]) => string;
18
+ /** Profiles that joined the jam room. Recurring jams share one room. */
19
+ export declare const listJamAttendeeProfileIds: (jamId: string) => Promise<string[]>;
18
20
  export declare const exportJamAttendanceCsv: (jamId: string) => Promise<string>;
19
21
  export {};
@@ -49,6 +49,11 @@ const listJamJoinEvents = async (jamId) => {
49
49
  ];
50
50
  });
51
51
  };
52
+ /** Profiles that joined the jam room. Recurring jams share one room. */
53
+ export const listJamAttendeeProfileIds = async (jamId) => {
54
+ const joins = await listJamJoinEvents(jamId);
55
+ return [...new Set(joins.map((join) => join.profileId))];
56
+ };
52
57
  export const exportJamAttendanceCsv = async (jamId) => {
53
58
  const joins = await listJamJoinEvents(jamId);
54
59
  const profileIds = [...new Set(joins.map((join) => join.profileId))];
@@ -10,6 +10,7 @@ export declare const listJamEvents: (jamId: string, { start, limit }?: {
10
10
  start?: string;
11
11
  limit?: number;
12
12
  }) => Promise<import("../db/pg/map").WithId<JamEvent>[]>;
13
+ export declare const listJamStarts: (jamId: string) => Promise<import("../db/pg/map").WithId<JamEvent>[]>;
13
14
  export declare const listAttendance: (jamId: string, { start, limit }?: {
14
15
  start?: string;
15
16
  limit?: number;
@@ -7,6 +7,7 @@ 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
11
  export const listAttendance = (jamId, { start, limit } = {}) => allpeepDb().then(({ db }) => baseListJam({ jamId, type: 'join' }, { start, limit }).all(db));
11
12
  export const findJamState = async (jam, hideParticipants, recurrenceId) => {
12
13
  const state = await getJamState(jam, recurrenceId);
@@ -1,10 +1,33 @@
1
+ import { type LivekitDiagnosis } from '@openpeepshq/common/types';
1
2
  export declare const LIVEKIT_HEALTH_TIMEOUT_MS = 5000;
2
3
  export declare const LIVEKIT_HEALTH_MAX_ATTEMPTS = 3;
4
+ /** Drop credential material if a client library echoes it in an error. */
5
+ export declare const redactSecrets: (message: string, secrets: Array<string | undefined>) => string;
6
+ export type LivekitProbeResult = {
7
+ ok: boolean;
8
+ error?: string;
9
+ };
3
10
  /**
4
11
  * True when a LiveKit RoomService call succeeds within maxAttempts. Retries so a
5
12
  * single transient failure does not disable jams for a full /server/info bucket.
6
13
  * Credentials in config are not enough — invalid keys fail on first RPC.
7
14
  */
15
+ export declare const probeLivekitConnectionResult: (listRooms: () => Promise<unknown>, timeoutMs?: number, maxAttempts?: number) => Promise<LivekitProbeResult>;
8
16
  export declare const probeLivekitConnection: (listRooms: () => Promise<unknown>, timeoutMs?: number, maxAttempts?: number) => Promise<boolean>;
9
17
  /** Cached LiveKit reachability. False when unset, unauthorized, or unreachable. */
10
18
  export declare const isLivekitConnected: () => Promise<boolean>;
19
+ export type LivekitDiagnosisInput = {
20
+ url?: string;
21
+ hasApiKey: boolean;
22
+ hasApiSecret: boolean;
23
+ recordingEnabled: boolean;
24
+ reachable: boolean;
25
+ error?: string;
26
+ };
27
+ /** Checklist the admin diagnosis page renders. Secrets never leave this shape. */
28
+ export declare const buildLivekitDiagnosis: (input: LivekitDiagnosisInput) => LivekitDiagnosis;
29
+ /**
30
+ * Fresh LiveKit check for admins. Bypasses the short health cache so Refresh
31
+ * reports the current credentials and the last probe error.
32
+ */
33
+ export declare const diagnoseLivekit: () => Promise<LivekitDiagnosis>;
@@ -1,4 +1,6 @@
1
1
  import { createCache } from 'cache-manager';
2
+ import { livekitDiagnosisSchema, } from '@openpeepshq/common/types';
3
+ import { config } from '../config/index.js';
2
4
  import { logger } from '../log/index.js';
3
5
  import { roomService } from './livekit.js';
4
6
  const log = logger('app:jams:livekit');
@@ -23,28 +25,98 @@ const withTimeout = (promise, timeoutMs) => new Promise((resolve, reject) => {
23
25
  reject(err);
24
26
  });
25
27
  });
28
+ const errorMessage = (e) => e instanceof Error && e.message ? e.message : 'LiveKit health check failed';
29
+ /** Drop credential material if a client library echoes it in an error. */
30
+ export const redactSecrets = (message, secrets) => secrets.reduce((text, secret) => {
31
+ if (!secret || secret.length < 8)
32
+ return text;
33
+ return text.split(secret).join('[redacted]');
34
+ }, message);
26
35
  /**
27
36
  * True when a LiveKit RoomService call succeeds within maxAttempts. Retries so a
28
37
  * single transient failure does not disable jams for a full /server/info bucket.
29
38
  * Credentials in config are not enough — invalid keys fail on first RPC.
30
39
  */
31
- export const probeLivekitConnection = async (listRooms, timeoutMs = LIVEKIT_HEALTH_TIMEOUT_MS, maxAttempts = LIVEKIT_HEALTH_MAX_ATTEMPTS) => {
40
+ export const probeLivekitConnectionResult = async (listRooms, timeoutMs = LIVEKIT_HEALTH_TIMEOUT_MS, maxAttempts = LIVEKIT_HEALTH_MAX_ATTEMPTS) => {
41
+ let lastError = 'LiveKit health check failed';
32
42
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
33
43
  try {
34
44
  await withTimeout(listRooms(), timeoutMs);
35
- return true;
45
+ return { ok: true };
36
46
  }
37
47
  catch (e) {
38
- log.warn(`LiveKit health check failed (attempt ${attempt}/${maxAttempts}): ${e.message}`);
48
+ lastError = errorMessage(e);
49
+ log.warn(`LiveKit health check failed (attempt ${attempt}/${maxAttempts}): ${lastError}`);
39
50
  }
40
51
  }
41
- return false;
52
+ return { ok: false, error: lastError };
42
53
  };
54
+ export const probeLivekitConnection = async (listRooms, timeoutMs = LIVEKIT_HEALTH_TIMEOUT_MS, maxAttempts = LIVEKIT_HEALTH_MAX_ATTEMPTS) => (await probeLivekitConnectionResult(listRooms, timeoutMs, maxAttempts)).ok;
43
55
  /** Cached LiveKit reachability. False when unset, unauthorized, or unreachable. */
44
56
  export const isLivekitConnected = () => livekitHealthCache.wrap(LIVEKIT_HEALTH_CACHE_KEY, async () => {
45
- const rs = await roomService();
46
- if (rs === undefined) {
57
+ try {
58
+ const rs = await roomService();
59
+ if (rs === undefined) {
60
+ return false;
61
+ }
62
+ return probeLivekitConnection(() => rs.listRooms([LIVEKIT_HEALTH_ROOM]));
63
+ }
64
+ catch (e) {
65
+ log.warn(`LiveKit health check failed: ${errorMessage(e)}`);
47
66
  return false;
48
67
  }
49
- return probeLivekitConnection(() => rs.listRooms([LIVEKIT_HEALTH_ROOM]));
50
68
  });
69
+ /** Checklist the admin diagnosis page renders. Secrets never leave this shape. */
70
+ export const buildLivekitDiagnosis = (input) => {
71
+ const configured = Boolean(input.url) && input.hasApiKey && input.hasApiSecret;
72
+ return {
73
+ connected: configured && input.reachable,
74
+ recordingEnabled: input.recordingEnabled,
75
+ ...(input.url ? { url: input.url } : {}),
76
+ ...(configured && !input.reachable && input.error
77
+ ? { error: input.error }
78
+ : {}),
79
+ checks: [
80
+ { id: 'url', ok: Boolean(input.url) },
81
+ { id: 'apiKey', ok: input.hasApiKey },
82
+ { id: 'apiSecret', ok: input.hasApiSecret },
83
+ { id: 'reachable', ok: configured && input.reachable },
84
+ ],
85
+ };
86
+ };
87
+ /**
88
+ * Fresh LiveKit check for admins. Bypasses the short health cache so Refresh
89
+ * reports the current credentials and the last probe error.
90
+ */
91
+ export const diagnoseLivekit = async () => {
92
+ const { url, apiKey, apiSecret, recordingEnabled } = (await config()).jams
93
+ .livekit;
94
+ const base = {
95
+ url,
96
+ hasApiKey: Boolean(apiKey),
97
+ hasApiSecret: Boolean(apiSecret),
98
+ recordingEnabled: !!recordingEnabled,
99
+ };
100
+ // Only probe when all credentials are present: a partial config can't tell
101
+ // "missing secret" apart from "auth rejected" and would surface errors that
102
+ // don't reflect the real problem.
103
+ let reachable = false;
104
+ let error;
105
+ if (url && apiKey && apiSecret) {
106
+ try {
107
+ const rs = await roomService();
108
+ if (rs) {
109
+ const probe = await probeLivekitConnectionResult(() => rs.listRooms([LIVEKIT_HEALTH_ROOM]));
110
+ reachable = probe.ok;
111
+ error = probe.error
112
+ ? redactSecrets(probe.error, [apiKey, apiSecret])
113
+ : undefined;
114
+ }
115
+ }
116
+ catch (e) {
117
+ error = redactSecrets(errorMessage(e), [apiKey, apiSecret]);
118
+ log.warn(`LiveKit diagnosis failed: ${error}`);
119
+ }
120
+ }
121
+ return livekitDiagnosisSchema.parse(buildLivekitDiagnosis({ ...base, reachable, error }));
122
+ };
@@ -1,6 +1,6 @@
1
1
  import { type AuthorizationData, type MuteParticipantRequest, type PostWithMeta, type Profile } from '@openpeepshq/common/types';
2
2
  export { createJamToken, createJamEgressToken } from './token';
3
- export { isLivekitConnected } from './health';
3
+ export { diagnoseLivekit, isLivekitConnected } from './health';
4
4
  export { startRecording, stopRecording, startRtmpStream, stopRtmpStream, stopEgress, listParticipantIds, reclaimOrphanJamRoom, finishRecording, getJamRecordingUrl, getJamObserverPath, JAM_ROOM_EMPTY_TIMEOUT_SEC, JAM_ROOM_DEPARTURE_TIMEOUT_SEC, } from './livekit';
5
5
  export { rtmpStreamOutput } from './rtmp';
6
6
  export { jamRecordingStopQueue, jamRecordingStopWorker, scheduleRecordingAutoStop, cancelRecordingAutoStop, JAM_RECORDING_MAX_DURATION_MS, } from './jobs';
@@ -10,7 +10,7 @@ import { canReadPost } from '../posts/helpers/index.js';
10
10
  import { capabilitiesConfig } from '../config/index.js';
11
11
  import { logger } from '../log/index.js';
12
12
  export { createJamToken, createJamEgressToken } from './token.js';
13
- export { isLivekitConnected } from './health.js';
13
+ export { diagnoseLivekit, isLivekitConnected } from './health.js';
14
14
  export { startRecording, stopRecording, startRtmpStream, stopRtmpStream, stopEgress, listParticipantIds, reclaimOrphanJamRoom, finishRecording, getJamRecordingUrl, getJamObserverPath, JAM_ROOM_EMPTY_TIMEOUT_SEC, JAM_ROOM_DEPARTURE_TIMEOUT_SEC, } from './livekit.js';
15
15
  export { rtmpStreamOutput } from './rtmp.js';
16
16
  export { jamRecordingStopQueue, jamRecordingStopWorker, scheduleRecordingAutoStop, cancelRecordingAutoStop, JAM_RECORDING_MAX_DURATION_MS, } from './jobs.js';
@@ -35,7 +35,14 @@ const reclaimLocalOrphan = (post) => {
35
35
  * Auth filtering happens in {@link listLiveJams} so the cache is not per-user.
36
36
  */
37
37
  const fetchLiveJamPosts = async () => {
38
- const rs = await roomService();
38
+ let rs;
39
+ try {
40
+ rs = await roomService();
41
+ }
42
+ catch (e) {
43
+ log.warn(`Failed to reach LiveKit (${e.message}). Admins can diagnose this at /admin/diagnostics/livekit.`);
44
+ return [];
45
+ }
39
46
  if (rs === undefined) {
40
47
  return [];
41
48
  }
@@ -48,7 +55,7 @@ const fetchLiveJamPosts = async () => {
48
55
  ]);
49
56
  }
50
57
  catch (e) {
51
- log.warn(`Failed to list live jam rooms: ${e.message}`);
58
+ log.warn(`Failed to list live jam rooms (${e.message}). Admins can diagnose this at /admin/diagnostics/livekit.`);
52
59
  return [];
53
60
  }
54
61
  const posts = await Promise.all(rooms.map(async (room) => {
@@ -1,5 +1,5 @@
1
1
  import { publicProfileSchema, } from '@openpeepshq/common/types';
2
- import { canModerateJam, countYesRsvps, getEffectiveRsvp, isBlockedPair, jamRoomName, } from '@openpeepshq/common/lib';
2
+ import { canModerateJam, countYesRsvps, getEffectiveRsvp, isBlockedPair, jamRoomName, occurrenceForJamStart, } from '@openpeepshq/common/lib';
3
3
  import { authNeeded, forbidden, notFound } from '../errors/index.js';
4
4
  import { config } from '../config/index.js';
5
5
  import { AccessToken, TrackSource } from 'livekit-server-sdk';
@@ -133,7 +133,11 @@ export const createJamToken = async (event, profile, { external = false, recurre
133
133
  canUpdateOwnMetadata: true,
134
134
  });
135
135
  if (!jamOpen) {
136
- hub.emit('jamStarted', profile, event);
136
+ const eventData = event.data?.type === 'event' ? event.data : undefined;
137
+ const startedOccurrenceId = eventData
138
+ ? occurrenceForJamStart(eventData, { recurrenceId })?.recurrenceId
139
+ : undefined;
140
+ hub.emit('jamStarted', profile, event, startedOccurrenceId);
137
141
  }
138
142
  return accessToken.toJwt();
139
143
  };
@@ -12,7 +12,9 @@ const currentWaitingRoom = (event, recurrenceId) => getSharedConnection()
12
12
  .then((entries) => entries.filter((e) => e[0] && e[1]))
13
13
  .then((entries) => entries.map(([key, value]) => [
14
14
  key,
15
- publicProfileSchema.partial().parse(JSON.parse(value)),
15
+ publicProfileSchema
16
+ .partial()
17
+ .parse(JSON.parse(value)),
16
18
  ]))
17
19
  .then((entries) => Object.fromEntries(entries));
18
20
  const currentAdmittance = (event, recurrenceId) => getSharedConnection().then((conn) => conn.hGetAll(admittanceKey(event, recurrenceId)));
@@ -0,0 +1,109 @@
1
+ import type { StoredMediaFile, StoredMediaStatus } from '@openpeepshq/common/types';
2
+ /**
3
+ * How long a file must stay unreferenced before it is deleted. The clock
4
+ * starts the first time a collection run sees the file with no live link, so
5
+ * the run that ships this job only records files — it does not delete them.
6
+ * In-progress uploads (stored, not yet saved onto a post or recording) survive
7
+ * the same window.
8
+ */
9
+ export declare const MEDIA_GC_GRACE_MS: number;
10
+ /** Type alias for the stream-active check, overridable in tests. */
11
+ export type StreamActiveChecker = (storageId: string, now: number) => Promise<boolean>;
12
+ /** SHA-256 digest, base64url, no padding. */
13
+ export declare const STORAGE_ID_LENGTH = 43;
14
+ /**
15
+ * POSIX regex (no lookahead) shared with the SQL scan. Matches
16
+ * `/storage/allpeep/<id>/<file>` and `/media/streaming/<id>/...`.
17
+ */
18
+ export declare const STORAGE_URL_SOURCE = "/(?:allpeep|media/streaming)/([A-Za-z0-9_-]{43})(?:[^A-Za-z0-9_-]|$)";
19
+ /**
20
+ * Live content that can embed a media URL. The scan also covers every other
21
+ * public jsonb column, so a new page or plugin table is included without a
22
+ * code change. These are the ones GC refuses to run without.
23
+ */
24
+ export declare const REFERENCE_TABLES: readonly ["posts", "profiles", "groups", "configs", "jam_recordings"];
25
+ /**
26
+ * Rows that store a media URL but are not a live link:
27
+ * - `media_attachments` is the upload registry. It keeps a copy of every file
28
+ * URL, including files whose post or recording is already gone.
29
+ * - `entries` snapshots the post at create and edit time. After the post is
30
+ * deleted those snapshots are the only remaining copy, so counting them
31
+ * would keep the file forever. The rendered post is the post row itself.
32
+ */
33
+ export declare const EXCLUDED_REFERENCE_TABLES: readonly ["media_attachments", "entries"];
34
+ export declare const isStorageId: (value: string) => boolean;
35
+ /** Quick existence check for the stored source file (without the HLS dir). */
36
+ export declare const mediaFileExists: (storageId: string) => Promise<boolean>;
37
+ export declare const quoteIdent: (name: string) => string;
38
+ export declare const extractStorageIds: (text: string) => string[];
39
+ export interface JsonbColumn {
40
+ tableName: string;
41
+ columnName: string;
42
+ }
43
+ export declare const buildReferenceScanSql: (columns: JsonbColumn[], tablesWithDeletedAt: ReadonlySet<string>) => string | null;
44
+ export interface SqlExecutor {
45
+ execute: (query: string) => Promise<{
46
+ rows: Record<string, unknown>[];
47
+ }>;
48
+ }
49
+ export declare const loadReferencedStorageIds: (executor: SqlExecutor) => Promise<Set<string>>;
50
+ export interface AttachmentBody {
51
+ id: string;
52
+ body: string;
53
+ }
54
+ /**
55
+ * Attachment rows whose local files are all gone. Rows that still point at a
56
+ * file on disk (referenced, or inside the grace window) stay so an in-progress
57
+ * upload can finish.
58
+ */
59
+ export declare const danglingMediaAttachmentIds: (rows: AttachmentBody[], filesOnDisk: ReadonlySet<string>) => string[];
60
+ export interface SweepOptions {
61
+ filesDir: string;
62
+ hlsRoot: string;
63
+ statePath: string;
64
+ referencedIds: ReadonlySet<string>;
65
+ now?: number;
66
+ graceMs?: number;
67
+ /** Override the recent-access check (default: Redis-backed). */
68
+ streamActiveChecker?: StreamActiveChecker;
69
+ }
70
+ export interface SweepResult {
71
+ deleted: string[];
72
+ marked: number;
73
+ kept: number;
74
+ skipped: string[];
75
+ remainingIds: string[];
76
+ tempDeleted: number;
77
+ storageMissing: boolean;
78
+ }
79
+ /**
80
+ * Delete stored files with no live reference, once they have stayed that way
81
+ * for the grace period. Also drops HLS directories for those files, stale
82
+ * upload temps, and HLS directories whose source file is already gone.
83
+ */
84
+ export declare const sweepUnreferencedMedia: (options: SweepOptions) => Promise<SweepResult>;
85
+ export declare const deleteMediaAttachmentRows: (ids: string[]) => Promise<number>;
86
+ export interface MediaGarbageCollectionResult extends SweepResult {
87
+ referenced: number;
88
+ attachmentsDeleted: number;
89
+ }
90
+ export declare const collectUnreferencedMedia: (graceMs?: number) => Promise<MediaGarbageCollectionResult>;
91
+ interface ClassifiedMedia {
92
+ status: StoredMediaStatus;
93
+ unreferencedSince: string | null;
94
+ deletesAt: string | null;
95
+ }
96
+ /** How garbage collection treats one file, given the live link set and clock. */
97
+ export declare const classifyMediaFile: (storageId: string, referencedIds: ReadonlySet<string>, unreferencedSinceMs: number | undefined, now: number, graceMs?: number) => ClassifiedMedia;
98
+ export declare const listStoredMedia: () => Promise<{
99
+ files: StoredMediaFile[];
100
+ graceMs: number;
101
+ }>;
102
+ /**
103
+ * Remove one stored file immediately. The garbage-collection clock and
104
+ * dangling attachment rows are cleaned up too. Live links are left in place
105
+ * and will 404. The HLS cache is preserved if the stream was accessed within
106
+ * the recent-access window; it will be reclaimed by the streaming-cleanup cron.
107
+ */
108
+ export declare const deleteStoredMediaNow: (storageId: string) => Promise<boolean>;
109
+ export {};