@bigmistqke/workpad 0.0.0-stage → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1509 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1190 -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 +2098 -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 +211 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +341 -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 +665 -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 +588 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +133 -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 +137 -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 +238 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +426 -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 +748 -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
@@ -0,0 +1,69 @@
1
+ // A window around a block: a header with its label (or an address), a button that opens what it
2
+ // shows on its own (an address, an image), and one that fills the browser window with it (the page
3
+ // does that: src/client/page/window.ts; the same button, or Esc, puts it back). The iframe block
4
+ // is one around a page, `:::window` one around any markdown; any block can draw one.
5
+ import { html, raw, type Html } from '../html.ts'
6
+
7
+ // the header's buttons, as icons
8
+ const svg = (d: string) =>
9
+ raw(
10
+ `<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`,
11
+ )
12
+ const OPEN = svg(
13
+ '<path d="M9 2.5h4.5V7M13.5 2.5 7.5 8.5M11.5 9.5v3a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h3"/>',
14
+ )
15
+ const MAXIMIZE = svg('<path d="M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10"/>')
16
+ const RESTORE = svg('<path d="M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5"/>')
17
+
18
+ export interface WindowOptions {
19
+ /** what the window shows, as HTML */
20
+ body: Html | string
21
+ /** its label, as HTML (a block's label); without one, the header shows `address` */
22
+ label?: Html | string | null
23
+ /** what it shows on its own: an address, an image's; the ↗ button opens it, and hovering the label shows it */
24
+ open?: string | null
25
+ /** wider than the text column */
26
+ wide?: boolean
27
+ /** a height for its body (a CSS length); what's taller scrolls */
28
+ height?: string
29
+ /** a class for the window itself, for a block's styles and browser code to find it by */
30
+ className?: string
31
+ /** more in the header, after the label: a block's own controls (the tabs' ‹ › ) */
32
+ controls?: Html | string
33
+ }
34
+
35
+ /** A window around a block's HTML: see the top of this file. */
36
+ export function windowFrame({
37
+ body,
38
+ label = null,
39
+ open = null,
40
+ wide = false,
41
+ height,
42
+ className = '',
43
+ controls = '',
44
+ }: WindowOptions): Html {
45
+ const name =
46
+ label != null && String(label) !== ''
47
+ ? html`<span class="wp-window-title">${raw(String(label))}</span>`
48
+ : open
49
+ ? html`<span class="wp-window-address">${open}</span>`
50
+ : html``
51
+ const header = html`<div class="wp-window-bar">
52
+ <span class="wp-window-name" ${open ? html` title="${open}"` : ''}>${name}</span>
53
+ ${raw(String(controls))}
54
+ ${open && html`<a class="wp-window-button" href="${open}" target="_blank" rel="noopener" title="Open on its own" aria-label="Open on its own">${OPEN}</a>`}
55
+ <button
56
+ type="button"
57
+ class="wp-window-button"
58
+ data-wp-maximize
59
+ title="Fill the window"
60
+ aria-label="Fill the window"
61
+ >
62
+ <span class="wp-window-max">${MAXIMIZE}</span><span class="wp-window-restore">${RESTORE}</span>
63
+ </button>
64
+ </div>`
65
+ return html`<div class="wp-window${wide && raw(' wp-wide')}${className && raw(' ' + className)}">
66
+ ${header}
67
+ <div class="wp-window-body" ${height ? html` style="height: ${height}"` : ''}>${raw(String(body))}</div>
68
+ </div>`
69
+ }
package/src/plugins.ts ADDED
@@ -0,0 +1,319 @@
1
+ // Plugins' routes and commands: declared, so the core mounts them under the plugin's name,
2
+ // checks the token and the arguments before a plugin's code runs, and lists them in the help
3
+ // and the docs. Two plugins can't collide: everything a plugin declares lives under its name,
4
+ // and names are unique (and can't be a built-in command).
5
+ //
6
+ // routes: { 'GET /status': { description, auth, query, run } } → GET /api/<plugin>/status
7
+ // commands: { '': { description, args, options, run }, stop: {…} } → workpad <plugin> [stop]
8
+ import { parseArgs, type ParseArgsOptionsConfig } from 'node:util'
9
+ import type { IncomingMessage, ServerResponse } from 'node:http'
10
+ import type { Command, FieldType, Plugin, Route } from './define.ts'
11
+
12
+ /** A route as mounted: its method and full path, and the plugin it is from. */
13
+ export interface MountedRoute {
14
+ method: string
15
+ path: string
16
+ route: Route
17
+ plugin: string
18
+ }
19
+
20
+ /** A plugin's command as the command line offers it: `workpad <plugin> [sub]`; or the config's, `workpad <name>`. */
21
+ export interface PluginCommand {
22
+ /** the plugin's name, or the config's command's */
23
+ plugin: string
24
+ /** where it is from: a plugin, or the config's own `commands` */
25
+ from: 'plugin' | 'config'
26
+ sub: string
27
+ command: Command
28
+ /** `<plugin> <sub>`, as typed */
29
+ name: string
30
+ }
31
+
32
+ // ---- fields --------------------------------------------------------------------------------------
33
+ // The small vocabulary of a route's body and query and a command's options: a type name, `?` for
34
+ // optional.
35
+
36
+ type BaseType = 'string' | 'number' | 'boolean' | 'string[]'
37
+
38
+ const TYPES: Record<BaseType, (v: unknown) => boolean> = {
39
+ string: v => typeof v === 'string',
40
+ number: v => typeof v === 'number' && Number.isFinite(v),
41
+ boolean: v => typeof v === 'boolean',
42
+ 'string[]': v => Array.isArray(v) && v.every(x => typeof x === 'string'),
43
+ }
44
+
45
+ function parseType(spec: FieldType | string, where: string): { type: BaseType; optional: boolean } {
46
+ const optional = spec.endsWith('?')
47
+ const type = optional ? spec.slice(0, -1) : spec
48
+ if (!(type in TYPES))
49
+ throw new Error(`${where}: unknown type "${spec}" (one of ${Object.keys(TYPES).join(', ')}, with ? when optional)`)
50
+ return { type: type as BaseType, optional }
51
+ }
52
+
53
+ /** What is wrong with `value` against `spec` ({ name: 'string?' }), or null. Unknown fields are wrong too. */
54
+ function checkFields(spec: Record<string, FieldType> = {}, input: unknown = {}, where: string): string | null {
55
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) return `${where} must be an object`
56
+ const value = input as Record<string, unknown>
57
+ for (const [name, s] of Object.entries(spec)) {
58
+ const { type, optional } = parseType(s, where)
59
+ if (value[name] === undefined) {
60
+ if (!optional) return `${where}: ${name} is missing`
61
+ continue
62
+ }
63
+ if (!TYPES[type](value[name])) return `${where}: ${name} must be ${type}`
64
+ }
65
+ for (const name of Object.keys(value)) if (!(name in spec)) return `${where}: unknown field ${name}`
66
+ return null
67
+ }
68
+
69
+ /** Query strings are text: a number or boolean in the spec is read from it. */
70
+ function fromQuery(spec: Record<string, FieldType> = {}, params: URLSearchParams): Record<string, unknown> {
71
+ const out: Record<string, unknown> = {}
72
+ for (const [name, value] of params) {
73
+ const field = spec[name]
74
+ const type = field ? parseType(field, 'query').type : 'string'
75
+ out[name] = type === 'number' ? Number(value) : type === 'boolean' ? value === 'true' || value === '' : value
76
+ }
77
+ return out
78
+ }
79
+
80
+ // ---- routes ------------------------------------------------------------------------------------
81
+
82
+ const ROUTE = /^(GET|POST|PUT|PATCH|DELETE) (\/[\w\-/]*)$/
83
+
84
+ /** A plugin's routes, checked and mounted under /api/<name>/. Throws on a malformed one. */
85
+ export function mountRoutes(name: string, routes: Record<string, Route> = {}): MountedRoute[] {
86
+ const table: MountedRoute[] = []
87
+ for (const [key, route] of Object.entries(routes)) {
88
+ const m = ROUTE.exec(key)
89
+ if (!m) throw new Error(`plugin ${name}: route "${key}" must look like "GET /path"`)
90
+ if (typeof route?.run !== 'function') throw new Error(`plugin ${name}: route "${key}" has no run function`)
91
+ for (const [field, spec] of Object.entries({ ...route.body, ...route.query }))
92
+ parseType(spec, `plugin ${name}, route "${key}", ${field}`)
93
+ const [, method, at] = m as unknown as [string, string, string]
94
+ const path = `/api/${name}${at === '/' ? '' : at.replace(/\/$/, '')}`
95
+ if (table.some(r => r.method === method && r.path === path))
96
+ throw new Error(`plugin ${name}: route "${key}" is declared twice`)
97
+ table.push({ method, path, route, plugin: name })
98
+ }
99
+ return table
100
+ }
101
+
102
+ function readJson(req: IncomingMessage): Promise<unknown> {
103
+ return new Promise((resolve, reject) => {
104
+ let body = ''
105
+ req.on('data', (c: Buffer) => {
106
+ body += c
107
+ if (body.length > 1e6) {
108
+ reject(new Error('body too large'))
109
+ req.destroy()
110
+ }
111
+ })
112
+ req.on('end', () => {
113
+ try {
114
+ resolve(body ? JSON.parse(body) : {})
115
+ } catch {
116
+ reject(new Error('the body is not JSON'))
117
+ }
118
+ })
119
+ req.on('error', reject)
120
+ })
121
+ }
122
+
123
+ const json = (res: ServerResponse, status: number, data: unknown) => {
124
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })
125
+ res.end(JSON.stringify(data))
126
+ }
127
+
128
+ /**
129
+ * Answer a request with the route it matches: false when none does. The core checks the token
130
+ * (`auth`), the query and the body before the route's code runs. A route returns what is sent as
131
+ * JSON; a stream route (`stream: true`) writes to `res` itself. An error it throws is sent with its
132
+ * `status` (default 500).
133
+ */
134
+ export async function dispatch(
135
+ table: MountedRoute[],
136
+ req: IncomingMessage,
137
+ res: ServerResponse,
138
+ url: URL,
139
+ authorized: (req: IncomingMessage) => boolean,
140
+ ): Promise<boolean> {
141
+ const forPath = table.filter(r => r.path === url.pathname)
142
+ if (!forPath.length) return false
143
+ const hit = forPath.find(r => r.method === req.method)
144
+ if (!hit) {
145
+ res.setHeader('allow', forPath.map(r => r.method).join(', '))
146
+ json(res, 405, { error: `use ${forPath.map(r => r.method).join(' or ')}` })
147
+ return true
148
+ }
149
+ const { route } = hit
150
+ if (route.auth && !authorized(req)) {
151
+ json(res, 403, {
152
+ error: "this needs the project's token: open a link from the command line, or send x-workpad-token",
153
+ })
154
+ return true
155
+ }
156
+ try {
157
+ const query = fromQuery(route.query, url.searchParams)
158
+ const queryError = route.query ? checkFields(route.query, query, 'query') : null
159
+ if (queryError) {
160
+ json(res, 400, { error: queryError })
161
+ return true
162
+ }
163
+ let body: Record<string, unknown> = {}
164
+ if (hit.method !== 'GET' && hit.method !== 'DELETE') {
165
+ const input = await readJson(req)
166
+ const bodyError = checkFields(route.body, input, 'body')
167
+ if (bodyError) {
168
+ json(res, 400, { error: bodyError })
169
+ return true
170
+ }
171
+ body = input as Record<string, unknown>
172
+ }
173
+ if (route.stream) {
174
+ await route.run({ body, query, req, res })
175
+ return true
176
+ }
177
+ const out = await route.run({ body, query, req })
178
+ json(res, 200, out ?? { ok: true })
179
+ } catch (err) {
180
+ if (res.headersSent) {
181
+ res.end()
182
+ return true
183
+ }
184
+ const e = err as { status?: number; message?: string } | null
185
+ json(res, e?.status ?? 500, { error: e?.message ?? String(err) })
186
+ }
187
+ return true
188
+ }
189
+
190
+ /** The routes for the docs: method, path, what it does, what it takes. */
191
+ export const describeRoutes = (table: MountedRoute[]) =>
192
+ table.map(({ method, path, route }) => ({
193
+ method,
194
+ path,
195
+ description: route.description ?? '',
196
+ auth: !!route.auth,
197
+ stream: !!route.stream,
198
+ body: route.body ?? null,
199
+ query: route.query ?? null,
200
+ }))
201
+
202
+ // ---- commands ----------------------------------------------------------------------------------
203
+
204
+ /** The commands of a plugin as `workpad <name> [sub]`, checked. */
205
+ export function pluginCommands(plugin: Plugin): PluginCommand[] {
206
+ return Object.entries(plugin.commands ?? {}).map(([sub, command]) => {
207
+ const where = `plugin ${plugin.name}, command "${sub}"`
208
+ if (sub && !/^[\w-]+$/.test(sub)) throw new Error(`${where}: use letters, digits, - and _`)
209
+ checkCommand(command, where)
210
+ return {
211
+ plugin: plugin.name,
212
+ from: 'plugin' as const,
213
+ sub,
214
+ command,
215
+ name: [plugin.name, sub].filter(Boolean).join(' '),
216
+ }
217
+ })
218
+ }
219
+
220
+ function checkCommand(command: Command, where: string) {
221
+ if (typeof command?.run !== 'function') throw new Error(`${where} has no run function`)
222
+ if (command.live !== undefined && typeof command.live !== 'boolean') throw new Error(`${where}: live is true or false`)
223
+ for (const [name, o] of Object.entries(command.options ?? {})) parseType(o.type, `${where}, option ${name}`)
224
+ }
225
+
226
+ /**
227
+ * The config's own commands (`commands` in defineConfig), as `workpad <name>`, checked: a name is
228
+ * letters, digits, - and _, and is none of `taken` (the built-in commands, the core's folders) nor a
229
+ * plugin's name, which would be two commands under one name.
230
+ */
231
+ export function configCommands(
232
+ commands: Record<string, Command> | undefined,
233
+ { taken, plugins, where }: { taken: ReadonlySet<string>; plugins: readonly string[]; where: string | null },
234
+ ): PluginCommand[] {
235
+ return Object.entries(commands ?? {}).map(([name, command]) => {
236
+ const at = `command "${name}" in ${where}`
237
+ if (!/^[\w-]+$/.test(name)) throw new Error(`${at}: name it with letters, digits, - and _`)
238
+ if (taken.has(name)) throw new Error(`${at}: \`workpad ${name}\` is workpad's own (a built-in command or a folder of the core); name it otherwise`)
239
+ if (plugins.includes(name))
240
+ throw new Error(`${at}: the plugin ${name} has that name, and its commands are \`workpad ${name}\`; name it otherwise`)
241
+ checkCommand(command, at)
242
+ return { plugin: name, from: 'config' as const, sub: '', command, name }
243
+ })
244
+ }
245
+
246
+ /** Do these arguments ask for help (--help or -h before any `--`)? */
247
+ export function asksHelp(args: string[]): boolean {
248
+ const cut = args.indexOf('--')
249
+ return (cut < 0 ? args : args.slice(0, cut)).some(a => a === '--help' || a === '-h')
250
+ }
251
+
252
+ /** `workpad <plugin> [sub] --help`: its usage, description, and each option with what it means. */
253
+ export function pluginCommandHelp({ name, command }: PluginCommand): string {
254
+ const options = Object.entries(command.options ?? {}).map(([key, o]) => {
255
+ const { type } = parseType(o.type, key)
256
+ const flag = `--${key}${type === 'boolean' ? '' : ` <${o.value ?? type}>`}${o.short ? `, -${o.short}` : ''}`
257
+ return ` ${flag.padEnd(22)} ${o.description ?? ''}`.trimEnd()
258
+ })
259
+ return [
260
+ `usage: workpad ${[name, usage(command)].filter(Boolean).join(' ')}`,
261
+ '',
262
+ command.description,
263
+ ...(options.length ? ['', ...options] : []),
264
+ ...(command.rest ? ['', `after --: ${command.rest}, passed on as they are`] : []),
265
+ ].join('\n')
266
+ }
267
+
268
+ /** `[page] [--restart] [-- <arguments>]` */
269
+ export function usage(command: Command): string {
270
+ const options = Object.entries(command.options ?? {}).map(([name, o]) => {
271
+ const { type } = parseType(o.type, name)
272
+ return `[--${name}${type === 'boolean' ? '' : ` <${o.value ?? type}>`}]`
273
+ })
274
+ return [command.args ?? '', ...options, command.rest ? `[-- ${command.rest}]` : ''].filter(Boolean).join(' ')
275
+ }
276
+
277
+ /**
278
+ * Parse a command's arguments by its declared options; throws with the usage on a wrong one. What
279
+ * follows `--` is passed on untouched, as `rest`, when the command takes it.
280
+ */
281
+ export function parseCommandArgs(command: Command, all: string[], name: string) {
282
+ const cut = all.indexOf('--')
283
+ const args = cut < 0 ? all : all.slice(0, cut)
284
+ const rest = cut < 0 ? [] : all.slice(cut + 1)
285
+ if (rest.length && !command.rest)
286
+ throw new Error(`workpad ${name} takes nothing after --\nusage: workpad ${name} ${usage(command)}`)
287
+ const options: ParseArgsOptionsConfig = Object.fromEntries(
288
+ Object.entries(command.options ?? {}).map(([key, o]) => {
289
+ const { type } = parseType(o.type, key)
290
+ return [
291
+ key,
292
+ {
293
+ type: type === 'boolean' ? ('boolean' as const) : ('string' as const),
294
+ ...(o.short ? { short: o.short } : {}),
295
+ },
296
+ ]
297
+ }),
298
+ )
299
+ let parsed
300
+ try {
301
+ parsed = parseArgs({ args, options, allowPositionals: true, strict: true })
302
+ } catch (err) {
303
+ throw new Error(`${(err as Error).message}\nusage: workpad ${name} ${usage(command)}`)
304
+ }
305
+ const values: Record<string, unknown> = { ...parsed.values }
306
+ for (const [key, o] of Object.entries(command.options ?? {})) {
307
+ const { type, optional } = parseType(o.type, key)
308
+ if (values[key] === undefined) {
309
+ if (!optional && type !== 'boolean')
310
+ throw new Error(`--${key} is missing\nusage: workpad ${name} ${usage(command)}`)
311
+ continue
312
+ }
313
+ if (type === 'number') {
314
+ values[key] = Number(values[key])
315
+ if (!Number.isFinite(values[key])) throw new Error(`--${key} must be a number`)
316
+ }
317
+ }
318
+ return { options: values, positionals: parsed.positionals, rest }
319
+ }
package/src/public.ts ADDED
@@ -0,0 +1,39 @@
1
+ // A plugin's public folder: the one place its browser files are served from (its client modules,
2
+ // stylesheets, images, fonts; TypeScript there is served with its types stripped). The server
3
+ // serves what is inside a plugin's public folder, and nothing else of the plugin: not its server
4
+ // code, not the project's files beside it.
5
+ //
6
+ // A plugin says where (`public`); definePlugin defaults it to `public/` next to the module that
7
+ // calls it; a plugin that is a plain object (one written inline in the config, say) has the
8
+ // project's `.workpad/public/`. Its files (`client`, `style`, a block's) are named within it.
9
+ import path from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import type { Plugin } from './define.ts'
12
+
13
+ const asPath = (ref: URL | string): string => (ref instanceof URL || ref.startsWith('file:') ? fileURLToPath(ref) : ref)
14
+
15
+ /** The folder a plugin's browser files are served from. */
16
+ export function publicDirOf(plugin: Plugin, wp: string): string {
17
+ return path.resolve(plugin.public != null ? asPath(plugin.public) : path.join(wp, 'public'))
18
+ }
19
+
20
+ /** Is `file` inside `dir`? */
21
+ export const within = (file: string, dir: string): boolean => {
22
+ const rel = path.relative(dir, file)
23
+ return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel)
24
+ }
25
+
26
+ /**
27
+ * A file a plugin names, as a path: a name within its public folder (`style.css`,
28
+ * `client/main.js`), or a URL or absolute path, which must be inside it. Anything else is an
29
+ * error, said when the config loads, rather than a file that quietly isn't served.
30
+ */
31
+ export function inPublic(dir: string, ref: URL | string, what: string): string {
32
+ const file =
33
+ typeof ref === 'string' && !ref.startsWith('file:') && !path.isAbsolute(ref)
34
+ ? path.resolve(dir, ref)
35
+ : path.resolve(asPath(ref))
36
+ if (!within(file, dir))
37
+ throw new Error(`${what}: ${file} is not in its public folder (${dir}); a plugin's browser files live there`)
38
+ return file
39
+ }
package/src/rename.ts ADDED
@@ -0,0 +1,147 @@
1
+ // From the name this tool had before, whiteboard, to workpad: a project's `.whiteboard/` folder
2
+ // becomes `.workpad/`, the log's `whiteboard:*` events `workpad:*`, and its config and plugins
3
+ // import @bigmistqke/workpad and use `ctx.wp` and `wp-` classes; the machine's folders move too.
4
+ // Run once by `workpad migrate` (see bin/workpad.ts); nothing else reads the old names.
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import { alive } from './running.ts'
9
+
10
+ export const OLD = '.whiteboard'
11
+
12
+ /** One thing to do, said before it is done. */
13
+ export interface RenameStep {
14
+ what: string
15
+ run(): void
16
+ }
17
+
18
+ /** The project folder still under the old name: the nearest folder upward with a `.whiteboard/` folder and no `.workpad/`. */
19
+ export function oldProjectDir(from: string = process.cwd()): string | null {
20
+ let dir = path.resolve(from)
21
+ for (;;) {
22
+ if (isDir(path.join(dir, OLD)) && !isDir(path.join(dir, '.workpad'))) return dir
23
+ const up = path.dirname(dir)
24
+ if (up === dir) return null
25
+ dir = up
26
+ }
27
+ }
28
+
29
+ /** The code of a config or plugin, in the new names. */
30
+ export function renameCode(source: string): string {
31
+ return source
32
+ .replace(/@bigmistqke\/whiteboard\b/g, '@bigmistqke/workpad')
33
+ .replace(/\buseWhiteboard\b/g, 'useWorkpad')
34
+ .replace(/\bWbEvent\b/g, 'WpEvent')
35
+ .replace(/\bctx\.wb\b/g, 'ctx.wp')
36
+ .replace(/\bwb-(?=[a-z])/g, 'wp-')
37
+ .replace(/\bdataset\.wb(?=[A-Z])/g, 'dataset.wp')
38
+ .replace(/\bWHITEBOARD_/g, 'WORKPAD_')
39
+ }
40
+
41
+ /** A line of the log, its type in the new name. */
42
+ export function renameEvent(line: string): string {
43
+ if (!line.includes('"whiteboard:')) return line
44
+ try {
45
+ const e = JSON.parse(line)
46
+ if (typeof e.type !== 'string' || !e.type.startsWith('whiteboard:')) return line
47
+ return JSON.stringify({ ...e, type: `workpad:${e.type.slice('whiteboard:'.length)}` })
48
+ } catch {
49
+ return line
50
+ }
51
+ }
52
+
53
+ /** What moving the project in `dir` to the new names takes; throws when its server is running. */
54
+ export function projectSteps(dir: string): RenameStep[] {
55
+ const from = path.join(dir, OLD)
56
+ const to = path.join(dir, '.workpad')
57
+ refuseRunning(path.join(from, 'server.json'), `the server of ${dir}`, 'workpad stop')
58
+ const steps: RenameStep[] = [{ what: `${rel(from)} → ${rel(to)}`, run: () => fs.renameSync(from, to) }]
59
+ const log = path.join(from, 'events.ndjson')
60
+ if (fs.existsSync(log)) {
61
+ const lines = fs.readFileSync(log, 'utf8').split('\n')
62
+ const renamed = lines.map(renameEvent)
63
+ const n = renamed.filter((l, i) => l !== lines[i]).length
64
+ if (n)
65
+ steps.push({
66
+ what: ` events.ndjson: ${n} whiteboard:* event${n === 1 ? '' : 's'} → workpad:*`,
67
+ run: () => fs.writeFileSync(path.join(to, 'events.ndjson'), renamed.join('\n')),
68
+ })
69
+ }
70
+ for (const file of codeFiles(from)) {
71
+ const before = fs.readFileSync(file, 'utf8')
72
+ const after = renameCode(before)
73
+ if (after !== before)
74
+ steps.push({
75
+ what: ` ${path.relative(from, file)}: the new names`,
76
+ run: () => fs.writeFileSync(path.join(to, path.relative(from, file)), after),
77
+ })
78
+ }
79
+ const ignore = path.join(dir, '.gitignore')
80
+ if (fs.existsSync(ignore)) {
81
+ const before = fs.readFileSync(ignore, 'utf8')
82
+ const after = before.replace(/^(\/?)\.whiteboard(\/?)$/gm, '$1.workpad$2')
83
+ if (after !== before)
84
+ steps.push({ what: ` ${rel(ignore)}: .whiteboard → .workpad`, run: () => fs.writeFileSync(ignore, after) })
85
+ }
86
+ return steps
87
+ }
88
+
89
+ /**
90
+ * The machine's folders under the old name, moved where workpad looks: the machine config
91
+ * (`~/.config/whiteboard`) and the shared server's state (`~/.local/state/whiteboard`). Only the
92
+ * defaults: a folder set with $WHITEBOARD_HOME stays, and is $WORKPAD_HOME now.
93
+ */
94
+ export function machineSteps(env: NodeJS.ProcessEnv = process.env): RenameStep[] {
95
+ if (env.WORKPAD_HOME) return []
96
+ const config = env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')
97
+ const state = env.WORKPAD_STATE ? null : env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state')
98
+ const steps: RenameStep[] = []
99
+ for (const base of [config, state]) {
100
+ if (!base) continue
101
+ const from = path.join(base, 'whiteboard')
102
+ const to = path.join(base, 'workpad')
103
+ if (!isDir(from) || fs.existsSync(to)) continue
104
+ refuseRunning(path.join(from, 'server.json'), 'the shared server', 'workpad stop --shared')
105
+ steps.push({ what: `${tilde(from)} → ${tilde(to)}`, run: () => fs.renameSync(from, to) })
106
+ }
107
+ return steps
108
+ }
109
+
110
+ function refuseRunning(record: string, who: string, stop: string) {
111
+ try {
112
+ const { pid } = JSON.parse(fs.readFileSync(record, 'utf8'))
113
+ if (typeof pid === 'number' && alive(pid))
114
+ throw new Error(`${who} is running (pid ${pid}) under the old name: stop it first (${stop}, or kill ${pid})`)
115
+ } catch (e) {
116
+ if (e instanceof Error && e.message.includes('is running')) throw e
117
+ }
118
+ }
119
+
120
+ /** A project folder's config and plugins: the code that may name the old package, ctx.wb or wb- classes. */
121
+ function codeFiles(folder: string): string[] {
122
+ const out: string[] = []
123
+ const walk = (dir: string, top: boolean) => {
124
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
125
+ const p = path.join(dir, e.name)
126
+ if (e.isDirectory()) {
127
+ if (top ? e.name === 'plugins' : e.name !== 'node_modules') walk(p, false)
128
+ } else if (/\.(ts|tsx|js|jsx|mjs|css)$/.test(e.name) && (!top || e.name.startsWith('config.'))) out.push(p)
129
+ }
130
+ }
131
+ walk(folder, true)
132
+ return out
133
+ }
134
+
135
+ function isDir(p: string) {
136
+ try {
137
+ return fs.statSync(p).isDirectory()
138
+ } catch {
139
+ return false
140
+ }
141
+ }
142
+
143
+ const rel = (p: string) => {
144
+ const r = path.relative(process.cwd(), p)
145
+ return r && !r.startsWith('..') ? r : p
146
+ }
147
+ const tilde = (p: string) => (p.startsWith(os.homedir()) ? `~${p.slice(os.homedir().length)}` : p)