@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
@@ -1,10 +1,13 @@
1
+ import { jamRoomName } from '@openpeepshq/common/lib';
1
2
  import { publicProfileSchema, } from '@openpeepshq/common/types';
2
3
  import { assertJamRsvpAllowed, createJamToken } from './token.js';
3
4
  import { disconnect, getConnection, getSharedConnection, } from '../redis/connection.js';
4
- const waitingRoomKey = (event) => `jams:waiting-room:${event.id}`;
5
- const admittanceKey = (event) => `jams:admitted:${event.id}`;
6
- const currentWaitingRoom = (event) => getSharedConnection()
7
- .then((conn) => conn.hGetAll(waitingRoomKey(event)))
5
+ const waitingRoomKey = (event, recurrenceId) => `jams:waiting-room:${jamRoomName(event.id, recurrenceId)}`;
6
+ const admittanceKey = (event, recurrenceId) => `jams:admitted:${jamRoomName(event.id, recurrenceId)}`;
7
+ /** Keep admissions around for the length of a long jam / mobile backgrounding. */
8
+ const ADMITTANCE_TTL_SEC = 12 * 60 * 60;
9
+ const currentWaitingRoom = (event, recurrenceId) => getSharedConnection()
10
+ .then((conn) => conn.hGetAll(waitingRoomKey(event, recurrenceId)))
8
11
  .then((wrRaw) => Object.entries(wrRaw))
9
12
  .then((entries) => entries.filter((e) => e[0] && e[1]))
10
13
  .then((entries) => entries.map(([key, value]) => [
@@ -12,18 +15,25 @@ const currentWaitingRoom = (event) => getSharedConnection()
12
15
  publicProfileSchema.partial().parse(JSON.parse(value)),
13
16
  ]))
14
17
  .then((entries) => Object.fromEntries(entries));
15
- const currentAdmittance = (event) => getSharedConnection().then((conn) => conn.hGetAll(admittanceKey(event)));
16
- export const currentWaitingRoomWatch = (jamEvent, onChange) => currentWaitingRoom(jamEvent)
18
+ const currentAdmittance = (event, recurrenceId) => getSharedConnection().then((conn) => conn.hGetAll(admittanceKey(event, recurrenceId)));
19
+ export const isAdmittedToJam = async (event, profileId, recurrenceId) => {
20
+ const conn = await getSharedConnection();
21
+ return Boolean(await conn.hExists(admittanceKey(event, recurrenceId), profileId));
22
+ };
23
+ export const clearJamAdmittance = async (event, recurrenceId) => {
24
+ await getSharedConnection().then((conn) => conn.del(admittanceKey(event, recurrenceId)));
25
+ };
26
+ export const currentWaitingRoomWatch = (jamEvent, onChange, recurrenceId) => currentWaitingRoom(jamEvent, recurrenceId)
17
27
  .then(onChange)
18
28
  .then(() => getConnection())
