@openpeepshq/common 0.6.4 → 0.8.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.
@@ -0,0 +1,25 @@
1
+ export declare const visibleTextLength: (markdown?: string | null) => number;
2
+ /** Visible-text budget for note/question content. */
3
+ export declare const POST_MAX_VISIBLE_LENGTH = 500;
4
+ /** Raw markdown backstop for note/question content. */
5
+ export declare const POST_MAX_RAW_LENGTH = 5000;
6
+ /**
7
+ * Whitespace-only content is measured as empty (nothing renders), so the
8
+ * same "is there anything to send" test must ignore whitespace everywhere
9
+ * a composer or schema checks it.
10
+ */
11
+ export declare const hasVisibleText: (content?: string | null) => boolean;
12
+ /** True when note/question content fits the visible + raw budgets. */
13
+ export declare const postContentWithinBudget: (content?: string | null) => boolean;
14
+ /**
15
+ * Shared composer submit gate over the visible budget. Question composers
16
+ * need visible text for their poll to make sense; note composers accept an
17
+ * attachment instead. In-flight state (submitting, pending uploads,
18
+ * audience/group requirements) stays at the call site.
19
+ */
20
+ export declare const canSubmitPostContent: ({ visibleContentLength, attachmentsLength, composerType, pollOptionsValid, }: {
21
+ visibleContentLength: number;
22
+ attachmentsLength: number;
23
+ composerType?: "note" | "question";
24
+ pollOptionsValid?: boolean;
25
+ }) => boolean;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Visible-text measurement for the post content budget.
3
+ *
4
+ * Counts what a reader sees, not the raw markdown source:
5
+ * - fenced code counts its content verbatim (it renders as visible code)
6
+ * - links and images count their text/alt, not the URL
7
+ * - structural line syntax (table cells/pipes, list markers, setext
8
+ * underlines, thematic breaks, headings, blockquotes) and HTML tags
9
+ * render no characters and do not count
10
+ * - whitespace runs collapse and line edges trim, so the count tracks
11
+ * what renders
12
+ *
13
+ * This is a budget estimate, not a markdown parser: unbounded content is
14
+ * guarded by the raw-length cap (`POST_MAX_RAW_LENGTH`), not by this
15
+ * function.
16
+ */
17
+ const FENCE_RE = /^[ \t]*```[^\n]*\n?([\s\S]*?)^[ \t]*```[ \t]*$/gm;
18
+ // Built from a string, not a regex literal: ESLint's no-control-regex
19
+ // rejects control characters in regex sources. U+FFFE is a noncharacter
20
+ // no renderer emits, and stray occurrences are stripped from the content
21
+ // before fencing, so it cannot collide with real input.
22
+ const FENCE_SENTINEL_RE = () => new RegExp('\\uFFFE(\\d+)\\uFFFE', 'g');
23
+ /**
24
+ * A line that renders nothing: table delimiter rows (`| --- | --- |`),
25
+ * setext underlines (`---`, `===`), and thematic breaks (`---`, `***`,
26
+ * `___`). The character class mirrors their allowed symbols; `-` is last
27
+ * so it cannot form a range.
28
+ */
29
+ const INVISIBLE_LINE_RE = /^[ \t]*\|?[ \t]*[-=*_][ \t:|=*_-]*\|?[ \t]*$/;
30
+ export const visibleTextLength = (markdown) => {
31
+ if (!markdown)
32
+ return 0;
33
+ // Stray sentinels in user content must not collide with the fence
34
+ // sentinel (U+FFFE is a noncharacter no renderer emits).
35
+ let text = markdown
36
+ .replace(/\r\n?/g, '\n')
37
+ .replaceAll('\uFFFE', '')
38
+ .replaceAll('\u0000', '');
39
+ // Fenced code renders verbatim, so hold its content aside while the
40
+ // line-structural passes run on the surrounding text.
41
+ const fenced = [];
42
+ text = text.replace(FENCE_RE, (_match, content) => {
43
+ fenced.push(content);
44
+ return `\uFFFE${fenced.length - 1}\uFFFE`;
45
+ });
46
+ // Inline code counts its content, not the backticks.
47
+ text = text.replace(/`([^`]+)`/g, '$1');
48
+ // Autolinks: the URL is the visible text.
49
+ text = text.replace(/<(https?:\/\/[^>\s]+|mailto:[^>\s]+)>/gi, '$1');
50
+ // Images: count the alt text, drop the marker and URL.
51
+ text = text.replace(/!\[([^\]]*)\]\(((?:[^()]+|\([^()]*\))*)\)/g, '$1');
52
+ // Links: count the text, drop the URL (one level of nested parens ok).
53
+ text = text.replace(/\[([^\]]+)\]\(((?:[^()]+|\([^()]*\))*)\)/g, '$1');
54
+ // Reference-style links: count the text, drop the reference.
55
+ text = text.replace(/\[([^\]]+)\]\[[^\]]*\]/g, '$1');
56
+ // HTML tags: drop the tags, keep the inner text.
57
+ text = text.replace(/<\/?[a-zA-Z][^>]*>/g, '');
58
+ text = text
59
+ .split('\n')
60
+ .map((line) => {
61
+ if (INVISIBLE_LINE_RE.test(line))
62
+ return '';
63
+ return (line
64
+ // Heading and blockquote markers.
65
+ .replace(/^[ \t]*(?:#{1,6}|>)[ \t]*/, '')
66
+ // List markers ("-", "*", "+", "1.", "1)").
67
+ .replace(/^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+/, '')
68
+ // Table cells: the pipes and their padding are syntax.
69
+ .replace(/^[ \t]*\|/, '')
70
+ .replace(/\|[ \t]*$/, '')
71
+ .replace(/\|/g, ' ')
72
+ .replace(/^[ \t]+|[\t ]+$/g, ''));
73
+ })
74
+ .filter((line) => line.length > 0)
75
+ .join('\n');
76
+ // Emphasis/strikethrough markers. `_` inside a word (snake_case) is kept.
77
+ text = text.replace(/[*~]{1,3}/g, '');
78
+ text = text.replace(/(^|\s)_{1,3}(\S)/gm, '$1$2');
79
+ text = text.replace(/(\S)_{1,3}(\s|$)/gm, '$1$2');
80
+ // Whitespace runs collapse to single spaces (the renderer collapses
81
+ // them), so the count tracks what renders.
82
+ text = text.replace(/[\t ]{2,}/g, ' ');
83
+ // Restore the fenced code content verbatim.
84
+ text = text.replace(FENCE_SENTINEL_RE(), (_match, index) => {
85
+ return fenced[Number(index)] ?? '';
86
+ });
87
+ // Count code points so emoji and other astral characters cost what they
88
+ // render, not their UTF-16 surrogate pair.
89
+ return [...text].length;
90
+ };
91
+ /** Visible-text budget for note/question content. */
92
+ export const POST_MAX_VISIBLE_LENGTH = 500;
93
+ /** Raw markdown backstop for note/question content. */
94
+ export const POST_MAX_RAW_LENGTH = 5000;
95
+ /**
96
+ * Whitespace-only content is measured as empty (nothing renders), so the
97
+ * same "is there anything to send" test must ignore whitespace everywhere
98
+ * a composer or schema checks it.
99
+ */
100
+ export const hasVisibleText = (content) => visibleTextLength(content) > 0;
101
+ /** True when note/question content fits the visible + raw budgets. */
102
+ export const postContentWithinBudget = (content) => {
103
+ const raw = content ?? '';
104
+ return (visibleTextLength(raw) <= POST_MAX_VISIBLE_LENGTH &&
105
+ raw.length <= POST_MAX_RAW_LENGTH);
106
+ };
107
+ /**
108
+ * Shared composer submit gate over the visible budget. Question composers
109
+ * need visible text for their poll to make sense; note composers accept an
110
+ * attachment instead. In-flight state (submitting, pending uploads,
111
+ * audience/group requirements) stays at the call site.
112
+ */
113
+ export const canSubmitPostContent = ({ visibleContentLength, attachmentsLength, composerType, pollOptionsValid = true, }) => composerType === 'question'
114
+ ? visibleContentLength > 0 &&
115
+ visibleContentLength <= POST_MAX_VISIBLE_LENGTH &&
116
+ pollOptionsValid
117
+ : visibleContentLength <= POST_MAX_VISIBLE_LENGTH &&
118
+ (visibleContentLength > 0 || attachmentsLength > 0);
@@ -11,6 +11,7 @@ export * from './groupHelpers';
11
11
  export * from './groupTemplateHelpers';
12
12
  export * from './colors';
13
13
  export * from './markdownHelpers';
14
+ export * from './contentLength';
14
15
  export * from './attachmentHelpers';
15
16
  export * from './resources';
16
17
  export * from './eventIcs';
package/dist/lib/index.js CHANGED
@@ -11,6 +11,7 @@ export * from './groupHelpers.js';
11
11
  export * from './groupTemplateHelpers.js';
12
12
  export * from './colors.js';
13
13
  export * from './markdownHelpers.js';
14
+ export * from './contentLength.js';
14
15
  export * from './attachmentHelpers.js';
15
16
  export * from './resources.js';
16
17
  export * from './eventIcs.js';
@@ -1,4 +1,4 @@
1
- import { Answer, AnswerWithPublicProfile, AuthorizationData, CapabilitiesConfig, Event, GroupWithMeta, PostType, PostDataUnion, PublicPost, PublicProfile, PublicRsvp, RSVP, Thread, VisibilityType } from '../types';
1
+ import { Answer, AnswerWithPublicProfile, AuthorizationData, CapabilitiesConfig, EntryWithPublicProfile, Event, GroupWithMeta, PostType, PostDataUnion, PublicPost, PublicProfile, PublicRsvp, RSVP, Thread, VisibilityType } from '../types';
2
2
  export declare const buildThreads: (posts: PublicPost[]) => Thread[];
3
3
  export type ThreadPreviewPost = {
4
4
  id: string;
@@ -309,6 +309,7 @@ export declare const HIDDEN_AUTHOR_HANDLE = "hidden";
309
309
  export declare const toHiddenPost: <T extends {
310
310
  data: PostDataUnion;
311
311
  profile: PublicProfile;
312
+ entries?: EntryWithPublicProfile[];
312
313
  }>(post: T) => T & {
313
314
  hidden: true;
314
315
  };
@@ -334,6 +335,27 @@ export declare const isOneToOneDm: (post: Pick<PublicPost, "visibility" | "audie
334
335
  * notes so they remain valid ActivityPub direct messages.
335
336
  */
336
337
  export declare const isConversationLeavePost: (post: Pick<PublicPost, "inReplyToId" | "audience" | "profile">) => boolean;
338
+ export type PostVersionOrder = 'oldest' | 'newest';
339
+ export type PostEditVersion = {
340
+ id: string;
341
+ createdAt: string;
342
+ data: PostDataUnion;
343
+ /** Author snapshot of the entry that produced this version. */
344
+ profile: EntryWithPublicProfile['profile'];
345
+ /** Create entry is the original text. Each edit entry is that save's text. */
346
+ kind: 'original' | 'edit';
347
+ current: boolean;
348
+ };
349
+ /** True when at least one edit has been saved for this post. */
350
+ export declare const postHasEditHistory: (entries: readonly EntryWithPublicProfile[] | undefined) => boolean;
351
+ /**
352
+ * Saved versions of a post. The create entry is the original; each edit entry
353
+ * stores the content written at that save. Oldest first unless `order` is newest.
354
+ * Returns nothing until the post has been edited.
355
+ */
356
+ export declare const postEditVersions: (entries: readonly EntryWithPublicProfile[] | undefined, order?: PostVersionOrder) => PostEditVersion[];
357
+ export declare const postEditVersionKind: (version: Pick<PostEditVersion, "current" | "kind">) => "original" | "edit" | "current";
358
+ export declare const postEditVersionTitle: (data: PostDataUnion) => string | undefined;
337
359
  export declare const isOneToOneWithBlocked: (post: Pick<PublicPost, "visibility" | "audience" | "profile"> & {
338
360
  creatorId?: string;
339
361
  }, viewer: {
@@ -502,6 +502,11 @@ export const toHiddenPost = (post) => ({
502
502
  ...post.data,
503
503
  ...('content' in post.data ? { content: '' } : {}),
504
504
  },
505
+ // create/edit entries each carry a full content snapshot; dropping them
506
+ // keeps the redacted text out of the hidden post's serialized payload.
507
+ entries: post.entries
508
+ ? post.entries.filter((entry) => entry.type !== 'create' && entry.type !== 'edit')
509
+ : post.entries,
505
510
  profile: {
506
511
  ...post.profile,
507
512
  displayName: undefined,
@@ -538,6 +543,42 @@ export const isConversationLeavePost = (post) => {
538
543
  return false;
539
544
  return !post.audience?.some((p) => p.id === authorId);
540
545
  };
546
+ const isSnapshotEntry = (entry) => entry.type === 'create' || entry.type === 'edit';
547
+ /** True when at least one edit has been saved for this post. */
548
+ export const postHasEditHistory = (entries) => !!entries?.some((entry) => entry.type === 'edit');
549
+ /**
550
+ * Saved versions of a post. The create entry is the original; each edit entry
551
+ * stores the content written at that save. Oldest first unless `order` is newest.
552
+ * Returns nothing until the post has been edited.
553
+ */
554
+ export const postEditVersions = (entries, order = 'oldest') => {
555
+ if (!postHasEditHistory(entries))
556
+ return [];
557
+ const chronological = (entries ?? [])
558
+ .map((entry, index) => ({ entry, index }))
559
+ .filter((item) => isSnapshotEntry(item.entry))
560
+ .sort((a, b) => Date.parse(a.entry.createdAt) - Date.parse(b.entry.createdAt) ||
561
+ a.index - b.index);
562
+ const last = chronological.length - 1;
563
+ const versions = chronological.map(({ entry, index }, position) => ({
564
+ id: `${entry.type}-${entry.createdAt}-${index}`,
565
+ createdAt: entry.createdAt,
566
+ data: entry.data,
567
+ profile: entry.profile,
568
+ kind: entry.type === 'create' ? 'original' : 'edit',
569
+ current: position === last,
570
+ }));
571
+ return order === 'newest' ? [...versions].reverse() : versions;
572
+ };
573
+ export const postEditVersionKind = (version) => version.current ? 'current' : version.kind;
574
+ export const postEditVersionTitle = (data) => {
575
+ if (data.type === 'article' || data.type === 'resource') {
576
+ return data.title || undefined;
577
+ }
578
+ if (data.type === 'event')
579
+ return data.name || undefined;
580
+ return undefined;
581
+ };
541
582
  export const isOneToOneWithBlocked = (post, viewer, blockedIds) => {
542
583
  if (!viewer || post.visibility !== 'direct')
543
584
  return false;
@@ -104,9 +104,9 @@ export declare const analyticsMemberRowSchema: z.ZodObject<{
104
104
  }, z.core.$strip>;
105
105
  export type AnalyticsMemberRow = z.infer<typeof analyticsMemberRowSchema>;
106
106
  export declare const analyticsPostTypeKeySchema: z.ZodEnum<{
107
+ note: "note";
107
108
  jam: "jam";
108
109
  resource: "resource";
109
- note: "note";
110
110
  event: "event";
111
111
  article: "article";
112
112
  poll: "poll";
@@ -114,9 +114,9 @@ export declare const analyticsPostTypeKeySchema: z.ZodEnum<{
114
114
  export type AnalyticsPostTypeKey = z.infer<typeof analyticsPostTypeKeySchema>;
115
115
  export declare const analyticsPostTypeCountSchema: z.ZodObject<{
116
116
  type: z.ZodEnum<{
117
+ note: "note";
117
118
  jam: "jam";
118
119
  resource: "resource";
119
- note: "note";
120
120
  event: "event";
121
121
  article: "article";
122
122
  poll: "poll";
@@ -271,9 +271,9 @@ export declare const analyticsOverviewSchema: z.ZodObject<{
271
271
  }, z.core.$strip>>;
272
272
  postTypes: z.ZodArray<z.ZodObject<{
273
273
  type: z.ZodEnum<{
274
+ note: "note";
274
275
  jam: "jam";
275
276
  resource: "resource";
276
- note: "note";
277
277
  event: "event";
278
278
  article: "article";
279
279
  poll: "poll";