pi-pocket 0.0.0-stage → 0.26.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.
Files changed (369) hide show
  1. package/AGENTS.md +14 -0
  2. package/CONTRIBUTING.md +22 -0
  3. package/LICENSE +21 -0
  4. package/README.md +119 -2
  5. package/SECURITY.md +23 -0
  6. package/bin/pi-pocket.js +27 -0
  7. package/bin/strip-types.js +62 -0
  8. package/contrib/systemd/pi-pocket@.service +38 -0
  9. package/docs/architecture.md +306 -0
  10. package/docs/customizing.md +134 -0
  11. package/docs/design/design-mode.md +108 -0
  12. package/docs/design/docs-site.md +183 -0
  13. package/docs/design/notes-a.md +106 -0
  14. package/docs/design/notes-b.md +123 -0
  15. package/docs/design/notes-c.md +92 -0
  16. package/docs/design/notes-d.md +78 -0
  17. package/docs/design/rate-limit-wait.md +204 -0
  18. package/docs/design/release-notes-design.md +46 -0
  19. package/docs/design/theming.md +256 -0
  20. package/docs/docker.md +93 -0
  21. package/docs/examples/clock.ts +100 -0
  22. package/docs/examples/my-words.ts +39 -0
  23. package/docs/examples/no-force-push.ts +38 -0
  24. package/docs/examples/read-page.ts +86 -0
  25. package/docs/examples/server-status.js +106 -0
  26. package/docs/examples/server-status.ts +35 -0
  27. package/docs/extensions/app.md +37 -0
  28. package/docs/extensions/browser-modules.md +228 -0
  29. package/docs/extensions/built-in.md +23 -0
  30. package/docs/extensions/cleanups.md +33 -0
  31. package/docs/extensions/commands.md +85 -0
  32. package/docs/extensions/events.md +47 -0
  33. package/docs/extensions/first-extension.md +109 -0
  34. package/docs/extensions/hooks.md +52 -0
  35. package/docs/extensions/host.md +59 -0
  36. package/docs/extensions/linked-sessions.md +78 -0
  37. package/docs/extensions/modules.md +50 -0
  38. package/docs/extensions/people-values.md +186 -0
  39. package/docs/extensions/policies/api-stability.md +288 -0
  40. package/docs/extensions/policies/core-or-extension.md +135 -0
  41. package/docs/extensions/policies/gallery-review.md +154 -0
  42. package/docs/extensions/policies/index.md +24 -0
  43. package/docs/extensions/policies/security-model.md +183 -0
  44. package/docs/extensions/prompt-sections.md +39 -0
  45. package/docs/extensions/public-pages.md +91 -0
  46. package/docs/extensions/publishing.md +73 -0
  47. package/docs/extensions/reference/api-versions.md +87 -0
  48. package/docs/extensions/reference/command-context.md +147 -0
  49. package/docs/extensions/reference/gallery-entry.md +351 -0
  50. package/docs/extensions/reference/glossary.md +326 -0
  51. package/docs/extensions/reference/host.md +692 -0
  52. package/docs/extensions/reference/limits.md +184 -0
  53. package/docs/extensions/reference/names.md +65 -0
  54. package/docs/extensions/reference/pocket.md +1361 -0
  55. package/docs/extensions/reference/theme-surface.md +257 -0
  56. package/docs/extensions/reference/types.md +140 -0
  57. package/docs/extensions/reference/web.md +539 -0
  58. package/docs/extensions/routes.md +106 -0
  59. package/docs/extensions/services-settings.md +118 -0
  60. package/docs/extensions/testing.md +98 -0
  61. package/docs/extensions/themes.md +208 -0
  62. package/docs/extensions/tool-calls.md +42 -0
  63. package/docs/extensions/tools.md +96 -0
  64. package/docs/extensions.md +114 -0
  65. package/docs/features.md +128 -0
  66. package/docs/index.md +56 -0
  67. package/docs/map.md +288 -0
  68. package/docs/release-notes.md +84 -0
  69. package/docs/self-editing.md +84 -0
  70. package/docs/showcase-0.12.1.png +0 -0
  71. package/docs/systemd.md +113 -0
  72. package/npm-shrinkwrap.json +3162 -0
  73. package/package.json +83 -5
  74. package/src/launcher/access.ts +354 -0
  75. package/src/launcher/main.ts +918 -0
  76. package/src/launcher/options.ts +101 -0
  77. package/src/launcher/term.ts +227 -0
  78. package/src/server/alerts.ts +278 -0
  79. package/src/server/anthropic-shape.ts +133 -0
  80. package/src/server/app-events.ts +114 -0
  81. package/src/server/app.ts +3627 -0
  82. package/src/server/artifact-state.ts +153 -0
  83. package/src/server/attribution.ts +278 -0
  84. package/src/server/auth.ts +193 -0
  85. package/src/server/background.ts +1524 -0
  86. package/src/server/branches.ts +243 -0
  87. package/src/server/browser/cdp.ts +275 -0
  88. package/src/server/browser/discovery.ts +203 -0
  89. package/src/server/browser/keys.ts +135 -0
  90. package/src/server/browser/local-servers.ts +124 -0
  91. package/src/server/browser/page-scripts.ts +289 -0
  92. package/src/server/browser/page.ts +1458 -0
  93. package/src/server/browser/urls.ts +140 -0
  94. package/src/server/browser/viewport.ts +73 -0
  95. package/src/server/browser.ts +434 -0
  96. package/src/server/cache-keeper.ts +605 -0
  97. package/src/server/changes.ts +508 -0
  98. package/src/server/collab.ts +573 -0
  99. package/src/server/commands.ts +2322 -0
  100. package/src/server/compaction.ts +108 -0
  101. package/src/server/config.ts +515 -0
  102. package/src/server/design/bundle.ts +65 -0
  103. package/src/server/design/export.ts +118 -0
  104. package/src/server/design/files.ts +49 -0
  105. package/src/server/design/guide.ts +56 -0
  106. package/src/server/design/index.ts +232 -0
  107. package/src/server/design/pptx.ts +304 -0
  108. package/src/server/design/render.ts +593 -0
  109. package/src/server/design/system.ts +248 -0
  110. package/src/server/docs.ts +922 -0
  111. package/src/server/entry-format.ts +66 -0
  112. package/src/server/errors.ts +33 -0
  113. package/src/server/export.ts +202 -0
  114. package/src/server/extension-commands.ts +497 -0
  115. package/src/server/extension-document-compat.ts +32 -0
  116. package/src/server/extension-document-imports.ts +114 -0
  117. package/src/server/extension-points.ts +283 -0
  118. package/src/server/extension-request.ts +132 -0
  119. package/src/server/extension-settings.ts +301 -0
  120. package/src/server/extension-web.ts +1455 -0
  121. package/src/server/extensions/agent-teams.js +29 -0
  122. package/src/server/extensions/agent-teams.ts +206 -0
  123. package/src/server/extensions/anthropic-subscription.ts +18 -0
  124. package/src/server/extensions/artifacts.ts +603 -0
  125. package/src/server/extensions/ask-someone/index.js +500 -0
  126. package/src/server/extensions/ask-someone/style.css +110 -0
  127. package/src/server/extensions/ask-someone.ts +571 -0
  128. package/src/server/extensions/background.ts +184 -0
  129. package/src/server/extensions/browser.ts +477 -0
  130. package/src/server/extensions/codemode.ts +430 -0
  131. package/src/server/extensions/design/canvas.js +304 -0
  132. package/src/server/extensions/design/comments.js +15 -0
  133. package/src/server/extensions/design/data.js +263 -0
  134. package/src/server/extensions/design/devices.js +70 -0
  135. package/src/server/extensions/design/docks.js +647 -0
  136. package/src/server/extensions/design/edits.js +37 -0
  137. package/src/server/extensions/design/index.js +326 -0
  138. package/src/server/extensions/design/messages.js +92 -0
  139. package/src/server/extensions/design/parts.js +160 -0
  140. package/src/server/extensions/design/state.js +146 -0
  141. package/src/server/extensions/design/style.css +1332 -0
  142. package/src/server/extensions/design/tweaks.js +161 -0
  143. package/src/server/extensions/design/views.js +375 -0
  144. package/src/server/extensions/design/workspace.js +723 -0
  145. package/src/server/extensions/design.ts +620 -0
  146. package/src/server/extensions/gallery.ts +154 -0
  147. package/src/server/extensions/goals.ts +103 -0
  148. package/src/server/extensions/guard.ts +80 -0
  149. package/src/server/extensions/memory.ts +183 -0
  150. package/src/server/extensions/pip.ts +714 -0
  151. package/src/server/extensions/plan.ts +345 -0
  152. package/src/server/extensions/prompt.ts +134 -0
  153. package/src/server/extensions/schedules.ts +164 -0
  154. package/src/server/extensions/session-tags/index.js +511 -0
  155. package/src/server/extensions/session-tags/style.css +150 -0
  156. package/src/server/extensions/session-tags.ts +165 -0
  157. package/src/server/extensions/subagents.ts +1087 -0
  158. package/src/server/extensions/triggers.ts +104 -0
  159. package/src/server/extensions/updates/index.js +429 -0
  160. package/src/server/extensions/updates/style.css +120 -0
  161. package/src/server/extensions/updates.ts +177 -0
  162. package/src/server/fence.ts +49 -0
  163. package/src/server/files.ts +343 -0
  164. package/src/server/folder-favorites.ts +76 -0
  165. package/src/server/gallery/diff.ts +202 -0
  166. package/src/server/gallery/entry.ts +930 -0
  167. package/src/server/gallery/fetch.ts +131 -0
  168. package/src/server/gallery/files.ts +364 -0
  169. package/src/server/gallery/share.ts +495 -0
  170. package/src/server/gallery/themes.ts +247 -0
  171. package/src/server/gallery.ts +1478 -0
  172. package/src/server/git.ts +57 -0
  173. package/src/server/github.ts +396 -0
  174. package/src/server/goals.ts +198 -0
  175. package/src/server/hidden.ts +470 -0
  176. package/src/server/hooks.ts +677 -0
  177. package/src/server/host.ts +707 -0
  178. package/src/server/http/api.ts +858 -0
  179. package/src/server/http/artifact-assets.ts +216 -0
  180. package/src/server/http/artifact-inspect.ts +1281 -0
  181. package/src/server/http/artifacts.ts +347 -0
  182. package/src/server/http/assets.ts +412 -0
  183. package/src/server/http/browser-routes.ts +210 -0
  184. package/src/server/http/compress.ts +108 -0
  185. package/src/server/http/conversation-routes.ts +757 -0
  186. package/src/server/http/events.ts +405 -0
  187. package/src/server/http/extension-routes.ts +234 -0
  188. package/src/server/http/hook-routes.ts +93 -0
  189. package/src/server/http/io.ts +205 -0
  190. package/src/server/http/link-routes.ts +342 -0
  191. package/src/server/http/push-routes.ts +95 -0
  192. package/src/server/http/sign-in.ts +183 -0
  193. package/src/server/http/theme-routes.ts +86 -0
  194. package/src/server/http.ts +152 -0
  195. package/src/server/lancet.ts +424 -0
  196. package/src/server/limit-gate.ts +1333 -0
  197. package/src/server/limits.ts +489 -0
  198. package/src/server/linked-sessions.ts +942 -0
  199. package/src/server/lock.ts +275 -0
  200. package/src/server/main.ts +279 -0
  201. package/src/server/memory.ts +719 -0
  202. package/src/server/model-facts.ts +60 -0
  203. package/src/server/model-names.ts +337 -0
  204. package/src/server/model-refresh.ts +256 -0
  205. package/src/server/models.ts +196 -0
  206. package/src/server/net.ts +54 -0
  207. package/src/server/npm-install.ts +82 -0
  208. package/src/server/npm-update.ts +100 -0
  209. package/src/server/omarchy.ts +114 -0
  210. package/src/server/paths.ts +28 -0
  211. package/src/server/pi-sessions.ts +556 -0
  212. package/src/server/pip-compact.ts +595 -0
  213. package/src/server/pip.ts +1732 -0
  214. package/src/server/project-model.ts +114 -0
  215. package/src/server/projection.ts +1055 -0
  216. package/src/server/prompts.ts +264 -0
  217. package/src/server/providers.ts +423 -0
  218. package/src/server/public-fetch.ts +443 -0
  219. package/src/server/public-links.ts +239 -0
  220. package/src/server/push.ts +503 -0
  221. package/src/server/reload.ts +1154 -0
  222. package/src/server/repo-watches.ts +842 -0
  223. package/src/server/requests.ts +26 -0
  224. package/src/server/resend.ts +191 -0
  225. package/src/server/reveal.ts +104 -0
  226. package/src/server/room.ts +1132 -0
  227. package/src/server/running.ts +243 -0
  228. package/src/server/schedules.ts +400 -0
  229. package/src/server/share.ts +245 -0
  230. package/src/server/shell.ts +365 -0
  231. package/src/server/skills.ts +259 -0
  232. package/src/server/spend.ts +528 -0
  233. package/src/server/subagent-runs.ts +21 -0
  234. package/src/server/themes/css.ts +592 -0
  235. package/src/server/themes/format.ts +166 -0
  236. package/src/server/themes/reserved.ts +39 -0
  237. package/src/server/themes.ts +1211 -0
  238. package/src/server/timing.ts +98 -0
  239. package/src/server/titles.ts +168 -0
  240. package/src/server/transcripts.ts +208 -0
  241. package/src/server/update-state.ts +963 -0
  242. package/src/server/updates.ts +1371 -0
  243. package/src/server/versions.ts +47 -0
  244. package/src/server/watches.ts +1108 -0
  245. package/src/server/when.ts +403 -0
  246. package/src/server/workspace.ts +507 -0
  247. package/src/server/worktrees.ts +203 -0
  248. package/src/server/zip.ts +163 -0
  249. package/types/pocket.d.ts +2725 -0
  250. package/web/activity-fold.js +28 -0
  251. package/web/agent-now.js +37 -0
  252. package/web/agent-tile.js +79 -0
  253. package/web/app.js +964 -0
  254. package/web/apple-touch-icon.png +0 -0
  255. package/web/artifact-bridge.js +656 -0
  256. package/web/avatar.js +87 -0
  257. package/web/back.js +554 -0
  258. package/web/box-keys.js +216 -0
  259. package/web/browser-panel.js +1097 -0
  260. package/web/browser.js +68 -0
  261. package/web/calls.js +119 -0
  262. package/web/chat.js +919 -0
  263. package/web/clock.js +34 -0
  264. package/web/commands.js +578 -0
  265. package/web/composer.js +2003 -0
  266. package/web/diff-parse.js +672 -0
  267. package/web/diff.js +1646 -0
  268. package/web/dock.js +299 -0
  269. package/web/extension-ui.js +2734 -0
  270. package/web/files-panel.js +772 -0
  271. package/web/files.js +368 -0
  272. package/web/fonts/FiraCode-OFL.txt +93 -0
  273. package/web/fonts/FiraCode-VF.woff2 +0 -0
  274. package/web/fonts/Geist-OFL.txt +92 -0
  275. package/web/fonts/Geist.woff2 +0 -0
  276. package/web/fonts/IBMPlexMono-OFL.txt +92 -0
  277. package/web/fonts/IBMPlexMono-Variable-Italic.woff2 +0 -0
  278. package/web/fonts/IBMPlexMono-Variable.woff2 +0 -0
  279. package/web/fonts/Inter-OFL.txt +92 -0
  280. package/web/fonts/InterVariable-Italic.woff2 +0 -0
  281. package/web/fonts/InterVariable.woff2 +0 -0
  282. package/web/fonts/Iosevka-Bold.woff2 +0 -0
  283. package/web/fonts/Iosevka-BoldItalic.woff2 +0 -0
  284. package/web/fonts/Iosevka-Italic.woff2 +0 -0
  285. package/web/fonts/Iosevka-OFL.txt +110 -0
  286. package/web/fonts/Iosevka-Regular.woff2 +0 -0
  287. package/web/fonts/Iosevka-SemiBold.woff2 +0 -0
  288. package/web/fonts/Iosevka-SemiBoldItalic.woff2 +0 -0
  289. package/web/fonts/JetBrainsMono-Italic.woff2 +0 -0
  290. package/web/fonts/JetBrainsMono.woff2 +0 -0
  291. package/web/fonts/NerdFonts-LICENSE.txt +21 -0
  292. package/web/fonts/NerdFonts-README.txt +67 -0
  293. package/web/fonts/NerdFontsSymbolsMono.woff2 +0 -0
  294. package/web/fonts/OFL.txt +93 -0
  295. package/web/fonts/SOURCES.md +69 -0
  296. package/web/gestures.js +610 -0
  297. package/web/highlight.js +480 -0
  298. package/web/history.js +70 -0
  299. package/web/home.js +169 -0
  300. package/web/icon-192.png +0 -0
  301. package/web/icon-512.png +0 -0
  302. package/web/icon-maskable-512.png +0 -0
  303. package/web/icon.svg +16 -0
  304. package/web/index.html +123 -0
  305. package/web/launcher.js +1293 -0
  306. package/web/linked-sessions.js +55 -0
  307. package/web/live.js +39 -0
  308. package/web/manifest.webmanifest +32 -0
  309. package/web/model-refresh.js +73 -0
  310. package/web/notify.js +251 -0
  311. package/web/peeks.js +915 -0
  312. package/web/pip-attachments.js +182 -0
  313. package/web/pip-window.js +141 -0
  314. package/web/pip.js +1217 -0
  315. package/web/rich.js +403 -0
  316. package/web/run-frame.js +106 -0
  317. package/web/safe-mode.js +71 -0
  318. package/web/seen.js +137 -0
  319. package/web/session-tree.js +117 -0
  320. package/web/sessions.js +1944 -0
  321. package/web/share.js +126 -0
  322. package/web/sheets/appearance.js +820 -0
  323. package/web/sheets/branch.js +353 -0
  324. package/web/sheets/extensions.js +750 -0
  325. package/web/sheets/file.js +306 -0
  326. package/web/sheets/find.js +250 -0
  327. package/web/sheets/folder.js +680 -0
  328. package/web/sheets/gallery.js +1720 -0
  329. package/web/sheets/hooks.js +350 -0
  330. package/web/sheets/memory.js +531 -0
  331. package/web/sheets/menu.js +580 -0
  332. package/web/sheets/message.js +220 -0
  333. package/web/sheets/model.js +412 -0
  334. package/web/sheets/people.js +409 -0
  335. package/web/sheets/pi-sessions.js +264 -0
  336. package/web/sheets/providers.js +525 -0
  337. package/web/sheets/running.js +130 -0
  338. package/web/sheets/schedules.js +71 -0
  339. package/web/sheets/session.js +60 -0
  340. package/web/sheets/shortcuts.js +101 -0
  341. package/web/sheets/spend.js +150 -0
  342. package/web/sheets/text.js +53 -0
  343. package/web/sheets/viewers.js +363 -0
  344. package/web/sheets/worktree.js +50 -0
  345. package/web/sheets.js +395 -0
  346. package/web/signin.js +57 -0
  347. package/web/slots.js +208 -0
  348. package/web/store.js +1731 -0
  349. package/web/style.css +17562 -0
  350. package/web/subagents-board.js +879 -0
  351. package/web/subagents.js +273 -0
  352. package/web/sw.js +169 -0
  353. package/web/taps.js +26 -0
  354. package/web/theme-surface.d.ts +4 -0
  355. package/web/theme-surface.js +243 -0
  356. package/web/theme.js +833 -0
  357. package/web/themes/lantern/colors.toml +25 -0
  358. package/web/themes/lantern/direction.css +60 -0
  359. package/web/themes/lantern/frame.css +254 -0
  360. package/web/themes/lantern/theme.css +10 -0
  361. package/web/themes/lantern/theme.json +7 -0
  362. package/web/themes/pocket/theme.css +189 -0
  363. package/web/themes/pocket/theme.json +6 -0
  364. package/web/themes.js +556 -0
  365. package/web/transcript.js +3224 -0
  366. package/web/trust.js +295 -0
  367. package/web/turns.js +507 -0
  368. package/web/ui.js +1906 -0
  369. package/web/voice.js +345 -0
