@openpeepshq/common 0.4.0 → 0.5.11

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 (69) hide show
  1. package/dist/lib/adminSections.d.ts +4 -0
  2. package/dist/lib/adminSections.js +5 -0
  3. package/dist/lib/attachmentHelpers.js +5 -1
  4. package/dist/lib/capabilitiesHelpers.d.ts +9 -0
  5. package/dist/lib/capabilitiesHelpers.js +9 -0
  6. package/dist/lib/csvHelpers.d.ts +2 -0
  7. package/dist/lib/csvHelpers.js +13 -0
  8. package/dist/lib/eventRecurrence.d.ts +9 -0
  9. package/dist/lib/eventRecurrence.js +17 -9
  10. package/dist/lib/eventWaitlist.d.ts +58 -0
  11. package/dist/lib/eventWaitlist.js +217 -0
  12. package/dist/lib/index.d.ts +1 -0
  13. package/dist/lib/index.js +1 -0
  14. package/dist/lib/markdownHelpers.d.ts +12 -3
  15. package/dist/lib/markdownHelpers.js +115 -6
  16. package/dist/lib/postHelpers.d.ts +35 -5
  17. package/dist/lib/postHelpers.js +85 -10
  18. package/dist/lib/profileHelpers.d.ts +12 -2
  19. package/dist/lib/profileHelpers.js +24 -3
  20. package/dist/lib/resources.d.ts +29 -1
  21. package/dist/lib/resources.js +74 -2
  22. package/dist/lib/utils.js +11 -11
  23. package/dist/types/admin-livekit.d.ts +23 -0
  24. package/dist/types/admin-livekit.js +18 -0
  25. package/dist/types/admin-media.d.ts +41 -0
  26. package/dist/types/admin-media.js +20 -0
  27. package/dist/types/api.d.ts +19945 -3526
  28. package/dist/types/api.js +15 -9
  29. package/dist/types/capabilities.d.ts +2 -2
  30. package/dist/types/capabilities.js +3 -0
  31. package/dist/types/config.d.ts +3 -0
  32. package/dist/types/config.js +6 -0
  33. package/dist/types/db.d.ts +65 -22
  34. package/dist/types/forbiddenHandles.d.ts +28 -0
  35. package/dist/types/forbiddenHandles.js +75 -0
  36. package/dist/types/index.d.ts +2 -0
  37. package/dist/types/index.js +2 -0
  38. package/dist/types/internal.d.ts +163 -44
  39. package/dist/types/models.d.ts +28 -14
  40. package/dist/types/models.js +27 -28
  41. package/dist/types/notifications.d.ts +2 -0
  42. package/dist/types/notifications.js +4 -2
  43. package/dist/types/roleDefaults.js +109 -95
  44. package/dist/types/stats.d.ts +348 -108
  45. package/package.json +7 -6
  46. package/src/lib/adminSections.ts +5 -0
  47. package/src/lib/attachmentHelpers.ts +18 -12
  48. package/src/lib/capabilitiesHelpers.ts +15 -0
  49. package/src/lib/csvHelpers.ts +19 -3
  50. package/src/lib/eventRecurrence.ts +19 -10
  51. package/src/lib/eventWaitlist.ts +325 -0
  52. package/src/lib/index.ts +1 -0
  53. package/src/lib/markdownHelpers.ts +121 -7
  54. package/src/lib/postHelpers.ts +129 -11
  55. package/src/lib/profileHelpers.ts +38 -3
  56. package/src/lib/resources.ts +105 -2
  57. package/src/lib/utils.ts +40 -31
  58. package/src/types/admin-livekit.ts +24 -0
  59. package/src/types/admin-media.ts +29 -0
  60. package/src/types/api.ts +19 -9
  61. package/src/types/auth.ts +2 -2
  62. package/src/types/capabilities.ts +3 -0
  63. package/src/types/config.ts +6 -0
  64. package/src/types/forbiddenHandles.ts +103 -0
  65. package/src/types/index.ts +2 -0
  66. package/src/types/models.ts +53 -33
  67. package/src/types/notifications.ts +7 -7
  68. package/src/types/roleDefaults.ts +115 -96
  69. package/src/types/stripe.ts +3 -1
@@ -29,12 +29,15 @@ import {
29
29
  } from './eventRecurrence';
30
30
  import { formatEventWhen } from './eventTime';
