powr-sdk-api 4.17.0 → 4.18.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.
@@ -36,6 +36,7 @@ const toolsRoutes = require('./tools');
36
36
  const tasksRoutes = require('./tasks');
37
37
  const preferencesRoutes = require('./preferences');
38
38
  const schedulerRoutes = require('./scheduler');
39
+ const postsRoutes = require('./posts');
39
40
 
40
41
  // Synchronous router creation
41
42
  const createPowrRoutes = (options = {}) => {
@@ -68,6 +69,8 @@ const createPowrRoutes = (options = {}) => {
68
69
  router.use('/tools', verifyToken, toolsRoutes);
69
70
  router.use('/tasks', verifyToken, tasksRoutes);
70
71
  router.use('/scheduler', verifyTokenOrServiceKey, schedulerRoutes);
72
+ // Public reads stay open. Writer and editor routes check the token themselves.
73
+ router.use('/posts', postsRoutes);
71
74
  return router;
72
75
  };
73
76
 
@@ -0,0 +1,758 @@
1
+ "use strict";
2
+
3
+ const express = require("express");
4
+ const {
5
+ ObjectId
6
+ } = require("mongodb");
7
+ const {
8
+ getDb
9
+ } = require("../services/mongo");
10
+ const {
11
+ verifyToken
12
+ } = require("../middleware/jwtToken");
13
+ const {
14
+ isPageviewAdmin
15
+ } = require("../utils/track");
16
+ const {
17
+ getPhoneLookupVariants
18
+ } = require("../utils/phone");
19
+ const {
20
+ slugify,
21
+ parsePostWrite,
22
+ parseAuthorWrite,
23
+ publicAuthor,
24
+ publicCard,
25
+ publicPost,
26
+ staffPost,
27
+ authorView
28
+ } = require("../utils/posts");
29
+ const router = express.Router();
30
+ const POSTS = "powrPosts";
31
+ const AUTHORS = "powrAuthors";
32
+ async function callerIsAdmin(db, req) {
33
+ const rawId = String(req.user && req.user.powrId || "");
34
+ let profileAccess;
35
+ let userAccess;
36
+ if (rawId.length === 24 && ObjectId.isValid(rawId)) {
37
+ const oid = new ObjectId(rawId);
38
+ const projectId = String(req.projectId || "");
39
+ const [profile, user] = await Promise.all([db.collection("profiles").findOne({
40
+ userId: {
41
+ $in: [oid, rawId]
42
+ },
43
+ projectId
44
+ }, {
45
+ projection: {
46
+ access: 1
47
+ }
48
+ }), db.collection("users").findOne({
49
+ _id: oid
50
+ }, {
51
+ projection: {
52
+ access: 1
53
+ }
54
+ })]);
55
+ if (profile) profileAccess = profile.access;
56
+ if (user) userAccess = user.access;
57
+ }
58
+ return isPageviewAdmin({
59
+ jwtAccess: req.user && req.user.access,
60
+ profileAccess,
61
+ userAccess
62
+ });
63
+ }
64
+ const writes = new Map();
65
+ let indexReady = null;
66
+ function ensureIndexes(db) {
67
+ if (!indexReady) {
68
+ indexReady = Promise.all([db.collection(POSTS).createIndex({
69
+ projectId: 1,
70
+ slug: 1
71
+ }, {
72
+ unique: true,
73
+ name: "project_slug"
74
+ }), db.collection(POSTS).createIndex({
75
+ projectId: 1,
76
+ status: 1,
77
+ publishedAt: -1
78
+ }, {
79
+ name: "project_status_published"
80
+ }), db.collection(POSTS).createIndex({
81
+ projectId: 1,
82
+ authorId: 1,
83
+ status: 1
84
+ }, {
85
+ name: "project_author_status"
86
+ }), db.collection(POSTS).createIndex({
87
+ projectId: 1,
88
+ tags: 1
89
+ }, {
90
+ name: "project_tags"
91
+ }), db.collection(AUTHORS).createIndex({
92
+ projectId: 1,
93
+ powrId: 1
94
+ }, {
95
+ unique: true,
96
+ name: "project_user"
97
+ }), db.collection(AUTHORS).createIndex({
98
+ projectId: 1,
99
+ handle: 1
100
+ }, {
101
+ unique: true,
102
+ name: "project_handle"
103
+ })]).catch(error => {
104
+ indexReady = null;
105
+ console.error("posts index:", error.message);
106
+ });
107
+ }
108
+ return indexReady;
109
+ }
110
+ function allowWrite(powrId) {
111
+ const now = Date.now();
112
+ const recent = (writes.get(powrId) || []).filter(at => now - at < 60000);
113
+ if (recent.length >= 20) return false;
114
+ recent.push(now);
115
+ writes.set(powrId, recent);
116
+ return true;
117
+ }
118
+ function fail(res, error, label) {
119
+ const status = error.statusCode || 500;
120
+ if (status >= 500) console.error(label, error);
121
+ return res.status(status).json({
122
+ success: false,
123
+ message: status >= 500 ? "Something went wrong." : error.message
124
+ });
125
+ }
126
+ function asId(value) {
127
+ const id = String(value || "");
128
+ if (!ObjectId.isValid(id) || id.length !== 24) return null;
129
+ return new ObjectId(id);
130
+ }
131
+ async function roleOf(db, req) {
132
+ const powrId = String(req.user && req.user.powrId || "");
133
+ const projectId = String(req.projectId);
134
+ const author = powrId ? await db.collection(AUTHORS).findOne({
135
+ projectId,
136
+ powrId
137
+ }) : null;
138
+ const admin = await callerIsAdmin(db, req);
139
+ const editor = admin || !!(author && author.role === "editor");
140
+ return {
141
+ powrId,
142
+ projectId,
143
+ author,
144
+ editor,
145
+ writer: editor || !!author
146
+ };
147
+ }
148
+ async function authorsById(db, projectId, rows) {
149
+ const ids = [...new Set(rows.map(row => row.authorId).filter(Boolean))];
150
+ if (!ids.length) return new Map();
151
+ const authors = await db.collection(AUTHORS).find({
152
+ projectId,
153
+ powrId: {
154
+ $in: ids
155
+ }
156
+ }).toArray();
157
+ return new Map(authors.map(author => [String(author.powrId), author]));
158
+ }
159
+ async function uniqueSlug(db, projectId, base, exceptId) {
160
+ let slug = base;
161
+ for (let n = 2; n < 50; n += 1) {
162
+ const query = {
163
+ projectId,
164
+ slug
165
+ };
166
+ if (exceptId) query._id = {
167
+ $ne: exceptId
168
+ };
169
+ const hit = await db.collection(POSTS).findOne(query, {
170
+ projection: {
171
+ _id: 1
172
+ }
173
+ });
174
+ if (!hit) return slug;
175
+ slug = `${base.slice(0, 76)}-${n}`;
176
+ }
177
+ const error = new Error("Could not make a free link for this title.");
178
+ error.statusCode = 409;
179
+ throw error;
180
+ }
181
+ async function findUserId(db, {
182
+ powrId,
183
+ phone
184
+ }) {
185
+ if (powrId) {
186
+ const id = asId(powrId);
187
+ if (!id) {
188
+ const error = new Error("That user id is not valid.");
189
+ error.statusCode = 400;
190
+ throw error;
191
+ }
192
+ const user = await db.collection("users").findOne({
193
+ _id: id
194
+ }, {
195
+ projection: {
196
+ _id: 1,
197
+ fullName: 1
198
+ }
199
+ });
200
+ if (!user) {
201
+ const error = new Error("No Powr user with that id.");
202
+ error.statusCode = 404;
203
+ throw error;
204
+ }
205
+ return {
206
+ powrId: String(user._id),
207
+ fullName: user.fullName || ""
208
+ };
209
+ }
210
+ const variants = getPhoneLookupVariants(phone);
211
+ if (!variants.length) {
212
+ const error = new Error("That phone is not valid.");
213
+ error.statusCode = 400;
214
+ throw error;
215
+ }
216
+ const user = await db.collection("users").findOne({
217
+ phoneNumber: {
218
+ $in: variants
219
+ }
220
+ }, {
221
+ projection: {
222
+ _id: 1,
223
+ fullName: 1
224
+ }
225
+ });
226
+ if (!user) {
227
+ const error = new Error("No Powr user with that phone.");
228
+ error.statusCode = 404;
229
+ throw error;
230
+ }
231
+ return {
232
+ powrId: String(user._id),
233
+ fullName: user.fullName || ""
234
+ };
235
+ }
236
+ router.get("/mine", verifyToken, async (req, res) => {
237
+ try {
238
+ const db = await getDb();
239
+ await ensureIndexes(db);
240
+ const {
241
+ powrId,
242
+ projectId,
243
+ writer
244
+ } = await roleOf(db, req);
245
+ if (!writer) {
246
+ return res.status(403).json({
247
+ success: false,
248
+ message: "You are not a writer on this product."
249
+ });
250
+ }
251
+ const rows = await db.collection(POSTS).find({
252
+ projectId,
253
+ authorId: powrId
254
+ }).sort({
255
+ updatedAt: -1
256
+ }).limit(100).toArray();
257
+ const authors = await authorsById(db, projectId, rows);
258
+ return res.json({
259
+ success: true,
260
+ data: rows.map(row => staffPost(row, authors.get(String(row.authorId))))
261
+ });
262
+ } catch (error) {
263
+ return fail(res, error, "GET /posts/mine");
264
+ }
265
+ });
266
+ router.get("/all", verifyToken, async (req, res) => {
267
+ try {
268
+ const db = await getDb();
269
+ await ensureIndexes(db);
270
+ const {
271
+ projectId,
272
+ editor
273
+ } = await roleOf(db, req);
274
+ if (!editor) return res.status(403).json({
275
+ success: false,
276
+ message: "Access denied."
277
+ });
278
+ const status = String(req.query.status || "").trim();
279
+ const query = {
280
+ projectId
281
+ };
282
+ if (status) query.status = status;
283
+ const rows = await db.collection(POSTS).find(query).sort({
284
+ updatedAt: -1
285
+ }).limit(200).toArray();
286
+ const authors = await authorsById(db, projectId, rows);
287
+ return res.json({
288
+ success: true,
289
+ data: rows.map(row => staffPost(row, authors.get(String(row.authorId))))
290
+ });
291
+ } catch (error) {
292
+ return fail(res, error, "GET /posts/all");
293
+ }
294
+ });
295
+ router.get("/authors", verifyToken, async (req, res) => {
296
+ try {
297
+ const db = await getDb();
298
+ await ensureIndexes(db);
299
+ const {
300
+ projectId,
301
+ editor
302
+ } = await roleOf(db, req);
303
+ if (!editor) return res.status(403).json({
304
+ success: false,
305
+ message: "Access denied."
306
+ });
307
+ const rows = await db.collection(AUTHORS).find({
308
+ projectId
309
+ }).sort({
310
+ displayName: 1
311
+ }).toArray();
312
+ return res.json({
313
+ success: true,
314
+ data: rows.map(authorView)
315
+ });
316
+ } catch (error) {
317
+ return fail(res, error, "GET /posts/authors");
318
+ }
319
+ });
320
+ router.post("/authors", verifyToken, async (req, res) => {
321
+ try {
322
+ const db = await getDb();
323
+ await ensureIndexes(db);
324
+ const {
325
+ projectId,
326
+ editor
327
+ } = await roleOf(db, req);
328
+ if (!editor) return res.status(403).json({
329
+ success: false,
330
+ message: "Access denied."
331
+ });
332
+ const fields = parseAuthorWrite(req.body || {});
333
+ const user = await findUserId(db, fields);
334
+ const taken = await db.collection(AUTHORS).findOne({
335
+ projectId,
336
+ $or: [{
337
+ powrId: user.powrId
338
+ }, {
339
+ handle: fields.handle
340
+ }]
341
+ });
342
+ if (taken) {
343
+ return res.status(409).json({
344
+ success: false,
345
+ message: "That writer or handle is already on this product."
346
+ });
347
+ }
348
+ const now = new Date();
349
+ const doc = {
350
+ projectId,
351
+ powrId: user.powrId,
352
+ handle: fields.handle,
353
+ displayName: fields.displayName || user.fullName,
354
+ bio: fields.bio,
355
+ avatarUrl: fields.avatarUrl,
356
+ role: fields.role,
357
+ createdAt: now
358
+ };
359
+ const result = await db.collection(AUTHORS).insertOne(doc);
360
+ return res.status(201).json({
361
+ success: true,
362
+ data: authorView({
363
+ ...doc,
364
+ _id: result.insertedId
365
+ })
366
+ });
367
+ } catch (error) {
368
+ return fail(res, error, "POST /posts/authors");
369
+ }
370
+ });
371
+ router.patch("/authors/:id", verifyToken, async (req, res) => {
372
+ try {
373
+ const db = await getDb();
374
+ const {
375
+ projectId,
376
+ editor
377
+ } = await roleOf(db, req);
378
+ if (!editor) return res.status(403).json({
379
+ success: false,
380
+ message: "Access denied."
381
+ });
382
+ const id = asId(req.params.id);
383
+ if (!id) return res.status(400).json({
384
+ success: false,
385
+ message: "Invalid author id."
386
+ });
387
+ const current = await db.collection(AUTHORS).findOne({
388
+ _id: id,
389
+ projectId
390
+ });
391
+ if (!current) return res.status(404).json({
392
+ success: false,
393
+ message: "Author not found."
394
+ });
395
+ const fields = parseAuthorWrite({
396
+ displayName: req.body.displayName !== undefined ? req.body.displayName : current.displayName,
397
+ handle: req.body.handle !== undefined ? req.body.handle : current.handle,
398
+ role: req.body.role !== undefined ? req.body.role : current.role,
399
+ bio: req.body.bio !== undefined ? req.body.bio : current.bio,
400
+ avatarUrl: req.body.avatarUrl !== undefined ? req.body.avatarUrl : current.avatarUrl,
401
+ powrId: current.powrId
402
+ });
403
+ if (fields.handle !== current.handle) {
404
+ const clash = await db.collection(AUTHORS).findOne({
405
+ projectId,
406
+ handle: fields.handle,
407
+ _id: {
408
+ $ne: id
409
+ }
410
+ });
411
+ if (clash) return res.status(409).json({
412
+ success: false,
413
+ message: "That handle is taken."
414
+ });
415
+ }
416
+ const next = {
417
+ handle: fields.handle,
418
+ displayName: fields.displayName,
419
+ bio: fields.bio,
420
+ avatarUrl: fields.avatarUrl,
421
+ role: fields.role
422
+ };
423
+ await db.collection(AUTHORS).updateOne({
424
+ _id: id,
425
+ projectId
426
+ }, {
427
+ $set: next
428
+ });
429
+ return res.json({
430
+ success: true,
431
+ data: authorView({
432
+ ...current,
433
+ ...next
434
+ })
435
+ });
436
+ } catch (error) {
437
+ return fail(res, error, "PATCH /posts/authors/:id");
438
+ }
439
+ });
440
+ router.delete("/authors/:id", verifyToken, async (req, res) => {
441
+ try {
442
+ const db = await getDb();
443
+ const {
444
+ projectId,
445
+ editor
446
+ } = await roleOf(db, req);
447
+ if (!editor) return res.status(403).json({
448
+ success: false,
449
+ message: "Access denied."
450
+ });
451
+ const id = asId(req.params.id);
452
+ if (!id) return res.status(400).json({
453
+ success: false,
454
+ message: "Invalid author id."
455
+ });
456
+ const result = await db.collection(AUTHORS).deleteOne({
457
+ _id: id,
458
+ projectId
459
+ });
460
+ if (!result.deletedCount) return res.status(404).json({
461
+ success: false,
462
+ message: "Author not found."
463
+ });
464
+ return res.json({
465
+ success: true
466
+ });
467
+ } catch (error) {
468
+ return fail(res, error, "DELETE /posts/authors/:id");
469
+ }
470
+ });
471
+ router.get("/authors/:handle", async (req, res) => {
472
+ try {
473
+ const db = await getDb();
474
+ await ensureIndexes(db);
475
+ const projectId = String(req.projectId);
476
+ const handle = slugify(req.params.handle);
477
+ const author = await db.collection(AUTHORS).findOne({
478
+ projectId,
479
+ handle
480
+ });
481
+ if (!author) return res.status(404).json({
482
+ success: false,
483
+ message: "Author not found."
484
+ });
485
+ const rows = await db.collection(POSTS).find({
486
+ projectId,
487
+ authorId: author.powrId,
488
+ status: "published"
489
+ }, {
490
+ projection: {
491
+ bodyMd: 0
492
+ }
493
+ }).sort({
494
+ publishedAt: -1
495
+ }).limit(50).toArray();
496
+ return res.json({
497
+ success: true,
498
+ data: {
499
+ author: publicAuthor(author),
500
+ posts: rows.map(row => publicCard(row, author))
501
+ }
502
+ });
503
+ } catch (error) {
504
+ return fail(res, error, "GET /posts/authors/:handle");
505
+ }
506
+ });
507
+ router.get("/", async (req, res) => {
508
+ try {
509
+ const db = await getDb();
510
+ await ensureIndexes(db);
511
+ const projectId = String(req.projectId);
512
+ const limit = Math.min(50, Math.max(1, Number(req.query.limit) || 20));
513
+ const page = Math.max(1, Number(req.query.page) || 1);
514
+ const query = {
515
+ projectId,
516
+ status: "published"
517
+ };
518
+ const tag = String(req.query.tag || "").trim().toLowerCase();
519
+ if (tag) query.tags = tag;
520
+ const handle = String(req.query.author || "").trim();
521
+ if (handle) {
522
+ const author = await db.collection(AUTHORS).findOne({
523
+ projectId,
524
+ handle: slugify(handle)
525
+ });
526
+ if (!author) return res.json({
527
+ success: true,
528
+ data: [],
529
+ page,
530
+ limit
531
+ });
532
+ query.authorId = author.powrId;
533
+ }
534
+ const rows = await db.collection(POSTS).find(query, {
535
+ projection: {
536
+ bodyMd: 0
537
+ }
538
+ }).sort({
539
+ publishedAt: -1,
540
+ _id: -1
541
+ }).skip((page - 1) * limit).limit(limit).toArray();
542
+ const authors = await authorsById(db, projectId, rows);
543
+ return res.json({
544
+ success: true,
545
+ page,
546
+ limit,
547
+ data: rows.map(row => publicCard(row, authors.get(String(row.authorId))))
548
+ });
549
+ } catch (error) {
550
+ return fail(res, error, "GET /posts");
551
+ }
552
+ });
553
+ router.get("/:slug", async (req, res) => {
554
+ try {
555
+ const db = await getDb();
556
+ const projectId = String(req.projectId);
557
+ const row = await db.collection(POSTS).findOne({
558
+ projectId,
559
+ slug: slugify(req.params.slug),
560
+ status: "published"
561
+ });
562
+ if (!row) return res.status(404).json({
563
+ success: false,
564
+ message: "Post not found."
565
+ });
566
+ const author = row.authorId ? await db.collection(AUTHORS).findOne({
567
+ projectId,
568
+ powrId: String(row.authorId)
569
+ }) : null;
570
+ return res.json({
571
+ success: true,
572
+ data: publicPost(row, author)
573
+ });
574
+ } catch (error) {
575
+ return fail(res, error, "GET /posts/:slug");
576
+ }
577
+ });
578
+ router.post("/", verifyToken, async (req, res) => {
579
+ try {
580
+ const db = await getDb();
581
+ await ensureIndexes(db);
582
+ const access = await roleOf(db, req);
583
+ if (!access.writer) {
584
+ return res.status(403).json({
585
+ success: false,
586
+ message: "You are not a writer on this product."
587
+ });
588
+ }
589
+ if (!allowWrite(access.powrId)) {
590
+ return res.status(429).json({
591
+ success: false,
592
+ message: "Slow down a moment, then save again."
593
+ });
594
+ }
595
+ const fields = parsePostWrite(req.body || {});
596
+ if (!fields.title) {
597
+ const error = new Error("Title is required.");
598
+ error.statusCode = 400;
599
+ throw error;
600
+ }
601
+ const slug = await uniqueSlug(db, access.projectId, fields.slug || slugify(fields.title));
602
+ const now = new Date();
603
+ const doc = {
604
+ projectId: access.projectId,
605
+ slug,
606
+ title: fields.title,
607
+ description: fields.description || "",
608
+ coverUrl: fields.coverUrl || "",
609
+ sourcePdfUrl: fields.sourcePdfUrl || "",
610
+ bodyMd: fields.bodyMd || "",
611
+ tags: fields.tags || [],
612
+ readMinutes: fields.readMinutes || 1,
613
+ authorId: access.powrId,
614
+ status: "draft",
615
+ slugLocked: false,
616
+ publishedAt: null,
617
+ createdAt: now,
618
+ updatedAt: now
619
+ };
620
+ const result = await db.collection(POSTS).insertOne(doc);
621
+ const author = access.author;
622
+ return res.status(201).json({
623
+ success: true,
624
+ data: staffPost({
625
+ ...doc,
626
+ _id: result.insertedId
627
+ }, author)
628
+ });
629
+ } catch (error) {
630
+ return fail(res, error, "POST /posts");
631
+ }
632
+ });
633
+ router.patch("/:id", verifyToken, async (req, res) => {
634
+ try {
635
+ const db = await getDb();
636
+ const access = await roleOf(db, req);
637
+ if (!allowWrite(access.powrId)) {
638
+ return res.status(429).json({
639
+ success: false,
640
+ message: "Slow down a moment, then save again."
641
+ });
642
+ }
643
+ const id = asId(req.params.id);
644
+ if (!id) return res.status(400).json({
645
+ success: false,
646
+ message: "Invalid post id."
647
+ });
648
+ const current = await db.collection(POSTS).findOne({
649
+ _id: id,
650
+ projectId: access.projectId
651
+ });
652
+ if (!current) return res.status(404).json({
653
+ success: false,
654
+ message: "Post not found."
655
+ });
656
+ const owns = String(current.authorId) === access.powrId;
657
+ if (!owns && !access.editor) {
658
+ return res.status(403).json({
659
+ success: false,
660
+ message: "Access denied."
661
+ });
662
+ }
663
+ if (current.status === "published" && !access.editor) {
664
+ return res.status(403).json({
665
+ success: false,
666
+ message: "A published post is edited by an editor."
667
+ });
668
+ }
669
+ const fields = parsePostWrite(req.body || {}, true);
670
+ if (fields.slug && (current.slugLocked || current.status === "published")) delete fields.slug;
671
+ if (fields.slug && fields.slug !== current.slug) {
672
+ fields.slug = await uniqueSlug(db, access.projectId, fields.slug, id);
673
+ }
674
+ fields.updatedAt = new Date();
675
+ await db.collection(POSTS).updateOne({
676
+ _id: id
677
+ }, {
678
+ $set: fields
679
+ });
680
+ const author = await db.collection(AUTHORS).findOne({
681
+ projectId: access.projectId,
682
+ powrId: String(current.authorId)
683
+ });
684
+ return res.json({
685
+ success: true,
686
+ data: staffPost({
687
+ ...current,
688
+ ...fields
689
+ }, author)
690
+ });
691
+ } catch (error) {
692
+ return fail(res, error, "PATCH /posts/:id");
693
+ }
694
+ });
695
+ async function setStatus(req, res, nextStatus) {
696
+ const db = await getDb();
697
+ const access = await roleOf(db, req);
698
+ const id = asId(req.params.id);
699
+ if (!id) return res.status(400).json({
700
+ success: false,
701
+ message: "Invalid post id."
702
+ });
703
+ const current = await db.collection(POSTS).findOne({
704
+ _id: id,
705
+ projectId: access.projectId
706
+ });
707
+ if (!current) return res.status(404).json({
708
+ success: false,
709
+ message: "Post not found."
710
+ });
711
+ const owns = String(current.authorId) === access.powrId;
712
+ if (nextStatus === "in_review") {
713
+ if (!owns) return res.status(403).json({
714
+ success: false,
715
+ message: "Access denied."
716
+ });
717
+ if (current.status !== "draft") {
718
+ return res.status(400).json({
719
+ success: false,
720
+ message: "Only a draft can be sent for review."
721
+ });
722
+ }
723
+ } else if (!access.editor) {
724
+ return res.status(403).json({
725
+ success: false,
726
+ message: "Access denied."
727
+ });
728
+ }
729
+ const patch = {
730
+ status: nextStatus,
731
+ updatedAt: new Date()
732
+ };
733
+ if (nextStatus === "published") {
734
+ patch.slugLocked = true;
735
+ if (!current.publishedAt) patch.publishedAt = patch.updatedAt;
736
+ }
737
+ await db.collection(POSTS).updateOne({
738
+ _id: id
739
+ }, {
740
+ $set: patch
741
+ });
742
+ const author = await db.collection(AUTHORS).findOne({
743
+ projectId: access.projectId,
744
+ powrId: String(current.authorId)
745
+ });
746
+ return res.json({
747
+ success: true,
748
+ data: staffPost({
749
+ ...current,
750
+ ...patch
751
+ }, author)
752
+ });
753
+ }
754
+ router.post("/:id/submit", verifyToken, (req, res) => setStatus(req, res, "in_review").catch(error => fail(res, error, "POST /posts/:id/submit")));
755
+ router.post("/:id/publish", verifyToken, (req, res) => setStatus(req, res, "published").catch(error => fail(res, error, "POST /posts/:id/publish")));
756
+ router.post("/:id/unpublish", verifyToken, (req, res) => setStatus(req, res, "draft").catch(error => fail(res, error, "POST /posts/:id/unpublish")));
757
+ router.post("/:id/archive", verifyToken, (req, res) => setStatus(req, res, "archived").catch(error => fail(res, error, "POST /posts/:id/archive")));
758
+ module.exports = router;
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+
3
+ const STATUSES = ["draft", "in_review", "published", "archived"];
4
+ const ROLES = ["writer", "editor"];
5
+ const TITLE_MAX = 140;
6
+ const DESC_MAX = 300;
7
+ const BODY_MAX = 80000;
8
+ const TAG_MAX = 8;
9
+ const TAG_LEN = 40;
10
+ const SLUG_MAX = 80;
11
+ function bad(message) {
12
+ const error = new Error(message);
13
+ error.statusCode = 400;
14
+ throw error;
15
+ }
16
+ function slugify(value) {
17
+ const base = String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, SLUG_MAX).replace(/-+$/g, "");
18
+ return base || "post";
19
+ }
20
+ function parseTags(value) {
21
+ const list = Array.isArray(value) ? value : String(value || "").split(",");
22
+ const tags = [];
23
+ for (const raw of list) {
24
+ const tag = String(raw || "").trim().toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/^-+|-+$/g, "").slice(0, TAG_LEN);
25
+ if (!tag || tags.includes(tag)) continue;
26
+ tags.push(tag);
27
+ if (tags.length >= TAG_MAX) break;
28
+ }
29
+ return tags;
30
+ }
31
+ function readMinutes(markdown) {
32
+ const words = String(markdown || "").trim().split(/\s+/).filter(Boolean).length;
33
+ if (!words) return 1;
34
+ return Math.max(1, Math.round(words / 200));
35
+ }
36
+ function parsePostWrite(body, partial) {
37
+ const source = body || {};
38
+ const out = {};
39
+ const has = key => !partial || Object.prototype.hasOwnProperty.call(source, key);
40
+ if (has("title")) {
41
+ const title = String(source.title || "").trim();
42
+ if (!title) bad("Title is required.");
43
+ if (title.length > TITLE_MAX) bad("Title must be under 140 characters.");
44
+ out.title = title;
45
+ }
46
+ if (has("description")) {
47
+ const description = String(source.description || "").trim();
48
+ if (description.length > DESC_MAX) bad("Description must be under 300 characters.");
49
+ out.description = description;
50
+ }
51
+ if (has("bodyMd")) {
52
+ const bodyMd = String(source.bodyMd || "");
53
+ if (bodyMd.length > BODY_MAX) bad("Article is too long.");
54
+ out.bodyMd = bodyMd;
55
+ out.readMinutes = readMinutes(bodyMd);
56
+ }
57
+ if (has("tags")) out.tags = parseTags(source.tags);
58
+ if (has("coverUrl")) {
59
+ const coverUrl = String(source.coverUrl || "").trim();
60
+ if (coverUrl && !/^https:\/\//i.test(coverUrl)) bad("Cover must be an https link.");
61
+ out.coverUrl = coverUrl;
62
+ }
63
+ if (has("sourcePdfUrl")) {
64
+ const sourcePdfUrl = String(source.sourcePdfUrl || "").trim();
65
+ if (sourcePdfUrl && !/^https:\/\//i.test(sourcePdfUrl)) bad("The PDF must be an https link.");
66
+ if (sourcePdfUrl && !/\.pdf(\?|#|$)/i.test(sourcePdfUrl)) bad("The file must be a PDF.");
67
+ out.sourcePdfUrl = sourcePdfUrl;
68
+ }
69
+ if (Object.prototype.hasOwnProperty.call(source, "slug")) {
70
+ out.slug = slugify(source.slug);
71
+ }
72
+ return out;
73
+ }
74
+ function parseAuthorWrite(body) {
75
+ const source = body || {};
76
+ const displayName = String(source.displayName || "").trim();
77
+ if (!displayName) bad("Name is required.");
78
+ if (displayName.length > 80) bad("Name must be under 80 characters.");
79
+ const handle = slugify(source.handle || displayName).slice(0, 40);
80
+ if (handle.length < 2) bad("Handle is too short.");
81
+ const role = String(source.role || "writer").trim().toLowerCase();
82
+ if (!ROLES.includes(role)) bad("Role must be writer or editor.");
83
+ const bio = String(source.bio || "").trim();
84
+ if (bio.length > 300) bad("Bio must be under 300 characters.");
85
+ const avatarUrl = String(source.avatarUrl || "").trim();
86
+ if (avatarUrl && !/^https:\/\//i.test(avatarUrl)) bad("Photo must be an https link.");
87
+ const powrId = String(source.powrId || "").trim();
88
+ const phone = String(source.phone || "").trim();
89
+ if (!powrId && !phone) bad("A Powr user or a phone is required.");
90
+ return {
91
+ displayName,
92
+ handle,
93
+ role,
94
+ bio,
95
+ avatarUrl,
96
+ powrId,
97
+ phone
98
+ };
99
+ }
100
+ function publicAuthor(author) {
101
+ if (!author) return null;
102
+ return {
103
+ handle: author.handle || "",
104
+ displayName: author.displayName || "",
105
+ avatarUrl: author.avatarUrl || "",
106
+ bio: author.bio || ""
107
+ };
108
+ }
109
+ function publicCard(row, author) {
110
+ return {
111
+ _id: String(row._id),
112
+ slug: row.slug || "",
113
+ title: row.title || "",
114
+ description: row.description || "",
115
+ coverUrl: row.coverUrl || "",
116
+ tags: row.tags || [],
117
+ publishedAt: row.publishedAt || null,
118
+ readMinutes: row.readMinutes || 1,
119
+ author: publicAuthor(author)
120
+ };
121
+ }
122
+ function publicPost(row, author) {
123
+ return Object.assign({}, publicCard(row, author), {
124
+ bodyMd: row.bodyMd || ""
125
+ });
126
+ }
127
+ function staffPost(row, author) {
128
+ return Object.assign({}, publicPost(row, author), {
129
+ status: row.status || "draft",
130
+ authorId: row.authorId ? String(row.authorId) : "",
131
+ slugLocked: !!row.slugLocked,
132
+ sourcePdfUrl: row.sourcePdfUrl || "",
133
+ createdAt: row.createdAt || null,
134
+ updatedAt: row.updatedAt || null
135
+ });
136
+ }
137
+ function authorView(row) {
138
+ return {
139
+ _id: String(row._id),
140
+ powrId: row.powrId ? String(row.powrId) : "",
141
+ handle: row.handle || "",
142
+ displayName: row.displayName || "",
143
+ bio: row.bio || "",
144
+ avatarUrl: row.avatarUrl || "",
145
+ role: row.role || "writer",
146
+ createdAt: row.createdAt || null
147
+ };
148
+ }
149
+ module.exports = {
150
+ STATUSES,
151
+ ROLES,
152
+ slugify,
153
+ parseTags,
154
+ readMinutes,
155
+ parsePostWrite,
156
+ parseAuthorWrite,
157
+ publicAuthor,
158
+ publicCard,
159
+ publicPost,
160
+ staffPost,
161
+ authorView
162
+ };
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+
3
+ const {
4
+ slugify,
5
+ parsePostWrite,
6
+ parseAuthorWrite,
7
+ publicCard,
8
+ staffPost,
9
+ readMinutes
10
+ } = require("./posts");
11
+ describe("slugify", () => {
12
+ it("makes a url piece from a title", () => {
13
+ expect(slugify(" Cursor for a new student! ")).toBe("cursor-for-a-new-student");
14
+ });
15
+ it("falls back when the title has no letters", () => {
16
+ expect(slugify("???")).toBe("post");
17
+ });
18
+ });
19
+ describe("parsePostWrite", () => {
20
+ it("keeps a draft's fields", () => {
21
+ const fields = parsePostWrite({
22
+ title: " Hello ",
23
+ description: "A short line",
24
+ bodyMd: "One two three",
25
+ tags: "Vibe, vibe, AI",
26
+ coverUrl: "https://cdn.example/a.png"
27
+ });
28
+ expect(fields.title).toBe("Hello");
29
+ expect(fields.tags).toEqual(["vibe", "ai"]);
30
+ expect(fields.readMinutes).toBe(1);
31
+ });
32
+ it("keeps a pdf link and rejects anything else", () => {
33
+ expect(parsePostWrite({
34
+ title: "Guide",
35
+ sourcePdfUrl: "https://cdn.example/guide.pdf"
36
+ }).sourcePdfUrl).toBe("https://cdn.example/guide.pdf");
37
+ expect(() => parsePostWrite({
38
+ title: "Guide",
39
+ sourcePdfUrl: "https://cdn.example/guide.png"
40
+ })).toThrow("The file must be a PDF.");
41
+ });
42
+ it("rejects a cover that is not https", () => {
43
+ expect(() => parsePostWrite({
44
+ title: "Hi",
45
+ coverUrl: "http://x"
46
+ })).toThrow("Cover must be an https link.");
47
+ });
48
+ it("on a partial update only touches the keys that were sent", () => {
49
+ expect(parsePostWrite({
50
+ description: "Only this"
51
+ }, true)).toEqual({
52
+ description: "Only this"
53
+ });
54
+ });
55
+ });
56
+ describe("readMinutes", () => {
57
+ it("rounds about 200 words to a minute", () => {
58
+ const words = new Array(400).fill("word").join(" ");
59
+ expect(readMinutes(words)).toBe(2);
60
+ });
61
+ });
62
+ describe("parseAuthorWrite", () => {
63
+ it("builds a writer from a phone", () => {
64
+ const author = parseAuthorWrite({
65
+ displayName: "Om",
66
+ phone: "9999999999"
67
+ });
68
+ expect(author.handle).toBe("om");
69
+ expect(author.role).toBe("writer");
70
+ expect(author.phone).toBe("9999999999");
71
+ });
72
+ });
73
+ describe("publicCard", () => {
74
+ it("does not include the article body", () => {
75
+ const card = publicCard({
76
+ _id: "a",
77
+ slug: "hi",
78
+ title: "Hi",
79
+ bodyMd: "secret",
80
+ status: "published",
81
+ sourcePdfUrl: "https://cdn.example/a.pdf"
82
+ }, {
83
+ handle: "om",
84
+ displayName: "Om"
85
+ });
86
+ expect(card.bodyMd).toBeUndefined();
87
+ expect(card.status).toBeUndefined();
88
+ expect(card.sourcePdfUrl).toBeUndefined();
89
+ expect(card.author.displayName).toBe("Om");
90
+ });
91
+ it("shows the pdf only to staff", () => {
92
+ const row = {
93
+ _id: "a",
94
+ title: "Hi",
95
+ sourcePdfUrl: "https://cdn.example/a.pdf",
96
+ status: "in_review"
97
+ };
98
+ expect(staffPost(row, null).sourcePdfUrl).toBe("https://cdn.example/a.pdf");
99
+ expect(publicCard(row, null).sourcePdfUrl).toBeUndefined();
100
+ });
101
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.17.0",
3
+ "version": "4.18.1",
4
4
  "description": "Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",