aboutsummaryrefslogtreecommitdiffstats
path: root/packages/trpc/routers/bookmarks.test.ts
blob: c272e015b0758d31b2e55dad6795c43b6597947e (plain) (blame)
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
import { eq } from "drizzle-orm";
import { assert, beforeEach, describe, expect, test } from "vitest";

import {
  bookmarkLinks,
  bookmarks,
  rssFeedImportsTable,
  users,
} from "@karakeep/db/schema";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";

import type { APICallerType, CustomTestContext } from "../testUtils";
import { defaultBeforeEach } from "../testUtils";

beforeEach<CustomTestContext>(defaultBeforeEach(true));

describe("Bookmark Routes", () => {
  async function createTestTag(api: APICallerType, tagName: string) {
    const result = await api.tags.create({ name: tagName });
    return result.id;
  }

  async function createTestFeed(
    api: APICallerType,
    feedName: string,
    feedUrl: string,
  ) {
    // Create an RSS feed and return its ID
    const feed = await api.feeds.create({
      name: feedName,
      url: feedUrl,
      enabled: true,
    });
    return feed.id;
  }

  test<CustomTestContext>("create bookmark", async ({ apiCallers }) => {
    const api = apiCallers[0].bookmarks;
    const bookmark = await api.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });

    const res = await api.getBookmark({ bookmarkId: bookmark.id });
    assert(res.content.type == BookmarkTypes.LINK);
    expect(res.content.url).toEqual("https://google.com");
    expect(res.favourited).toEqual(false);
    expect(res.archived).toEqual(false);
    expect(res.content.type).toEqual(BookmarkTypes.LINK);
  });

  test<CustomTestContext>("delete bookmark", async ({ apiCallers }) => {
    const api = apiCallers[0].bookmarks;

    // Create the bookmark
    const bookmark = await api.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });

    // It should exist
    await api.getBookmark({ bookmarkId: bookmark.id });

    // Delete it
    await api.deleteBookmark({ bookmarkId: bookmark.id });

    // It shouldn't be there anymore
    await expect(() =>
      api.getBookmark({ bookmarkId: bookmark.id }),
    ).rejects.toThrow(/Bookmark not found/);
  });

  test<CustomTestContext>("update bookmark", async ({ apiCallers }) => {
    const api = apiCallers[0].bookmarks;

    // Create the bookmark
    const bookmark = await api.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });

    await api.updateBookmark({
      bookmarkId: bookmark.id,
      archived: true,
      favourited: true,
    });

    let res = await api.getBookmark({ bookmarkId: bookmark.id });
    expect(res.archived).toBeTruthy();
    expect(res.favourited).toBeTruthy();

    // Update other common fields
    const newDate = new Date(Date.now() - 1000 * 60 * 60 * 24); // Yesterday
    newDate.setMilliseconds(0);
    await api.updateBookmark({
      bookmarkId: bookmark.id,
      title: "New Title",
      note: "Test Note",
      summary: "Test Summary",
      createdAt: newDate,
    });

    res = await api.getBookmark({ bookmarkId: bookmark.id });
    expect(res.title).toEqual("New Title");
    expect(res.note).toEqual("Test Note");
    expect(res.summary).toEqual("Test Summary");
    expect(res.createdAt).toEqual(newDate);

    // Update link-specific fields
    const linkUpdateDate = new Date(Date.now() - 1000 * 60 * 60 * 48); // 2 days ago
    linkUpdateDate.setMilliseconds(0);
    await api.updateBookmark({
      bookmarkId: bookmark.id,
      url: "https://new-google.com",
      description: "New Description",
      author: "New Author",
      publisher: "New Publisher",
      datePublished: linkUpdateDate,
      dateModified: linkUpdateDate,
    });

    res = await api.getBookmark({ bookmarkId: bookmark.id });
    assert(res.content.type === BookmarkTypes.LINK);
    expect(res.content.url).toEqual("https://new-google.com");
    expect(res.content.description).toEqual("New Description");
    expect(res.content.author).toEqual("New Author");
    expect(res.content.publisher).toEqual("New Publisher");
    expect(res.content.datePublished).toEqual(linkUpdateDate);
    expect(res.content.dateModified).toEqual(linkUpdateDate);
  });

  test<CustomTestContext>("update bookmark - non-link type error", async ({
    apiCallers,
  }) => {
    const api = apiCallers[0].bookmarks;

    // Create a TEXT bookmark
    const bookmark = await api.createBookmark({
      text: "Initial text",
      type: BookmarkTypes.TEXT,
    });

    // Attempt to update link-specific fields
    await expect(() =>
      api.updateBookmark({
        bookmarkId: bookmark.id,
        url: "https://should-fail.com", // Link-specific field
      }),
    ).rejects.toThrow(
      /Attempting to set link attributes for non-link type bookmark/,
    );
  });

  test<CustomTestContext>("list bookmarks", async ({ apiCallers, db }) => {
    const api = apiCallers[0].bookmarks;
    const emptyBookmarks = await api.getBookmarks({});
    expect(emptyBookmarks.bookmarks.length).toEqual(0);

    const bookmark1 = await api.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });

    const bookmark2 = await api.createBookmark({
      url: "https://google2.com",
      type: BookmarkTypes.LINK,
    });

    {
      const bookmarks = await api.getBookmarks({});
      expect(bookmarks.bookmarks.length).toEqual(2);
    }

    // Archive and favourite bookmark1
    await api.updateBookmark({
      bookmarkId: bookmark1.id,
      archived: true,
      favourited: true,
    });

    {
      const bookmarks = await api.getBookmarks({ archived: false });
      expect(bookmarks.bookmarks.length).toEqual(1);
      expect(bookmarks.bookmarks[0].id).toEqual(bookmark2.id);
    }

    {
      const bookmarks = await api.getBookmarks({ favourited: true });
      expect(bookmarks.bookmarks.length).toEqual(1);
      expect(bookmarks.bookmarks[0].id).toEqual(bookmark1.id);
    }

    {
      const bookmarks = await api.getBookmarks({ archived: true });
      expect(bookmarks.bookmarks.length).toEqual(1);
      expect(bookmarks.bookmarks[0].id).toEqual(bookmark1.id);
    }

    {
      const bookmarks = await api.getBookmarks({ ids: [bookmark1.id] });
      expect(bookmarks.bookmarks.length).toEqual(1);
      expect(bookmarks.bookmarks[0].id).toEqual(bookmark1.id);
    }

    // Test tagId filter
    {
      const tagId = await createTestTag(apiCallers[0], "testTag");
      await api.updateTags({
        bookmarkId: bookmark1.id,
        attach: [{ tagId }],
        detach: [],
      });
      const tagResult = await api.getBookmarks({ tagId });
      expect(tagResult.bookmarks.length).toBeGreaterThan(0);
      expect(
        tagResult.bookmarks.some((b) => b.id === bookmark1.id),
      ).toBeTruthy();
    }

    // Test rssFeedId filter
    {
      const feedId = await createTestFeed(
        apiCallers[0],
        "Test Feed",
        "https://rss-feed.com",
      );
      const rssBookmark = await api.createBookmark({
        url: "https://rss-feed.com",
        type: BookmarkTypes.LINK,
      });
      await db.insert(rssFeedImportsTable).values([
        {
          rssFeedId: feedId,
          entryId: "entry-id",
          bookmarkId: rssBookmark.id,
        },
      ]);
      const rssResult = await api.getBookmarks({ rssFeedId: feedId });
      expect(rssResult.bookmarks.length).toBeGreaterThan(0);
      expect(
        rssResult.bookmarks.some((b) => b.id === rssBookmark.id),
      ).toBeTruthy();
    }

    // Test listId filter
    {
      const list = await apiCallers[0].lists.create({
        name: "Test List",
        type: "manual",
        icon: "😂",
      });
      await apiCallers[0].lists.addToList({
        listId: list.id,
        bookmarkId: bookmark1.id,
      });
      const listResult = await api.getBookmarks({ listId: list.id });
      expect(listResult.bookmarks.length).toBeGreaterThan(0);
      expect(
        listResult.bookmarks.some((b) => b.id === bookmark1.id),
      ).toBeTruthy();
    }
  });

  test<CustomTestContext>("update tags", async ({ apiCallers }) => {
    const api = apiCallers[0].bookmarks;
    const createdBookmark = await api.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });

    await api.updateTags({
      bookmarkId: createdBookmark.id,
      attach: [
        { tagName: "tag1" },
        { tagName: "tag2" },
        { tagName: "tag3" },
        { tagName: "tag4" },
      ],
      detach: [],
    });

    let bookmark = await api.getBookmark({ bookmarkId: createdBookmark.id });
    expect(bookmark.tags.map((t) => t.name).sort()).toEqual([
      "tag1",
      "tag2",
      "tag3",
      "tag4",
    ]);

    const tag1Id = bookmark.tags.filter((t) => t.name == "tag1")[0].id;

    await api.updateTags({
      bookmarkId: bookmark.id,
      attach: [{ tagName: "tag5" }],
      detach: [{ tagId: tag1Id }, { tagName: "tag4" }],
    });

    bookmark = await api.getBookmark({ bookmarkId: bookmark.id });
    expect(bookmark.tags.map((t) => t.name).sort()).toEqual([
      "tag2",
      "tag3",
      "tag5",
    ]);

    await api.updateTags({
      bookmarkId: bookmark.id,
      attach: [{ tagId: tag1Id }, { tagName: "tag4" }],
      detach: [],
    });
    bookmark = await api.getBookmark({ bookmarkId: bookmark.id });
    expect(bookmark.tags.map((t) => t.name).sort()).toEqual([
      "tag1",
      "tag2",
      "tag3",
      "tag4",
      "tag5",
    ]);

    await expect(() =>
      api.updateTags({ bookmarkId: bookmark.id, attach: [{}], detach: [] }),
    ).rejects.toThrow(/You must provide either a tagId or a tagName/);
    await expect(() =>
      api.updateTags({ bookmarkId: bookmark.id, attach: [], detach: [{}] }),
    ).rejects.toThrow(/You must provide either a tagId or a tagName/);
    await expect(() =>
      api.updateTags({
        bookmarkId: bookmark.id,
        attach: [{ tagName: "" }],
        detach: [{}],
      }),
    ).rejects.toThrow(/You must provide either a tagId or a tagName/);
  });

  test<CustomTestContext>("update bookmark text", async ({ apiCallers }) => {
    const api = apiCallers[0].bookmarks;
    const createdBookmark = await api.createBookmark({
      text: "HELLO WORLD",
      type: BookmarkTypes.TEXT,
    });

    await api.updateBookmarkText({
      bookmarkId: createdBookmark.id,
      text: "WORLD HELLO",
    });

    const bookmark = await api.getBookmark({ bookmarkId: createdBookmark.id });
    assert(bookmark.content.type == BookmarkTypes.TEXT);
    expect(bookmark.content.text).toEqual("WORLD HELLO");
  });

  test<CustomTestContext>("privacy", async ({ apiCallers }) => {
    const user1Bookmark = await apiCallers[0].bookmarks.createBookmark({
      type: BookmarkTypes.LINK,
      url: "https://google.com",
    });
    const user2Bookmark = await apiCallers[1].bookmarks.createBookmark({
      type: BookmarkTypes.LINK,
      url: "https://google.com",
    });

    // All interactions with the wrong user should fail
    await expect(() =>
      apiCallers[0].bookmarks.deleteBookmark({ bookmarkId: user2Bookmark.id }),
    ).rejects.toThrow(/Bookmark not found/);
    await expect(() =>
      apiCallers[0].bookmarks.getBookmark({ bookmarkId: user2Bookmark.id }),
    ).rejects.toThrow(/Bookmark not found/);
    await expect(() =>
      apiCallers[0].bookmarks.updateBookmark({ bookmarkId: user2Bookmark.id }),
    ).rejects.toThrow(/Bookmark not found/);
    await expect(() =>
      apiCallers[0].bookmarks.updateTags({
        bookmarkId: user2Bookmark.id,
        attach: [],
        detach: [],
      }),
    ).rejects.toThrow(/Bookmark not found/);

    // Get bookmarks should only show the correct one
    expect(
      (await apiCallers[0].bookmarks.getBookmarks({})).bookmarks.map(
        (b) => b.id,
      ),
    ).toEqual([user1Bookmark.id]);
    expect(
      (await apiCallers[1].bookmarks.getBookmarks({})).bookmarks.map(
        (b) => b.id,
      ),
    ).toEqual([user2Bookmark.id]);
  });

  test<CustomTestContext>("bookmark links dedup", async ({ apiCallers }) => {
    // Two users with google in their bookmarks
    const bookmark1User1 = await apiCallers[0].bookmarks.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });
    expect(bookmark1User1.alreadyExists).toEqual(false);

    const bookmark1User2 = await apiCallers[1].bookmarks.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });
    expect(bookmark1User2.alreadyExists).toEqual(false);

    // User1 attempting to re-add google. Should return the existing bookmark
    const bookmark2User1 = await apiCallers[0].bookmarks.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });
    expect(bookmark2User1.alreadyExists).toEqual(true);
    expect(bookmark2User1.id).toEqual(bookmark1User1.id);

    // User2 attempting to re-add google. Should return the existing bookmark
    const bookmark2User2 = await apiCallers[1].bookmarks.createBookmark({
      url: "https://google.com",
      type: BookmarkTypes.LINK,
    });
    expect(bookmark2User2.alreadyExists).toEqual(true);
    expect(bookmark2User2.id).toEqual(bookmark1User2.id);

    // User1 adding google2. Should not return an existing bookmark
    const bookmark3User1 = await apiCallers[0].bookmarks.createBookmark({
      url: "https://google2.com",
      type: BookmarkTypes.LINK,
    });
    expect(bookmark3User1.alreadyExists).toEqual(false);
  });

  // Ensure that the pagination returns all the results
  test<CustomTestContext>("pagination", async ({ apiCallers, db }) => {
    const user = await apiCallers[0].users.whoami();
    let now = 100_000;

    const bookmarkWithDate = (date_ms: number) => ({
      userId: user.id,
      createdAt: new Date(date_ms),
      type: BookmarkTypes.TEXT as const,
    });

    // One normal bookmark
    const values = [bookmarkWithDate(now)];
    // 10 with a second in between
    for (let i = 0; i < 10; i++) {
      now -= 1000;
      values.push(bookmarkWithDate(now));
    }
    // Another ten but at the same second
    for (let i = 0; i < 10; i++) {
      values.push(bookmarkWithDate(now));
    }
    // And then another one with a second afterwards
    for (let i = 0; i < 10; i++) {
      now -= 1000;
      values.push(bookmarkWithDate(now));
    }
    // In total, we should have 31 bookmarks

    const inserted = await db.insert(bookmarks).values(values).returning();

    const validateWithLimit = async (limit: number) => {
      const results: string[] = [];
      let cursor = undefined;

      // To avoid running the test forever
      let i = 0;

      do {
        const res = await apiCallers[0].bookmarks.getBookmarks({
          limit,
          cursor,
          useCursorV2: true,
        });
        results.push(...res.bookmarks.map((b) => b.id));
        cursor = res.nextCursor;
        i++;
      } while (cursor && i < 100);

      expect(results.sort()).toEqual(inserted.map((b) => b.id).sort());
    };

    await validateWithLimit(1);
    await validateWithLimit(2);
    await validateWithLimit(3);
    await validateWithLimit(10);
    await validateWithLimit(100);
  });

  test<CustomTestContext>("getBookmark", async ({ apiCallers }) => {
    const api = apiCallers[0].bookmarks;
    const createdBookmark = await api.createBookmark({
      url: "https://example.com",
      type: BookmarkTypes.LINK,
    });

    // Test successful getBookmark with includeContent false
    const bookmarkWithoutContent = await api.getBookmark({
      bookmarkId: createdBookmark.id,
      includeContent: false,
    });
    expect(bookmarkWithoutContent.id).toEqual(createdBookmark.id);
    expect(bookmarkWithoutContent.content).toBeDefined(); // Content should still be present but might be partial
    expect(bookmarkWithoutContent.content.type).toEqual(BookmarkTypes.LINK);
    assert(bookmarkWithoutContent.content.type == BookmarkTypes.LINK);
    expect(bookmarkWithoutContent.content.url).toEqual("https://example.com");

    // Test successful getBookmark with includeContent true
    const bookmarkWithContent = await api.getBookmark({
      bookmarkId: createdBookmark.id,
      includeContent: true,
    });
    expect(bookmarkWithContent.id).toEqual(createdBookmark.id);
    expect(bookmarkWithContent.content).toBeDefined();
    expect(bookmarkWithContent.content.type).toEqual(BookmarkTypes.LINK);
    assert(bookmarkWithContent.content.type == BookmarkTypes.LINK);
    expect(bookmarkWithContent.content.url).toEqual("https://example.com");
    // Additional checks if content includes more details, e.g., htmlContent if available

    // Test non-existent bookmark
    await expect(() =>
      api.getBookmark({ bookmarkId: "non-existent-id" }),
    ).rejects.toThrow(/Bookmark not found/);
  });

  test<CustomTestContext>("getBrokenLinks", async ({ apiCallers, db }) => {
    const api = apiCallers[0].bookmarks;

    // Create a broken link bookmark (simulate by setting crawlStatus to 'failure')
    const brokenBookmark = await api.createBookmark({
      url: "https://broken-link.com",
      type: BookmarkTypes.LINK,
    });
    await db
      .update(bookmarkLinks)
      .set({ crawlStatus: "failure" })
      .where(eq(bookmarkLinks.id, brokenBookmark.id));

    const result = await api.getBrokenLinks();
    expect(result.bookmarks.length).toBeGreaterThan(0);
    expect(
      result.bookmarks.some((b) => b.id === brokenBookmark.id),
    ).toBeTruthy();
    expect(result.bookmarks[0].url).toEqual("https://broken-link.com");
    expect(result.bookmarks[0].isCrawlingFailure).toBeTruthy();

    // Test with no broken links
    await db
      .update(bookmarkLinks)
      .set({ crawlStatus: "success" })
      .where(eq(bookmarkLinks.id, brokenBookmark.id));
    const emptyResult = await api.getBrokenLinks();
    expect(emptyResult.bookmarks.length).toEqual(0);
  });

  describe("Bookmark Quotas", () => {
    test<CustomTestContext>("create bookmark with no quota (unlimited)", async ({
      apiCallers,
    }) => {
      const api = apiCallers[0].bookmarks;

      // User should be able to create bookmarks without any quota restrictions
      const bookmark1 = await api.createBookmark({
        url: "https://example1.com",
        type: BookmarkTypes.LINK,
      });
      expect(bookmark1.alreadyExists).toEqual(false);

      const bookmark2 = await api.createBookmark({
        url: "https://example2.com",
        type: BookmarkTypes.LINK,
      });
      expect(bookmark2.alreadyExists).toEqual(false);

      const bookmark3 = await api.createBookmark({
        text: "Test text bookmark",
        type: BookmarkTypes.TEXT,
      });
      expect(bookmark3.alreadyExists).toEqual(false);
    });

    test<CustomTestContext>("create bookmark with quota limit", async ({
      apiCallers,
      db,
    }) => {
      const user = await apiCallers[0].users.whoami();
      const api = apiCallers[0].bookmarks;

      // Set quota to 2 bookmarks for this user
      await db
        .update(users)
        .set({ bookmarkQuota: 2 })
        .where(eq(users.id, user.id));

      // First bookmark should succeed
      const bookmark1 = await api.createBookmark({
        url: "https://example1.com",
        type: BookmarkTypes.LINK,
      });
      expect(bookmark1.alreadyExists).toEqual(false);

      // Second bookmark should succeed
      const bookmark2 = await api.createBookmark({
        url: "https://example2.com",
        type: BookmarkTypes.LINK,
      });
      expect(bookmark2.alreadyExists).toEqual(false);

      // Third bookmark should fail due to quota
      await expect(() =>
        api.createBookmark({
          url: "https://example3.com",
          type: BookmarkTypes.LINK,
        }),
      ).rejects.toThrow(
        /Bookmark quota exceeded. You can only have 2 bookmarks./,
      );
    });

    test<CustomTestContext>("create bookmark with quota limit - different types", async ({
      apiCallers,
      db,
    }) => {
      const user = await apiCallers[0].users.whoami();
      const api = apiCallers[0].bookmarks;

      // Set quota to 2 bookmarks for this user
      await db
        .update(users)
        .set({ bookmarkQuota: 2 })
        .where(eq(users.id, user.id));

      // Create one link bookmark
      await api.createBookmark({
        url: "https://example1.com",
        type: BookmarkTypes.LINK,
      });

      // Create one text bookmark
      await api.createBookmark({
        text: "Test text content",
        type: BookmarkTypes.TEXT,
      });

      // Third bookmark (any type) should fail
      await expect(() =>
        api.createBookmark({
          text: "Another text bookmark",
          type: BookmarkTypes.TEXT,
        }),
      ).rejects.toThrow(
        /Bookmark quota exceeded. You can only have 2 bookmarks./,
      );
    });

    test<CustomTestContext>("quota enforcement after deletion", async ({
      apiCallers,
      db,
    }) => {
      const user = await apiCallers[0].users.whoami();
      const api = apiCallers[0].bookmarks;

      // Set quota to 1 bookmark for this user
      await db
        .update(users)
        .set({ bookmarkQuota: 1 })
        .where(eq(users.id, user.id));

      // Create first bookmark
      const bookmark1 = await api.createBookmark({
        url: "https://example1.com",
        type: BookmarkTypes.LINK,
      });

      // Second bookmark should fail
      await expect(() =>
        api.createBookmark({
          url: "https://example2.com",
          type: BookmarkTypes.LINK,
        }),
      ).rejects.toThrow(
        /Bookmark quota exceeded. You can only have 1 bookmarks./,
      );

      // Delete the first bookmark
      await api.deleteBookmark({ bookmarkId: bookmark1.id });

      // Now should be able to create a new bookmark
      const bookmark2 = await api.createBookmark({
        url: "https://example2.com",
        type: BookmarkTypes.LINK,
      });
      expect(bookmark2.alreadyExists).toEqual(false);
    });

    test<CustomTestContext>("quota isolation between users", async ({
      apiCallers,
      db,
    }) => {
      const user1 = await apiCallers[0].users.whoami();

      // Set quota to 1 for user1, unlimited for user2
      await db
        .update(users)
        .set({ bookmarkQuota: 1 })
        .where(eq(users.id, user1.id));

      // User1 creates one bookmark (reaches quota)
      await apiCallers[0].bookmarks.createBookmark({
        url: "https://user1-example.com",
        type: BookmarkTypes.LINK,
      });

      // User1 cannot create another bookmark
      await expect(() =>
        apiCallers[0].bookmarks.createBookmark({
          url: "https://user1-example2.com",
          type: BookmarkTypes.LINK,
        }),
      ).rejects.toThrow(
        /Bookmark quota exceeded. You can only have 1 bookmarks./,
      );

      // User2 should be able to create multiple bookmarks (no quota)
      await apiCallers[1].bookmarks.createBookmark({
        url: "https://user2-example1.com",
        type: BookmarkTypes.LINK,
      });

      await apiCallers[1].bookmarks.createBookmark({
        url: "https://user2-example2.com",
        type: BookmarkTypes.LINK,
      });

      await apiCallers[1].bookmarks.createBookmark({
        text: "User2 text bookmark",
        type: BookmarkTypes.TEXT,
      });
    });

    test<CustomTestContext>("quota with zero limit", async ({
      apiCallers,
      db,
    }) => {
      const user = await apiCallers[0].users.whoami();
      const api = apiCallers[0].bookmarks;

      // Set quota to 0 bookmarks for this user
      await db
        .update(users)
        .set({ bookmarkQuota: 0 })
        .where(eq(users.id, user.id));

      // Any bookmark creation should fail
      await expect(() =>
        api.createBookmark({
          url: "https://example.com",
          type: BookmarkTypes.LINK,
        }),
      ).rejects.toThrow(
        /Bookmark quota exceeded. You can only have 0 bookmarks./,
      );

      await expect(() =>
        api.createBookmark({
          text: "Test text",
          type: BookmarkTypes.TEXT,
        }),
      ).rejects.toThrow(
        /Bookmark quota exceeded. You can only have 0 bookmarks./,
      );
    });

    test<CustomTestContext>("quota does not affect duplicate link detection", async ({
      apiCallers,
      db,
    }) => {
      const user = await apiCallers[0].users.whoami();
      const api = apiCallers[0].bookmarks;

      // Set quota to 1 bookmark for this user
      await db
        .update(users)
        .set({ bookmarkQuota: 1 })
        .where(eq(users.id, user.id));

      // Create first bookmark
      const bookmark1 = await api.createBookmark({
        url: "https://example.com",
        type: BookmarkTypes.LINK,
      });
      expect(bookmark1.alreadyExists).toEqual(false);

      // Try to create the same URL again - should return existing bookmark, not fail with quota
      const bookmark2 = await api.createBookmark({
        url: "https://example.com",
        type: BookmarkTypes.LINK,
      });
      expect(bookmark2.alreadyExists).toEqual(true);
      expect(bookmark2.id).toEqual(bookmark1.id);

      // But creating a different URL should fail due to quota
      await expect(() =>
        api.createBookmark({
          url: "https://different-example.com",
          type: BookmarkTypes.LINK,
        }),
      ).rejects.toThrow(
        /Bookmark quota exceeded. You can only have 1 bookmarks./,
      );
    });
  });
});