31
31
  import {
32
+ checkCapabilities,
32
33
  checkGroupCapabilities,
33
34
  checkPostCapabilities,
34
35
  checkRoleCapabilities,
36
+ getGroupCapabilities,
35
37
  } from './capabilitiesHelpers';
36
38
  import { scopeMatches } from './scopeHelpers';
37
39
  import { countBy, dateSorter, groupBy, transformValues } from './utils';
40
+ import { truncateText } from './text';
38
41
 
39
42
  const buildThread = (rootPost: PublicPost, postList: PublicPost[]): Thread => ({
40
43
  ...rootPost,
@@ -498,6 +501,11 @@ export const displayRsvpForProfile = (
498
501
  },
499
502
  ): PublicRsvp | undefined => {
500
503
  const event = post.data?.type === 'event' ? post.data : undefined;
504
+ // One-time events have no occurrences. Older claims stamped the start time
505
+ // onto some RSVPs; a newer unscoped waitlist must still be the current one.
506
+ if (event && !event.recurrence) {
507
+ return getEffectiveRsvp(post, profileId);
508
+ }
501
509
  const scopedId = options?.lockToOccurrence
502
510
  ? options.recurrenceId
503
511
  : event
@@ -521,6 +529,9 @@ export const displayRsvpForProfile = (
521
529
 
522
530
  export const isCapacityEvent = (event: Event) => !!event.maxAttendees;
523
531
 
532
+ export const DEFAULT_WAITLIST_OFFER_MINUTES = 60;
533
+ export const MAX_WAITLIST_OFFER_MINUTES = 7 * 24 * 60;
534
+
524
535
  export const parseEventMaxAttendeesInput = (
525
536
  raw: string,
526
537
  ): number | undefined => {
@@ -530,8 +541,25 @@ export const parseEventMaxAttendeesInput = (
530
541
  return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
531
542
  };
532
543
 
544
+ export const normalizeWaitlistOfferMinutes = (
545
+ value: number | null | undefined,
546
+ ): number | undefined => {
547
+ if (value == null || !Number.isFinite(value)) return undefined;
548
+ const minutes = Math.trunc(value);
549
+ if (minutes < 1 || minutes > MAX_WAITLIST_OFFER_MINUTES) return undefined;
550
+ return minutes;
551
+ };
552
+
553
+ export const parseEventWaitlistOfferMinutesInput = (
554
+ raw: string,
555
+ ): number | undefined => {
556
+ const trimmed = raw.trim();
557
+ if (!trimmed) return undefined;
558
+ return normalizeWaitlistOfferMinutes(Number.parseInt(trimmed, 10));
559
+ };
560
+
533
561
  export const withoutEventMaxAttendees = <T extends Event>(event: T): T => {
534
- const { maxAttendees: _, ...rest } = event;
562
+ const { maxAttendees: _, waitlistOfferMinutes: __, ...rest } = event;
535
563
  return rest as T;
536
564
  };
537
565
 
@@ -544,33 +572,52 @@ export const normalizeEventDataForSave = <T extends Event>(event: T): T => {
544
572
  ) {
545
573
  return withoutEventMaxAttendees(event);
546
574
  }
547
- return { ...event, maxAttendees: Math.trunc(maxAttendees) };
575
+ const minutes = normalizeWaitlistOfferMinutes(event.waitlistOfferMinutes);
576
+ const { waitlistOfferMinutes: _, ...rest } = event;
577
+ return {
578
+ ...rest,
579
+ maxAttendees: Math.trunc(maxAttendees),
580
+ ...(minutes != null ? { waitlistOfferMinutes: minutes } : {}),
581
+ } as T;
548
582
  };
549
583
 
550
584
  /** Null capacity means it was cleared; strip for validation/output. */
551
585
  export const normalizeEventDataFromDb = <T extends Event>(event: T): T => {
552
- if (event.maxAttendees != null) {
553
- return event;
554
- }
555
- return withoutEventMaxAttendees(event);
586
+ const { maxAttendees, waitlistOfferMinutes, ...rest } = event;
587
+ return {
588
+ ...rest,
589
+ ...(maxAttendees != null ? { maxAttendees } : {}),
590
+ ...(waitlistOfferMinutes != null ? { waitlistOfferMinutes } : {}),
591
+ } as T;
556
592
  };
557
593
 
558
594
  export const normalizePostDataFromDb = (data: PostDataUnion): PostDataUnion =>
559
595
  data.type === 'event' ? normalizeEventDataFromDb(data) : data;
560
596
 
561
- /** Nested `data` updates send null to remove maxAttendees. */
562
- export type EventDbUpdate = Omit<Event, 'maxAttendees'> & {
597
+ /** Nested `data` updates send null to remove cleared capacity fields. */
598
+ export type EventDbUpdate = Omit<
599
+ Event,
600
+ 'maxAttendees' | 'waitlistOfferMinutes'
601
+ > & {
563
602
  maxAttendees?: number | null;
603
+ waitlistOfferMinutes?: number | null;
564
604
  };
565
605
 
566
606
  export const eventDataForDbUpdate = (
567
607
  previous: Event | undefined,
568
608
  normalized: Event,
569
609
  ): EventDbUpdate => {
610
+ let next: EventDbUpdate = normalized;
570
611
  if (previous?.maxAttendees != null && !('maxAttendees' in normalized)) {
571
- return { ...normalized, maxAttendees: null };
612
+ next = { ...next, maxAttendees: null };
613
+ }
614
+ if (
615
+ previous?.waitlistOfferMinutes != null &&
616
+ !('waitlistOfferMinutes' in normalized)
617
+ ) {
618
+ next = { ...next, waitlistOfferMinutes: null };
572
619
  }
573
- return normalized;
620
+ return next;
574
621
  };
575
622
 
576
623
  export const canManageEventRsvps = (
@@ -610,6 +657,16 @@ export const getJamCapacityJoinBlock = (
610
657
  if (countYesRsvps(post, recurrenceId) >= event.maxAttendees) {
611
658
  return { blocked: true, reason: 'full' };
612
659
  }
660
+ // A freed seat stays reserved for the waitlist unless this profile holds the offer.
661
+ const waiting = calculateEffectiveRsvps(post, recurrenceId).filter(
662
+ (rsvp) => rsvp.response === 'waitlist' && rsvp.profile.type !== 'federated',
663
+ );
664
+ const mine = waiting.find((rsvp) => rsvp.profile.id === profile.id);
665
+ const offerOpen =
666
+ !!mine?.offerExpiresAt && Date.parse(mine.offerExpiresAt) > Date.now();
667
+ if (waiting.length > 0 && !offerOpen) {
668
+ return { blocked: true, reason: 'full' };
669
+ }
613
670
  return { blocked: true, reason: 'rsvp-required' };
614
671
  };
615
672
 
@@ -678,6 +735,32 @@ export const canCreatePostType = (
678
735
  canCreatePostTypeWithVisibility(authData, type, visibility),
679
736
  );
680
737
 
738
+ /**
739
+ * Scope-free variant of {@link canCreatePostType}: may this profile create a
740
+ * post of `type` in any of `visibilities`, judging capabilities only. Token
741
+ * scopes load after the first paint in the clients, so gating UI on them would
742
+ * flash a denial for allowed users; the create endpoints still enforce
743
+ * scopes.
744
+ */
745
+ export const canCreatePostTypeIgnoringScopes = (
746
+ authData: AuthorizationData,
747
+ type: PostType,
748
+ visibilities: readonly VisibilityType[] = visibilityTypeValues,
749
+ ) =>
750
+ visibilities.some((visibility) =>
751
+ visibility === 'group'
752
+ ? !!authData.profile?.memberships?.some(
753
+ (m) =>
754
+ checkCapabilities(
755
+ [`core-posts-create-${type}`],
756
+ getGroupCapabilities(authData, m.group as GroupWithMeta),
757
+ ).success,
758
+ )
759
+ : checkRoleCapabilities(authData.profile?.roles, [
760
+ `core-posts-create-${type}-${visibility}`,
761
+ ]).success,
762
+ );
763
+
681
764
  export type PostActionAvailability = {
682
765
  canReply: boolean;
683
766
  canRepost: boolean;
@@ -754,7 +837,7 @@ export const toHiddenPost = <
754
837
  export const isHiddenPost = (post: { hidden?: boolean }): boolean =>
755
838
  !!post.hidden;
756
839
 
757
- const participantIds = (
840
+ export const participantIds = (
758
841
  post: Pick<PublicPost, 'audience' | 'profile'> & { creatorId?: string },
759
842
  ): Set<string> => {
760
843
  const ids = new Set(
@@ -765,6 +848,13 @@ const participantIds = (
765
848
  return ids;
766
849
  };
767
850
 
851
+ /** Direct message between exactly two participants. */
852
+ export const isOneToOneDm = (
853
+ post: Pick<PublicPost, 'visibility' | 'audience' | 'profile'> & {
854
+ creatorId?: string;
855
+ },
856
+ ): boolean => post.visibility === 'direct' && participantIds(post).size === 2;
857
+
768
858
  export const isOneToOneWithBlocked = (
769
859
  post: Pick<PublicPost, 'visibility' | 'audience' | 'profile'> & {
770
860
  creatorId?: string;
@@ -780,3 +870,31 @@ export const isOneToOneWithBlocked = (
780
870
  others.delete(viewer.id);
781
871
  return others.size === 1 && blocked.has([...others][0]!);
782
872
  };
873
+
874
+ /** First usable text field of a post, whitespace-collapsed and truncated. */
875
+ export const messagePreviewText = (
876
+ message: PublicPost,
877
+ maxLength = 160,
878
+ ): string => {
879
+ const data = message.data;
880
+ if (!data || typeof data !== 'object') return '';
881
+ const text =
882
+ 'content' in data && typeof data.content === 'string' && data.content
883
+ ? data.content
884
+ : 'name' in data && typeof data.name === 'string'
885
+ ? data.name
886
+ : 'title' in data && typeof data.title === 'string'
887
+ ? data.title
888
+ : '';
889
+ return truncateText(text.replace(/\s+/g, ' ').trim(), maxLength);
890
+ };
891
+
892
+ /** Display names of a post's audience minus the viewer, comma-joined. */
893
+ export const conversationLabel = (
894
+ message: PublicPost,
895
+ viewerId?: string,
896
+ ): string =>
897
+ (message.audience ?? [])
898
+ .filter((profile) => profile.id !== viewerId)
899
+ .map((profile) => profile.displayName || `@${profile.handle}`)
900
+ .join(', ');
@@ -12,8 +12,8 @@ const containsIgnoreCase = (candidate: string, query: string) =>
12
12
 
13
13
  export const PROFILE_DISPLAY_NAME_MAX_LENGTH = 30;
14
14
 
15
- /** Public sentinel shown for soft-deleted authors (API + clients). */
16
- export const DELETED_AUTHOR_DISPLAY_NAME = 'Deleted author';
15
+ /** Public sentinel shown for soft-deleted profiles (API + clients). */
16
+ export const DELETED_AUTHOR_DISPLAY_NAME = 'Deleted Profile';
17
17
  export const DELETED_AUTHOR_HANDLE = 'deleted';
18
18
 
19
19
  export const clampProfileDisplayName = (
@@ -28,6 +28,35 @@ export const isDeletedProfile = (
28
28
  profile: { deletedAt?: string | null } | undefined | null,
29
29
  ): boolean => !!profile?.deletedAt;
30
30
 
31
+ // `handle`/`displayName` arrive from untyped DB rows (`rowToModel`),
32
+ // so the hydration helper must accept `unknown`, not just `string | null`.
33
+ type DeletedProfileIdentity = {
34
+ deletedAt?: string | null;
35
+ displayName?: unknown;
36
+ handle?: unknown;
37
+ };
38
+
39
+ /**
40
+ * Deleted rows keep their original handle (the column is unique) and may have
41
+ * no display name. Public hydration fills in the sentinel when it is missing.
42
+ */
43
+ export const withDeletedProfileIdentity = <T extends DeletedProfileIdentity>(
44
+ profile: T,
45
+ ): T => {
46
+ if (!isDeletedProfile(profile)) return profile;
47
+ if (
48
+ profile.displayName === DELETED_AUTHOR_DISPLAY_NAME &&
49
+ profile.handle === DELETED_AUTHOR_HANDLE
50
+ ) {
51
+ return profile;
52
+ }
53
+ return {
54
+ ...profile,
55
+ displayName: DELETED_AUTHOR_DISPLAY_NAME,
56
+ handle: DELETED_AUTHOR_HANDLE,
57
+ };
58
+ };
59
+
31
60
  /**
32
61
  * Strip PII from a soft-deleted profile for public API / UI surfaces.
33
62
  * Keeps id + timestamps (including deletedAt) so clients can detect the state.
@@ -125,9 +154,14 @@ export const inviteLinkMatchesQuery = (
125
154
  queryOptions = { handle: true, displayName: true, slug: true, group: true },
126
155
  ) => {
127
156
  const profile = inviteLink.profile as PublicProfile;
157
+ const redemptionMatches = inviteLink.redemptions.some((r) =>
158
+ matchesQuery(r, query, queryOptions),
159
+ );
128
160
  if (query.startsWith('@')) {
129
161
  return !!(
130
- profile?.handle && containsIgnoreCase(profile.handle, query.substring(1))
162
+ (profile?.handle &&
163
+ containsIgnoreCase(profile.handle, query.substring(1))) ||
164
+ redemptionMatches
131
165
  );
132
166
  }
133
167
  const groupMatches =
@@ -139,6 +173,7 @@ export const inviteLinkMatchesQuery = (
139
173
  );
140
174
  return !!(
141
175
  groupMatches ||
176
+ redemptionMatches ||
142
177
  (profile &&
143
178
  ((queryOptions.handle &&
144
179
  profile.handle &&
@@ -1,4 +1,22 @@
1
- import type { MediaAttachmentData, ResourceKind } from '../types/models';
1
+ import { z } from 'zod';
2
+ import {
3
+ RESOURCE_TITLE_MAX_LENGTH,
4
+ visibilityTypeValues,
5
+ type MediaAttachmentData,
6
+ type ResourceKind,
7
+ type VisibilityType,
8
+ } from '../types/models';
9
+
10
+ export { RESOURCE_TITLE_MAX_LENGTH };
11
+
12
+ /** Matches `resourcePostSchema.url` (`z.url()`), after trimming. */
13
+ const resourceUrlSchema = z.url();
14
+
15
+ export const isValidResourceUrl = (url: string | undefined): boolean => {
16
+ const trimmed = url?.trim() ?? '';
17
+ if (!trimmed) return false;
18
+ return resourceUrlSchema.safeParse(trimmed).success;
19
+ };
2
20
 
3
21
  export const RESOURCE_KINDS = [
4
22
  'video',
@@ -24,7 +42,9 @@ export const resourceHasRequiredMedia = (resource: {
24
42
  url?: string;
25
43
  attachments?: MediaAttachmentData[];
26
44
  }): boolean => {
27
- if (resource.resourceKind === 'link') return Boolean(resource.url);
45
+ if (resource.resourceKind === 'link') {
46
+ return isValidResourceUrl(resource.url);
47
+ }
28
48
  const need =
29
49
  resource.resourceKind === 'gallery'
30
50
  ? 'image'
@@ -38,6 +58,89 @@ export const resourceHasRequiredMedia = (resource: {
38
58
  );
39
59
  };
40
60
 
61
+ export const RESOURCE_FORM_ISSUES = [
62
+ 'title',
63
+ 'titleLength',
64
+ 'url',
65
+ 'media',
66
+ 'audience',
67
+ 'group',
68
+ ] as const;
69
+
70
+ export type ResourceFormIssue = (typeof RESOURCE_FORM_ISSUES)[number];
71
+
72
+ export const resourceFormIssues = (input: {
73
+ title?: string;
74
+ resourceKind: ResourceKind;
75
+ url?: string;
76
+ attachments?: MediaAttachmentData[];
77
+ visibility?: string | null;
78
+ audience?: readonly unknown[] | null;
79
+ groupId?: string | null;
80
+ }): ResourceFormIssue[] => {
81
+ const issues: ResourceFormIssue[] = [];
82
+ if (!input.title?.trim()) issues.push('title');
83
+ else if (input.title.length > RESOURCE_TITLE_MAX_LENGTH) {
84
+ issues.push('titleLength');
85
+ }
86
+ if (input.resourceKind === 'link') {
87
+ if (!isValidResourceUrl(input.url)) issues.push('url');
88
+ } else if (!resourceHasRequiredMedia(input)) {
89
+ issues.push('media');
90
+ }
91
+ if (input.visibility === 'direct' && !input.audience?.length) {
92
+ issues.push('audience');
93
+ }
94
+ if (input.visibility === 'group' && !input.groupId) {
95
+ issues.push('group');
96
+ }
97
+ return issues;
98
+ };
99
+
100
+ const isVisibility = (
101
+ value: string | null | undefined,
102
+ ): value is VisibilityType =>
103
+ !!value && (visibilityTypeValues as readonly string[]).includes(value);
104
+
105
+ /**
106
+ * Draft visibility the profile may actually post with. A group-only author
107
+ * starts on Specific Group; a single postable group is preselected. Pass
108
+ * `postableGroupIds: null` while memberships are still loading so an existing
109
+ * group choice is not cleared.
110
+ */
111
+ export const resourceVisibilityForCapabilities = (input: {
112
+ visibility?: string | null;
113
+ groupId?: string | null;
114
+ allowed: readonly VisibilityType[];
115
+ postableGroupIds: readonly string[] | null;
116
+ }): { visibility: VisibilityType; groupId?: string } => {
117
+ const current = isVisibility(input.visibility) ? input.visibility : 'local';
118
+ const fallback = input.allowed[0];
119
+ if (!fallback) {
120
+ return { visibility: current, groupId: input.groupId ?? undefined };
121
+ }
122
+
123
+ const keep = input.allowed.includes(current) ? current : fallback;
124
+ if (keep !== 'group') return { visibility: keep };
125
+
126
+ if (input.postableGroupIds == null) {
127
+ return { visibility: 'group', groupId: input.groupId ?? undefined };
128
+ }
129
+
130
+ const kept =
131
+ input.groupId && input.postableGroupIds.includes(input.groupId)
132
+ ? input.groupId
133
+ : undefined;
134
+ return {
135
+ visibility: 'group',
136
+ groupId:
137
+ kept ??
138
+ (input.postableGroupIds.length === 1
139
+ ? input.postableGroupIds[0]
140
+ : undefined),
141
+ };
142
+ };
143
+
41
144
  export type CategoryNode = {
42
145
  name: string;
43
146
  path: string[];
package/src/lib/utils.ts CHANGED
@@ -64,8 +64,8 @@ export const asyncFilter = async <T>(
64
64
 
65
65
  export const passThroughUndefined =
66
66
  <Input, Output>(func: (input: Input) => Output) =>
67
- (input: Input | undefined) =>
68
- input && func(input);
67
+ (input: Input | undefined) =>
68
+ input && func(input);
69
69
 
70
70
  export const countBy = <T, V extends string | number | symbol>(
71
71
  arr: T[],
@@ -93,8 +93,8 @@ export const groupBy = <T, V extends string | number | symbol>(
93
93
 
94
94
  export const dateSorter =
95
95
  <T extends { createdAt: string }>(): ((v0: T, v1: T) => number) =>
96
- (v0: T, v1: T) =>
97
- Date.parse(v0.createdAt) - Date.parse(v1.createdAt);
96
+ (v0: T, v1: T) =>
97
+ Date.parse(v0.createdAt) - Date.parse(v1.createdAt);
98
98
 
99
99
  export const getUniqueBy = <T, V = string>(
100
100
  arr: T[],
@@ -135,11 +135,11 @@ export const deepSet = <T>(
135
135
  const keys = Array.isArray(path)
136
136
  ? path
137
137
  : path
138
- .replace(/(\w)\[/g, '$1.[')
139
- .split('.')
140
- .map((k) =>
141
- k.includes('[') ? parseInt(k.substring(1, k.length - 1)) : k,
142
- );
138
+ .replace(/(\w)\[/g, '$1.[')
139
+ .split('.')
140
+ .map((k) =>
141
+ k.includes('[') ? parseInt(k.substring(1, k.length - 1)) : k,
142
+ );
143
143
 
144
144
  let subObject: unknown = obj;
145
145
  for (let i = 0; i < keys.length; i++) {
@@ -150,9 +150,9 @@ export const deepSet = <T>(
150
150
  // @ts-expect-error deepset is not really typeable
151
151
  subObject[currentKey] = subObject[currentKey]
152
152
  ? // @ts-expect-error deepset is not really typeable
153
- subObject[currentKey]
153
+ subObject[currentKey]
154
154
  : // @ts-expect-error deepset is not really typeable
155
- isNaN(nextKey)
155
+ isNaN(nextKey)
156
156
  ? {}
157
157
  : [];
158
158
  } else {
@@ -203,35 +203,41 @@ export const formatTimeStamp = (
203
203
  return new Date(timestamp * 1000).toLocaleDateString();
204
204
  };
205
205
 
206
- const getMode = (config: CommunityConfig, profileSettings: ProfileSettings | undefined, systemTheme: 'dark' | 'light'): 'dark' | 'light' => {
206
+ const getMode = (
207
+ config: CommunityConfig,
208
+ profileSettings: ProfileSettings | undefined,
209
+ systemTheme: 'dark' | 'light',
210
+ ): 'dark' | 'light' => {
207
211
  if (profileSettings) {
208
- if (profileSettings.theme === "system") {
212
+ if (profileSettings.theme === 'system') {
209
213
  return systemTheme;
210
- } else if (profileSettings?.theme === "dark") {
211
- return "dark";
212
- } else if (profileSettings?.theme === "light") {
213
- return "light";
214
+ } else if (profileSettings?.theme === 'dark') {
215
+ return 'dark';
216
+ } else if (profileSettings?.theme === 'light') {
217
+ return 'light';
214
218
  }
215
219
  }
216
220
  return config.theme.base === 'OpenpeepsDark' ? 'dark' : 'light';
217
- }
221
+ };
218
222
 
219
223
  export const getTheme = (
220
224
  config: CommunityConfig,
221
225
  profileSettings?: ProfileSettings,
222
- systemTheme: 'dark' | 'light' = getSystemTheme()
226
+ systemTheme: 'dark' | 'light' = getSystemTheme(),
223
227
  ) =>
224
- getMode(config, profileSettings, systemTheme) === 'dark' ?
225
- { ...config.theme.dark, dark: true } :
226
- { ...config.theme.light, dark: false };
228
+ getMode(config, profileSettings, systemTheme) === 'dark'
229
+ ? { ...config.theme.dark, dark: true }
230
+ : { ...config.theme.light, dark: false };
227
231
 
228
232
  export const getSystemTheme = () => {
229
- if (typeof window !== "undefined" && window.matchMedia) {
230
- const systemIsDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
231
- return systemIsDark ? "dark" : "light"
233
+ if (typeof window !== 'undefined' && window.matchMedia) {
234
+ const systemIsDark = window.matchMedia(
235
+ '(prefers-color-scheme: dark)',
236
+ ).matches;
237
+ return systemIsDark ? 'dark' : 'light';
232
238
  }
233
239
  return 'light';
234
- }
240
+ };
235
241
 
236
242
  export const getProfileAvatar = (
237
243
  profile: PublicProfile | undefined | null,
@@ -252,7 +258,8 @@ export const getGroupAvatar = (
252
258
  };
253
259
 
254
260
  export const extractDateFromUUIDv7 = (uuidV7: string): string => {
255
- const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
261
+ const UUID_REGEX =
262
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
256
263
  if (!UUID_REGEX.test(uuidV7)) {
257
264
  throw new Error('Invalid UUID format');
258
265
  }
@@ -271,13 +278,15 @@ export const extractDateFromUUIDv7 = (uuidV7: string): string => {
271
278
 
272
279
  const pad = (num: number, size: number): string => {
273
280
  let s = String(num);
274
- while (s.length < size) { s = '0' + s; }
281
+ while (s.length < size) {
282
+ s = '0' + s;
283
+ }
275
284
  return s;
276
285
  };
277
286
 
278
287
  return (
279
288
  date.getUTCFullYear().toString() +
280
- pad(date.getUTCMonth() + 1, 2) + // months are zero‑based
289
+ pad(date.getUTCMonth() + 1, 2) + // months are zero‑based
281
290
  pad(date.getUTCDate(), 2) +
282
291
  pad(date.getUTCHours(), 2) +
283
292
  pad(date.getUTCMinutes(), 2)
@@ -292,7 +301,7 @@ export const formatSize = (bytes: number) => {
292
301
 
293
302
  export const hasVisibilityChanged = (
294
303
  previousAudienceSetting: AudienceSetting,
295
- newAudienceSetting: AudienceSetting
304
+ newAudienceSetting: AudienceSetting,
296
305
  ): boolean => {
297
306
  if (previousAudienceSetting.visibility !== newAudienceSetting.visibility) {
298
307
  return true;
@@ -319,4 +328,4 @@ export const hasVisibilityChanged = (
319
328
  }
320
329
 
321
330
  return false;
322
- };
331
+ };
@@ -0,0 +1,24 @@
1
+ import { z } from 'zod';
2
+
3
+ export const livekitDiagnosisCheckIdSchema = z.enum([
4
+ 'url',
5
+ 'apiKey',
6
+ 'apiSecret',
7
+ 'reachable',
8
+ ]);
9
+
10
+ export const livekitDiagnosisSchema = z.object({
11
+ connected: z.boolean(),
12
+ recordingEnabled: z.boolean(),
13
+ url: z.string().optional(),
14
+ /** Last probe failure. Credentials are redacted before this is returned. */
15
+ error: z.string().optional(),
16
+ checks: z.array(
17
+ z.object({
18
+ id: livekitDiagnosisCheckIdSchema,
19
+ ok: z.boolean(),
20
+ }),
21
+ ),
22
+ });
23
+
24
+ export type LivekitDiagnosis = z.infer<typeof livekitDiagnosisSchema>;
@@ -0,0 +1,29 @@
1
+ import { z } from 'zod';
2
+
3
+ export const storedMediaStatusSchema = z.enum([
4
+ 'referenced',
5
+ 'pending',
6
+ 'due',
7
+ 'unseen',
8
+ ]);
9
+
10
+ export type StoredMediaStatus = z.infer<typeof storedMediaStatusSchema>;
11
+
12
+ export const storedMediaFileSchema = z.object({
13
+ storageId: z.string(),
14
+ size: z.number(),
15
+ modifiedAt: z.string(),
16
+ status: storedMediaStatusSchema,
17
+ unreferencedSince: z.string().nullable(),
18
+ deletesAt: z.string().nullable(),
19
+ url: z.string(),
20
+ });
21
+
22
+ export type StoredMediaFile = z.infer<typeof storedMediaFileSchema>;
23
+
24
+ export const storedMediaListSchema = z.object({
25
+ files: z.array(storedMediaFileSchema),
26
+ graceMs: z.number(),
27
+ });
28
+
29
+ export type StoredMediaList = z.infer<typeof storedMediaListSchema>;
package/src/types/api.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  accessTokenSchema,
10
10
  accountInteractionsSchema,
11
11
  accountNameSchema,
12
+ federatedHandleSchema,
12
13
  accountSchema,
13
14
  answerSchema,
14
15
  applicationDataSchema,
@@ -76,7 +77,7 @@ export const publicProfileSchema = z.object({
76
77
  createdAt: z.string().datetime(),
77
78
  updatedAt: z.string().datetime(),
78
79
  deletedAt: z.string().datetime().nullable().optional(),
79
- handle: accountNameSchema,
80
+ handle: federatedHandleSchema,
80
81
  avatar: z.string().url().nullable().optional(),
81
82
  header: z.string().url().nullable().optional(),
82
83
  displayName: z.string().max(30).optional(),
@@ -661,14 +662,15 @@ export const updateProfileRequestSchema = profileDataSchema
661
662
  })
662
663
  .superRefine((value, ctx) => {
663
664
  if (value.handle === undefined || value.type === 'federated') return;
664
- if (!accountNameSchema.safeParse(value.handle).success) {
665
- ctx.addIssue({
666
- code: 'custom',
667
- path: ['handle'],
668
- message:
669
- 'Handle must be 1–16 characters: letters, numbers, underscores, or hyphens (no spaces or punctuation)',
670
- });
671
- }
665
+ const result = accountNameSchema.safeParse(value.handle);
666
+ if (result.success) return;
667
+ ctx.addIssue({
668
+ code: 'custom',
669
+ path: ['handle'],
670
+ message:
671
+ result.error.issues[0]?.message ??
672
+ 'Handle must be 1–16 characters: letters, numbers, underscores, or hyphens (no spaces or punctuation)',
673
+ });
672
674
  });
673
675
  export type UpdateProfileRequest = z.infer<typeof updateProfileRequestSchema>;
674
676
 
@@ -782,6 +784,14 @@ export const searchResultCountsSchema = z.object({
782
784
  });
783
785
  export type SearchResultCounts = z.infer<typeof searchResultCountsSchema>;
784
786
 
787
+ export const directMessageSearchHitSchema = z.object({
788
+ conversationId: z.uuid(),
789
+ message: publicPostSchema,
790
+ });
791
+ export type DirectMessageSearchHit = z.infer<
792
+ typeof directMessageSearchHitSchema
793
+ >;
794
+
785
795
  // Plain object schema — used as API contract & in OpenAPI generation. Cross-
786
796
  // field validation lives on `postCreationDataFormSchema` below to keep this
787
797
  // schema introspectable by zod-to-openapi (which can't walk zod-4 `.refine()`
package/src/types/auth.ts CHANGED
@@ -17,6 +17,6 @@ export const authorizationDataSchema = z.object({
17
17
  account: accountWithMetaSchema.optional(),
18
18
  service: z.string().optional(),
19
19
  scopes: z.array(scopeSchema),
20
- })
20
+ });
21
21
 
22
- export type AuthorizationData = z.infer<typeof authorizationDataSchema>;
22
+ export type AuthorizationData = z.infer<typeof authorizationDataSchema>;