Repository navigation
Expand file tree
/
Copy pathutils.ts
More file actions
473 lines (438 loc) · 12.2 KB
/
Copy pathutils.ts
File metadata and controls
473 lines (438 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import {
posts,
notification,
banned_users,
content_report,
} from "@/server/db/schema";
import { expect } from "@playwright/test";
import type { Page } from "@playwright/test";
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { eq, and, isNotNull } from "drizzle-orm";
import { normalizeUrl } from "@/server/lib/normalizeUrl";
import {
E2E_USER_ONE_SESSION_ID,
E2E_USER_TWO_SESSION_ID,
E2E_ADMIN_SESSION_ID,
E2E_USER_ONE_ID,
E2E_ADMIN_ID,
} from "../constants";
// All E2E DB helpers talk to the same Postgres the global setup seeds (see
// e2e/setup.ts). Centralised here so individual helpers don't re-declare the
// connection string — four of them used to, which meant a run pointed at a
// scratch DATABASE_URL still wrote fixtures into the default database and then
// failed on foreign keys.
const E2E_DB_URL =
process.env.DATABASE_URL ??
"postgresql://postgres:secret@127.0.0.1:5432/postgres";
const e2eDb = () => drizzle(postgres(E2E_DB_URL));
/**
* Signed-in users can legitimately earn a badge mid-test (commenting, voting…),
* which pops the full-screen BadgeCelebration dialog and blocks pointer events.
* Auto-dismiss it whenever it appears so tests exercise the flow under it.
*/
const dismissBadgeCelebration = async (page: Page) => {
const keepBrowsing = page.getByRole("button", { name: "Keep browsing" });
await page.addLocatorHandler(keepBrowsing, async () => {
await keepBrowsing.click();
});
};
export const loggedInAsUserOne = async (page: Page) => {
try {
// Clear cookies to ensure fresh session (prevents stale React Query cache when switching users)
await page.context().clearCookies();
await page.context().addCookies([
{
name: "authjs.session-token",
value: E2E_USER_ONE_SESSION_ID,
domain: "localhost",
path: "/",
sameSite: "Lax",
},
]);
expect(
(await page.context().cookies()).find(
(cookie) => cookie.name === "authjs.session-token",
),
).toBeTruthy();
await dismissBadgeCelebration(page);
} catch (err) {
throw Error("Error while authenticating E2E test user one");
}
};
export const loggedInAsUserTwo = async (page: Page) => {
try {
await page.context().clearCookies();
await page.context().addCookies([
{
name: "authjs.session-token",
value: E2E_USER_TWO_SESSION_ID,
domain: "localhost",
path: "/",
sameSite: "Lax",
},
]);
expect(
(await page.context().cookies()).find(
(cookie) => cookie.name === "authjs.session-token",
),
).toBeTruthy();
await dismissBadgeCelebration(page);
} catch (err) {
throw Error("Error while authenticating E2E test user two");
}
};
export const loggedInAsAdmin = async (page: Page) => {
try {
// Clear cookies to ensure fresh session (prevents stale React Query cache when switching users)
await page.context().clearCookies();
await page.context().addCookies([
{
name: "authjs.session-token",
value: E2E_ADMIN_SESSION_ID,
domain: "localhost",
path: "/",
sameSite: "Lax",
},
]);
expect(
(await page.context().cookies()).find(
(cookie) => cookie.name === "authjs.session-token",
),
).toBeTruthy();
await dismissBadgeCelebration(page);
} catch (err) {
throw Error("Error while authenticating E2E admin user");
}
};
// Interface for creating articles using new posts table
interface CreateArticleInput {
title: string;
slug: string;
excerpt?: string;
body?: string;
upvotesCount?: number;
downvotesCount?: number;
readingTime?: number;
status?: "draft" | "published" | "scheduled" | "unlisted";
publishedAt?: string | null;
authorId?: string;
}
// Interface for creating link posts
interface CreateLinkPostInput {
title: string;
slug: string;
externalUrl: string;
excerpt?: string;
upvotesCount?: number;
downvotesCount?: number;
readingTime?: number;
status?: "draft" | "published" | "scheduled" | "unlisted";
publishedAt?: string | null;
authorId?: string;
}
export async function createArticle({
title,
slug,
excerpt = "",
body = "",
upvotesCount = 10,
downvotesCount = 0,
readingTime = 3,
status = "published",
publishedAt = new Date().toISOString(),
authorId = E2E_USER_ONE_ID,
}: CreateArticleInput) {
const db = drizzle(postgres(E2E_DB_URL));
try {
const result = await db
.insert(posts)
.values({
type: "article",
title,
slug,
excerpt,
body,
upvotesCount,
downvotesCount,
readingTime,
status,
publishedAt,
authorId,
showComments: true,
})
.onConflictDoNothing()
.returning();
return result[0];
} catch (err) {
throw Error(`Error while creating E2E test article: ${err}`);
}
}
export async function createLinkPost({
title,
slug,
externalUrl,
excerpt = "",
upvotesCount = 0,
downvotesCount = 0,
readingTime = 1,
status = "draft",
publishedAt = null,
authorId = E2E_USER_ONE_ID,
}: CreateLinkPostInput) {
const db = drizzle(postgres(E2E_DB_URL));
try {
const result = await db
.insert(posts)
.values({
type: "link",
title,
slug,
excerpt,
body: "", // Link posts don't have body content
externalUrl,
upvotesCount,
downvotesCount,
readingTime,
status,
publishedAt,
authorId,
showComments: true,
})
.onConflictDoNothing()
.returning();
return result[0];
} catch (err) {
throw Error(`Error while creating E2E test link post: ${err}`);
}
}
// Interface for creating notifications
interface CreateNotificationInput {
userId: string;
notifierId: string;
type: number; // 0 = NEW_COMMENT_ON_YOUR_POST, 1 = NEW_REPLY_TO_YOUR_COMMENT
postId?: string;
commentId?: string; // UUID
}
export async function createNotification({
userId,
notifierId,
type,
postId,
commentId,
}: CreateNotificationInput) {
const db = drizzle(postgres(E2E_DB_URL));
try {
// If no postId provided, get a published post to use
let actualPostId = postId;
if (!actualPostId) {
const [publishedPost] = await db
.select({ id: posts.id })
.from(posts)
.where(eq(posts.slug, "e2e-test-slug-published"))
.limit(1);
if (publishedPost) {
actualPostId = publishedPost.id;
}
}
const result = await db
.insert(notification)
.values({
userId,
notifierId,
type,
postId: actualPostId,
commentId,
})
.returning();
return result[0];
} catch (err) {
throw Error(`Error while creating E2E test notification: ${err}`);
}
}
export async function clearNotifications(userId: string) {
const db = drizzle(postgres(E2E_DB_URL));
try {
await db.delete(notification).where(eq(notification.userId, userId));
} catch (err) {
throw Error(`Error while clearing E2E test notifications: ${err}`);
}
}
// ---------------------------------------------------------------------------
// Moderation helpers (Phases 9 & 10). These mirror the createArticle / report
// flows the real app performs, but seed/clean state directly against the same
// local Postgres so the moderation specs stay deterministic.
// ---------------------------------------------------------------------------
/** Delete a post (and its open reports) by exact slug, so a spec can re-run. */
export async function deletePostBySlug(slug: string) {
const db = e2eDb();
try {
const rows = await db
.select({ id: posts.id })
.from(posts)
.where(eq(posts.slug, slug));
for (const row of rows) {
await db.delete(content_report).where(eq(content_report.postId, row.id));
}
await db.delete(posts).where(eq(posts.slug, slug));
} catch (err) {
throw Error(`Error while deleting E2E post by slug: ${err}`);
}
}
/** Read back a post's status by slug (used to assert ban/hide transitions). */
export async function getPostStatusBySlug(slug: string) {
const db = e2eDb();
const [row] = await db
.select({ id: posts.id, status: posts.status })
.from(posts)
.where(eq(posts.slug, slug))
.limit(1);
return row ?? null;
}
/**
* Publish a link post directly, populating `externalUrlNormalized` exactly as
* the real publish path does. This is the precondition for the link-dedupe
* spec: a fresh, published link with the same normalized URL must make the
* second attempt CONFLICT.
*/
export async function createPublishedLink({
title,
slug,
externalUrl,
authorId = E2E_USER_ONE_ID,
}: {
title: string;
slug: string;
externalUrl: string;
authorId?: string;
}) {
const db = e2eDb();
try {
const [row] = await db
.insert(posts)
.values({
type: "link",
title,
slug,
excerpt: "",
body: "",
externalUrl,
externalUrlNormalized: normalizeUrl(externalUrl),
upvotesCount: 0,
downvotesCount: 0,
readingTime: 1,
status: "published",
publishedAt: new Date().toISOString(),
authorId,
showComments: true,
})
.onConflictDoNothing()
.returning();
return row;
} catch (err) {
throw Error(`Error while creating E2E published link: ${err}`);
}
}
/**
* Seed an article in `in_review` — the state gatePublish puts an article into
* when MODERATION_ENABLED=true. Used to assert feed-exclusion + the my-posts
* "In review" badge deterministically (without depending on the slow full
* editor publish flow, which articles.spec.ts already covers).
*/
export async function createInReviewArticle({
title,
slug,
body = "An article awaiting moderator review.",
excerpt = "Awaiting review excerpt.",
authorId = E2E_USER_ONE_ID,
}: {
title: string;
slug: string;
body?: string;
excerpt?: string;
authorId?: string;
}) {
const db = e2eDb();
try {
const [row] = await db
.insert(posts)
.values({
type: "article",
title,
slug,
excerpt,
body,
upvotesCount: 0,
downvotesCount: 0,
readingTime: 2,
status: "in_review",
// in_review posts have no publishedAt yet.
publishedAt: null,
authorId,
showComments: true,
})
.onConflictDoNothing()
.returning();
return row;
} catch (err) {
throw Error(`Error while creating E2E in_review article: ${err}`);
}
}
/** Ban a user (admin action equivalent): insert a ban + hide their live posts. */
export async function banUserInDb(
userId: string,
bannedById: string = E2E_ADMIN_ID,
) {
const db = e2eDb();
try {
await db
.insert(banned_users)
.values({
userId,
bannedById,
note: "E2E test ban",
createdAt: new Date().toISOString(),
})
.onConflictDoNothing();
// Mirror admin.ban: published posts by the banned user become drafts so the
// feed's banned-users join + status filter both hide them.
await db
.update(posts)
.set({ status: "draft" })
.where(and(eq(posts.authorId, userId), eq(posts.status, "published")));
} catch (err) {
throw Error(`Error while banning E2E user: ${err}`);
}
}
/** Remove any ban for a user, so banned-state specs can re-run cleanly. */
export async function clearBanForUser(userId: string) {
const db = e2eDb();
try {
await db.delete(banned_users).where(eq(banned_users.userId, userId));
} catch (err) {
throw Error(`Error while clearing E2E ban: ${err}`);
}
}
/**
* Unban a user (admin action equivalent): remove the ban AND restore posts the
* ban had drafted (status draft + a publishedAt set → published), mirroring
* admin.unban.
*/
export async function unbanUserInDb(userId: string) {
const db = e2eDb();
try {
await db.delete(banned_users).where(eq(banned_users.userId, userId));
await db
.update(posts)
.set({ status: "published" })
.where(
and(
eq(posts.authorId, userId),
eq(posts.status, "draft"),
isNotNull(posts.publishedAt),
),
);
} catch (err) {
throw Error(`Error while unbanning E2E user: ${err}`);
}
}