@bigmistqke/workpad 0.0.0-stage → 0.18.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 (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1526 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1202 -0
  6. package/dist/client/runtime.js +1194 -0
  7. package/dist/define.js +27 -0
  8. package/dist/plugins/alert/README.md +18 -0
  9. package/dist/plugins/alert/index.js +40 -0
  10. package/dist/plugins/alert/public/style.css +40 -0
  11. package/dist/plugins/ansi/README.md +36 -0
  12. package/dist/plugins/ansi/index.js +63 -0
  13. package/dist/plugins/ansi/public/style.css +28 -0
  14. package/dist/plugins/badge/README.md +32 -0
  15. package/dist/plugins/badge/index.js +28 -0
  16. package/dist/plugins/badge/public/style.css +30 -0
  17. package/dist/plugins/chat/README.md +81 -0
  18. package/dist/plugins/chat/index.js +96 -0
  19. package/dist/plugins/chat/public/client.js +3 -0
  20. package/dist/plugins/chat/public/style.css +143 -0
  21. package/dist/plugins/claude/README.md +116 -0
  22. package/dist/plugins/claude/channel.js +130 -0
  23. package/dist/plugins/claude/doctor.js +316 -0
  24. package/dist/plugins/claude/index.js +199 -0
  25. package/dist/plugins/claude/session.js +68 -0
  26. package/dist/plugins/code/README.md +54 -0
  27. package/dist/plugins/code/diff.js +75 -0
  28. package/dist/plugins/code/index.js +105 -0
  29. package/dist/plugins/code/public/client.js +1 -0
  30. package/dist/plugins/code/public/style.css +99 -0
  31. package/dist/plugins/comments/README.md +30 -0
  32. package/dist/plugins/comments/index.js +39 -0
  33. package/dist/plugins/comments/public/client.js +24 -0
  34. package/dist/plugins/comments/public/style.css +224 -0
  35. package/dist/plugins/details/README.md +24 -0
  36. package/dist/plugins/details/index.js +28 -0
  37. package/dist/plugins/details/public/style.css +7 -0
  38. package/dist/plugins/draft/README.md +14 -0
  39. package/dist/plugins/draft/index.js +27 -0
  40. package/dist/plugins/draft/public/style.css +21 -0
  41. package/dist/plugins/forge/README.md +22 -0
  42. package/dist/plugins/forge/index.js +83 -0
  43. package/dist/plugins/form/README.md +126 -0
  44. package/dist/plugins/form/index.js +179 -0
  45. package/dist/plugins/form/public/style.css +172 -0
  46. package/dist/plugins/grid/README.md +45 -0
  47. package/dist/plugins/grid/index.js +35 -0
  48. package/dist/plugins/grid/public/style.css +98 -0
  49. package/dist/plugins/iframe/README.md +18 -0
  50. package/dist/plugins/iframe/index.js +49 -0
  51. package/dist/plugins/iframe/public/style.css +28 -0
  52. package/dist/plugins/index.js +44 -0
  53. package/dist/plugins/lightbox/README.md +24 -0
  54. package/dist/plugins/lightbox/index.js +20 -0
  55. package/dist/plugins/lightbox/public/client.js +4 -0
  56. package/dist/plugins/lightbox/public/style.css +66 -0
  57. package/dist/plugins/mermaid/README.md +21 -0
  58. package/dist/plugins/mermaid/index.js +42 -0
  59. package/dist/plugins/mermaid/public/style.css +21 -0
  60. package/dist/plugins/opencode/README.md +48 -0
  61. package/dist/plugins/opencode/channel.js +92 -0
  62. package/dist/plugins/opencode/index.js +64 -0
  63. package/dist/plugins/opencode/shim.js +150 -0
  64. package/dist/plugins/quiet/README.md +26 -0
  65. package/dist/plugins/quiet/index.js +23 -0
  66. package/dist/plugins/tabs/README.md +44 -0
  67. package/dist/plugins/tabs/index.js +75 -0
  68. package/dist/plugins/tabs/public/client.js +1 -0
  69. package/dist/plugins/tabs/public/style.css +98 -0
  70. package/dist/plugins/terminal/README.md +63 -0
  71. package/dist/plugins/terminal/host.js +338 -0
  72. package/dist/plugins/terminal/index.js +170 -0
  73. package/dist/plugins/terminal/modes.js +32 -0
  74. package/dist/plugins/terminal/public/client.js +41 -0
  75. package/dist/plugins/terminal/public/style.css +511 -0
  76. package/dist/plugins/terminal/server.js +256 -0
  77. package/dist/plugins/terminal/sizes.js +58 -0
  78. package/dist/plugins/timeline/README.md +48 -0
  79. package/dist/plugins/timeline/index.js +83 -0
  80. package/dist/plugins/timeline/public/style.css +138 -0
  81. package/dist/plugins/toc/README.md +40 -0
  82. package/dist/plugins/toc/index.js +29 -0
  83. package/dist/plugins/toc/public/client.js +1 -0
  84. package/dist/plugins/toc/public/style.css +117 -0
  85. package/dist/plugins/window/README.md +51 -0
  86. package/dist/plugins/window/index.js +91 -0
  87. package/dist/solid/index.js +41 -0
  88. package/dist/src/agents.js +81 -0
  89. package/dist/src/anchors.js +52 -0
  90. package/dist/src/api.js +282 -0
  91. package/dist/src/archive.js +49 -0
  92. package/dist/src/auth.js +67 -0
  93. package/dist/src/build.js +159 -0
  94. package/dist/src/client/page/base.css +1762 -0
  95. package/dist/src/client/page/main.js +2121 -0
  96. package/dist/src/config.js +76 -0
  97. package/dist/src/document.js +93 -0
  98. package/dist/src/entries.js +264 -0
  99. package/dist/src/events.js +322 -0
  100. package/dist/src/files.js +47 -0
  101. package/dist/src/formstate.js +65 -0
  102. package/dist/src/help.js +213 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +348 -0
  105. package/dist/src/icons.js +6 -0
  106. package/dist/src/listen.js +132 -0
  107. package/dist/src/listeners.js +64 -0
  108. package/dist/src/load.js +81 -0
  109. package/dist/src/loader.js +179 -0
  110. package/dist/src/migrate.js +314 -0
  111. package/dist/src/package.js +52 -0
  112. package/dist/src/pages/blocks.js +67 -0
  113. package/dist/src/pages/board.js +59 -0
  114. package/dist/src/pages/index.js +27 -0
  115. package/dist/src/pages/markdown.js +863 -0
  116. package/dist/src/pages/render.js +761 -0
  117. package/dist/src/pages/window.js +29 -0
  118. package/dist/src/plugins.js +283 -0
  119. package/dist/src/public.js +24 -0
  120. package/dist/src/rename.js +130 -0
  121. package/dist/src/running.js +146 -0
  122. package/dist/src/serve.js +188 -0
  123. package/dist/src/server.js +1105 -0
  124. package/dist/src/site.js +179 -0
  125. package/dist/src/state.js +155 -0
  126. package/dist/src/status.js +323 -0
  127. package/dist/src/thread.js +68 -0
  128. package/dist/src/watchdog.js +38 -0
  129. package/dist/src/ws.js +128 -0
  130. package/package.json +154 -4
  131. package/plugins/README.md +304 -0
  132. package/plugins/alert/README.md +18 -0
  133. package/plugins/alert/index.ts +50 -0
  134. package/plugins/alert/public/style.css +40 -0
  135. package/plugins/ansi/README.md +36 -0
  136. package/plugins/ansi/index.ts +95 -0
  137. package/plugins/ansi/public/style.css +28 -0
  138. package/plugins/badge/README.md +32 -0
  139. package/plugins/badge/index.ts +36 -0
  140. package/plugins/badge/public/style.css +30 -0
  141. package/plugins/chat/README.md +81 -0
  142. package/plugins/chat/autosize.ts +139 -0
  143. package/plugins/chat/client.tsx +187 -0
  144. package/plugins/chat/index.ts +146 -0
  145. package/plugins/chat/public/style.css +143 -0
  146. package/plugins/claude/README.md +116 -0
  147. package/plugins/claude/channel.ts +136 -0
  148. package/plugins/claude/doctor.ts +274 -0
  149. package/plugins/claude/index.ts +248 -0
  150. package/plugins/claude/session.ts +70 -0
  151. package/plugins/code/README.md +54 -0
  152. package/plugins/code/client.ts +73 -0
  153. package/plugins/code/diff.ts +96 -0
  154. package/plugins/code/index.ts +136 -0
  155. package/plugins/code/public/style.css +99 -0
  156. package/plugins/comments/README.md +30 -0
  157. package/plugins/comments/client.ts +723 -0
  158. package/plugins/comments/index.ts +48 -0
  159. package/plugins/comments/public/style.css +224 -0
  160. package/plugins/details/README.md +24 -0
  161. package/plugins/details/index.ts +30 -0
  162. package/plugins/details/public/style.css +7 -0
  163. package/plugins/draft/README.md +14 -0
  164. package/plugins/draft/index.ts +23 -0
  165. package/plugins/draft/public/style.css +21 -0
  166. package/plugins/forge/README.md +22 -0
  167. package/plugins/forge/index.ts +84 -0
  168. package/plugins/form/README.md +126 -0
  169. package/plugins/form/index.ts +199 -0
  170. package/plugins/form/public/style.css +172 -0
  171. package/plugins/grid/README.md +45 -0
  172. package/plugins/grid/index.ts +41 -0
  173. package/plugins/grid/public/style.css +98 -0
  174. package/plugins/iframe/README.md +18 -0
  175. package/plugins/iframe/index.ts +53 -0
  176. package/plugins/iframe/public/style.css +28 -0
  177. package/plugins/index.ts +49 -0
  178. package/plugins/lightbox/README.md +24 -0
  179. package/plugins/lightbox/client.ts +109 -0
  180. package/plugins/lightbox/index.ts +25 -0
  181. package/plugins/lightbox/public/style.css +66 -0
  182. package/plugins/mermaid/README.md +21 -0
  183. package/plugins/mermaid/index.ts +46 -0
  184. package/plugins/mermaid/public/style.css +21 -0
  185. package/plugins/opencode/README.md +48 -0
  186. package/plugins/opencode/channel.ts +112 -0
  187. package/plugins/opencode/index.ts +91 -0
  188. package/plugins/opencode/shim.ts +166 -0
  189. package/plugins/quiet/README.md +26 -0
  190. package/plugins/quiet/index.ts +28 -0
  191. package/plugins/tabs/README.md +44 -0
  192. package/plugins/tabs/client.ts +96 -0
  193. package/plugins/tabs/index.ts +103 -0
  194. package/plugins/tabs/public/style.css +98 -0
  195. package/plugins/terminal/README.md +63 -0
  196. package/plugins/terminal/client.ts +391 -0
  197. package/plugins/terminal/host.ts +434 -0
  198. package/plugins/terminal/index.ts +199 -0
  199. package/plugins/terminal/modes.ts +30 -0
  200. package/plugins/terminal/public/style.css +225 -0
  201. package/plugins/terminal/server.ts +266 -0
  202. package/plugins/terminal/sizes.ts +72 -0
  203. package/plugins/timeline/README.md +48 -0
  204. package/plugins/timeline/index.ts +82 -0
  205. package/plugins/timeline/public/style.css +138 -0
  206. package/plugins/toc/README.md +40 -0
  207. package/plugins/toc/client.ts +236 -0
  208. package/plugins/toc/index.ts +55 -0
  209. package/plugins/toc/public/style.css +117 -0
  210. package/plugins/window/README.md +51 -0
  211. package/plugins/window/index.ts +92 -0
  212. package/skills/workpad/SKILL.md +592 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +134 -0
  215. package/src/anchors.ts +85 -0
  216. package/src/api.ts +444 -0
  217. package/src/archive.ts +75 -0
  218. package/src/auth.ts +99 -0
  219. package/src/build.ts +213 -0
  220. package/src/client/base.ts +19 -0
  221. package/src/client/forms.ts +420 -0
  222. package/src/client/markdown.ts +147 -0
  223. package/src/client/page/base.css +1762 -0
  224. package/src/client/page/board.ts +166 -0
  225. package/src/client/page/elsewhere.ts +153 -0
  226. package/src/client/page/fresh.ts +343 -0
  227. package/src/client/page/heading-link.ts +32 -0
  228. package/src/client/page/live.ts +134 -0
  229. package/src/client/page/main.ts +398 -0
  230. package/src/client/page/orphans.ts +64 -0
  231. package/src/client/page/place.ts +260 -0
  232. package/src/client/page/sort.ts +49 -0
  233. package/src/client/page/sticky.ts +58 -0
  234. package/src/client/page/theme.ts +36 -0
  235. package/src/client/page/view.ts +9 -0
  236. package/src/client/page/waiting.ts +278 -0
  237. package/src/client/page/window.ts +40 -0
  238. package/src/client/reactive.ts +19 -0
  239. package/src/client/read.ts +111 -0
  240. package/src/client/runtime.ts +499 -0
  241. package/src/client/scroll.ts +90 -0
  242. package/src/client/toast.ts +99 -0
  243. package/src/config.ts +111 -0
  244. package/src/define.ts +997 -0
  245. package/src/document.ts +191 -0
  246. package/src/entries.ts +352 -0
  247. package/src/events.ts +463 -0
  248. package/src/files.ts +74 -0
  249. package/src/formstate.ts +72 -0
  250. package/src/help.ts +240 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +435 -0
  253. package/src/icons.ts +18 -0
  254. package/src/listen.ts +171 -0
  255. package/src/listeners.ts +89 -0
  256. package/src/load.ts +113 -0
  257. package/src/loader.ts +227 -0
  258. package/src/migrate.ts +352 -0
  259. package/src/package.ts +62 -0
  260. package/src/pages/blocks.ts +106 -0
  261. package/src/pages/board.ts +89 -0
  262. package/src/pages/index.ts +79 -0
  263. package/src/pages/markdown.ts +976 -0
  264. package/src/pages/render.ts +845 -0
  265. package/src/pages/window.ts +69 -0
  266. package/src/plugins.ts +319 -0
  267. package/src/public.ts +39 -0
  268. package/src/rename.ts +147 -0
  269. package/src/running.ts +171 -0
  270. package/src/serve.ts +221 -0
  271. package/src/server.ts +1385 -0
  272. package/src/site.ts +170 -0
  273. package/src/state.ts +327 -0
  274. package/src/status.ts +466 -0
  275. package/src/thread.ts +98 -0
  276. package/src/watchdog.ts +53 -0
  277. package/src/ws.ts +155 -0
package/src/hub.ts ADDED
@@ -0,0 +1,435 @@
1
+ // The shared server: one per machine, serving every project of the machine config's entries, each
2
+ // under its own path (see entries.ts). A request handler like a project's server, so tests make one
3
+ // for a throwaway machine folder and send it requests; listening and its record are serve.ts.
4
+ //
5
+ // / the overview: every project's pages as columns, by state or by project (pages/board.ts);
6
+ // a project of the server's own (overview/ in the machine folder), rendered and
7
+ // live like any project's overview
8
+ // /<entry>/<path>/… a project, as its own server serves it at / (createServer with a base)
9
+ // /api/health { hub: true, pid, version, projects }; `?rescan` looks for projects first
10
+ // /api/index every project's pages and what is open on them, as JSON (?entry=: one entry's),
11
+ // for a page's menu of what waits elsewhere
12
+ // /api/shutdown POST { version }: a newer workpad takes over; an older one is refused
13
+ // /api/projects, /api/pages, /api/forms, /api/chats, /api/subscriptions, /api/agents
14
+ // the API's lists (state.ts) across every project, each item with its
15
+ // project's path (`project`): every open form of the machine in one ask
16
+ // /api/stream every project's log as it grows, as server-sent events, each event with its
17
+ // project; projects that appear meanwhile are followed too
18
+ // /api/listen?entry=<name>[&as=<who>]
19
+ // a listen over a whole entry, for as long as the connection is open: held on
20
+ // every page of its projects, also those that appear meanwhile; its stream is
21
+ // told the entry's projects (listeners.ts). Any number run
22
+ //
23
+ // A project's server is made when the project is found and closed when it goes, so a project
24
+ // appears and disappears without a restart. Each keeps its own state, config and log, as it would
25
+ // on a port of its own: the shared server only routes.
26
+ import { filesFold } from './pages/render.ts'
27
+ import fs from 'node:fs'
28
+ import path from 'node:path'
29
+ import type { IncomingMessage, ServerResponse } from 'node:http'
30
+ import type { Duplex } from 'node:stream'
31
+ import { project as projectAt, type Project } from './config.ts'
32
+ import { followEntries, machineDir, readMachineConfig, stateDir, type EntryProject } from './entries.ts'
33
+ import { compareVersions, VERSION } from './package.ts'
34
+ import { API_LISTS, createServer, type ApiList, type WorkpadServer } from './server.ts'
35
+ import type { LiveEvent } from './state.ts'
36
+ import type { IndexPage, IndexProject, Listener, PageStatus } from './define.ts'
37
+ import { holdStream, listenerOf } from './listeners.ts'
38
+
39
+ export interface HubOptions {
40
+ /** the machine folder (its config.json), which the server only reads; default machineDir() */
41
+ dir?: string
42
+ /** the server's own folder, which it writes (the overview's project); default stateDir() */
43
+ state?: string
44
+ /** what `~` means in the globs (tests) */
45
+ home?: string
46
+ /** how often to look for projects coming and going, in ms */
47
+ interval?: number
48
+ /** a newer workpad asked this one to make way (POST /api/shutdown) */
49
+ onShutdown?: () => void
50
+ /** the version this server says it is (tests); default the package's */
51
+ version?: string
52
+ }
53
+
54
+ /** A project the shared server serves: where, and its own server. */
55
+ interface Served extends EntryProject {
56
+ project: Project
57
+ server: WorkpadServer
58
+ }
59
+
60
+ export interface Hub {
61
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>
62
+ /** an upgrade request (the HTTP server's 'upgrade' event): a page's live channel */
63
+ upgrade(req: IncomingMessage, conn: Duplex, head: Buffer): void
64
+ /** the projects it serves now */
65
+ projects(): EntryProject[]
66
+ /** look for projects coming and going now */
67
+ rescan(): EntryProject[]
68
+ close(): void
69
+ }
70
+
71
+ export function createHub({
72
+ dir = machineDir(),
73
+ state = stateDir(),
74
+ home,
75
+ interval,
76
+ onShutdown,
77
+ version = VERSION,
78
+ }: HubOptions = {}): Hub {
79
+ const served = new Map<string, Served>()
80
+ // the machine config's origins, as last read: the projects' servers ask for them on each request
81
+ let origins: readonly string[] = []
82
+ const allowed = () => origins
83
+ // the listens over a whole entry (`workpad listen` without a page in one of its projects): each
84
+ // held as a listener on every project of its entry, and what tells its stream the projects
85
+ interface EntryListen {
86
+ entry: string
87
+ listener: Listener
88
+ held: Map<Served, () => void>
89
+ tell: () => void
90
+ }
91
+ const entryListens = new Set<EntryListen>()
92
+ /** An entry listen held on one of its projects, so the project's pages say it listens. */
93
+ function hold(s: Served, el: EntryListen) {
94
+ if (!el.held.has(s)) el.held.set(s, s.server.addListener(el.listener))
95
+ }
96
+ /** Let go of a project (gone, or the listen ended). */
97
+ function release(s: Served, el: EntryListen) {
98
+ el.held.get(s)?.()
99
+ el.held.delete(s)
100
+ }
101
+
102
+ // the streams across every project (/api/stream): each follows every project's log, and the
103
+ // projects that appear later
104
+ interface Stream {
105
+ query: Record<string, string>
106
+ send: (e: LiveEvent) => void
107
+ followed: Map<Served, () => void>
108
+ }
109
+ const allStreams = new Set<Stream>()
110
+ const followAll = (st: Stream) => {
111
+ for (const s of served.values()) if (!st.followed.has(s)) st.followed.set(s, s.server.stream(st.query, st.send))
112
+ for (const [s, stop] of st.followed)
113
+ if (![...served.values()].includes(s)) {
114
+ stop()
115
+ st.followed.delete(s)
116
+ }
117
+ }
118
+
119
+ function sync(projects: EntryProject[]) {
120
+ // projects come and go: the overview lists them
121
+ setImmediate(() => touch())
122
+ // a project whose entry's files changed is made again with it
123
+ const wanted = new Map(projects.map(p => [`${p.base}\n${p.dir}\n${p.files ?? ''}`, p]))
124
+ for (const [key, s] of served)
125
+ if (!wanted.has(key)) {
126
+ for (const el of entryListens) release(s, el)
127
+ s.server.close()
128
+ served.delete(key)
129
+ console.log(`workpad: ${s.base} is gone (${s.dir})`)
130
+ }
131
+ for (const [key, p] of wanted) {
132
+ if (served.has(key)) continue
133
+ const project = projectAt(p.dir)
134
+ if (!project) continue
135
+ const server = createServer(project, {
136
+ base: p.base,
137
+ entry: p.entry,
138
+ label: [p.group, p.name].filter(Boolean).join(' › '),
139
+ onChange: () => changed(p.base),
140
+ origins: allowed,
141
+ filesDefault: p.files,
142
+ })
143
+ const s: Served = { ...p, project, server }
144
+ served.set(key, s)
145
+ for (const el of entryListens) if (el.entry === p.entry) hold(s, el)
146
+ console.log(`workpad: ${p.base} → ${p.dir}`)
147
+ }
148
+ // an entry listen follows its projects coming and going
149
+ for (const el of entryListens) el.tell()
150
+ for (const st of allStreams) followAll(st)
151
+ }
152
+
153
+ // the overview at /: a project of the shared server's own, in the machine folder, whose overview
154
+ // lists every project's pages; rendered and live like any project's, so it looks like one
155
+ const overviewDir = path.join(state, 'overview')
156
+ fs.mkdirSync(path.join(overviewDir, '.workpad', 'pages'), { recursive: true })
157
+ const root = createServer(projectAt(overviewDir)!, {
158
+ name: 'workpad',
159
+ files: false,
160
+ origins: allowed,
161
+ overview: async () => {
162
+ const projects = await Promise.all(
163
+ [...served.values()].map(async s => ({
164
+ ...(await indexOf(s)),
165
+ files: await s.server.files().catch(() => false),
166
+ })),
167
+ )
168
+ const boxed = (process.env.WORKPAD_SANDBOX ?? '').split(':').filter(Boolean)
169
+ return {
170
+ projects,
171
+ note: `workpad ${version} · ${boxed.length ? `boxed: ${boxed.join(', ')}` : 'not boxed'} · ${dir}/config.json`,
172
+ }
173
+ },
174
+ })
175
+ // what the overview lists changed: told a moment later, once for several changes
176
+ let touching: ReturnType<typeof setTimeout> | undefined
177
+ // the projects that changed since: each other project's open pages are told, for their menu of
178
+ // what waits elsewhere (pushed, so no page has to ask every project now and then)
179
+ const changes = new Set<string>()
180
+ const touch = () => {
181
+ clearTimeout(touching)
182
+ touching = setTimeout(() => {
183
+ root.touch()
184
+ const from = [...changes]
185
+ changes.clear()
186
+ for (const s of served.values()) if (from.some(b => b !== s.base)) s.server.elsewhere()
187
+ }, 150)
188
+ }
189
+ const changed = (base: string) => {
190
+ changes.add(base)
191
+ touch()
192
+ }
193
+
194
+ const entries = followEntries(
195
+ () => {
196
+ const config = readMachineConfig(dir)
197
+ origins = config?.origins ?? []
198
+ return config
199
+ },
200
+ sync,
201
+ { interval, home },
202
+ )
203
+
204
+ /** The project a path is under: the longest base that is the path or a folder above it. */
205
+ const owner = (p: string): Served | null => {
206
+ let best: Served | null = null
207
+ for (const s of served.values())
208
+ if ((p === s.base || p.startsWith(s.base + '/')) && (!best || s.base.length > best.base.length)) best = s
209
+ return best
210
+ }
211
+
212
+ /** A project's pages and what waits on each, as the index and the overview give them. */
213
+ async function indexOf(s: Served): Promise<IndexProject> {
214
+ const at = {
215
+ entry: s.entry,
216
+ group: s.group,
217
+ name: s.name,
218
+ label: [s.group, s.name].filter(Boolean).join(' › '),
219
+ dir: s.dir,
220
+ base: s.base,
221
+ }
222
+ let statuses: PageStatus[]
223
+ try {
224
+ statuses = await s.server.status()
225
+ } catch (err) {
226
+ return { ...at, pages: [], active: 0, error: (err as Error).message }
227
+ }
228
+ const pages = statuses
229
+ .map((p): IndexPage => ({
230
+ page: p.page,
231
+ title: p.title,
232
+ url: `${s.base}/${p.page.split('/').map(encodeURIComponent).join('/')}`,
233
+ mtime: mtimeOf(p.file),
234
+ open: p.open,
235
+ unread: p.unread.length,
236
+ unreceived: p.unreceived.length,
237
+ }))
238
+ .toSorted((a, b) => b.mtime - a.mtime)
239
+ return { ...at, pages, active: pages[0]?.mtime ?? 0 }
240
+ }
241
+ const index = () => Promise.all([...served.values()].map(indexOf))
242
+
243
+ const send = (res: ServerResponse, status: number, body: string, type = 'text/html; charset=utf-8') => {
244
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
245
+ res.end(body)
246
+ }
247
+ const sendJson = (res: ServerResponse, status: number, data: unknown) =>
248
+ send(res, status, JSON.stringify(data), 'application/json')
249
+ const list = () =>
250
+ [...served.values()].map(({ entry, group, name, dir, base }) => ({ entry, group, name, dir, base }))
251
+
252
+ function readBody(req: IncomingMessage): Promise<string> {
253
+ return new Promise((resolve, reject) => {
254
+ let body = ''
255
+ req.setEncoding('utf8')
256
+ req.on('data', c => {
257
+ body += c
258
+ if (body.length > 1e4) req.destroy()
259
+ })
260
+ req.on('end', () => resolve(body))
261
+ req.on('error', reject)
262
+ })
263
+ }
264
+
265
+ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
266
+ try {
267
+ const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
268
+ const p = decodeURIComponent(url.pathname)
269
+ if (p === '/api/health') {
270
+ if (url.searchParams.has('rescan')) entries.rescan()
271
+ return sendJson(res, 200, { ok: true, hub: true, pid: process.pid, version, dir, projects: list() })
272
+ }
273
+ if (p === '/api/index') {
274
+ const entry = url.searchParams.get('entry')
275
+ return sendJson(
276
+ res,
277
+ 200,
278
+ (await index()).filter(x => !entry || x.entry === entry),
279
+ )
280
+ }
281
+ if (p === '/api/shutdown' && req.method === 'POST') {
282
+ // only from the command line: a page of a project has an Origin
283
+ if (req.headers.origin) return sendJson(res, 403, { error: 'not from a browser' })
284
+ let asker = ''
285
+ try {
286
+ asker = String(JSON.parse(await readBody(req)).version ?? '')
287
+ } catch {}
288
+ // an older workpad never replaces a newer one, nor one as new
289
+ if (!asker || compareVersions(asker, version) <= 0)
290
+ return sendJson(res, 409, { error: `workpad ${version} runs here; ${asker || 'that'} is not newer` })
291
+ sendJson(res, 200, { ok: true, version })
292
+ setImmediate(() => onShutdown?.())
293
+ return
294
+ }
295
+ if (p === '/api/listen' && url.searchParams.has('entry')) return listenEntry(req, res, url.searchParams)
296
+ // the API across every project: each project's list, put together
297
+ const what = /^\/api\/(\w+)$/.exec(p)?.[1]
298
+ if (req.method === 'GET' && what && (API_LISTS as readonly string[]).includes(what)) {
299
+ const query = Object.fromEntries(url.searchParams)
300
+ const all = await Promise.all(
301
+ [...served.values()].map(s => s.server.read(what as ApiList, query).catch(() => [] as unknown[])),
302
+ )
303
+ return sendJson(res, 200, all.flat())
304
+ }
305
+ if (p === '/api/stream') return streamAll(req, res, Object.fromEntries(url.searchParams))
306
+ // a project's files, for its fold on the overview: listed when the reader opens it, off the
307
+ // event loop, so the overview's render reads no project's files (src/pages/render.ts)
308
+ if (p === '/api/files') {
309
+ const s = [...served.values()].find(x => x.base === url.searchParams.get('base'))
310
+ if (!s) return sendJson(res, 404, { error: 'no such project' })
311
+ if (!(await s.server.files().catch(() => false))) return sendJson(res, 403, { error: 'its files are not served' })
312
+ return sendJson(res, 200, await filesFold(s.dir, s.base))
313
+ }
314
+ if (p === '/favicon.ico') {
315
+ res.writeHead(204)
316
+ return void res.end()
317
+ }
318
+ // the project's overview is at its folder: /rg/develop/
319
+ const s = owner(p)
320
+ if (s && p === s.base) {
321
+ res.writeHead(302, { location: `${s.base}/${url.search}` })
322
+ return void res.end()
323
+ }
324
+ return route(req, p, url).handle(req, res)
325
+ } catch (err) {
326
+ console.error(err)
327
+ send(res, 500, String((err as Error)?.stack || err), 'text/plain')
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Whose request this is: a project's (`req.url` made the path within it), or else the overview's.
333
+ */
334
+ function route(req: IncomingMessage, p: string, url: URL): WorkpadServer {
335
+ let s = owner(p)
336
+ if (s) {
337
+ // the path less the project's part, encoded again for the project's server to decode
338
+ req.url = p.slice(s.base.length).split('/').map(encodeURIComponent).join('/') + url.search
339
+ return s.server
340
+ }
341
+ // A plugin's browser module that writes `/api/<name>/…` itself, from before api.url: the page
342
+ // that asked is in the Referer, and the request is that project's.
343
+ const from = req.headers.referer ? new URL(req.headers.referer).pathname : null
344
+ s = /^\/(api|_)\//.test(p) && from ? owner(decodeURIComponent(from)) : null
345
+ req.url = s ? (req.url ?? '/').replace(/^\/+/, '/') : req.url
346
+ // anything else outside the projects is the overview's: /, its page, its files and live channel
347
+ return s ? s.server : root
348
+ }
349
+
350
+ /** An upgrade (a page's live channel), routed as a request is. */
351
+ function upgrade(req: IncomingMessage, conn: Duplex, head: Buffer) {
352
+ try {
353
+ const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
354
+ route(req, decodeURIComponent(url.pathname), url).upgrade(req, conn, head)
355
+ } catch (err) {
356
+ console.error(err)
357
+ conn.destroy()
358
+ }
359
+ }
360
+
361
+ /**
362
+ * A listen over a whole entry (`workpad listen` without a page in one of its projects): any
363
+ * number run. Each project holds it as a listener, so its pages say who listens; its stream is
364
+ * told the entry's projects, at once and whenever they change. The command itself reads their logs.
365
+ */
366
+ function listenEntry(req: IncomingMessage, res: ServerResponse, q: URLSearchParams) {
367
+ const entry = q.get('entry')!
368
+ const mine = () => [...served.values()].filter(s => s.entry === entry)
369
+ const el: EntryListen = { entry, listener: listenerOf(q), held: new Map(), tell: () => {} }
370
+ for (const s of mine()) hold(s, el)
371
+ entryListens.add(el)
372
+ const stream = holdStream(req, res, () => {
373
+ closers.delete(stream.end)
374
+ entryListens.delete(el)
375
+ for (const s of [...el.held.keys()]) release(s, el)
376
+ })
377
+ el.tell = () => stream.send('projects', { projects: mine().map(s => ({ dir: s.dir, base: s.base })) })
378
+ closers.add(stream.end)
379
+ el.tell()
380
+ }
381
+ const closers = new Set<() => void>()
382
+
383
+ /** /api/stream across every project: as a project's, each event with its project. */
384
+ function streamAll(req: IncomingMessage, res: ServerResponse, query: Record<string, string>) {
385
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
386
+ res.write(': streaming\n\n')
387
+ const st: Stream = {
388
+ query,
389
+ send: e => res.write(`event: event\nid: ${e.id}\ndata: ${JSON.stringify(e)}\n\n`),
390
+ followed: new Map(),
391
+ }
392
+ allStreams.add(st)
393
+ followAll(st)
394
+ const ping = setInterval(() => res.write(': ping\n\n'), 25000)
395
+ const end = () => {
396
+ clearInterval(ping)
397
+ allStreams.delete(st)
398
+ for (const stop of st.followed.values()) stop()
399
+ st.followed.clear()
400
+ closers.delete(close)
401
+ }
402
+ const close = () => {
403
+ end()
404
+ res.end()
405
+ }
406
+ closers.add(close)
407
+ req.on('close', end)
408
+ }
409
+
410
+ return {
411
+ handle,
412
+ upgrade,
413
+ projects: list,
414
+ rescan() {
415
+ entries.rescan()
416
+ return list()
417
+ },
418
+ close() {
419
+ clearTimeout(touching)
420
+ root.close()
421
+ for (const c of closers) c()
422
+ entries.stop()
423
+ for (const s of served.values()) s.server.close()
424
+ served.clear()
425
+ },
426
+ }
427
+ }
428
+
429
+ const mtimeOf = (file: string) => {
430
+ try {
431
+ return fs.statSync(file).mtimeMs
432
+ } catch {
433
+ return 0
434
+ }
435
+ }
package/src/icons.ts ADDED
@@ -0,0 +1,18 @@
1
+ // Icons the page and the server both draw, as SVG markup. No Node in it: the browser runtime
2
+ // imports it too.
3
+
4
+ /** An inbox: what awaits the reader (the header's menu, the overview). */
5
+ export const INBOX_ICON =
6
+ '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/></svg>'
7
+
8
+ /** Copy: two sheets (the list of who listens copies an agent's id with it). */
9
+ export const COPY_ICON =
10
+ '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><rect x="5.5" y="5.5" width="8" height="8" rx="1.5" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M10.5 3.5v-.5A1.5 1.5 0 0 0 9 1.5H4A1.5 1.5 0 0 0 2.5 3v5A1.5 1.5 0 0 0 4 9.5h.5" fill="none" stroke="currentColor" stroke-width="1.4"/></svg>'
11
+
12
+ /** Done: a check (what was copied). */
13
+ export const CHECK_ICON =
14
+ '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M3 8.5 6.5 12 13 4.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>'
15
+
16
+ /** "Awaiting you: 2 things", and where: what the inbox says to a reader who hovers it. */
17
+ export const awaitingLabel = (n: number, where = '') =>
18
+ `Awaiting you: ${n === 1 ? '1 question or message' : `${n} questions and messages`}${where}`
package/src/listen.ts ADDED
@@ -0,0 +1,171 @@
1
+ // The command's side of listening (`workpad listen`): holding a listener at a server. A listen
2
+ // registers at its project's server first and only then reads the log, so from its first answer on
3
+ // the server knows it listens. A listen without a page in a project of the machine's entries covers
4
+ // the whole entry: the shared server names its projects (listeners.ts), at once and on every change,
5
+ // and the listen hands out from each project's log.
6
+ import http from 'node:http'
7
+ import https from 'node:https'
8
+ import type { Followed, Snapshot } from './listeners.ts'
9
+
10
+ /**
11
+ * A held GET to the server, over http or https as its address says: a server reached at an https
12
+ * URL (a container behind a proxy, see serverUrl) is held the same way, its certificate checked as
13
+ * Node checks any (a private CA: NODE_EXTRA_CA_CERTS).
14
+ */
15
+ const get = (url: string, onResponse: (res: http.IncomingMessage) => void): http.ClientRequest =>
16
+ (url.startsWith('https:') ? https : http).get(url, onResponse)
17
+
18
+ export interface ListenOptions {
19
+ /** the server's base URL; null (or a throw) while none runs, tried again */
20
+ at: () => Promise<string | null>
21
+ /** what to ask /api/listen for: page, type, agent, or `entry` */
22
+ query: Record<string, string>
23
+ /** a listen over a whole entry: the projects it covers, at once and on every change */
24
+ onSnapshot?: (snapshot: Snapshot) => void
25
+ }
26
+
27
+ /**
28
+ * Hold a listener at a server for as long as the process runs, and again after the server restarts.
29
+ * Resolves once the server holds it; with `orNone`, also after a first try that found no server
30
+ * running (a listen reads the log all the same, and registers once one appears).
31
+ */
32
+ export function listen({ at, query, onSnapshot }: ListenOptions, { orNone = false } = {}): Promise<void> {
33
+ return new Promise(settled => {
34
+ const connect = async () => {
35
+ let base: string | null = null
36
+ try {
37
+ base = await at()
38
+ } catch {
39
+ /* none runs */
40
+ }
41
+ if (!base) {
42
+ if (orNone) settled()
43
+ return setTimeout(connect, 2000).unref()
44
+ }
45
+ let again = false
46
+ const retry = (ms: number) => {
47
+ if (!again) {
48
+ again = true
49
+ setTimeout(connect, ms).unref()
50
+ }
51
+ }
52
+ const req = get(`${base}/api/listen?${new URLSearchParams(query)}`, res => {
53
+ res.setEncoding('utf8')
54
+ settled()
55
+ // held: the connection alone does not keep the command running. Not before: until the
56
+ // server answers, nothing else may keep it alive, and it would exit mid-connect
57
+ res.socket.unref()
58
+ let buf = ''
59
+ res.on('data', (chunk: string) => {
60
+ buf += chunk
61
+ // an event ends at a blank line: `event: projects` and its data
62
+ let end
63
+ while ((end = buf.indexOf('\n\n')) >= 0) {
64
+ const block = buf.slice(0, end)
65
+ buf = buf.slice(end + 2)
66
+ const event = /^event: (.*)$/m.exec(block)?.[1]
67
+ const data = /^data: (.*)$/m.exec(block)?.[1]
68
+ if (event === 'projects' && data && onSnapshot) onSnapshot(JSON.parse(data) as Snapshot)
69
+ }
70
+ })
71
+ res.on('close', () => retry(1000))
72
+ })
73
+ req.on('error', () => retry(2000))
74
+ }
75
+ void connect()
76
+ })
77
+ }
78
+
79
+ /**
80
+ * A listen over the projects a server names: `start` is called once for each project as it appears,
81
+ * to hand out from its log; a project no longer named is stopped (`signal`).
82
+ * @returns what takes each snapshot the server sends
83
+ */
84
+ export function everyProject(start: (project: Followed, signal: AbortSignal) => void): (snapshot: Snapshot) => void {
85
+ const followed = new Map<string, AbortController>()
86
+ return ({ projects }) => {
87
+ for (const p of projects) {
88
+ if (followed.has(p.dir)) continue
89
+ const stop = new AbortController()
90
+ followed.set(p.dir, stop)
91
+ start(p, stop.signal)
92
+ }
93
+ for (const [dir, stop] of followed)
94
+ if (!projects.some(p => p.dir === dir)) {
95
+ stop.abort()
96
+ followed.delete(dir)
97
+ }
98
+ }
99
+ }
100
+
101
+ /** What a channel's line does with what the server sends it (`CommandContext.channel`). */
102
+ export interface ChannelHandlers {
103
+ /** `workpad agent ping` in the session: push the pong, with this code, into it */
104
+ onPing(code: string): void
105
+ /** the agent confirmed a pong: its messages reach it */
106
+ onConfirmed(): void
107
+ }
108
+
109
+ /**
110
+ * Hold an agent channel's line at the server (/api/channel) for as long as the process runs, and
111
+ * again after the server restarts, then saying it was confirmed: the server forgets that. `move`:
112
+ * the session it serves changed (a resume); it was confirmed for the process, not the session, so
113
+ * that stays.
114
+ */
115
+ export function holdChannel(
116
+ at: () => Promise<string | null>,
117
+ first: string,
118
+ { onPing, onConfirmed }: ChannelHandlers,
119
+ ): { move(session: string): void } {
120
+ const id = Math.random().toString(36).slice(2) + Date.now().toString(36)
121
+ let session = first
122
+ let confirmed = false
123
+ let current: http.ClientRequest | null = null
124
+ const connect = async () => {
125
+ let base: string | null = null
126
+ try {
127
+ base = await at()
128
+ } catch {
129
+ /* none runs */
130
+ }
131
+ if (!base) return void setTimeout(connect, 2000).unref()
132
+ let again = false
133
+ const retry = (ms: number) => {
134
+ if (again) return
135
+ again = true
136
+ setTimeout(connect, ms).unref()
137
+ }
138
+ const query = new URLSearchParams({ id, session, ...(confirmed && { confirmed: '1' }) })
139
+ const req = (current = get(`${base}/api/channel?${query}`, res => {
140
+ res.setEncoding('utf8')
141
+ res.socket.unref()
142
+ let buf = ''
143
+ res.on('data', (chunk: string) => {
144
+ buf += chunk
145
+ let end
146
+ while ((end = buf.indexOf('\n\n')) >= 0) {
147
+ const block = buf.slice(0, end)
148
+ buf = buf.slice(end + 2)
149
+ const event = /^event: (.*)$/m.exec(block)?.[1]
150
+ const data = /^data: (.*)$/m.exec(block)?.[1]
151
+ if (event === 'ping' && data) onPing((JSON.parse(data) as { code: string }).code)
152
+ if (event === 'confirmed' && !confirmed) {
153
+ confirmed = true
154
+ onConfirmed()
155
+ }
156
+ }
157
+ })
158
+ res.on('close', () => retry(1000))
159
+ }))
160
+ req.on('error', () => retry(2000))
161
+ }
162
+ void connect()
163
+ return {
164
+ move(next) {
165
+ if (next === session) return
166
+ session = next
167
+ // its close connects again, with the new session
168
+ current?.destroy()
169
+ },
170
+ }
171
+ }