@openpeepshq/core 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,8 +32,9 @@ export declare const listLeftConversations: (authData: AuthorizationData) => Pro
32
32
  * Conversation detail: root plus newest capped descendants (lean mapping +
33
33
  * seenBatch). Prefer newest messages so long DMs stay usable.
34
34
  */
35
- export declare const getConversationThread: (root: PostWithMeta, authData: AuthorizationData, { limit }?: {
35
+ export declare const getConversationThread: (root: PostWithMeta, authData: AuthorizationData, { limit, focusId, }?: {
36
36
  limit?: number;
37
+ focusId?: string;
37
38
  }) => Promise<PostWithMeta[]>;
38
39
  /**
39
40
  * All post ids in the 1:1 conversation between two profiles, oldest first:
@@ -55,7 +56,39 @@ export declare const listOneToOneConversationRootLeaves: (db: PgDb, profileAId:
55
56
  * Merged 1:1 conversation: every message for the pair across all roots,
56
57
  * oldest first. Any post of the conversation (typically the root in the URL)
57
58
  * resolves to the same list. Capped like {@link getConversationThread}:
58
- * the oldest message plus the newest CONTEXT_NODE_CAP others.
59
+ * the oldest message plus the newest CONTEXT_NODE_CAP others. `focusId`,
60
+ * when it belongs to the pair, is included even if it falls outside that window.
59
61
  */
60
- export declare const getOneToOneConversation: (post: PostWithMeta, authData: AuthorizationData) => Promise<PostWithMeta[]>;
62
+ export declare const getOneToOneConversation: (post: PostWithMeta, authData: AuthorizationData, { focusId }?: {
63
+ focusId?: string;
64
+ }) => Promise<PostWithMeta[]>;
65
+ /** Keep `focusId` in a capped id list when it is part of the full conversation. */
66
+ export declare const includeFocusMessage: (capped: string[], all: string[], focusId?: string) => string[];
67
+ /** True when `postId` is `rootId` or a reply descendant of it. */
68
+ export declare const conversationIncludesPost: (db: PgDb, rootId: string, postId: string) => Promise<boolean>;
69
+ export type DirectMessageSearchRow = {
70
+ messageId: string;
71
+ rootId: string;
72
+ };
73
+ /**
74
+ * Direct posts the profile authored or is an audience of, whose text matches
75
+ * `query`. Optional `conversation` limits the match to that thread. Newest
76
+ * uuidv7 id first. Each row's `rootId` is the reply-graph root to open.
77
+ * Only the newest `limit` matches resolve their roots, so the upward walk
78
+ * stays bounded no matter how many posts match the text.
79
+ */
80
+ export declare const searchDirectMessageRows: (db: PgDb, profileId: string, query: string, options?: {
81
+ conversation?: PostWithMeta;
82
+ limit?: number;
83
+ }) => Promise<DirectMessageSearchRow[]>;
84
+ /**
85
+ * Message search for the viewer's direct conversations. Hidden and blocked
86
+ * 1:1 threads are dropped after hydration, matching the inbox.
87
+ */
88
+ export declare const searchDirectMessages: (authData: AuthorizationData, query: string, options?: {
89
+ conversation?: PostWithMeta;
90
+ }) => Promise<{
91
+ conversationId: string;
92
+ message: PostWithMeta;
93
+ }[]>;
61
94
  export {};
@@ -1,10 +1,11 @@
1
1
  import { sql } from 'drizzle-orm';
2
- import { blockedPairIds, isOneToOneDm, isOneToOneWithBlocked, participantIds, toHiddenPost, } from '@openpeepshq/common/lib';
2
+ import { blockedPairIds, isHiddenPost, isOneToOneDm, isOneToOneWithBlocked, participantIds, toHiddenPost, } from '@openpeepshq/common/lib';
3
3
  import { allpeepDb } from '../db/index.js';
4
4
  import { fetchRowsByIds, hydrateMapData } from '../db/pg/map/relations.js';
5
5
  import { capabilitiesConfig } from '../config/index.js';
6
6
  import { canReadPost, transformPost } from './helpers/index.js';
7
7
  import { CONTEXT_NODE_CAP, collectReplyClosureIds } from './contextClosure.js';
8
+ import { findReplyRootId } from './activity.js';
8
9
  import { postContextMappingForProfile } from './mapping.js';
9
10
  /** Root + newest leaf per DM thread the profile is in (ids only). */
10
11
  export const listConversationRootLeafPairs = async (db, profileId) => {
@@ -217,13 +218,20 @@ export const listLeftConversations = async (authData) => {
217
218
  * Conversation detail: root plus newest capped descendants (lean mapping +
218
219
  * seenBatch). Prefer newest messages so long DMs stay usable.
219
220
  */
220
- export const getConversationThread = async (root, authData, { limit = CONTEXT_NODE_CAP } = {}) => {
221
+ export const getConversationThread = async (root, authData, { limit = CONTEXT_NODE_CAP, focusId, } = {}) => {
221
222
  const { db } = await allpeepDb();
222
- const newestIds = await collectReplyClosureIds(db, root.id, 'descendents', {
223
+ let newestIds = await collectReplyClosureIds(db, root.id, 'descendents', {
223
224
  maxDepth: 9999,
224
225
  limit,
225
226
  newestFirst: true,
226
227
  });
228
+ // Long threads only keep the newest window. A search hit older than that
229
+ // window still has to be loaded, but only if it belongs to this thread.
230
+ if (focusId && focusId !== root.id && !newestIds.includes(focusId)) {
231
+ if (await conversationIncludesPost(db, root.id, focusId)) {
232
+ newestIds = includeFocusMessage(newestIds, [...newestIds, focusId], focusId);
233
+ }
234
+ }
227
235
  const byId = await hydrateLeanPostsByIds(authData, newestIds);
228
236
  const ordered = newestIds
229
237
  .map((id) => byId.get(id))
@@ -236,24 +244,33 @@ export const getConversationThread = async (root, authData, { limit = CONTEXT_NO
236
244
  * exactly the pair — tolerates legacy rows where the creator is not in the
237
245
  * audience edge set.
238
246
  */
239
- const oneToOnePairPost = (profileAId, profileBId) => sql `
240
- p.visibility = 'direct'
241
- AND p.deleted_at IS NULL
247
+ const sqlAlias = (alias) => {
248
+ if (!/^[a-z][a-z0-9]*$/.test(alias)) {
249
+ throw new Error('Invalid SQL alias');
250
+ }
251
+ return sql.raw(alias);
252
+ };
253
+ const oneToOnePairPost = (profileAId, profileBId, alias = 'p') => {
254
+ const table = sqlAlias(alias);
255
+ return sql `
256
+ ${table}.visibility = 'direct'
257
+ AND ${table}.deleted_at IS NULL
242
258
  AND NOT EXISTS (
243
259
  SELECT 1 FROM audience a
244
- WHERE a.from_id = p.id::text
260
+ WHERE a.from_id = ${table}.id::text
245
261
  AND a.to_id <> ${profileAId}
246
262
  AND a.to_id <> ${profileBId}
247
263
  )
248
- AND (p.creator_id = ${profileAId} OR EXISTS (
264
+ AND (${table}.creator_id = ${profileAId} OR EXISTS (
249
265
  SELECT 1 FROM audience a
250
- WHERE a.from_id = p.id::text AND a.to_id = ${profileAId}
266
+ WHERE a.from_id = ${table}.id::text AND a.to_id = ${profileAId}
251
267
  ))
252
- AND (p.creator_id = ${profileBId} OR EXISTS (
268
+ AND (${table}.creator_id = ${profileBId} OR EXISTS (
253
269
  SELECT 1 FROM audience a
254
- WHERE a.from_id = p.id::text AND a.to_id = ${profileBId}
270
+ WHERE a.from_id = ${table}.id::text AND a.to_id = ${profileBId}
255
271
  ))
256
272
  `;
273
+ };
257
274
  /**
258
275
  * All post ids in the 1:1 conversation between two profiles, oldest first:
259
276
  * every post of the pair, plus their reply descendants (e.g. system "left"
@@ -315,9 +332,10 @@ export const listOneToOneConversationRootLeaves = async (db, profileAId, profile
315
332
  * Merged 1:1 conversation: every message for the pair across all roots,
316
333
  * oldest first. Any post of the conversation (typically the root in the URL)
317
334
  * resolves to the same list. Capped like {@link getConversationThread}:
318
- * the oldest message plus the newest CONTEXT_NODE_CAP others.
335
+ * the oldest message plus the newest CONTEXT_NODE_CAP others. `focusId`,
336
+ * when it belongs to the pair, is included even if it falls outside that window.
319
337
  */
320
- export const getOneToOneConversation = async (post, authData) => {
338
+ export const getOneToOneConversation = async (post, authData, { focusId } = {}) => {
321
339
  const { db } = await allpeepDb();
322
340
  const [profileAId, profileBId] = [...participantIds(post)];
323
341
  const ids = await listOneToOneConversationPostIds(db, profileAId, profileBId);
@@ -326,8 +344,176 @@ export const getOneToOneConversation = async (post, authData) => {
326
344
  const capped = ids.length > CONTEXT_NODE_CAP + 1
327
345
  ? [ids[0], ...ids.slice(-CONTEXT_NODE_CAP)]
328
346
  : ids;
329
- const byId = await hydrateLeanPostsByIds(authData, [...new Set(capped)]);
330
- return capped
347
+ const withFocus = includeFocusMessage(capped, ids, focusId);
348
+ const byId = await hydrateLeanPostsByIds(authData, [...new Set(withFocus)]);
349
+ return withFocus
331
350
  .map((id) => byId.get(id))
332
351
  .filter((message) => !!message);
333
352
  };
353
+ const byUuidAsc = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
354
+ /** Keep `focusId` in a capped id list when it is part of the full conversation. */
355
+ export const includeFocusMessage = (capped, all, focusId) => {
356
+ if (!focusId || capped.includes(focusId) || !all.includes(focusId)) {
357
+ return capped;
358
+ }
359
+ return [...capped, focusId].sort(byUuidAsc);
360
+ };
361
+ /** True when `postId` is `rootId` or a reply descendant of it. */
362
+ export const conversationIncludesPost = async (db, rootId, postId) => {
363
+ if (rootId === postId)
364
+ return true;
365
+ const result = (await db.execute(sql `
366
+ WITH RECURSIVE thread AS (
367
+ SELECT ${rootId}::text AS id, 0 AS depth
368
+ UNION ALL
369
+ SELECT rt.from_id, thread.depth + 1
370
+ FROM reply_to rt
371
+ INNER JOIN thread ON rt.to_id = thread.id
372
+ WHERE thread.depth < 9999
373
+ )
374
+ SELECT id
375
+ FROM thread
376
+ WHERE id = ${postId}
377
+ LIMIT 1
378
+ `));
379
+ return result.rows.length > 0;
380
+ };
381
+ const DIRECT_MESSAGE_SEARCH_LIMIT = 30;
382
+ const escapeLike = (value) => value.replace(/[\\%_]/g, '\\$&');
383
+ // plainto_tsquery of a punctuation-only string is empty, and `@@` against an
384
+ // empty tsquery errors on some Postgres versions. Substring match still works.
385
+ const hasSearchWord = (value) => /[\p{L}\p{N}]/u.test(value);
386
+ const conversationScopeSql = async (db, post) => {
387
+ if (post.visibility !== 'direct')
388
+ return sql `AND false`;
389
+ if (isOneToOneDm(post)) {
390
+ const [profileAId, profileBId] = [...participantIds(post)];
391
+ if (!profileAId || !profileBId)
392
+ return sql `AND false`;
393
+ return sql `AND p.id::text IN (
394
+ WITH RECURSIVE pair_posts AS (
395
+ SELECT p2.id::text AS id
396
+ FROM posts p2
397
+ WHERE ${oneToOnePairPost(profileAId, profileBId, 'p2')}
398
+ ),
399
+ pair_walk AS (
400
+ SELECT id FROM pair_posts
401
+ UNION ALL
402
+ SELECT rt.from_id::text
403
+ FROM reply_to rt
404
+ INNER JOIN pair_walk ON rt.to_id = pair_walk.id
405
+ )
406
+ SELECT id FROM pair_walk
407
+ )`;
408
+ }
409
+ const rootId = await findReplyRootId(db, post.id);
410
+ return sql `AND p.id::text IN (
411
+ WITH RECURSIVE thread AS (
412
+ SELECT ${rootId}::text AS id
413
+ UNION ALL
414
+ SELECT rt.from_id
415
+ FROM reply_to rt
416
+ INNER JOIN thread ON rt.to_id = thread.id
417
+ )
418
+ SELECT id FROM thread
419
+ )`;
420
+ };
421
+ /**
422
+ * Direct posts the profile authored or is an audience of, whose text matches
423
+ * `query`. Optional `conversation` limits the match to that thread. Newest
424
+ * uuidv7 id first. Each row's `rootId` is the reply-graph root to open.
425
+ * Only the newest `limit` matches resolve their roots, so the upward walk
426
+ * stays bounded no matter how many posts match the text.
427
+ */
428
+ export const searchDirectMessageRows = async (db, profileId, query, options = {}) => {
429
+ const trimmed = query.trim();
430
+ if (trimmed.length < 2)
431
+ return [];
432
+ const limit = Math.min(Math.max(options.limit ?? DIRECT_MESSAGE_SEARCH_LIMIT, 1), 50);
433
+ const like = `%${escapeLike(trimmed)}%`;
434
+ const ilikeMatch = sql `(
435
+ COALESCE(p.body->>'content', '') ILIKE ${like} ESCAPE '\\'
436
+ OR COALESCE(p.body->>'name', '') ILIKE ${like} ESCAPE '\\'
437
+ OR COALESCE(p.body->>'title', '') ILIKE ${like} ESCAPE '\\'
438
+ )`;
439
+ const textMatch = hasSearchWord(trimmed)
440
+ ? sql `(
441
+ p.search_vector @@ plainto_tsquery('english', ${trimmed})
442
+ OR ${ilikeMatch}
443
+ )`
444
+ : ilikeMatch;
445
+ const scope = options.conversation
446
+ ? await conversationScopeSql(db, options.conversation)
447
+ : sql ``;
448
+ const result = (await db.execute(sql `
449
+ WITH RECURSIVE visible AS (
450
+ SELECT id
451
+ FROM (
452
+ SELECT p.id::text AS id
453
+ FROM posts p
454
+ WHERE p.deleted_at IS NULL
455
+ AND p.visibility = 'direct'
456
+ AND (
457
+ p.creator_id = ${profileId}
458
+ OR EXISTS (
459
+ SELECT 1 FROM audience a
460
+ WHERE a.from_id = p.id::text AND a.to_id = ${profileId}
461
+ )
462
+ )
463
+ AND ${textMatch}
464
+ ${scope}
465
+ ORDER BY p.id::text DESC
466
+ LIMIT ${limit}
467
+ ) candidates
468
+ ),
469
+ walk AS (
470
+ SELECT id AS message_id, id AS node_id, 0 AS depth
471
+ FROM visible
472
+ UNION ALL
473
+ SELECT walk.message_id, rt.to_id, walk.depth + 1
474
+ FROM reply_to rt
475
+ INNER JOIN walk ON rt.from_id = walk.node_id
476
+ WHERE walk.depth < 9999
477
+ ),
478
+ roots AS (
479
+ SELECT DISTINCT ON (message_id) message_id, node_id AS root_id
480
+ FROM walk
481
+ ORDER BY message_id, depth DESC
482
+ )
483
+ SELECT message_id, root_id
484
+ FROM roots
485
+ ORDER BY message_id DESC
486
+ LIMIT ${limit}
487
+ `));
488
+ return result.rows.flatMap((row) => {
489
+ const messageId = row.message_id;
490
+ const rootId = row.root_id;
491
+ if (typeof messageId !== 'string' || typeof rootId !== 'string')
492
+ return [];
493
+ return [{ messageId, rootId }];
494
+ });
495
+ };
496
+ /**
497
+ * Message search for the viewer's direct conversations. Hidden and blocked
498
+ * 1:1 threads are dropped after hydration, matching the inbox.
499
+ */
500
+ export const searchDirectMessages = async (authData, query, options = {}) => {
501
+ const profile = authData.profile;
502
+ if (!profile) {
503
+ throw new Error('AuthorizationData.profile is required for this finder');
504
+ }
505
+ const { db } = await allpeepDb();
506
+ const hits = await searchDirectMessageRows(db, profile.id, query, options);
507
+ if (!hits.length)
508
+ return [];
509
+ const byId = await hydrateLeanPostsByIds(authData, hits.map((hit) => hit.messageId));
510
+ const blocked = new Set(blockedPairIds(profile));
511
+ return hits.flatMap((hit) => {
512
+ const message = byId.get(hit.messageId);
513
+ if (!message || isHiddenPost(message))
514
+ return [];
515
+ if (isOneToOneWithBlocked(message, profile, blocked))
516
+ return [];
517
+ return [{ conversationId: hit.rootId, message }];
518
+ });
519
+ };
@@ -368,7 +368,9 @@ export declare const getConversationByEnd: (post: PostWithMeta, authData: Author
368
368
  * any root — or even the system "left" post — of the pair resolves to the
369
369
  * same view. Group conversations stay per root.
370
370
  */
371
- export declare const getConversationByStart: (post: PostWithMeta, authData: AuthorizationData) => Promise<PostWithMeta[]>;
371
+ export declare const getConversationByStart: (post: PostWithMeta, authData: AuthorizationData, options?: {
372
+ focusId?: string;
373
+ }) => Promise<PostWithMeta[]>;
372
374
  /** Newest post across all roots of a 1:1 conversation (uuidv7-ordered). */
373
375
  export declare const findLatestOneToOnePostId: (post: PostWithMeta) => Promise<string>;
374
376
  /** Full ancestor/descendant trees for post detail (CTE + lean mapping). */
@@ -291,13 +291,13 @@ export const getConversationByEnd = async (post, authData) => ancestors(authData
291
291
  * any root — or even the system "left" post — of the pair resolves to the
292
292
  * same view. Group conversations stay per root.
293
293
  */
294
- export const getConversationByStart = async (post, authData) => {
294
+ export const getConversationByStart = async (post, authData, options) => {
295
295
  if (isOneToOneDm(post)) {
296
- const conversation = await getOneToOneConversation(post, authData);
296
+ const conversation = await getOneToOneConversation(post, authData, options);
297
297
  if (conversation.length > 0)
298
298
  return conversation;
299
299
  }
300
- return getConversationThread(post, authData);
300
+ return getConversationThread(post, authData, options);
301
301
  };
302
302
  /** Newest post across all roots of a 1:1 conversation (uuidv7-ordered). */
303
303
  export const findLatestOneToOnePostId = async (post) => {
@@ -3,7 +3,7 @@ export * from './mutations';
3
3
  export * from './mapping';
4
4
  export { CONTEXT_NODE_CAP, collectReplyClosureIds, loadReplyContextPosts, } from './contextClosure';
5
5
  export { loadThreadPreviewReplies, THREAD_PREVIEW_LIMIT, } from './threadPreview';
6
- export { listConversationPreviews, getConversationThread, getOneToOneConversation, listOneToOneConversationPostIds, listOneToOneConversationRootLeaves, findLatestThreadPostId, listLeftConversations, } from './conversationQueries';
6
+ export { listConversationPreviews, getConversationThread, getOneToOneConversation, listOneToOneConversationPostIds, listOneToOneConversationRootLeaves, findLatestThreadPostId, listLeftConversations, searchDirectMessages, } from './conversationQueries';
7
7
  export * from './helpers';
8
8
  export { bumpConversationActivity, findReplyRootId } from './activity';
9
9
  export { registerRsvpConfirmationEmail } from './rsvpConfirmationEmail';
@@ -3,7 +3,7 @@ export * from './mutations.js';
3
3
  export * from './mapping.js';
4
4
  export { CONTEXT_NODE_CAP, collectReplyClosureIds, loadReplyContextPosts, } from './contextClosure.js';
5
5
  export { loadThreadPreviewReplies, THREAD_PREVIEW_LIMIT, } from './threadPreview.js';
6
- export { listConversationPreviews, getConversationThread, getOneToOneConversation, listOneToOneConversationPostIds, listOneToOneConversationRootLeaves, findLatestThreadPostId, listLeftConversations, } from './conversationQueries.js';
6
+ export { listConversationPreviews, getConversationThread, getOneToOneConversation, listOneToOneConversationPostIds, listOneToOneConversationRootLeaves, findLatestThreadPostId, listLeftConversations, searchDirectMessages, } from './conversationQueries.js';
7
7
  export * from './helpers/index.js';
8
8
  export { bumpConversationActivity, findReplyRootId } from './activity.js';
9
9
  export { registerRsvpConfirmationEmail } from './rsvpConfirmationEmail.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "dependencies": {
@@ -37,10 +37,10 @@
37
37
  "type-fest": "^4.31.0",
38
38
  "uuidv7": "^1.0.2",
39
39
  "web-push": "^3.6.7",
40
- "@openpeepshq/common": "0.4.0",
41
- "@openpeepshq/fetch-client": "^0.2.1",
40
+ "@openpeepshq/common": "0.5.0",
42
41
  "@openpeepshq/geocoder": "^0.1.2",
43
- "@openpeepshq/i18n": "^0.3.2"
42
+ "@openpeepshq/fetch-client": "^0.2.1",
43
+ "@openpeepshq/i18n": "^0.4.0"
44
44
  },
45
45
  "main": "dist/index.js",
46
46
  "types": "dist/index.d.ts",