@peaske7/readit 0.2.1 → 0.3.0-rc.1

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 (367) hide show
  1. package/dist/.vite/manifest.json +1111 -0
  2. package/dist/assets/_basePickBy-BMMA4Tou.js +1 -0
  3. package/dist/assets/_baseUniq-D40qku1I.js +1 -0
  4. package/dist/assets/arc-Ckg65iy8.js +1 -0
  5. package/dist/assets/architecture-YZFGNWBL-Dv3EY0zV.js +1 -0
  6. package/dist/assets/architectureDiagram-Q4EWVU46-ClRss4cm.js +36 -0
  7. package/dist/assets/array-Bjz-wYpJ.js +1 -0
  8. package/dist/assets/blockDiagram-DXYQGD6D-CBcFvoK1.js +132 -0
  9. package/dist/assets/c4Diagram-AHTNJAMY-D4d3ZLam.js +10 -0
  10. package/dist/assets/channel-D9EJxDy_.js +1 -0
  11. package/dist/assets/chunk-2KRD3SAO-DaFfaCGO.js +1 -0
  12. package/dist/assets/chunk-336JU56O-yLEQoF0v.js +2 -0
  13. package/dist/assets/chunk-426QAEUC-Uyzd4wAA.js +1 -0
  14. package/dist/assets/chunk-4BX2VUAB-DRuTD7x5.js +1 -0
  15. package/dist/assets/chunk-4TB4RGXK-3xbpIi_o.js +206 -0
  16. package/dist/assets/chunk-55IACEB6-BExiaAoD.js +1 -0
  17. package/dist/assets/chunk-5FUZZQ4R-DatVvHnF.js +62 -0
  18. package/dist/assets/chunk-5PVQY5BW-BKgvrGh8.js +2 -0
  19. package/dist/assets/chunk-67CJDMHE-DMt8LNEX.js +1 -0
  20. package/dist/assets/chunk-7N4EOEYR-CzLGefVf.js +1 -0
  21. package/dist/assets/chunk-AA7GKIK3-B6GFAk4U.js +1 -0
  22. package/dist/assets/chunk-BSJP7CBP-BK29yehL.js +1 -0
  23. package/dist/assets/chunk-CIAEETIT-D7hBXImP.js +1 -0
  24. package/dist/assets/chunk-Dlc7tRH4.js +1 -0
  25. package/dist/assets/chunk-EDXVE4YY-PYJdlmyH.js +1 -0
  26. package/dist/assets/chunk-ENJZ2VHE-DUHKBv6x.js +10 -0
  27. package/dist/assets/chunk-FMBD7UC4-2FWyCCAV.js +15 -0
  28. package/dist/assets/chunk-FOC6F5B3-DKFHrt4K.js +1 -0
  29. package/dist/assets/chunk-ICPOFSXX-Bh__D0ec.js +122 -0
  30. package/dist/assets/chunk-K5T4RW27-D51O7IkG.js +94 -0
  31. package/dist/assets/chunk-KGLVRYIC-DMHSCH4T.js +1 -0
  32. package/dist/assets/chunk-LIHQZDEY-C2aANxt9.js +1 -0
  33. package/dist/assets/chunk-ORNJ4GCN-Db_37NRX.js +1 -0
  34. package/dist/assets/chunk-OYMX7WX6-BltXOJLJ.js +231 -0
  35. package/dist/assets/chunk-QZHKN3VN-8Lcg9gti.js +1 -0
  36. package/dist/assets/chunk-U2HBQHQK-ByS6tilY.js +70 -0
  37. package/dist/assets/chunk-X2U36JSP-Bm-4Gqg_.js +1 -0
  38. package/dist/assets/chunk-XPW4576I-Bqbompq4.js +32 -0
  39. package/dist/assets/chunk-YZCP3GAM-CsC0imPb.js +1 -0
  40. package/dist/assets/chunk-ZZ45TVLE-CG-CqfPC.js +1 -0
  41. package/dist/assets/classDiagram-6PBFFD2Q-Jy1uFUk4.js +1 -0
  42. package/dist/assets/classDiagram-v2-HSJHXN6E-ChiLl3rR.js +1 -0
  43. package/dist/assets/clone-BBjvuERA.js +1 -0
  44. package/dist/assets/cose-bilkent-S5V4N54A-q90QeGKv.js +1 -0
  45. package/dist/assets/cytoscape.esm-BfXff3fb.js +321 -0
  46. package/dist/assets/dagre-KV5264BT-BQWiLFJB.js +4 -0
  47. package/dist/assets/dagre-nn_aIZ2E.js +1 -0
  48. package/dist/assets/defaultLocale-BwmRmqJp.js +1 -0
  49. package/dist/assets/diagram-5BDNPKRD-CJa7Y97H.js +10 -0
  50. package/dist/assets/diagram-G4DWMVQ6-tVQGBWfY.js +24 -0
  51. package/dist/assets/diagram-MMDJMWI5-CpimFldm.js +43 -0
  52. package/dist/assets/diagram-TYMM5635-D11WQVgy.js +24 -0
  53. package/dist/assets/dist-BNz65Ibc.js +1 -0
  54. package/dist/assets/erDiagram-SMLLAGMA-C2bLd0jS.js +85 -0
  55. package/dist/assets/flowDiagram-DWJPFMVM-Kw3fOOLT.js +162 -0
  56. package/dist/assets/ganttDiagram-T4ZO3ILL-fyMhyE2X.js +292 -0
  57. package/dist/assets/gitGraph-7Q5UKJZL-BGFRt2qs.js +1 -0
  58. package/dist/assets/gitGraphDiagram-UUTBAWPF-D4JoiOvg.js +106 -0
  59. package/dist/assets/graphlib-DGcD9J2L.js +1 -0
  60. package/dist/assets/index-Cow3qpoq.css +2 -0
  61. package/dist/assets/index-DUf7okYi.js +14 -0
  62. package/dist/assets/info-OMHHGYJF-DI6-Z9vh.js +1 -0
  63. package/dist/assets/infoDiagram-42DDH7IO-D1ZkeMBy.js +2 -0
  64. package/dist/assets/init-TPm5RB77.js +1 -0
  65. package/dist/assets/isArrayLikeObject-69BLnVNM.js +1 -0
  66. package/dist/assets/isEmpty-DUS28g5f.js +1 -0
  67. package/dist/assets/ishikawaDiagram-UXIWVN3A-Dv8hzjZB.js +70 -0
  68. package/dist/assets/journeyDiagram-VCZTEJTY-COeB7F5r.js +139 -0
  69. package/dist/assets/kanban-definition-6JOO6SKY-BbYmxCYU.js +89 -0
  70. package/dist/assets/katex-5SGEXwpi.js +261 -0
  71. package/dist/assets/line-_v2NGEdn.js +1 -0
  72. package/dist/assets/linear-CXMqTN8N.js +1 -0
  73. package/dist/assets/mermaid-config-C8a4L22x.js +1 -0
  74. package/dist/assets/mermaid-parser.core-CFmphzPP.js +4 -0
  75. package/dist/assets/mermaid.core-DnHAupTp.js +11 -0
  76. package/dist/assets/mindmap-definition-QFDTVHPH-D7_lIep7.js +96 -0
  77. package/dist/assets/ordinal-D7l-8DAO.js +1 -0
  78. package/dist/assets/packet-4T2RLAQJ-DidW3JFc.js +1 -0
  79. package/dist/assets/path-BVpCanzE.js +1 -0
  80. package/dist/assets/pie-ZZUOXDRM-Bff2e5hg.js +1 -0
  81. package/dist/assets/pieDiagram-DEJITSTG-DDvYHCT_.js +30 -0
  82. package/dist/assets/quadrantDiagram-34T5L4WZ-DcLcIrdi.js +7 -0
  83. package/dist/assets/radar-PYXPWWZC-CsdZBH3M.js +1 -0
  84. package/dist/assets/requirementDiagram-MS252O5E-DLX6ld7D.js +84 -0
  85. package/dist/assets/rough.esm-BoTisKeL.js +1 -0
  86. package/dist/assets/sankeyDiagram-XADWPNL6-D-1GtsHM.js +10 -0
  87. package/dist/assets/sequenceDiagram-FGHM5R23-Bwxs0YQg.js +157 -0
  88. package/dist/assets/src-CrmkjRpa.js +1 -0
  89. package/dist/assets/stateDiagram-FHFEXIEX-DW7rOcnQ.js +1 -0
  90. package/dist/assets/stateDiagram-v2-QKLJ7IA2-Jm-24vQ2.js +1 -0
  91. package/dist/assets/timeline-definition-GMOUNBTQ-DVdHyzxS.js +120 -0
  92. package/dist/assets/treeView-SZITEDCU-DPKseaET.js +1 -0
  93. package/dist/assets/treemap-W4RFUUIX-DH-7GZe_.js +1 -0
  94. package/dist/assets/vennDiagram-DHZGUBPP-DJaC6xmI.js +34 -0
  95. package/dist/assets/wardley-RL74JXVD-AgyXyBN5.js +1 -0
  96. package/dist/assets/wardleyDiagram-NUSXRM2D-CTKERPKv.js +20 -0
  97. package/dist/assets/xychartDiagram-5P7HB3ND-BuExiLXc.js +7 -0
  98. package/{index.html → dist/index.html} +2 -1
  99. package/dist/index.js +2539 -0
  100. package/package.json +11 -1
  101. package/.agents/skills/remotion-best-practices/SKILL.md +0 -61
  102. package/.agents/skills/remotion-best-practices/rules/3d.md +0 -86
  103. package/.agents/skills/remotion-best-practices/rules/animations.md +0 -27
  104. package/.agents/skills/remotion-best-practices/rules/assets/charts-bar-chart.tsx +0 -178
  105. package/.agents/skills/remotion-best-practices/rules/assets/text-animations-typewriter.tsx +0 -100
  106. package/.agents/skills/remotion-best-practices/rules/assets/text-animations-word-highlight.tsx +0 -108
  107. package/.agents/skills/remotion-best-practices/rules/assets.md +0 -78
  108. package/.agents/skills/remotion-best-practices/rules/audio-visualization.md +0 -198
  109. package/.agents/skills/remotion-best-practices/rules/audio.md +0 -169
  110. package/.agents/skills/remotion-best-practices/rules/calculate-metadata.md +0 -134
  111. package/.agents/skills/remotion-best-practices/rules/can-decode.md +0 -75
  112. package/.agents/skills/remotion-best-practices/rules/charts.md +0 -120
  113. package/.agents/skills/remotion-best-practices/rules/compositions.md +0 -154
  114. package/.agents/skills/remotion-best-practices/rules/display-captions.md +0 -184
  115. package/.agents/skills/remotion-best-practices/rules/extract-frames.md +0 -229
  116. package/.agents/skills/remotion-best-practices/rules/ffmpeg.md +0 -38
  117. package/.agents/skills/remotion-best-practices/rules/fonts.md +0 -152
  118. package/.agents/skills/remotion-best-practices/rules/get-audio-duration.md +0 -58
  119. package/.agents/skills/remotion-best-practices/rules/get-video-dimensions.md +0 -68
  120. package/.agents/skills/remotion-best-practices/rules/get-video-duration.md +0 -60
  121. package/.agents/skills/remotion-best-practices/rules/gifs.md +0 -141
  122. package/.agents/skills/remotion-best-practices/rules/images.md +0 -134
  123. package/.agents/skills/remotion-best-practices/rules/import-srt-captions.md +0 -69
  124. package/.agents/skills/remotion-best-practices/rules/light-leaks.md +0 -73
  125. package/.agents/skills/remotion-best-practices/rules/lottie.md +0 -70
  126. package/.agents/skills/remotion-best-practices/rules/maps.md +0 -412
  127. package/.agents/skills/remotion-best-practices/rules/measuring-dom-nodes.md +0 -34
  128. package/.agents/skills/remotion-best-practices/rules/measuring-text.md +0 -140
  129. package/.agents/skills/remotion-best-practices/rules/parameters.md +0 -109
  130. package/.agents/skills/remotion-best-practices/rules/sequencing.md +0 -118
  131. package/.agents/skills/remotion-best-practices/rules/sfx.md +0 -26
  132. package/.agents/skills/remotion-best-practices/rules/subtitles.md +0 -36
  133. package/.agents/skills/remotion-best-practices/rules/tailwind.md +0 -11
  134. package/.agents/skills/remotion-best-practices/rules/text-animations.md +0 -20
  135. package/.agents/skills/remotion-best-practices/rules/timing.md +0 -179
  136. package/.agents/skills/remotion-best-practices/rules/transcribe-captions.md +0 -70
  137. package/.agents/skills/remotion-best-practices/rules/transitions.md +0 -197
  138. package/.agents/skills/remotion-best-practices/rules/transparent-videos.md +0 -106
  139. package/.agents/skills/remotion-best-practices/rules/trimming.md +0 -51
  140. package/.agents/skills/remotion-best-practices/rules/videos.md +0 -171
  141. package/.agents/skills/remotion-best-practices/rules/voiceover.md +0 -99
  142. package/.agents/skills/simple/SKILL.md +0 -52
  143. package/.agents/skills/vercel-react-best-practices/AGENTS.md +0 -3254
  144. package/.agents/skills/vercel-react-best-practices/README.md +0 -123
  145. package/.agents/skills/vercel-react-best-practices/SKILL.md +0 -141
  146. package/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +0 -55
  147. package/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md +0 -42
  148. package/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md +0 -39
  149. package/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md +0 -38
  150. package/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md +0 -80
  151. package/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md +0 -51
  152. package/.agents/skills/vercel-react-best-practices/rules/async-parallel.md +0 -28
  153. package/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +0 -99
  154. package/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +0 -59
  155. package/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md +0 -31
  156. package/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +0 -49
  157. package/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +0 -35
  158. package/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md +0 -50
  159. package/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md +0 -74
  160. package/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md +0 -71
  161. package/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md +0 -48
  162. package/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md +0 -56
  163. package/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +0 -107
  164. package/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md +0 -80
  165. package/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md +0 -28
  166. package/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md +0 -70
  167. package/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md +0 -32
  168. package/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md +0 -50
  169. package/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md +0 -60
  170. package/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +0 -45
  171. package/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md +0 -37
  172. package/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md +0 -49
  173. package/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md +0 -82
  174. package/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +0 -24
  175. package/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +0 -57
  176. package/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md +0 -26
  177. package/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +0 -47
  178. package/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +0 -40
  179. package/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +0 -38
  180. package/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +0 -46
  181. package/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +0 -82
  182. package/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md +0 -30
  183. package/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md +0 -85
  184. package/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md +0 -68
  185. package/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +0 -28
  186. package/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md +0 -75
  187. package/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md +0 -39
  188. package/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md +0 -45
  189. package/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md +0 -40
  190. package/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md +0 -29
  191. package/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md +0 -74
  192. package/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md +0 -58
  193. package/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md +0 -38
  194. package/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md +0 -44
  195. package/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md +0 -45
  196. package/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md +0 -82
  197. package/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md +0 -35
  198. package/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md +0 -40
  199. package/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md +0 -73
  200. package/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md +0 -73
  201. package/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md +0 -96
  202. package/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md +0 -41
  203. package/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md +0 -76
  204. package/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md +0 -65
  205. package/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md +0 -142
  206. package/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md +0 -83
  207. package/.agents/skills/vercel-react-best-practices/rules/server-serialization.md +0 -38
  208. package/.claude/CLAUDE.md +0 -184
  209. package/.claude/commands/review.md +0 -120
  210. package/.claude/commands/sync-docs.md +0 -71
  211. package/.claude/roadmap.md +0 -121
  212. package/.claude/rules/style-guide.md +0 -830
  213. package/.claude/settings.json +0 -18
  214. package/.claude/user-stories.md +0 -333
  215. package/AGENTS.md +0 -68
  216. package/Makefile +0 -32
  217. package/biome.json +0 -79
  218. package/bun.lock +0 -854
  219. package/bunfig.toml +0 -2
  220. package/docs/design.md +0 -563
  221. package/docs/perf-baseline.md +0 -130
  222. package/docs/plans/2026-03-13-client-mode-design.md +0 -86
  223. package/docs/plans/2026-03-13-client-mode-plan.md +0 -605
  224. package/docs/plans/2026-03-13-keyboard-shortcuts-design.md +0 -129
  225. package/docs/plans/2026-03-13-keyboard-shortcuts-plan.md +0 -1471
  226. package/docs/plans/2026-03-13-multi-document-design.md +0 -183
  227. package/docs/plans/2026-03-13-performance-benchmarks-design.md +0 -121
  228. package/docs/superpowers/plans/2026-03-26-surgical-pruning.md +0 -1176
  229. package/docs/superpowers/specs/2026-03-27-go-server-rewrite-design.md +0 -284
  230. package/e2e/comments.spec.ts +0 -81
  231. package/e2e/document-load.spec.ts +0 -32
  232. package/e2e/export.spec.ts +0 -58
  233. package/e2e/fixtures/sample.md +0 -7
  234. package/e2e/perf/add-comment.spec.ts +0 -116
  235. package/e2e/perf/fixtures/generate.ts +0 -327
  236. package/e2e/perf/initial-load.spec.ts +0 -49
  237. package/e2e/perf/perf.setup.ts +0 -23
  238. package/e2e/perf/perf.teardown.ts +0 -9
  239. package/e2e/perf/screenshot-final.png +0 -0
  240. package/e2e/perf/scroll.spec.ts +0 -39
  241. package/e2e/perf/tab-switch.spec.ts +0 -69
  242. package/e2e/perf/text-selection.spec.ts +0 -119
  243. package/e2e/perf/utils/metrics.ts +0 -350
  244. package/e2e/perf/utils/perf-cli.ts +0 -86
  245. package/e2e/persistence-file.spec.ts +0 -357
  246. package/e2e/utils/cli.ts +0 -84
  247. package/e2e/utils/selection.ts +0 -79
  248. package/go/cmd/readit/main.go +0 -416
  249. package/go/go.mod +0 -20
  250. package/go/go.sum +0 -41
  251. package/go/internal/server/anchor.go +0 -302
  252. package/go/internal/server/anchor_test.go +0 -111
  253. package/go/internal/server/comments.go +0 -390
  254. package/go/internal/server/documents.go +0 -113
  255. package/go/internal/server/embed.go +0 -17
  256. package/go/internal/server/headings.go +0 -33
  257. package/go/internal/server/headings_test.go +0 -75
  258. package/go/internal/server/htmltext.go +0 -123
  259. package/go/internal/server/markdown.go +0 -157
  260. package/go/internal/server/markdown_bench_test.go +0 -42
  261. package/go/internal/server/markdown_test.go +0 -79
  262. package/go/internal/server/server.go +0 -453
  263. package/go/internal/server/server_bench_test.go +0 -122
  264. package/go/internal/server/settings.go +0 -110
  265. package/go/internal/server/sse.go +0 -140
  266. package/go/internal/server/storage.go +0 -275
  267. package/go/internal/server/storage_test.go +0 -118
  268. package/go/internal/server/template.go +0 -66
  269. package/go/internal/server/types.go +0 -101
  270. package/go/internal/server/watcher.go +0 -74
  271. package/lefthook.yml +0 -8
  272. package/nvim-readit/lua/readit/health.lua +0 -64
  273. package/nvim-readit/lua/readit/init.lua +0 -463
  274. package/nvim-readit/plugin/readit.lua +0 -19
  275. package/playwright.config.ts +0 -34
  276. package/skills-lock.json +0 -20
  277. package/src/App.svelte +0 -881
  278. package/src/cli.ts +0 -881
  279. package/src/components/ActionsMenu.svelte +0 -95
  280. package/src/components/CommentBadge.svelte +0 -67
  281. package/src/components/CommentErrorBanner.svelte +0 -33
  282. package/src/components/CommentInput.svelte +0 -75
  283. package/src/components/CommentListItem.svelte +0 -95
  284. package/src/components/CommentManager.svelte +0 -129
  285. package/src/components/CommentNav.svelte +0 -109
  286. package/src/components/DocumentViewer.svelte +0 -218
  287. package/src/components/FloatingComment.svelte +0 -107
  288. package/src/components/Header.svelte +0 -76
  289. package/src/components/InlineEditor.svelte +0 -72
  290. package/src/components/MarginNote.svelte +0 -167
  291. package/src/components/MarginNotesContainer.svelte +0 -33
  292. package/src/components/RawModal.svelte +0 -126
  293. package/src/components/ReanchorConfirm.svelte +0 -30
  294. package/src/components/SettingsModal.svelte +0 -220
  295. package/src/components/ShortcutCapture.svelte +0 -82
  296. package/src/components/ShortcutList.svelte +0 -145
  297. package/src/components/TabBar.svelte +0 -52
  298. package/src/components/TableOfContents.svelte +0 -125
  299. package/src/components/ui/ActionLink.svelte +0 -40
  300. package/src/components/ui/Button.svelte +0 -53
  301. package/src/components/ui/Dialog.svelte +0 -97
  302. package/src/components/ui/DropdownMenu.svelte +0 -85
  303. package/src/components/ui/DropdownMenuItem.svelte +0 -38
  304. package/src/components/ui/DropdownMenuSeparator.svelte +0 -11
  305. package/src/components/ui/Text.svelte +0 -42
  306. package/src/env.d.ts +0 -6
  307. package/src/index.css +0 -754
  308. package/src/lib/__fixtures__/bench-data.ts +0 -114
  309. package/src/lib/anchor.bench.ts +0 -91
  310. package/src/lib/anchor.test.ts +0 -527
  311. package/src/lib/anchor.ts +0 -381
  312. package/src/lib/comment-storage.bench.ts +0 -49
  313. package/src/lib/comment-storage.test.ts +0 -632
  314. package/src/lib/comment-storage.ts +0 -222
  315. package/src/lib/export.bench.ts +0 -21
  316. package/src/lib/export.ts +0 -36
  317. package/src/lib/headings.test.ts +0 -103
  318. package/src/lib/headings.ts +0 -44
  319. package/src/lib/highlight/core.test.ts +0 -93
  320. package/src/lib/highlight/dom.ts +0 -187
  321. package/src/lib/highlight/highlight-registry.ts +0 -221
  322. package/src/lib/highlight/highlight.bench.ts +0 -92
  323. package/src/lib/highlight/highlighter.ts +0 -247
  324. package/src/lib/highlight/resolver.ts +0 -38
  325. package/src/lib/highlight/types.ts +0 -17
  326. package/src/lib/html-text.test.ts +0 -162
  327. package/src/lib/html-text.ts +0 -161
  328. package/src/lib/i18n/en.ts +0 -116
  329. package/src/lib/i18n/index.ts +0 -3
  330. package/src/lib/i18n/ja.ts +0 -118
  331. package/src/lib/i18n/translations.ts +0 -27
  332. package/src/lib/i18n/types.ts +0 -122
  333. package/src/lib/margin-layout.bench.ts +0 -61
  334. package/src/lib/margin-layout.ts +0 -71
  335. package/src/lib/markdown-renderer.test.ts +0 -154
  336. package/src/lib/markdown-renderer.ts +0 -177
  337. package/src/lib/mermaid-config.ts +0 -38
  338. package/src/lib/mermaid-renderer.ts +0 -162
  339. package/src/lib/mermaid-worker.ts +0 -60
  340. package/src/lib/positions.ts +0 -157
  341. package/src/lib/shortcut-registry.ts +0 -244
  342. package/src/lib/utils.ts +0 -15
  343. package/src/main.ts +0 -16
  344. package/src/schema.ts +0 -92
  345. package/src/server.ts +0 -1220
  346. package/src/stores/app.svelte.ts +0 -231
  347. package/src/stores/locale.svelte.ts +0 -46
  348. package/src/stores/settings.svelte.ts +0 -90
  349. package/src/stores/shortcuts.svelte.ts +0 -104
  350. package/src/stores/ui.svelte.ts +0 -12
  351. package/src/template.ts +0 -104
  352. package/src/test-setup.ts +0 -48
  353. package/svelte.config.js +0 -5
  354. package/test.md +0 -74
  355. package/tsconfig.cli.json +0 -12
  356. package/tsconfig.json +0 -20
  357. package/vite.config.ts +0 -47
  358. package/vitest.config.ts +0 -15
  359. package/vscode-readit/.mcp.json +0 -7
  360. package/vscode-readit/.vscodeignore +0 -7
  361. package/vscode-readit/bun.lock +0 -78
  362. package/vscode-readit/icon.svg +0 -10
  363. package/vscode-readit/package.json +0 -110
  364. package/vscode-readit/src/extension.ts +0 -117
  365. package/vscode-readit/src/server-manager.ts +0 -272
  366. package/vscode-readit/src/webview-provider.ts +0 -204
  367. package/vscode-readit/tsconfig.json +0 -20
