create-signet-app 0.4.1 → 0.4.5

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.
Files changed (70) hide show
  1. package/package.json +6 -3
  2. package/src/desktop.ts +50 -0
  3. package/src/index.ts +116 -14
  4. package/template/public/offline.html +20 -0
  5. package/template/src/lib/i18n.test.ts +11 -0
  6. package/template/src/lib/i18n.ts +31 -0
  7. package/template/src/lib/pwa.ts +59 -0
  8. package/template/src/locales/en.json +18 -0
  9. package/template/src/main.tsx +4 -0
  10. package/template/src/routes/index.tsx +7 -8
  11. package/template/src/routes/login.tsx +4 -4
  12. package/template/src/sw.ts +79 -0
  13. package/template/tsconfig.app.json +1 -1
  14. package/template/vite.config.ts +18 -0
  15. package/template-cli/README.md +51 -0
  16. package/template-cli/_github/workflows/ci.yml +42 -0
  17. package/template-cli/_gitignore +9 -0
  18. package/template-cli/biome.json +49 -0
  19. package/template-cli/src/config.ts +23 -0
  20. package/template-cli/src/index.ts +104 -0
  21. package/template-cli/src/poll.ts +58 -0
  22. package/template-cli/src/ui.ts +16 -0
  23. package/template-cli/test/poll.test.ts +68 -0
  24. package/template-cli/tsconfig.json +15 -0
  25. package/template-cli/tsconfig.test.json +7 -0
  26. package/template-desktop/README.md +39 -0
  27. package/template-desktop/_github/workflows/ci.yml +48 -0
  28. package/template-desktop/_gitignore +6 -0
  29. package/template-desktop/biome.json +49 -0
  30. package/template-desktop/index.html +16 -0
  31. package/template-desktop/src/App.tsx +59 -0
  32. package/template-desktop/src/app.css +9 -0
  33. package/template-desktop/src/lib/auth.ts +102 -0
  34. package/template-desktop/src/lib/pkce.ts +21 -0
  35. package/template-desktop/src/main.tsx +16 -0
  36. package/template-desktop/src/pkce.test.ts +15 -0
  37. package/template-desktop/src-tauri/Cargo.toml +13 -0
  38. package/template-desktop/src-tauri/build.rs +3 -0
  39. package/template-desktop/src-tauri/capabilities/default.json +18 -0
  40. package/template-desktop/src-tauri/icons/128x128.png +0 -0
  41. package/template-desktop/src-tauri/icons/32x32.png +0 -0
  42. package/template-desktop/src-tauri/icons/icon.icns +0 -0
  43. package/template-desktop/src-tauri/icons/icon.ico +0 -0
  44. package/template-desktop/src-tauri/icons/icon.png +0 -0
  45. package/template-desktop/src-tauri/src/main.rs +124 -0
  46. package/template-desktop/src-tauri/tauri.conf.json +42 -0
  47. package/template-desktop/tsconfig.json +22 -0
  48. package/template-desktop/vite.config.ts +12 -0
  49. package/template-extension/.env.example +3 -0
  50. package/template-extension/README.md +64 -0
  51. package/template-extension/_github/workflows/ci.yml +22 -0
  52. package/template-extension/_gitignore +8 -0
  53. package/template-extension/biome.json +50 -0
  54. package/template-extension/options.html +13 -0
  55. package/template-extension/popup.html +13 -0
  56. package/template-extension/public/manifest.json +11 -0
  57. package/template-extension/public/theme-init.js +9 -0
  58. package/template-extension/src/app.css +9 -0
  59. package/template-extension/src/background.ts +23 -0
  60. package/template-extension/src/chrome.d.ts +21 -0
  61. package/template-extension/src/config.ts +11 -0
  62. package/template-extension/src/lib/api.ts +15 -0
  63. package/template-extension/src/lib/auth.ts +67 -0
  64. package/template-extension/src/lib/pkce.test.ts +13 -0
  65. package/template-extension/src/lib/pkce.ts +17 -0
  66. package/template-extension/src/lib/use-auth.ts +31 -0
  67. package/template-extension/src/options.tsx +56 -0
  68. package/template-extension/src/popup.tsx +44 -0
  69. package/template-extension/tsconfig.json +21 -0
  70. package/template-extension/vite.config.ts +23 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-signet-app",
3
- "version": "0.4.1",
3
+ "version": "0.4.5",
4
4
  "license": "MIT",