19
29
  .then((conn) => conn
20
- .subscribe(`__keyspace@0__:${waitingRoomKey(jamEvent)}`, (event) => {
30
+ .subscribe(`__keyspace@0__:${waitingRoomKey(jamEvent, recurrenceId)}`, (event) => {
21
31
  if (['hset', 'hdel'].includes(event)) {
22
- currentWaitingRoom(jamEvent).then(onChange);
32
+ currentWaitingRoom(jamEvent, recurrenceId).then(onChange);
23
33
  }
24
34
  })
25
35
  .then(() => () => disconnect(conn)));
26
- export const admittanceWatch = (jamEvent, profileId, onToken) => currentAdmittance(jamEvent)
36
+ export const admittanceWatch = (jamEvent, profileId, onToken, recurrenceId) => currentAdmittance(jamEvent, recurrenceId)
27
37
  .then((admittance) => {
28
38
  if (admittance[profileId]) {
29
39
  return onToken(admittance[profileId]);
@@ -31,9 +41,9 @@ export const admittanceWatch = (jamEvent, profileId, onToken) => currentAdmittan
31
41
  })
32
42
  .then(() => getConnection())
33
43
  .then((conn) => conn
34
- .subscribe(`__keyspace@0__:${admittanceKey(jamEvent)}`, async (event) => {
44
+ .subscribe(`__keyspace@0__:${admittanceKey(jamEvent, recurrenceId)}`, async (event) => {
35
45
  if ('hset' === event) {
36
- const token = await getSharedConnection().then((c) => c.hGet(admittanceKey(jamEvent), profileId));
46
+ const token = await getSharedConnection().then((c) => c.hGet(admittanceKey(jamEvent, recurrenceId), profileId));
37
47
  if (token) {
38
48
  await disconnect(conn);
39
49
  return onToken(token);
@@ -41,22 +51,20 @@ export const admittanceWatch = (jamEvent, profileId, onToken) => currentAdmittan
41
51
  }
42
52
  })
43
53
  .then(() => async () => {
44
- await getSharedConnection().then((c) => c.hDel(waitingRoomKey(jamEvent), profileId));
54
+ await getSharedConnection().then((c) => c.hDel(waitingRoomKey(jamEvent, recurrenceId), profileId));
45
55
  await disconnect(conn);
46
56
  }));
47
- export const joinWaitingRoom = async (event, profile) => {
48
- assertJamRsvpAllowed(event, profile);
57
+ export const joinWaitingRoom = async (event, profile, recurrenceId) => {
58
+ assertJamRsvpAllowed(event, profile, recurrenceId);
49
59
  const conn = await getSharedConnection();
50
- const multi = conn.multi();
51
- const wrKey = waitingRoomKey(event);
52
- const aKey = admittanceKey(event);
53
- multi.hDel(aKey, profile.id);
54
- multi.hSet(wrKey, { [profile.id]: JSON.stringify(profile) });
55
- await multi.exec();
60
+ const wrKey = waitingRoomKey(event, recurrenceId);
61
+ // Do not clear admittance here — once admitted, the guest may reconnect
62
+ // (mobile idle / tab freeze) without a second moderator approval.
63
+ await conn.hSet(wrKey, { [profile.id]: JSON.stringify(profile) });
56
64
  };
57
- export const acceptFromWaitingRoom = async (event, profileId) => {
65
+ export const acceptFromWaitingRoom = async (event, profileId, recurrenceId) => {
58
66
  const conn = await getSharedConnection();
59
- const wrKey = waitingRoomKey(event);
67
+ const wrKey = waitingRoomKey(event, recurrenceId);
60
68
  const profile = await publicProfileSchema
61
69
  .parseAsync(JSON.parse((await conn.hGet(wrKey, profileId)) || 'undefined'))
62
70
  .catch(() => undefined);
@@ -64,8 +72,9 @@ export const acceptFromWaitingRoom = async (event, profileId) => {
64
72
  if (!event || !profile) {
65
73
  return undefined;
66
74
  }
67
- const aKey = admittanceKey(event);
75
+ const aKey = admittanceKey(event, recurrenceId);
68
76
  await conn.hSet(aKey, {
69
- [profile.id]: await createJamToken(event, profile),
77
+ [profile.id]: await createJamToken(event, profile, false, recurrenceId),
70
78
  });
79
+ await conn.expire(aKey, ADMITTANCE_TTL_SEC);
71
80
  };
@@ -0,0 +1,4 @@
1
+ export { importPostgres } from '../db/migration/importPostgres';
2
+ export { validateMigration } from '../db/migration/validate';
3
+ export { collectionInfos } from '../db/pg/collections';
4
+ export { collectionFilePath, collectionsDir, exportDirFromEnv, sortedChecksum, writeManifest, type MigrationManifest, } from '../db/migration/shared';
@@ -0,0 +1,4 @@
1
+ export { importPostgres } from '../db/migration/importPostgres.js';
2
+ export { validateMigration } from '../db/migration/validate.js';
3
+ export { collectionInfos } from '../db/pg/collections.js';
4
+ export { collectionFilePath, collectionsDir, exportDirFromEnv, sortedChecksum, writeManifest, } from '../db/migration/shared.js';
@@ -8,7 +8,9 @@ export default {
8
8
  event: 'groupMemberJoined',
9
9
  eventHandler: async (...args) => {
10
10
  const [group, profile] = args;
11
- for (const groupAdmin of await listGroupMembers(group).then((members) => members.filter((m) => { var _a; return (_a = m.roles) === null || _a === void 0 ? void 0 : _a.includes('admin'); }).map((m) => m.profile))) {
11
+ for (const groupAdmin of await listGroupMembers(group).then((members) => members
12
+ .filter((m) => { var _a, _b; return ((_a = m.roles) === null || _a === void 0 ? void 0 : _a.includes('owner')) || ((_b = m.roles) === null || _b === void 0 ? void 0 : _b.includes('admin')); })
13
+ .map((m) => m.profile))) {
12
14
  await maybeCreateNotification(groupAdmin, {
13
15
  type: 'groupMemberJoined',
14
16
  fromProfileId: profile.id,
@@ -8,7 +8,9 @@ export default {
8
8
  event: 'groupMemberLeft',
9
9
  eventHandler: async (...args) => {
10
10
  const [group, profile] = args;
11
- for (const groupAdmin of await listGroupMembers(group).then((members) => members.filter((m) => { var _a; return (_a = m.roles) === null || _a === void 0 ? void 0 : _a.includes('admin'); }).map((m) => m.profile))) {
11
+ for (const groupAdmin of await listGroupMembers(group).then((members) => members
12
+ .filter((m) => { var _a, _b; return ((_a = m.roles) === null || _a === void 0 ? void 0 : _a.includes('owner')) || ((_b = m.roles) === null || _b === void 0 ? void 0 : _b.includes('admin')); })
13
+ .map((m) => m.profile))) {
12
14
  await maybeCreateNotification(groupAdmin, {
13
15
  type: 'groupMemberLeft',
14
16
  fromProfileId: profile.id,
@@ -14,8 +14,12 @@ export const notificationSettings = (profileSettings, type) => {
14
14
  };
15
15
  export const expandNotification = async (notification) => {
16
16
  var _a, _b;
17
- const intermediateNotification = Object.assign(Object.assign({}, notification), { senderProfile: notification.fromProfileId
18
- ? anonymizeProfileIfDeleted(await getProfile(notification.fromProfileId))
17
+ const intermediateNotification = Object.assign(Object.assign({}, notification), {
18
+ // Include soft-deleted senders so anonymizeProfileIfDeleted can tombstone
19
+ // them; otherwise fromProfileId resolves to undefined and the UI falls
20
+ // back to an uninterpolated "{{profileName}} …" string.
21
+ senderProfile: notification.fromProfileId
22
+ ? anonymizeProfileIfDeleted(await getProfile(notification.fromProfileId, true))
19
23
  : undefined, post: notification.post
20
24
  ? await transformPost(notification.post)
21
25
  : undefined, recipientProfile: (await getProfile(notification.profileId)) });
@@ -9,6 +9,7 @@ import { updateNotification } from './mutations.js';
9
9
  import { getNotificationStats } from './finders.js';
10
10
  import { findProfileSettings } from '../profileSettings/index.js';
11
11
  import { logger } from '../log/index.js';
12
+ import { publishSessionEvent } from '../session/index.js';
12
13
  const log = logger('core:notifications:worker');
13
14
  const [notificationQueue, notificationWorker] = queueAndWorker('process-notification', async (job) => {
14
15
  var _a, _b;
@@ -33,6 +34,7 @@ const [notificationQueue, notificationWorker] = queueAndWorker('process-notifica
33
34
  const notificationStats = await getNotificationStats(profile);
34
35
  await logStep(jobLog, log, `Resolved ${accounts.length} account(s) for profile ${profile.id}; ` +
35
36
  `delivery channels: email=${email} push=${push}`);
37
+ let sessionPublished = false;
36
38
  for (const account of accounts) {
37
39
  if (email) {
38
40
  await logStep(jobLog, log, `Queueing email notification to ${account.email}`);
@@ -50,8 +52,17 @@ const [notificationQueue, notificationWorker] = queueAndWorker('process-notifica
50
52
  }
51
53
  if (push) {
52
54
  try {
53
- await doPush(await ((_b = notificationHandlers
54
- .get(notification.type)) === null || _b === void 0 ? void 0 : _b.pushRenderer(notification)), notificationStats, account, jobLog);
55
+ const pushNotification = await ((_b = notificationHandlers
56
+ .get(notification.type)) === null || _b === void 0 ? void 0 : _b.pushRenderer(notification));
57
+ if (pushNotification && !sessionPublished) {
58
+ sessionPublished = true;
59
+ await publishSessionEvent(profile.id, {
60
+ type: 'invalidate',
61
+ notification: pushNotification,
62
+ notificationStats,
63
+ }).catch((error) => logFailure(jobLog, log, `session SSE publish for profile ${profile.id} failed`, error));
64
+ }
65
+ await doPush(pushNotification, notificationStats, account, jobLog);
55
66
  }
56
67
  catch (error) {
57
68
  await logFailure(jobLog, log, `push delivery to account ${account.id} (${account.email}) threw`, error);
@@ -1,3 +1,4 @@
1
+ import { getUniqueBy, pushSubscriptionDeliveryKey, } from '@openpeepshq/common/lib';
1
2
  import { communityConfig, config } from '../config/index.js';
2
3
  import webPush from 'web-push';
3
4
  import { logger } from '../log/index.js';
@@ -178,10 +179,16 @@ export const doPush = async (notification, notificationStats, account, jobLog) =
178
179
  notificationStats,
179
180
  };
180
181
  const subscriptions = await listPushSubscriptionsByAccount(account);
181
- const webSubscriptions = subscriptions.filter((sub) => sub.type === 'web');
182
- const webhookSubscriptions = subscriptions.filter((sub) => sub.type === 'webhook');
183
- const apnSubscriptions = subscriptions.filter((sub) => sub.type === 'apn');
184
- const fcmSubscriptions = subscriptions.filter((sub) => sub.type === 'fcm');
182
+ const uniqueSubscriptions = getUniqueBy(subscriptions, pushSubscriptionDeliveryKey);
183
+ const duplicateSubscriptions = subscriptions.filter((subscription) => !uniqueSubscriptions.some((unique) => unique.id === subscription.id));
184
+ if (duplicateSubscriptions.length > 0) {
185
+ await logStep(jobLog, log, `Removing ${duplicateSubscriptions.length} duplicate push subscription(s) for account ${account.id}`);
186
+ await Promise.all(duplicateSubscriptions.map((subscription) => deletePushSubscription(subscription.id).catch((error) => logFailure(jobLog, log, `failed to remove duplicate subscription ${subscription.id}`, error))));
187
+ }
188
+ const webSubscriptions = uniqueSubscriptions.filter((sub) => sub.type === 'web');
189
+ const webhookSubscriptions = uniqueSubscriptions.filter((sub) => sub.type === 'webhook');
190
+ const apnSubscriptions = uniqueSubscriptions.filter((sub) => sub.type === 'apn');
191
+ const fcmSubscriptions = uniqueSubscriptions.filter((sub) => sub.type === 'fcm');
185
192
  await logStep(jobLog, log, `Delivering push "${notification.title}" to account ${account.id} (${account.email}); ` +
186
193
  `subscriptions: web=${webSubscriptions.length} webhook=${webhookSubscriptions.length} ` +
187
194
  `apn=${apnSubscriptions.length} fcm=${fcmSubscriptions.length}`);
@@ -1,3 +1,7 @@
1
1
  import { PackageJson } from 'type-fest';
2
- export declare const sortByDependencies: (pluginInfos: [string, PackageJson][]) => [string, PackageJson][];
3
- export declare const enumeratePluginInfos: (pluginsPath: string) => Promise<[string, PackageJson][]>;
2
+ export declare const isPluginEnabled: (info: PackageJson) => boolean;
3
+ type PluginInfo = [string, PackageJson, string];
4
+ export declare const sortByDependencies: (pluginInfos: PluginInfo[]) => PluginInfo[];
5
+ export declare const enumeratePluginInfos: (pluginsPath: string) => Promise<PluginInfo[]>;
6
+ export declare const enumerateReferencedPluginInfos: (rootPackageJsonPath: string) => PluginInfo[];
7
+ export {};
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { logger } from '../log/index.js';
4
4
  const log = logger('core:plugins');
5
- const isPluginEnabled = (info) => {
5
+ export const isPluginEnabled = (info) => {
6
6
  var _a;
7
7
  return ((_a = info.openpeeps) === null || _a === void 0 ? void 0 : _a.enabled) !== false;
8
8
  };
@@ -46,15 +46,9 @@ const enumeratePluginsForNamespace = (pluginsPath, namespace) => {
46
46
  .filter((pluginName) => fs.lstatSync(path.join(pluginsPath, namespace, pluginName)).isDirectory())
47
47
  .map((name) => {
48
48
  const key = path.join(namespace, name);
49
- const info = JSON.parse(fs.readFileSync(path.join(path.join(pluginsPath, key), 'package.json'), 'utf-8'));
50
- return [key, info];
51
- })
52
- .filter(([key, info]) => {
53
- if (isPluginEnabled(info)) {
54
- return true;
55
- }
56
- log.info(`Skipping disabled plugin ${key}.`);
57
- return false;
49
+ const pluginPath = path.join(pluginsPath, key);
50
+ const info = JSON.parse(fs.readFileSync(path.join(pluginPath, 'package.json'), 'utf-8'));
51
+ return [key, info, pluginPath];
58
52
  });
59
53
  };
60
54
  export const enumeratePluginInfos = async (pluginsPath) => {
@@ -70,3 +64,21 @@ export const enumeratePluginInfos = async (pluginsPath) => {
70
64
  return [];
71
65
  }
72
66
  };
67
+ // Plugins outside `plugins/<namespace>/<name>/` (e.g. `examples/*`) are not
68
+ // scanned automatically. They only load when explicitly referenced from the
69
+ // root `package.json`'s `openpeeps.plugins` array (paths relative to the repo
70
+ // root), keeping example/demo plugins opt-in.
71
+ export const enumerateReferencedPluginInfos = (rootPackageJsonPath) => {
72
+ var _a, _b;
73
+ if (!fs.existsSync(rootPackageJsonPath)) {
74
+ return [];
75
+ }
76
+ const rootPackageJson = JSON.parse(fs.readFileSync(rootPackageJsonPath, 'utf-8'));
77
+ const repoRoot = path.dirname(rootPackageJsonPath);
78
+ return ((_b = (_a = rootPackageJson.openpeeps) === null || _a === void 0 ? void 0 : _a.plugins) !== null && _b !== void 0 ? _b : []).map((relativePath) => {
79
+ const pluginPath = path.join(repoRoot, relativePath);
80
+ const key = path.join('examples', path.basename(pluginPath));
81
+ const info = JSON.parse(fs.readFileSync(path.join(pluginPath, 'package.json'), 'utf-8'));
82
+ return [key, info, pluginPath];
83
+ });
84
+ };
@@ -1,10 +1,15 @@
1
1
  import type { PackageJson } from 'type-fest';
2
2
  import type { Plugin, PluginManifest } from '@openpeepshq/common';
3
3
  export * from './pluginAuth';
4
+ export * from './state';
5
+ export * from './install';
4
6
  export declare const getPlugins: () => Plugin[];
5
7
  export declare const getPluginModule: (key: string) => unknown | undefined;
6
8
  export declare const getPluginManifests: () => Record<string, PluginManifest>;
7
9
  export declare const initializePlugins: () => Promise<{
8
10
  [k: string]: Plugin;
9
11
  } | undefined>;
10
- export declare const sortedPluginInfos: () => Promise<[string, PackageJson][]>;
12
+ export declare const sortedPluginInfos: () => Promise<[string, PackageJson, string][]>;
13
+ export declare const reloadPlugins: () => Promise<{
14
+ [k: string]: Plugin;
15
+ } | undefined>;
@@ -1,31 +1,45 @@
1
- import path from 'node:path';
2
1
  import { hub, VALID_EVENT_KEYS } from '../events/index.js';
3
2
  import { defaultConfig, registerConfigSchema } from '../config/index.js';
4
3
  import { pluginManifestSchema } from '@openpeepshq/common';
5
- import { enumeratePluginInfos, sortByDependencies } from './helpers.js';
4
+ import { enumeratePluginInfos, enumerateReferencedPluginInfos, isPluginEnabled, sortByDependencies, } from './helpers.js';
5
+ import { getPluginStateOverrides } from './state.js';
6
6
  import { logger } from '../log/index.js';
7
7
  export * from './pluginAuth.js';
8
+ export * from './state.js';
9
+ export * from './install.js';
8
10
  const log = logger('core:plugins');
9
11
  let initialized = false;
10
12
  const loadedPlugins = new Map();
11
13
  const loadedModules = new Map();
12
14
  const pluginManifests = new Map();
15
+ const pluginUnsubscribers = new Map();
13
16
  export const getPlugins = () => Array.from(loadedPlugins.values());
14
17
  export const getPluginModule = (key) => loadedModules.get(key);
15
18
  export const getPluginManifests = () => Object.fromEntries(pluginManifests.entries());
19
+ const clearPluginState = () => {
20
+ for (const unsubscribers of pluginUnsubscribers.values()) {
21
+ for (const unsub of unsubscribers) {
22
+ unsub();
23
+ }
24
+ }
25
+ loadedPlugins.clear();
26
+ loadedModules.clear();
27
+ pluginManifests.clear();
28
+ pluginUnsubscribers.clear();
29
+ initialized = false;
30
+ };
16
31
  export const initializePlugins = async () => {
17
32
  if (initialized) {
18
33
  return;
19
34
  }
20
- const { plugins: { path: pluginsPath }, } = await defaultConfig;
21
- const loadPlugin = async (pluginsPath, key, info) => {
22
- var _a;
35
+ const { plugins: { path: pluginsPath, rootPackageJsonPath }, } = await defaultConfig;
36
+ const stateOverrides = await getPluginStateOverrides();
37
+ const loadPlugin = async (key, info, pluginPath) => {
38
+ var _a, _b;
23
39
  const [namespace, name] = key.split('/');
24
- const pluginPath = path.join(pluginsPath, key);
25
40
  const displayName = typeof ((_a = info === null || info === void 0 ? void 0 : info.config) === null || _a === void 0 ? void 0 : _a.displayName) === 'string'
26
41
  ? info.config.displayName
27
42
  : key;
28
- log.info(`Loading plugin "${displayName}" (key: ${key}) from path ${pluginPath}.`);
29
43
  const plugin = {
30
44
  key,
31
45
  namespace,
@@ -33,19 +47,31 @@ export const initializePlugins = async () => {
33
47
  info,
34
48
  path: pluginPath,
35
49
  };
50
+ // DB override (set via the admin toggle) takes precedence over the
51
+ // static `openpeeps.enabled` package.json gate; a missing override
52
+ // falls back to the static gate.
53
+ const enabled = (_b = stateOverrides[key]) !== null && _b !== void 0 ? _b : isPluginEnabled(info);
54
+ if (!enabled) {
55
+ log.info(`Skipping disabled plugin "${displayName}" (key: ${key}).`);
56
+ plugin.status = 'disabled';
57
+ loadedPlugins.set(key, plugin);
58
+ return;
59
+ }
60
+ log.info(`Loading plugin "${displayName}" (key: ${key}) from path ${pluginPath}.`);
36
61
  try {
37
62
  const pluginModule = await import(
38
63
  /* @vite-ignore */ `${pluginPath}/dist/index.js`);
39
64
  loadedModules.set(key, pluginModule);
40
65
  if ('interceptors' in pluginModule) {
41
66
  const interceptors = await pluginModule.interceptors();
67
+ const unsubscribers = [];
42
68
  for (const [eventKey, handler] of Object.entries(interceptors)) {
43
69
  if (!VALID_EVENT_KEYS.includes(eventKey)) {
44
70
  log.warn(`${plugin.key} registered handler for unknown event ${eventKey}. Skipping.`);
45
71
  continue;
46
72
  }
47
73
  log.info(`${plugin.key} listening for event ${eventKey}`);
48
- hub.on(eventKey, async (...args) => {
74
+ const unsub = hub.on(eventKey, async (...args) => {
49
75
  try {
50
76
  await handler(...args);
51
77
  }
@@ -53,7 +79,9 @@ export const initializePlugins = async () => {
53
79
  log.error(e, `${plugin.key} handler for event ${eventKey} failed.`);
54
80
  }
55
81
  });
82
+ unsubscribers.push(unsub);
56
83
  }
84
+ pluginUnsubscribers.set(key, unsubscribers);
57
85
  }
58
86
  if ('configSchema' in pluginModule) {
59
87
  registerConfigSchema(namespace, name, pluginModule.configSchema.schema, pluginModule.configSchema.defaults);
@@ -71,14 +99,27 @@ export const initializePlugins = async () => {
71
99
  }
72
100
  loadedPlugins.set(key, plugin);
73
101
  };
74
- const sortedInfos = sortByDependencies(await enumeratePluginInfos(pluginsPath));
75
- for (const [key, info] of sortedInfos) {
76
- await loadPlugin(pluginsPath, key, info);
102
+ const sortedInfos = sortByDependencies([
103
+ ...(await enumeratePluginInfos(pluginsPath)),
104
+ ...enumerateReferencedPluginInfos(rootPackageJsonPath),
105
+ ]);
106
+ for (const [key, info, pluginPath] of sortedInfos) {
107
+ await loadPlugin(key, info, pluginPath);
77
108
  }
78
109
  initialized = true;
79
110
  return Object.fromEntries(loadedPlugins.entries());
80
111
  };
81
112
  export const sortedPluginInfos = async () => {
82
- const { plugins: { path: pluginsPath }, } = defaultConfig;
83
- return sortByDependencies(await enumeratePluginInfos(pluginsPath));
113
+ const { plugins: { path: pluginsPath, rootPackageJsonPath }, } = defaultConfig;
114
+ return sortByDependencies([
115
+ ...(await enumeratePluginInfos(pluginsPath)),
116
+ ...enumerateReferencedPluginInfos(rootPackageJsonPath),
117
+ ]);
118
+ };
119
+ export const reloadPlugins = async () => {
120
+ log.info('Reloading all plugins...');
121
+ clearPluginState();
122
+ const result = await initializePlugins();
123
+ log.info('Plugin reload complete.');
124
+ return result;
84
125
  };
@@ -0,0 +1,20 @@
1
+ type InstallSource = {
2
+ type: 'npm';
3
+ package: string;
4
+ version?: string;
5
+ } | {
6
+ type: 'git';
7
+ url: string;
8
+ ref?: string;
9
+ };
10
+ export declare const installPlugin: (source: InstallSource, installedBy?: string) => Promise<{
11
+ success: boolean;
12
+ pluginKey?: string;
13
+ error?: string;
14
+ }>;
15
+ export declare const uninstallPlugin: (pluginKey: string, uninstalledBy?: string) => Promise<{
16
+ success: boolean;
17
+ error?: string;
18
+ }>;
19
+ export declare const getInstalledPluginKeys: () => Promise<string[]>;
20
+ export {};