@@ -0,0 +1,1211 @@
1
+ /**
2
+ * Themes: folders of CSS, colors, fonts, and images that change how the app looks and is laid out
3
+ * (docs/extensions/themes.md). The built-in ones are in `web/themes/`, the owner's in the data folder's `themes/`. Each
4
+ * is read and checked here (`themes/format.ts`, `themes/css.ts`), its CSS kept in memory as it was checked, and served
5
+ * at `/themes/<id>/<rev>/…` to everyone signed in (`http/theme-routes.ts`). A theme that breaks keeps its last good
6
+ * version while the server runs, and the owner is told why.
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import {
10
+ closeSync,
11
+ constants,
12
+ cpSync,
13
+ type Dirent,
14
+ fstatSync,
15
+ lstatSync,
16
+ mkdirSync,
17
+ openSync,
18
+ readdirSync,
19
+ readFileSync,
20
+ realpathSync,
21
+ renameSync,
22
+ writeFileSync,
23
+ } from "node:fs";
24
+ import { basename, dirname, join } from "node:path";
25
+ import { pathToFileURL } from "node:url";
26
+ import { APP_ROOT } from "./config.ts";
27
+ import { describe, HttpError } from "./errors.ts";
28
+ import { opened } from "./http/io.ts";
29
+ import { desktopTheme } from "./omarchy.ts";
30
+ import { watchTree } from "./reload.ts";
31
+ import { cssReferences, themeFile, tokenize } from "./themes/css.ts";
32
+ import { reservedThemeIds } from "./themes/reserved.ts";
33
+ import { pocketVersion } from "./versions.ts";
34
+ import {
35
+ assetType,
36
+ colorsToml,
37
+ type Manifest,
38
+ newThemeId,
39
+ parseManifest,
40
+ parseThemeColors,
41
+ plainLine,
42
+ THEME_ID,
43
+ THEME_LIMITS,
44
+ ThemeProblem,
45
+ } from "./themes/format.ts";
46
+
47
+ /** The app's own look, which every theme builds on: choosing it loads no stylesheet. */
48
+ export const BASE_THEME = "pocket";
49
+
50
+ /** A theme as the web app lists it. */
51
+ export interface ThemeInfo {
52
+ id: string;
53
+ name: string;
54
+ description?: string;
55
+ author?: string;
56
+ version?: string;
57
+ /** In `web/themes/`, with the app: it cannot be changed or removed here. */
58
+ builtIn: boolean;
59
+ /** The stylesheets to load; none for the base theme and for colors alone. */
60
+ css: string[];
61
+ /** Its palette, by `colors.toml`'s keys, when it has one. */
62
+ colors?: Record<string, string>;
63
+ /** A light palette beside it (`colors-light.toml`): the theme's colors follow the system's light or dark. */
64
+ colorsLight?: Record<string, string>;
65
+ /** The fonts its stylesheets load, to preload with them. */
66
+ fonts: string[];
67
+ /** The fonts it uses, as Appearance's Fonts show them and set them (`fonts.css`). */
68
+ typography?: ThemeTypography;
69
+ /** Changes when any of its files do. */
70
+ rev?: string;
71
+ /** Why it is not as its files are: it keeps its last good version, or, with none, it is not offered. */
72
+ problem?: string;
73
+ /** Whether it can be chosen: it has a good version. */
74
+ usable: boolean;
75
+ }
76
+
77
+ /**
78
+ * A theme's fonts: the first family of its `--sans` and `--mono` (none for the app's), and ligatures; `own` names the
79
+ * families its own stylesheets set, without what Appearance saved over them.
80
+ */
81
+ export interface ThemeTypography {
82
+ sans?: string;
83
+ mono?: string;
84
+ ligatures: boolean;
85
+ own?: { sans?: string; mono?: string };
86
+ }
87
+
88
+ /** A file of a theme's folder, as it was when it was read. */
89
+ interface FileStat {
90
+ file: string;
91
+ size: number;
92
+ mtimeMs: number;
93
+ dev: number;
94
+ ino: number;
95
+ }
96
+
97
+ /** A theme as it was checked: what is served. */
98
+ interface Version {
99
+ id: string;
100
+ dir: string;
101
+ builtIn: boolean;
102
+ manifest?: Manifest;
103
+ colors?: Record<string, string>;
104
+ colorsLight?: Record<string, string>;
105
+ /** Its stylesheets' text, by their path in the folder, `theme.css` first. */
106
+ css: Map<string, string>;
107
+ /** Its fonts and images, by their path in the folder. */
108
+ assets: Map<string, FileStat & { type: string }>;
109
+ rev: string;
110
+ }
111
+
112
+ /**
113
+ * The fonts that come with the app (`web/style.css`), which a theme names in `--sans` or `--mono`, and the upright file
114
+ * of each, for the page to preload with the theme. The Nerd Fonts symbols are left out: they load only for an icon.
115
+ */
116
+ const APP_FONTS: Record<string, string> = {
117
+ "Pocket Inter": "/fonts/InterVariable.woff2",
118
+ "Pocket Fira Code": "/fonts/FiraCode-VF.woff2",
119
+ "Pocket IBM Plex Mono": "/fonts/IBMPlexMono-Variable.woff2",
120
+ "Pocket Iosevka": "/fonts/Iosevka-Regular.woff2",
121
+ };
122
+
123
+ /**
124
+ * The fonts Appearance offers a theme, for words and for code: the app's own two, APP_FONTS, and the device's own, by
125
+ * the CSS generic family each starts with (`system-ui`, `ui-monospace`), which is how a stylesheet names them.
126
+ */
127
+ export const THEME_FONTS = {
128
+ sans: [
129
+ "Pocket Sans",
130
+ "Pocket Inter",
131
+ "system-ui",
132
+ "Pocket Mono",
133
+ "Pocket Fira Code",
134
+ "Pocket IBM Plex Mono",
135
+ "Pocket Iosevka",
136
+ "ui-monospace",
137
+ ],
138
+ mono: [
139
+ "Pocket Mono",
140
+ "Pocket Fira Code",
141
+ "Pocket IBM Plex Mono",
142
+ "Pocket Iosevka",
143
+ "ui-monospace",
144
+ ],
145
+ };
146
+
147
+ /** The whole list a font of THEME_FONTS is written as: each falls back to the device's own of its kind. */
148
+ function fontStack(family: string, kind: "sans" | "mono"): string {
149
+ const monospace = family === "ui-monospace" || THEME_FONTS.mono.includes(family);
150
+ const named = family.startsWith("Pocket ") ? `"${family}"` : family;
151
+
152
+ if (!monospace) {
153
+ return `${named}, ${family === "system-ui" ? "" : "system-ui, "}ui-sans-serif, sans-serif`;
154
+ }
155
+
156
+ // Code keeps the Nerd Fonts icons after its font, for the ones prompts and tools print.
157
+ const icons = kind === "mono" ? `"Pocket Nerd Symbols", ` : "";
158
+
159
+ return family === "ui-monospace"
160
+ ? `ui-monospace, ${icons}SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace`
161
+ : `${named}, ${icons}ui-monospace, monospace`;
162
+ }
163
+
164
+ /** What CSS sets for fonts: the first family of the last `--sans` and `--mono`, and whether ligatures are on. */
165
+ function cssFonts(text: string): { sans?: string; mono?: string; ligatures?: boolean } {
166
+ const css = text.replace(/\/\*[\s\S]*?\*\//g, "");
167
+
168
+ // The last value set: a name in quotes, or a keyword (`system-ui`), not a function (`var(…)`).
169
+ const last = (name: string) =>
170
+ [
171
+ ...css.matchAll(
172
+ new RegExp(
173
+ `(?<![\\w-])--${name}\\s*:\\s*(?:"([^"]+)"|'([^']+)'|([a-z][a-z-]*)(?![\\w(-]))`,
174
+ "g",
175
+ ),
176
+ ),
177
+ ]
178
+ .map((found) => found[1] ?? found[2] ?? found[3])
179
+ .at(-1);
180
+
181
+ const sans = last("sans");
182
+ const mono = last("mono");
183
+ const ligatures = last("ligatures");
184
+
185
+ return {
186
+ ...(sans === undefined ? {} : { sans }),
187
+ ...(mono === undefined ? {} : { mono }),
188
+ ...(ligatures === undefined ? {} : { ligatures: /^(contextual|normal)$/.test(ligatures) }),
189
+ };
190
+ }
191
+
192
+ /**
193
+ * The fonts a theme uses (Appearance's Fonts): what its `fonts.css` sets, which wins (its values are `!important`), else
194
+ * what its own stylesheets set; and, as `own`, what they alone set, so that the menus can go back to a family of its own.
195
+ */
196
+ function typography(sheets: Map<string, string>): ThemeTypography {
197
+ const own = cssFonts(
198
+ [...sheets]
199
+ .filter(([path]) => path !== "fonts.css")
200
+ .map(([, text]) => text)
201
+ .join("\n"),
202
+ );
203
+ const saved = cssFonts(sheets.get("fonts.css") ?? "");
204
+ const sans = saved.sans ?? own.sans;
205
+ const mono = saved.mono ?? own.mono;
206
+ const theirs = {
207
+ ...(own.sans === undefined ? {} : { sans: own.sans }),
208
+ ...(own.mono === undefined ? {} : { mono: own.mono }),
209
+ };
210
+
211
+ return {
212
+ ...(sans === undefined ? {} : { sans }),
213
+ ...(mono === undefined ? {} : { mono }),
214
+ ligatures: saved.ligatures ?? own.ligatures ?? false,
215
+ ...(Object.keys(theirs).length === 0 ? {} : { own: theirs }),
216
+ };
217
+ }
218
+
219
+ /** Whether a theme's file is a plain file, or not there; a link or a folder in its place is refused, not followed. */
220
+ function plainFile(file: string): boolean {
221
+ let stats;
222
+
223
+ try {
224
+ stats = lstatSync(file);
225
+ } catch {
226
+ return false;
227
+ }
228
+
229
+ if (!stats.isFile()) {
230
+ throw new HttpError(
231
+ 409,
232
+ `${file} is not a plain file (a link or a folder): change the theme's fonts by hand`,
233
+ );
234
+ }
235
+
236
+ return true;
237
+ }
238
+
239
+ /** Write a file of a theme's folder in one step, through a hidden file renamed over it: never through a link. */
240
+ function writeThemeFile(file: string, text: string): void {
241
+ const temp = join(dirname(file), `.${basename(file)}.${process.pid}.${Date.now()}.tmp`);
242
+
243
+ writeFileSync(temp, text, { flag: "wx" });
244
+ renameSync(temp, file);
245
+ }
246
+
247
+ /** A theme's file's address: its path in the folder, each part escaped, under the theme's id and version. */
248
+ const themeAddress = (id: string, rev: string, path: string) =>
249
+ `/themes/${id}/${rev}/${path.split("/").map(encodeURIComponent).join("/")}`;
250
+
251
+ /** A theme folder found, in the order listed. */
252
+ interface Listed {
253
+ id: string;
254
+ builtIn: boolean;
255
+ name?: string | undefined;
256
+ }
257
+
258
+ /** What a theme's address serves: a stylesheet as it was checked, or a font or image on disk. */
259
+ export type ThemeFile = { css: string } | (FileStat & { type: string });
260
+
261
+ export interface ThemesOptions {
262
+ builtIn: string;
263
+ dataDir: string;
264
+ /** Pi Pocket's version, for a theme's `minPocket`: its package's, unless a test says otherwise. */
265
+ version?: string;
266
+ /** Something about a theme only the owner can mend. */
267
+ notify: (message: string) => void;
268
+ /** The list changed: tabs should hear it. */
269
+ changed: () => void;
270
+ log: (line: string) => void;
271
+ }
272
+
273
+ export class Themes {
274
+ readonly builtInDir: string;
275
+ /** The owner's themes: a real path once `load` made it, as reading a file checks the path it opened. */
276
+ dir: string;
277
+ readonly #options: ThemesOptions & { version: string };
278
+ /** The last good version of each theme, by id. */
279
+ readonly #good = new Map<string, Version>();
280
+ /** Why a theme's files are not what is served, by id. */
281
+ readonly #problems = new Map<string, string>();
282
+ /** Every theme folder found, by id, in the order listed: built-in ones first. */
283
+ #found: Listed[] = [];
284
+ /** The palettes that come with the app (`web/themes.js`), by id: their ids are taken. */
285
+ #palettes: Record<string, { name: string; colors: Record<string, string> }> = {};
286
+ /** The ids the app keeps (`reservedThemeIds`): no folder of the owner's may take one. */
287
+ #reserved = new Set<string>(["pocket", "desktop"]);
288
+ #failure: string | undefined;
289
+ /** Folders not read for their names, with why: told once. */
290
+ #misnamed = new Map<string, string>();
291
+ #stops: (() => void)[] = [];
292
+ #timer: NodeJS.Timeout | undefined;
293
+ #listKey = "";
294
+
295
+ constructor(options: ThemesOptions) {
296
+ this.#options = { ...options, version: options.version ?? pocketVersion() };
297
+ this.builtInDir = options.builtIn;
298
+ this.dir = join(options.dataDir, "themes");
299
+ }
300
+
301
+ /** Read every theme, once, as the server starts. */
302
+ async load(): Promise<void> {
303
+ try {
304
+ const module = (await import(
305
+ pathToFileURL(join(APP_ROOT, "web", "themes.js")).href
306
+ )) as {
307
+ THEMES: Record<string, { name: string; colors: Record<string, string> }>;
308
+ };
309
+
310
+ this.#palettes = module.THEMES;
311
+ } catch (error) {
312
+ this.#options.log(`The app's palettes could not be read: ${describe(error)}`);
313
+ }
314
+
315
+ this.#reserved = await reservedThemeIds();
316
+
317
+ try {
318
+ mkdirSync(this.dir, { recursive: true });
319
+ // A data folder reached through a link (or named relatively) would make every file read differ from the
320
+ // path `/proc` gives for it, and no theme of the owner's would load.
321
+ this.dir = realpathSync(this.dir);
322
+ } catch (error) {
323
+ this.#options.log(`No themes folder at ${this.dir}: ${describe(error)}`);
324
+ }
325
+
326
+ // A theme folder must never keep the server from starting: past a failure, the built-in themes alone.
327
+ try {
328
+ this.#scan(false);
329
+ } catch (error) {
330
+ this.#failure = `The owner's themes could not be read, so only the built-in ones are offered until the server restarts: ${describe(error)}`;
331
+ this.#options.log(this.#failure);
332
+ this.#good.clear();
333
+ this.#problems.clear();
334
+ this.#found = [];
335
+
336
+ try {
337
+ this.#scan(false, false);
338
+ } catch (again) {
339
+ this.#options.log(`The built-in themes could not be read: ${describe(again)}`);
340
+ }
341
+ }
342
+ }
343
+
344
+ /** Why the owner's themes were not read at the start, if they were not: the owner is told when they connect. */
345
+ get failure(): string | undefined {
346
+ return this.#failure;
347
+ }
348
+
349
+ /** While an update moves Pi Pocket's checkout, the built-in themes' edits are read at the restart after it. */
350
+ #paused = false;
351
+
352
+ pause(paused: boolean): void {
353
+ this.#paused = paused;
354
+
355
+ if (paused) {
356
+ clearTimeout(this.#timer);
357
+ }
358
+ }
359
+
360
+ /** Read the themes again shortly after their files change. */
361
+ watch(): void {
362
+ const later = () => {
363
+ if (this.#paused) {
364
+ return;
365
+ }
366
+
367
+ clearTimeout(this.#timer);
368
+ this.#timer = setTimeout(() => this.rescan(), 300);
369
+ };
370
+
371
+ for (const dir of [this.builtInDir, this.dir]) {
372
+ try {
373
+ this.#stops.push(watchTree(dir, later));
374
+ } catch (error) {
375
+ this.#options.log(
376
+ `Themes in ${dir} are not reloaded when edited: ${describe(error)}`,
377
+ );
378
+ }
379
+ }
380
+ }
381
+
382
+ close(): void {
383
+ clearTimeout(this.#timer);
384
+
385
+ for (const stop of this.#stops.splice(0)) {
386
+ stop();
387
+ }
388
+ }
389
+
390
+ /** Read every theme again, and tell the tabs and the owner what changed. */
391
+ rescan(): void {
392
+ // From a timer: what it throws would end the process.
393
+ try {
394
+ this.#scan(true);
395
+ } catch (error) {
396
+ const message = `Themes could not be read again; the ones in use stay as they were: ${describe(error)}`;
397
+
398
+ this.#options.log(message);
399
+ this.#options.notify(message);
400
+ }
401
+ }
402
+
403
+ /** Every theme, as the web app lists it: built-in ones first, then the owner's by name. */
404
+ list(owner = true): ThemeInfo[] {
405
+ return this.#found.map(({ id, builtIn, name }) => {
406
+ const good = this.#good.get(id);
407
+ const problem = this.#problems.get(id);
408
+ const manifest = good?.manifest;
409
+
410
+ return {
411
+ id,
412
+ name: manifest?.name ?? name ?? id,
413
+ ...(manifest?.description === undefined
414
+ ? {}
415
+ : { description: manifest.description }),
416
+ ...(manifest?.author === undefined ? {} : { author: manifest.author }),
417
+ ...(manifest?.version === undefined ? {} : { version: manifest.version }),
418
+ builtIn,
419
+ css: good === undefined || id === BASE_THEME ? [] : this.#chain(good),
420
+ ...(good?.colors === undefined ? {} : { colors: good.colors }),
421
+ ...(good?.colorsLight === undefined ? {} : { colorsLight: good.colorsLight }),
422
+ fonts: good === undefined || id === BASE_THEME ? [] : this.#fonts(good),
423
+ ...(good === undefined || id === BASE_THEME
424
+ ? {}
425
+ : { typography: typography(good.css) }),
426
+ ...(good === undefined ? {} : { rev: good.rev }),
427
+ // What is wrong can name the server's folders: the owner's to read, as extensions' load errors are.
428
+ ...(problem === undefined || !owner ? {} : { problem }),
429
+ usable: good !== undefined,
430
+ };
431
+ });
432
+ }
433
+
434
+ /**
435
+ * A file a theme serves now, by its path in the folder, and whether `rev` is the version it is now (an address that
436
+ * will never serve anything else); none for anything else.
437
+ */
438
+ file(
439
+ id: string,
440
+ rev: string | undefined,
441
+ path: readonly string[],
442
+ ): { file: ThemeFile; current: boolean } | undefined {
443
+ const good = this.#good.get(id);
444
+ const key = path.join("/");
445
+
446
+ if (good === undefined) {
447
+ return undefined;
448
+ }
449
+
450
+ const css = good.css.get(key);
451
+ const file = css === undefined ? good.assets.get(key) : { css };
452
+
453
+ return file === undefined ? undefined : { file, current: rev === good.rev };
454
+ }
455
+
456
+ /**
457
+ * Whether colors are here to use: the desktop's (on a machine with Omarchy), a palette that comes with the app, or a
458
+ * theme folder's that can be used (`<id>`, or a half of a pair: `<id>@dark`, `<id>@light`).
459
+ */
460
+ async hasColors(id: string): Promise<boolean> {
461
+ if (id === "desktop") {
462
+ return (await desktopTheme()) !== null;
463
+ }
464
+
465
+ if (Object.hasOwn(this.#palettes, id)) {
466
+ return true;
467
+ }
468
+
469
+ const [base, half] = id.split("@");
470
+ const good = base === undefined ? undefined : this.#good.get(base);
471
+
472
+ return half === "light"
473
+ ? good?.colorsLight !== undefined
474
+ : half === "dark"
475
+ ? good?.colorsLight !== undefined && good.colors !== undefined
476
+ : good?.colors !== undefined;
477
+ }
478
+
479
+ /** Whether a theme is the owner's, and so may be changed or removed here. */
480
+ #owned(id: string): boolean {
481
+ return this.#found.some((each) => each.id === id && !each.builtIn);
482
+ }
483
+
484
+ /**
485
+ * A new theme of the owner's called `name`. Of a theme (`colors` false): a copy of its whole folder, with a new name.
486
+ * Of colors (`colors` true): a theme of colors alone, from a palette that comes with the app, `desktop` (the
487
+ * desktop's, as it is now), or a theme folder's (`<id>`, both halves of a pair; `<id>@dark` or `<id>@light`, one).
488
+ * Answers its id.
489
+ */
490
+ async duplicate(from: string, name: unknown, colorsOnly = false): Promise<string> {
491
+ const title = (() => {
492
+ try {
493
+ return plainLine(name, "The name", 60);
494
+ } catch (error) {
495
+ throw new HttpError(400, describe(error));
496
+ }
497
+ })();
498
+ const [base, half] = from.split("@") as [string, string | undefined];
499
+ const source = this.#good.get(base);
500
+ /** What to write, by file name, besides the copied files. */
501
+ const write = new Map<string, string>();
502
+ let copy: Map<string, FileStat> | undefined;
503
+ let manifest: Record<string, unknown> = { themeApi: 1, name: title };
504
+
505
+ if (!colorsOnly) {
506
+ if (source === undefined || half !== undefined) {
507
+ throw new HttpError(404, "No such theme to copy");
508
+ }
509
+
510
+ copy = walk(source.dir);
511
+ // Its own now: what the copy says of itself is the owner's to write.
512
+ manifest = {
513
+ ...(source.manifest ?? {}),
514
+ themeApi: source.manifest?.themeApi ?? 1,
515
+ name: title,
516
+ };
517
+ delete manifest.description;
518
+ delete manifest.author;
519
+ delete manifest.version;
520
+ } else if (source !== undefined) {
521
+ const dark = half === "light" ? undefined : source.colors;
522
+ const light = half === "dark" ? undefined : source.colorsLight;
523
+
524
+ if (dark === undefined && light === undefined) {
525
+ throw new HttpError(404, "That theme has no such colors");
526
+ }
527
+
528
+ if (dark !== undefined) {
529
+ write.set("colors.toml", colorsToml(dark));
530
+ }
531
+
532
+ if (light !== undefined) {
533
+ write.set(
534
+ dark === undefined ? "colors.toml" : "colors-light.toml",
535
+ colorsToml(light),
536
+ );
537
+ }
538
+ } else {
539
+ const colors =
540
+ from === "desktop"
541
+ ? (await desktopTheme())?.colors
542
+ : Object.hasOwn(this.#palettes, from)
543
+ ? this.#palettes[from]!.colors
544
+ : undefined;
545
+
546
+ if (colors === undefined) {
547
+ throw new HttpError(404, "No such colors to copy");
548
+ }
549
+
550
+ write.set("colors.toml", colorsToml(colors));
551
+ }
552
+
553
+ write.set("theme.json", `${JSON.stringify(manifest, null, 4)}\n`);
554
+ const id = newThemeId(title, (each) => this.#taken(each));
555
+ const target = join(this.dir, id);
556
+
557
+ mkdirSync(this.dir, { recursive: true });
558
+ mkdirSync(target);
559
+
560
+ try {
561
+ // Every file of its folder, as written (its fonts' licences too), not as served.
562
+ for (const [path, stat] of copy ?? []) {
563
+ mkdirSync(dirname(join(target, path)), { recursive: true });
564
+ cpSync(stat.file, join(target, path), { dereference: false });
565
+ }
566
+
567
+ for (const [file, text] of write) {
568
+ writeFileSync(join(target, file), text);
569
+ }
570
+ } catch (error) {
571
+ this.#options.log(`Theme ${id} was not copied whole: ${describe(error)}`);
572
+
573
+ throw new HttpError(500, `The copy failed: ${describe(error)}`);
574
+ }
575
+
576
+ this.#scan(true);
577
+
578
+ return id;
579
+ }
580
+
581
+ /**
582
+ * Change the fonts and ligatures of one of the owner's themes (Appearance), in its `fonts.css`, which its `theme.css`
583
+ * imports. Each that is given replaces what was saved: a family of THEME_FONTS, or null for the theme's own; one that
584
+ * is not given stays as it was saved.
585
+ */
586
+ setFonts(id: string, fonts: { sans?: unknown; mono?: unknown; ligatures?: unknown }): void {
587
+ const good = this.#good.get(id);
588
+
589
+ if (!this.#owned(id) || good === undefined) {
590
+ throw new HttpError(
591
+ 404,
592
+ "Only your own themes can be changed: duplicate this one first",
593
+ );
594
+ }
595
+
596
+ // What was saved before, as far as it is one of the app's fonts: a family changed by hand to another is dropped.
597
+ const saved = cssFonts(good.css.get("fonts.css") ?? "");
598
+
599
+ // A family given, null for the theme's own, or, when none is given, the one saved.
600
+ const family = (value: unknown, which: "sans" | "mono"): string | null => {
601
+ if (value === undefined) {
602
+ const before = saved[which];
603
+
604
+ return before !== undefined && THEME_FONTS[which].includes(before) ? before : null;
605
+ }
606
+
607
+ if (value === null) {
608
+ return null;
609
+ }
610
+
611
+ if (typeof value !== "string" || !THEME_FONTS[which].includes(value)) {
612
+ throw new HttpError(
613
+ 400,
614
+ `Not one of the app's fonts for ${which === "sans" ? "words" : "code"}`,
615
+ );
616
+ }
617
+
618
+ return value;
619
+ };
620
+
621
+ if (![undefined, null, true, false].includes(fonts.ligatures as never)) {
622
+ throw new HttpError(400, "Ligatures are on (true) or off (false)");
623
+ }
624
+
625
+ const sans = family(fonts.sans, "sans");
626
+ const mono = family(fonts.mono, "mono");
627
+ const ligatures =
628
+ fonts.ligatures === undefined ? saved.ligatures : (fonts.ligatures as boolean | null);
629
+ const rules = [
630
+ ...(sans === null ? [] : [` --sans: ${fontStack(sans, "sans")} !important;`]),
631
+ ...(mono === null ? [] : [` --mono: ${fontStack(mono, "mono")} !important;`]),
632
+ ...(typeof ligatures === "boolean"
633
+ ? [` --ligatures: ${ligatures ? "contextual" : "none"} !important;`]
634
+ : []),
635
+ ];
636
+ const dir = join(this.dir, id);
637
+ const main = join(dir, "theme.css");
638
+ const manifest = join(dir, "theme.json");
639
+ const sheet = join(dir, "fonts.css");
640
+
641
+ // Only into the theme's own folder: none of its files that are written may be a link out of it.
642
+ if (!lstatSync(dir).isDirectory()) {
643
+ throw new HttpError(409, `${dir} is not a folder (a link to one is not changed)`);
644
+ }
645
+
646
+ const hasCss = plainFile(main);
647
+ const hasManifest = plainFile(manifest);
648
+
649
+ plainFile(sheet);
650
+
651
+ let css = "";
652
+
653
+ if (hasCss) {
654
+ const fd = openSync(
655
+ main,
656
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
657
+ );
658
+
659
+ try {
660
+ css = readFileSync(fd, "utf8");
661
+ } finally {
662
+ closeSync(fd);
663
+ }
664
+ } else if (!hasManifest) {
665
+ // A theme of colors alone gets a stylesheet now, which needs a theme.json: its name as it is listed.
666
+ const name = this.list().find((each) => each.id === id)?.name ?? id;
667
+
668
+ writeThemeFile(manifest, `${JSON.stringify({ themeApi: 1, name }, null, 4)}\n`);
669
+ }
670
+
671
+ writeThemeFile(
672
+ sheet,
673
+ `/* Set in Appearance (Fonts), over the theme's own: changes here are overwritten there. */\n:root {\n${rules.join("\n")}\n}\n`,
674
+ );
675
+
676
+ // `@import` must come first in a stylesheet (after an `@charset`), so a theme that has none of it starts with it.
677
+ if (
678
+ !/@import\s+(url\()?\s*["']?fonts\.css["']?/.test(css.replace(/\/\*[\s\S]*?\*\//g, ""))
679
+ ) {
680
+ const charset = /^\uFEFF?@charset\s+"[^"]*";\s*/.exec(css)?.[0] ?? "";
681
+
682
+ writeThemeFile(main, `${charset}@import "fonts.css";\n${css.slice(charset.length)}`);
683
+ }
684
+
685
+ this.#scan(true);
686
+ }
687
+
688
+ /** Take one of the owner's themes away: into `themes/.removed/`, which is not listed, so nothing is lost. */
689
+ remove(id: string): void {
690
+ if (!this.#owned(id)) {
691
+ throw new HttpError(404, "No such theme of yours");
692
+ }
693
+
694
+ const removed = join(this.dir, ".removed");
695
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
696
+
697
+ mkdirSync(removed, { recursive: true });
698
+ renameSync(join(this.dir, id), join(removed, `${id}-${stamp}`));
699
+ this.#scan(true);
700
+ }
701
+
702
+ /** Where a session that edits one of the owner's themes works, and what its message box starts with. */
703
+ edit(id: string): { cwd: string; draft: string } {
704
+ if (!this.#owned(id)) {
705
+ throw new HttpError(
706
+ 404,
707
+ "Only your own themes can be edited here: duplicate this one first",
708
+ );
709
+ }
710
+
711
+ const name = this.list().find((each) => each.id === id)?.name ?? id;
712
+ const docs = join(APP_ROOT, "docs", "extensions");
713
+
714
+ return {
715
+ cwd: join(this.dir, id),
716
+ draft: `Help me change the theme “${name}” in this folder. Read the theme guide (${join(docs, "themes.md")}) and the list of tokens and parts (${join(docs, "reference", "theme-surface.md")}) first. What I want: `,
717
+ };
718
+ }
719
+
720
+ /** Whether an id is a theme's, a built-in palette's, or a word the app keeps. */
721
+ #taken(id: string): boolean {
722
+ if (this.#reserved.has(id)) {
723
+ return true;
724
+ }
725
+
726
+ if (this.#found.some((each) => each.id === id)) {
727
+ return true;
728
+ }
729
+
730
+ try {
731
+ lstatSync(join(this.dir, id));
732
+
733
+ return true;
734
+ } catch {
735
+ return false;
736
+ }
737
+ }
738
+
739
+ /** The fonts a theme's stylesheets load: its own, and the upright file of each of the app's that it names. */
740
+ #fonts(version: Version): string[] {
741
+ // Its strings, as CSS reads them (comments skipped, escapes resolved): a family it names is one of them.
742
+ const named = new Set(
743
+ [...version.css.values()].flatMap((text) =>
744
+ tokenize(text).flatMap((token) => (token.type === "string" ? [token.value] : [])),
745
+ ),
746
+ );
747
+
748
+ return [
749
+ ...[...version.assets]
750
+ .filter(([, asset]) => asset.type === "font/woff2")
751
+ .map(([path]) => themeAddress(version.id, version.rev, path)),
752
+ ...Object.entries(APP_FONTS)
753
+ .filter(([family]) => named.has(family))
754
+ .map(([, file]) => file),
755
+ ];
756
+ }
757
+
758
+ /** The stylesheet of a theme: its `theme.css`, which imports the rest; none for colors alone. */
759
+ #chain(version: Version): string[] {
760
+ return version.css.has("theme.css")
761
+ ? [`/themes/${version.id}/${version.rev}/theme.css`]
762
+ : [];
763
+ }
764
+
765
+ /** Read every theme folder; with `tell`, tell the owner about new problems and the tabs about a changed list. */
766
+ #scan(tell: boolean, theirs = true): void {
767
+ const found: { id: string; builtIn: boolean; dir: string }[] = [];
768
+
769
+ for (const [root, builtIn] of [
770
+ [this.builtInDir, true],
771
+ ...(theirs ? [[this.dir, false] as const] : []),
772
+ ] as const) {
773
+ let entries: Dirent[];
774
+
775
+ try {
776
+ entries = readdirSync(root, { withFileTypes: true });
777
+ } catch {
778
+ continue;
779
+ }
780
+
781
+ for (const entry of entries
782
+ .filter((each) => each.isDirectory() && !each.name.startsWith("."))
783
+ .sort((a, b) => (a.name < b.name ? -1 : 1))) {
784
+ found.push({ id: entry.name, builtIn, dir: join(root, entry.name) });
785
+ }
786
+ }
787
+
788
+ const before = new Map(this.#problems);
789
+ const seen = new Set<string>();
790
+ const listed: Listed[] = [];
791
+ const misnamed = new Map<string, string>();
792
+
793
+ for (const { id, builtIn, dir } of found) {
794
+ if (!THEME_ID.test(id)) {
795
+ misnamed.set(
796
+ dir,
797
+ "its folder's name is not an id: 2 to 48 lowercase letters, digits, and -",
798
+ );
799
+ continue;
800
+ }
801
+
802
+ if (seen.has(id) || (!builtIn && this.#reserved.has(id))) {
803
+ misnamed.set(
804
+ dir,
805
+ "its folder has the name of a theme or colors that come with Pi Pocket",
806
+ );
807
+ continue;
808
+ }
809
+
810
+ seen.add(id);
811
+
812
+ try {
813
+ const version = readTheme(dir, id, builtIn, this.#options.version);
814
+
815
+ this.#good.set(id, version);
816
+ this.#problems.delete(id);
817
+ listed.push({ id, builtIn, name: version.manifest?.name });
818
+ } catch (error) {
819
+ this.#problems.set(
820
+ id,
821
+ error instanceof ThemeProblem
822
+ ? error.message
823
+ : `it cannot be read: ${describe(error)}`,
824
+ );
825
+ listed.push({ id, builtIn, name: this.#good.get(id)?.manifest?.name });
826
+ }
827
+ }
828
+
829
+ // Themes whose folder went: nothing of them is served or listed.
830
+ for (const id of [...this.#good.keys()]) {
831
+ if (!seen.has(id)) {
832
+ this.#good.delete(id);
833
+ }
834
+ }
835
+
836
+ for (const id of [...this.#problems.keys()]) {
837
+ if (!seen.has(id)) {
838
+ this.#problems.delete(id);
839
+ }
840
+ }
841
+
842
+ // The owner's by name, after the built-in ones.
843
+ const owners = listed
844
+ .filter((each) => !each.builtIn)
845
+ .sort((a, b) => (a.name ?? a.id).localeCompare(b.name ?? b.id));
846
+
847
+ this.#found = [...listed.filter((each) => each.builtIn), ...owners];
848
+
849
+ const told: string[] = [];
850
+
851
+ for (const [id, problem] of this.#problems) {
852
+ if (before.get(id) !== problem) {
853
+ const name = this.#found.find((each) => each.id === id)?.name;
854
+ const kept = this.#good.has(id)
855
+ ? "It keeps its last good version."
856
+ : "It is not offered until that is mended.";
857
+
858
+ told.push(`Theme ${name ? `“${name}” (${id})` : id}: ${problem}. ${kept}`);
859
+ }
860
+ }
861
+
862
+ for (const [dir, problem] of misnamed) {
863
+ if (this.#misnamed.get(dir) !== problem) {
864
+ told.push(`The theme folder ${dir} is not read: ${problem}.`);
865
+ }
866
+ }
867
+
868
+ this.#misnamed = misnamed;
869
+
870
+ for (const message of told) {
871
+ this.#options.log(message);
872
+
873
+ if (tell) {
874
+ this.#options.notify(message);
875
+ }
876
+ }
877
+
878
+ const key = JSON.stringify(this.list());
879
+
880
+ if (key !== this.#listKey) {
881
+ this.#listKey = key;
882
+
883
+ if (tell) {
884
+ this.#options.changed();
885
+ }
886
+ }
887
+ }
888
+ }
889
+
890
+ /** A theme's folder: its files, by their path in it; no hidden ones, `node_modules`, or links, four folders deep. */
891
+ function walk(dir: string): Map<string, FileStat> {
892
+ const files = new Map<string, FileStat>();
893
+ let looked = 0;
894
+
895
+ const visit = (folder: string, prefix: string, depth: number) => {
896
+ let entries: Dirent[];
897
+
898
+ try {
899
+ entries = readdirSync(folder, { withFileTypes: true });
900
+ } catch {
901
+ return;
902
+ }
903
+
904
+ for (const entry of entries) {
905
+ if (++looked > THEME_LIMITS.walk) {
906
+ throw new ThemeProblem(
907
+ `its folder holds more than ${THEME_LIMITS.walk} files and folders`,
908
+ );
909
+ }
910
+
911
+ if (entry.name.startsWith(".") || entry.name === "node_modules") {
912
+ continue;
913
+ }
914
+
915
+ const path = join(folder, entry.name);
916
+ const relative = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
917
+
918
+ if (entry.isDirectory()) {
919
+ if (depth < THEME_LIMITS.depth) {
920
+ visit(path, relative, depth + 1);
921
+ }
922
+ } else if (entry.isFile()) {
923
+ try {
924
+ const stats = lstatSync(path);
925
+
926
+ files.set(relative, {
927
+ file: path,
928
+ size: stats.size,
929
+ mtimeMs: stats.mtimeMs,
930
+ dev: stats.dev,
931
+ ino: stats.ino,
932
+ });
933
+ } catch {
934
+ // Gone since the listing.
935
+ }
936
+ }
937
+ }
938
+ };
939
+
940
+ const stats = lstatSync(dir);
941
+
942
+ if (!stats.isDirectory()) {
943
+ throw new ThemeProblem("it is not a folder (a link to one is not read)");
944
+ }
945
+
946
+ visit(dir, "", 0);
947
+
948
+ return files;
949
+ }
950
+
951
+ /** A file of the folder as text, read as it was listed: not a link, the same file, and no bigger than `max`. */
952
+ export function readListed(stat: FileStat, max: number, what: string): string {
953
+ if (stat.size > max) {
954
+ throw new ThemeProblem(`${what} is larger than ${Math.round(max / 1024)} KB`);
955
+ }
956
+
957
+ let fd: number;
958
+
959
+ try {
960
+ fd = openSync(stat.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
961
+ } catch (error) {
962
+ throw new ThemeProblem(`${what} cannot be read: ${describe(error)}`);
963
+ }
964
+
965
+ try {
966
+ const now = fstatSync(fd);
967
+
968
+ if (!now.isFile() || !opened(fd, stat, now) || now.size > max) {
969
+ throw new ThemeProblem(`${what} changed while it was read: it is read again soon`);
970
+ }
971
+
972
+ return readFileSync(fd, "utf8");
973
+ } finally {
974
+ closeSync(fd);
975
+ }
976
+ }
977
+
978
+ /** Read and check one theme folder: what it serves, or why it cannot. */
979
+ export function readTheme(
980
+ dir: string,
981
+ id: string,
982
+ builtIn: boolean,
983
+ pocketVersion: string,
984
+ ): Version {
985
+ const files = walk(dir);
986
+ const hash = createHash("sha256");
987
+ const manifestFile = files.get("theme.json");
988
+ const colorsFile = files.get("colors.toml");
989
+ const lightFile = files.get("colors-light.toml");
990
+ const entry = files.get("theme.css");
991
+ let manifest: Manifest | undefined;
992
+ let colors: Record<string, string> | undefined;
993
+ let colorsLight: Record<string, string> | undefined;
994
+
995
+ if (manifestFile !== undefined) {
996
+ const text = readListed(manifestFile, THEME_LIMITS.small, "theme.json");
997
+
998
+ manifest = parseManifest(text, pocketVersion);
999
+ hash.update(`theme.json\0${text}\0`);
1000
+ }
1001
+
1002
+ if (colorsFile !== undefined) {
1003
+ const text = readListed(colorsFile, THEME_LIMITS.small, "colors.toml");
1004
+
1005
+ colors = parseThemeColors(text);
1006
+ hash.update(`colors.toml\0${text}\0`);
1007
+ }
1008
+
1009
+ if (lightFile !== undefined) {
1010
+ const text = readListed(lightFile, THEME_LIMITS.small, "colors-light.toml");
1011
+ const light = parseThemeColors(text);
1012
+
1013
+ if ((light.mode ?? "light") !== "light") {
1014
+ throw new ThemeProblem('colors-light.toml says mode = "dark"');
1015
+ }
1016
+
1017
+ // Alone, it is the theme's palette; beside colors.toml, the light half of a pair.
1018
+ if (colors === undefined) {
1019
+ colors = { ...light, mode: "light" };
1020
+ } else {
1021
+ colorsLight = { ...light, mode: "light" };
1022
+ }
1023
+
1024
+ hash.update(`colors-light.toml\0${text}\0`);
1025
+ }
1026
+
1027
+ if (entry === undefined && colors === undefined) {
1028
+ throw new ThemeProblem("it has no theme.css, colors.toml, or colors-light.toml");
1029
+ }
1030
+
1031
+ if (entry !== undefined && manifest === undefined) {
1032
+ throw new ThemeProblem("it has a theme.css but no theme.json");
1033
+ }
1034
+
1035
+ const css = new Map<string, string>();
1036
+ /** Where each stylesheet loads a font or an image, to write the theme's own address in (`served` below). */
1037
+ const loads = new Map<string, Load[]>();
1038
+ const assets = new Map<string, FileStat & { type: string }>();
1039
+ let cssBytes = 0;
1040
+ let assetBytes = 0;
1041
+ const queue = entry === undefined ? [] : ["theme.css"];
1042
+
1043
+ while (queue.length > 0) {
1044
+ const path = queue.shift()!;
1045
+
1046
+ if (css.has(path)) {
1047
+ continue;
1048
+ }
1049
+
1050
+ const stat = files.get(path)!;
1051
+
1052
+ cssBytes += stat.size;
1053
+
1054
+ if (cssBytes > THEME_LIMITS.css) {
1055
+ throw new ThemeProblem(`its CSS is larger than ${THEME_LIMITS.css / 1024} KB together`);
1056
+ }
1057
+
1058
+ const text = readListed(stat, THEME_LIMITS.css, path);
1059
+ const found = cssReferences(text);
1060
+ const where = (line: number) => `${path} line ${line}`;
1061
+
1062
+ css.set(path, found.text);
1063
+ loads.set(path, []);
1064
+ hash.update(`${path}\0${text}\0`);
1065
+
1066
+ if (found.problems.length > 0) {
1067
+ const first = found.problems[0]!;
1068
+
1069
+ throw new ThemeProblem(`${where(first.line)}: ${first.message}`);
1070
+ }
1071
+
1072
+ for (const ref of found.imports) {
1073
+ const target = themeFile(ref.url, path);
1074
+
1075
+ if (typeof target !== "object" || !target.file.toLowerCase().endsWith(".css")) {
1076
+ throw new ThemeProblem(
1077
+ `${where(ref.line)}: @import ${JSON.stringify(ref.url)} is not a .css file of the theme's own: a theme loads only its own files`,
1078
+ );
1079
+ }
1080
+
1081
+ if (!files.has(target.file)) {
1082
+ throw new ThemeProblem(
1083
+ `${where(ref.line)}: there is no ${target.file} in its folder`,
1084
+ );
1085
+ }
1086
+
1087
+ queue.push(target.file);
1088
+ // Written as its full address, as a font or an image is: the check read the address against the theme's
1089
+ // folder, and the browser must read it the same way, not against the app's.
1090
+ loads.get(path)!.push({
1091
+ start: ref.start,
1092
+ end: ref.end,
1093
+ quoted: ref.quoted,
1094
+ file: target.file,
1095
+ });
1096
+ }
1097
+
1098
+ for (const ref of found.assets) {
1099
+ const target = themeFile(ref.url, path);
1100
+
1101
+ if (target === "fragment" || target === "data") {
1102
+ continue;
1103
+ }
1104
+
1105
+ if (target === undefined) {
1106
+ throw new ThemeProblem(
1107
+ `${where(ref.line)}: url(${JSON.stringify(ref.url)}) is not a file in the theme's folder: a theme loads only its own files`,
1108
+ );
1109
+ }
1110
+
1111
+ const type = assetType(target.file);
1112
+ const stat = files.get(target.file);
1113
+
1114
+ if (type === undefined) {
1115
+ throw new ThemeProblem(
1116
+ `${where(ref.line)}: ${target.file} is not a .woff2 font or an image (.png, .jpg, .webp, .avif, .gif, .svg)`,
1117
+ );
1118
+ }
1119
+
1120
+ if (stat === undefined) {
1121
+ throw new ThemeProblem(
1122
+ `${where(ref.line)}: there is no ${target.file} in its folder`,
1123
+ );
1124
+ }
1125
+
1126
+ const fragment = ref.url.indexOf("#");
1127
+
1128
+ loads.get(path)!.push({
1129
+ start: ref.start,
1130
+ end: ref.end,
1131
+ quoted: ref.quoted,
1132
+ file: target.file,
1133
+ ...(fragment === -1
1134
+ ? {}
1135
+ : { fragment: encodeURIComponent(ref.url.slice(fragment + 1)) }),
1136
+ });
1137
+
1138
+ if (assets.has(target.file)) {
1139
+ continue;
1140
+ }
1141
+
1142
+ if (stat.size > THEME_LIMITS.asset) {
1143
+ throw new ThemeProblem(
1144
+ `${target.file} is larger than ${THEME_LIMITS.asset / 1024 / 1024} MB`,
1145
+ );
1146
+ }
1147
+
1148
+ assetBytes += stat.size;
1149
+
1150
+ if (assetBytes > THEME_LIMITS.total) {
1151
+ throw new ThemeProblem(
1152
+ `its fonts and images are larger than ${THEME_LIMITS.total / 1024 / 1024} MB together`,
1153
+ );
1154
+ }
1155
+
1156
+ assets.set(target.file, { ...stat, type });
1157
+ hash.update(`${target.file}\0${stat.size}\0${stat.mtimeMs}\0`);
1158
+ }
1159
+
1160
+ if (css.size + assets.size > THEME_LIMITS.files) {
1161
+ throw new ThemeProblem(`it serves more than ${THEME_LIMITS.files} files`);
1162
+ }
1163
+ }
1164
+
1165
+ const rev = hash.digest("base64url").slice(0, 12);
1166
+
1167
+ return {
1168
+ id,
1169
+ dir,
1170
+ builtIn,
1171
+ ...(manifest === undefined ? {} : { manifest }),
1172
+ ...(colors === undefined ? {} : { colors }),
1173
+ ...(colorsLight === undefined ? {} : { colorsLight }),
1174
+ css: new Map(
1175
+ [...css].map(([path, text]) => [path, served(text, loads.get(path)!, id, rev)]),
1176
+ ),
1177
+ assets,
1178
+ rev,
1179
+ };
1180
+ }
1181
+
1182
+ /** A file a stylesheet loads, where it names it, and the file of the folder it is (a `#` in its name kept apart). */
1183
+ interface Load {
1184
+ start: number;
1185
+ end: number;
1186
+ quoted: boolean;
1187
+ file: string;
1188
+ fragment?: string;
1189
+ }
1190
+
1191
+ /**
1192
+ * A stylesheet as it is served: each font and image it loads named by its full address, not by a path from the
1193
+ * stylesheet. A path in a variable (`--wallpaper: url("images/a.png")`) would otherwise be read where the variable is
1194
+ * used, from the app's own stylesheet, and miss.
1195
+ */
1196
+ function served(text: string, loads: Load[], id: string, rev: string): string {
1197
+ const parts: string[] = [];
1198
+ let at = 0;
1199
+
1200
+ // In one pass, front to back: a slice of the whole text for each load would grow with their count times the size.
1201
+ for (const load of [...loads].sort((a, b) => a.start - b.start)) {
1202
+ const address = `${themeAddress(id, rev, load.file)}${load.fragment === undefined ? "" : `#${load.fragment}`}`;
1203
+
1204
+ parts.push(text.slice(at, load.start), load.quoted ? `"${address}"` : `url("${address}")`);
1205
+ at = load.end;
1206
+ }
1207
+
1208
+ parts.push(text.slice(at));
1209
+
1210
+ return parts.join("");
1211
+ }