@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
@@ -0,0 +1,223 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
12
+ import { spawn } from 'node:child_process';
13
+ import fs from 'node:fs/promises';
14
+ import path from 'node:path';
15
+ import { defaultConfig } from '../config/index.js';
16
+ import { logger } from '../log/index.js';
17
+ import { allpeepDb } from '../db/index.js';
18
+ import { configs } from '../db/pg/schema/documents.js';
19
+ import { nowIso } from '../db/pg/mappers.js';
20
+ import { eq } from 'drizzle-orm';
21
+ import { setPluginEnabledOverride } from './state.js';
22
+ const log = logger('core:plugins:install');
23
+ const INSTALLED_PLUGINS_KEY = 'openpeeps-installed-plugins';
24
+ const getInstalledPlugins = async () => {
25
+ var _a, _b;
26
+ const { db } = await allpeepDb();
27
+ const rows = await db
28
+ .select()
29
+ .from(configs)
30
+ .where(eq(configs.key, INSTALLED_PLUGINS_KEY))
31
+ .limit(1);
32
+ return (_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.body) !== null && _b !== void 0 ? _b : {};
33
+ };
34
+ const setInstalledPlugin = async (pluginKey, source, installedBy) => {
35
+ const installed = await getInstalledPlugins();
36
+ const body = Object.assign(Object.assign({}, installed), { [pluginKey]: { source, installedAt: nowIso(), installedBy } });
37
+ const ts = nowIso();
38
+ const { db } = await allpeepDb();
39
+ await db
40
+ .insert(configs)
41
+ .values({ key: INSTALLED_PLUGINS_KEY, body, createdAt: ts, updatedAt: ts })
42
+ .onConflictDoUpdate({
43
+ target: configs.key,
44
+ set: { body, updatedAt: ts },
45
+ });
46
+ };
47
+ const removeInstalledPlugin = async (pluginKey) => {
48
+ const installed = await getInstalledPlugins();
49
+ const _a = installed, _b = pluginKey, _removed = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
50
+ const ts = nowIso();
51
+ const { db } = await allpeepDb();
52
+ await db
53
+ .insert(configs)
54
+ .values({
55
+ key: INSTALLED_PLUGINS_KEY,
56
+ body: rest,
57
+ createdAt: ts,
58
+ updatedAt: ts,
59
+ })
60
+ .onConflictDoUpdate({
61
+ target: configs.key,
62
+ set: { body: rest, updatedAt: ts },
63
+ });
64
+ };
65
+ const runCommand = (command, args, cwd) => new Promise((resolve) => {
66
+ const child = spawn(command, args, { cwd, shell: true });
67
+ let stdout = '';
68
+ let stderr = '';
69
+ child.stdout.on('data', (chunk) => {
70
+ stdout += chunk.toString();
71
+ });
72
+ child.stderr.on('data', (chunk) => {
73
+ stderr += chunk.toString();
74
+ });
75
+ child.on('close', (exitCode) => {
76
+ resolve({ exitCode: exitCode !== null && exitCode !== void 0 ? exitCode : 1, stdout, stderr });
77
+ });
78
+ child.on('error', (err) => {
79
+ resolve({ exitCode: 1, stdout, stderr: String(err) });
80
+ });
81
+ });
82
+ const getPluginDir = async () => {
83
+ const { plugins } = await defaultConfig;
84
+ return plugins.path;
85
+ };
86
+ const sourceLabel = (source) => source.type === 'npm'
87
+ ? `npm:${source.package}${source.version ? `@${source.version}` : ''}`
88
+ : `git:${source.url}${source.ref ? `#${source.ref}` : ''}`;
89
+ export const installPlugin = async (source, installedBy) => {
90
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
91
+ const pluginsDir = await getPluginDir();
92
+ const label = sourceLabel(source);
93
+ let tempDir;
94
+ try {
95
+ tempDir = await fs.mkdtemp(path.join(pluginsDir, '.install-'));
96
+ }
97
+ catch (e) {
98
+ log.error(e, `Failed to create temp dir in ${pluginsDir}`);
99
+ return { success: false, error: `Cannot write to plugins directory: ${e}` };
100
+ }
101
+ try {
102
+ let installDir;
103
+ if (source.type === 'npm') {
104
+ const pkg = source.version
105
+ ? `${source.package}@${source.version}`
106
+ : source.package;
107
+ log.info(`Installing npm package ${pkg} to temp dir ${tempDir}`);
108
+ const init = await runCommand('npm', ['init', '-y'], tempDir);
109
+ if (init.exitCode !== 0) {
110
+ return { success: false, error: `npm init failed: ${init.stderr}` };
111
+ }
112
+ const install = await runCommand('npm', ['install', pkg], tempDir);
113
+ if (install.exitCode !== 0) {
114
+ return {
115
+ success: false,
116
+ error: `npm install failed: ${install.stderr}`,
117
+ };
118
+ }
119
+ installDir = path.join(tempDir, 'node_modules', source.package);
120
+ }
121
+ else {
122
+ log.info(`Cloning git repo ${source.url} to temp dir ${tempDir}`);
123
+ const cloneArgs = ['clone', '--depth', '1'];
124
+ if (source.ref) {
125
+ cloneArgs.push('--branch', source.ref);
126
+ }
127
+ cloneArgs.push(source.url, path.join(tempDir, 'repo'));
128
+ const clone = await runCommand('git', cloneArgs, tempDir);
129
+ if (clone.exitCode !== 0) {
130
+ return { success: false, error: `git clone failed: ${clone.stderr}` };
131
+ }
132
+ installDir = path.join(tempDir, 'repo');
133
+ }
134
+ // Read package.json to determine namespace/name
135
+ const pkgJsonRaw = await fs.readFile(path.join(installDir, 'package.json'), 'utf-8');
136
+ const pkgJson = JSON.parse(pkgJsonRaw);
137
+ const namespace = (_e = (_b = (_a = pkgJson.openpeeps) === null || _a === void 0 ? void 0 : _a.namespace) !== null && _b !== void 0 ? _b : (_d = (_c = pkgJson.name) === null || _c === void 0 ? void 0 : _c.split('/')[0]) === null || _d === void 0 ? void 0 : _d.replace(/^@/, '')) !== null && _e !== void 0 ? _e : 'custom';
138
+ const name = (_l = (_j = (_g = (_f = pkgJson.openpeeps) === null || _f === void 0 ? void 0 : _f.name) !== null && _g !== void 0 ? _g : (_h = pkgJson.name) === null || _h === void 0 ? void 0 : _h.split('/')[1]) !== null && _j !== void 0 ? _j : (_k = pkgJson.name) === null || _k === void 0 ? void 0 : _k.replace(/^@[^/]+\//, '')) !== null && _l !== void 0 ? _l : 'plugin';
139
+ const pluginKey = `${namespace}/${name}`;
140
+ const destDir = path.join(pluginsDir, namespace, name);
141
+ // Check if already exists in the plugins dir (built-in)
142
+ const existingEntries = await fs
143
+ .readdir(pluginsDir)
144
+ .catch(() => []);
145
+ const nsEntries = existingEntries.includes(namespace)
146
+ ? await fs
147
+ .readdir(path.join(pluginsDir, namespace))
148
+ .catch(() => [])
149
+ : [];
150
+ if (nsEntries.includes(name)) {
151
+ // Check if this is a built-in plugin (not in installed list)
152
+ const installed = await getInstalledPlugins();
153
+ if (!installed[pluginKey]) {
154
+ return {
155
+ success: false,
156
+ error: `Plugin "${pluginKey}" is a built-in plugin and cannot be overwritten.`,
157
+ };
158
+ }
159
+ }
160
+ // Build the plugin if it has a build script
161
+ if ((_m = pkgJson.scripts) === null || _m === void 0 ? void 0 : _m.build) {
162
+ log.info(`Building plugin ${pluginKey}...`);
163
+ const buildDeps = await runCommand('npm', ['install'], installDir);
164
+ if (buildDeps.exitCode !== 0) {
165
+ return {
166
+ success: false,
167
+ error: `Dependency install failed: ${buildDeps.stderr}`,
168
+ };
169
+ }
170
+ const build = await runCommand('npm', ['run', 'build'], installDir);
171
+ if (build.exitCode !== 0) {
172
+ return {
173
+ success: false,
174
+ error: `Build failed: ${build.stderr}`,
175
+ };
176
+ }
177
+ }
178
+ // Move to final location
179
+ await fs.mkdir(path.join(pluginsDir, namespace), { recursive: true });
180
+ await fs.rm(destDir, { recursive: true, force: true });
181
+ await fs.cp(installDir, destDir, { recursive: true });
182
+ await fs.rm(tempDir, { recursive: true, force: true });
183
+ await setInstalledPlugin(pluginKey, label, installedBy);
184
+ // Installed plugins never auto-enable — an admin must explicitly
185
+ // activate them via the enable toggle (Phase B) after reviewing them.
186
+ await setPluginEnabledOverride(pluginKey, false);
187
+ log.info(`Plugin ${pluginKey} installed successfully from ${label}${installedBy ? ` by ${installedBy}` : ''}. Disabled by default — activate it explicitly to load it.`);
188
+ return { success: true, pluginKey };
189
+ }
190
+ catch (e) {
191
+ // Cleanup on any error
192
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => { });
193
+ const message = e instanceof Error ? e.message : String(e);
194
+ log.error(e, `Failed to install plugin from ${label}.`);
195
+ return { success: false, error: message };
196
+ }
197
+ };
198
+ export const uninstallPlugin = async (pluginKey, uninstalledBy) => {
199
+ const installed = await getInstalledPlugins();
200
+ if (!installed[pluginKey]) {
201
+ return {
202
+ success: false,
203
+ error: `Plugin "${pluginKey}" was not installed via the admin UI.`,
204
+ };
205
+ }
206
+ const pluginsDir = await getPluginDir();
207
+ const pluginDir = path.join(pluginsDir, pluginKey);
208
+ try {
209
+ await fs.rm(pluginDir, { recursive: true, force: true });
210
+ await removeInstalledPlugin(pluginKey);
211
+ log.info(`Plugin ${pluginKey} uninstalled${uninstalledBy ? ` by ${uninstalledBy}` : ''}.`);
212
+ return { success: true };
213
+ }
214
+ catch (e) {
215
+ const message = e instanceof Error ? e.message : String(e);
216
+ log.error(e, `Failed to uninstall plugin ${pluginKey}.`);
217
+ return { success: false, error: message };
218
+ }
219
+ };
220
+ export const getInstalledPluginKeys = async () => {
221
+ const installed = await getInstalledPlugins();
222
+ return Object.keys(installed);
223
+ };
@@ -0,0 +1,4 @@
1
+ type PluginStateBody = Record<string, boolean>;
2
+ export declare const getPluginStateOverrides: () => Promise<PluginStateBody>;
3
+ export declare const setPluginEnabledOverride: (pluginKey: string, enabled: boolean) => Promise<import("pg").QueryResult<never>>;
4
+ export {};
@@ -0,0 +1,29 @@
1
+ import { eq } from 'drizzle-orm';
2
+ import { allpeepDb } from '../db/index.js';
3
+ import { configs } from '../db/pg/schema/documents.js';
4
+ import { nowIso } from '../db/pg/mappers.js';
5
+ // Single JSONB row keyed by plugin key -> desired enabled state. A missing
6
+ // entry means "no override"; the static `openpeeps.enabled` package.json
7
+ // gate decides. Reuses the generic `configs` table rather than a dedicated
8
+ // one — this is a small, boot-time-read key/value document, not a relation.
9
+ const PLUGIN_STATE_KEY = 'openpeeps-plugin-state';
10
+ export const getPluginStateOverrides = () => allpeepDb().then(async ({ db }) => {
11
+ var _a, _b;
12
+ const rows = await db
13
+ .select()
14
+ .from(configs)
15
+ .where(eq(configs.key, PLUGIN_STATE_KEY))
16
+ .limit(1);
17
+ return (_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.body) !== null && _b !== void 0 ? _b : {};
18
+ });
19
+ export const setPluginEnabledOverride = (pluginKey, enabled) => getPluginStateOverrides().then((overrides) => {
20
+ const body = Object.assign(Object.assign({}, overrides), { [pluginKey]: enabled });
21
+ const ts = nowIso();
22
+ return allpeepDb().then(({ db }) => db
23
+ .insert(configs)
24
+ .values({ key: PLUGIN_STATE_KEY, body, createdAt: ts, updatedAt: ts })
25
+ .onConflictDoUpdate({
26
+ target: configs.key,
27
+ set: { body, updatedAt: ts },
28
+ }));
29
+ });
@@ -4,9 +4,10 @@ import type { Mapping } from '../db/pg/map';
4
4
  export declare const CONTEXT_NODE_CAP = 100;
5
5
  type ClosureDirection = 'ancestors' | 'descendents';
6
6
  /** Collect reply-graph ids via one recursive CTE (capped). */
7
- export declare const collectReplyClosureIds: (db: PgDb, startId: string, direction: ClosureDirection, { maxDepth, limit, }?: {
7
+ export declare const collectReplyClosureIds: (db: PgDb, startId: string, direction: ClosureDirection, { maxDepth, limit, newestFirst, }?: {
8
8
  maxDepth?: number;
9
9
  limit?: number;
10
+ newestFirst?: boolean;
10
11
  }) => Promise<string[]>;
11
12
  /** Load and hydrate posts in a reply closure, then ACL-filter + transform. */
12
13
  export declare const loadReplyContextPosts: (authData: AuthorizationData, startId: string, direction: ClosureDirection, mapping: Mapping<DbPost>, { maxDepth, limit, }?: {
@@ -6,9 +6,12 @@ import { capabilitiesConfig } from '../config/index.js';
6
6
  import { canReadPost, transformPost } from './helpers/index.js';
7
7
  export const CONTEXT_NODE_CAP = 100;
8
8
  /** Collect reply-graph ids via one recursive CTE (capped). */
9
- export const collectReplyClosureIds = async (db, startId, direction, { maxDepth = 9999, limit = CONTEXT_NODE_CAP, } = {}) => {
9
+ export const collectReplyClosureIds = async (db, startId, direction, { maxDepth = 9999, limit = CONTEXT_NODE_CAP,
10
+ /** Newest-first by uuidv7 id (useful for long DM threads). */
11
+ newestFirst = false, } = {}) => {
10
12
  if (!startId || limit <= 0)
11
13
  return [];
14
+ const orderClause = newestFirst ? sql `ORDER BY id DESC` : sql ``;
12
15
  const query = direction === 'ancestors'
13
16
  ? sql `
14
17
  WITH RECURSIVE t AS (
@@ -22,6 +25,7 @@ export const collectReplyClosureIds = async (db, startId, direction, { maxDepth
22
25
  WHERE t.depth < ${maxDepth}
23
26
  )
24
27
  SELECT id FROM t
28
+ ${orderClause}
25
29
  LIMIT ${limit}
26
30
  `
27
31
  : sql `
@@ -36,6 +40,7 @@ export const collectReplyClosureIds = async (db, startId, direction, { maxDepth
36
40
  WHERE t.depth < ${maxDepth}
37
41
  )
38
42
  SELECT id FROM t
43
+ ${orderClause}
39
44
  LIMIT ${limit}
40
45
  `;
41
46
  const result = (await db.execute(query));
@@ -0,0 +1,23 @@
1
+ import type { AuthorizationData, PostWithMeta } from '@openpeepshq/common/types';
2
+ import type { PgDb } from '../db/pg/client';
3
+ type RootLeafPair = {
4
+ rootId: string;
5
+ leafId: string;
6
+ };
7
+ /** Root + newest leaf per DM thread the profile is in (ids only). */
8
+ export declare const listConversationRootLeafPairs: (db: PgDb, profileId: string) => Promise<RootLeafPair[]>;
9
+ /** Newest post id in a reply thread (root included); uuidv7-ordered. */
10
+ export declare const findLatestThreadPostId: (rootId: string) => Promise<string>;
11
+ /**
12
+ * Inbox list: one preview per conversation as [root, leaf] (or [root] when
13
+ * they are the same). Avoids walking full ancestor chains.
14
+ */
15
+ export declare const listConversationPreviews: (authData: AuthorizationData) => Promise<PostWithMeta[][]>;
16
+ /**
17
+ * Conversation detail: root plus newest capped descendants (lean mapping +
18
+ * seenBatch). Prefer newest messages so long DMs stay usable.
19
+ */
20
+ export declare const getConversationThread: (root: PostWithMeta, authData: AuthorizationData, { limit }?: {
21
+ limit?: number;
22
+ }) => Promise<PostWithMeta[]>;
23
+ export {};
@@ -0,0 +1,135 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { getUniqueBy } from '@openpeepshq/common/lib';
3
+ import { allpeepDb } from '../db/index.js';
4
+ import { fetchRowsByIds, hydrateMapData } from '../db/pg/map/relations.js';
5
+ import { capabilitiesConfig } from '../config/index.js';
6
+ import { canReadPost, transformPost } from './helpers/index.js';
7
+ import { CONTEXT_NODE_CAP, collectReplyClosureIds } from './contextClosure.js';
8
+ import { postContextMappingForProfile } from './mapping.js';
9
+ /** Root + newest leaf per DM thread the profile is in (ids only). */
10
+ export const listConversationRootLeafPairs = async (db, profileId) => {
11
+ const result = (await db.execute(sql `
12
+ WITH RECURSIVE leaves AS (
13
+ SELECT p.id::text AS leaf_id
14
+ FROM audience a
15
+ INNER JOIN posts p
16
+ ON p.id::text = a.from_id
17
+ AND p.deleted_at IS NULL
18
+ WHERE a.to_id = ${profileId}
19
+ AND p.visibility = 'direct'
20
+ AND (
21
+ SELECT count(*)::int
22
+ FROM reply_to rt
23
+ INNER JOIN posts rp
24
+ ON rp.id::text = rt.from_id
25
+ AND rp.deleted_at IS NULL
26
+ WHERE rt.to_id = p.id::text
27
+ ) = 0
28
+ ),
29
+ walk AS (
30
+ SELECT l.leaf_id, l.leaf_id AS node_id, 0 AS depth
31
+ FROM leaves l
32
+ UNION ALL
33
+ SELECT walk.leaf_id, rt.to_id, walk.depth + 1
34
+ FROM reply_to rt
35
+ INNER JOIN walk ON rt.from_id = walk.node_id
36
+ ),
37
+ roots AS (
38
+ SELECT DISTINCT ON (leaf_id) leaf_id, node_id AS root_id
39
+ FROM walk
40
+ ORDER BY leaf_id, depth DESC
41
+ ),
42
+ best AS (
43
+ SELECT DISTINCT ON (root_id) root_id, leaf_id
44
+ FROM roots
45
+ ORDER BY root_id, leaf_id DESC
46
+ )
47
+ SELECT root_id, leaf_id
48
+ FROM best
49
+ ORDER BY leaf_id DESC
50
+ `));
51
+ return result.rows.map((row) => ({
52
+ rootId: row.root_id,
53
+ leafId: row.leaf_id,
54
+ }));
55
+ };
56
+ /** Newest post id in a reply thread (root included); uuidv7-ordered. */
57
+ export const findLatestThreadPostId = async (rootId) => {
58
+ var _a, _b;
59
+ const { db } = await allpeepDb();
60
+ const result = (await db.execute(sql `
61
+ WITH RECURSIVE t AS (
62
+ SELECT ${rootId}::text AS id
63
+ UNION ALL
64
+ SELECT rt.from_id
65
+ FROM reply_to rt
66
+ INNER JOIN t ON rt.to_id = t.id
67
+ INNER JOIN posts p
68
+ ON p.id::text = rt.from_id
69
+ AND p.deleted_at IS NULL
70
+ )
71
+ SELECT id
72
+ FROM t
73
+ ORDER BY id DESC
74
+ LIMIT 1
75
+ `));
76
+ return (_b = (_a = result.rows[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : rootId;
77
+ };
78
+ const hydrateLeanPostsByIds = async (authData, ids) => {
79
+ if (!ids.length)
80
+ return new Map();
81
+ const { db } = await allpeepDb();
82
+ const mapData = postContextMappingForProfile(authData.profile).data();
83
+ const rows = await fetchRowsByIds(db, mapData.collection, ids, mapData.softDelete);
84
+ const hydrated = (await hydrateMapData(db, mapData, rows));
85
+ const config = await capabilitiesConfig();
86
+ const readable = canReadPost(config, authData);
87
+ const byId = new Map();
88
+ for (const post of hydrated) {
89
+ const transformed = await transformPost(post, authData.profile);
90
+ if (readable(transformed))
91
+ byId.set(transformed.id, transformed);
92
+ }
93
+ return byId;
94
+ };
95
+ /**
96
+ * Inbox list: one preview per conversation as [root, leaf] (or [root] when
97
+ * they are the same). Avoids walking full ancestor chains.
98
+ */
99
+ export const listConversationPreviews = async (authData) => {
100
+ const profile = authData.profile;
101
+ if (!profile) {
102
+ throw new Error('AuthorizationData.profile is required for this finder');
103
+ }
104
+ const { db } = await allpeepDb();
105
+ const pairs = await listConversationRootLeafPairs(db, profile.id);
106
+ const ids = [...new Set(pairs.flatMap((pair) => [pair.rootId, pair.leafId]))];
107
+ const byId = await hydrateLeanPostsByIds(authData, ids);
108
+ return getUniqueBy(pairs
109
+ .map(({ rootId, leafId }) => {
110
+ const root = byId.get(rootId);
111
+ const leaf = byId.get(leafId);
112
+ if (!root || !leaf)
113
+ return null;
114
+ return rootId === leafId ? [root] : [root, leaf];
115
+ })
116
+ .filter((conversation) => !!conversation), (conversation) => conversation[0].id);
117
+ };
118
+ /**
119
+ * Conversation detail: root plus newest capped descendants (lean mapping +
120
+ * seenBatch). Prefer newest messages so long DMs stay usable.
121
+ */
122
+ export const getConversationThread = async (root, authData, { limit = CONTEXT_NODE_CAP } = {}) => {
123
+ const { db } = await allpeepDb();
124
+ const newestIds = await collectReplyClosureIds(db, root.id, 'descendents', {
125
+ maxDepth: 9999,
126
+ limit,
127
+ newestFirst: true,
128
+ });
129
+ const byId = await hydrateLeanPostsByIds(authData, newestIds);
130
+ const ordered = newestIds
131
+ .map((id) => byId.get(id))
132
+ .filter((post) => !!post)
133
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
134
+ return [root, ...ordered.filter((post) => post.id !== root.id)];
135
+ };
@@ -0,0 +1,165 @@
1
+ import type { AuthorizationData, PostWithMeta } from '@openpeepshq/common/types';
2
+ import { type PgDb } from '../db';
3
+ export type EventAgendaWindow = 'upcoming' | 'current' | 'past';
4
+ export type EventAgendaOptions = {
5
+ offset?: number;
6
+ limit?: number;
7
+ jamOnly?: boolean;
8
+ mine?: boolean;
9
+ groupId?: string;
10
+ };
11
+ export type EventAgendaQueryArgs = {
12
+ window: EventAgendaWindow;
13
+ now: string;
14
+ offset: number;
15
+ limit: number;
16
+ jamOnly?: boolean;
17
+ mine?: boolean;
18
+ groupId?: string;
19
+ profileId?: string;
20
+ };
21
+ export declare const eventAgendaOccurrenceQuery: (db: Pick<PgDb, "select" | "selectDistinctOn">, args: EventAgendaQueryArgs) => Omit<import("drizzle-orm/pg-core").PgSelectBase<"event_agenda", {
22
+ postId: import("drizzle-orm/pg-core").PgColumn<{
23
+ name: "post_id";
24
+ tableName: "event_agenda";
25
+ dataType: "string";
26
+ columnType: "PgUUID";
27
+ data: string;
28
+ driverParam: string;
29
+ notNull: true;
30
+ hasDefault: false;
31
+ isPrimaryKey: false;
32
+ isAutoincrement: false;
33
+ hasRuntimeDefault: false;
34
+ enumValues: undefined;
35
+ baseColumn: never;
36
+ identity: undefined;
37
+ generated: undefined;
38
+ }, {}, {}>;
39
+ recurrenceId: import("drizzle-orm/pg-core").PgColumn<{
40
+ name: "recurrence_id";
41
+ tableName: "event_agenda";
42
+ dataType: "string";
43
+ columnType: "PgTimestampString";
44
+ data: string;
45
+ driverParam: string;
46
+ notNull: true;
47
+ hasDefault: false;
48
+ isPrimaryKey: false;
49
+ isAutoincrement: false;
50
+ hasRuntimeDefault: false;
51
+ enumValues: undefined;
52
+ baseColumn: never;
53
+ identity: undefined;
54
+ generated: undefined;
55
+ }, {}, {}>;
56
+ start: import("drizzle-orm/pg-core").PgColumn<{
57
+ name: "start";
58
+ tableName: "event_agenda";
59
+ dataType: "string";
60
+ columnType: "PgTimestampString";
61
+ data: string;
62
+ driverParam: string;
63
+ notNull: true;
64
+ hasDefault: false;
65
+ isPrimaryKey: false;
66
+ isAutoincrement: false;
67
+ hasRuntimeDefault: false;
68
+ enumValues: undefined;
69
+ baseColumn: never;
70
+ identity: undefined;
71
+ generated: undefined;
72
+ }, {}, {}>;
73
+ end: import("drizzle-orm/pg-core").PgColumn<{
74
+ name: "end";
75
+ tableName: "event_agenda";
76
+ dataType: "string";
77
+ columnType: "PgTimestampString";
78
+ data: string;
79
+ driverParam: string;
80
+ notNull: false;
81
+ hasDefault: false;
82
+ isPrimaryKey: false;
83
+ isAutoincrement: false;
84
+ hasRuntimeDefault: false;
85
+ enumValues: undefined;
86
+ baseColumn: never;
87
+ identity: undefined;
88
+ generated: undefined;
89
+ }, {}, {}>;
90
+ }, "partial", Record<"event_agenda", "not-null">, false, "limit" | "offset" | "orderBy", {
91
+ postId: string;
92
+ recurrenceId: string;
93
+ start: string;
94
+ end: string | null;
95
+ }[], {
96
+ postId: import("drizzle-orm/pg-core").PgColumn<{
97
+ name: "post_id";
98
+ tableName: "event_agenda";
99
+ dataType: "string";
100
+ columnType: "PgUUID";
101
+ data: string;
102
+ driverParam: string;
103
+ notNull: true;
104
+ hasDefault: false;
105
+ isPrimaryKey: false;
106
+ isAutoincrement: false;
107
+ hasRuntimeDefault: false;
108
+ enumValues: undefined;
109
+ baseColumn: never;
110
+ identity: undefined;
111
+ generated: undefined;
112
+ }, {}, {}>;
113
+ recurrenceId: import("drizzle-orm/pg-core").PgColumn<{
114
+ name: "recurrence_id";
115
+ tableName: "event_agenda";
116
+ dataType: "string";
117
+ columnType: "PgTimestampString";
118
+ data: string;
119
+ driverParam: string;
120
+ notNull: true;
121
+ hasDefault: false;
122
+ isPrimaryKey: false;
123
+ isAutoincrement: false;
124
+ hasRuntimeDefault: false;
125
+ enumValues: undefined;
126
+ baseColumn: never;
127
+ identity: undefined;
128
+ generated: undefined;
129
+ }, {}, {}>;
130
+ start: import("drizzle-orm/pg-core").PgColumn<{
131
+ name: "start";
132
+ tableName: "event_agenda";
133
+ dataType: "string";
134
+ columnType: "PgTimestampString";
135
+ data: string;
136
+ driverParam: string;
137
+ notNull: true;
138
+ hasDefault: false;
139
+ isPrimaryKey: false;
140
+ isAutoincrement: false;
141
+ hasRuntimeDefault: false;
142
+ enumValues: undefined;
143
+ baseColumn: never;
144
+ identity: undefined;
145
+ generated: undefined;
146
+ }, {}, {}>;
147
+ end: import("drizzle-orm/pg-core").PgColumn<{
148
+ name: "end";
149
+ tableName: "event_agenda";
150
+ dataType: "string";
151
+ columnType: "PgTimestampString";
152
+ data: string;
153
+ driverParam: string;
154
+ notNull: false;
155
+ hasDefault: false;
156
+ isPrimaryKey: false;
157
+ isAutoincrement: false;
158
+ hasRuntimeDefault: false;
159
+ enumValues: undefined;
160
+ baseColumn: never;
161
+ identity: undefined;
162
+ generated: undefined;
163
+ }, {}, {}>;
164
+ }>, "limit" | "offset" | "orderBy">;
165
+ export declare const listEventAgenda: (authData: AuthorizationData, window: EventAgendaWindow, { offset, limit, jamOnly, mine, groupId, }?: EventAgendaOptions) => Promise<PostWithMeta[]>;