@peaske7/readit 0.3.0-rc.0 → 0.3.0-rc.2

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 (374) hide show
  1. package/README.md +3 -3
  2. package/dist/.vite/manifest.json +1111 -0
  3. package/dist/assets/_basePickBy-BMMA4Tou.js +1 -0
  4. package/dist/assets/_baseUniq-D40qku1I.js +1 -0
  5. package/dist/assets/arc-Ckg65iy8.js +1 -0
  6. package/dist/assets/architecture-YZFGNWBL-Dv3EY0zV.js +1 -0
  7. package/dist/assets/architectureDiagram-Q4EWVU46-DQnkwSaB.js +36 -0
  8. package/dist/assets/array-Bjz-wYpJ.js +1 -0
  9. package/dist/assets/blockDiagram-DXYQGD6D-UB6_S1lm.js +132 -0
  10. package/dist/assets/c4Diagram-AHTNJAMY-sn3k2GND.js +10 -0
  11. package/dist/assets/channel-D9wPw2fQ.js +1 -0
  12. package/dist/assets/chunk-2KRD3SAO-DaFfaCGO.js +1 -0
  13. package/dist/assets/chunk-336JU56O-C8siO5Of.js +2 -0
  14. package/dist/assets/chunk-426QAEUC-BB478m3j.js +1 -0
  15. package/dist/assets/chunk-4BX2VUAB-DRuTD7x5.js +1 -0
  16. package/dist/assets/chunk-4TB4RGXK-_l6jvVAY.js +206 -0
  17. package/dist/assets/chunk-55IACEB6-BExiaAoD.js +1 -0
  18. package/dist/assets/chunk-5FUZZQ4R-HOSFTxuG.js +62 -0
  19. package/dist/assets/chunk-5PVQY5BW-BRVNNRAX.js +2 -0
  20. package/dist/assets/chunk-67CJDMHE-DMt8LNEX.js +1 -0
  21. package/dist/assets/chunk-7N4EOEYR-CzLGefVf.js +1 -0
  22. package/dist/assets/chunk-AA7GKIK3-B6GFAk4U.js +1 -0
  23. package/dist/assets/chunk-BSJP7CBP-BK29yehL.js +1 -0
  24. package/dist/assets/chunk-CIAEETIT-D7hBXImP.js +1 -0
  25. package/dist/assets/chunk-Dlc7tRH4.js +1 -0
  26. package/dist/assets/chunk-EDXVE4YY-CSvKh9DT.js +1 -0
  27. package/dist/assets/chunk-ENJZ2VHE-QApb5cYr.js +10 -0
  28. package/dist/assets/chunk-FMBD7UC4-2FWyCCAV.js +15 -0
  29. package/dist/assets/chunk-FOC6F5B3-DKFHrt4K.js +1 -0
  30. package/dist/assets/chunk-ICPOFSXX-agBjBxsW.js +122 -0
  31. package/dist/assets/chunk-K5T4RW27-D51O7IkG.js +94 -0
  32. package/dist/assets/chunk-KGLVRYIC-DMHSCH4T.js +1 -0
  33. package/dist/assets/chunk-LIHQZDEY-C2aANxt9.js +1 -0
  34. package/dist/assets/chunk-ORNJ4GCN-Db_37NRX.js +1 -0
  35. package/dist/assets/chunk-OYMX7WX6-HGUtT2Q9.js +231 -0
  36. package/dist/assets/chunk-QZHKN3VN-8Lcg9gti.js +1 -0
  37. package/dist/assets/chunk-U2HBQHQK-BFYYQeuC.js +70 -0
  38. package/dist/assets/chunk-X2U36JSP-p8ehTP6s.js +1 -0
  39. package/dist/assets/chunk-XPW4576I-Bqbompq4.js +32 -0
  40. package/dist/assets/chunk-YZCP3GAM-HIMez9pG.js +1 -0
  41. package/dist/assets/chunk-ZZ45TVLE-DRIE_0bu.js +1 -0
  42. package/dist/assets/classDiagram-6PBFFD2Q-BawhEeUl.js +1 -0
  43. package/dist/assets/classDiagram-v2-HSJHXN6E-CLNjgH9n.js +1 -0
  44. package/dist/assets/clone-BBjvuERA.js +1 -0
  45. package/dist/assets/cose-bilkent-S5V4N54A-q90QeGKv.js +1 -0
  46. package/dist/assets/cytoscape.esm-BfXff3fb.js +321 -0
  47. package/dist/assets/dagre-Dxbob2Lr.js +1 -0
  48. package/dist/assets/dagre-KV5264BT-BuvpNxMw.js +4 -0
  49. package/dist/assets/defaultLocale-BwmRmqJp.js +1 -0
  50. package/dist/assets/diagram-5BDNPKRD-DQLsxwwt.js +10 -0
  51. package/dist/assets/diagram-G4DWMVQ6-Jv9Eefw4.js +24 -0
  52. package/dist/assets/diagram-MMDJMWI5-D-0YgNhU.js +43 -0
  53. package/dist/assets/diagram-TYMM5635-BHwO7zQG.js +24 -0
  54. package/dist/assets/dist-BNz65Ibc.js +1 -0
  55. package/dist/assets/erDiagram-SMLLAGMA-BjZGGBJz.js +85 -0
  56. package/dist/assets/flowDiagram-DWJPFMVM-CFbFUm_m.js +162 -0
  57. package/dist/assets/ganttDiagram-T4ZO3ILL-CXk4TcBi.js +292 -0
  58. package/dist/assets/gitGraph-7Q5UKJZL-BGFRt2qs.js +1 -0
  59. package/dist/assets/gitGraphDiagram-UUTBAWPF-C8yZOxjo.js +106 -0
  60. package/dist/assets/graphlib-DGcD9J2L.js +1 -0
  61. package/dist/assets/index-D-m0LiFI.js +14 -0
  62. package/dist/assets/index-DANHO6J0.css +2 -0
  63. package/dist/assets/info-OMHHGYJF-DI6-Z9vh.js +1 -0
  64. package/dist/assets/infoDiagram-42DDH7IO-p-PXDra2.js +2 -0
  65. package/dist/assets/init-TPm5RB77.js +1 -0
  66. package/dist/assets/isArrayLikeObject-69BLnVNM.js +1 -0
  67. package/dist/assets/isEmpty-DUS28g5f.js +1 -0
  68. package/dist/assets/ishikawaDiagram-UXIWVN3A-BrIoEvtb.js +70 -0
  69. package/dist/assets/journeyDiagram-VCZTEJTY-aZpvKa9g.js +139 -0
  70. package/dist/assets/kanban-definition-6JOO6SKY-CoOAY9ji.js +89 -0
  71. package/dist/assets/katex-5SGEXwpi.js +261 -0
  72. package/dist/assets/line-4MF1lR4d.js +1 -0
  73. package/dist/assets/linear-CXMqTN8N.js +1 -0
  74. package/dist/assets/mermaid-config-C8a4L22x.js +1 -0
  75. package/dist/assets/mermaid-parser.core-DREsY2u4.js +4 -0
  76. package/dist/assets/mermaid.core-8ysLpTJi.js +11 -0
  77. package/dist/assets/mindmap-definition-QFDTVHPH-CsqUJCMn.js +96 -0
  78. package/dist/assets/ordinal-D7l-8DAO.js +1 -0
  79. package/dist/assets/packet-4T2RLAQJ-DidW3JFc.js +1 -0
  80. package/dist/assets/path-BVpCanzE.js +1 -0
  81. package/dist/assets/pie-ZZUOXDRM-Bff2e5hg.js +1 -0
  82. package/dist/assets/pieDiagram-DEJITSTG-k0Br4NDS.js +30 -0
  83. package/dist/assets/quadrantDiagram-34T5L4WZ-Be9oCSza.js +7 -0
  84. package/dist/assets/radar-PYXPWWZC-CsdZBH3M.js +1 -0
  85. package/dist/assets/requirementDiagram-MS252O5E-8ECT7dEs.js +84 -0
  86. package/dist/assets/rough.esm-BoTisKeL.js +1 -0
  87. package/dist/assets/sankeyDiagram-XADWPNL6-CoKpeJJ0.js +10 -0
  88. package/dist/assets/sequenceDiagram-FGHM5R23-BTT2fFxG.js +157 -0
  89. package/dist/assets/src-CrmkjRpa.js +1 -0
  90. package/dist/assets/stateDiagram-FHFEXIEX-CIF47NYe.js +1 -0
  91. package/dist/assets/stateDiagram-v2-QKLJ7IA2-Cy1rmPfG.js +1 -0
  92. package/dist/assets/timeline-definition-GMOUNBTQ-Bes4B58n.js +120 -0
  93. package/dist/assets/treeView-SZITEDCU-DPKseaET.js +1 -0
  94. package/dist/assets/treemap-W4RFUUIX-DH-7GZe_.js +1 -0
  95. package/dist/assets/vennDiagram-DHZGUBPP-3wx2huKk.js +34 -0
  96. package/dist/assets/wardley-RL74JXVD-AgyXyBN5.js +1 -0
  97. package/dist/assets/wardleyDiagram-NUSXRM2D-DzViT1Yx.js +20 -0
  98. package/dist/assets/xychartDiagram-5P7HB3ND-BO_dbU0r.js +7 -0
  99. package/{index.html → dist/index.html} +2 -1
  100. package/dist/index.js +2625 -0
  101. package/package.json +11 -1
  102. package/.agents/skills/remotion-best-practices/SKILL.md +0 -61
  103. package/.agents/skills/remotion-best-practices/rules/3d.md +0 -86
  104. package/.agents/skills/remotion-best-practices/rules/animations.md +0 -27
  105. package/.agents/skills/remotion-best-practices/rules/assets/charts-bar-chart.tsx +0 -178
  106. package/.agents/skills/remotion-best-practices/rules/assets/text-animations-typewriter.tsx +0 -100
  107. package/.agents/skills/remotion-best-practices/rules/assets/text-animations-word-highlight.tsx +0 -108
  108. package/.agents/skills/remotion-best-practices/rules/assets.md +0 -78
  109. package/.agents/skills/remotion-best-practices/rules/audio-visualization.md +0 -198
  110. package/.agents/skills/remotion-best-practices/rules/audio.md +0 -169
  111. package/.agents/skills/remotion-best-practices/rules/calculate-metadata.md +0 -134
  112. package/.agents/skills/remotion-best-practices/rules/can-decode.md +0 -75
  113. package/.agents/skills/remotion-best-practices/rules/charts.md +0 -120
  114. package/.agents/skills/remotion-best-practices/rules/compositions.md +0 -154
  115. package/.agents/skills/remotion-best-practices/rules/display-captions.md +0 -184
  116. package/.agents/skills/remotion-best-practices/rules/extract-frames.md +0 -229
  117. package/.agents/skills/remotion-best-practices/rules/ffmpeg.md +0 -38
  118. package/.agents/skills/remotion-best-practices/rules/fonts.md +0 -152
  119. package/.agents/skills/remotion-best-practices/rules/get-audio-duration.md +0 -58
  120. package/.agents/skills/remotion-best-practices/rules/get-video-dimensions.md +0 -68
  121. package/.agents/skills/remotion-best-practices/rules/get-video-duration.md +0 -60
  122. package/.agents/skills/remotion-best-practices/rules/gifs.md +0 -141
  123. package/.agents/skills/remotion-best-practices/rules/images.md +0 -134
  124. package/.agents/skills/remotion-best-practices/rules/import-srt-captions.md +0 -69
  125. package/.agents/skills/remotion-best-practices/rules/light-leaks.md +0 -73
  126. package/.agents/skills/remotion-best-practices/rules/lottie.md +0 -70
  127. package/.agents/skills/remotion-best-practices/rules/maps.md +0 -412
  128. package/.agents/skills/remotion-best-practices/rules/measuring-dom-nodes.md +0 -34
  129. package/.agents/skills/remotion-best-practices/rules/measuring-text.md +0 -140
  130. package/.agents/skills/remotion-best-practices/rules/parameters.md +0 -109
  131. package/.agents/skills/remotion-best-practices/rules/sequencing.md +0 -118
  132. package/.agents/skills/remotion-best-practices/rules/sfx.md +0 -26
  133. package/.agents/skills/remotion-best-practices/rules/subtitles.md +0 -36
  134. package/.agents/skills/remotion-best-practices/rules/tailwind.md +0 -11
  135. package/.agents/skills/remotion-best-practices/rules/text-animations.md +0 -20
  136. package/.agents/skills/remotion-best-practices/rules/timing.md +0 -179
  137. package/.agents/skills/remotion-best-practices/rules/transcribe-captions.md +0 -70
  138. package/.agents/skills/remotion-best-practices/rules/transitions.md +0 -197
  139. package/.agents/skills/remotion-best-practices/rules/transparent-videos.md +0 -106
  140. package/.agents/skills/remotion-best-practices/rules/trimming.md +0 -51
  141. package/.agents/skills/remotion-best-practices/rules/videos.md +0 -171
  142. package/.agents/skills/remotion-best-practices/rules/voiceover.md +0 -99
  143. package/.agents/skills/simple/SKILL.md +0 -52
  144. package/.agents/skills/vercel-react-best-practices/AGENTS.md +0 -3254
  145. package/.agents/skills/vercel-react-best-practices/README.md +0 -123
  146. package/.agents/skills/vercel-react-best-practices/SKILL.md +0 -141
  147. package/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +0 -55
  148. package/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md +0 -42
  149. package/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md +0 -39
  150. package/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md +0 -38
  151. package/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md +0 -80
  152. package/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md +0 -51
  153. package/.agents/skills/vercel-react-best-practices/rules/async-parallel.md +0 -28
  154. package/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +0 -99
  155. package/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +0 -59
  156. package/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md +0 -31
  157. package/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +0 -49
  158. package/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +0 -35
  159. package/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md +0 -50
  160. package/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md +0 -74
  161. package/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md +0 -71
  162. package/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md +0 -48
  163. package/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md +0 -56
  164. package/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +0 -107
  165. package/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md +0 -80
  166. package/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md +0 -28
  167. package/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md +0 -70
  168. package/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md +0 -32
  169. package/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md +0 -50
  170. package/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md +0 -60
  171. package/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +0 -45
  172. package/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md +0 -37
  173. package/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md +0 -49
  174. package/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md +0 -82
  175. package/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +0 -24
  176. package/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +0 -57
  177. package/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md +0 -26
  178. package/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +0 -47
  179. package/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +0 -40
  180. package/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +0 -38
  181. package/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +0 -46
  182. package/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +0 -82
  183. package/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md +0 -30
  184. package/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md +0 -85
  185. package/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md +0 -68
  186. package/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +0 -28
  187. package/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md +0 -75
  188. package/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md +0 -39
  189. package/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md +0 -45
  190. package/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md +0 -40
  191. package/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md +0 -29
  192. package/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md +0 -74
  193. package/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md +0 -58
  194. package/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md +0 -38
  195. package/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md +0 -44
  196. package/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md +0 -45
  197. package/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md +0 -82
  198. package/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md +0 -35
  199. package/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md +0 -40
  200. package/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md +0 -73
  201. package/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md +0 -73
  202. package/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md +0 -96
  203. package/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md +0 -41
  204. package/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md +0 -76
  205. package/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md +0 -65
  206. package/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md +0 -142
  207. package/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md +0 -83
  208. package/.agents/skills/vercel-react-best-practices/rules/server-serialization.md +0 -38
  209. package/.claude/CLAUDE.md +0 -184
  210. package/.claude/commands/review.md +0 -120
  211. package/.claude/commands/sync-docs.md +0 -71
  212. package/.claude/roadmap.md +0 -121
  213. package/.claude/rules/style-guide.md +0 -830
  214. package/.claude/settings.json +0 -18
  215. package/.claude/user-stories.md +0 -333
  216. package/AGENTS.md +0 -68
  217. package/Makefile +0 -32
  218. package/biome.json +0 -79
  219. package/bun.lock +0 -854
  220. package/bunfig.toml +0 -2
  221. package/docs/design.md +0 -563
  222. package/docs/perf-baseline.md +0 -130
  223. package/docs/plans/2026-03-13-client-mode-design.md +0 -86
  224. package/docs/plans/2026-03-13-client-mode-plan.md +0 -605
  225. package/docs/plans/2026-03-13-keyboard-shortcuts-design.md +0 -129
  226. package/docs/plans/2026-03-13-keyboard-shortcuts-plan.md +0 -1471
  227. package/docs/plans/2026-03-13-multi-document-design.md +0 -183
  228. package/docs/plans/2026-03-13-performance-benchmarks-design.md +0 -121
  229. package/docs/superpowers/plans/2026-03-26-surgical-pruning.md +0 -1176
  230. package/docs/superpowers/specs/2026-03-27-go-server-rewrite-design.md +0 -284
  231. package/e2e/comments.spec.ts +0 -81
  232. package/e2e/document-load.spec.ts +0 -32
  233. package/e2e/export.spec.ts +0 -58
  234. package/e2e/fixtures/sample.md +0 -7
  235. package/e2e/perf/add-comment.spec.ts +0 -116
  236. package/e2e/perf/fixtures/generate.ts +0 -327
  237. package/e2e/perf/initial-load.spec.ts +0 -49
  238. package/e2e/perf/perf.setup.ts +0 -23
  239. package/e2e/perf/perf.teardown.ts +0 -9
  240. package/e2e/perf/screenshot-final.png +0 -0
  241. package/e2e/perf/scroll.spec.ts +0 -39
  242. package/e2e/perf/tab-switch.spec.ts +0 -69
  243. package/e2e/perf/text-selection.spec.ts +0 -119
  244. package/e2e/perf/utils/metrics.ts +0 -350
  245. package/e2e/perf/utils/perf-cli.ts +0 -86
  246. package/e2e/persistence-file.spec.ts +0 -357
  247. package/e2e/utils/cli.ts +0 -84
  248. package/e2e/utils/selection.ts +0 -79
  249. package/go/cmd/readit/main.go +0 -416
  250. package/go/go.mod +0 -20
  251. package/go/go.sum +0 -41
  252. package/go/internal/server/anchor.go +0 -302
  253. package/go/internal/server/anchor_test.go +0 -111
  254. package/go/internal/server/comments.go +0 -390
  255. package/go/internal/server/documents.go +0 -113
  256. package/go/internal/server/embed.go +0 -17
  257. package/go/internal/server/headings.go +0 -33
  258. package/go/internal/server/headings_test.go +0 -75
  259. package/go/internal/server/htmltext.go +0 -123
  260. package/go/internal/server/markdown.go +0 -157
  261. package/go/internal/server/markdown_bench_test.go +0 -42
  262. package/go/internal/server/markdown_test.go +0 -79
  263. package/go/internal/server/server.go +0 -453
  264. package/go/internal/server/server_bench_test.go +0 -122
  265. package/go/internal/server/settings.go +0 -110
  266. package/go/internal/server/sse.go +0 -140
  267. package/go/internal/server/storage.go +0 -275
  268. package/go/internal/server/storage_test.go +0 -152
  269. package/go/internal/server/template.go +0 -66
  270. package/go/internal/server/types.go +0 -101
  271. package/go/internal/server/watcher.go +0 -74
  272. package/lefthook.yml +0 -8
  273. package/nvim-readit/lua/readit/health.lua +0 -64
  274. package/nvim-readit/lua/readit/init.lua +0 -463
  275. package/nvim-readit/plugin/readit.lua +0 -19
  276. package/playwright.config.ts +0 -34
  277. package/skills-lock.json +0 -20
  278. package/src/App.svelte +0 -890
  279. package/src/cli.ts +0 -881
  280. package/src/components/ActionsMenu.svelte +0 -95
  281. package/src/components/CommentBadge.svelte +0 -67
  282. package/src/components/CommentErrorBanner.svelte +0 -33
  283. package/src/components/CommentInput.svelte +0 -75
  284. package/src/components/CommentListItem.svelte +0 -95
  285. package/src/components/CommentManager.svelte +0 -129
  286. package/src/components/CommentNav.svelte +0 -109
  287. package/src/components/DocumentViewer.svelte +0 -233
  288. package/src/components/FloatingComment.svelte +0 -107
  289. package/src/components/Header.svelte +0 -76
  290. package/src/components/InlineEditor.svelte +0 -72
  291. package/src/components/MarginNote.svelte +0 -167
  292. package/src/components/MarginNotesContainer.svelte +0 -33
  293. package/src/components/MermaidEnhancer.svelte +0 -218
  294. package/src/components/MermaidModal.svelte +0 -67
  295. package/src/components/RawModal.svelte +0 -126
  296. package/src/components/ReanchorConfirm.svelte +0 -30
  297. package/src/components/SettingsModal.svelte +0 -220
  298. package/src/components/ShortcutCapture.svelte +0 -82
  299. package/src/components/ShortcutList.svelte +0 -145
  300. package/src/components/TabBar.svelte +0 -52
  301. package/src/components/TableOfContents.svelte +0 -125
  302. package/src/components/ui/ActionLink.svelte +0 -40
  303. package/src/components/ui/Button.svelte +0 -53
  304. package/src/components/ui/Dialog.svelte +0 -97
  305. package/src/components/ui/DropdownMenu.svelte +0 -85
  306. package/src/components/ui/DropdownMenuItem.svelte +0 -38
  307. package/src/components/ui/DropdownMenuSeparator.svelte +0 -11
  308. package/src/components/ui/Text.svelte +0 -42
  309. package/src/env.d.ts +0 -6
  310. package/src/index.css +0 -859
  311. package/src/lib/__fixtures__/bench-data.ts +0 -114
  312. package/src/lib/anchor.bench.ts +0 -91
  313. package/src/lib/anchor.test.ts +0 -527
  314. package/src/lib/anchor.ts +0 -381
  315. package/src/lib/comment-storage.bench.ts +0 -49
  316. package/src/lib/comment-storage.test.ts +0 -694
  317. package/src/lib/comment-storage.ts +0 -226
  318. package/src/lib/export.bench.ts +0 -21
  319. package/src/lib/export.ts +0 -36
  320. package/src/lib/fetch-or-throw.test.ts +0 -59
  321. package/src/lib/fetch-or-throw.ts +0 -12
  322. package/src/lib/headings.test.ts +0 -103
  323. package/src/lib/headings.ts +0 -44
  324. package/src/lib/highlight/core.test.ts +0 -93
  325. package/src/lib/highlight/dom.ts +0 -187
  326. package/src/lib/highlight/highlight-registry.ts +0 -221
  327. package/src/lib/highlight/highlight.bench.ts +0 -92
  328. package/src/lib/highlight/highlighter.ts +0 -247
  329. package/src/lib/highlight/resolver.ts +0 -38
  330. package/src/lib/highlight/types.ts +0 -17
  331. package/src/lib/html-text.test.ts +0 -162
  332. package/src/lib/html-text.ts +0 -161
  333. package/src/lib/i18n/en.ts +0 -124
  334. package/src/lib/i18n/index.ts +0 -3
  335. package/src/lib/i18n/ja.ts +0 -126
  336. package/src/lib/i18n/translations.ts +0 -27
  337. package/src/lib/i18n/types.ts +0 -130
  338. package/src/lib/key-lock.test.ts +0 -104
  339. package/src/lib/key-lock.ts +0 -23
  340. package/src/lib/margin-layout.bench.ts +0 -61
  341. package/src/lib/margin-layout.ts +0 -71
  342. package/src/lib/markdown-renderer.test.ts +0 -154
  343. package/src/lib/markdown-renderer.ts +0 -178
  344. package/src/lib/mermaid-config.ts +0 -38
  345. package/src/lib/mermaid-renderer.ts +0 -162
  346. package/src/lib/mermaid-worker.ts +0 -60
  347. package/src/lib/positions.ts +0 -157
  348. package/src/lib/shortcut-registry.ts +0 -244
  349. package/src/lib/utils.ts +0 -15
  350. package/src/main.ts +0 -16
  351. package/src/schema.ts +0 -92
  352. package/src/server.ts +0 -1216
  353. package/src/stores/app.svelte.ts +0 -231
  354. package/src/stores/locale.svelte.ts +0 -46
  355. package/src/stores/settings.svelte.ts +0 -90
  356. package/src/stores/shortcuts.svelte.ts +0 -104
  357. package/src/stores/ui.svelte.ts +0 -12
  358. package/src/template.ts +0 -104
  359. package/src/test-setup.ts +0 -48
  360. package/svelte.config.js +0 -5
  361. package/test.md +0 -74
  362. package/tsconfig.cli.json +0 -12
  363. package/tsconfig.json +0 -20
  364. package/vite.config.ts +0 -47
  365. package/vitest.config.ts +0 -15
  366. package/vscode-readit/.mcp.json +0 -7
  367. package/vscode-readit/.vscodeignore +0 -7
  368. package/vscode-readit/bun.lock +0 -78
  369. package/vscode-readit/icon.svg +0 -10
  370. package/vscode-readit/package.json +0 -110
  371. package/vscode-readit/src/extension.ts +0 -117
  372. package/vscode-readit/src/server-manager.ts +0 -272
  373. package/vscode-readit/src/webview-provider.ts +0 -204
  374. package/vscode-readit/tsconfig.json +0 -20
