@openpeepshq/core 0.1.34 → 0.2.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.
Files changed (192) hide show
  1. package/dist/accessTokens/finders.js +5 -6
  2. package/dist/accessTokens/mutations.js +1 -1
  3. package/dist/accessTokens/tokens.js +8 -11
  4. package/dist/accounts/helpers.js +6 -2
  5. package/dist/accounts/mutations.js +13 -8
  6. package/dist/analytics/cache.js +3 -3
  7. package/dist/analytics/clicks.js +14 -22
  8. package/dist/analytics/compile.js +1 -2
  9. package/dist/analytics/dateRange.js +3 -5
  10. package/dist/analytics/jobs.js +3 -4
  11. package/dist/analytics/pdfReport.js +45 -61
  12. package/dist/analytics/privacy.js +1 -1
  13. package/dist/analytics/read.js +116 -135
  14. package/dist/analytics/report.d.ts +2 -1
  15. package/dist/analytics/report.js +2 -3
  16. package/dist/analytics/settings.js +3 -4
  17. package/dist/backups/index.js +13 -16
  18. package/dist/backups/metadata.js +1 -1
  19. package/dist/config/db.js +2 -4
  20. package/dist/config/defaults/community.js +1 -0
  21. package/dist/config/defaults/core.js +13 -8
  22. package/dist/config/defaults/logs.d.ts +4 -0
  23. package/dist/config/defaults/logs.js +5 -0
  24. package/dist/config/index.d.ts +9 -0
  25. package/dist/config/index.js +9 -11
  26. package/dist/db/explorer/query.js +9 -8
  27. package/dist/db/explorer/sql.js +8 -8
  28. package/dist/db/helpers.js +15 -5
  29. package/dist/db/migration/importCollections.js +15 -18
  30. package/dist/db/migration/shared.js +15 -35
  31. package/dist/db/pg/client.js +4 -7
  32. package/dist/db/pg/filters/index.js +1 -1
  33. package/dist/db/pg/filters/posts.d.ts +2 -0
  34. package/dist/db/pg/filters/posts.js +3 -1
  35. package/dist/db/pg/helpers.js +2 -14
  36. package/dist/db/pg/map/filters.js +8 -8
  37. package/dist/db/pg/map/helpers.js +5 -1
  38. package/dist/db/pg/map/index.js +46 -51
  39. package/dist/db/pg/map/mutations.js +56 -21
  40. package/dist/db/pg/map/registry.js +87 -50
  41. package/dist/db/pg/map/relations.js +67 -63
  42. package/dist/db/pg/map/search.js +15 -37
  43. package/dist/db/pg/mappers.js +13 -7
  44. package/dist/db/pg/migrate.js +2 -3
  45. package/dist/db/pg/queries/activity.js +2 -2
  46. package/dist/db/pg/queries/derived.js +8 -12
  47. package/dist/db/pg/schema/documents.js +119 -18
  48. package/dist/db/pg/schema/edges.js +7 -1
  49. package/dist/db/pg/schema/index.js +5 -1
  50. package/dist/db/pg/sql/0016_posts_search_vector_title_tags_path.sql +54 -0
  51. package/dist/db/pg/sql/meta/_journal.json +8 -1
  52. package/dist/db/replaceOrigin.js +1 -1
  53. package/dist/email/queueStats.js +8 -11
  54. package/dist/email/render.js +7 -4
  55. package/dist/email/send.js +19 -17
  56. package/dist/email/smtpTest.js +10 -6
  57. package/dist/errors/index.js +1 -1
  58. package/dist/events/once.js +2 -4
  59. package/dist/federation/activities.js +1 -2
  60. package/dist/groups/finders.d.ts +2 -2
  61. package/dist/groups/helpers.d.ts +6 -6
  62. package/dist/groups/helpers.js +1 -2
  63. package/dist/groups/mapping.d.ts +4 -4
  64. package/dist/groups/mutations.js +1 -1
  65. package/dist/hashtags/finders.js +2 -2
  66. package/dist/inviteLinks/mutations.js +2 -3
  67. package/dist/jams/export.js +5 -7
  68. package/dist/jams/finders.js +4 -1
  69. package/dist/jams/health.d.ts +6 -4
  70. package/dist/jams/health.js +15 -11
  71. package/dist/jams/helpers.d.ts +2 -2
  72. package/dist/jams/helpers.js +6 -2
  73. package/dist/jams/index.js +2 -2
  74. package/dist/jams/jobs.js +1 -2
  75. package/dist/jams/livekit.d.ts +2 -2
  76. package/dist/jams/livekit.js +8 -8
  77. package/dist/jams/mapping.d.ts +10 -10
  78. package/dist/jams/mutations.d.ts +2 -2
  79. package/dist/jams/recording.js +1 -1
  80. package/dist/jams/token.js +13 -17
  81. package/dist/jobs/index.js +7 -6
  82. package/dist/jobs/jobDetail.js +5 -6
  83. package/dist/jobs/jobLog.js +2 -3
  84. package/dist/lib/streams.js +4 -39
  85. package/dist/lib/zodDeepPartial.d.ts +1 -1
  86. package/dist/lib/zodDeepPartial.js +1 -1
  87. package/dist/log/index.d.ts +1 -0
  88. package/dist/log/index.js +14 -29
  89. package/dist/log/retention.d.ts +9 -0
  90. package/dist/log/retention.js +83 -0
  91. package/dist/log/retentionJobs.d.ts +17 -0
  92. package/dist/log/retentionJobs.js +50 -0
  93. package/dist/media/index.js +127 -4
  94. package/dist/media/jobs.js +1 -2
  95. package/dist/media/openpeeps/index.js +11 -46
  96. package/dist/media/processing.js +7 -4
  97. package/dist/media/streaming.js +5 -5
  98. package/dist/media/streamingCleanupJobs.js +1 -2
  99. package/dist/media/streamingJobs.js +3 -4
  100. package/dist/media/streamingPrewarm.js +7 -11
  101. package/dist/mediaAttachments/index.js +6 -2
  102. package/dist/mediaAttachments/mapping.d.ts +1 -1
  103. package/dist/notifications/defaultNotifications/announcement/index.js +15 -18
  104. package/dist/notifications/defaultNotifications/directMessage/index.js +9 -8
  105. package/dist/notifications/defaultNotifications/follow/index.js +14 -17
  106. package/dist/notifications/defaultNotifications/groupAdded/index.js +14 -17
  107. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +15 -18
  108. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +15 -18
  109. package/dist/notifications/defaultNotifications/jamModerator/index.js +27 -20
  110. package/dist/notifications/defaultNotifications/jamModerator/recipients.d.ts +2 -0
  111. package/dist/notifications/defaultNotifications/jamModerator/recipients.js +5 -0
  112. package/dist/notifications/defaultNotifications/jamSpeaker/index.js +14 -18
  113. package/dist/notifications/defaultNotifications/jamStarted/index.js +18 -22
  114. package/dist/notifications/defaultNotifications/mention/index.js +20 -24
  115. package/dist/notifications/defaultNotifications/newGroupPost/index.js +9 -10
  116. package/dist/notifications/defaultNotifications/newGroupPost/recipients.d.ts +5 -0
  117. package/dist/notifications/defaultNotifications/newGroupPost/recipients.js +23 -0
  118. package/dist/notifications/defaultNotifications/newProfile/index.js +14 -17
  119. package/dist/notifications/defaultNotifications/pollEnded/index.js +21 -21
  120. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +2 -3
  121. package/dist/notifications/defaultNotifications/pollVote/index.js +14 -17
  122. package/dist/notifications/defaultNotifications/reaction/index.js +18 -21
  123. package/dist/notifications/defaultNotifications/reply/index.js +21 -22
  124. package/dist/notifications/defaultNotifications/repost/index.js +16 -20
  125. package/dist/notifications/defaultNotifications/rsvp/index.js +24 -18
  126. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +20 -13
  127. package/dist/notifications/eventIcsAttachment.d.ts +6 -0
  128. package/dist/notifications/eventIcsAttachment.js +32 -0
  129. package/dist/notifications/fcmCredential.js +1 -1
  130. package/dist/notifications/finders.js +1 -1
  131. package/dist/notifications/helpers.d.ts +11 -1
  132. package/dist/notifications/helpers.js +38 -9
  133. package/dist/notifications/jobs.js +16 -7
  134. package/dist/notifications/mutations.js +13 -2
  135. package/dist/notifications/push.js +11 -16
  136. package/dist/performance/index.js +3 -3
  137. package/dist/plugins/helpers.js +3 -6
  138. package/dist/plugins/index.js +2 -3
  139. package/dist/plugins/install.js +31 -17
  140. package/dist/plugins/pluginAuth.js +3 -4
  141. package/dist/plugins/state.js +2 -3
  142. package/dist/posts/activity.d.ts +1 -1
  143. package/dist/posts/activity.js +2 -3
  144. package/dist/posts/contextClosure.js +1 -2
  145. package/dist/posts/conversationQueries.js +2 -4
  146. package/dist/posts/eventAgenda.js +12 -7
  147. package/dist/posts/eventOccurrences.js +2 -2
  148. package/dist/posts/finders.d.ts +46 -6
  149. package/dist/posts/finders.js +21 -9
  150. package/dist/posts/helpers/filters.js +2 -3
  151. package/dist/posts/helpers/index.d.ts +170 -18
  152. package/dist/posts/helpers/index.js +43 -27
  153. package/dist/posts/mapping.d.ts +616 -84
  154. package/dist/posts/mapping.js +60 -18
  155. package/dist/posts/mutations.d.ts +85 -9
  156. package/dist/posts/mutations.js +47 -34
  157. package/dist/posts/pollEnd.js +3 -6
  158. package/dist/posts/rsvpConfirmationEmail.js +18 -8
  159. package/dist/posts/threadPreview.js +1 -1
  160. package/dist/processingStats/queries.js +6 -7
  161. package/dist/profileSettings/cache.js +1 -2
  162. package/dist/profileSettings/mapping.d.ts +1 -0
  163. package/dist/profiles/activitySummary.js +23 -28
  164. package/dist/profiles/cache.js +15 -8
  165. package/dist/profiles/export.js +30 -39
  166. package/dist/profiles/finders.js +7 -5
  167. package/dist/profiles/mapping.d.ts +10 -10
  168. package/dist/profiles/mutations.js +3 -5
  169. package/dist/redis/connection.js +1 -1
  170. package/dist/reports/helpers.js +7 -3
  171. package/dist/reports/mapping.d.ts +1 -1
  172. package/dist/roles/mutations.js +20 -21
  173. package/dist/search/finders.js +15 -3
  174. package/dist/search/helpers.js +1 -1
  175. package/dist/sentry/index.js +9 -11
  176. package/dist/seo/index.d.ts +50 -0
  177. package/dist/seo/index.js +145 -0
  178. package/dist/seo/route.d.ts +18 -0
  179. package/dist/seo/route.js +19 -0
  180. package/dist/server/index.d.ts +1 -0
  181. package/dist/server/index.js +16 -11
  182. package/dist/server/status.js +6 -7
  183. package/dist/session/index.js +2 -2
  184. package/dist/stats/finders.js +13 -4
  185. package/dist/stats/helpers.js +4 -1
  186. package/dist/stats/mapping.d.ts +43 -5
  187. package/dist/stats/mapping.js +9 -2
  188. package/dist/stripe/cache.js +5 -6
  189. package/dist/stripe/connection.js +3 -4
  190. package/dist/stripe/helpers.js +15 -20
  191. package/package.json +5 -6
  192. package/LICENSE +0 -674