5
5
  "description": "Scaffold a Vite + React + Tailwind app wired to Signet.",
6
6
  "keywords": [
@@ -30,11 +30,14 @@
30
30
  "src",
31
31
  "template",
32
32
  "template-api",
33
- "template-full"
33
+ "template-full",
34
+ "template-cli",
35
+ "template-extension",
36
+ "template-desktop"
34
37
  ],
35
38
  "scripts": {
36
39
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
37
- "test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts"
40
+ "test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts"
38
41
  },
39
42
  "devDependencies": {
40
43
  "@types/bun": "^1.4.2",
package/src/desktop.ts ADDED
@@ -0,0 +1,50 @@
1
+ /** The desktop template (Tauri v2): its package.json and the app id derived from the name. */
2
+
3
+ /**
4
+ * Lowercase alphanumerics only, starting with a letter: valid in a reverse-domain
5
+ * identifier segment and as a Cargo crate name. "My App!" -> "myapp".
6
+ */
7
+ export function appId(name: string): string {
8
+ const id = name.toLowerCase().replace(/[^a-z0-9]/g, "")
9
+ return /^[a-z]/.test(id) ? id : `app${id}`
10
+ }
11
+
12
+ export const DESKTOP_PKG = {
13
+ scripts: {
14
+ dev: "vite",
15
+ build: "tsc --noEmit && vite build",
16
+ preview: "vite preview",
17
+ tauri: "tauri",
18
+ lint: "biome check .",
19
+ format: "biome check --write .",
20
+ typecheck: "tsc --noEmit",
21
+ test: "bun test src",
22
+ },
23
+ dependencies: {
24
+ "@dapplelight/signet-lib": "^0.4.1",
25
+ "@dapplelight/signet-tokens": "^0.4.0",
26
+ "@dapplelight/signet-ui": "^0.3.0",
27
+ "@tauri-apps/api": "^2.0.0",
28
+ "@tauri-apps/plugin-opener": "^2.0.0",
29
+ "@tauri-apps/plugin-store": "^2.0.0",
30
+ "class-variance-authority": "^0.7.1",
31
+ clsx: "^2.1.1",
32
+ "lucide-react": "^1.47.0",
33
+ react: "^19.3.0",
34
+ "react-dom": "^19.3.0",
35
+ "tailwind-merge": "^3.7.0",
36
+ },
37
+ devDependencies: {
38
+ "@biomejs/biome": "^2.5.14",
39
+ "@tailwindcss/vite": "^4.3.3",
40
+ "@tauri-apps/cli": "^2.0.0",
41
+ "@types/bun": "^1.4.2",
42
+ "@types/node": "^26.6.2",
43
+ "@types/react": "^19.3.0",
44
+ "@types/react-dom": "^19.3.0",
45
+ "@vitejs/plugin-react": "^6.1.1",
46
+ tailwindcss: "^4.3.3",
47
+ typescript: "^7.0.2",
48
+ vite: "^8.3.0",
49
+ },
50
+ }
package/src/index.ts CHANGED
@@ -14,10 +14,11 @@ import { existsSync } from "node:fs"
14
14
  import { cp, mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises"
15
15
  import { basename, join, resolve } from "node:path"
16
16
  import { createInterface } from "node:readline/promises"
17
+ import { appId, DESKTOP_PKG } from "./desktop.js"
17
18
 
18
19
  const THEMES = ["editorial", "cinematic", "finance"] as const
19
20
  type Theme = (typeof THEMES)[number]
20
- const TEMPLATES = ["web", "api", "full"] as const
21
+ const TEMPLATES = ["web", "api", "full", "cli", "extension", "desktop"] as const
21
22
  type Template = (typeof TEMPLATES)[number]
22
23
  const TARGETS = ["cloudflare", "bun", "node", "vercel"] as const
23
24
  type Target = (typeof TARGETS)[number]
@@ -73,12 +74,12 @@ function applyPm(ci: string, pm: Pm): string {
73
74
  " - uses: oven-sh/setup-bun@v2",
74
75
  ].join("\n")
75
76
  return ci
76
- .replace(/^ {6}- uses: oven-sh\/setup-bun@v2$/m, setup)
77
+ .replace(/^ {6}- uses: oven-sh\/setup-bun@v2$/gm, setup)
77
78
  .replace(
78
79
  /Commit bun\.lock: --frozen-lockfile fails/,
79
80
  `Commit ${p.lock}: a frozen install fails`,
80
81
  )
81
- .replace("bun install --frozen-lockfile", p.ci)
82
+ .replaceAll("bun install --frozen-lockfile", p.ci)
82
83
  .replaceAll("bun run ", `${p.run} `)
83
84
  .replaceAll("bunx ", `${p.x} `)
84
85
  }
@@ -87,6 +88,9 @@ const TEMPLATE_DIRS: Record<Template, string> = {
87
88
  web: "template",
88
89
  api: "template-api",
89
90
  full: "template-full",
91
+ cli: "template-cli",
92
+ extension: "template-extension",
93
+ desktop: "template-desktop",
90
94
  }
91
95
 
92
96
  // The api template: a Hono Worker with Signet's request id, error envelope,
@@ -158,7 +162,7 @@ const DEPS = {
158
162
  // app installs from npm and works anywhere. Inside this monorepo bun still
159
163
  // links the local copies, because the range matches the workspace version.
160
164
  "@dapplelight/signet-lib": "^0.4.0",
161
- "@dapplelight/signet-tokens": "^0.3.0",
165
+ "@dapplelight/signet-tokens": "^0.4.0",
162
166
  "@dapplelight/signet-ui": "^0.3.0",
163
167
  "@tanstack/react-query": "^5.103.2",
164
168
  "@tanstack/react-router": "^1.170.39",
@@ -171,6 +175,20 @@ const DEPS = {
171
175
  "tailwind-merge": "^3.7.0",
172
176
  }
173
177
 
178
+ // The web template's i18n: src/lib/i18n.ts + src/locales/*.json.
179
+ const I18N_DEPS = {
180
+ i18next: "^26.4.2",
181
+ "react-i18next": "^17.0.15",
182
+ }
183
+
184
+ // The web template's PWA: vite-plugin-pwa builds src/sw.ts with Workbox.
185
+ const PWA_DEV_DEPS = {
186
+ "vite-plugin-pwa": "^1.3.0",
187
+ "workbox-precaching": "^7.4.0",
188
+ "workbox-routing": "^7.4.0",
189
+ "workbox-window": "^7.4.0",
190
+ }
191
+
174
192
  const DEV_DEPS = {
175
193
  "@biomejs/biome": "^2.5.14",
176
194
  "@tailwindcss/vite": "^4.3.3",
@@ -203,6 +221,38 @@ const FULL_DEV_DEPS = {
203
221
  "drizzle-kit": "^0.31.11",
204
222
  }
205
223
 
224
+ // The cli template: a Bun CLI that signs in by device code, compiled to one binary.
225
+ const CLI_PKG = {
226
+ scripts: {
227
+ dev: "bun src/index.ts",
228
+ build: "bun build --compile src/index.ts --outfile dist/__APP_NAME__",
229
+ lint: "biome check .",
230
+ format: "biome check --write .",
231
+ typecheck: "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
232
+ test: "bun test",
233
+ },
234
+ dependencies: {
235
+ "@dapplelight/signet-lib": "^0.4.0",
236
+ "@dapplelight/signet-tokens": "^0.4.0",
237
+ },
238
+ devDependencies: API_DEV_DEPS,
239
+ }
240
+
241
+ // The extension template: the web app's deps without the router, query and
242
+ // toasts, built by plain Vite into popup, options and service worker.
243
+ const EXT_OMIT = ["@tanstack/react-query", "@tanstack/react-router", "sonner"]
244
+ const EXT_DEV_OMIT = ["@tanstack/router-plugin"]
245
+ const omit = (o: Record<string, string>, keys: string[]) =>
246
+ Object.fromEntries(Object.entries(o).filter(([k]) => !keys.includes(k)))
247
+ const EXT_SCRIPTS = {
248
+ dev: "vite build --watch",
249
+ build: "tsc --noEmit && vite build",
250
+ lint: "biome check .",
251
+ format: "biome check --write .",
252
+ typecheck: "tsc --noEmit",
253
+ test: "bun test",
254
+ }
255
+
206
256
  const FULL_SCRIPTS = {
207
257
  // Both halves: the API (restarting on change) and Vite, which proxies /api to it.
208
258
  dev: "bun scripts/dev.ts",
@@ -264,13 +314,20 @@ function parseArgs(argv: string[]) {
264
314
  create-signet-app <directory> [options]
265
315
 
266
316
  Options:
267
- --template <kind> web | api | full (default: web)
317
+ --template <kind> web | api | full | cli | extension | desktop (default: web)
268
318
  web: Vite + React + Signet UI
269
319
  api: Hono Worker with the error envelope, request ids,
270
320
  validation and Durable Object rate limiting
271
321
  full: web + API in one project, typed client between
272
322
  them, SQLite with migrations, phone sign-in,
273
323
  account, inbox, privacy, billing and admin
324
+ cli: Bun CLI compiled to one binary; login by device
325
+ code, logout, whoami
326
+ extension: Chrome MV3 extension: popup, options page and
327
+ service worker, signed in over PKCE with
328
+ chrome.identity (plain Vite, no extension plugin)
329
+ desktop: Tauri v2 desktop + menu-bar app, browser sign-in
330
+ (PKCE, loopback redirect), CI on macOS/Windows/Linux
274
331
  --target <runtime> ${TARGETS.join(" | ")} (default: cloudflare; api only)
275
332
  cloudflare: Worker entry + wrangler.jsonc
276
333
  bun: Bun.serve entry + Dockerfile
@@ -288,6 +345,7 @@ Examples:
288
345
  bun create-signet-app my-api --template api
289
346
  bun create-signet-app my-api --template api --target bun
290
347
  bun create-signet-app my-app --template full --theme finance
348
+ bun create-signet-app my-cli --template cli
291
349
  npm create signet-app my-app -- --template full --pm npm
292
350
  `)
293
351
  process.exit(0)
@@ -300,7 +358,10 @@ Examples:
300
358
 
301
359
  if (!name) throw new Error("Missing target directory.\nUsage: create-signet-app <directory>")
302
360
  if (target && template !== "api") throw new Error("--target applies to --template api only.")
303
- if (mcp !== undefined && template === "web")
361
+ if (
362
+ mcp !== undefined &&
363
+ (template === "web" || template === "cli" || template === "extension" || template === "desktop")
364
+ )
304
365
  throw new Error("--mcp / --no-mcp apply to --template api and full only.")
305
366
  if (theme !== "editorial" && template === "api")
306
367
  throw new Error("--theme applies to --template web and full only.")
@@ -348,7 +409,7 @@ async function main() {
348
409
  throw new Error(`${dest} already exists and is not empty.`)
349
410
  }
350
411
 
351
- const mcp = template !== "web" && (flags.mcp ?? (await askMcp()))
412
+ const mcp = (template === "api" || template === "full") && (flags.mcp ?? (await askMcp()))
352
413
  const templateDir = resolve(import.meta.dirname, `../${TEMPLATE_DIRS[template]}`)
353
414
  await mkdir(dest, { recursive: true })
354
415
  const targetsDir = join(templateDir, "_targets")
@@ -362,8 +423,11 @@ async function main() {
362
423
  if (mcp && existsSync(mcpDir)) await cp(mcpDir, dest, { recursive: true })
363
424
  const mcpFiles: Record<Template, string[]> = {
364
425
  web: [],
426
+ extension: [],
427
+ desktop: [],
365
428
  api: ["src/app.ts", "src/env.ts"],
366
429
  full: ["api/app.ts", "api/env.ts"],
430
+ cli: [],
367
431
  }
368
432
  for (const f of mcpFiles[template]) {
369
433
  const path = join(dest, f)
@@ -391,6 +455,7 @@ async function main() {
391
455
 
392
456
  await substitute(dest, {
393
457
  __APP_NAME__: appName,
458
+ __APP_ID__: appId(appName),
394
459
  __THEME__: theme,
395
460
  __PM_INSTALL__: PM[pm].install,
396
461
  __PM_RUN__: PM[pm].run,
@@ -442,35 +507,72 @@ async function main() {
442
507
  ? { ...API_DEPS, ...(mcp ? MCP_DEPS : {}) }
443
508
  : template === "full"
444
509
  ? { ...FULL_DEPS, ...(mcp ? MCP_DEPS : {}) }
445
- : DEPS,
510
+ : { ...DEPS, ...I18N_DEPS },
446
511
  devDependencies:
447
512
  template === "api"
448
513
  ? { ...API_DEV_DEPS, ...API_TARGETS[target].devDeps }
449
514
  : template === "full"
450
515
  ? FULL_DEV_DEPS
451
- : DEV_DEPS,
516
+ : { ...DEV_DEPS, ...PWA_DEV_DEPS },
452
517
  ...(template === "api" && API_TARGETS[target].engines
453
518
  ? { engines: API_TARGETS[target].engines }
454
519
  : {}),
455
520
  }
521
+ if (template === "extension")
522
+ Object.assign(pkg, {
523
+ scripts: EXT_SCRIPTS,
524
+ // ^0.4.1: chromeStorage().watch, so the pages see the service worker sign in.
525
+ dependencies: { ...omit(DEPS, EXT_OMIT), "@dapplelight/signet-lib": "^0.4.1" },
526
+ devDependencies: omit(DEV_DEPS, EXT_DEV_OMIT),
527
+ })
528
+ const final =
529
+ template === "cli"
530
+ ? JSON.parse(JSON.stringify(CLI_PKG).replaceAll("__APP_NAME__", appName))
531
+ : pkg
456
532
  await writeFile(
457
533
  join(dest, "package.json"),
458
- `${JSON.stringify({ name: appName, private: true, version: "0.1.0", type: "module", ...pkg }, null, 2)}\n`,
534
+ `${JSON.stringify({ name: appName, private: true, version: "0.1.0", type: "module", ...(template === "desktop" ? DESKTOP_PKG : final) }, null, 2)}\n`,
459
535
  )
460
536
 
461
537
  const { install, run } = PM[pm]
462
538
  const steps = `cd ${name}\n ${install}\n ${run} dev`
463
539
  console.log(
464
- template === "api"
540
+ template === "cli"
465
541
  ? `
542
+ Created ${appName}, a CLI that compiles to one binary.
543
+
544
+ ${steps.replace(`${run} dev`, `${run} build`)}
545
+
546
+ Then ./dist/${appName} login. README.md covers the server side.
547
+ `
548
+ : template === "extension"
549
+ ? `
550
+ Created ${appName}, a Chrome extension with the ${theme} theme.
551
+
552
+ ${steps.replace(`${run} dev`, `${run} build`)}
553
+
554
+ Then load dist/ at chrome://extensions (Developer mode, Load unpacked), and
555
+ register its redirect URI on your server. README.md has both steps.
556
+ `
557
+ : template === "api"
558
+ ? `
466
559
  Created ${appName}, an API for ${target}${mcp ? ", with MCP at /mcp (MCP=off turns it off)" : ""}.
467
560
 
468
561
  ${steps}
469
562
 
470
563
  ${API_NEXT_STEPS[target]}
471
564
  `
472
- : template === "full"
473
- ? `
565
+ : template === "desktop"
566
+ ? `
567
+ Created ${appName}, a Tauri desktop + menu-bar app with the ${theme} theme.
568
+
569
+ ${steps.replace(`${run} dev`, `${PM[pm].x} tauri dev`)}
570
+
571
+ Needs Rust and Tauri's system dependencies. README.md covers sign-in (register
572
+ the client on signet-server) and the identifier in src-tauri/tauri.conf.json.
573
+ `
574
+ : template === "full"
575
+ ? `
474
576
  Created ${appName}: web app + API with the ${theme} theme${mcp ? ", MCP at /mcp" : ""}.
475
577
 
476
578
  ${steps}
@@ -480,7 +582,7 @@ async function main() {
480
582
  to see /admin. README.md walks through the first day. The API runs on Bun,
481
583
  whichever package manager installs it.
482
584
  `
483
- : `
585
+ : `
484
586
  Created ${appName} with the ${theme} theme.
485
587
 
486
588
  ${steps}
@@ -0,0 +1,20 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Offline · __APP_NAME__</title>
7
+ <style>
8
+ :root { color-scheme: light dark; font-family: system-ui, sans-serif; }
9
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; text-align: center; padding: 24px; }
10
+ button { font: inherit; padding: 8px 16px; border-radius: 8px; border: 1px solid currentColor; background: none; color: inherit; cursor: pointer; }
11
+ </style>
12
+ </head>
13
+ <body>
14
+ <main>
15
+ <h1>You're offline</h1>
16
+ <p>__APP_NAME__ will load again when you're back online.</p>
17
+ <button type="button" onclick="location.reload()">Try again</button>
18
+ </main>
19
+ </body>
20
+ </html>
@@ -0,0 +1,11 @@
1
+ import { expect, test } from "bun:test"
2
+ import en from "../locales/en.json"
3
+ import i18n, { pseudo } from "./i18n"
4
+
5
+ test("t() reads src/locales/en.json", () => {
6
+ expect(i18n.t("login.title")).toBe(en.login.title)
7
+ })
8
+
9
+ test("pseudo accents letters and pads ~35%", () => {
10
+ expect(pseudo("Sign in")).toBe("[Sîgñ îñ~~~]")
11
+ })
@@ -0,0 +1,31 @@
1
+ // Every string the app shows lives in src/locales/<language>.json; components
2
+ // call t("…") from useTranslation(). A new language = a new file + an entry in
3
+ // `resources`. The browser's language picks the file, English is the fallback.
4
+ // Money and dates: Intl via @dapplelight/signet-lib/format, not here.
5
+ import i18n from "i18next"
6
+ import { initReactI18next } from "react-i18next"
7
+ import en from "../locales/en.json"
8
+
9
+ // Pseudo-locale for review screenshots, dev only: open the app with ?pseudo=1
10
+ // and every string comes out accented and ~35% longer in brackets, so text that
11
+ // skipped t() (plain letters) and text that gets cut off both show at a glance.
12
+ const PLAIN = "aeiouycnAEIOUYCN"
13
+ const ACCENTED = [..."åéîöüýçñÅÉÎÖÜÝÇÑ"]
14
+ export const pseudo = (s: string) =>
15
+ `[${s.replace(/[a-zA-Z]/g, (c) => ACCENTED[PLAIN.indexOf(c)] ?? c)}${"~".repeat(Math.ceil(s.length * 0.35))}]`
16
+
17
+ const usePseudo =
18
+ import.meta.env.DEV && new URLSearchParams(globalThis.location?.search).has("pseudo")
19
+
20
+ i18n
21
+ .use({ type: "postProcessor", name: "pseudo", process: (v: string) => pseudo(v) })
22
+ .use(initReactI18next)
23
+ .init({
24
+ resources: { en: { translation: en } },
25
+ lng: globalThis.navigator?.language?.split("-")[0] ?? "en",
26
+ fallbackLng: "en",
27
+ interpolation: { escapeValue: false },
28
+ ...(usePseudo ? { postProcess: ["pseudo"] } : {}),
29
+ })
30
+
31
+ export default i18n
@@ -0,0 +1,59 @@
1
+ // Keeps the installed app on the latest deploy. An installed PWA that stays
2
+ // open rarely re-checks its service worker (browsers do it on navigation), so:
3
+ // - check for an update when the app returns to the foreground, and every 30 min;
4
+ // - when one is waiting, show a "Reload" toast, and apply it by itself once every
5
+ // tab of the app is in the background, so nothing reloads under someone mid-task.
6
+
7
+ import { registerSW } from "virtual:pwa-register"
8
+ import { toast } from "sonner"
9
+ import i18n from "./i18n"
10
+
11
+ const CHECK_EVERY_MS = 30 * 60 * 1000
12
+
13
+ type Doc = Pick<Document, "visibilityState" | "addEventListener" | "removeEventListener">
14
+
15
+ export function wireUpdateChecks(
16
+ registration: { update: () => Promise<unknown> },
17
+ doc: Doc = document,
18
+ everyMs = CHECK_EVERY_MS,
19
+ ): () => void {
20
+ // A failed check (offline) is harmless; the next one retries.
21
+ const check = () => void registration.update().catch(() => {})
22
+ const onVisible = () => doc.visibilityState === "visible" && check()
23
+ doc.addEventListener("visibilitychange", onVisible)
24
+ const timer = setInterval(check, everyMs)
25
+ return () => {
26
+ doc.removeEventListener("visibilitychange", onVisible)
27
+ clearInterval(timer)
28
+ }
29
+ }
30
+
31
+ /** Run `apply` each time the page is hidden (now, if it already is). */
32
+ export function whenHidden(apply: () => void, doc: Doc = document): () => void {
33
+ const maybe = () => {
34
+ if (doc.visibilityState === "hidden") apply()
35
+ }
36
+ maybe()
37
+ doc.addEventListener("visibilitychange", maybe)
38
+ return () => doc.removeEventListener("visibilitychange", maybe)
39
+ }
40
+
41
+ export function registerPwa(): void {
42
+ // `bun run dev` has no service worker; only built and previewed apps do.
43
+ if (!import.meta.env.PROD || !("serviceWorker" in navigator)) return
44
+ let reg: ServiceWorkerRegistration | undefined
45
+ const update = registerSW({
46
+ onRegisteredSW(_url, registration) {
47
+ reg = registration
48
+ if (registration) wireUpdateChecks(registration)
49
+ },
50
+ onNeedRefresh() {
51
+ toast(i18n.t("update.available"), {
52
+ duration: Number.POSITIVE_INFINITY,
53
+ action: { label: i18n.t("update.reload"), onClick: () => void update(true) },
54
+ })
55
+ // The worker applies it only if every tab is hidden; the last one to hide does it.
56
+ whenHidden(() => reg?.waiting?.postMessage({ type: "SKIP_WAITING_IF_HIDDEN" }))
57
+ },
58
+ })
59
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "home": {
3
+ "title": "Running on the __THEME__ theme",
4
+ "showToast": "Show a toast",
5
+ "saved": "Saved",
6
+ "outline": "Outline",
7
+ "badge": "Badge",
8
+ "themeHint": "Swap the theme import in src/app.css and everything here reshapes: colour, radius, type scale and motion. No component changes."
9
+ },
10
+ "login": {
11
+ "title": "Sign in",
12
+ "body": "Your session has ended or you are not signed in. Replace this page with your sign-in flow."
13
+ },
14
+ "update": {
15
+ "available": "A new version is available.",
16
+ "reload": "Reload"
17
+ }
18
+ }
@@ -5,6 +5,8 @@ import { RouterProvider } from "@tanstack/react-router"
5
5
  import { StrictMode } from "react"
6
6
  import { createRoot } from "react-dom/client"
7
7
  import { Toaster } from "./components/toaster"
8
+ import "./lib/i18n"
9
+ import { registerPwa } from "./lib/pwa"
8
10
  import { createAppRouter } from "./router"
9
11
  import "./app.css"
10
12
 
@@ -21,6 +23,8 @@ onAuthErrorRedirect(queryClient, () => {
21
23
  window.location.assign(router.buildLocation({ to: "/login" }).href)
22
24
  })
23
25
 
26
+ registerPwa()
27
+
24
28
  const rootElement = document.getElementById("root")
25
29
  if (!rootElement) throw new Error("Root element #root not found in index.html")
26
30
 
@@ -2,6 +2,7 @@ import { Badge } from "@dapplelight/signet-ui/components/badge"
2
2
  import { Button } from "@dapplelight/signet-ui/components/button"
3
3
  import { Card, CardContent, CardHeader, CardTitle } from "@dapplelight/signet-ui/components/card"
4
4
  import { createFileRoute } from "@tanstack/react-router"
5
+ import { useTranslation } from "react-i18next"
5
6
  import { toast } from "sonner"
6
7
 
7
8
  export const Route = createFileRoute("/")({
@@ -9,19 +10,17 @@ export const Route = createFileRoute("/")({
9
10
  })
10
11
 
11
12
  function Home() {
13
+ const { t } = useTranslation()
12
14
  return (
13
15
  <Card>
14
16
  <CardHeader>
15
- <CardTitle>Running on the __THEME__ theme</CardTitle>
17
+ <CardTitle>{t("home.title")}</CardTitle>
16
18
  </CardHeader>
17
19
  <CardContent className="flex flex-wrap items-center gap-3">
18
- <Button onClick={() => toast.success("Saved")}>Show a toast</Button>
19
- <Button variant="outline">Outline</Button>
20
- <Badge>Badge</Badge>
21
- <p className="w-full text-sm text-muted-foreground">
22
- Swap the theme import in <code>src/app.css</code> and everything here reshapes — colour,
23
- radius, type scale and motion. No component changes.
24
- </p>
20
+ <Button onClick={() => toast.success(t("home.saved"))}>{t("home.showToast")}</Button>
21
+ <Button variant="outline">{t("home.outline")}</Button>
22
+ <Badge>{t("home.badge")}</Badge>
23
+ <p className="w-full text-sm text-muted-foreground">{t("home.themeHint")}</p>
25
24
  </CardContent>
26
25
  </Card>
27
26
  )
@@ -1,5 +1,6 @@
1
1
  import { Card, CardContent, CardHeader, CardTitle } from "@dapplelight/signet-ui/components/card"
2
2
  import { createFileRoute } from "@tanstack/react-router"
3
+ import { useTranslation } from "react-i18next"
3
4
 
4
5
  // Where the 401 handler in main.tsx sends the user. A placeholder: wire it to
5
6
  // your own auth (a form posting to your API, an OAuth button) — the template
@@ -9,15 +10,14 @@ export const Route = createFileRoute("/login")({
9
10
  })
10
11
 
11
12
  function Login() {
13
+ const { t } = useTranslation()
12
14
  return (
13
15
  <Card className="mx-auto max-w-sm">
14
16
  <CardHeader>
15
- <CardTitle>Sign in</CardTitle>
17
+ <CardTitle>{t("login.title")}</CardTitle>
16
18
  </CardHeader>
17
19
  <CardContent>
18
- <p className="text-sm text-muted-foreground">
19
- Your session has ended or you are not signed in. Replace this page with your sign-in flow.
20
- </p>
20
+ <p className="text-sm text-muted-foreground">{t("login.body")}</p>
21
21
  </CardContent>
22
22
  </Card>
23
23
  )
@@ -0,0 +1,79 @@
1
+ /// <reference lib="webworker" />
2
+ // The service worker vite-plugin-pwa builds from this file (injectManifest).
3
+ // It precaches the built app, serves public/offline.html for a page load with
4
+ // no network, applies an update when the "Reload" toast is tapped, and shows
5
+ // web push notifications. Authenticated API responses are never cached here:
6
+ // /api/* always goes to the network, so nothing private outlives sign-out.
7
+ import { cleanupOutdatedCaches, precacheAndRoute } from "workbox-precaching"
8
+ import { NavigationRoute, registerRoute } from "workbox-routing"
9
+
10
+ declare const self: ServiceWorkerGlobalScope
11
+
12
+ precacheAndRoute(self.__WB_MANIFEST)
13
+ cleanupOutdatedCaches()
14
+
15
+ const OFFLINE_CACHE = "offline-fallback"
16
+
17
+ registerRoute(
18
+ new NavigationRoute(
19
+ async ({ request }) => {
20
+ try {
21
+ return await fetch(request)
22
+ } catch {
23
+ return (
24
+ (await caches.match("/offline.html", { cacheName: OFFLINE_CACHE })) ?? Response.error()
25
+ )
26
+ }
27
+ },
28
+ // OAuth callbacks and API navigations never get the app shell or the offline page.
29
+ { denylist: [/^\/api\//] },
30
+ ),
31
+ )
32
+
33
+ self.addEventListener("install", (event) => {
34
+ event.waitUntil(caches.open(OFFLINE_CACHE).then((c) => c.add("/offline.html")))
35
+ })
36
+
37
+ // registerType "prompt": the page posts SKIP_WAITING when the person taps Reload,
38
+ // and SKIP_WAITING_IF_HIDDEN when a tab goes to the background. Activating
39
+ // reloads every open tab, so the second applies only when no window is visible.
40
+ self.addEventListener("message", (event) => {
41
+ const type = event.data?.type
42
+ if (type === "SKIP_WAITING") self.skipWaiting()
43
+ if (type === "SKIP_WAITING_IF_HIDDEN")
44
+ event.waitUntil(
45
+ self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((all) => {
46
+ if (all.every((c) => c.visibilityState === "hidden")) return self.skipWaiting()
47
+ }),
48
+ )
49
+ })
50
+ self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()))
51
+
52
+ // Web push: { title, message, url, tag } as JSON; plain text also works.
53
+ self.addEventListener("push", (event) => {
54
+ let p: { title?: string; message?: string; url?: string; tag?: string } = {}
55
+ try {
56
+ p = event.data?.json() ?? {}
57
+ } catch {
58
+ p = { message: event.data?.text() ?? "" }
59
+ }
60
+ event.waitUntil(
61
+ self.registration.showNotification(p.title ?? "__APP_NAME__", {
62
+ body: p.message ?? "",
63
+ tag: p.tag,
64
+ data: { url: p.url ?? "/" },
65
+ }),
66
+ )
67
+ })
68
+
69
+ self.addEventListener("notificationclick", (event) => {
70
+ event.notification.close()
71
+ const url = (event.notification.data?.url as string | undefined) ?? "/"
72
+ event.waitUntil(
73
+ self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((clients) => {
74
+ const open = clients.find((c) => "focus" in c) as WindowClient | undefined
75
+ if (open) return open.navigate(url).then(() => open.focus())
76
+ return self.clients.openWindow(url)
77
+ }),
78
+ )
79
+ })
@@ -19,7 +19,7 @@
19
19
  "paths": {
20
20
  "@/*": ["./src/*"]
21
21
  },
22
- "types": ["vite/client"]
22
+ "types": ["vite/client", "vite-plugin-pwa/client"]
23
23
  },
24
24
  "include": ["src"],
25
25
  "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"]