Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

browser-single-tab.test.ts

145 lines3.7 KB

1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, expect, it } from 'vitest'
5import {
6 InvalidPersistedCollectionConfigError,
7 PersistenceUnavailableError,
8} from '@tanstack/db-sqlite-persistence-core'
9import {
10 createBrowserWASQLitePersistence,
11 openBrowserWASQLiteOPFSDatabase,
12} from '../src'
13import { createWASQLiteTestDatabase } from './helpers/wa-sqlite-test-db'
14​
15const activeCleanupFns: Array<() => void | Promise<void>> = []
16​
17afterEach(async () => {
18 while (activeCleanupFns.length > 0) {
19 const cleanupFn = activeCleanupFns.pop()
20 await Promise.resolve(cleanupFn?.())
21 }
22})
23​
24function createTempSqlitePath(): string {
25 const tempDirectory = mkdtempSync(
26 join(tmpdir(), `db-browser-single-tab-test-`),
27 )
28 const dbPath = join(tempDirectory, `state.sqlite`)
29 activeCleanupFns.push(() => {
30 rmSync(tempDirectory, { recursive: true, force: true })
31 })
32 return dbPath
34​
35it(`works without browser election primitives`, async () => {
36 const dbPath = createTempSqlitePath()
37 const database = createWASQLiteTestDatabase({
38 filename: dbPath,
39 })
40 activeCleanupFns.push(() => Promise.resolve(database.close?.()))
41​
42 const originalBroadcastDescriptor = Object.getOwnPropertyDescriptor(
43 globalThis,
44 `BroadcastChannel`,
45 )
46 Object.defineProperty(globalThis, `BroadcastChannel`, {
47 value: class {
48 constructor() {
49 throw new Error(
50 `BroadcastChannel should not be used in single-tab mode`,
51 )
52 }
53 },
54 configurable: true,
55 writable: true,
56 })
57 activeCleanupFns.push(() => {
58 if (originalBroadcastDescriptor) {
59 Object.defineProperty(
60 globalThis,
61 `BroadcastChannel`,
62 originalBroadcastDescriptor,
63 )
64 return
65 }
66 Reflect.deleteProperty(globalThis, `BroadcastChannel`)
67 })
68​
69 const navigatorWithOptionalLocks = globalThis.navigator as
70 | (Navigator & { locks?: unknown })
71 | undefined
72 const originalLocks = navigatorWithOptionalLocks?.locks
73 if (navigatorWithOptionalLocks) {
74 try {
75 Object.defineProperty(navigatorWithOptionalLocks, `locks`, {
76 value: {
77 request: () => {
78 throw new Error(`Web Locks should not be used in single-tab mode`)
79 },
80 },
81 configurable: true,
82 writable: true,
83 })
84 activeCleanupFns.push(() => {
85 Object.defineProperty(navigatorWithOptionalLocks, `locks`, {
86 value: originalLocks,
87 configurable: true,
88 writable: true,
89 })
90 })
91 } catch {
92 // Some runtimes expose a non-configurable navigator.locks property.
93 }
94 }
95​
96 const persistence = createBrowserWASQLitePersistence({
97 database,
98 })
99​
100 await persistence.adapter.applyCommittedTx(`todos`, {
101 txId: `tx-1`,
102 term: 1,
103 seq: 1,
104 rowVersion: 1,
105 mutations: [
106 {
107 type: `insert`,
108 key: `1`,
109 value: {
110 id: `1`,
111 title: `single-tab`,
112 score: 1,
113 },
114 },
115 ],
116 })
117​
118 const rows = await persistence.adapter.loadSubset(`todos`, {})
119 expect(rows).toEqual([
120 {
121 key: `1`,
122 value: {
123 id: `1`,
124 title: `single-tab`,
125 score: 1,
126 },
127 },
128 ])
129})
130​
131it(`throws PersistenceUnavailableError when OPFS sync access is missing`, async () => {
132 await expect(
133 openBrowserWASQLiteOPFSDatabase({
134 databaseName: `phase-7.sqlite`,
135 }),
136 ).rejects.toBeInstanceOf(PersistenceUnavailableError)
137})
138​
139it(`rejects empty browser OPFS database names`, async () => {
140 await expect(
141 openBrowserWASQLiteOPFSDatabase({
142 databaseName: ` `,
143 }),
144 ).rejects.toBeInstanceOf(InvalidPersistedCollectionConfigError)
145})