@openpeepshq/common 0.2.0 → 0.3.1

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.
@@ -12,6 +12,7 @@ export * from './groupTemplateHelpers';
12
12
  export * from './colors';
13
13
  export * from './markdownHelpers';
14
14
  export * from './attachmentHelpers';
15
+ export * from './resources';
15
16
  export * from './eventIcs';
16
17
  export * from './eventTime';
17
18
  export * from './timeZone';
package/dist/lib/index.js CHANGED
@@ -12,6 +12,7 @@ export * from './groupTemplateHelpers.js';
12
12
  export * from './colors.js';
13
13
  export * from './markdownHelpers.js';
14
14
  export * from './attachmentHelpers.js';
15
+ export * from './resources.js';
15
16
  export * from './eventIcs.js';
16
17
  export * from './eventTime.js';
17
18
  export * from './timeZone.js';
@@ -1,3 +1,10 @@
1
+ export interface MarkdownRenderProps {
2
+ source?: string;
3
+ mentions?: MentionProfileRef[];
4
+ linkPreviewMode?: 'prepend' | 'append' | 'inline' | 'none';
5
+ /** When true, all links open in a new tab (web) / system browser (RN). */
6
+ newTab?: boolean | ((link: string) => boolean);
7
+ }
1
8
  export type MentionProfileRef = {
2
9
  profile: {
3
10
  handle?: string | null;
@@ -11,13 +18,50 @@ export type MentionProfileRef = {
11
18
  * Bare `@handle` tokens use the allowed handle charset (letters, digits, `_`, `-`).
12
19
  */
13
20
  export declare const linkProfileMentions: (source: string, mentions?: MentionProfileRef[]) => string;
21
+ /**
22
+ * Pre-process markdown source: convert `@handle` mentions into markdown
23
+ * profile links. Hashtag conversion is handled per-platform (web regex vs.
24
+ * markdown-it plugin) because the resulting URL schemes differ.
25
+ * Shared by web and RN renderers so both start from the same text.
26
+ */
27
+ export declare const preprocessMarkdownSource: (source: string, mentions?: MentionProfileRef[]) => string;
14
28
  export declare const matchMentionHandles: (text?: string | null) => string[];
15
29
  /** Readable text for a shortened preview. Drops markdown marks, keeps words. */
16
30
  export declare const markdownPlainText: (markdown?: string | null) => string;
17
31
  export declare const firstNWords: (markdown: string | undefined, n: number) => string;
32
+ /**
33
+ * Truncates markdown to at most `maxBlocks` block-level regions, then to
34
+ * `maxChars` characters at a word boundary. Preserves punctuation and inline
35
+ * markdown formatting (links, bold, etc.). An ellipsis is appended only when
36
+ * the content was actually shortened.
37
+ */
38
+ export declare const truncateMarkdown: (markdown: string | undefined, maxBlocks: number, maxChars: number) => string;
18
39
  /**
19
40
  * Estimate reading time for a markdown article. Strips markdown syntax
20
41
  * before counting words, then divides by the words-per-minute rate.
21
42
  * Always returns at least 1 for non-empty content.
22
43
  */
23
44
  export declare const minutesToRead: (markdown: string | undefined, wordsPerMinute?: number) => number;
45
+ /**
46
+ * True when `href` points to a different origin than `origin`.
47
+ * Same logic as the web `linkTargets.isExternalLink`.
48
+ */
49
+ export declare const isExternalLink: (href: string, origin?: string) => boolean;
50
+ /** Convert a same-origin path or URL to a `goto:` deep-link for RN navigation. */
51
+ export declare const toGotoUrl: (url: string, origin: string) => string;
52
+ /**
53
+ * Tags, attrs and forbits shared by both the web (DOMPurify config) and
54
+ * RN (custom HTML token renderers) so both platforms apply the same policy.
55
+ */
56
+ export declare const MARKDOWN_HTML_ALLOWED_TAGS: readonly ["b", "i", "em", "strong", "a", "p", "br", "ul", "ol", "li", "blockquote", "code", "pre", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "img", "iframe", "video", "source", "picture", "figcaption"];
57
+ export declare const MARKDOWN_HTML_ALLOWED_ATTRS: readonly ["href", "src", "title", "alt", "target", "rel", "width", "height", "loading", "sandbox", "frameborder", "allowfullscreen", "referrerpolicy", "style"];
58
+ export declare const MARKDOWN_HTML_FORBIDDEN_TAGS: readonly ["script", "style", "form", "object", "embed"];
59
+ export declare const MARKDOWN_HTML_FORBIDDEN_ATTRS: readonly ["onload", "onerror", "onclick", "onmouseover"];
60
+ /** Extract all iframe `src` URLs found in an HTML string. */
61
+ export declare const extractIframeSrcs: (html: string) => string[];
62
+ /**
63
+ * Inject safety attributes onto `<iframe>` tags so they can't break out of
64
+ * their container or execute script navigation. Runs after sanitization
65
+ * (so attackers can't smuggle attributes through), before DOM injection.
66
+ */
67
+ export declare const injectIframeSafetyAttrs: (html: string) => string;
@@ -27,6 +27,13 @@ export const linkProfileMentions = (source, mentions = []) => {
27
27
  }
28
28
  return text.replace(new RegExp(mentionHandleRegexBase, 'g'), (_full, prefix, handle) => `${prefix}[@${handle}](/@${handle})`);
29
29
  };
30
+ /**
31
+ * Pre-process markdown source: convert `@handle` mentions into markdown
32
+ * profile links. Hashtag conversion is handled per-platform (web regex vs.
33
+ * markdown-it plugin) because the resulting URL schemes differ.
34
+ * Shared by web and RN renderers so both start from the same text.
35
+ */
36
+ export const preprocessMarkdownSource = linkProfileMentions;
30
37
  export const matchMentionHandles = (text) => {
31
38
  if (!text)
32
39
  return [];
@@ -75,6 +82,34 @@ export const firstNWords = (markdown, n) => {
75
82
  }
76
83
  return firstTwelveWords.join(' ');
77
84
  };
85
+ /**
86
+ * Truncates markdown to at most `maxBlocks` block-level regions, then to
87
+ * `maxChars` characters at a word boundary. Preserves punctuation and inline
88
+ * markdown formatting (links, bold, etc.). An ellipsis is appended only when
89
+ * the content was actually shortened.
90
+ */
91
+ export const truncateMarkdown = (markdown, maxBlocks, maxChars) => {
92
+ if (!markdown)
93
+ return '';
94
+ const blocks = markdown
95
+ .replace(/\r\n/g, '\n')
96
+ .split(/\n{2,}/)
97
+ .map((block) => block.trim())
98
+ .filter(Boolean);
99
+ if (blocks.length === 0)
100
+ return '';
101
+ const hadMoreBlocks = blocks.length > maxBlocks;
102
+ const content = blocks.slice(0, maxBlocks).join('\n\n');
103
+ if (content.length <= maxChars) {
104
+ return hadMoreBlocks ? `${content}…` : content;
105
+ }
106
+ const candidate = content.slice(0, maxChars);
107
+ const lastBreak = Math.max(candidate.lastIndexOf(' '), candidate.lastIndexOf('\n'), candidate.lastIndexOf('\t'));
108
+ if (lastBreak > 0) {
109
+ return `${content.slice(0, lastBreak).trimEnd()}…`;
110
+ }
111
+ return `${candidate}…`;
112
+ };
78
113
  /** Average adult reading speed (words per minute). */
79
114
  const DEFAULT_WORDS_PER_MINUTE = 210;
80
115
  /**
@@ -91,3 +126,145 @@ export const minutesToRead = (markdown, wordsPerMinute = DEFAULT_WORDS_PER_MINUT
91
126
  ? 0
92
127
  : Math.max(1, Math.ceil(wordCount / wordsPerMinute));
93
128
  };
129
+ /* ------------------------------------------------------------------ */
130
+ /* Shared link utilities */
131
+ /* ------------------------------------------------------------------ */
132
+ /**
133
+ * True when `href` points to a different origin than `origin`.
134
+ * Same logic as the web `linkTargets.isExternalLink`.
135
+ */
136
+ export const isExternalLink = (href, origin) => {
137
+ if (!href || /^(mailto:|tel:|#)/.test(href)) {
138
+ return false;
139
+ }
140
+ if (href.startsWith('/') && !href.startsWith('//')) {
141
+ return false;
142
+ }
143
+ if (!origin) {
144
+ return !href.startsWith('/');
145
+ }
146
+ try {
147
+ return new URL(href, origin).origin !== origin;
148
+ }
149
+ catch {
150
+ return !href.startsWith('/');
151
+ }
152
+ };
153
+ /** Convert a same-origin path or URL to a `goto:` deep-link for RN navigation. */
154
+ export const toGotoUrl = (url, origin) => {
155
+ if (url.includes('goto:/')) {
156
+ return url;
157
+ }
158
+ if (url.startsWith('/') && !url.startsWith('//')) {
159
+ return `goto:${url}`;
160
+ }
161
+ try {
162
+ const urlObj = new URL(url);
163
+ if (urlObj.origin === origin) {
164
+ return `goto:${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
165
+ }
166
+ }
167
+ catch {
168
+ // fall through
169
+ }
170
+ return url;
171
+ };
172
+ /* ------------------------------------------------------------------ */
173
+ /* HTML sanitization helpers (shared allowlist + iframe safety) */
174
+ /* ------------------------------------------------------------------ */
175
+ /**
176
+ * Tags, attrs and forbits shared by both the web (DOMPurify config) and
177
+ * RN (custom HTML token renderers) so both platforms apply the same policy.
178
+ */
179
+ export const MARKDOWN_HTML_ALLOWED_TAGS = [
180
+ 'b',
181
+ 'i',
182
+ 'em',
183
+ 'strong',
184
+ 'a',
185
+ 'p',
186
+ 'br',
187
+ 'ul',
188
+ 'ol',
189
+ 'li',
190
+ 'blockquote',
191
+ 'code',
192
+ 'pre',
193
+ 'h1',
194
+ 'h2',
195
+ 'h3',
196
+ 'h4',
197
+ 'h5',
198
+ 'h6',
199
+ 'hr',
200
+ 'img',
201
+ 'iframe',
202
+ 'video',
203
+ 'source',
204
+ 'picture',
205
+ 'figcaption',
206
+ ];
207
+ export const MARKDOWN_HTML_ALLOWED_ATTRS = [
208
+ 'href',
209
+ 'src',
210
+ 'title',
211
+ 'alt',
212
+ 'target',
213
+ 'rel',
214
+ 'width',
215
+ 'height',
216
+ 'loading',
217
+ 'sandbox',
218
+ 'frameborder',
219
+ 'allowfullscreen',
220
+ 'referrerpolicy',
221
+ 'style',
222
+ ];
223
+ export const MARKDOWN_HTML_FORBIDDEN_TAGS = [
224
+ 'script',
225
+ 'style',
226
+ 'form',
227
+ 'object',
228
+ 'embed',
229
+ ];
230
+ export const MARKDOWN_HTML_FORBIDDEN_ATTRS = [
231
+ 'onload',
232
+ 'onerror',
233
+ 'onclick',
234
+ 'onmouseover',
235
+ ];
236
+ /** Simple `<iframe>` tag detector for extracting embed URLs from raw HTML. */
237
+ const IFRAME_SRC_RE = /<iframe\b[^>]*?\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)')[^>]*>/gi;
238
+ /** Extract all iframe `src` URLs found in an HTML string. */
239
+ export const extractIframeSrcs = (html) => {
240
+ const srcs = [];
241
+ let match;
242
+ while ((match = IFRAME_SRC_RE.exec(html)) !== null) {
243
+ srcs.push(match[1] ?? match[2] ?? '');
244
+ }
245
+ return srcs;
246
+ };
247
+ /**
248
+ * Inject safety attributes onto `<iframe>` tags so they can't break out of
249
+ * their container or execute script navigation. Runs after sanitization
250
+ * (so attackers can't smuggle attributes through), before DOM injection.
251
+ */
252
+ export const injectIframeSafetyAttrs = (html) => {
253
+ return html.replace(/<iframe([^>]*?)>/gi, (match, attrs) => {
254
+ let safeAttrs = attrs;
255
+ if (!/loading\s*=/.test(safeAttrs)) {
256
+ safeAttrs += ' loading="lazy"';
257
+ }
258
+ if (!/sandbox\s*=/.test(safeAttrs)) {
259
+ safeAttrs +=
260
+ ' sandbox="allow-scripts allow-same-origin allow-popups allow-presentation"';
261
+ }
262
+ if (!/referrerpolicy\s*=/.test(safeAttrs)) {
263
+ safeAttrs += ' referrerpolicy="no-referrer"';
264
+ }
265
+ if (!/style\s*=/.test(safeAttrs)) {
266
+ safeAttrs += ' style="max-width:100%;width:100%;border:0;display:block;"';
267
+ }
268
+ return `<iframe${safeAttrs}>`;
269
+ });
270
+ };
@@ -0,0 +1,16 @@
1
+ import type { MediaAttachmentData, ResourceKind } from '../types/models';
2
+ export declare const RESOURCE_KINDS: readonly ["video", "file", "gallery", "audio", "link"];
3
+ export declare const attachmentMediaKind: (att: Pick<MediaAttachmentData, "type" | "meta">) => "image" | "video" | "audio" | "file";
4
+ export declare const resourceHasRequiredMedia: (resource: {
5
+ resourceKind: ResourceKind;
6
+ url?: string;
7
+ attachments?: MediaAttachmentData[];
8
+ }) => boolean;
9
+ export type CategoryNode = {
10
+ name: string;
11
+ path: string[];
12
+ children: CategoryNode[];
13
+ };
14
+ export declare const categoryTreeFromPaths: (paths: readonly (readonly string[])[]) => CategoryNode[];
15
+ export declare const pathStartsWith: (path: readonly string[], prefix: readonly string[]) => boolean;
16
+ export declare const normalizeResourceTags: (tags: readonly string[] | undefined) => string[];
@@ -0,0 +1,64 @@
1
+ export const RESOURCE_KINDS = [
2
+ 'video',
3
+ 'file',
4
+ 'gallery',
5
+ 'audio',
6
+ 'link',
7
+ ];
8
+ export const attachmentMediaKind = (att) => {
9
+ const mime = att.meta?.mimetype ?? '';
10
+ const type = att.type ?? '';
11
+ if (type === 'image' || mime.startsWith('image/'))
12
+ return 'image';
13
+ if (type === 'video' || mime.startsWith('video/'))
14
+ return 'video';
15
+ if (type === 'audio' || mime.startsWith('audio/'))
16
+ return 'audio';
17
+ return 'file';
18
+ };
19
+ export const resourceHasRequiredMedia = (resource) => {
20
+ if (resource.resourceKind === 'link')
21
+ return Boolean(resource.url);
22
+ const need = resource.resourceKind === 'gallery'
23
+ ? 'image'
24
+ : resource.resourceKind === 'video'
25
+ ? 'video'
26
+ : resource.resourceKind === 'audio'
27
+ ? 'audio'
28
+ : 'file';
29
+ return (resource.attachments ?? []).some((att) => attachmentMediaKind(att) === need);
30
+ };
31
+ export const categoryTreeFromPaths = (paths) => {
32
+ const root = [];
33
+ for (const path of paths) {
34
+ let level = root;
35
+ const acc = [];
36
+ for (const name of path) {
37
+ const segment = name.trim();
38
+ if (!segment)
39
+ continue;
40
+ acc.push(segment);
41
+ let node = level.find((entry) => entry.name === segment);
42
+ if (!node) {
43
+ node = { name: segment, path: [...acc], children: [] };
44
+ level.push(node);
45
+ }
46
+ level = node.children;
47
+ }
48
+ }
49
+ return root;
50
+ };
51
+ export const pathStartsWith = (path, prefix) => prefix.length <= path.length &&
52
+ prefix.every((segment, index) => path[index] === segment);
53
+ export const normalizeResourceTags = (tags) => {
54
+ const seen = new Set();
55
+ const out = [];
56
+ for (const raw of tags ?? []) {
57
+ const tag = raw.replace(/^#/, '').trim().toLowerCase();
58
+ if (!tag || seen.has(tag))
59
+ continue;
60
+ seen.add(tag);
61
+ out.push(tag);
62
+ }
63
+ return out;
64
+ };
@@ -105,6 +105,7 @@ export declare const analyticsMemberRowSchema: z.ZodObject<{
105
105
  export type AnalyticsMemberRow = z.infer<typeof analyticsMemberRowSchema>;
106
106
  export declare const analyticsPostTypeKeySchema: z.ZodEnum<{
107
107
  jam: "jam";
108
+ resource: "resource";
108
109
  note: "note";
109
110
  event: "event";
110
111
  article: "article";
@@ -114,6 +115,7 @@ export type AnalyticsPostTypeKey = z.infer<typeof analyticsPostTypeKeySchema>;
114
115
  export declare const analyticsPostTypeCountSchema: z.ZodObject<{
115
116
  type: z.ZodEnum<{
116
117
  jam: "jam";
118
+ resource: "resource";
117
119
  note: "note";
118
120
  event: "event";
119
121
  article: "article";
@@ -130,6 +132,7 @@ export declare const analyticsStackedPointSchema: z.ZodObject<{
130
132
  note: z.ZodNumber;
131
133
  poll: z.ZodNumber;
132
134
  event: z.ZodNumber;
135
+ resource: z.ZodNumber;
133
136
  }, z.core.$strip>;
134
137
  export type AnalyticsStackedPoint = z.infer<typeof analyticsStackedPointSchema>;
135
138
  export declare const analyticsBucketedPointSchema: z.ZodObject<{
@@ -264,10 +267,12 @@ export declare const analyticsOverviewSchema: z.ZodObject<{
264
267
  note: z.ZodNumber;
265
268
  poll: z.ZodNumber;
266
269
  event: z.ZodNumber;
270
+ resource: z.ZodNumber;
267
271
  }, z.core.$strip>>;
268
272
  postTypes: z.ZodArray<z.ZodObject<{
269
273
  type: z.ZodEnum<{
270
274
  jam: "jam";
275
+ resource: "resource";
271
276
  note: "note";
272
277
  event: "event";
273
278
  article: "article";
@@ -88,6 +88,7 @@ export const analyticsPostTypeKeySchema = z.enum([
88
88
  'note',
89
89
  'poll',
90
90
  'event',
91
+ 'resource',
91
92
  ]);
92
93
  export const analyticsPostTypeCountSchema = z.object({
93
94
  type: analyticsPostTypeKeySchema,
@@ -101,6 +102,7 @@ export const analyticsStackedPointSchema = z.object({
101
102
  note: z.number(),
102
103
  poll: z.number(),
103
104
  event: z.number(),
105
+ resource: z.number(),
104
106
  });
105
107
  export const analyticsBucketedPointSchema = z.object({
106
108
  day: z.string(),