package/dist/index.js ADDED
@@ -0,0 +1,2539 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var __require = import.meta.require;
4
+
5
+ // src/cli.ts
6
+ import {
7
+ existsSync,
8
+ lstatSync,
9
+ readdirSync,
10
+ readFileSync,
11
+ realpathSync,
12
+ statSync
13
+ } from "fs";
14
+ import * as fs2 from "fs/promises";
15
+ import * as os3 from "os";
16
+ import { join as join4, resolve as resolve3 } from "path";
17
+ import { Command } from "commander";
18
+ import open2 from "open";
19
+
20
+ // src/lib/comment-storage.ts
21
+ import * as crypto from "crypto";
22
+ import * as os from "os";
23
+ import * as path from "path";
24
+ var FORMAT_VERSION = 1;
25
+ var HASH_LENGTH = 16;
26
+ var MAX_SELECTION_LENGTH = 1000;
27
+ var TRUNCATION_MARKER = `
28
+ ...
29
+ `;
30
+ var ANCHOR_PREFIX_LENGTH = 200;
31
+ function truncateSelection(text) {
32
+ if (text.length <= MAX_SELECTION_LENGTH) {
33
+ return text;
34
+ }
35
+ const half = Math.floor((MAX_SELECTION_LENGTH - TRUNCATION_MARKER.length) / 2);
36
+ return text.slice(0, half) + TRUNCATION_MARKER + text.slice(-half);
37
+ }
38
+ function getCommentPath(sourcePath) {
39
+ const absolute = path.resolve(sourcePath);
40
+ const normalized = absolute.replace(/^\//, "").replace(/^[A-Z]:[\\/]/, "");
41
+ const ext = path.extname(normalized);
42
+ const withoutExt = normalized.slice(0, -ext.length || undefined);
43
+ return path.join(os.homedir(), ".readit", "comments", `${withoutExt}.comments.md`);
44
+ }
45
+ function computeHash(content) {
46
+ return crypto.createHash("sha256").update(content).digest("hex").slice(0, HASH_LENGTH);
47
+ }
48
+ function getLineNumber(content, offset) {
49
+ if (offset <= 0 || content.length === 0)
50
+ return 1;
51
+ const clampedOffset = Math.min(offset, content.length);
52
+ return content.slice(0, clampedOffset).split(`
53
+ `).length;
54
+ }
55
+ function getLineHint(content, startOffset, endOffset) {
56
+ const startLine = getLineNumber(content, startOffset);
57
+ const endLine = getLineNumber(content, endOffset);
58
+ return startLine === endLine ? `L${startLine}` : `L${startLine}-L${endLine}`;
59
+ }
60
+ function parseCommentFile(content) {
61
+ const result = {
62
+ source: "",
63
+ hash: "",
64
+ version: FORMAT_VERSION,
65
+ comments: []
66
+ };
67
+ if (!content.trim()) {
68
+ return result;
69
+ }
70
+ const frontMatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
71
+ if (frontMatterMatch) {
72
+ const frontMatter = frontMatterMatch[1];
73
+ const sourceMatch = frontMatter.match(/^source:\s*(.+)$/m);
74
+ const hashMatch = frontMatter.match(/^hash:\s*(.+)$/m);
75
+ const versionMatch = frontMatter.match(/^version:\s*(\d+)$/m);
76
+ if (sourceMatch)
77
+ result.source = sourceMatch[1].trim();
78
+ if (hashMatch)
79
+ result.hash = hashMatch[1].trim();
80
+ if (versionMatch)
81
+ result.version = Number.parseInt(versionMatch[1], 10);
82
+ if (result.version > FORMAT_VERSION) {
83
+ throw new Error(`Comment file requires readit v${result.version} or higher. ` + `Current version supports format v${FORMAT_VERSION}.`);
84
+ }
85
+ }
86
+ const bodyContent = content.replace(/^---\n[\s\S]*?\n---\n*/, "");
87
+ const markerRe = /<!--\s*c:[^|]+\|[^|>\s]+(?:\|[^>]*)?\s*-->/g;
88
+ const markerStarts = [];
89
+ for (const m of bodyContent.matchAll(markerRe)) {
90
+ if (m.index !== undefined)
91
+ markerStarts.push(m.index);
92
+ }
93
+ for (let i = 0;i < markerStarts.length; i++) {
94
+ const start = markerStarts[i];
95
+ const end = i + 1 < markerStarts.length ? markerStarts[i + 1] : bodyContent.length;
96
+ const block = bodyContent.slice(start, end).replace(/\n+---\s*$/, "").trim();
97
+ if (!block)
98
+ continue;
99
+ const comment = parseCommentBlock(block);
100
+ if (comment) {
101
+ result.comments.push(comment);
102
+ }
103
+ }
104
+ return result;
105
+ }
106
+ function parseCommentBlock(block) {
107
+ const metadataMatch = block.match(/<!--\s*c:([^|]+)\|([^|>\s]+)(?:\|([^>]*))?\s*-->/);
108
+ if (!metadataMatch) {
109
+ return;
110
+ }
111
+ const [, id, lineHint, createdAtRaw] = metadataMatch;
112
+ const createdAt = createdAtRaw?.trim() || undefined;
113
+ const anchorMatch = block.match(/<!--\s*anchor:(.+?)\s*-->/);
114
+ const anchorPrefix = anchorMatch ? anchorMatch[1] : undefined;
115
+ const blockquoteMatch = block.match(/^>\s*(.+(?:\n>\s*.+)*)$/m);
116
+ if (!blockquoteMatch) {
117
+ return;
118
+ }
119
+ const selectedText = blockquoteMatch[1].split(`
120
+ `).map((line) => line.replace(/^>\s*/, "")).join(`
121
+ `);
122
+ const afterBlockquote = block.slice(block.indexOf(blockquoteMatch[0]) + blockquoteMatch[0].length);
123
+ const commentBody = afterBlockquote.trim();
124
+ return {
125
+ id,
126
+ selectedText,
127
+ comment: commentBody,
128
+ lineHint,
129
+ createdAt,
130
+ anchorPrefix,
131
+ startOffset: 0,
132
+ endOffset: 0
133
+ };
134
+ }
135
+ function serializeComments(file) {
136
+ const lines = [];
137
+ lines.push("---");
138
+ lines.push(`source: ${file.source}`);
139
+ lines.push(`hash: ${file.hash}`);
140
+ lines.push(`version: ${file.version}`);
141
+ lines.push("---");
142
+ lines.push("");
143
+ for (const comment of file.comments) {
144
+ lines.push(serializeComment(comment));
145
+ lines.push("");
146
+ lines.push("---");
147
+ lines.push("");
148
+ }
149
+ return lines.join(`
150
+ `);
151
+ }
152
+ function serializeComment(comment) {
153
+ const lines = [];
154
+ const lineHint = comment.lineHint || "L0";
155
+ const createdAt = comment.createdAt || new Date().toISOString();
156
+ lines.push(`<!-- c:${comment.id}|${lineHint}|${createdAt} -->`);
157
+ if (comment.anchorPrefix) {
158
+ lines.push(`<!-- anchor:${comment.anchorPrefix} -->`);
159
+ }
160
+ const quotedLines = comment.selectedText.split(`
161
+ `).map((line) => `> ${line}`);
162
+ lines.push(...quotedLines);
163
+ if (comment.comment) {
164
+ lines.push("");
165
+ lines.push(comment.comment);
166
+ }
167
+ return lines.join(`
168
+ `);
169
+ }
170
+ function createComment(selectedText, commentText, startOffset, endOffset, sourceContent) {
171
+ const id = crypto.randomUUID().slice(0, 8);
172
+ const lineHint = getLineHint(sourceContent, startOffset, endOffset);
173
+ const needsTruncation = selectedText.length > MAX_SELECTION_LENGTH;
174
+ return {
175
+ id,
176
+ selectedText: truncateSelection(selectedText),
177
+ comment: commentText,
178
+ startOffset,
179
+ endOffset,
180
+ lineHint,
181
+ createdAt: new Date().toISOString(),
182
+ anchorPrefix: needsTruncation ? selectedText.slice(0, ANCHOR_PREFIX_LENGTH) : undefined
183
+ };
184
+ }
185
+
186
+ // src/lib/utils.ts
187
+ import { clsx } from "clsx";
188
+ import { twMerge } from "tailwind-merge";
189
+ function isMarkdownFile(filePath) {
190
+ return filePath.endsWith(".md") || filePath.endsWith(".markdown");
191
+ }
192
+
193
+ // src/server.ts
194
+ import { watch } from "fs";
195
+ import * as fs from "fs/promises";
196
+ import * as os2 from "os";
197
+ import * as path2 from "path";
198
+ import { basename, dirname as dirname2, join as join3 } from "path";
199
+
200
+ // src/schema.ts
201
+ var AnchorConfidences = {
202
+ EXACT: "exact",
203
+ NORMALIZED: "normalized",
204
+ FUZZY: "fuzzy",
205
+ UNRESOLVED: "unresolved"
206
+ };
207
+ var FontFamilies = {
208
+ SERIF: "serif",
209
+ SANS_SERIF: "sans-serif"
210
+ };
211
+
212
+ // src/lib/anchor.ts
213
+ var DEFAULT_SEARCH_WINDOW = 500;
214
+ var DEFAULT_FUZZY_THRESHOLD = 5;
215
+ var MAX_FUZZY_TEXT_LENGTH = 200;
216
+ var FUZZY_SEARCH_WINDOW = 2000;
217
+ function normalizeWhitespace(text) {
218
+ return text.replace(/\s+/g, " ").trim();
219
+ }
220
+ function levenshteinDistance(a, b, maxDistance) {
221
+ if (a.length > b.length) {
222
+ [a, b] = [b, a];
223
+ }
224
+ const m = a.length;
225
+ const n = b.length;
226
+ if (m === 0)
227
+ return n;
228
+ if (n === 0)
229
+ return m;
230
+ if (maxDistance !== undefined && Math.abs(m - n) > maxDistance) {
231
+ return Number.POSITIVE_INFINITY;
232
+ }
233
+ let prevRow = new Array(m + 1);
234
+ let currRow = new Array(m + 1);
235
+ for (let i = 0;i <= m; i++) {
236
+ prevRow[i] = i;
237
+ }
238
+ for (let j = 1;j <= n; j++) {
239
+ currRow[0] = j;
240
+ let rowMin = currRow[0];
241
+ for (let i = 1;i <= m; i++) {
242
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
243
+ currRow[i] = Math.min(prevRow[i] + 1, currRow[i - 1] + 1, prevRow[i - 1] + cost);
244
+ rowMin = Math.min(rowMin, currRow[i]);
245
+ }
246
+ if (maxDistance !== undefined && rowMin > maxDistance) {
247
+ return Number.POSITIVE_INFINITY;
248
+ }
249
+ [prevRow, currRow] = [currRow, prevRow];
250
+ }
251
+ return prevRow[m];
252
+ }
253
+ function getLineOffset(content, lineNumber) {
254
+ if (lineNumber <= 1)
255
+ return 0;
256
+ let currentLine = 1;
257
+ for (let i = 0;i < content.length; i++) {
258
+ if (content[i] === `
259
+ `) {
260
+ currentLine++;
261
+ if (currentLine === lineNumber) {
262
+ return i + 1;
263
+ }
264
+ }
265
+ }
266
+ return content.length;
267
+ }
268
+ function parseLineHint(lineHint) {
269
+ const match = lineHint.match(/^L(\d+)(?:-L?(\d+))?$/);
270
+ if (!match) {
271
+ return { start: 1, end: 1 };
272
+ }
273
+ const start = Number.parseInt(match[1], 10);
274
+ const end = match[2] ? Number.parseInt(match[2], 10) : start;
275
+ return { start, end };
276
+ }
277
+ function findAnchor({
278
+ source,
279
+ selectedText,
280
+ lineHint,
281
+ searchWindow = DEFAULT_SEARCH_WINDOW
282
+ }) {
283
+ if (!selectedText || !source) {
284
+ return;
285
+ }
286
+ const { start: hintLine } = parseLineHint(lineHint);
287
+ const lineOffset = getLineOffset(source, hintLine);
288
+ const windowStart = Math.max(0, lineOffset - searchWindow);
289
+ const windowEnd = Math.min(source.length, lineOffset + searchWindow);
290
+ const window = source.slice(windowStart, windowEnd);
291
+ const localIndex = window.indexOf(selectedText);
292
+ if (localIndex !== -1) {
293
+ const start = windowStart + localIndex;
294
+ const end = start + selectedText.length;
295
+ return {
296
+ start,
297
+ end,
298
+ line: getLineNumber(source, start),
299
+ confidence: AnchorConfidences.EXACT
300
+ };
301
+ }
302
+ const globalIndex = source.indexOf(selectedText);
303
+ if (globalIndex !== -1) {
304
+ return {
305
+ start: globalIndex,
306
+ end: globalIndex + selectedText.length,
307
+ line: getLineNumber(source, globalIndex),
308
+ confidence: AnchorConfidences.EXACT
309
+ };
310
+ }
311
+ return;
312
+ }
313
+ function buildNormalizedPositionMap(text) {
314
+ const toOriginal = [];
315
+ let normalized = "";
316
+ let inWhitespace = false;
317
+ for (let i = 0;i < text.length; i++) {
318
+ const char = text[i];
319
+ const isSpace = /\s/.test(char);
320
+ if (isSpace) {
321
+ if (!inWhitespace && normalized.length > 0) {
322
+ normalized += " ";
323
+ toOriginal.push(i);
324
+ }
325
+ inWhitespace = true;
326
+ } else {
327
+ normalized += char;
328
+ toOriginal.push(i);
329
+ inWhitespace = false;
330
+ }
331
+ }
332
+ if (normalized.endsWith(" ")) {
333
+ normalized = normalized.slice(0, -1);
334
+ toOriginal.pop();
335
+ }
336
+ return { normalized, toOriginal };
337
+ }
338
+ function findAnchorNormalized({
339
+ source,
340
+ selectedText,
341
+ lineHint,
342
+ searchWindow = FUZZY_SEARCH_WINDOW
343
+ }) {
344
+ if (!selectedText || !source) {
345
+ return;
346
+ }
347
+ const normalizedText = normalizeWhitespace(selectedText);
348
+ if (!normalizedText) {
349
+ return;
350
+ }
351
+ if (normalizedText === selectedText) {
352
+ return;
353
+ }
354
+ const { start: hintLine } = parseLineHint(lineHint);
355
+ const lineOffset = getLineOffset(source, hintLine);
356
+ const windowStart = Math.max(0, lineOffset - searchWindow);
357
+ const windowEnd = Math.min(source.length, lineOffset + searchWindow);
358
+ const window = source.slice(windowStart, windowEnd);
359
+ const { normalized: normalizedWindow, toOriginal } = buildNormalizedPositionMap(window);
360
+ const normalizedIndex = normalizedWindow.indexOf(normalizedText);
361
+ if (normalizedIndex !== -1) {
362
+ const originalStart = windowStart + toOriginal[normalizedIndex];
363
+ const endNormIndex = normalizedIndex + normalizedText.length - 1;
364
+ let originalEnd = windowStart + toOriginal[endNormIndex] + 1;
365
+ while (originalEnd < source.length && /\s/.test(source[originalEnd])) {
366
+ originalEnd++;
367
+ }
368
+ return {
369
+ start: originalStart,
370
+ end: originalEnd,
371
+ line: getLineNumber(source, originalStart),
372
+ confidence: AnchorConfidences.NORMALIZED
373
+ };
374
+ }
375
+ const { normalized: fullNormalized, toOriginal: fullToOriginal } = buildNormalizedPositionMap(source);
376
+ const globalIndex = fullNormalized.indexOf(normalizedText);
377
+ if (globalIndex !== -1) {
378
+ const originalStart = fullToOriginal[globalIndex];
379
+ const endNormIndex = globalIndex + normalizedText.length - 1;
380
+ let originalEnd = fullToOriginal[endNormIndex] + 1;
381
+ while (originalEnd < source.length && /\s/.test(source[originalEnd])) {
382
+ originalEnd++;
383
+ }
384
+ return {
385
+ start: originalStart,
386
+ end: originalEnd,
387
+ line: getLineNumber(source, originalStart),
388
+ confidence: AnchorConfidences.NORMALIZED
389
+ };
390
+ }
391
+ return;
392
+ }
393
+ function findAnchorFuzzy({
394
+ source,
395
+ selectedText,
396
+ lineHint,
397
+ threshold = DEFAULT_FUZZY_THRESHOLD
398
+ }) {
399
+ if (!selectedText || !source) {
400
+ return;
401
+ }
402
+ const textLen = selectedText.length;
403
+ if (textLen > MAX_FUZZY_TEXT_LENGTH) {
404
+ return;
405
+ }
406
+ let bestMatch;
407
+ let bestDistance = threshold + 1;
408
+ let searchStart = 0;
409
+ let searchEnd = source.length;
410
+ if (lineHint) {
411
+ const { start: hintLine } = parseLineHint(lineHint);
412
+ const lineOffset = getLineOffset(source, hintLine);
413
+ searchStart = Math.max(0, lineOffset - FUZZY_SEARCH_WINDOW);
414
+ searchEnd = Math.min(source.length, lineOffset + FUZZY_SEARCH_WINDOW);
415
+ }
416
+ const minLen = Math.max(1, textLen - threshold);
417
+ const maxLen = textLen + threshold;
418
+ for (let len = minLen;len <= maxLen; len++) {
419
+ for (let i = searchStart;i <= searchEnd - len; i++) {
420
+ const candidate = source.slice(i, i + len);
421
+ const distance = levenshteinDistance(selectedText, candidate, bestDistance - 1);
422
+ if (distance < bestDistance) {
423
+ bestDistance = distance;
424
+ bestMatch = {
425
+ start: i,
426
+ end: i + len,
427
+ line: getLineNumber(source, i),
428
+ confidence: AnchorConfidences.FUZZY,
429
+ distance
430
+ };
431
+ if (distance === 0) {
432
+ return bestMatch;
433
+ }
434
+ }
435
+ }
436
+ }
437
+ return bestMatch;
438
+ }
439
+ function findAnchorWithFallback({
440
+ source,
441
+ selectedText,
442
+ lineHint,
443
+ fuzzyThreshold
444
+ }) {
445
+ const exactMatch = findAnchor({ source, selectedText, lineHint });
446
+ if (exactMatch) {
447
+ return exactMatch;
448
+ }
449
+ const normalizedMatch = findAnchorNormalized({
450
+ source,
451
+ selectedText,
452
+ lineHint
453
+ });
454
+ if (normalizedMatch) {
455
+ return normalizedMatch;
456
+ }
457
+ return findAnchorFuzzy({
458
+ source,
459
+ selectedText,
460
+ lineHint,
461
+ threshold: fuzzyThreshold
462
+ });
463
+ }
464
+
465
+ // src/lib/highlight/resolver.ts
466
+ function findTextPosition(textContent, selectedText, hintOffset) {
467
+ if (!selectedText || !textContent)
468
+ return;
469
+ const occurrences = [];
470
+ let idx = 0;
471
+ for (;; ) {
472
+ idx = textContent.indexOf(selectedText, idx);
473
+ if (idx === -1)
474
+ break;
475
+ occurrences.push(idx);
476
+ idx += 1;
477
+ }
478
+ if (occurrences.length === 0)
479
+ return;
480
+ if (occurrences.length === 1) {
481
+ return {
482
+ start: occurrences[0],
483
+ end: occurrences[0] + selectedText.length
484
+ };
485
+ }
486
+ const target = hintOffset ?? 0;
487
+ let closest = occurrences[0];
488
+ let minDist = Math.abs(closest - target);
489
+ for (const occ of occurrences) {
490
+ const dist = Math.abs(occ - target);
491
+ if (dist < minDist) {
492
+ minDist = dist;
493
+ closest = occ;
494
+ }
495
+ }
496
+ return { start: closest, end: closest + selectedText.length };
497
+ }
498
+
499
+ // src/lib/html-text.ts
500
+ var BLOCK_ELEMENTS = new Set([
501
+ "p",
502
+ "div",
503
+ "h1",
504
+ "h2",
505
+ "h3",
506
+ "h4",
507
+ "h5",
508
+ "h6",
509
+ "pre",
510
+ "blockquote",
511
+ "li",
512
+ "tr",
513
+ "br"
514
+ ]);
515
+ function extractTextFromHtml(html) {
516
+ const textNodes = collectTextNodesFromHtml(html);
517
+ if (textNodes.length === 0)
518
+ return "";
519
+ let result = "";
520
+ let lastBlockPath = null;
521
+ for (const node of textNodes) {
522
+ if (lastBlockPath) {
523
+ const lastBlock = lastBlockPath;
524
+ const currBlock = node.blockAncestorPath;
525
+ if (lastBlock.length > 0 && currBlock.length > 0 && !isNested(lastBlock, currBlock)) {
526
+ if (lastBlock[lastBlock.length - 1] !== currBlock[currBlock.length - 1]) {
527
+ result += `
528
+ `;
529
+ }
530
+ }
531
+ }
532
+ result += node.text;
533
+ lastBlockPath = node.blockAncestorPath;
534
+ }
535
+ return result;
536
+ }
537
+ function isNested(pathA, pathB) {
538
+ const blockA = pathA[pathA.length - 1];
539
+ const blockB = pathB[pathB.length - 1];
540
+ if (pathB.includes(blockA))
541
+ return true;
542
+ if (pathA.includes(blockB))
543
+ return true;
544
+ return false;
545
+ }
546
+ function collectTextNodesFromHtml(html) {
547
+ const nodes = [];
548
+ const stack = [];
549
+ let idCounter = 0;
550
+ const tagPattern = /<\/?([a-zA-Z][a-zA-Z0-9]*)[^>]*\/?>/g;
551
+ let lastIndex = 0;
552
+ let match;
553
+ match = tagPattern.exec(html);
554
+ while (match !== null) {
555
+ if (match.index > lastIndex) {
556
+ const text = decodeEntities(html.slice(lastIndex, match.index));
557
+ if (text) {
558
+ nodes.push({
559
+ text,
560
+ blockAncestorPath: getBlockAncestorPath(stack)
561
+ });
562
+ }
563
+ }
564
+ const fullTag = match[0];
565
+ const tagName = match[1].toLowerCase();
566
+ const isClosing = fullTag.startsWith("</");
567
+ const isSelfClosing = fullTag.endsWith("/>") || isVoidElement(tagName);
568
+ if (isClosing) {
569
+ for (let i = stack.length - 1;i >= 0; i--) {
570
+ if (stack[i].tag === tagName) {
571
+ stack.splice(i);
572
+ break;
573
+ }
574
+ }
575
+ } else if (!isSelfClosing) {
576
+ stack.push({ tag: tagName, id: `e${idCounter++}` });
577
+ }
578
+ lastIndex = match.index + fullTag.length;
579
+ match = tagPattern.exec(html);
580
+ }
581
+ if (lastIndex < html.length) {
582
+ const text = decodeEntities(html.slice(lastIndex));
583
+ if (text) {
584
+ nodes.push({
585
+ text,
586
+ blockAncestorPath: getBlockAncestorPath(stack)
587
+ });
588
+ }
589
+ }
590
+ return nodes;
591
+ }
592
+ function getBlockAncestorPath(stack) {
593
+ const path2 = [];
594
+ for (const entry of stack) {
595
+ if (BLOCK_ELEMENTS.has(entry.tag)) {
596
+ path2.push(entry.id);
597
+ }
598
+ }
599
+ return path2;
600
+ }
601
+ var VOID_ELEMENTS = new Set([
602
+ "area",
603
+ "base",
604
+ "br",
605
+ "col",
606
+ "embed",
607
+ "hr",
608
+ "img",
609
+ "input",
610
+ "link",
611
+ "meta",
612
+ "param",
613
+ "source",
614
+ "track",
615
+ "wbr"
616
+ ]);
617
+ function isVoidElement(tag) {
618
+ return VOID_ELEMENTS.has(tag);
619
+ }
620
+ function decodeEntities(text) {
621
+ return text.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&#x27;/g, "'").replace(/&nbsp;/g, "\xA0").replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number(code))).replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
622
+ }
623
+
624
+ // src/lib/key-lock.ts
625
+ var locks = new Map;
626
+ function namespace(name) {
627
+ let n = locks.get(name);
628
+ if (!n) {
629
+ n = new Map;
630
+ locks.set(name, n);
631
+ }
632
+ return n;
633
+ }
634
+ function createKeyLock(name) {
635
+ const map = namespace(name);
636
+ return function withLock(key, fn) {
637
+ const prev = map.get(key) ?? Promise.resolve();
638
+ const next = prev.catch(() => {}).then(fn);
639
+ map.set(key, next.catch(() => {}));
640
+ return next;
641
+ };
642
+ }
643
+
644
+ // src/lib/markdown-renderer.ts
645
+ import MarkdownIt from "markdown-it";
646
+
647
+ // src/lib/headings.ts
648
+ function slugify(text) {
649
+ return text.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-");
650
+ }
651
+ function stripCodeBlocks(content) {
652
+ let result = content.replace(/^(`{3,}|~{3,}).*$[\s\S]*?^\1\s*$/gm, "");
653
+ result = result.replace(/(?:^|\n\n)((?:(?:[ ]{4}|\t).+\n?)+)/g, `
654
+
655
+ `);
656
+ return result;
657
+ }
658
+ function parseMarkdownHeadings(content) {
659
+ const headings = [];
660
+ const seenIds = new Map;
661
+ const contentWithoutCode = stripCodeBlocks(content);
662
+ const regex = /^(#{1,6})\s+(.+)$/gm;
663
+ let match = regex.exec(contentWithoutCode);
664
+ while (match !== null) {
665
+ const level = match[1].length;
666
+ const text = match[2].trim();
667
+ const baseId = slugify(text);
668
+ const count = seenIds.get(baseId) ?? 0;
669
+ const id = count > 0 ? `${baseId}-${count}` : baseId;
670
+ seenIds.set(baseId, count + 1);
671
+ headings.push({ id, text, level });
672
+ match = regex.exec(contentWithoutCode);
673
+ }
674
+ return headings;
675
+ }
676
+
677
+ // src/lib/mermaid-renderer.ts
678
+ var RENDER_TIMEOUT_MS = 15000;
679
+ var MAX_CONSECUTIVE_ERRORS = 3;
680
+ var worker = null;
681
+ var workerReady = null;
682
+ var pendingRequests = new Map;
683
+ var requestCounter = 0;
684
+ var consecutiveErrors = 0;
685
+ function resetWorker(reason, currentWorker = worker) {
686
+ if (currentWorker)
687
+ currentWorker.terminate();
688
+ if (worker === currentWorker) {
689
+ worker = null;
690
+ workerReady = null;
691
+ }
692
+ for (const [, pending] of pendingRequests) {
693
+ clearTimeout(pending.timer);
694
+ pending.reject(reason);
695
+ }
696
+ pendingRequests.clear();
697
+ }
698
+ function createWorker() {
699
+ const w = new Worker(new URL("./mermaid-worker.ts", import.meta.url).href, {
700
+ type: "module"
701
+ });
702
+ const ready = new Promise((resolve2, reject) => {
703
+ const timeout = setTimeout(() => {
704
+ w.removeEventListener("message", onReady);
705
+ w.removeEventListener("error", onStartupError);
706
+ w.terminate();
707
+ if (worker === w) {
708
+ worker = null;
709
+ workerReady = null;
710
+ }
711
+ reject(new Error("Mermaid worker failed to start within 30s"));
712
+ }, 30000);
713
+ function onStartupError(event) {
714
+ clearTimeout(timeout);
715
+ w.removeEventListener("message", onReady);
716
+ w.removeEventListener("error", onStartupError);
717
+ w.terminate();
718
+ if (worker === w) {
719
+ worker = null;
720
+ workerReady = null;
721
+ }
722
+ reject(new Error(`Mermaid worker failed to start: ${event.message}`));
723
+ }
724
+ function onReady(event) {
725
+ if (event.data?.type === "ready") {
726
+ clearTimeout(timeout);
727
+ w.removeEventListener("message", onReady);
728
+ w.removeEventListener("error", onStartupError);
729
+ resolve2();
730
+ }
731
+ }
732
+ w.addEventListener("message", onReady);
733
+ w.addEventListener("error", onStartupError);
734
+ });
735
+ w.addEventListener("message", (event) => {
736
+ const { id, svg, error } = event.data;
737
+ if (!id)
738
+ return;
739
+ const pending = pendingRequests.get(id);
740
+ if (!pending)
741
+ return;
742
+ clearTimeout(pending.timer);
743
+ pendingRequests.delete(id);
744
+ if (error) {
745
+ consecutiveErrors++;
746
+ pending.reject(new Error(error));
747
+ } else {
748
+ consecutiveErrors = 0;
749
+ pending.resolve(svg);
750
+ }
751
+ });
752
+ w.addEventListener("error", (event) => {
753
+ resetWorker(new Error(`Worker error: ${event.message}`), w);
754
+ });
755
+ return { worker: w, ready };
756
+ }
757
+ async function ensureWorker() {
758
+ if (worker && workerReady) {
759
+ await workerReady;
760
+ if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
761
+ resetWorker(new Error("Mermaid worker restarted after repeated render failures"));
762
+ consecutiveErrors = 0;
763
+ }
764
+ }
765
+ if (!worker) {
766
+ const result = createWorker();
767
+ worker = result.worker;
768
+ workerReady = result.ready;
769
+ await workerReady;
770
+ }
771
+ return worker;
772
+ }
773
+ async function renderMermaidSvg(code) {
774
+ const w = await ensureWorker();
775
+ const id = `req-${++requestCounter}`;
776
+ const diagramId = `mermaid-ssr-${requestCounter}`;
777
+ return new Promise((resolve2, reject) => {
778
+ const timer = setTimeout(() => {
779
+ pendingRequests.delete(id);
780
+ resetWorker(new Error(`Mermaid render timed out after ${RENDER_TIMEOUT_MS}ms`), w);
781
+ reject(new Error(`Mermaid render timed out after ${RENDER_TIMEOUT_MS}ms`));
782
+ }, RENDER_TIMEOUT_MS);
783
+ pendingRequests.set(id, { resolve: resolve2, reject, timer });
784
+ w.postMessage({ id, code, diagramId });
785
+ });
786
+ }
787
+ async function renderMermaidBlocks(blocks) {
788
+ const results = [];
789
+ for (const code of blocks) {
790
+ try {
791
+ const svg = await renderMermaidSvg(code);
792
+ results.push(svg);
793
+ } catch {
794
+ results.push(null);
795
+ }
796
+ }
797
+ return results;
798
+ }
799
+ function disposeMermaidWorker() {
800
+ resetWorker(new Error("Mermaid worker disposed"));
801
+ }
802
+
803
+ // src/lib/markdown-renderer.ts
804
+ var SHIKI_LANGUAGES = [
805
+ "bash",
806
+ "css",
807
+ "diff",
808
+ "go",
809
+ "graphql",
810
+ "javascript",
811
+ "json",
812
+ "jsx",
813
+ "markdown",
814
+ "python",
815
+ "rust",
816
+ "sql",
817
+ "tsx",
818
+ "typescript",
819
+ "yaml"
820
+ ];
821
+ var SHIKI_THEME = "one-dark-pro";
822
+ var shikiInstance = null;
823
+ var shikiPromise = null;
824
+ async function getShiki() {
825
+ if (shikiInstance)
826
+ return shikiInstance;
827
+ if (shikiPromise)
828
+ return shikiPromise;
829
+ shikiPromise = import("shiki").then(async ({ createHighlighter }) => {
830
+ const highlighter = await createHighlighter({
831
+ themes: [SHIKI_THEME],
832
+ langs: SHIKI_LANGUAGES
833
+ });
834
+ shikiInstance = highlighter;
835
+ return highlighter;
836
+ });
837
+ return shikiPromise;
838
+ }
839
+ function createMarkdownRenderer(shiki) {
840
+ const md = new MarkdownIt({
841
+ html: true,
842
+ linkify: true,
843
+ typographer: false,
844
+ highlight(code, lang) {
845
+ if (lang === "mermaid") {
846
+ return `<pre><code class="language-mermaid">${md.utils.escapeHtml(code)}</code></pre>`;
847
+ }
848
+ const language = normalizeLanguage(lang);
849
+ if (language && shiki.getLoadedLanguages().includes(language)) {
850
+ return shiki.codeToHtml(code, {
851
+ lang: language,
852
+ theme: SHIKI_THEME
853
+ });
854
+ }
855
+ return `<pre class="shiki"><code>${md.utils.escapeHtml(code)}</code></pre>`;
856
+ }
857
+ });
858
+ return md;
859
+ }
860
+ function normalizeLanguage(lang) {
861
+ const aliases = {
862
+ sh: "bash",
863
+ shell: "bash",
864
+ js: "javascript",
865
+ ts: "typescript",
866
+ py: "python",
867
+ rs: "rust",
868
+ yml: "yaml",
869
+ md: "markdown"
870
+ };
871
+ const normalized = lang.toLowerCase().trim();
872
+ if (SHIKI_LANGUAGES.includes(normalized)) {
873
+ return normalized;
874
+ }
875
+ return aliases[normalized];
876
+ }
877
+ function injectHeadingIds(html, headings) {
878
+ let headingIdx = 0;
879
+ return html.replace(/<(h[1-6])([^>]*)>([\s\S]*?)<\/\1>/gi, (match, tag, attrs, content) => {
880
+ if (headingIdx >= headings.length)
881
+ return match;
882
+ const heading = headings[headingIdx];
883
+ headingIdx++;
884
+ if (/\bid\s*=/.test(attrs))
885
+ return match;
886
+ return `<${tag} id="${heading.id}"${attrs}>${content}</${tag}>`;
887
+ });
888
+ }
889
+ var MERMAID_BLOCK_RE = /<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g;
890
+ function unescapeHtml(str) {
891
+ return str.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"');
892
+ }
893
+ async function replaceMermaidBlocks(html) {
894
+ MERMAID_BLOCK_RE.lastIndex = 0;
895
+ const matches = [];
896
+ let match = MERMAID_BLOCK_RE.exec(html);
897
+ while (match !== null) {
898
+ matches.push({
899
+ fullMatch: match[0],
900
+ code: unescapeHtml(match[1]),
901
+ index: match.index
902
+ });
903
+ match = MERMAID_BLOCK_RE.exec(html);
904
+ }
905
+ if (matches.length === 0)
906
+ return html;
907
+ const codes = matches.map((m) => m.code);
908
+ const svgs = await renderMermaidBlocks(codes);
909
+ for (let i = matches.length - 1;i >= 0; i--) {
910
+ const svg = svgs[i];
911
+ if (svg !== null) {
912
+ const { fullMatch, index, code } = matches[i];
913
+ const encodedSource = encodeURIComponent(code);
914
+ const replacement = `<div class="mermaid-container" data-mermaid-source="${encodedSource}">${svg}</div>`;
915
+ html = html.slice(0, index) + replacement + html.slice(index + fullMatch.length);
916
+ }
917
+ }
918
+ return html;
919
+ }
920
+ async function renderMarkdown(content) {
921
+ const shiki = await getShiki();
922
+ const md = createMarkdownRenderer(shiki);
923
+ const headings = parseMarkdownHeadings(content);
924
+ let html = md.render(content);
925
+ html = injectHeadingIds(html, headings);
926
+ html = await replaceMermaidBlocks(html);
927
+ return { html, headings };
928
+ }
929
+
930
+ // src/template.ts
931
+ function safeJsonStringify(data) {
932
+ return JSON.stringify(data).replace(/</g, "\\u003c");
933
+ }
934
+ function escapeHtml(str) {
935
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
936
+ }
937
+ function escapeAttr(str) {
938
+ return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
939
+ }
940
+ function sanitizeHtml(html) {
941
+ let sanitized = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
942
+ sanitized = sanitized.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
943
+ sanitized = sanitized.replace(/\bhref\s*=\s*(?:"javascript:[^"]*"|'javascript:[^']*')/gi, "");
944
+ sanitized = sanitized.replace(/\bsrc\s*=\s*(?:"javascript:[^"]*"|'javascript:[^']*')/gi, "");
945
+ return sanitized;
946
+ }
947
+ function renderTemplate(options) {
948
+ const {
949
+ title,
950
+ cssPath,
951
+ jsPath,
952
+ documentHtml,
953
+ inlineData,
954
+ isDev,
955
+ fontFamily
956
+ } = options;
957
+ const viteClient = isDev ? '<script type="module" src="http://127.0.0.1:24678/@vite/client"></script>' : "";
958
+ const cssLink = cssPath ? `<link rel="stylesheet" href="${escapeAttr(cssPath)}">` : "";
959
+ const proseClass = fontFamily === "sans-serif" ? "prose-sans" : "prose-serif";
960
+ return `<!DOCTYPE html>
961
+ <html lang="en">
962
+ <head>
963
+ <meta charset="UTF-8">
964
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
965
+ <title>readit \u2014 ${escapeHtml(title)}</title>
966
+ <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>\uD83D\uDCD6</text></svg>">
967
+ <script>
968
+ (() => {
969
+ var t = localStorage.getItem("readit:theme");
970
+ var d = t === "dark" || (t !== "light" && matchMedia("(prefers-color-scheme: dark)").matches);
971
+ if (d) document.documentElement.classList.add("dark");
972
+ })();
973
+ </script>
974
+ ${viteClient}
975
+ ${cssLink}
976
+ </head>
977
+ <body class="min-h-screen">
978
+ <article id="document-content" class="prose ${proseClass}">${sanitizeHtml(documentHtml)}</article>
979
+ <div id="app"></div>
980
+ <script type="application/json" id="__readit">${safeJsonStringify(inlineData)}</script>
981
+ <script type="module" src="${escapeAttr(jsPath)}" defer></script>
982
+ </body>
983
+ </html>`;
984
+ }
985
+
986
+ // src/server.ts
987
+ function isErrnoException(err) {
988
+ return err instanceof Error && "code" in err;
989
+ }
990
+ var resolvedCommentsCache = new Map;
991
+ function invalidateResolvedComments(filePath) {
992
+ resolvedCommentsCache.delete(filePath);
993
+ }
994
+ var withCommentLock = createKeyLock("comments");
995
+ async function canonicalPath(filePath) {
996
+ return fs.realpath(path2.resolve(filePath));
997
+ }
998
+ async function readCommentsFromFile(filePath, sourceContent, renderedHtml) {
999
+ const commentPath = getCommentPath(filePath);
1000
+ const sourceHash = computeHash(sourceContent);
1001
+ try {
1002
+ const stats = await fs.stat(commentPath);
1003
+ const cached = resolvedCommentsCache.get(filePath);
1004
+ if (cached && cached.sourceHash === sourceHash && cached.commentMtimeMs === stats.mtimeMs) {
1005
+ return cached.comments;
1006
+ }
1007
+ const content = await fs.readFile(commentPath, "utf-8");
1008
+ const file = parseCommentFile(content);
1009
+ const domText = renderedHtml ? extractTextFromHtml(renderedHtml) : null;
1010
+ const resolvedComments = file.comments.map((comment) => {
1011
+ const textForMatching = comment.anchorPrefix || comment.selectedText;
1012
+ const anchor = findAnchorWithFallback({
1013
+ source: sourceContent,
1014
+ selectedText: textForMatching,
1015
+ lineHint: comment.lineHint || "L1"
1016
+ });
1017
+ if (!anchor) {
1018
+ return {
1019
+ ...comment,
1020
+ anchorConfidence: AnchorConfidences.UNRESOLVED
1021
+ };
1022
+ }
1023
+ let startOffset = anchor.start;
1024
+ let endOffset = anchor.end;
1025
+ if (domText) {
1026
+ const domPos = findTextPosition(domText, comment.selectedText, anchor.start);
1027
+ if (domPos) {
1028
+ startOffset = domPos.start;
1029
+ endOffset = domPos.end;
1030
+ }
1031
+ }
1032
+ return {
1033
+ ...comment,
1034
+ startOffset,
1035
+ endOffset,
1036
+ lineHint: `L${anchor.line}`,
1037
+ anchorConfidence: anchor.confidence
1038
+ };
1039
+ });
1040
+ resolvedCommentsCache.set(filePath, {
1041
+ sourceHash,
1042
+ commentMtimeMs: stats.mtimeMs,
1043
+ comments: resolvedComments
1044
+ });
1045
+ return resolvedComments;
1046
+ } catch (err) {
1047
+ if (isErrnoException(err) && err.code === "ENOENT") {
1048
+ invalidateResolvedComments(filePath);
1049
+ return [];
1050
+ }
1051
+ throw err;
1052
+ }
1053
+ }
1054
+ async function writeCommentsToFile(filePath, sourceContent, comments) {
1055
+ const commentPath = getCommentPath(filePath);
1056
+ const commentDir = dirname2(commentPath);
1057
+ await fs.mkdir(commentDir, { recursive: true });
1058
+ const file = {
1059
+ source: filePath,
1060
+ hash: computeHash(sourceContent),
1061
+ version: 1,
1062
+ comments
1063
+ };
1064
+ const content = serializeComments(file);
1065
+ const tempPath = `${commentPath}.tmp`;
1066
+ await fs.writeFile(tempPath, content, "utf-8");
1067
+ await fs.rename(tempPath, commentPath);
1068
+ invalidateResolvedComments(filePath);
1069
+ }
1070
+ async function deleteCommentFile(filePath) {
1071
+ const commentPath = getCommentPath(filePath);
1072
+ try {
1073
+ await fs.unlink(commentPath);
1074
+ } catch (err) {
1075
+ if (!isErrnoException(err) || err.code !== "ENOENT") {
1076
+ throw err;
1077
+ }
1078
+ }
1079
+ invalidateResolvedComments(filePath);
1080
+ }
1081
+ var SETTINGS_PATH = path2.join(os2.homedir(), ".readit", "settings.json");
1082
+ var DEFAULT_SETTINGS = {
1083
+ version: 1,
1084
+ fontFamily: FontFamilies.SERIF
1085
+ };
1086
+ async function readSettings() {
1087
+ try {
1088
+ const content = await fs.readFile(SETTINGS_PATH, "utf-8");
1089
+ return JSON.parse(content);
1090
+ } catch (err) {
1091
+ if (isErrnoException(err) && err.code === "ENOENT") {
1092
+ return DEFAULT_SETTINGS;
1093
+ }
1094
+ throw err;
1095
+ }
1096
+ }
1097
+ async function writeSettings(settings) {
1098
+ const settingsDir = dirname2(SETTINGS_PATH);
1099
+ await fs.mkdir(settingsDir, { recursive: true });
1100
+ const tempPath = `${SETTINGS_PATH}.tmp`;
1101
+ await fs.writeFile(tempPath, JSON.stringify(settings, null, 2), "utf-8");
1102
+ await fs.rename(tempPath, SETTINGS_PATH);
1103
+ }
1104
+ function isValidFontFamily(value) {
1105
+ return value === FontFamilies.SERIF || value === FontFamilies.SANS_SERIF;
1106
+ }
1107
+ var SERVER_INFO_PATH = path2.join(os2.homedir(), ".readit", "server.json");
1108
+ async function writeServerInfo(port) {
1109
+ await fs.mkdir(path2.dirname(SERVER_INFO_PATH), { recursive: true });
1110
+ await fs.writeFile(SERVER_INFO_PATH, JSON.stringify({ port, pid: process.pid }), "utf-8");
1111
+ }
1112
+ async function removeServerInfo() {
1113
+ try {
1114
+ await fs.unlink(SERVER_INFO_PATH);
1115
+ } catch (err) {
1116
+ if (!isErrnoException(err) || err.code !== "ENOENT") {
1117
+ console.error("Failed to remove server info:", err);
1118
+ }
1119
+ }
1120
+ }
1121
+ function json(data, status = 200) {
1122
+ return Response.json(data, { status });
1123
+ }
1124
+ function errorResponse(message, status) {
1125
+ return Response.json({ error: message }, { status });
1126
+ }
1127
+ function errorWithDetail(message, err, status = 500) {
1128
+ const detail = err instanceof Error ? err.message : String(err);
1129
+ return errorResponse(`${message}: ${detail}`, status);
1130
+ }
1131
+ async function getComments(ctx, renderedHtml) {
1132
+ try {
1133
+ const currentContent = await ctx.getCurrentContent();
1134
+ const comments = await readCommentsFromFile(ctx.filePath, currentContent, renderedHtml);
1135
+ return json({ comments });
1136
+ } catch (err) {
1137
+ console.error("Failed to read comments:", err);
1138
+ return errorResponse("Failed to read comments", 500);
1139
+ }
1140
+ }
1141
+ async function addComment(ctx, req) {
1142
+ try {
1143
+ const {
1144
+ selectedText,
1145
+ comment: commentText,
1146
+ startOffset,
1147
+ endOffset
1148
+ } = await req.json();
1149
+ if (!selectedText || typeof commentText !== "string" || startOffset === undefined || endOffset === undefined) {
1150
+ return errorResponse("Missing required fields", 400);
1151
+ }
1152
+ const currentContent = await ctx.getCurrentContent();
1153
+ const newComment = createComment(selectedText, commentText, startOffset, endOffset, currentContent);
1154
+ await withCommentLock(ctx.filePath, async () => {
1155
+ const existingComments = await readCommentsFromFile(ctx.filePath, currentContent);
1156
+ const allComments = [...existingComments, newComment];
1157
+ await writeCommentsToFile(ctx.filePath, currentContent, allComments);
1158
+ });
1159
+ return json({ comment: newComment }, 201);
1160
+ } catch (err) {
1161
+ console.error("Failed to add comment:", err);
1162
+ return errorWithDetail("Failed to add comment", err);
1163
+ }
1164
+ }
1165
+ async function updateComment(ctx, req, id) {
1166
+ try {
1167
+ const { comment: commentText } = await req.json();
1168
+ if (typeof commentText !== "string") {
1169
+ return errorResponse("Missing comment text", 400);
1170
+ }
1171
+ const currentContent = await ctx.getCurrentContent();
1172
+ const result = await withCommentLock(ctx.filePath, async () => {
1173
+ const existingComments = await readCommentsFromFile(ctx.filePath, currentContent);
1174
+ const commentIndex = existingComments.findIndex((c) => c.id === id);
1175
+ if (commentIndex === -1)
1176
+ return null;
1177
+ const updatedComments = existingComments.map((c, i) => i === commentIndex ? { ...c, comment: commentText.trim() } : c);
1178
+ await writeCommentsToFile(ctx.filePath, currentContent, updatedComments);
1179
+ return updatedComments[commentIndex];
1180
+ });
1181
+ if (!result)
1182
+ return errorResponse("Comment not found", 404);
1183
+ return json({ comment: result });
1184
+ } catch (err) {
1185
+ console.error("Failed to update comment:", err);
1186
+ return errorWithDetail("Failed to update comment", err);
1187
+ }
1188
+ }
1189
+ async function deleteComment(ctx, id) {
1190
+ try {
1191
+ const currentContent = await ctx.getCurrentContent();
1192
+ const found = await withCommentLock(ctx.filePath, async () => {
1193
+ const existingComments = await readCommentsFromFile(ctx.filePath, currentContent);
1194
+ const filteredComments = existingComments.filter((c) => c.id !== id);
1195
+ if (filteredComments.length === existingComments.length)
1196
+ return false;
1197
+ if (filteredComments.length === 0) {
1198
+ await deleteCommentFile(ctx.filePath);
1199
+ } else {
1200
+ await writeCommentsToFile(ctx.filePath, currentContent, filteredComments);
1201
+ }
1202
+ return true;
1203
+ });
1204
+ if (!found)
1205
+ return errorResponse("Comment not found", 404);
1206
+ return json({ success: true });
1207
+ } catch (err) {
1208
+ console.error("Failed to delete comment:", err);
1209
+ return errorWithDetail("Failed to delete comment", err);
1210
+ }
1211
+ }
1212
+ async function clearComments(ctx) {
1213
+ try {
1214
+ await withCommentLock(ctx.filePath, () => deleteCommentFile(ctx.filePath));
1215
+ return json({ success: true });
1216
+ } catch (err) {
1217
+ console.error("Failed to clear comments:", err);
1218
+ return errorWithDetail("Failed to clear comments", err);
1219
+ }
1220
+ }
1221
+ async function getRawComments(ctx) {
1222
+ const commentPath = getCommentPath(ctx.filePath);
1223
+ try {
1224
+ const content = await fs.readFile(commentPath, "utf-8");
1225
+ return json({ content, path: commentPath });
1226
+ } catch (err) {
1227
+ if (isErrnoException(err) && err.code === "ENOENT") {
1228
+ return json({ content: null, path: commentPath });
1229
+ }
1230
+ console.error("Failed to read raw comments:", err);
1231
+ return errorResponse("Failed to read raw comments", 500);
1232
+ }
1233
+ }
1234
+ async function reanchorComment(ctx, req, id) {
1235
+ try {
1236
+ const { selectedText, startOffset, endOffset } = await req.json();
1237
+ if (!selectedText || startOffset === undefined || endOffset === undefined) {
1238
+ return errorResponse("Missing required fields", 400);
1239
+ }
1240
+ const currentContent = await ctx.getCurrentContent();
1241
+ const result = await withCommentLock(ctx.filePath, async () => {
1242
+ const existingComments = await readCommentsFromFile(ctx.filePath, currentContent);
1243
+ const commentIndex = existingComments.findIndex((c) => c.id === id);
1244
+ if (commentIndex === -1)
1245
+ return null;
1246
+ const lineHint = getLineHint(currentContent, startOffset, endOffset);
1247
+ const truncatedText = truncateSelection(selectedText);
1248
+ const updatedComment = {
1249
+ ...existingComments[commentIndex],
1250
+ selectedText: truncatedText,
1251
+ startOffset,
1252
+ endOffset,
1253
+ lineHint,
1254
+ anchorConfidence: AnchorConfidences.EXACT,
1255
+ anchorPrefix: selectedText.length > 1000 ? selectedText.slice(0, 200) : undefined
1256
+ };
1257
+ const updatedComments = existingComments.map((c, i) => i === commentIndex ? updatedComment : c);
1258
+ await writeCommentsToFile(ctx.filePath, currentContent, updatedComments);
1259
+ return updatedComment;
1260
+ });
1261
+ if (!result)
1262
+ return errorResponse("Comment not found", 404);
1263
+ return json({ comment: result });
1264
+ } catch (err) {
1265
+ console.error("Failed to re-anchor comment:", err);
1266
+ return errorWithDetail("Failed to re-anchor comment", err);
1267
+ }
1268
+ }
1269
+ async function getSettingsRoute() {
1270
+ try {
1271
+ const settings = await readSettings();
1272
+ return json(settings);
1273
+ } catch (err) {
1274
+ console.error("Failed to read settings:", err);
1275
+ return errorResponse("Failed to read settings", 500);
1276
+ }
1277
+ }
1278
+ async function updateSettingsRoute(req) {
1279
+ try {
1280
+ const body = await req.json();
1281
+ const { fontFamily } = body;
1282
+ if (fontFamily !== undefined && !isValidFontFamily(fontFamily)) {
1283
+ return errorResponse("Invalid font family", 400);
1284
+ }
1285
+ const current = await readSettings();
1286
+ const settings = {
1287
+ ...current,
1288
+ ...fontFamily !== undefined && { fontFamily }
1289
+ };
1290
+ await writeSettings(settings);
1291
+ return json(settings);
1292
+ } catch (err) {
1293
+ console.error("Failed to save settings:", err);
1294
+ return errorResponse("Failed to save settings", 500);
1295
+ }
1296
+ }
1297
+ function createDocumentStream(sseClients) {
1298
+ let pingInterval;
1299
+ let captured;
1300
+ const stream = new ReadableStream({
1301
+ start(controller) {
1302
+ captured = controller;
1303
+ controller.enqueue(`data: connected
1304
+
1305
+ `);
1306
+ sseClients.add(controller);
1307
+ pingInterval = setInterval(() => {
1308
+ try {
1309
+ controller.enqueue(`data: ping
1310
+
1311
+ `);
1312
+ } catch {
1313
+ clearInterval(pingInterval);
1314
+ sseClients.delete(controller);
1315
+ }
1316
+ }, 5000);
1317
+ },
1318
+ cancel() {
1319
+ clearInterval(pingInterval);
1320
+ sseClients.delete(captured);
1321
+ }
1322
+ });
1323
+ return new Response(stream, {
1324
+ headers: {
1325
+ "Content-Type": "text/event-stream",
1326
+ "Cache-Control": "no-cache",
1327
+ Connection: "keep-alive"
1328
+ }
1329
+ });
1330
+ }
1331
+ function createHeartbeat(onOpen, onClose) {
1332
+ let interval;
1333
+ let captured;
1334
+ const stream = new ReadableStream({
1335
+ start(controller) {
1336
+ captured = controller;
1337
+ controller.enqueue(`data: connected
1338
+
1339
+ `);
1340
+ onOpen(controller);
1341
+ interval = setInterval(() => {
1342
+ try {
1343
+ controller.enqueue(`data: ping
1344
+
1345
+ `);
1346
+ } catch {
1347
+ clearInterval(interval);
1348
+ onClose(controller);
1349
+ }
1350
+ }, 5000);
1351
+ },
1352
+ cancel() {
1353
+ clearInterval(interval);
1354
+ onClose(captured);
1355
+ }
1356
+ });
1357
+ return new Response(stream, {
1358
+ headers: {
1359
+ "Content-Type": "text/event-stream",
1360
+ "Cache-Control": "no-cache",
1361
+ Connection: "keep-alive"
1362
+ }
1363
+ });
1364
+ }
1365
+ async function serveStaticFile(distPath, pathname) {
1366
+ const filePath = join3(distPath, pathname);
1367
+ const file = Bun.file(filePath);
1368
+ if (await file.exists()) {
1369
+ const isHashed = pathname.startsWith("/assets/");
1370
+ const headers = isHashed ? { "Cache-Control": "public, max-age=31536000, immutable" } : {};
1371
+ return new Response(file, { headers });
1372
+ }
1373
+ const indexFile = Bun.file(join3(distPath, "index.html"));
1374
+ if (await indexFile.exists()) {
1375
+ return new Response(indexFile);
1376
+ }
1377
+ return new Response("Not Found", { status: 404 });
1378
+ }
1379
+ var VITE_DEV_PORT = 24678;
1380
+ var VITE_DEV_ORIGIN = `http://127.0.0.1:${VITE_DEV_PORT}`;
1381
+ async function proxyToVite(req, pathname, search) {
1382
+ const target = `${VITE_DEV_ORIGIN}${pathname}${search}`;
1383
+ try {
1384
+ return await fetch(new Request(target, {
1385
+ method: req.method,
1386
+ headers: req.headers,
1387
+ body: req.body,
1388
+ redirect: "manual"
1389
+ }));
1390
+ } catch {
1391
+ return new Response("Vite dev server not available", { status: 502 });
1392
+ }
1393
+ }
1394
+ function extractCommentId(pathname) {
1395
+ const match = pathname.match(/^\/api\/comments\/([^/]+)/);
1396
+ return match?.[1];
1397
+ }
1398
+ function createServer(options) {
1399
+ const fileMap = new Map;
1400
+ const fileOrder = [];
1401
+ for (const entry of options.files) {
1402
+ fileMap.set(entry.filePath, {
1403
+ content: entry.content ?? null,
1404
+ renderedHtml: null,
1405
+ headings: null,
1406
+ isLoaded: entry.content !== undefined,
1407
+ debounceTimer: null
1408
+ });
1409
+ fileOrder.push(entry.filePath);
1410
+ if (options.clean) {
1411
+ const commentPath = getCommentPath(entry.filePath);
1412
+ fs.unlink(commentPath).catch(() => {});
1413
+ invalidateResolvedComments(entry.filePath);
1414
+ }
1415
+ }
1416
+ const defaultPath = fileOrder[0];
1417
+ const sseClients = new Set;
1418
+ const heartbeatClients = new Set;
1419
+ let shutdownTimer = null;
1420
+ function sendEvent(event) {
1421
+ const message = `data: ${JSON.stringify(event)}
1422
+
1423
+ `;
1424
+ for (const controller of sseClients) {
1425
+ try {
1426
+ controller.enqueue(message);
1427
+ } catch {
1428
+ sseClients.delete(controller);
1429
+ }
1430
+ }
1431
+ }
1432
+ function clearShutdownTimer() {
1433
+ if (!shutdownTimer)
1434
+ return;
1435
+ clearTimeout(shutdownTimer);
1436
+ shutdownTimer = null;
1437
+ }
1438
+ function onHeartbeatOpen(controller) {
1439
+ heartbeatClients.add(controller);
1440
+ clearShutdownTimer();
1441
+ }
1442
+ function onHeartbeatClose(controller) {
1443
+ heartbeatClients.delete(controller);
1444
+ if (isDev || heartbeatClients.size > 0 || shutdownTimer)
1445
+ return;
1446
+ shutdownTimer = setTimeout(() => {
1447
+ if (heartbeatClients.size > 0) {
1448
+ clearShutdownTimer();
1449
+ return;
1450
+ }
1451
+ console.log(`
1452
+ Browser disconnected, shutting down...`);
1453
+ process.exit(0);
1454
+ }, 1500);
1455
+ }
1456
+ async function ensureFileContent(filePath) {
1457
+ const state = fileMap.get(filePath);
1458
+ if (!state) {
1459
+ throw new Error(`File not found: ${filePath}`);
1460
+ }
1461
+ if (state.isLoaded && state.content !== null) {
1462
+ return state.content;
1463
+ }
1464
+ const content = await fs.readFile(filePath, "utf-8");
1465
+ state.content = content;
1466
+ state.isLoaded = true;
1467
+ return content;
1468
+ }
1469
+ async function ensureRenderedHtml(filePath) {
1470
+ const state = fileMap.get(filePath);
1471
+ if (!state)
1472
+ throw new Error(`File not found: ${filePath}`);
1473
+ if (state.renderedHtml !== null && state.headings !== null) {
1474
+ return { html: state.renderedHtml, headings: state.headings };
1475
+ }
1476
+ const content = await ensureFileContent(filePath);
1477
+ const result = await renderMarkdown(content);
1478
+ state.renderedHtml = result.html;
1479
+ state.headings = result.headings;
1480
+ return result;
1481
+ }
1482
+ function resolveContext(url) {
1483
+ const requestedPath = url.searchParams.get("path") ?? defaultPath;
1484
+ const state = fileMap.get(requestedPath);
1485
+ if (!state)
1486
+ return null;
1487
+ return {
1488
+ filePath: requestedPath,
1489
+ getCurrentContent: () => ensureFileContent(requestedPath)
1490
+ };
1491
+ }
1492
+ function requireContext(url) {
1493
+ const ctx = resolveContext(url);
1494
+ if (!ctx) {
1495
+ return errorResponse("File not found", 404);
1496
+ }
1497
+ return ctx;
1498
+ }
1499
+ const isDev = false;
1500
+ const distPath = import.meta.dir;
1501
+ let manifestCache = null;
1502
+ async function getManifest() {
1503
+ if (manifestCache)
1504
+ return manifestCache;
1505
+ try {
1506
+ const manifestPath = join3(distPath, ".vite", "manifest.json");
1507
+ const content = await fs.readFile(manifestPath, "utf-8");
1508
+ manifestCache = JSON.parse(content);
1509
+ return manifestCache;
1510
+ } catch {
1511
+ return null;
1512
+ }
1513
+ }
1514
+ let pageCache = null;
1515
+ let pageCacheGz = null;
1516
+ function invalidatePageCache() {
1517
+ pageCache = null;
1518
+ pageCacheGz = null;
1519
+ }
1520
+ async function serveAppPage(req) {
1521
+ const acceptGzip = req.headers.get("accept-encoding")?.includes("gzip") ?? false;
1522
+ try {
1523
+ if (pageCache) {
1524
+ if (acceptGzip && pageCacheGz) {
1525
+ return new Response(pageCacheGz, {
1526
+ headers: {
1527
+ "Content-Type": "text/html; charset=utf-8",
1528
+ "Content-Encoding": "gzip"
1529
+ }
1530
+ });
1531
+ }
1532
+ return new Response(pageCache, {
1533
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1534
+ });
1535
+ }
1536
+ const { html, headings } = await ensureRenderedHtml(defaultPath);
1537
+ const content = await ensureFileContent(defaultPath);
1538
+ const comments = await readCommentsFromFile(defaultPath, content, html);
1539
+ const settings = await readSettings();
1540
+ const files = fileOrder.map((fp) => ({
1541
+ path: fp,
1542
+ fileName: basename(fp)
1543
+ }));
1544
+ const inlineData = {
1545
+ files,
1546
+ activeFile: defaultPath,
1547
+ settings,
1548
+ documents: {
1549
+ [defaultPath]: {
1550
+ headings,
1551
+ comments
1552
+ }
1553
+ },
1554
+ clean: options.clean || false,
1555
+ workingDirectory: process.cwd()
1556
+ };
1557
+ let cssPath = "";
1558
+ let jsPath;
1559
+ if (isDev) {
1560
+ jsPath = `http://127.0.0.1:${VITE_DEV_PORT}/src/main.ts`;
1561
+ } else {
1562
+ const manifest = await getManifest();
1563
+ const entry = manifest?.["index.html"];
1564
+ jsPath = entry ? `/${entry.file}` : "/assets/index.js";
1565
+ if (entry?.css?.[0]) {
1566
+ cssPath = `/${entry.css[0]}`;
1567
+ }
1568
+ }
1569
+ const body = renderTemplate({
1570
+ title: basename(defaultPath),
1571
+ cssPath,
1572
+ jsPath,
1573
+ documentHtml: html,
1574
+ inlineData,
1575
+ isDev,
1576
+ fontFamily: settings.fontFamily
1577
+ });
1578
+ if (!isDev) {
1579
+ pageCache = body;
1580
+ pageCacheGz = Bun.gzipSync(new TextEncoder().encode(body));
1581
+ }
1582
+ if (acceptGzip) {
1583
+ const gz = pageCacheGz ?? Bun.gzipSync(new TextEncoder().encode(body));
1584
+ return new Response(gz, {
1585
+ headers: {
1586
+ "Content-Type": "text/html; charset=utf-8",
1587
+ "Content-Encoding": "gzip"
1588
+ }
1589
+ });
1590
+ }
1591
+ return new Response(body, {
1592
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1593
+ });
1594
+ } catch (err) {
1595
+ console.error("Failed to serve app page:", err);
1596
+ return new Response("Internal Server Error", { status: 500 });
1597
+ }
1598
+ }
1599
+ function watchFile(targetPath) {
1600
+ try {
1601
+ const watcher = watch(targetPath, async (eventType) => {
1602
+ if (eventType !== "change" && eventType !== "rename")
1603
+ return;
1604
+ const state = fileMap.get(targetPath);
1605
+ if (!state)
1606
+ return;
1607
+ if (state.debounceTimer)
1608
+ clearTimeout(state.debounceTimer);
1609
+ state.debounceTimer = setTimeout(async () => {
1610
+ try {
1611
+ const newContent = await fs.readFile(targetPath, "utf-8");
1612
+ if (!state.isLoaded || newContent !== state.content) {
1613
+ state.content = newContent;
1614
+ state.renderedHtml = null;
1615
+ state.headings = null;
1616
+ state.isLoaded = true;
1617
+ invalidateResolvedComments(targetPath);
1618
+ invalidatePageCache();
1619
+ console.log(`File changed: ${basename(targetPath)}`);
1620
+ sendEvent({ type: "document-updated", path: targetPath });
1621
+ }
1622
+ } catch (err) {
1623
+ if (isErrnoException(err) && err.code === "ENOENT") {
1624
+ await rewatch(targetPath);
1625
+ } else {
1626
+ console.error(`Failed to read updated file ${targetPath}:`, err);
1627
+ }
1628
+ }
1629
+ }, 100);
1630
+ });
1631
+ async function rewatch(filePath) {
1632
+ const maxRetries = 10;
1633
+ const retryInterval = 200;
1634
+ for (let i = 0;i < maxRetries; i++) {
1635
+ await new Promise((r) => setTimeout(r, retryInterval));
1636
+ try {
1637
+ await fs.access(filePath);
1638
+ try {
1639
+ watcher.close();
1640
+ } catch {}
1641
+ const idx = watchers.indexOf(watcher);
1642
+ const newWatcher = watchFile(filePath);
1643
+ if (newWatcher) {
1644
+ if (idx >= 0)
1645
+ watchers[idx] = newWatcher;
1646
+ else
1647
+ watchers.push(newWatcher);
1648
+ }
1649
+ const state = fileMap.get(filePath);
1650
+ if (state) {
1651
+ const newContent = await fs.readFile(filePath, "utf-8");
1652
+ if (!state.isLoaded || newContent !== state.content) {
1653
+ state.content = newContent;
1654
+ state.renderedHtml = null;
1655
+ state.headings = null;
1656
+ state.isLoaded = true;
1657
+ invalidateResolvedComments(filePath);
1658
+ invalidatePageCache();
1659
+ console.log(`File changed: ${basename(filePath)}`);
1660
+ sendEvent({ type: "document-updated", path: filePath });
1661
+ }
1662
+ }
1663
+ return;
1664
+ } catch {}
1665
+ }
1666
+ console.warn(`File did not reappear after rename: ${filePath}`);
1667
+ }
1668
+ return watcher;
1669
+ } catch (err) {
1670
+ console.warn(`File watching not available for ${targetPath}:`, err);
1671
+ return null;
1672
+ }
1673
+ }
1674
+ const watchers = [];
1675
+ const server = Bun.serve({
1676
+ port: options.port,
1677
+ hostname: options.host,
1678
+ idleTimeout: 255,
1679
+ async fetch(req) {
1680
+ const url = new URL(req.url);
1681
+ const { pathname } = url;
1682
+ const method = req.method;
1683
+ if (pathname === "/api/documents" && method === "GET") {
1684
+ const files = fileOrder.map((fp) => ({
1685
+ path: fp,
1686
+ fileName: basename(fp)
1687
+ }));
1688
+ return json({
1689
+ files,
1690
+ clean: options.clean || false,
1691
+ workingDirectory: process.cwd()
1692
+ });
1693
+ }
1694
+ if (pathname === "/api/documents" && method === "POST") {
1695
+ try {
1696
+ const { path: requestedPath } = await req.json();
1697
+ if (!requestedPath || typeof requestedPath !== "string") {
1698
+ return errorResponse("Missing 'path' field", 400);
1699
+ }
1700
+ let filePath;
1701
+ try {
1702
+ filePath = await canonicalPath(requestedPath);
1703
+ } catch (err) {
1704
+ if (isErrnoException(err) && err.code === "ENOENT") {
1705
+ return errorResponse(`File not found: ${requestedPath}`, 404);
1706
+ }
1707
+ throw err;
1708
+ }
1709
+ if (!isMarkdownFile(filePath)) {
1710
+ return errorResponse(`Unsupported file type: ${filePath} (expected .md or .markdown)`, 400);
1711
+ }
1712
+ const existingState = fileMap.get(filePath);
1713
+ if (existingState) {
1714
+ return json({
1715
+ path: filePath,
1716
+ fileName: basename(filePath),
1717
+ status: "present"
1718
+ });
1719
+ } else {
1720
+ fileMap.set(filePath, {
1721
+ content: null,
1722
+ renderedHtml: null,
1723
+ headings: null,
1724
+ isLoaded: false,
1725
+ debounceTimer: null
1726
+ });
1727
+ fileOrder.push(filePath);
1728
+ const watcher = watchFile(filePath);
1729
+ if (watcher)
1730
+ watchers.push(watcher);
1731
+ sendEvent({
1732
+ type: "document-added",
1733
+ path: filePath,
1734
+ fileName: basename(filePath)
1735
+ });
1736
+ }
1737
+ return json({
1738
+ path: filePath,
1739
+ fileName: basename(filePath),
1740
+ status: "added"
1741
+ });
1742
+ } catch (err) {
1743
+ console.error("Failed to add document:", err);
1744
+ return errorResponse("Failed to add document", 500);
1745
+ }
1746
+ }
1747
+ if (pathname === "/api/document" && method === "GET") {
1748
+ const ctxOrRes = requireContext(url);
1749
+ if (ctxOrRes instanceof Response)
1750
+ return ctxOrRes;
1751
+ const { html, headings } = await ensureRenderedHtml(ctxOrRes.filePath);
1752
+ return json({
1753
+ html,
1754
+ headings,
1755
+ filePath: ctxOrRes.filePath,
1756
+ fileName: basename(ctxOrRes.filePath),
1757
+ clean: options.clean || false
1758
+ });
1759
+ }
1760
+ if (pathname === "/api/document/stream" && method === "GET") {
1761
+ return createDocumentStream(sseClients);
1762
+ }
1763
+ if (pathname === "/api/health" && method === "GET") {
1764
+ return json({ status: "ok" });
1765
+ }
1766
+ if (pathname === "/api/heartbeat" && method === "GET") {
1767
+ return createHeartbeat(onHeartbeatOpen, onHeartbeatClose);
1768
+ }
1769
+ if (pathname === "/api/comments" && method === "GET") {
1770
+ const ctxOrRes = requireContext(url);
1771
+ if (ctxOrRes instanceof Response)
1772
+ return ctxOrRes;
1773
+ const rendered = await ensureRenderedHtml(ctxOrRes.filePath);
1774
+ return getComments(ctxOrRes, rendered.html);
1775
+ }
1776
+ if (pathname === "/api/comments/raw" && method === "GET") {
1777
+ const ctxOrRes = requireContext(url);
1778
+ if (ctxOrRes instanceof Response)
1779
+ return ctxOrRes;
1780
+ return getRawComments(ctxOrRes);
1781
+ }
1782
+ if (pathname === "/api/comments" && method === "POST") {
1783
+ const ctxOrRes = requireContext(url);
1784
+ if (ctxOrRes instanceof Response)
1785
+ return ctxOrRes;
1786
+ invalidatePageCache();
1787
+ return addComment(ctxOrRes, req);
1788
+ }
1789
+ if (pathname === "/api/comments" && method === "DELETE") {
1790
+ const ctxOrRes = requireContext(url);
1791
+ if (ctxOrRes instanceof Response)
1792
+ return ctxOrRes;
1793
+ invalidatePageCache();
1794
+ return clearComments(ctxOrRes);
1795
+ }
1796
+ const commentId = extractCommentId(pathname);
1797
+ if (commentId) {
1798
+ const ctxOrRes = requireContext(url);
1799
+ if (ctxOrRes instanceof Response)
1800
+ return ctxOrRes;
1801
+ invalidatePageCache();
1802
+ if (pathname.endsWith("/reanchor") && method === "PUT") {
1803
+ return reanchorComment(ctxOrRes, req, commentId);
1804
+ }
1805
+ if (method === "PUT") {
1806
+ return updateComment(ctxOrRes, req, commentId);
1807
+ }
1808
+ if (method === "DELETE") {
1809
+ return deleteComment(ctxOrRes, commentId);
1810
+ }
1811
+ }
1812
+ if (pathname === "/api/settings" && method === "GET") {
1813
+ return getSettingsRoute();
1814
+ }
1815
+ if (pathname === "/api/settings" && method === "PUT") {
1816
+ return updateSettingsRoute(req);
1817
+ }
1818
+ if (pathname === "/") {
1819
+ return serveAppPage(req);
1820
+ }
1821
+ if (isDev) {
1822
+ return proxyToVite(req, pathname, url.search);
1823
+ }
1824
+ return serveStaticFile(distPath, pathname);
1825
+ }
1826
+ });
1827
+ for (const fp of fileOrder) {
1828
+ const watcher = watchFile(fp);
1829
+ if (watcher)
1830
+ watchers.push(watcher);
1831
+ }
1832
+ return { server, watchers };
1833
+ }
1834
+ async function startServer(options) {
1835
+ getShiki();
1836
+ const MAX_PORT = 65535;
1837
+ for (let port = options.port;port <= MAX_PORT; port++) {
1838
+ try {
1839
+ const { server, watchers } = createServer({ ...options, port });
1840
+ const displayHost = options.host === "0.0.0.0" ? "localhost" : options.host;
1841
+ let stopVite;
1842
+ if (false) {}
1843
+ const originalStop = server.stop.bind(server);
1844
+ const wrappedServer = {
1845
+ stop() {
1846
+ disposeMermaidWorker();
1847
+ stopVite?.();
1848
+ for (const w of watchers)
1849
+ w.close();
1850
+ originalStop();
1851
+ }
1852
+ };
1853
+ const actualPort = server.port ?? port;
1854
+ await writeServerInfo(actualPort);
1855
+ return {
1856
+ port: actualPort,
1857
+ url: `http://${displayHost}:${actualPort}`,
1858
+ server: wrappedServer
1859
+ };
1860
+ } catch (err) {
1861
+ if (isErrnoException(err) && (err.code === "EADDRINUSE" || err.code === "EACCES")) {
1862
+ console.log(`Port ${port} is busy, trying ${port + 1}...`);
1863
+ continue;
1864
+ }
1865
+ throw err;
1866
+ }
1867
+ }
1868
+ throw new Error(`No available port found starting from ${options.port}`);
1869
+ }
1870
+
1871
+ // src/cli.ts
1872
+ var program = new Command;
1873
+ function isPermissionError(err) {
1874
+ return err instanceof Error && "code" in err && err.code === "EACCES";
1875
+ }
1876
+ var READIT_DIR = join4(os3.homedir(), ".readit");
1877
+ var SERVER_INFO_PATH2 = join4(READIT_DIR, "server.json");
1878
+ var SERVER_LOCK_PATH = join4(READIT_DIR, "server.lock");
1879
+ var SERVER_LOCK_MAX_AGE_MS = 30000;
1880
+ var SERVER_LOCK_TIMEOUT_MS = 1e4;
1881
+ var SERVER_LOCK_WAIT_MS = 100;
1882
+ function isAlive(pid) {
1883
+ try {
1884
+ process.kill(pid, 0);
1885
+ return true;
1886
+ } catch {
1887
+ return false;
1888
+ }
1889
+ }
1890
+ function getErrnoCode(err) {
1891
+ return err instanceof Error && "code" in err ? err.code : undefined;
1892
+ }
1893
+ function sleep(ms) {
1894
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
1895
+ }
1896
+ async function clearStaleServerLock() {
1897
+ try {
1898
+ const [stats, content] = await Promise.all([
1899
+ fs2.stat(SERVER_LOCK_PATH),
1900
+ fs2.readFile(SERVER_LOCK_PATH, "utf-8").catch(() => "")
1901
+ ]);
1902
+ const age = Date.now() - stats.mtimeMs;
1903
+ let pid;
1904
+ if (content) {
1905
+ try {
1906
+ const lock = JSON.parse(content);
1907
+ pid = lock.pid;
1908
+ } catch {}
1909
+ }
1910
+ if (age > SERVER_LOCK_MAX_AGE_MS || pid !== undefined && !isAlive(pid)) {
1911
+ await fs2.unlink(SERVER_LOCK_PATH).catch(() => {});
1912
+ }
1913
+ } catch (err) {
1914
+ if (getErrnoCode(err) !== "ENOENT")
1915
+ throw err;
1916
+ }
1917
+ }
1918
+ async function withServerLock(run) {
1919
+ await fs2.mkdir(READIT_DIR, { recursive: true });
1920
+ const start = Date.now();
1921
+ while (true) {
1922
+ let handle;
1923
+ try {
1924
+ handle = await fs2.open(SERVER_LOCK_PATH, "wx");
1925
+ await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: Date.now() }), "utf-8");
1926
+ try {
1927
+ return await run();
1928
+ } finally {
1929
+ await handle.close().catch(() => {});
1930
+ await fs2.unlink(SERVER_LOCK_PATH).catch(() => {});
1931
+ }
1932
+ } catch (err) {
1933
+ if (handle) {
1934
+ await handle.close().catch(() => {});
1935
+ }
1936
+ if (getErrnoCode(err) !== "EEXIST") {
1937
+ throw err;
1938
+ }
1939
+ await clearStaleServerLock();
1940
+ if (Date.now() - start >= SERVER_LOCK_TIMEOUT_MS) {
1941
+ throw new Error("Timed out waiting for readit server lock");
1942
+ }
1943
+ await sleep(SERVER_LOCK_WAIT_MS);
1944
+ }
1945
+ }
1946
+ }
1947
+ async function discoverServer() {
1948
+ try {
1949
+ const content = readFileSync(SERVER_INFO_PATH2, "utf-8");
1950
+ const info = JSON.parse(content);
1951
+ if (!isAlive(info.pid)) {
1952
+ return null;
1953
+ }
1954
+ try {
1955
+ const res = await fetch(`http://127.0.0.1:${info.port}/api/health`);
1956
+ if (!res.ok)
1957
+ return null;
1958
+ } catch {
1959
+ return null;
1960
+ }
1961
+ return info;
1962
+ } catch {
1963
+ return null;
1964
+ }
1965
+ }
1966
+ async function attachFiles(server, files) {
1967
+ for (const file of files) {
1968
+ try {
1969
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`, {
1970
+ method: "POST",
1971
+ headers: { "Content-Type": "application/json" },
1972
+ body: JSON.stringify({ path: file.path })
1973
+ });
1974
+ if (!res.ok) {
1975
+ const data2 = await res.json();
1976
+ console.error(`error: failed to add ${file.path}: ${data2.error}`);
1977
+ process.exit(1);
1978
+ }
1979
+ const data = await res.json();
1980
+ if (data.status === "added") {
1981
+ console.log(`Added: ${data.fileName}`);
1982
+ } else {
1983
+ console.log(`Present: ${data.fileName}`);
1984
+ }
1985
+ } catch (err) {
1986
+ console.error("error: failed to connect to server:", err instanceof Error ? err.message : err);
1987
+ process.exit(1);
1988
+ }
1989
+ }
1990
+ }
1991
+ async function getServerTarget(files, port, host) {
1992
+ return withServerLock(async () => {
1993
+ const server = await discoverServer();
1994
+ if (server) {
1995
+ return {
1996
+ kind: "existing",
1997
+ port: server.port,
1998
+ url: `http://127.0.0.1:${server.port}`
1999
+ };
2000
+ }
2001
+ const started = await startServer({ files, port, host });
2002
+ return {
2003
+ kind: "started",
2004
+ port: started.port,
2005
+ url: started.url,
2006
+ server: started.server
2007
+ };
2008
+ });
2009
+ }
2010
+ function findCommentFiles(dir) {
2011
+ const results = [];
2012
+ try {
2013
+ const entries = readdirSync(dir);
2014
+ for (const entry of entries) {
2015
+ const fullPath = join4(dir, entry);
2016
+ try {
2017
+ const lstat = lstatSync(fullPath);
2018
+ if (lstat.isSymbolicLink())
2019
+ continue;
2020
+ if (lstat.isDirectory()) {
2021
+ results.push(...findCommentFiles(fullPath));
2022
+ } else if (entry.endsWith(".comments.md")) {
2023
+ results.push(fullPath);
2024
+ }
2025
+ } catch (err) {
2026
+ if (isPermissionError(err)) {
2027
+ console.warn(`Warning: Permission denied: ${fullPath}`);
2028
+ }
2029
+ }
2030
+ }
2031
+ } catch (err) {
2032
+ if (isPermissionError(err)) {
2033
+ console.warn(`Warning: Permission denied: ${dir}`);
2034
+ }
2035
+ }
2036
+ return results;
2037
+ }
2038
+ function findReviewableFiles(dir) {
2039
+ const results = [];
2040
+ try {
2041
+ const entries = readdirSync(dir);
2042
+ for (const entry of entries) {
2043
+ if (entry.startsWith(".") || entry === "node_modules")
2044
+ continue;
2045
+ const fullPath = join4(dir, entry);
2046
+ try {
2047
+ const lstat = lstatSync(fullPath);
2048
+ if (lstat.isSymbolicLink())
2049
+ continue;
2050
+ if (lstat.isDirectory()) {
2051
+ results.push(...findReviewableFiles(fullPath));
2052
+ } else if (isMarkdownFile(entry)) {
2053
+ results.push({ filePath: fullPath });
2054
+ }
2055
+ } catch (err) {
2056
+ if (isPermissionError(err)) {
2057
+ console.warn(`Warning: Permission denied: ${fullPath}`);
2058
+ }
2059
+ }
2060
+ }
2061
+ } catch (err) {
2062
+ if (isPermissionError(err)) {
2063
+ console.warn(`Warning: Permission denied: ${dir}`);
2064
+ }
2065
+ }
2066
+ return results;
2067
+ }
2068
+ function resolveFiles(args) {
2069
+ const seen = new Set;
2070
+ const files = [];
2071
+ for (const arg of args) {
2072
+ const inputPath = resolve3(process.cwd(), arg);
2073
+ if (!existsSync(inputPath)) {
2074
+ console.error(`error: not found: ${inputPath}`);
2075
+ process.exit(1);
2076
+ }
2077
+ const filePath = realpathSync(inputPath);
2078
+ const stat3 = statSync(filePath);
2079
+ if (stat3.isDirectory()) {
2080
+ const found = findReviewableFiles(filePath);
2081
+ for (const entry of found) {
2082
+ if (!seen.has(entry.filePath)) {
2083
+ seen.add(entry.filePath);
2084
+ files.push(entry);
2085
+ }
2086
+ }
2087
+ } else {
2088
+ if (seen.has(filePath))
2089
+ continue;
2090
+ if (!isMarkdownFile(filePath)) {
2091
+ console.error(`error: unsupported file type: ${arg} (expected .md or .markdown)`);
2092
+ process.exit(1);
2093
+ }
2094
+ seen.add(filePath);
2095
+ files.push({ filePath });
2096
+ }
2097
+ }
2098
+ return files;
2099
+ }
2100
+ var SETTINGS_PATH2 = join4(os3.homedir(), ".readit", "settings.json");
2101
+ function isOnboarded() {
2102
+ try {
2103
+ const content = readFileSync(SETTINGS_PATH2, "utf-8");
2104
+ const settings = JSON.parse(content);
2105
+ return settings.onboarded === true;
2106
+ } catch {
2107
+ return false;
2108
+ }
2109
+ }
2110
+ async function markOnboarded() {
2111
+ let settings = {};
2112
+ try {
2113
+ const content = readFileSync(SETTINGS_PATH2, "utf-8");
2114
+ settings = JSON.parse(content);
2115
+ } catch {}
2116
+ settings.onboarded = true;
2117
+ const dir = join4(os3.homedir(), ".readit");
2118
+ await fs2.mkdir(dir, { recursive: true });
2119
+ await fs2.writeFile(SETTINGS_PATH2, JSON.stringify(settings, null, 2), "utf-8");
2120
+ }
2121
+ var WELCOME_CONTENT = `# Welcome to readit
2122
+
2123
+ A simple tool for reviewing markdown with inline comments.
2124
+
2125
+ ---
2126
+
2127
+ ## How It Works
2128
+
2129
+ readit follows a simple loop: **read \u2192 comment \u2192 extract**.
2130
+
2131
+ ### 1. Read
2132
+
2133
+ You're already doing this. Open any markdown file with \`readit <file.md>\` and it renders in your browser with a clean reading experience.
2134
+
2135
+ ### 2. Comment
2136
+
2137
+ Select any text to add a comment. Try it now \u2014 **select this sentence** and type your first comment.
2138
+
2139
+ Your comments appear as margin notes next to the highlighted text, just like reviewing a document in Google Docs. Add as many as you need.
2140
+
2141
+ ### 3. Extract
2142
+
2143
+ When you're done reviewing, click the menu in the top-right and choose **Copy as Prompt**. This exports all your comments in a format ready for Claude, ChatGPT, or any AI assistant.
2144
+
2145
+ You can also export as JSON if you prefer structured data.
2146
+
2147
+ ---
2148
+
2149
+ ## Everything is Plain Markdown
2150
+
2151
+ Your comments are saved as \`.comments.md\` files in \`~/.readit/comments/\`. No database, no lock-in \u2014 just readable markdown files you can version control, search, or edit by hand.
2152
+
2153
+ Each comment file looks something like this:
2154
+
2155
+ \`\`\`markdown
2156
+ ## Comment 1
2157
+ **Selected:** "select this sentence"
2158
+ **Comment:** This is my first comment!
2159
+ **Created:** 2024-01-15T10:30:00Z
2160
+ \`\`\`
2161
+
2162
+ ---
2163
+
2164
+ ## Navigating Comments
2165
+
2166
+ Once you have multiple comments, use the navigation bar at the bottom of the screen to jump between them. You can also use keyboard shortcuts:
2167
+
2168
+ | Shortcut | Action |
2169
+ |----------|--------|
2170
+ | \`Alt + \u2191\` | Previous comment |
2171
+ | \`Alt + \u2193\` | Next comment |
2172
+ | \`\u2318 + C\` | Copy selected text (raw) |
2173
+ | \`\u2318 + Shift + C\` | Copy selected text with context (for AI) |
2174
+
2175
+ ---
2176
+
2177
+ ## Quick Start
2178
+
2179
+ \`\`\`bash
2180
+ # Review a markdown file
2181
+ readit document.md
2182
+
2183
+ # Use a custom port
2184
+ readit document.md --port 3000
2185
+
2186
+ # Start fresh (clear existing comments)
2187
+ readit document.md --clean
2188
+ \`\`\`
2189
+
2190
+ ---
2191
+
2192
+ ## Try It Now
2193
+
2194
+ Go ahead and add a few comments to this document. When you're done, export them and see the output. That's the entire workflow \u2014 simple, transparent, and designed for reviewing AI-generated content.
2195
+ `;
2196
+ var WELCOME_PATH = join4(os3.homedir(), ".readit", "welcome.md");
2197
+ program.name("readit").description("Review Markdown documents with inline comments").version("0.2.0");
2198
+ program.command("list").description("List all files with comments").action(async () => {
2199
+ const readitDir = join4(os3.homedir(), ".readit", "comments");
2200
+ if (!existsSync(readitDir)) {
2201
+ console.log("No comments found.");
2202
+ return;
2203
+ }
2204
+ const commentFiles = findCommentFiles(readitDir);
2205
+ if (commentFiles.length === 0) {
2206
+ console.log("No comments found.");
2207
+ return;
2208
+ }
2209
+ console.log(`
2210
+ Found ${commentFiles.length} file(s) with comments:
2211
+ `);
2212
+ for (const file of commentFiles) {
2213
+ try {
2214
+ const content = readFileSync(file, "utf-8");
2215
+ const parsed = parseCommentFile(content);
2216
+ const commentCount = parsed.comments.length;
2217
+ const sourcePath = parsed.source || "(unknown source)";
2218
+ console.log(` ${sourcePath}`);
2219
+ console.log(` ${commentCount} comment${commentCount !== 1 ? "s" : ""}`);
2220
+ console.log();
2221
+ } catch {}
2222
+ }
2223
+ });
2224
+ program.command("show <file>").description("Show comments for a file").action(async (file) => {
2225
+ const filePath = resolve3(process.cwd(), file);
2226
+ const commentPath = getCommentPath(filePath);
2227
+ if (!existsSync(commentPath)) {
2228
+ console.log(`No comments found for: ${filePath}`);
2229
+ return;
2230
+ }
2231
+ try {
2232
+ const content = await fs2.readFile(commentPath, "utf-8");
2233
+ const parsed = parseCommentFile(content);
2234
+ if (parsed.comments.length === 0) {
2235
+ console.log(`No comments found for: ${filePath}`);
2236
+ return;
2237
+ }
2238
+ console.log(`
2239
+ Comments for: ${filePath}`);
2240
+ console.log(`${"\u2500".repeat(60)}
2241
+ `);
2242
+ for (let i = 0;i < parsed.comments.length; i++) {
2243
+ const comment = parsed.comments[i];
2244
+ console.log(`[${i + 1}] ${comment.lineHint || "L?"}`);
2245
+ console.log(`Selected: "${comment.selectedText.slice(0, 80)}${comment.selectedText.length > 80 ? "..." : ""}"`);
2246
+ console.log(`Comment: ${comment.comment}`);
2247
+ console.log();
2248
+ }
2249
+ } catch (err) {
2250
+ console.error("error: failed to read comments:", err instanceof Error ? err.message : err);
2251
+ process.exit(1);
2252
+ }
2253
+ });
2254
+ program.argument("[files...]", "Markdown files/directories to review").option("-p, --port <number>", "Port to run server on", "4567").option("--host <address>", "Host address to bind to", "127.0.0.1").option("--no-open", "Don't automatically open browser").option("--clean", "Clear all existing comments on startup").action(async (fileArgs, options) => {
2255
+ let files;
2256
+ if (fileArgs.length === 0) {
2257
+ if (isOnboarded()) {
2258
+ files = [];
2259
+ } else {
2260
+ files = [
2261
+ {
2262
+ content: WELCOME_CONTENT,
2263
+ filePath: WELCOME_PATH
2264
+ }
2265
+ ];
2266
+ }
2267
+ } else {
2268
+ files = resolveFiles(fileArgs);
2269
+ if (files.length === 0) {
2270
+ console.error("error: no reviewable files found");
2271
+ process.exit(1);
2272
+ }
2273
+ }
2274
+ const preferredPort = Number.parseInt(options.port, 10);
2275
+ if (Number.isNaN(preferredPort) || preferredPort < 1 || preferredPort > 65535) {
2276
+ console.error(`error: invalid port number: ${options.port}`);
2277
+ process.exit(1);
2278
+ }
2279
+ let previousPort;
2280
+ try {
2281
+ const info = JSON.parse(readFileSync(SERVER_INFO_PATH2, "utf-8"));
2282
+ if (!isAlive(info.pid)) {
2283
+ previousPort = info.port;
2284
+ }
2285
+ } catch {}
2286
+ try {
2287
+ const { url, server } = await startServer({
2288
+ files,
2289
+ port: preferredPort,
2290
+ host: options.host,
2291
+ clean: options.clean
2292
+ });
2293
+ if (files.length === 0) {
2294
+ console.log(`
2295
+ readit - Document Review Tool
2296
+
2297
+ URL: ${url}
2298
+
2299
+ No files specified. Add files with:
2300
+ readit open <file.md>
2301
+
2302
+ Server running. Press Ctrl+C to stop.
2303
+ `);
2304
+ } else {
2305
+ const fileList = files.map((f) => ` ${f.filePath}`);
2306
+ console.log(`
2307
+ readit - Document Review Tool
2308
+
2309
+ ${files.length === 1 ? "File:" : "Files:"}
2310
+ ${fileList.join(`
2311
+ `)}
2312
+ URL: ${url}
2313
+
2314
+ Server running. Close browser tab to stop.
2315
+ Press Ctrl+C to force stop.
2316
+ `);
2317
+ }
2318
+ const browserLikelyOpen = previousPort === preferredPort || false;
2319
+ if (options.open && !browserLikelyOpen) {
2320
+ open2(url);
2321
+ }
2322
+ if (fileArgs.length === 0) {
2323
+ await markOnboarded();
2324
+ }
2325
+ process.on("SIGINT", async () => {
2326
+ console.log(`
2327
+
2328
+ Shutting down...`);
2329
+ server.stop();
2330
+ await removeServerInfo();
2331
+ process.exit(0);
2332
+ });
2333
+ } catch (error) {
2334
+ console.error("error: failed to start server:", error instanceof Error ? error.message : error);
2335
+ process.exit(1);
2336
+ }
2337
+ });
2338
+ program.command("open").argument("<files...>", "Markdown files to add to running server").description("Add files to a running readit server, or start a new one").option("-p, --port <number>", "Port for new server (if starting)", "4567").option("--host <address>", "Host for new server (if starting)", "127.0.0.1").action(async (fileArgs, options) => {
2339
+ const resolvedFiles = [];
2340
+ for (const arg of fileArgs) {
2341
+ const inputPath = resolve3(process.cwd(), arg);
2342
+ if (!existsSync(inputPath)) {
2343
+ console.error(`error: not found: ${inputPath}`);
2344
+ process.exit(1);
2345
+ }
2346
+ const filePath = realpathSync(inputPath);
2347
+ if (!isMarkdownFile(filePath)) {
2348
+ console.error(`error: unsupported file type: ${arg} (expected .md or .markdown)`);
2349
+ process.exit(1);
2350
+ }
2351
+ resolvedFiles.push({ path: filePath });
2352
+ }
2353
+ const files = resolvedFiles.map((f) => ({
2354
+ filePath: f.path
2355
+ }));
2356
+ const preferredPort = Number.parseInt(options.port, 10);
2357
+ try {
2358
+ const target = await getServerTarget(files, preferredPort, options.host);
2359
+ if (target.kind === "existing") {
2360
+ await attachFiles({ port: target.port, pid: process.pid }, resolvedFiles);
2361
+ console.log(`
2362
+ Server: ${target.url}`);
2363
+ return;
2364
+ }
2365
+ const fileList = files.map((f) => ` ${f.filePath}`);
2366
+ console.log(`
2367
+ readit - Document Review Tool
2368
+
2369
+ ${files.length === 1 ? "File:" : "Files:"}
2370
+ ${fileList.join(`
2371
+ `)}
2372
+ URL: ${target.url}
2373
+
2374
+ Server running. Close browser tab to stop.
2375
+ Press Ctrl+C to force stop.
2376
+ `);
2377
+ open2(target.url);
2378
+ process.on("SIGINT", async () => {
2379
+ console.log(`
2380
+
2381
+ Shutting down...`);
2382
+ target.server?.stop();
2383
+ await removeServerInfo();
2384
+ process.exit(0);
2385
+ });
2386
+ } catch (error) {
2387
+ console.error("error: failed to start server:", error instanceof Error ? error.message : error);
2388
+ process.exit(1);
2389
+ }
2390
+ });
2391
+ program.command("completion").argument("[shell]", "Shell type (zsh, bash, fish)", "zsh").description("Output shell completion and integration script").action((shell) => {
2392
+ const shellDir = join4(import.meta.dir, "..", "shell");
2393
+ switch (shell) {
2394
+ case "zsh": {
2395
+ const widgetPath = join4(shellDir, "readit.zsh");
2396
+ const compPath = join4(shellDir, "_readit");
2397
+ if (!existsSync(widgetPath) || !existsSync(compPath)) {
2398
+ console.log(generateInlineZshCompletion());
2399
+ return;
2400
+ }
2401
+ const compdefContent = readFileSync(compPath, "utf-8");
2402
+ const widgetContent = readFileSync(widgetPath, "utf-8");
2403
+ const lines = [];
2404
+ lines.push("# readit shell integration for zsh");
2405
+ lines.push('# Add to your .zshrc: eval "$(readit completion zsh)"');
2406
+ lines.push("");
2407
+ lines.push("# \u2500\u2500 _readit compdef (autoloaded) \u2500\u2500");
2408
+ lines.push("# This handles: subcommand/option completion + @ file autocomplete");
2409
+ lines.push("# Renders [file.md] in a native multi-column grid via compadd");
2410
+ lines.push("");
2411
+ lines.push(compdefContent.replace(/^#compdef readit\n/, `autoload -Uz _readit
2412
+ _readit() {
2413
+ `).replace(/\n_readit "\$@"\n?$/, `
2414
+ }
2415
+ `));
2416
+ lines.push("");
2417
+ lines.push("# \u2500\u2500 readit.zsh (sourced) \u2500\u2500");
2418
+ lines.push("# This handles: @[...] bracket stripping on Enter + syntax highlighting");
2419
+ lines.push("");
2420
+ lines.push(widgetContent.replace(/^#!/, "#").replace(/\n\(\( \$\+ functions\[_readit_plugin_loaded\] \)\)/, ""));
2421
+ console.log(lines.join(`
2422
+ `));
2423
+ break;
2424
+ }
2425
+ case "bash":
2426
+ console.log(generateBashCompletion());
2427
+ break;
2428
+ case "fish":
2429
+ console.log(generateFishCompletion());
2430
+ break;
2431
+ default:
2432
+ console.error(`error: unsupported shell: ${shell}`);
2433
+ console.error("Supported shells: zsh, bash, fish");
2434
+ process.exit(1);
2435
+ }
2436
+ });
2437
+ program.parse();
2438
+ function generateInlineZshCompletion() {
2439
+ return `
2440
+ #compdef readit
2441
+
2442
+ _readit_markdown_files() {
2443
+ local -a files
2444
+ files=( \${(f)"$(find . -type f \\( -name '*.md' -o -name '*.markdown' \\) -not -path '*/\\.*' -not -path '*/node_modules/*' 2>/dev/null | sed 's|^\\./||')"} )
2445
+ _describe -t files 'markdown files' files
2446
+ }
2447
+
2448
+ _readit() {
2449
+ local context state state_descr line
2450
+ typeset -A opt_args
2451
+ _arguments -C '1:command:->cmd_or_files' '*::arg:->args'
2452
+ case "$state" in
2453
+ cmd_or_files)
2454
+ local -a commands=(
2455
+ 'open:Add files to running server'
2456
+ 'list:List files with comments'
2457
+ 'show:Show comments for a file'
2458
+ 'completion:Output shell completion script'
2459
+ )
2460
+ _alternative 'commands:command:compadd -a commands' 'files:markdown file:_readit_markdown_files'
2461
+ ;;
2462
+ args)
2463
+ case "\${line[1]}" in
2464
+ open) _arguments '*:file:_readit_markdown_files' ;;
2465
+ show) _arguments '1:file:_files -g "*.md *.markdown"' ;;
2466
+ *) _arguments '*:file:_readit_markdown_files' ;;
2467
+ esac
2468
+ ;;
2469
+ esac
2470
+ }
2471
+ _readit "$@"
2472
+ `.trim();
2473
+ }
2474
+ function generateBashCompletion() {
2475
+ return `
2476
+ # readit bash completion
2477
+ # Add to .bashrc: eval "$(readit completion bash)"
2478
+
2479
+ _readit_completions() {
2480
+ local cur prev commands
2481
+ COMPREPLY=()
2482
+ cur="\${COMP_WORDS[COMP_CWORD]}"
2483
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
2484
+ commands="open list show completion"
2485
+
2486
+ if [[ \${COMP_CWORD} -eq 1 ]]; then
2487
+ COMPREPLY=( $(compgen -W "\${commands}" -- "\${cur}") )
2488
+ # Also complete markdown files
2489
+ local files=$(find . -type f \\( -name '*.md' -o -name '*.markdown' \\) \\
2490
+ -not -path '*/.*' -not -path '*/node_modules/*' 2>/dev/null | sed 's|^\\./||')
2491
+ COMPREPLY+=( $(compgen -W "\${files}" -- "\${cur}") )
2492
+ return 0
2493
+ fi
2494
+
2495
+ case "\${COMP_WORDS[1]}" in
2496
+ open|show)
2497
+ local files=$(find . -type f \\( -name '*.md' -o -name '*.markdown' \\) \\
2498
+ -not -path '*/.*' -not -path '*/node_modules/*' 2>/dev/null | sed 's|^\\./||')
2499
+ COMPREPLY=( $(compgen -W "\${files}" -- "\${cur}") )
2500
+ ;;
2501
+ completion)
2502
+ COMPREPLY=( $(compgen -W "zsh bash fish" -- "\${cur}") )
2503
+ ;;
2504
+ esac
2505
+ return 0
2506
+ }
2507
+
2508
+ complete -F _readit_completions readit
2509
+ `.trim();
2510
+ }
2511
+ function generateFishCompletion() {
2512
+ return `
2513
+ # readit fish completion
2514
+ # Add to config.fish: readit completion fish | source
2515
+
2516
+ # Disable file completions by default
2517
+ complete -c readit -f
2518
+
2519
+ # Subcommands
2520
+ complete -c readit -n '__fish_use_subcommand' -a 'open' -d 'Add files to running server'
2521
+ complete -c readit -n '__fish_use_subcommand' -a 'list' -d 'List files with comments'
2522
+ complete -c readit -n '__fish_use_subcommand' -a 'show' -d 'Show comments for a file'
2523
+ complete -c readit -n '__fish_use_subcommand' -a 'completion' -d 'Output shell completion script'
2524
+
2525
+ # Options
2526
+ complete -c readit -s p -l port -d 'Port to run server on'
2527
+ complete -c readit -l host -d 'Host address to bind to'
2528
+ complete -c readit -l no-open -d "Don't automatically open browser"
2529
+ complete -c readit -l clean -d 'Clear existing comments'
2530
+
2531
+ # File arguments for default command and open
2532
+ complete -c readit -n '__fish_use_subcommand' -F -a '(find . -type f \\( -name "*.md" -o -name "*.markdown" \\) -not -path "*/.*" -not -path "*/node_modules/*" 2>/dev/null | sed "s|^\\./||")'
2533
+ complete -c readit -n '__fish_seen_subcommand_from open' -F -a '(find . -type f \\( -name "*.md" -o -name "*.markdown" \\) -not -path "*/.*" -not -path "*/node_modules/*" 2>/dev/null | sed "s|^\\./||")'
2534
+ complete -c readit -n '__fish_seen_subcommand_from show' -F -a '(find . -type f \\( -name "*.md" -o -name "*.markdown" \\) -not -path "*/.*" -not -path "*/node_modules/*" 2>/dev/null | sed "s|^\\./||")'
2535
+
2536
+ # Shell completions for completion subcommand
2537
+ complete -c readit -n '__fish_seen_subcommand_from completion' -a 'zsh bash fish'
2538
+ `.trim();
2539
+ }