@@ -1,3 +1,4 @@
1
1
  import type { LoggerFactory } from '@openpeepshq/common/types';
2
+ export { logRetentionQueue, logRetentionWorker, ensureLogRetentionSchedule, LOG_RETENTION_CRON, type LogRetentionJobData, } from './retentionJobs';
2
3
  export declare const listLogs: (date?: Date) => Promise<any[]>;
3
4
  export declare const logger: LoggerFactory;
package/dist/log/index.js CHANGED
@@ -1,10 +1,3 @@
1
- var __asyncValues = (this && this.__asyncValues) || function (o) {
2
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3
- var m = o[Symbol.asyncIterator], i;
4
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
5
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
6
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
7
- };
8
1
  import { createReadStream, existsSync, mkdirSync } from 'node:fs';
9
2
  import { appendFile } from 'node:fs/promises';
10
3
  import { join } from 'node:path';
@@ -12,10 +5,10 @@ import * as readline from 'node:readline';
12
5
  import { formatDate } from 'date-fns/format';
13
6
  import safeJsonStringify from 'safe-json-stringify';
14
7
  import { default as logsConfig } from '../config/defaults/logs.js';
8
+ export { logRetentionQueue, logRetentionWorker, ensureLogRetentionSchedule, LOG_RETENTION_CRON, } from './retentionJobs.js';
15
9
  const createLogDirectory = () => mkdirSync(logsConfig.local.path, { recursive: true });
