@haatlabs-core/templates 0.19.0 → 0.22.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.
- package/package.json +3 -3
- package/starter/apps/api/package.json.tmpl +1 -0
- package/starter/apps/api/src/app.module.ts +36 -0
- package/starter/apps/api/src/notifications.int.test.ts +210 -0
- package/starter/apps/api/src/security-sweep.int.test.ts +81 -12
- package/starter/apps/api/src/seed-plans.int.test.ts +8 -1
- package/starter/apps/api/src/seed.ts +16 -3
- package/starter/apps/shopify-app/index.html +2 -0
- package/starter/apps/shopify-app/public/theme-boot.js +6 -0
- package/starter/apps/web/public/notifications-sw.js +47 -0
- package/starter/apps/worker/package.json.tmpl +2 -0
- package/starter/apps/worker/src/handlers/notifications.handler.ts +63 -0
- package/starter/apps/worker/src/runtime.ts +52 -26
- package/starter/dot-env.example +16 -0
- package/starter/packages/config/src/config.test.ts +26 -0
- package/starter/packages/config/src/config.ts +11 -2
- package/starter/packages/contracts/package.json.tmpl +3 -1
- package/starter/packages/contracts/src/notifications.ts +38 -0
- package/starter/packages/database/drizzle/0009_notifications.sql +87 -0
- package/starter/packages/database/drizzle/0010_platform_vendorhaat.sql +5 -0
- package/starter/packages/database/drizzle/meta/0009_snapshot.json +2446 -0
- package/starter/packages/database/drizzle/meta/0010_snapshot.json +2467 -0
- package/starter/packages/database/drizzle/meta/_journal.json +14 -0
- package/starter/packages/database/package.json.tmpl +1 -0
- package/starter/packages/database/src/index.ts +1 -0
- package/starter/packages/database/src/repositories/billing.int.test.ts +5 -4
- package/starter/packages/database/src/repositories/notification.repository.ts +65 -0
- package/starter/packages/database/src/schema/index.ts +1 -0
- package/starter/packages/database/src/schema/notifications.ts +37 -0
- package/starter/packages/database/src/schema-tables.int.test.ts +10 -0
- package/starter/packages/queue/src/topology.test.ts +1 -0
- package/starter/packages/queue/src/topology.ts +3 -0
- package/starter/packages/web-ui/package.json.tmpl +1 -0
- package/starter/packages/web-ui/src/App.test.tsx +140 -6
- package/starter/packages/web-ui/src/App.tsx +129 -27
- package/starter/packages/web-ui/src/api-client.test.ts +204 -1
- package/starter/packages/web-ui/src/api-client.ts +207 -1
- package/starter/packages/web-ui/src/components/Logo.tsx +11 -3
- package/starter/packages/web-ui/src/pages/HomePage.tsx +3 -3
- package/starter/packages/web-ui/src/pages/LoginPage.tsx +3 -1
- package/starter/packages/web-ui/src/pages/NotificationSettingsPage.tsx +24 -0
- package/starter/packages/web-ui/src/pages/NotificationsPage.tsx +19 -0
- package/starter/packages/web-ui/src/styles.css +73 -37
- package/starter/packages/web-ui/src/testing/fake-client.ts +16 -0
|
@@ -2,7 +2,15 @@
|
|
|
2
2
|
import { QueryClientProvider, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
3
3
|
import { useEffect, useState } from 'react';
|
|
4
4
|
import type { ReactElement } from 'react';
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
BrowserRouter,
|
|
7
|
+
NavLink,
|
|
8
|
+
Navigate,
|
|
9
|
+
Route,
|
|
10
|
+
Routes,
|
|
11
|
+
useLocation,
|
|
12
|
+
useNavigate,
|
|
13
|
+
} from 'react-router-dom';
|
|
6
14
|
import '@fontsource/instrument-sans/400.css';
|
|
7
15
|
import '@fontsource/instrument-sans/500.css';
|
|
8
16
|
import '@fontsource/instrument-sans/600.css';
|
|
@@ -13,13 +21,15 @@ import '@fontsource/jetbrains-mono/500.css';
|
|
|
13
21
|
import './styles.css';
|
|
14
22
|
import { ApiError } from './api-client';
|
|
15
23
|
import type { ApiClient } from './api-client';
|
|
16
|
-
import { createQueryClient, isUnauthorized } from '@haatlabs-core/ui/client';
|
|
17
|
-
import { AppShell, ThemeStyles } from '@haatlabs-core/ui';
|
|
24
|
+
import { NotificationBell, createQueryClient, isUnauthorized } from '@haatlabs-core/ui/client';
|
|
25
|
+
import { AppShell, MobileNav, NavIcon, ThemeStyles, useNarrow } from '@haatlabs-core/ui';
|
|
18
26
|
import type { NavGroup } from '@haatlabs-core/ui';
|
|
19
|
-
import { Logo } from './components/Logo';
|
|
27
|
+
import { Logo, LogoMark } from './components/Logo';
|
|
20
28
|
import { LoginPage } from './pages/LoginPage';
|
|
21
29
|
import { ConnectExtensionPage } from './pages/ConnectExtensionPage';
|
|
22
30
|
import { HomePage } from './pages/HomePage';
|
|
31
|
+
import { NotificationSettingsPage } from './pages/NotificationSettingsPage';
|
|
32
|
+
import { NotificationsPage } from './pages/NotificationsPage';
|
|
23
33
|
import { StoresPage } from './pages/stores/StoresPage';
|
|
24
34
|
import { UsagePage } from './pages/UsagePage';
|
|
25
35
|
#@if standalone
|
|
@@ -33,12 +43,45 @@ export type AppMode = 'standalone' | 'embedded';
|
|
|
33
43
|
const BRAND = '@@Name@@';
|
|
34
44
|
const ME_KEY = ['me'];
|
|
35
45
|
|
|
46
|
+
/**
|
|
47
|
+
* Turns push off on this device first, so a shared computer stops showing this person's
|
|
48
|
+
* notifications; a failure there (no service worker, the server already gone) does not stop
|
|
49
|
+
* the sign-out.
|
|
50
|
+
*/
|
|
51
|
+
async function signOut(client: ApiClient): Promise<void> {
|
|
52
|
+
await client.notifications.push?.disable().catch(() => undefined);
|
|
53
|
+
await client.logout();
|
|
54
|
+
}
|
|
55
|
+
|
|
36
56
|
/** Keeps the query string (Shopify's `host` and `shop`) when redirecting to the default page. */
|
|
37
57
|
function RedirectTo({ pathname }: { pathname: string }): ReactElement {
|
|
38
58
|
const { search } = useLocation();
|
|
39
59
|
return <Navigate to={{ pathname, search }} replace />;
|
|
40
60
|
}
|
|
41
61
|
|
|
62
|
+
/** The bell: the unread count, live, and the newest items; an item opens its page. */
|
|
63
|
+
function Bell({ client }: { client: ApiClient }): ReactElement {
|
|
64
|
+
const navigate = useNavigate();
|
|
65
|
+
return (
|
|
66
|
+
<NotificationBell client={client.notifications} onOpenItem={(link) => void navigate(link)} />
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Shopify's own query parameters, which every page of the embedded app keeps. */
|
|
71
|
+
const SHOPIFY_PARAMS = ['host', 'shop', 'embedded'];
|
|
72
|
+
|
|
73
|
+
/** `search` cut down to Shopify's parameters ('' when it has none): a page's own stay behind. */
|
|
74
|
+
function shopifyQuery(search: string): string {
|
|
75
|
+
const all = new URLSearchParams(search);
|
|
76
|
+
const kept = new URLSearchParams();
|
|
77
|
+
for (const name of SHOPIFY_PARAMS) {
|
|
78
|
+
const value = all.get(name);
|
|
79
|
+
if (value !== null) kept.set(name, value);
|
|
80
|
+
}
|
|
81
|
+
const query = kept.toString();
|
|
82
|
+
return query ? `?${query}` : '';
|
|
83
|
+
}
|
|
84
|
+
|
|
42
85
|
function Shell({
|
|
43
86
|
client,
|
|
44
87
|
mode,
|
|
@@ -51,9 +94,11 @@ function Shell({
|
|
|
51
94
|
reload: () => void;
|
|
52
95
|
}): ReactElement {
|
|
53
96
|
const queryClient = useQueryClient();
|
|
97
|
+
const narrow = useNarrow();
|
|
98
|
+
const shopify = shopifyQuery(useLocation().search);
|
|
54
99
|
const me = useQuery({ queryKey: ME_KEY, queryFn: () => client.me(), retry: false });
|
|
55
100
|
const logout = useMutation({
|
|
56
|
-
mutationFn: () => client
|
|
101
|
+
mutationFn: () => signOut(client),
|
|
57
102
|
onSuccess: () => queryClient.clear(),
|
|
58
103
|
});
|
|
59
104
|
|
|
@@ -90,11 +135,12 @@ function Shell({
|
|
|
90
135
|
const nav: NavGroup[] = [
|
|
91
136
|
{
|
|
92
137
|
items: [
|
|
93
|
-
|
|
94
|
-
{ label: '
|
|
95
|
-
{ label: '
|
|
138
|
+
// The pages of the phone and tablet bottom bar (at most 4; the rest go under More).
|
|
139
|
+
{ label: 'Home', to: '/home', icon: <NavIcon name="home" />, bottom: true },
|
|
140
|
+
{ label: 'Stores', to: '/stores', icon: <NavIcon name="store" />, bottom: true },
|
|
141
|
+
{ label: 'Plan and usage', to: '/usage', icon: <NavIcon name="plan" />, bottom: true },
|
|
96
142
|
#@if standalone
|
|
97
|
-
{ label: 'Find images', to: '/find-images' },
|
|
143
|
+
{ label: 'Find images', to: '/find-images', icon: <NavIcon name="images" />, bottom: true },
|
|
98
144
|
#@end
|
|
99
145
|
],
|
|
100
146
|
},
|
|
@@ -133,28 +179,53 @@ function Shell({
|
|
|
133
179
|
/>
|
|
134
180
|
}
|
|
135
181
|
/>
|
|
182
|
+
<Route
|
|
183
|
+
path="/notifications"
|
|
184
|
+
element={<NotificationsPage client={client.notifications} />}
|
|
185
|
+
/>
|
|
186
|
+
<Route
|
|
187
|
+
path="/settings/notifications"
|
|
188
|
+
element={<NotificationSettingsPage client={client.notifications} />}
|
|
189
|
+
/>
|
|
136
190
|
<Route path="*" element={<RedirectTo pathname="/home" />} />
|
|
137
191
|
</Routes>
|
|
138
192
|
);
|
|
139
|
-
if (embedded)
|
|
193
|
+
if (embedded) {
|
|
140
194
|
// Shopify's own frame already names the app and the shop, and there is nobody to
|
|
141
|
-
// sign out: one quiet navigation, as Shopify's own pages have
|
|
195
|
+
// sign out: one quiet navigation, as Shopify's own pages have; below 1024px the
|
|
196
|
+
// platform's bottom bar. Both keep Shopify's `host`, `shop` and `embedded`, nothing else.
|
|
197
|
+
const embeddedNav: NavGroup[] = [
|
|
198
|
+
{
|
|
199
|
+
items: [
|
|
200
|
+
{ label: 'Home', to: '/home', icon: <NavIcon name="home" />, bottom: true },
|
|
201
|
+
{ label: 'Store', to: '/stores', icon: <NavIcon name="store" />, bottom: true },
|
|
202
|
+
{ label: 'Plan and usage', to: '/usage', icon: <NavIcon name="plan" />, bottom: true },
|
|
203
|
+
],
|
|
204
|
+
},
|
|
205
|
+
];
|
|
142
206
|
return (
|
|
143
207
|
<>
|
|
144
208
|
<div className="embedded-nav">
|
|
145
|
-
|
|
146
|
-
<
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
209
|
+
{!narrow && (
|
|
210
|
+
<nav aria-label="Main" className="store-nav">
|
|
211
|
+
<NavLink to={{ pathname: '/home', search: shopify }}>Home</NavLink>
|
|
212
|
+
<NavLink to={{ pathname: '/stores', search: shopify }}>Store</NavLink>
|
|
213
|
+
<NavLink to={{ pathname: '/usage', search: shopify }}>Plan and usage</NavLink>
|
|
214
|
+
</nav>
|
|
215
|
+
)}
|
|
216
|
+
<Bell client={client} />
|
|
150
217
|
</div>
|
|
151
218
|
{routes}
|
|
219
|
+
{narrow && <MobileNav nav={embeddedNav} search={shopify} />}
|
|
152
220
|
</>
|
|
153
221
|
);
|
|
222
|
+
}
|
|
154
223
|
return (
|
|
155
224
|
<AppShell
|
|
156
225
|
brand={<Logo />}
|
|
226
|
+
brandMark={<LogoMark />}
|
|
157
227
|
nav={nav}
|
|
228
|
+
notifications={<Bell client={client} />}
|
|
158
229
|
account={{
|
|
159
230
|
name: me.data.organization.name,
|
|
160
231
|
detail: me.data.user?.email ?? undefined,
|
|
@@ -202,14 +273,14 @@ export function App({
|
|
|
202
273
|
useEffect(() => {
|
|
203
274
|
document.title = BRAND;
|
|
204
275
|
}, []);
|
|
205
|
-
// Inside Shopify admin the pages take on its
|
|
276
|
+
// Inside Shopify admin the pages take on its compact layout (see "Inside Shopify admin" in
|
|
277
|
+
// styles.css); the colours are the dashboard theme's, light, dark or the system's, there too.
|
|
206
278
|
useEffect(() => {
|
|
207
279
|
document.documentElement.classList.toggle('embedded', mode === 'embedded');
|
|
208
280
|
}, [mode]);
|
|
209
281
|
return (
|
|
210
282
|
<QueryClientProvider client={queryClient}>
|
|
211
|
-
|
|
212
|
-
{mode !== 'embedded' && <ThemeStyles accent="indigo" />}
|
|
283
|
+
<ThemeStyles accent="indigo" />
|
|
213
284
|
<BrowserRouter>
|
|
214
285
|
<ScrollToTop />
|
|
215
286
|
<Shell
|
|
@@ -227,7 +298,7 @@ export function App({
|
|
|
227
298
|
import { QueryClientProvider, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
228
299
|
import { useEffect, useState } from 'react';
|
|
229
300
|
import type { ReactElement } from 'react';
|
|
230
|
-
import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom';
|
|
301
|
+
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
|
|
231
302
|
import '@fontsource/instrument-sans/400.css';
|
|
232
303
|
import '@fontsource/instrument-sans/500.css';
|
|
233
304
|
import '@fontsource/instrument-sans/600.css';
|
|
@@ -238,13 +309,15 @@ import '@fontsource/jetbrains-mono/500.css';
|
|
|
238
309
|
import './styles.css';
|
|
239
310
|
import { ApiError } from './api-client';
|
|
240
311
|
import type { ApiClient } from './api-client';
|
|
241
|
-
import { createQueryClient, isUnauthorized } from '@haatlabs-core/ui/client';
|
|
242
|
-
import { AppShell, ThemeStyles } from '@haatlabs-core/ui';
|
|
312
|
+
import { NotificationBell, createQueryClient, isUnauthorized } from '@haatlabs-core/ui/client';
|
|
313
|
+
import { AppShell, NavIcon, ThemeStyles } from '@haatlabs-core/ui';
|
|
243
314
|
import type { NavGroup } from '@haatlabs-core/ui';
|
|
244
|
-
import { Logo } from './components/Logo';
|
|
315
|
+
import { Logo, LogoMark } from './components/Logo';
|
|
245
316
|
import { LoginPage } from './pages/LoginPage';
|
|
246
317
|
import { ConnectExtensionPage } from './pages/ConnectExtensionPage';
|
|
247
318
|
import { HomePage } from './pages/HomePage';
|
|
319
|
+
import { NotificationSettingsPage } from './pages/NotificationSettingsPage';
|
|
320
|
+
import { NotificationsPage } from './pages/NotificationsPage';
|
|
248
321
|
import { UsagePage } from './pages/UsagePage';
|
|
249
322
|
#@if standalone
|
|
250
323
|
import { FindImagesPage } from './pages/FindImagesPage';
|
|
@@ -254,17 +327,35 @@ import { Loading } from '@haatlabs-core/ui';
|
|
|
254
327
|
const BRAND = '@@Name@@';
|
|
255
328
|
const ME_KEY = ['me'];
|
|
256
329
|
|
|
330
|
+
/**
|
|
331
|
+
* Turns push off on this device first, so a shared computer stops showing this person's
|
|
332
|
+
* notifications; a failure there (no service worker, the server already gone) does not stop
|
|
333
|
+
* the sign-out.
|
|
334
|
+
*/
|
|
335
|
+
async function signOut(client: ApiClient): Promise<void> {
|
|
336
|
+
await client.notifications.push?.disable().catch(() => undefined);
|
|
337
|
+
await client.logout();
|
|
338
|
+
}
|
|
339
|
+
|
|
257
340
|
/** Keeps the query string when redirecting to the default page. */
|
|
258
341
|
function RedirectTo({ pathname }: { pathname: string }): ReactElement {
|
|
259
342
|
const { search } = useLocation();
|
|
260
343
|
return <Navigate to={{ pathname, search }} replace />;
|
|
261
344
|
}
|
|
262
345
|
|
|
346
|
+
/** The bell: the unread count, live, and the newest items; an item opens its page. */
|
|
347
|
+
function Bell({ client }: { client: ApiClient }): ReactElement {
|
|
348
|
+
const navigate = useNavigate();
|
|
349
|
+
return (
|
|
350
|
+
<NotificationBell client={client.notifications} onOpenItem={(link) => void navigate(link)} />
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
|
|
263
354
|
function Shell({ client, reload }: { client: ApiClient; reload: () => void }): ReactElement {
|
|
264
355
|
const queryClient = useQueryClient();
|
|
265
356
|
const me = useQuery({ queryKey: ME_KEY, queryFn: () => client.me(), retry: false });
|
|
266
357
|
const logout = useMutation({
|
|
267
|
-
mutationFn: () => client
|
|
358
|
+
mutationFn: () => signOut(client),
|
|
268
359
|
onSuccess: () => queryClient.clear(),
|
|
269
360
|
});
|
|
270
361
|
|
|
@@ -292,10 +383,11 @@ function Shell({ client, reload }: { client: ApiClient; reload: () => void }): R
|
|
|
292
383
|
const nav: NavGroup[] = [
|
|
293
384
|
{
|
|
294
385
|
items: [
|
|
295
|
-
|
|
296
|
-
{ label: '
|
|
386
|
+
// The pages of the phone and tablet bottom bar (at most 4; the rest go under More).
|
|
387
|
+
{ label: 'Home', to: '/home', icon: <NavIcon name="home" />, bottom: true },
|
|
388
|
+
{ label: 'Plan and usage', to: '/usage', icon: <NavIcon name="plan" />, bottom: true },
|
|
297
389
|
#@if standalone
|
|
298
|
-
{ label: 'Find images', to: '/find-images' },
|
|
390
|
+
{ label: 'Find images', to: '/find-images', icon: <NavIcon name="images" />, bottom: true },
|
|
299
391
|
#@end
|
|
300
392
|
],
|
|
301
393
|
},
|
|
@@ -303,7 +395,9 @@ function Shell({ client, reload }: { client: ApiClient; reload: () => void }): R
|
|
|
303
395
|
return (
|
|
304
396
|
<AppShell
|
|
305
397
|
brand={<Logo />}
|
|
398
|
+
brandMark={<LogoMark />}
|
|
306
399
|
nav={nav}
|
|
400
|
+
notifications={<Bell client={client} />}
|
|
307
401
|
account={{
|
|
308
402
|
name: me.data.organization.name,
|
|
309
403
|
detail: me.data.user?.email ?? undefined,
|
|
@@ -333,6 +427,14 @@ function Shell({ client, reload }: { client: ApiClient; reload: () => void }): R
|
|
|
333
427
|
/>
|
|
334
428
|
}
|
|
335
429
|
/>
|
|
430
|
+
<Route
|
|
431
|
+
path="/notifications"
|
|
432
|
+
element={<NotificationsPage client={client.notifications} />}
|
|
433
|
+
/>
|
|
434
|
+
<Route
|
|
435
|
+
path="/settings/notifications"
|
|
436
|
+
element={<NotificationSettingsPage client={client.notifications} />}
|
|
437
|
+
/>
|
|
336
438
|
<Route path="*" element={<RedirectTo pathname="/home" />} />
|
|
337
439
|
</Routes>
|
|
338
440
|
</AppShell>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from 'vitest';
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
2
|
import { ApiError, createApiClient, readCookie } from './api-client';
|
|
3
3
|
|
|
4
4
|
const STORE_ID = '7f2c1d5e-8a43-4b6f-9c1d-2e3f4a5b6c7d';
|
|
@@ -256,3 +256,206 @@ describe('readCookie', () => {
|
|
|
256
256
|
expect(readCookie('@@name@@_csrf', '')).toBeNull();
|
|
257
257
|
});
|
|
258
258
|
});
|
|
259
|
+
|
|
260
|
+
describe('the notifications client', () => {
|
|
261
|
+
const ITEM = {
|
|
262
|
+
id: '3b7e1f7a-4c1d-4e5f-9a8b-1c2d3e4f5a6b',
|
|
263
|
+
event: 'account.welcome',
|
|
264
|
+
title: 'Welcome',
|
|
265
|
+
body: 'Hello',
|
|
266
|
+
link: '/home',
|
|
267
|
+
readAt: null,
|
|
268
|
+
createdAt: '2026-11-22T10:00:00.000Z',
|
|
269
|
+
};
|
|
270
|
+
/** A response that streams `chunks`, then ends. */
|
|
271
|
+
const eventStream = (chunks: string[]): Response =>
|
|
272
|
+
new Response(
|
|
273
|
+
new ReadableStream<Uint8Array>({
|
|
274
|
+
start(controller) {
|
|
275
|
+
for (const chunk of chunks) controller.enqueue(new TextEncoder().encode(chunk));
|
|
276
|
+
controller.close();
|
|
277
|
+
},
|
|
278
|
+
}),
|
|
279
|
+
{ headers: { 'content-type': 'text/event-stream' } },
|
|
280
|
+
);
|
|
281
|
+
|
|
282
|
+
afterEach(() => {
|
|
283
|
+
vi.unstubAllGlobals();
|
|
284
|
+
vi.useRealTimers();
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it('reads the inbox and marks items read on the notification routes', async () => {
|
|
288
|
+
const fetch = vi
|
|
289
|
+
.fn()
|
|
290
|
+
.mockResolvedValueOnce(Response.json({ items: [ITEM], nextCursor: null }))
|
|
291
|
+
.mockResolvedValueOnce(Response.json({ unread: 3 }))
|
|
292
|
+
.mockResolvedValueOnce(Response.json({ unread: 2 }))
|
|
293
|
+
.mockResolvedValueOnce(Response.json({ unread: 0 }));
|
|
294
|
+
const { notifications } = cookieClient(fetch);
|
|
295
|
+
expect(await notifications.list({ unread: true, cursor: 'abc' })).toEqual({
|
|
296
|
+
items: [ITEM],
|
|
297
|
+
nextCursor: null,
|
|
298
|
+
});
|
|
299
|
+
expect(await notifications.unreadCount()).toBe(3);
|
|
300
|
+
expect(await notifications.markRead([ITEM.id])).toBe(2);
|
|
301
|
+
expect(await notifications.markAllRead()).toBe(0);
|
|
302
|
+
expect(fetch.mock.calls.map((call) => (call as FetchCall)[0])).toEqual([
|
|
303
|
+
'/api/v1/notifications?unread=true&cursor=abc',
|
|
304
|
+
'/api/v1/notifications/unread-count',
|
|
305
|
+
'/api/v1/notifications/read',
|
|
306
|
+
'/api/v1/notifications/read-all',
|
|
307
|
+
]);
|
|
308
|
+
const [, read] = callAt(fetch, 2) as unknown as [string, { body: string }];
|
|
309
|
+
expect(JSON.parse(read.body)).toEqual({ ids: [ITEM.id] });
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
it('streams the unread count and new items with the bearer token, then waits as the server says', async () => {
|
|
313
|
+
vi.useFakeTimers();
|
|
314
|
+
const fetch = vi
|
|
315
|
+
.fn()
|
|
316
|
+
.mockResolvedValueOnce(
|
|
317
|
+
eventStream([
|
|
318
|
+
'retry: 2000\n\n: ping\n\nevent: unr',
|
|
319
|
+
'ead\ndata: {"unread":4}\n\n',
|
|
320
|
+
`event: notification\ndata: ${JSON.stringify(ITEM)}\n\n`,
|
|
321
|
+
]),
|
|
322
|
+
);
|
|
323
|
+
const client = createApiClient({
|
|
324
|
+
credentials: { kind: 'bearer', getToken: async () => 'session-token' },
|
|
325
|
+
fetch: fetch as never,
|
|
326
|
+
});
|
|
327
|
+
const events: unknown[] = [];
|
|
328
|
+
let done = false;
|
|
329
|
+
const streamed = client.notifications.stream?.(new AbortController().signal, (event) => {
|
|
330
|
+
events.push(event);
|
|
331
|
+
});
|
|
332
|
+
void streamed?.then(() => {
|
|
333
|
+
done = true;
|
|
334
|
+
});
|
|
335
|
+
await vi.advanceTimersByTimeAsync(1_999);
|
|
336
|
+
expect(events).toEqual([
|
|
337
|
+
{ kind: 'unread', unread: 4 },
|
|
338
|
+
{ kind: 'notification', item: ITEM },
|
|
339
|
+
]);
|
|
340
|
+
expect(done).toBe(false);
|
|
341
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
342
|
+
expect(done).toBe(true);
|
|
343
|
+
const [url, init] = callAt(fetch, 0);
|
|
344
|
+
expect(url).toBe('/api/v1/notifications/stream');
|
|
345
|
+
expect(init.headers.authorization).toBe('Bearer session-token');
|
|
346
|
+
expect(init.credentials).toBe('omit');
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it('keeps a CRLF split across chunks as one line break, and joins multi-line data', async () => {
|
|
350
|
+
const fetch = vi
|
|
351
|
+
.fn()
|
|
352
|
+
.mockResolvedValueOnce(
|
|
353
|
+
eventStream([
|
|
354
|
+
'retry: 0\r\n\r\nevent: unread\r',
|
|
355
|
+
'\ndata: {"unread":\r',
|
|
356
|
+
'\ndata: 7}\r\n\r\n',
|
|
357
|
+
]),
|
|
358
|
+
);
|
|
359
|
+
const events: unknown[] = [];
|
|
360
|
+
await cookieClient(fetch).notifications.stream?.(new AbortController().signal, (event) => {
|
|
361
|
+
events.push(event);
|
|
362
|
+
});
|
|
363
|
+
expect(events).toEqual([{ kind: 'unread', unread: 7 }]);
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
it('stops the stream at once when it is aborted, and fails on a refused one', async () => {
|
|
367
|
+
const fetch = vi
|
|
368
|
+
.fn()
|
|
369
|
+
.mockImplementationOnce(
|
|
370
|
+
async () =>
|
|
371
|
+
new Response(
|
|
372
|
+
new ReadableStream<Uint8Array>({
|
|
373
|
+
start(controller) {
|
|
374
|
+
controller.enqueue(new TextEncoder().encode('retry: 60000\n\n'));
|
|
375
|
+
},
|
|
376
|
+
}),
|
|
377
|
+
),
|
|
378
|
+
)
|
|
379
|
+
.mockResolvedValueOnce(
|
|
380
|
+
Response.json(
|
|
381
|
+
{ error: { code: 'UNAUTHENTICATED', message: 'Sign in', requestId: 'r1' } },
|
|
382
|
+
{ status: 401 },
|
|
383
|
+
),
|
|
384
|
+
);
|
|
385
|
+
const { notifications } = cookieClient(fetch);
|
|
386
|
+
const controller = new AbortController();
|
|
387
|
+
const streamed = notifications.stream?.(controller.signal, () => undefined);
|
|
388
|
+
controller.abort();
|
|
389
|
+
await expect(streamed).resolves.toBeUndefined();
|
|
390
|
+
await expect(
|
|
391
|
+
notifications.stream?.(new AbortController().signal, () => undefined),
|
|
392
|
+
).rejects.toMatchObject({ status: 401, code: 'UNAUTHENTICATED' });
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
it('turns push on with the server’s key and saves the subscription, and off by its endpoint', async () => {
|
|
396
|
+
const subscription = {
|
|
397
|
+
endpoint: 'https://push.example/device-1',
|
|
398
|
+
options: { applicationServerKey: null },
|
|
399
|
+
toJSON: () => ({ keys: { p256dh: 'p256', auth: 'auth' } }),
|
|
400
|
+
unsubscribe: vi.fn().mockResolvedValue(true),
|
|
401
|
+
};
|
|
402
|
+
const pushManager = {
|
|
403
|
+
getSubscription: vi.fn().mockResolvedValueOnce(null).mockResolvedValue(subscription),
|
|
404
|
+
subscribe: vi.fn().mockResolvedValue(subscription),
|
|
405
|
+
};
|
|
406
|
+
const serviceWorker = {
|
|
407
|
+
register: vi.fn(),
|
|
408
|
+
ready: Promise.resolve({ pushManager }),
|
|
409
|
+
getRegistration: vi.fn().mockResolvedValue({ pushManager }),
|
|
410
|
+
};
|
|
411
|
+
vi.stubGlobal('window', { top: null, self: null });
|
|
412
|
+
vi.stubGlobal('navigator', { userAgent: 'Firefox', serviceWorker });
|
|
413
|
+
vi.stubGlobal('PushManager', function PushManager() {});
|
|
414
|
+
vi.stubGlobal('Notification', { requestPermission: async () => 'granted' });
|
|
415
|
+
const fetch = vi
|
|
416
|
+
.fn()
|
|
417
|
+
.mockResolvedValueOnce(Response.json({ webPush: 'BEl6' }))
|
|
418
|
+
.mockResolvedValueOnce(new Response(null, { status: 204 }))
|
|
419
|
+
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
|
420
|
+
const { notifications } = cookieClient(fetch);
|
|
421
|
+
expect(notifications.push?.support()).toBe('supported');
|
|
422
|
+
expect(await notifications.push?.enable()).toBe('subscribed');
|
|
423
|
+
expect(serviceWorker.register).toHaveBeenCalledWith('/notifications-sw.js');
|
|
424
|
+
// The settings page asks, to offer turning it off.
|
|
425
|
+
expect(await notifications.push?.isSubscribed?.()).toBe(true);
|
|
426
|
+
await notifications.push?.disable();
|
|
427
|
+
expect(subscription.unsubscribe).toHaveBeenCalled();
|
|
428
|
+
const calls = fetch.mock.calls as [
|
|
429
|
+
string,
|
|
430
|
+
{ method: string; headers: Record<string, string>; body: string },
|
|
431
|
+
][];
|
|
432
|
+
expect(calls.map(([url, init]) => `${init.method} ${url}`)).toEqual([
|
|
433
|
+
'GET /api/v1/notifications/push/key',
|
|
434
|
+
'POST /api/v1/notifications/push/subscriptions',
|
|
435
|
+
'DELETE /api/v1/notifications/push/subscriptions',
|
|
436
|
+
]);
|
|
437
|
+
expect(JSON.parse(calls[1]?.[1].body ?? '')).toEqual({
|
|
438
|
+
kind: 'webpush',
|
|
439
|
+
endpoint: 'https://push.example/device-1',
|
|
440
|
+
keys: { p256dh: 'p256', auth: 'auth' },
|
|
441
|
+
});
|
|
442
|
+
expect(calls[2]?.[1].headers['content-type']).toBe('application/json');
|
|
443
|
+
expect(JSON.parse(calls[2]?.[1].body ?? '')).toEqual({
|
|
444
|
+
endpoint: 'https://push.example/device-1',
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it('says push is not set up when the server has no key, and leaves push out of the embedded app', async () => {
|
|
449
|
+
vi.stubGlobal('window', { top: null, self: null });
|
|
450
|
+
vi.stubGlobal('navigator', { userAgent: 'Firefox', serviceWorker: {} });
|
|
451
|
+
vi.stubGlobal('PushManager', function PushManager() {});
|
|
452
|
+
vi.stubGlobal('Notification', { requestPermission: async () => 'granted' });
|
|
453
|
+
const fetch = vi.fn().mockResolvedValueOnce(Response.json({ webPush: null }));
|
|
454
|
+
expect(await cookieClient(fetch).notifications.push?.enable()).toBe('unsupported');
|
|
455
|
+
const embedded = createApiClient({
|
|
456
|
+
credentials: { kind: 'bearer', getToken: async () => 't' },
|
|
457
|
+
fetch: vi.fn() as never,
|
|
458
|
+
});
|
|
459
|
+
expect(embedded.notifications.push).toBeUndefined();
|
|
460
|
+
});
|
|
461
|
+
});
|