package/src/server.ts DELETED
@@ -1,1216 +0,0 @@
1
- import { type FSWatcher, watch } from "node:fs";
2
- import * as fs from "node:fs/promises";
3
- import * as os from "node:os";
4
- import * as path from "node:path";
5
- import { basename, dirname, join } from "node:path";
6
- import { findAnchorWithFallback } from "./lib/anchor.js";
7
- import {
8
- computeHash,
9
- createComment,
10
- getCommentPath,
11
- getLineHint,
12
- parseCommentFile,
13
- serializeComments,
14
- truncateSelection,
15
- } from "./lib/comment-storage.js";
16
- import { findTextPosition } from "./lib/highlight/resolver.js";
17
- import { extractTextFromHtml } from "./lib/html-text.js";
18
- import { createKeyLock } from "./lib/key-lock.js";
19
- import { getShiki, renderMarkdown } from "./lib/markdown-renderer.js";
20
- import { disposeMermaidWorker } from "./lib/mermaid-renderer.js";
21
- import { isMarkdownFile } from "./lib/utils.js";
22
- import {
23
- AnchorConfidences,
24
- type Comment,
25
- type DocumentSettings,
26
- FontFamilies,
27
- type FontFamily,
28
- } from "./schema.js";
29
- import { renderTemplate } from "./template.js";
30
-
31
- function isErrnoException(err: unknown): err is NodeJS.ErrnoException {
32
- return err instanceof Error && "code" in err;
33
- }
34
-
35
- export interface FileEntry {
36
- content?: string;
37
- filePath: string;
38
- }
39
-
40
- export interface ServerOptions {
41
- files: FileEntry[];
42
- port: number;
43
- host: string;
44
- clean?: boolean;
45
- }
46
-
47
- export interface ServerResult {
48
- port: number;
49
- url: string;
50
- server: { stop(): void };
51
- }
52
-
53
- interface ResolvedCommentsCacheEntry {
54
- commentMtimeMs: number;
55
- sourceHash: string;
56
- comments: Comment[];
57
- }
58
-
59
- const resolvedCommentsCache = new Map<string, ResolvedCommentsCacheEntry>();
60
-
61
- function invalidateResolvedComments(filePath: string): void {
62
- resolvedCommentsCache.delete(filePath);
63
- }
64
-
65
- const withCommentLock = createKeyLock("comments");
66
-
67
- async function canonicalPath(filePath: string): Promise<string> {
68
- return fs.realpath(path.resolve(filePath));
69
- }
70
-
71
- async function readCommentsFromFile(
72
- filePath: string,
73
- sourceContent: string,
74
- renderedHtml?: string,
75
- ): Promise<Comment[]> {
76
- const commentPath = getCommentPath(filePath);
77
- const sourceHash = computeHash(sourceContent);
78
-
79
- try {
80
- const stats = await fs.stat(commentPath);
81
- const cached = resolvedCommentsCache.get(filePath);
82
- if (
83
- cached &&
84
- cached.sourceHash === sourceHash &&
85
- cached.commentMtimeMs === stats.mtimeMs
86
- ) {
87
- return cached.comments;
88
- }
89
-
90
- const content = await fs.readFile(commentPath, "utf-8");
91
- const file = parseCommentFile(content);
92
-
93
- const domText = renderedHtml ? extractTextFromHtml(renderedHtml) : null;
94
-
95
- const resolvedComments = file.comments.map((comment) => {
96
- const textForMatching = comment.anchorPrefix || comment.selectedText;
97
-
98
- const anchor = findAnchorWithFallback({
99
- source: sourceContent,
100
- selectedText: textForMatching,
101
- lineHint: comment.lineHint || "L1",
102
- });
103
-
104
- if (!anchor) {
105
- return {
106
- ...comment,
107
- anchorConfidence: AnchorConfidences.UNRESOLVED,
108
- };
109
- }
110
-
111
- let startOffset = anchor.start;
112
- let endOffset = anchor.end;
113
-
114
- if (domText) {
115
- const domPos = findTextPosition(
116
- domText,
117
- comment.selectedText,
118
- anchor.start,
119
- );
120
- if (domPos) {
121
- startOffset = domPos.start;
122
- endOffset = domPos.end;
123
- }
124
- }
125
-
126
- return {
127
- ...comment,
128
- startOffset,
129
- endOffset,
130
- lineHint: `L${anchor.line}`,
131
- anchorConfidence: anchor.confidence,
132
- };
133
- });
134
-
135
- resolvedCommentsCache.set(filePath, {
136
- sourceHash,
137
- commentMtimeMs: stats.mtimeMs,
138
- comments: resolvedComments,
139
- });
140
-
141
- return resolvedComments;
142
- } catch (err) {
143
- if (isErrnoException(err) && err.code === "ENOENT") {
144
- invalidateResolvedComments(filePath);
145
- return [];
146
- }
147
- throw err;
148
- }
149
- }
150
-
151
- async function writeCommentsToFile(
152
- filePath: string,
153
- sourceContent: string,
154
- comments: Comment[],
155
- ): Promise<void> {
156
- const commentPath = getCommentPath(filePath);
157
- const commentDir = dirname(commentPath);
158
-
159
- await fs.mkdir(commentDir, { recursive: true });
160
-
161
- const file = {
162
- source: filePath,
163
- hash: computeHash(sourceContent),
164
- version: 1,
165
- comments,
166
- };
167
-
168
- const content = serializeComments(file);
169
- const tempPath = `${commentPath}.tmp`;
170
- await fs.writeFile(tempPath, content, "utf-8");
171
- await fs.rename(tempPath, commentPath);
172
- invalidateResolvedComments(filePath);
173
- }
174
-
175
- async function deleteCommentFile(filePath: string): Promise<void> {
176
- const commentPath = getCommentPath(filePath);
177
- try {
178
- await fs.unlink(commentPath);
179
- } catch (err) {
180
- if (!isErrnoException(err) || err.code !== "ENOENT") {
181
- throw err;
182
- }
183
- }
184
- invalidateResolvedComments(filePath);
185
- }
186
-
187
- const SETTINGS_PATH = path.join(os.homedir(), ".readit", "settings.json");
188
-
189
- const DEFAULT_SETTINGS: DocumentSettings = {
190
- version: 1,
191
- fontFamily: FontFamilies.SERIF,
192
- };
193
-
194
- async function readSettings(): Promise<DocumentSettings> {
195
- try {
196
- const content = await fs.readFile(SETTINGS_PATH, "utf-8");
197
- return JSON.parse(content) as DocumentSettings;
198
- } catch (err) {
199
- if (isErrnoException(err) && err.code === "ENOENT") {
200
- return DEFAULT_SETTINGS;
201
- }
202
- throw err;
203
- }
204
- }
205
-
206
- async function writeSettings(settings: DocumentSettings): Promise<void> {
207
- const settingsDir = dirname(SETTINGS_PATH);
208
- await fs.mkdir(settingsDir, { recursive: true });
209
-
210
- const tempPath = `${SETTINGS_PATH}.tmp`;
211
- await fs.writeFile(tempPath, JSON.stringify(settings, null, 2), "utf-8");
212
- await fs.rename(tempPath, SETTINGS_PATH);
213
- }
214
-
215
- function isValidFontFamily(value: unknown): value is FontFamily {
216
- return value === FontFamilies.SERIF || value === FontFamilies.SANS_SERIF;
217
- }
218
-
219
- export const SERVER_INFO_PATH = path.join(
220
- os.homedir(),
221
- ".readit",
222
- "server.json",
223
- );
224
-
225
- async function writeServerInfo(port: number): Promise<void> {
226
- await fs.mkdir(path.dirname(SERVER_INFO_PATH), { recursive: true });
227
- await fs.writeFile(
228
- SERVER_INFO_PATH,
229
- JSON.stringify({ port, pid: process.pid }),
230
- "utf-8",
231
- );
232
- }
233
-
234
- export async function removeServerInfo(): Promise<void> {
235
- try {
236
- await fs.unlink(SERVER_INFO_PATH);
237
- } catch (err) {
238
- if (!isErrnoException(err) || err.code !== "ENOENT") {
239
- console.error("Failed to remove server info:", err);
240
- }
241
- }
242
- }
243
-
244
- function json(data: unknown, status = 200): Response {
245
- return Response.json(data, { status });
246
- }
247
-
248
- function errorResponse(message: string, status: number): Response {
249
- return Response.json({ error: message }, { status });
250
- }
251
-
252
- function errorWithDetail(
253
- message: string,
254
- err: unknown,
255
- status = 500,
256
- ): Response {
257
- const detail = err instanceof Error ? err.message : String(err);
258
- return errorResponse(`${message}: ${detail}`, status);
259
- }
260
-
261
- interface RouteContext {
262
- filePath: string;
263
- getCurrentContent: () => Promise<string>;
264
- }
265
-
266
- async function getComments(
267
- ctx: RouteContext,
268
- renderedHtml?: string,
269
- ): Promise<Response> {
270
- try {
271
- const currentContent = await ctx.getCurrentContent();
272
- const comments = await readCommentsFromFile(
273
- ctx.filePath,
274
- currentContent,
275
- renderedHtml,
276
- );
277
- return json({ comments });
278
- } catch (err) {
279
- console.error("Failed to read comments:", err);
280
- return errorResponse("Failed to read comments", 500);
281
- }
282
- }
283
-
284
- async function addComment(ctx: RouteContext, req: Request): Promise<Response> {
285
- try {
286
- const {
287
- selectedText,
288
- comment: commentText,
289
- startOffset,
290
- endOffset,
291
- } = await req.json();
292
-
293
- if (
294
- !selectedText ||
295
- typeof commentText !== "string" ||
296
- startOffset === undefined ||
297
- endOffset === undefined
298
- ) {
299
- return errorResponse("Missing required fields", 400);
300
- }
301
-
302
- const currentContent = await ctx.getCurrentContent();
303
- const newComment = createComment(
304
- selectedText,
305
- commentText,
306
- startOffset,
307
- endOffset,
308
- currentContent,
309
- );
310
-
311
- await withCommentLock(ctx.filePath, async () => {
312
- const existingComments = await readCommentsFromFile(
313
- ctx.filePath,
314
- currentContent,
315
- );
316
- const allComments = [...existingComments, newComment];
317
- await writeCommentsToFile(ctx.filePath, currentContent, allComments);
318
- });
319
-
320
- return json({ comment: newComment }, 201);
321
- } catch (err) {
322
- console.error("Failed to add comment:", err);
323
- return errorWithDetail("Failed to add comment", err);
324
- }
325
- }
326
-
327
- async function updateComment(
328
- ctx: RouteContext,
329
- req: Request,
330
- id: string,
331
- ): Promise<Response> {
332
- try {
333
- const { comment: commentText } = await req.json();
334
-
335
- if (typeof commentText !== "string") {
336
- return errorResponse("Missing comment text", 400);
337
- }
338
-
339
- const currentContent = await ctx.getCurrentContent();
340
- const result = await withCommentLock(ctx.filePath, async () => {
341
- const existingComments = await readCommentsFromFile(
342
- ctx.filePath,
343
- currentContent,
344
- );
345
- const commentIndex = existingComments.findIndex((c) => c.id === id);
346
- if (commentIndex === -1) return null;
347
- const updatedComments = existingComments.map((c, i) =>
348
- i === commentIndex ? { ...c, comment: commentText.trim() } : c,
349
- );
350
- await writeCommentsToFile(ctx.filePath, currentContent, updatedComments);
351
- return updatedComments[commentIndex];
352
- });
353
-
354
- if (!result) return errorResponse("Comment not found", 404);
355
- return json({ comment: result });
356
- } catch (err) {
357
- console.error("Failed to update comment:", err);
358
- return errorWithDetail("Failed to update comment", err);
359
- }
360
- }
361
-
362
- async function deleteComment(ctx: RouteContext, id: string): Promise<Response> {
363
- try {
364
- const currentContent = await ctx.getCurrentContent();
365
- const found = await withCommentLock(ctx.filePath, async () => {
366
- const existingComments = await readCommentsFromFile(
367
- ctx.filePath,
368
- currentContent,
369
- );
370
- const filteredComments = existingComments.filter((c) => c.id !== id);
371
- if (filteredComments.length === existingComments.length) return false;
372
- if (filteredComments.length === 0) {
373
- await deleteCommentFile(ctx.filePath);
374
- } else {
375
- await writeCommentsToFile(
376
- ctx.filePath,
377
- currentContent,
378
- filteredComments,
379
- );
380
- }
381
- return true;
382
- });
383
-
384
- if (!found) return errorResponse("Comment not found", 404);
385
- return json({ success: true });
386
- } catch (err) {
387
- console.error("Failed to delete comment:", err);
388
- return errorWithDetail("Failed to delete comment", err);
389
- }
390
- }
391
-
392
- async function clearComments(ctx: RouteContext): Promise<Response> {
393
- try {
394
- await withCommentLock(ctx.filePath, () => deleteCommentFile(ctx.filePath));
395
- return json({ success: true });
396
- } catch (err) {
397
- console.error("Failed to clear comments:", err);
398
- return errorWithDetail("Failed to clear comments", err);
399
- }
400
- }
401
-
402
- async function getRawComments(ctx: RouteContext): Promise<Response> {
403
- const commentPath = getCommentPath(ctx.filePath);
404
- try {
405
- const content = await fs.readFile(commentPath, "utf-8");
406
- return json({ content, path: commentPath });
407
- } catch (err) {
408
- if (isErrnoException(err) && err.code === "ENOENT") {
409
- return json({ content: null, path: commentPath });
410
- }
411
- console.error("Failed to read raw comments:", err);
412
- return errorResponse("Failed to read raw comments", 500);
413
- }
414
- }
415
-
416
- async function reanchorComment(
417
- ctx: RouteContext,
418
- req: Request,
419
- id: string,
420
- ): Promise<Response> {
421
- try {
422
- const { selectedText, startOffset, endOffset } = await req.json();
423
-
424
- if (!selectedText || startOffset === undefined || endOffset === undefined) {
425
- return errorResponse("Missing required fields", 400);
426
- }
427
-
428
- const currentContent = await ctx.getCurrentContent();
429
- const result = await withCommentLock(ctx.filePath, async () => {
430
- const existingComments = await readCommentsFromFile(
431
- ctx.filePath,
432
- currentContent,
433
- );
434
- const commentIndex = existingComments.findIndex((c) => c.id === id);
435
- if (commentIndex === -1) return null;
436
-
437
- const lineHint = getLineHint(currentContent, startOffset, endOffset);
438
- const truncatedText = truncateSelection(selectedText);
439
- const updatedComment: Comment = {
440
- ...existingComments[commentIndex],
441
- selectedText: truncatedText,
442
- startOffset,
443
- endOffset,
444
- lineHint,
445
- anchorConfidence: AnchorConfidences.EXACT,
446
- anchorPrefix:
447
- selectedText.length > 1000 ? selectedText.slice(0, 200) : undefined,
448
- };
449
- const updatedComments = existingComments.map((c, i) =>
450
- i === commentIndex ? updatedComment : c,
451
- );
452
- await writeCommentsToFile(ctx.filePath, currentContent, updatedComments);
453
- return updatedComment;
454
- });
455
-
456
- if (!result) return errorResponse("Comment not found", 404);
457
- return json({ comment: result });
458
- } catch (err) {
459
- console.error("Failed to re-anchor comment:", err);
460
- return errorWithDetail("Failed to re-anchor comment", err);
461
- }
462
- }
463
-
464
- async function getSettingsRoute(): Promise<Response> {
465
- try {
466
- const settings = await readSettings();
467
- return json(settings);
468
- } catch (err) {
469
- console.error("Failed to read settings:", err);
470
- return errorResponse("Failed to read settings", 500);
471
- }
472
- }
473
-
474
- async function updateSettingsRoute(req: Request): Promise<Response> {
475
- try {
476
- const body = await req.json();
477
- const { fontFamily } = body;
478
-
479
- if (fontFamily !== undefined && !isValidFontFamily(fontFamily)) {
480
- return errorResponse("Invalid font family", 400);
481
- }
482
-
483
- const current = await readSettings();
484
- const settings: DocumentSettings = {
485
- ...current,
486
- ...(fontFamily !== undefined && { fontFamily }),
487
- };
488
-
489
- await writeSettings(settings);
490
- return json(settings);
491
- } catch (err) {
492
- console.error("Failed to save settings:", err);
493
- return errorResponse("Failed to save settings", 500);
494
- }
495
- }
496
-
497
- function createDocumentStream(
498
- sseClients: Set<ReadableStreamDefaultController>,
499
- ): Response {
500
- let pingInterval: ReturnType<typeof setInterval>;
501
- let captured: ReadableStreamDefaultController;
502
-
503
- const stream = new ReadableStream({
504
- start(controller) {
505
- captured = controller;
506
- controller.enqueue("data: connected\n\n");
507
- sseClients.add(controller);
508
- pingInterval = setInterval(() => {
509
- try {
510
- controller.enqueue("data: ping\n\n");
511
- } catch {
512
- clearInterval(pingInterval);
513
- sseClients.delete(controller);
514
- }
515
- }, 5000);
516
- },
517
- cancel() {
518
- clearInterval(pingInterval);
519
- sseClients.delete(captured);
520
- },
521
- });
522
-
523
- return new Response(stream, {
524
- headers: {
525
- "Content-Type": "text/event-stream",
526
- "Cache-Control": "no-cache",
527
- Connection: "keep-alive",
528
- },
529
- });
530
- }
531
-
532
- function createHeartbeat(
533
- onOpen: (controller: ReadableStreamDefaultController) => void,
534
- onClose: (controller: ReadableStreamDefaultController) => void,
535
- ): Response {
536
- let interval: ReturnType<typeof setInterval>;
537
- let captured: ReadableStreamDefaultController;
538
-
539
- const stream = new ReadableStream({
540
- start(controller) {
541
- captured = controller;
542
- controller.enqueue("data: connected\n\n");
543
- onOpen(controller);
544
- interval = setInterval(() => {
545
- try {
546
- controller.enqueue("data: ping\n\n");
547
- } catch {
548
- clearInterval(interval);
549
- onClose(controller);
550
- }
551
- }, 5000);
552
- },
553
- cancel() {
554
- clearInterval(interval);
555
- onClose(captured);
556
- },
557
- });
558
-
559
- return new Response(stream, {
560
- headers: {
561
- "Content-Type": "text/event-stream",
562
- "Cache-Control": "no-cache",
563
- Connection: "keep-alive",
564
- },
565
- });
566
- }
567
-
568
- async function serveStaticFile(
569
- distPath: string,
570
- pathname: string,
571
- ): Promise<Response> {
572
- const filePath = join(distPath, pathname);
573
- const file = Bun.file(filePath);
574
-
575
- if (await file.exists()) {
576
- const isHashed = pathname.startsWith("/assets/");
577
- const headers: Record<string, string> = isHashed
578
- ? { "Cache-Control": "public, max-age=31536000, immutable" }
579
- : {};
580
- return new Response(file, { headers });
581
- }
582
-
583
- const indexFile = Bun.file(join(distPath, "index.html"));
584
- if (await indexFile.exists()) {
585
- return new Response(indexFile);
586
- }
587
-
588
- return new Response("Not Found", { status: 404 });
589
- }
590
-
591
- const VITE_DEV_PORT = 24678;
592
- const VITE_DEV_ORIGIN = `http://127.0.0.1:${VITE_DEV_PORT}`;
593
-
594
- async function proxyToVite(
595
- req: Request,
596
- pathname: string,
597
- search: string,
598
- ): Promise<Response> {
599
- const target = `${VITE_DEV_ORIGIN}${pathname}${search}`;
600
- try {
601
- return await fetch(
602
- new Request(target, {
603
- method: req.method,
604
- headers: req.headers,
605
- body: req.body,
606
- redirect: "manual",
607
- }),
608
- );
609
- } catch {
610
- return new Response("Vite dev server not available", { status: 502 });
611
- }
612
- }
613
-
614
- async function isViteReady(): Promise<boolean> {
615
- try {
616
- const res = await fetch(`${VITE_DEV_ORIGIN}/`);
617
- return res.ok;
618
- } catch {
619
- return false;
620
- }
621
- }
622
-
623
- async function spawnViteDev(): Promise<() => void> {
624
- if (await isViteReady()) {
625
- return () => {};
626
- }
627
-
628
- const child = Bun.spawn(
629
- ["bunx", "vite", "--port", String(VITE_DEV_PORT), "--strictPort"],
630
- { stdout: "ignore", stderr: "inherit" },
631
- );
632
-
633
- const maxWaitMs = 10_000;
634
- const start = Date.now();
635
- while (Date.now() - start < maxWaitMs) {
636
- if (await isViteReady()) break;
637
- await new Promise((r) => setTimeout(r, 200));
638
- }
639
-
640
- return () => {
641
- child.kill();
642
- };
643
- }
644
-
645
- function extractCommentId(pathname: string): string | undefined {
646
- const match = pathname.match(/^\/api\/comments\/([^/]+)/);
647
- return match?.[1];
648
- }
649
-
650
- interface FileState {
651
- content: string | null;
652
- renderedHtml: string | null;
653
- headings: import("./lib/headings").Heading[] | null;
654
- isLoaded: boolean;
655
- debounceTimer: ReturnType<typeof setTimeout> | null;
656
- }
657
-
658
- interface ServerWithWatchers {
659
- server: ReturnType<typeof Bun.serve>;
660
- watchers: FSWatcher[];
661
- }
662
-
663
- function createServer(options: ServerOptions): ServerWithWatchers {
664
- const fileMap = new Map<string, FileState>();
665
- const fileOrder: string[] = [];
666
-
667
- for (const entry of options.files) {
668
- fileMap.set(entry.filePath, {
669
- content: entry.content ?? null,
670
- renderedHtml: null,
671
- headings: null,
672
- isLoaded: entry.content !== undefined,
673
- debounceTimer: null,
674
- });
675
- fileOrder.push(entry.filePath);
676
-
677
- if (options.clean) {
678
- const commentPath = getCommentPath(entry.filePath);
679
- fs.unlink(commentPath).catch(() => {});
680
- invalidateResolvedComments(entry.filePath);
681
- }
682
- }
683
-
684
- const defaultPath = fileOrder[0];
685
- const sseClients = new Set<ReadableStreamDefaultController>();
686
- const heartbeatClients = new Set<ReadableStreamDefaultController>();
687
- let shutdownTimer: ReturnType<typeof setTimeout> | null = null;
688
-
689
- function sendEvent(event: unknown): void {
690
- const message = `data: ${JSON.stringify(event)}\n\n`;
691
- for (const controller of sseClients) {
692
- try {
693
- controller.enqueue(message);
694
- } catch {
695
- sseClients.delete(controller);
696
- }
697
- }
698
- }
699
-
700
- function clearShutdownTimer(): void {
701
- if (!shutdownTimer) return;
702
- clearTimeout(shutdownTimer);
703
- shutdownTimer = null;
704
- }
705
-
706
- function onHeartbeatOpen(controller: ReadableStreamDefaultController): void {
707
- heartbeatClients.add(controller);
708
- clearShutdownTimer();
709
- }
710
-
711
- function onHeartbeatClose(controller: ReadableStreamDefaultController): void {
712
- heartbeatClients.delete(controller);
713
- if (isDev || heartbeatClients.size > 0 || shutdownTimer) return;
714
-
715
- shutdownTimer = setTimeout(() => {
716
- if (heartbeatClients.size > 0) {
717
- clearShutdownTimer();
718
- return;
719
- }
720
- console.log("\nBrowser disconnected, shutting down...");
721
- process.exit(0);
722
- }, 1500);
723
- }
724
-
725
- async function ensureFileContent(filePath: string): Promise<string> {
726
- const state = fileMap.get(filePath);
727
- if (!state) {
728
- throw new Error(`File not found: ${filePath}`);
729
- }
730
-
731
- if (state.isLoaded && state.content !== null) {
732
- return state.content;
733
- }
734
-
735
- const content = await fs.readFile(filePath, "utf-8");
736
- state.content = content;
737
- state.isLoaded = true;
738
- return content;
739
- }
740
-
741
- async function ensureRenderedHtml(
742
- filePath: string,
743
- ): Promise<{ html: string; headings: import("./lib/headings").Heading[] }> {
744
- const state = fileMap.get(filePath);
745
- if (!state) throw new Error(`File not found: ${filePath}`);
746
-
747
- if (state.renderedHtml !== null && state.headings !== null) {
748
- return { html: state.renderedHtml, headings: state.headings };
749
- }
750
-
751
- const content = await ensureFileContent(filePath);
752
- const result = await renderMarkdown(content);
753
- state.renderedHtml = result.html;
754
- state.headings = result.headings;
755
- return result;
756
- }
757
-
758
- function resolveContext(url: URL): RouteContext | null {
759
- const requestedPath = url.searchParams.get("path") ?? defaultPath;
760
- const state = fileMap.get(requestedPath);
761
- if (!state) return null;
762
- return {
763
- filePath: requestedPath,
764
- getCurrentContent: () => ensureFileContent(requestedPath),
765
- };
766
- }
767
-
768
- function requireContext(url: URL): RouteContext | Response {
769
- const ctx = resolveContext(url);
770
- if (!ctx) {
771
- return errorResponse("File not found", 404);
772
- }
773
- return ctx;
774
- }
775
-
776
- const isDev = process.env.NODE_ENV === "development";
777
- const distPath = import.meta.dir;
778
-
779
- let manifestCache: Record<string, { file: string; css?: string[] }> | null =
780
- null;
781
-
782
- async function getManifest(): Promise<typeof manifestCache> {
783
- if (manifestCache) return manifestCache;
784
- try {
785
- const manifestPath = join(distPath, ".vite", "manifest.json");
786
- const content = await fs.readFile(manifestPath, "utf-8");
787
- manifestCache = JSON.parse(content);
788
- return manifestCache;
789
- } catch {
790
- return null;
791
- }
792
- }
793
-
794
- let pageCache: string | null = null;
795
- let pageCacheGz: Uint8Array<ArrayBuffer> | null = null;
796
-
797
- function invalidatePageCache(): void {
798
- pageCache = null;
799
- pageCacheGz = null;
800
- }
801
-
802
- async function serveAppPage(req: Request): Promise<Response> {
803
- const acceptGzip =
804
- req.headers.get("accept-encoding")?.includes("gzip") ?? false;
805
-
806
- try {
807
- if (pageCache) {
808
- if (acceptGzip && pageCacheGz) {
809
- return new Response(pageCacheGz, {
810
- headers: {
811
- "Content-Type": "text/html; charset=utf-8",
812
- "Content-Encoding": "gzip",
813
- },
814
- });
815
- }
816
- return new Response(pageCache, {
817
- headers: { "Content-Type": "text/html; charset=utf-8" },
818
- });
819
- }
820
-
821
- const { html, headings } = await ensureRenderedHtml(defaultPath);
822
- const content = await ensureFileContent(defaultPath);
823
- const comments = await readCommentsFromFile(defaultPath, content, html);
824
- const settings = await readSettings();
825
-
826
- const files = fileOrder.map((fp) => ({
827
- path: fp,
828
- fileName: basename(fp),
829
- }));
830
-
831
- const inlineData = {
832
- files,
833
- activeFile: defaultPath,
834
- settings,
835
- documents: {
836
- [defaultPath]: {
837
- headings,
838
- comments,
839
- },
840
- },
841
- clean: options.clean || false,
842
- workingDirectory: process.cwd(),
843
- };
844
-
845
- let cssPath = "";
846
- let jsPath: string;
847
-
848
- if (isDev) {
849
- jsPath = `http://127.0.0.1:${VITE_DEV_PORT}/src/main.ts`;
850
- } else {
851
- const manifest = await getManifest();
852
- const entry = manifest?.["index.html"];
853
- jsPath = entry ? `/${entry.file}` : "/assets/index.js";
854
- if (entry?.css?.[0]) {
855
- cssPath = `/${entry.css[0]}`;
856
- }
857
- }
858
-
859
- const body = renderTemplate({
860
- title: basename(defaultPath),
861
- cssPath,
862
- jsPath,
863
- documentHtml: html,
864
- inlineData,
865
- isDev,
866
- fontFamily: settings.fontFamily,
867
- });
868
-
869
- if (!isDev) {
870
- pageCache = body;
871
- pageCacheGz = Bun.gzipSync(
872
- new TextEncoder().encode(body),
873
- ) as Uint8Array<ArrayBuffer>;
874
- }
875
-
876
- if (acceptGzip) {
877
- const gz = pageCacheGz ?? Bun.gzipSync(new TextEncoder().encode(body));
878
- return new Response(gz, {
879
- headers: {
880
- "Content-Type": "text/html; charset=utf-8",
881
- "Content-Encoding": "gzip",
882
- },
883
- });
884
- }
885
-
886
- return new Response(body, {
887
- headers: { "Content-Type": "text/html; charset=utf-8" },
888
- });
889
- } catch (err) {
890
- console.error("Failed to serve app page:", err);
891
- return new Response("Internal Server Error", { status: 500 });
892
- }
893
- }
894
-
895
- function watchFile(targetPath: string): FSWatcher | null {
896
- try {
897
- const watcher = watch(targetPath, async (eventType) => {
898
- // Handle both "change" and "rename" events.
899
- // Many editors (Vim, Neovim, Emacs) save files by writing to a temp
900
- // file and then renaming it over the original. This triggers a
901
- // "rename" event rather than "change". After a rename the original
902
- // watcher may become invalid, so we re-establish it.
903
- if (eventType !== "change" && eventType !== "rename") return;
904
-
905
- const state = fileMap.get(targetPath);
906
- if (!state) return;
907
-
908
- if (state.debounceTimer) clearTimeout(state.debounceTimer);
909
- state.debounceTimer = setTimeout(async () => {
910
- try {
911
- const newContent = await fs.readFile(targetPath, "utf-8");
912
- if (!state.isLoaded || newContent !== state.content) {
913
- state.content = newContent;
914
- state.renderedHtml = null;
915
- state.headings = null;
916
- state.isLoaded = true;
917
- invalidateResolvedComments(targetPath);
918
- invalidatePageCache();
919
- console.log(`File changed: ${basename(targetPath)}`);
920
- sendEvent({ type: "document-updated", path: targetPath });
921
- }
922
- } catch (err) {
923
- // File may have been temporarily removed during a rename-save.
924
- // If it reappears, re-establish the watcher.
925
- if (isErrnoException(err) && err.code === "ENOENT") {
926
- await rewatch(targetPath);
927
- } else {
928
- console.error(`Failed to read updated file ${targetPath}:`, err);
929
- }
930
- }
931
- }, 100);
932
- });
933
-
934
- // Re-establish file watch after a rename-style save
935
- async function rewatch(filePath: string) {
936
- const maxRetries = 10;
937
- const retryInterval = 200;
938
- for (let i = 0; i < maxRetries; i++) {
939
- await new Promise((r) => setTimeout(r, retryInterval));
940
- try {
941
- await fs.access(filePath);
942
- // File exists again — close old watcher, create new one
943
- try {
944
- watcher.close();
945
- } catch {}
946
- const idx = watchers.indexOf(watcher);
947
- const newWatcher = watchFile(filePath);
948
- if (newWatcher) {
949
- if (idx >= 0) watchers[idx] = newWatcher;
950
- else watchers.push(newWatcher);
951
- }
952
- // Read the new content and emit update
953
- const state = fileMap.get(filePath);
954
- if (state) {
955
- const newContent = await fs.readFile(filePath, "utf-8");
956
- if (!state.isLoaded || newContent !== state.content) {
957
- state.content = newContent;
958
- state.renderedHtml = null;
959
- state.headings = null;
960
- state.isLoaded = true;
961
- invalidateResolvedComments(filePath);
962
- invalidatePageCache();
963
- console.log(`File changed: ${basename(filePath)}`);
964
- sendEvent({ type: "document-updated", path: filePath });
965
- }
966
- }
967
- return;
968
- } catch {
969
- // File not yet recreated, keep retrying
970
- }
971
- }
972
- console.warn(`File did not reappear after rename: ${filePath}`);
973
- }
974
-
975
- return watcher;
976
- } catch (err) {
977
- console.warn(`File watching not available for ${targetPath}:`, err);
978
- return null;
979
- }
980
- }
981
-
982
- const watchers: FSWatcher[] = [];
983
-
984
- const server = Bun.serve({
985
- port: options.port,
986
- hostname: options.host,
987
- idleTimeout: 255,
988
-
989
- async fetch(req: Request) {
990
- const url = new URL(req.url);
991
- const { pathname } = url;
992
- const method = req.method;
993
-
994
- if (pathname === "/api/documents" && method === "GET") {
995
- const files = fileOrder.map((fp) => ({
996
- path: fp,
997
- fileName: basename(fp),
998
- }));
999
- return json({
1000
- files,
1001
- clean: options.clean || false,
1002
- workingDirectory: process.cwd(),
1003
- });
1004
- }
1005
-
1006
- if (pathname === "/api/documents" && method === "POST") {
1007
- try {
1008
- const { path: requestedPath } = await req.json();
1009
-
1010
- if (!requestedPath || typeof requestedPath !== "string") {
1011
- return errorResponse("Missing 'path' field", 400);
1012
- }
1013
-
1014
- let filePath: string;
1015
- try {
1016
- filePath = await canonicalPath(requestedPath);
1017
- } catch (err) {
1018
- if (isErrnoException(err) && err.code === "ENOENT") {
1019
- return errorResponse(`File not found: ${requestedPath}`, 404);
1020
- }
1021
- throw err;
1022
- }
1023
- if (!isMarkdownFile(filePath)) {
1024
- return errorResponse(
1025
- `Unsupported file type: ${filePath} (expected .md or .markdown)`,
1026
- 400,
1027
- );
1028
- }
1029
-
1030
- const existingState = fileMap.get(filePath);
1031
-
1032
- if (existingState) {
1033
- return json({
1034
- path: filePath,
1035
- fileName: basename(filePath),
1036
- status: "present",
1037
- });
1038
- } else {
1039
- fileMap.set(filePath, {
1040
- content: null,
1041
- renderedHtml: null,
1042
- headings: null,
1043
- isLoaded: false,
1044
- debounceTimer: null,
1045
- });
1046
- fileOrder.push(filePath);
1047
-
1048
- const watcher = watchFile(filePath);
1049
- if (watcher) watchers.push(watcher);
1050
-
1051
- sendEvent({
1052
- type: "document-added",
1053
- path: filePath,
1054
- fileName: basename(filePath),
1055
- });
1056
- }
1057
-
1058
- return json({
1059
- path: filePath,
1060
- fileName: basename(filePath),
1061
- status: "added",
1062
- });
1063
- } catch (err) {
1064
- console.error("Failed to add document:", err);
1065
- return errorResponse("Failed to add document", 500);
1066
- }
1067
- }
1068
-
1069
- if (pathname === "/api/document" && method === "GET") {
1070
- const ctxOrRes = requireContext(url);
1071
- if (ctxOrRes instanceof Response) return ctxOrRes;
1072
- const { html, headings } = await ensureRenderedHtml(ctxOrRes.filePath);
1073
- return json({
1074
- html,
1075
- headings,
1076
- filePath: ctxOrRes.filePath,
1077
- fileName: basename(ctxOrRes.filePath),
1078
- clean: options.clean || false,
1079
- });
1080
- }
1081
-
1082
- if (pathname === "/api/document/stream" && method === "GET") {
1083
- return createDocumentStream(sseClients);
1084
- }
1085
-
1086
- if (pathname === "/api/health" && method === "GET") {
1087
- return json({ status: "ok" });
1088
- }
1089
-
1090
- if (pathname === "/api/heartbeat" && method === "GET") {
1091
- return createHeartbeat(onHeartbeatOpen, onHeartbeatClose);
1092
- }
1093
-
1094
- if (pathname === "/api/comments" && method === "GET") {
1095
- const ctxOrRes = requireContext(url);
1096
- if (ctxOrRes instanceof Response) return ctxOrRes;
1097
- const rendered = await ensureRenderedHtml(ctxOrRes.filePath);
1098
- return getComments(ctxOrRes, rendered.html);
1099
- }
1100
-
1101
- if (pathname === "/api/comments/raw" && method === "GET") {
1102
- const ctxOrRes = requireContext(url);
1103
- if (ctxOrRes instanceof Response) return ctxOrRes;
1104
- return getRawComments(ctxOrRes);
1105
- }
1106
-
1107
- if (pathname === "/api/comments" && method === "POST") {
1108
- const ctxOrRes = requireContext(url);
1109
- if (ctxOrRes instanceof Response) return ctxOrRes;
1110
- invalidatePageCache();
1111
- return addComment(ctxOrRes, req);
1112
- }
1113
-
1114
- if (pathname === "/api/comments" && method === "DELETE") {
1115
- const ctxOrRes = requireContext(url);
1116
- if (ctxOrRes instanceof Response) return ctxOrRes;
1117
- invalidatePageCache();
1118
- return clearComments(ctxOrRes);
1119
- }
1120
-
1121
- const commentId = extractCommentId(pathname);
1122
- if (commentId) {
1123
- const ctxOrRes = requireContext(url);
1124
- if (ctxOrRes instanceof Response) return ctxOrRes;
1125
- invalidatePageCache();
1126
-
1127
- if (pathname.endsWith("/reanchor") && method === "PUT") {
1128
- return reanchorComment(ctxOrRes, req, commentId);
1129
- }
1130
- if (method === "PUT") {
1131
- return updateComment(ctxOrRes, req, commentId);
1132
- }
1133
- if (method === "DELETE") {
1134
- return deleteComment(ctxOrRes, commentId);
1135
- }
1136
- }
1137
-
1138
- if (pathname === "/api/settings" && method === "GET") {
1139
- return getSettingsRoute();
1140
- }
1141
-
1142
- if (pathname === "/api/settings" && method === "PUT") {
1143
- return updateSettingsRoute(req);
1144
- }
1145
-
1146
- if (pathname === "/") {
1147
- return serveAppPage(req);
1148
- }
1149
-
1150
- if (isDev) {
1151
- return proxyToVite(req, pathname, url.search);
1152
- }
1153
- return serveStaticFile(distPath, pathname);
1154
- },
1155
- });
1156
-
1157
- for (const fp of fileOrder) {
1158
- const watcher = watchFile(fp);
1159
- if (watcher) watchers.push(watcher);
1160
- }
1161
-
1162
- return { server, watchers };
1163
- }
1164
-
1165
- export async function startServer(
1166
- options: ServerOptions,
1167
- ): Promise<ServerResult> {
1168
- getShiki();
1169
-
1170
- const MAX_PORT = 65535;
1171
-
1172
- for (let port = options.port; port <= MAX_PORT; port++) {
1173
- try {
1174
- const { server, watchers } = createServer({ ...options, port });
1175
-
1176
- const displayHost =
1177
- options.host === "0.0.0.0" ? "localhost" : options.host;
1178
-
1179
- let stopVite: (() => void) | undefined;
1180
- if (process.env.NODE_ENV === "development") {
1181
- stopVite = await spawnViteDev();
1182
- }
1183
-
1184
- const originalStop = server.stop.bind(server);
1185
- const wrappedServer = {
1186
- stop() {
1187
- disposeMermaidWorker();
1188
- stopVite?.();
1189
- for (const w of watchers) w.close();
1190
- originalStop();
1191
- },
1192
- };
1193
-
1194
- const actualPort = server.port ?? port;
1195
-
1196
- await writeServerInfo(actualPort);
1197
-
1198
- return {
1199
- port: actualPort,
1200
- url: `http://${displayHost}:${actualPort}`,
1201
- server: wrappedServer,
1202
- };
1203
- } catch (err) {
1204
- if (
1205
- isErrnoException(err) &&
1206
- (err.code === "EADDRINUSE" || err.code === "EACCES")
1207
- ) {
1208
- console.log(`Port ${port} is busy, trying ${port + 1}...`);
1209
- continue;
1210
- }
1211
- throw err;
1212
- }
1213
- }
1214
-
1215
- throw new Error(`No available port found starting from ${options.port}`);
1216
- }