16
10
  const currentFile = (date) => join(logsConfig.local.path, formatDate(date, 'yyyyMMdd') + '.log');
17
11
  export const listLogs = async (date = new Date()) => {
18
- var _a, e_1, _b, _c;
19
12
  const filePath = currentFile(date);
20
13
  if (!existsSync(filePath)) {
21
14
  return [];
@@ -26,25 +19,13 @@ export const listLogs = async (date = new Date()) => {
26
19
  crlfDelay: Infinity,
27
20
  });
28
21
  const lines = [];
29
- try {
30
- for (var _d = true, iterator_1 = __asyncValues(iterator), iterator_1_1; iterator_1_1 = await iterator_1.next(), _a = iterator_1_1.done, !_a; _d = true) {
31
- _c = iterator_1_1.value;
32
- _d = false;
33
- const logLine = _c;
34
- try {
35
- lines.push(JSON.parse(logLine));
36
- }
37
- catch (_e) {
38
- // skip malformed lines
39
- }
40
- }
41
- }
42
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
43
- finally {
22
+ for await (const logLine of iterator) {
44
23
  try {
45
- if (!_d && !_a && (_b = iterator_1.return)) await _b.call(iterator_1);
24
+ lines.push(JSON.parse(logLine));
25
+ }
26
+ catch {
27
+ // skip malformed lines
46
28
  }
47
- finally { if (e_1) throw e_1.error; }
48
29
  }
49
30
  return lines.reverse();
50
31
  };
@@ -62,7 +43,12 @@ const namespaceLogLevels = {};
62
43
  /** Errors stringify to `{}` unless message/stack are copied onto enumerable keys. */
63
44
  const serializeLogArg = (arg) => {
64
45
  if (arg instanceof Error) {
65
- return safeJsonStringify(Object.assign({ name: arg.name, message: arg.message, stack: arg.stack }, arg));
46
+ return safeJsonStringify({
47
+ name: arg.name,
48
+ message: arg.message,
49
+ stack: arg.stack,
50
+ ...arg,
51
+ });
66
52
  }
67
53
  if (arg !== null && typeof arg === 'object') {
68
54
  return safeJsonStringify(arg);
@@ -72,12 +58,11 @@ const serializeLogArg = (arg) => {
72
58
  export const logger = (ns, meta) => {
73
59
  createLogDirectory();
74
60
  const log = (level, ...args) => {
75
- var _a;
76
- if (logLevels[level] < ((_a = namespaceLogLevels[ns]) !== null && _a !== void 0 ? _a : defaultLogLevel)) {
61
+ if (logLevels[level] < (namespaceLogLevels[ns] ?? defaultLogLevel)) {
77
62
  return;
78
63
  }
79
64
  const date = new Date();
80
- console.log(`${date.toISOString()} - ${ns} - ${level} | `, ...args, meta !== null && meta !== void 0 ? meta : '');
65
+ console.log(`${date.toISOString()} - ${ns} - ${level} | `, ...args, meta ?? '');
81
66
  appendFile(currentFile(date), JSON.stringify({
82
67
  level,
83
68
  message: args.map(serializeLogArg).join(' '),
@@ -0,0 +1,9 @@
1
+ export interface LogRetentionResult {
2
+ /** Log files archived to a .zip during this run. */
3
+ zipped: string[];
4
+ /** Files (log and .zip) removed during this run. */
5
+ deleted: string[];
6
+ /** Log files under the zip threshold, or already zipped. */
7
+ untouched: number;
8
+ }
9
+ export declare const cleanOldLogs: (dir: string, zipAfterDays: number, deleteAfterDays: number) => Promise<LogRetentionResult>;
@@ -0,0 +1,83 @@
1
+ import { createReadStream, createWriteStream } from 'node:fs';
2
+ import { readdir, rm, stat } from 'node:fs/promises';
3
+ import { basename, join } from 'node:path';
4
+ import archiver from 'archiver';
5
+ const DAY_MS = 24 * 60 * 60 * 1000;
6
+ /** Daily log file as written by the logger, e.g. `20261001.log`. */
7
+ const RAW_LOG_FILE = /^\d{8}\.log$/;
8
+ /** Archive produced by `cleanOldLogs`, e.g. `20261001.log.zip`. */
9
+ const LOG_ZIP_FILE = /^\d{8}\.log\.zip$/;
10
+ const fileExists = async (path) => {
11
+ try {
12
+ await stat(path);
13
+ return true;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ };
19
+ const zipLogFile = (file, zipPath) => new Promise((resolve, reject) => {
20
+ const output = createWriteStream(zipPath);
21
+ const archive = archiver('zip', { zlib: { level: 9 } });
22
+ output.on('close', () => resolve());
23
+ output.on('error', reject);
24
+ archive.on('error', reject);
25
+ archive.on('warning', (err) => {
26
+ if (err.code === 'ENOENT')
27
+ return;
28
+ reject(err);
29
+ });
30
+ archive.pipe(output);
31
+ archive.append(createReadStream(file), { name: basename(file) });
32
+ void archive.finalize();
33
+ });
34
+ export const cleanOldLogs = async (dir, zipAfterDays, deleteAfterDays) => {
35
+ const result = { zipped: [], deleted: [], untouched: 0 };
36
+ const now = Date.now();
37
+ let entries;
38
+ try {
39
+ entries = await readdir(dir);
40
+ }
41
+ catch (err) {
42
+ // The log directory is created lazily by the logger; nothing to clean.
43
+ if (err.code === 'ENOENT')
44
+ return result;
45
+ throw err;
46
+ }
47
+ for (const entry of entries) {
48
+ const isRawLog = RAW_LOG_FILE.test(entry);
49
+ if (!isRawLog && !LOG_ZIP_FILE.test(entry))
50
+ continue;
51
+ const filePath = join(dir, entry);
52
+ // May already be gone: deleting a raw log also removes its zip.
53
+ if (!(await fileExists(filePath)))
54
+ continue;
55
+ const st = await stat(filePath);
56
+ if (!st.isFile())
57
+ continue;
58
+ if (now - st.mtimeMs > deleteAfterDays * DAY_MS) {
59
+ // Zips share the raw log's lifetime so disk usage actually shrinks.
60
+ await rm(filePath, { force: true });
61
+ result.deleted.push(entry);
62
+ if (isRawLog) {
63
+ const zipPath = `${filePath}.zip`;
64
+ if (await fileExists(zipPath)) {
65
+ await rm(zipPath, { force: true });
66
+ result.deleted.push(`${entry}.zip`);
67
+ }
68
+ }
69
+ continue;
70
+ }
71
+ if (!isRawLog)
72
+ continue;
73
+ if (now - st.mtimeMs > zipAfterDays * DAY_MS &&
74
+ !(await fileExists(`${filePath}.zip`))) {
75
+ await zipLogFile(filePath, `${filePath}.zip`);
76
+ result.zipped.push(entry);
77
+ }
78
+ else {
79
+ result.untouched += 1;
80
+ }
81
+ }
82
+ return result;
83
+ };
@@ -0,0 +1,17 @@
1
+ export declare const LOG_RETENTION_CRON = "0 2 * * *";
2
+ export interface LogRetentionJobData {
3
+ /** Override the zip threshold; mostly for testing. */
4
+ zipAfterDays?: number;
5
+ /** Override the delete threshold; mostly for testing. */
6
+ deleteAfterDays?: number;
7
+ /** Override the log directory; mostly for testing. */
8
+ dir?: string;
9
+ }
10
+ declare const logRetentionQueue: () => import("bullmq").Queue, logRetentionWorker: () => import("bullmq").Worker;
11
+ /**
12
+ * Registers (or refreshes) the daily schedule with BullMQ. Safe to call
13
+ * repeatedly — `upsertJobScheduler` is idempotent and overwrites the existing
14
+ * schedule entry under the same id.
15
+ */
16
+ export declare const ensureLogRetentionSchedule: () => Promise<void>;
17
+ export { logRetentionQueue, logRetentionWorker };
@@ -0,0 +1,50 @@
1
+ import { queueAndWorker } from '../jobs/index.js';
2
+ import { cleanOldLogs } from './retention.js';
3
+ // Cron pattern (UTC): every day at 02:00. Off-peak for most regions and
4
+ // staggered away from the other daily housekeeping (streaming cleanup 03:00,
5
+ // analytics retention 03:30, event occurrences 04:00).
6
+ export const LOG_RETENTION_CRON = '0 2 * * *';
7
+ const SCHEDULER_ID = 'log-retention-daily';
8
+ const JOB_NAME = 'clean';
9
+ const [logRetentionQueue, logRetentionWorker] = queueAndWorker('log-retention', async (job) => {
10
+ // Dynamic imports: the log barrel is among the first modules loaded,
11
+ // and ../config -> ../events -> this barrel, so a static edge would
12
+ // create a load-time import cycle.
13
+ const { logger } = await import('./index.js');
14
+ const { config } = await import('../config/index.js');
15
+ const log = logger('app:log:retention');
16
+ const coreConfig = await config();
17
+ const zipAfterDays = job.data.zipAfterDays ?? coreConfig.logs.retention.zipAfterDays;
18
+ const deleteAfterDays = job.data.deleteAfterDays ?? coreConfig.logs.retention.deleteAfterDays;
19
+ const dir = job.data.dir ?? coreConfig.logs.local.path;
20
+ log.info(`Running log retention (zipAfterDays=${zipAfterDays}, ` +
21
+ `deleteAfterDays=${deleteAfterDays})`);
22
+ const result = await cleanOldLogs(dir, zipAfterDays, deleteAfterDays);
23
+ log.info(`Log retention done: zipped=${result.zipped.length}, ` +
24
+ `deleted=${result.deleted.length}, untouched=${result.untouched}`);
25
+ if (result.zipped.length > 0) {
26
+ log.info(`Zipped logs: ${result.zipped.join(', ')}`);
27
+ }
28
+ if (result.deleted.length > 0) {
29
+ log.info(`Deleted logs: ${result.deleted.join(', ')}`);
30
+ }
31
+ }, {
32
+ defaultJobOptions: {
33
+ // We never need more than the most recent runs; keep a small history
34
+ // for debugging and let BullMQ trim the rest.
35
+ removeOnComplete: { count: 10 },
36
+ removeOnFail: { age: 86400 * 14, count: 50 },
37
+ },
38
+ });
39
+ /**
40
+ * Registers (or refreshes) the daily schedule with BullMQ. Safe to call
41
+ * repeatedly — `upsertJobScheduler` is idempotent and overwrites the existing
42
+ * schedule entry under the same id.
43
+ */
44
+ export const ensureLogRetentionSchedule = async () => {
45
+ const queue = logRetentionQueue();
46
+ await queue.upsertJobScheduler(SCHEDULER_ID, { pattern: LOG_RETENTION_CRON }, { name: JOB_NAME });
47
+ const { logger } = await import('./index.js');
48
+ logger('app:log:retention').info(`Log retention schedule registered: cron="${LOG_RETENTION_CRON}"`);
49
+ };
50
+ export { logRetentionQueue, logRetentionWorker };
@@ -8,6 +8,7 @@ import fs from 'node:fs/promises';
8
8
  import { createReadStream, createWriteStream } from 'node:fs';
9
9
  import { Readable } from 'node:stream';
10
10
  import { pipeline } from 'node:stream/promises';
11
+ import { spawn } from 'node:child_process';
11
12
  import { getTheme, randomString } from '@openpeepshq/common/lib';
12
13
  import { logger } from '../log/index.js';
13
14
  import { hub } from '../events/index.js';
@@ -107,7 +108,7 @@ export const createPreview = async (inputPath, mimetype, originalName) => {
107
108
  if (originalName.endsWith('.mkv')) {
108
109
  return createVideoPreview(inputPath);
109
110
  }
110
- return { path: inputPath, mimetype };
111
+ return createFilePreview(inputPath, mimetype, originalName);
111
112
  }
112
113
  };
113
114
  const createImagePreview = async (inputPath, mimetype) => {
@@ -125,6 +126,128 @@ const createImagePreview = async (inputPath, mimetype) => {
125
126
  .toFile(outputPath);
126
127
  return { path: outputPath, mimetype: 'image/webp' };
127
128
  };
129
+ const escapeXml = (value) => value
130
+ .replace(/&/g, '&amp;')
131
+ .replace(/</g, '&lt;')
132
+ .replace(/>/g, '&gt;')
133
+ .replace(/"/g, '&quot;');
134
+ /**
135
+ * Render the first page of a PDF to a WebP thumbnail via sharp. The prebuilt
136
+ * sharp binary bundles poppler, so PDF decoding is available without any extra
137
+ * system packages on Linux/musl (Alpine) and glibc.
138
+ */
139
+ const createPdfPreview = async (inputPath) => {
140
+ const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
141
+ await sharp(inputPath, { density: 150, pages: 1 })
142
+ .resize(previewMaxWidth)
143
+ .webp({ quality: 80 })
144
+ .toFile(outputPath);
145
+ return { path: outputPath, mimetype: 'image/webp' };
146
+ };
147
+ const OFFICE_DOC_EXTENSIONS = new Set([
148
+ '.docx',
149
+ '.doc',
150
+ '.xlsx',
151
+ '.xls',
152
+ '.pptx',
153
+ '.ppt',
154
+ '.odt',
155
+ '.ods',
156
+ '.odp',
157
+ ]);
158
+ const isOfficeDocument = (originalName) => OFFICE_DOC_EXTENSIONS.has(path.extname(originalName).toLowerCase());
159
+ /**
160
+ * Convert an office document (docx/xlsx/pptx/etc.) to PDF using LibreOffice in
161
+ * headless mode. Returns the path to the generated PDF inside a temp directory
162
+ * the caller is responsible for cleaning up.
163
+ */
164
+ const convertOfficeToPdf = async (inputPath, originalName) => {
165
+ const outputDir = join(tmpdir(), `office-${randomString(16)}`);
166
+ await fs.mkdir(outputDir, { recursive: true });
167
+ await new Promise((resolve, reject) => {
168
+ const proc = spawn('libreoffice', [
169
+ '--headless',
170
+ '--no-first-run',
171
+ '--nofirstwizard',
172
+ '--norestore',
173
+ '--nologging',
174
+ '--convert-to',
175
+ 'pdf',
176
+ '--outdir',
177
+ outputDir,
178
+ inputPath,
179
+ ], { stdio: ['ignore', 'ignore', 'pipe'] });
180
+ let stderr = '';
181
+ proc.stderr?.setEncoding('utf8');
182
+ proc.stderr?.on('data', (chunk) => {
183
+ stderr += chunk;
184
+ });
185
+ proc.on('error', (err) => {
186
+ reject(err.code === 'ENOENT' ? new Error('libreoffice binary not found') : err);
187
+ });
188
+ proc.on('close', (code) => {
189
+ if (code === 0) {
190
+ resolve();
191
+ }
192
+ else {
193
+ reject(new Error(`libreoffice conversion failed (exit ${code}): ${stderr}`));
194
+ }
195
+ });
196
+ });
197
+ const files = await fs.readdir(outputDir);
198
+ const pdfFile = files.find((f) => f.endsWith('.pdf'));
199
+ if (!pdfFile) {
200
+ throw new Error(`libreoffice did not produce a PDF for ${originalName}`);
201
+ }
202
+ return join(outputDir, pdfFile);
203
+ };
204
+ const createDocumentCardPreview = async (originalName) => {
205
+ const ext = (path.extname(originalName).replace('.', '') || 'FILE')
206
+ .slice(0, 8)
207
+ .toUpperCase();
208
+ const base = path.parse(originalName).name.slice(0, 28);
209
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="700" height="700">
210
+ <rect width="700" height="700" fill="#f4f4f5"/>
211
+ <rect x="160" y="80" width="380" height="480" rx="16" fill="#ffffff" stroke="#d4d4d8" stroke-width="4"/>
212
+ <rect x="210" y="140" width="180" height="72" rx="8" fill="#18181b"/>
213
+ <text x="300" y="188" text-anchor="middle" font-family="sans-serif" font-size="28" font-weight="700" fill="#ffffff">${escapeXml(ext)}</text>
214
+ <text x="350" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="#18181b">${escapeXml(base)}</text>
215
+ </svg>`;
216
+ const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
217
+ await sharp(Buffer.from(svg)).webp({ quality: 80 }).toFile(outputPath);
218
+ return { path: outputPath, mimetype: 'image/webp' };
219
+ };
220
+ const createFilePreview = async (inputPath, mimetype, originalName) => {
221
+ const isPdf = mimetype === 'application/pdf' ||
222
+ originalName.toLowerCase().endsWith('.pdf');
223
+ if (isPdf) {
224
+ try {
225
+ return await createPdfPreview(inputPath);
226
+ }
227
+ catch {
228
+ // sharp PDF support may be missing; fall back to card preview below.
229
+ }
230
+ }
231
+ if (isOfficeDocument(originalName)) {
232
+ let pdfPath;
233
+ try {
234
+ pdfPath = await convertOfficeToPdf(inputPath, originalName);
235
+ return await createPdfPreview(pdfPath);
236
+ }
237
+ catch (error) {
238
+ const message = error instanceof Error ? error.message : String(error);
239
+ log.warn(`Office document preview failed for ${originalName}: ${message}`);
240
+ }
241
+ finally {
242
+ if (pdfPath) {
243
+ await fs
244
+ .rm(path.dirname(pdfPath), { recursive: true, force: true })
245
+ .catch(() => undefined);
246
+ }
247
+ }
248
+ }
249
+ return createDocumentCardPreview(originalName);
250
+ };
128
251
  const getMediaDuration = (filePath) => new Promise((resolve, reject) => {
129
252
  ffmpeg.ffprobe(filePath, (err, metadata) => {
130
253
  if (err) {
@@ -144,14 +267,14 @@ const getMediaDuration = (filePath) => new Promise((resolve, reject) => {
144
267
  });
145
268
  const getVideoStreamInfo = (filePath) => new Promise((resolve, reject) => {
146
269
  ffmpeg.ffprobe(filePath, (err, metadata) => {
147
- var _a;
148
270
  if (err) {
149
271
  reject(err);
150
272
  return;
151
273
  }
152
274
  const stream = metadata.streams.find((s) => s.codec_type === 'video');
153
- const duration = (_a = metadata.format.duration) !== null && _a !== void 0 ? _a : ((stream === null || stream === void 0 ? void 0 : stream.duration) ? Number(stream.duration) : undefined);
154
- if (!(stream === null || stream === void 0 ? void 0 : stream.width) || !(stream === null || stream === void 0 ? void 0 : stream.height) || !duration) {
275
+ const duration = metadata.format.duration ??
276
+ (stream?.duration ? Number(stream.duration) : undefined);
277
+ if (!stream?.width || !stream?.height || !duration) {
155
278
  reject(new Error('Could not determine video stream info'));
156
279
  return;
157
280
  }
@@ -42,13 +42,12 @@ export const subscribeToMediaProgress = async (mediaAttachmentId, onMessage) =>
42
42
  return () => disconnect(conn);
43
43
  };
44
44
  const [mediaProcessingQueue, mediaProcessingWorker] = queueAndWorker('media-processing', async (job) => {
45
- var _a;
46
45
  const { mediaAttachmentId, fileStorageKey } = job.data;
47
46
  const attachment = await findMediaAttachment(mediaAttachmentId);
48
47
  if (!attachment) {
49
48
  throw new Error(`MediaAttachment ${mediaAttachmentId} not found in worker`);
50
49
  }
51
- const filesize = (_a = attachment.meta.size) !== null && _a !== void 0 ? _a : 0;
50
+ const filesize = attachment.meta.size ?? 0;
52
51
  const estimatedDurationMs = await estimateProcessingDuration({
53
52
  filetype: attachment.type,
54
53
  filesize,
@@ -1,23 +1,3 @@
1
- var __asyncValues = (this && this.__asyncValues) || function (o) {
2
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3
- var m = o[Symbol.asyncIterator], i;
4
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
5
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
6
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
7
- };
8
- var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
9
- var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
10
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
11
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
12
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
13
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
14
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
15
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
16
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
17
- function fulfill(value) { resume("next", value); }
18
- function reject(value) { resume("throw", value); }
19
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
20
- };
21
1
  import { createHash, randomBytes } from 'node:crypto';
22
2
  import { createReadStream, createWriteStream } from 'node:fs';
23
3
  import fs from 'node:fs/promises';
@@ -48,32 +28,17 @@ const allpeepStorage = async (params) => {
48
28
  let size = 0;
49
29
  const source = Readable.fromWeb(stream);
50
30
  try {
51
- await pipeline(source, function (input) {
52
- return __asyncGenerator(this, arguments, function* () {
53
- var _a, e_1, _b, _c;
54
- try {
55
- for (var _d = true, input_1 = __asyncValues(input), input_1_1; input_1_1 = yield __await(input_1.next()), _a = input_1_1.done, !_a; _d = true) {
56
- _c = input_1_1.value;
57
- _d = false;
58
- const chunk = _c;
59
- // pipeline can yield Buffer or string depending on encoding; force
60
- // through the Buffer path so the hash and byte count are correct.
61
- const buf = chunk instanceof Buffer
62
- ? chunk
63
- : Buffer.from(chunk);
64
- hash.update(buf);
65
- size += buf.length;
66
- yield yield __await(buf);
67
- }
68
- }
69
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
70
- finally {
71
- try {
72
- if (!_d && !_a && (_b = input_1.return)) yield __await(_b.call(input_1));
73
- }
74
- finally { if (e_1) throw e_1.error; }
75
- }
76
- });
31
+ await pipeline(source, async function* (input) {
32
+ for await (const chunk of input) {
33
+ // pipeline can yield Buffer or string depending on encoding; force
34
+ // through the Buffer path so the hash and byte count are correct.
35
+ const buf = chunk instanceof Buffer
36
+ ? chunk
37
+ : Buffer.from(chunk);
38
+ hash.update(buf);
39
+ size += buf.length;
40
+ yield buf;
41
+ }
77
42
  }, createWriteStream(tempPath));
78
43
  }
79
44
  catch (err) {
@@ -16,7 +16,6 @@ export const runProcessing = async (input) => withSpan('worker.media.processing'
16
16
  mediaAttachmentId: input.mediaAttachmentId,
17
17
  });
18
18
  const runProcessingBody = async ({ mediaAttachmentId, sourceStorageKey, thumbnail, }) => {
19
- var _a, _b;
20
19
  const startedAt = Date.now();
21
20
  const attachment = await findMediaAttachment(mediaAttachmentId);
22
21
  if (!attachment) {
@@ -24,7 +23,7 @@ const runProcessingBody = async ({ mediaAttachmentId, sourceStorageKey, thumbnai
24
23
  }
25
24
  const filetype = attachment.type;
26
25
  const originalName = attachment.filename;
27
- const sourceMimetype = (_a = attachment.meta.mimetype) !== null && _a !== void 0 ? _a : '';
26
+ const sourceMimetype = attachment.meta.mimetype ?? '';
28
27
  const temps = new Set();
29
28
  try {
30
29
  const storage = await mediaStorage();
@@ -66,14 +65,18 @@ const runProcessingBody = async ({ mediaAttachmentId, sourceStorageKey, thumbnai
66
65
  const updated = await updateMediaAttachment(mediaAttachmentId, {
67
66
  url,
68
67
  previewUrl,
69
- meta: Object.assign(Object.assign({}, attachment.meta), { mimetype: transcoded.mimetype, size: storedSize }),
68
+ meta: {
69
+ ...attachment.meta,
70
+ mimetype: transcoded.mimetype,
71
+ size: storedSize,
72
+ },
70
73
  status: 'ready',
71
74
  error: undefined,
72
75
  });
73
76
  const durationMs = Date.now() - startedAt;
74
77
  await recordProcessingStats({
75
78
  mediaAttachmentId,
76
- filesize: (_b = attachment.meta.size) !== null && _b !== void 0 ? _b : storedSize,
79
+ filesize: attachment.meta.size ?? storedSize,
77
80
  filetype,
78
81
  durationMs,
79
82
  }).catch((e) => log.error('Failed to record processing stats', e));
@@ -13,7 +13,7 @@ const STREAM_ACCESS_KEY = 'media:streaming:lastAccess';
13
13
  // segments and we don't need to hammer Redis with a write for each. The
14
14
  // debounce is per-process; multiple app/worker processes will each issue at
15
15
  // most one write per window which is still fine.
16
- const ACCESS_WRITE_DEBOUNCE_MS = 60000;
16
+ const ACCESS_WRITE_DEBOUNCE_MS = 60_000;
17
17
  const lastAccessWriteCache = new Map();
18
18
  const getStorageParams = async () => (await config()).media.storage.params;
19
19
  const getHlsRoot = async () => {
@@ -47,7 +47,7 @@ export const parseLocalStorageUrl = async (rawUrl) => {
47
47
  try {
48
48
  url = new URL(rawUrl);
49
49
  }
50
- catch (_a) {
50
+ catch {
51
51
  return null;
52
52
  }
53
53
  const rootUrl = await serverRootUrl();
@@ -115,7 +115,7 @@ export const getStreamStatus = async (storageId) => {
115
115
  return null;
116
116
  }
117
117
  }
118
- catch (_a) {
118
+ catch {
119
119
  return null;
120
120
  }
121
121
  const errorsPath = join(streamDir, HLS_ERRORS_LOG);
@@ -140,7 +140,7 @@ export const buildStream = async (storageId) => {
140
140
  if (!status) {
141
141
  return null;
142
142
  }
143
- return Object.assign({ storageId }, status);
143
+ return { storageId, ...status };
144
144
  };
145
145
  export const ensureStreamDir = async (storageId) => {
146
146
  const streamDir = await getStreamDir(storageId);
@@ -225,7 +225,7 @@ export const cleanupStaleStreams = async (maxAgeMs) => {
225
225
  try {
226
226
  stat = await fs.stat(fullPath);
227
227
  }
228
- catch (_a) {
228
+ catch {
229
229
  continue;
230
230
  }
231
231
  if (!stat.isDirectory())
@@ -10,8 +10,7 @@ export const STREAM_CLEANUP_CRON = '0 3 * * *';
10
10
  const SCHEDULER_ID = 'streaming-cleanup-daily';
11
11
  const JOB_NAME = 'cleanup';
12
12
  const [mediaStreamingCleanupQueue, mediaStreamingCleanupWorker] = queueAndWorker('media-streaming-cleanup', async (job) => {
13
- var _a;
14
- const maxAgeMs = (_a = job.data.maxAgeMs) !== null && _a !== void 0 ? _a : STREAM_INACTIVITY_TTL_MS;
13
+ const maxAgeMs = job.data.maxAgeMs ?? STREAM_INACTIVITY_TTL_MS;
15
14
  log.info(`Running stream cleanup (maxAgeMs=${maxAgeMs}, ~${Math.round(maxAgeMs / DAY_MS)}d)`);
16
15
  const result = await cleanupStaleStreams(maxAgeMs);
17
16
  log.info(`Stream cleanup done: deleted=${result.deleted.length}, ` +
@@ -45,7 +45,6 @@ const SOURCE_BITRATE_FALLBACK_KBPS = {
45
45
  };
46
46
  const probeSource = (inputPath) => new Promise((resolve, reject) => {
47
47
  ffmpeg.ffprobe(inputPath, (err, metadata) => {
48
- var _a, _b;
49
48
  if (err) {
50
49
  reject(err);
51
50
  return;
@@ -72,10 +71,10 @@ const probeSource = (inputPath) => new Promise((resolve, reject) => {
72
71
  }
73
72
  if (!videoBitrateKbps) {
74
73
  const shorter = Math.min(video.width, video.height);
75
- const fallback = (_b = (_a = Object.entries(SOURCE_BITRATE_FALLBACK_KBPS)
74
+ const fallback = Object.entries(SOURCE_BITRATE_FALLBACK_KBPS)
76
75
  .map(([s, kbps]) => ({ s: Number(s), kbps }))
77
76
  .filter(({ s }) => s <= shorter)
78
- .sort((a, b) => b.s - a.s)[0]) === null || _a === void 0 ? void 0 : _a.kbps) !== null && _b !== void 0 ? _b : 500;
77
+ .sort((a, b) => b.s - a.s)[0]?.kbps ?? 500;
79
78
  videoBitrateKbps = fallback;
80
79
  }
81
80
  resolve({
@@ -246,7 +245,7 @@ const runHls = async (inputPath, streamDir, source, variants) => {
246
245
  // Conversion failed!" — the actual diagnostic is in stderr. We attach
247
246
  // the last ~40 lines so the worker log (and errors.log) show what
248
247
  // ffmpeg actually complained about instead of a useless exit code.
249
- const tail = String(stderr !== null && stderr !== void 0 ? stderr : '')
248
+ const tail = String(stderr ?? '')
250
249
  .trim()
251
250
  .split(/\r?\n/)
252
251
  .slice(-40)