@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,1105 @@
1
+ import { appendEvent, follow, forAgent, handle, isEventId, matches, read, readEvents } from "./events.js";
2
+ import { after, agentsOf, chatsOf, formsOf, live, matchesQuery, pageUrl, pagesOf, subscriptionsOf } from "./state.js";
3
+ import { FormStateError, holdForms, releaseForms, settleForms } from "./formstate.js";
4
+ import { anchorsOf } from "./anchors.js";
5
+ import { html } from "./html.js";
6
+ import { createConfigLoader, pluginDir, toPath } from "./loader.js";
7
+ import { describeRoutes, dispatch, mountRoutes, pluginCommands, usage } from "./plugins.js";
8
+ import { createAuth, sameSite } from "./auth.js";
9
+ import { accept, refuse } from "./ws.js";
10
+ import { FROM_SOURCE, PACKAGE_DIR, VERSION } from "./package.js";
11
+ import { SCROLL, SUBSCRIBE, agentMessagesIn, awaiting, handledIds, isAgentMessage, namesOf, projectStatus, receivedIds, subscriptions } from "./status.js";
12
+ import { formsIn, messageForms } from "./pages/markdown.js";
13
+ import { fileFilter } from "./files.js";
14
+ import { titleOf } from "./pages/render.js";
15
+ import { createRegistry, holdStream, listenerOf } from "./listeners.js";
16
+ import { inPublic } from "./public.js";
17
+ import { build } from "./build.js";
18
+ import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts } from "./document.js";
19
+ import { inside, isRepoId, pageSource, servedSite, within } from "./site.js";
20
+ import { stripTypeScriptTypes } from "node:module";
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import crypto from "node:crypto";
24
+ // src/server.ts
25
+ const ENGINE_DIR = PACKAGE_DIR;
26
+ const MIME = {
27
+ ".css": "text/css",
28
+ ".js": "text/javascript",
29
+ ".mjs": "text/javascript",
30
+ ".json": "application/json",
31
+ ".png": "image/png",
32
+ ".jpg": "image/jpeg",
33
+ ".jpeg": "image/jpeg",
34
+ ".gif": "image/gif",
35
+ ".webp": "image/webp",
36
+ ".avif": "image/avif",
37
+ ".svg": "image/svg+xml",
38
+ ".pdf": "application/pdf",
39
+ ".mp4": "video/mp4",
40
+ ".webm": "video/webm",
41
+ ".woff": "font/woff",
42
+ ".woff2": "font/woff2",
43
+ ".txt": "text/plain; charset=utf-8",
44
+ ".md": "text/markdown; charset=utf-8",
45
+ ".csv": "text/csv; charset=utf-8",
46
+ ".html": "text/html; charset=utf-8"
47
+ };
48
+ const OWN_FILES = /* @__PURE__ */ new Set([
49
+ "events.ndjson",
50
+ "server.json",
51
+ "server.log",
52
+ "server.lock",
53
+ "token"
54
+ ]);
55
+ /** The lists the API answers with, by the path they are at: GET /api/<what>. */
56
+ const API_LISTS = [
57
+ "projects",
58
+ "pages",
59
+ "forms",
60
+ "chats",
61
+ "subscriptions",
62
+ "agents"
63
+ ];
64
+ function createServer(project, { base = "", entry, label, name, files: filesOption, filesDefault, overview, onChange, origins = () => [] } = {}) {
65
+ const projectName = () => name ?? project.name;
66
+ const loader = createConfigLoader(project, { files: filesDefault });
67
+ const auth = createAuth(project.wp, base, origins);
68
+ const watchers = /* @__PURE__ */ new Set();
69
+ const streams = /* @__PURE__ */ new Set();
70
+ const watch = (dir, options, fn) => {
71
+ try {
72
+ watchers.add(fs.watch(dir, options, (_evt, name) => {
73
+ if (name) fn(String(name));
74
+ }));
75
+ } catch {}
76
+ };
77
+ const setups = /* @__PURE__ */ new WeakMap();
78
+ const pluginDirs = /* @__PURE__ */ new Set();
79
+ /** The hooks of the loaded config's plugins, set up once per config. */
80
+ async function pluginHooks() {
81
+ const c = await config();
82
+ if (!setups.has(c)) setups.set(c, Promise.all(c.plugins.map(async (e) => {
83
+ try {
84
+ pluginDirs.add(e.name);
85
+ const dataDir = pluginDir(project.wp, e.name);
86
+ const dir = c.publicDirs.get(e.name);
87
+ const hooks = await e.setup?.({
88
+ project: {
89
+ name: project.name,
90
+ dir: project.dir,
91
+ wp: project.wp
92
+ },
93
+ dataDir,
94
+ authorized: auth.authorized
95
+ }) ?? {};
96
+ const client = hooks.client != null ? inPublic(dir, hooks.client, `plugin ${e.name}: client`) : void 0;
97
+ return {
98
+ name: e.name,
99
+ ...hooks,
100
+ client,
101
+ table: mountRoutes(e.name, hooks.routes),
102
+ plugin: e
103
+ };
104
+ } catch (err) {
105
+ console.error(`plugin ${e.name}:`, err);
106
+ return {
107
+ name: e.name,
108
+ table: [],
109
+ plugin: e,
110
+ error: err
111
+ };
112
+ }
113
+ })));
114
+ return setups.get(c);
115
+ }
116
+ /** A page as the server serves it: the render with what the plugins add, their failures among its notices. */
117
+ async function page(req, stored, rendered) {
118
+ const notices = [...rendered.notices];
119
+ const parts = await pluginParts(await pluginHooks(), req, {
120
+ asset,
121
+ messages: [...(await config()).forReader],
122
+ failed: (message) => {
123
+ console.error(message);
124
+ notices.push(message);
125
+ }
126
+ });
127
+ return pageDocument(stored, {
128
+ ...rendered,
129
+ notices
130
+ }, parts, {
131
+ live: true,
132
+ base,
133
+ asset,
134
+ runtime: `${base}/_/runtime.js`,
135
+ title: projectName(),
136
+ stamps: stamps()
137
+ });
138
+ }
139
+ /** The loaded config. Also applies its `files` setting to what is served and watched. */
140
+ async function config() {
141
+ const c = await loader.config();
142
+ setFiles(filesOption ?? c.files, c.fileFilter);
143
+ publicDirs = [...c.publicDirs.values()];
144
+ return c;
145
+ }
146
+ const assets = /* @__PURE__ */ new Set();
147
+ const assetDirs = /* @__PURE__ */ new Set();
148
+ const TYPESCRIPT = /\.m?ts$/i;
149
+ const typeScriptModule = (file) => stripTypeScriptTypes(fs.readFileSync(file, "utf8"));
150
+ let publicDirs = [];
151
+ const servable = (file) => assets.has(file) || publicDirs.some((dir) => within(file, dir) && file !== dir);
152
+ function asset(ref) {
153
+ const file = toPath(ref);
154
+ if (!assets.has(file)) {
155
+ assets.add(file);
156
+ const dir = path.dirname(file);
157
+ if (!assetDirs.has(dir)) {
158
+ assetDirs.add(dir);
159
+ if (!within(dir, project.wp) && !ENGINE_WATCHED.some((d) => within(dir, d))) watch(dir, {}, (name) => onSourceChange(path.join(dir, name)));
160
+ }
161
+ }
162
+ return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join("/")}`;
163
+ }
164
+ const site = servedSite(project, {
165
+ base,
166
+ files: () => !!FILES,
167
+ filter: () => FILTER
168
+ });
169
+ const stored = site.page;
170
+ const pagesIn = site.pagesIn;
171
+ const urlFor = site.urlFor;
172
+ /** A config that failed to load: the page as stored, as text, under the error. */
173
+ function rawRender(page) {
174
+ const list = (items) => html`<ul>
175
+ ${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}
176
+ </ul>`;
177
+ if (page.kind === "pages") return { html: list(page.pages.map((p) => [`${base}/${p.id}`, p.id])) };
178
+ if (page.kind === "folder") return { html: list(page.entries.map((e) => [encodeURIComponent(e.name) + (e.dir ? "/" : ""), e.name + (e.dir ? "/" : "")])) };
179
+ return { html: html`<pre>${page.source}</pre>` };
180
+ }
181
+ const context = () => ({
182
+ project: {
183
+ name: projectName(),
184
+ dir: project.dir,
185
+ files: !!FILES,
186
+ shows: (rel) => FILTER.shows(rel)
187
+ },
188
+ asset,
189
+ urlFor,
190
+ base,
191
+ ...entry && { entry: {
192
+ name: entry,
193
+ label
194
+ } }
195
+ });
196
+ /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
197
+ async function render(page) {
198
+ const { pages, errors } = await config();
199
+ const notices = errors.map((e) => `config: ${e.message}`);
200
+ if (page.kind === "page" && page.frontmatterError) notices.push(`frontmatter: ${page.frontmatterError}`);
201
+ let out;
202
+ let rendered = !!pages;
203
+ try {
204
+ out = pages ? await pages.render(page, context()) : rawRender(page);
205
+ } catch (err) {
206
+ console.error("render:", err);
207
+ notices.push(`the page failed to render: ${err.message}`);
208
+ out = rawRender(page);
209
+ rendered = false;
210
+ }
211
+ for (const p of out.problems ?? []) notices.push(p);
212
+ const strings = {
213
+ ...out,
214
+ html: String(out.html ?? ""),
215
+ ...out.head != null ? { head: String(out.head) } : {}
216
+ };
217
+ return {
218
+ page: rendered,
219
+ out: strings,
220
+ notices
221
+ };
222
+ }
223
+ /**
224
+ * The project's status (status.ts): the pages, below `only` when given, with their questions, the
225
+ * log read once, and who listens. What `workpad status`, the hooks, the page lists and the log's
226
+ * picked-up marks take.
227
+ */
228
+ const asked = /* @__PURE__ */ new Map();
229
+ function questionsOf(renderer, id, file) {
230
+ let stat;
231
+ try {
232
+ stat = fs.statSync(file);
233
+ } catch {
234
+ return {
235
+ title: path.basename(id),
236
+ asks: [],
237
+ details: []
238
+ };
239
+ }
240
+ const kept = asked.get(id);
241
+ if (kept && kept.file === file && kept.mtime === stat.mtimeMs && kept.size === stat.size && kept.renderer === renderer) return kept;
242
+ let asks = [];
243
+ let chats;
244
+ let details = [];
245
+ try {
246
+ const source = pageSource(id, file);
247
+ asks = renderer?.questions(source) ?? [];
248
+ chats = renderer?.chats(source);
249
+ details = renderer?.forms(source) ?? [];
250
+ } catch (err) {
251
+ console.error("questions:", err);
252
+ }
253
+ const now = {
254
+ file,
255
+ mtime: stat.mtimeMs,
256
+ size: stat.size,
257
+ renderer,
258
+ title: titleOf(file, path.basename(id)),
259
+ asks,
260
+ chats,
261
+ details,
262
+ born: stat.birthtimeMs || stat.mtimeMs
263
+ };
264
+ asked.set(id, now);
265
+ return now;
266
+ }
267
+ async function snapshot(listed) {
268
+ const { pages: renderer, handedOut, forReader } = await config();
269
+ const events = readEvents(project.eventsFile);
270
+ const pages = listed.map((p) => {
271
+ const page = {
272
+ id: p.id,
273
+ file: p.file,
274
+ ...questionsOf(renderer, p.id, p.file)
275
+ };
276
+ return {
277
+ ...page,
278
+ asks: [...page.asks, ...messageForms(events, p.id, page.chats ?? [])]
279
+ };
280
+ });
281
+ return projectStatus({
282
+ pages,
283
+ events,
284
+ listeners: listenersFor,
285
+ forAgent: forAgent(handedOut),
286
+ forReader: (type) => forReader.has(type)
287
+ });
288
+ }
289
+ /** Per page, below `only` when given: what `workpad status` and the hooks report (see snapshot). */
290
+ const status = async (only) => (await snapshot(pagesIn(project.pagesDir).filter((p) => !only || p.id === only || p.id.startsWith(only + "/")))).pages;
291
+ /** A list of pages, with when each was last answered and how much waits on it, from one status. */
292
+ async function withStatus(pages) {
293
+ const s = await snapshot(pages);
294
+ pages.forEach((p, i) => {
295
+ p.awaiting = awaiting(s.pages[i]);
296
+ p.lastEvent = s.lastAnswered(p.id);
297
+ });
298
+ return pages;
299
+ }
300
+ /** The pages below `only` (a page and those below it), as listed. */
301
+ const listed = (only) => pagesIn(project.pagesDir).filter((p) => !only || p.id === only || p.id.startsWith(only + "/"));
302
+ /** What the API's lists are made from, for the pages below `only`. */
303
+ async function stateSource(only) {
304
+ const pages = listed(only);
305
+ const statuses = (await snapshot(pages)).pages;
306
+ const { pages: renderer } = await config();
307
+ const kept = (id) => {
308
+ const p = pages.find((x) => x.id === id);
309
+ return p ? questionsOf(renderer, p.id, p.file) : null;
310
+ };
311
+ return {
312
+ base,
313
+ statuses,
314
+ events: readEvents(project.eventsFile),
315
+ details: (id) => kept(id)?.details ?? [],
316
+ times: (id) => {
317
+ const p = pages.find((x) => x.id === id);
318
+ const born = kept(id)?.born;
319
+ return p ? {
320
+ born: born ?? p.mtime,
321
+ modified: p.mtime
322
+ } : null;
323
+ },
324
+ listeners: listenersFor(null)
325
+ };
326
+ }
327
+ /** This project, as GET /api/projects lists it. */
328
+ const projectInfo = () => ({
329
+ base,
330
+ name: projectName(),
331
+ label: label ?? projectName(),
332
+ dir: project.dir,
333
+ entry: entry ?? null
334
+ });
335
+ const listOf = (q, key) => q[key] ? q[key].split(",").filter(Boolean) : [];
336
+ async function readList(what, q) {
337
+ if (what === "projects") return [projectInfo()];
338
+ const only = q.page || null;
339
+ if (what === "subscriptions" || what === "agents") {
340
+ const events = readEvents(project.eventsFile);
341
+ const under = (page) => !only || page === "" || page === only || page.startsWith(only + "/") || only.startsWith(page + "/");
342
+ if (what === "subscriptions") return subscriptionsOf({
343
+ base,
344
+ events
345
+ }).filter((x) => under(x.page) && (!q.agent || x.agent === q.agent));
346
+ return agentsOf({
347
+ base,
348
+ events,
349
+ listeners: listenersFor(null)
350
+ });
351
+ }
352
+ const source = await stateSource(only);
353
+ if (what === "pages") return pagesOf(source);
354
+ if (what === "chats") return chatsOf(source).filter((c) => !q.chat || c.chat === q.chat);
355
+ const states = listOf(q, "state");
356
+ const names = listOf(q, "name");
357
+ return formsOf(source).filter((f) => (!states.length || states.includes(f.state)) && (!names.length || names.includes(f.name)));
358
+ }
359
+ function stream(q, send) {
360
+ const { events, end } = read(project.eventsFile);
361
+ if (q.since) {
362
+ for (const e of after(events, q.since)) if (matchesQuery(e, q)) send(live(e, base));
363
+ }
364
+ return follow(project.eventsFile, end, (e) => {
365
+ if (matchesQuery(e, q)) send(live(e, base));
366
+ });
367
+ }
368
+ /** A write of the API: it needs the project's token; its JSON body; and who writes it (`agent`). */
369
+ async function writeOf(req, res) {
370
+ if (!auth.authorized(req)) {
371
+ sendJson(res, 403, { error: "this needs the project's token: send it as the header x-workpad-token (.workpad/token)" });
372
+ return null;
373
+ }
374
+ let body;
375
+ try {
376
+ body = JSON.parse(await readBody(req) || "{}");
377
+ } catch {
378
+ sendJson(res, 400, { error: "the body is not JSON" });
379
+ return null;
380
+ }
381
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
382
+ sendJson(res, 400, { error: "the body must be a JSON object" });
383
+ return null;
384
+ }
385
+ const b = body;
386
+ return {
387
+ body: b,
388
+ by: typeof b.agent === "string" && b.agent ? b.agent : null
389
+ };
390
+ }
391
+ /** The names of forms in a body: `forms`, a list of names. */
392
+ const formsIn_ = (b) => Array.isArray(b.forms) && b.forms.every((f) => typeof f === "string") ? b.forms : null;
393
+ /** POST /api/forms/<hold|release|settle>: { page, forms, reason?, all?, agent? } */
394
+ async function formWrite(action, req, res) {
395
+ const w = await writeOf(req, res);
396
+ if (!w) return;
397
+ const { body, by } = w;
398
+ if (typeof body.page !== "string") return sendJson(res, 400, { error: "page: the page the forms are on" });
399
+ const p = (await status(body.page)).find((x) => x.page === body.page);
400
+ if (!p) return sendJson(res, 404, { error: `no page ${body.page}` });
401
+ const forms = formsIn_(body);
402
+ try {
403
+ if (action === "settle") {
404
+ if (!forms && body.all !== true) return sendJson(res, 400, { error: "forms: the names to settle, or all: true" });
405
+ const { event, forms: settled, skipped } = settleForms(project.eventsFile, p, forms ?? "all", by);
406
+ return sendJson(res, 200, {
407
+ event,
408
+ forms: settled,
409
+ skipped
410
+ });
411
+ }
412
+ if (!forms) return sendJson(res, 400, { error: "forms: a list of form names" });
413
+ if (action === "hold") {
414
+ if (typeof body.reason !== "string") return sendJson(res, 400, { error: "reason: why they are held" });
415
+ return sendJson(res, 200, { event: holdForms(project.eventsFile, p, forms, body.reason, by) });
416
+ }
417
+ return sendJson(res, 200, { event: releaseForms(project.eventsFile, p, forms, by) });
418
+ } catch (err) {
419
+ if (err instanceof FormStateError) return sendJson(res, err.status, { error: err.message });
420
+ throw err;
421
+ }
422
+ }
423
+ /** POST /api/handled: { ids, agent? } → { handled, already } */
424
+ async function handledWrite(req, res) {
425
+ const w = await writeOf(req, res);
426
+ if (!w) return;
427
+ const ids = w.body.ids;
428
+ if (!Array.isArray(ids) || !ids.every((i) => typeof i === "string")) return sendJson(res, 400, { error: "ids: a list of event ids" });
429
+ const events = readEvents(project.eventsFile);
430
+ const done = handledIds(events);
431
+ const missing = ids.filter((id) => !events.some((e) => e.id === id));
432
+ if (missing.length) return sendJson(res, 404, { error: `no event ${missing.join(", ")} in the log` });
433
+ const handled = ids.filter((id) => !done.has(id)).map((id) => handle(project.eventsFile, events.find((e) => e.id === id), w.by));
434
+ return sendJson(res, 200, {
435
+ handled,
436
+ already: ids.filter((id) => done.has(id))
437
+ });
438
+ }
439
+ /** POST /api/page: { page, markdown, agent? } → { page, file, url, created }. A page made is its writer's (subscribed). */
440
+ async function pageWrite(req, res) {
441
+ const w = await writeOf(req, res);
442
+ if (!w) return;
443
+ const { page: id, markdown } = w.body;
444
+ if (typeof markdown !== "string") return sendJson(res, 400, { error: "markdown: the page as text" });
445
+ const name = typeof id === "string" ? id.replace(/\.md$/, "").replace(/^\/+|\/+$/g, "") : "";
446
+ const file = name && !name.split("/").some((part) => !part || part === "." || part === ".." || part === "-" || part === "_") ? inside(project.pagesDir, `${name}.md`) : null;
447
+ if (!file) return sendJson(res, 400, { error: "page: a page name like plan or task/plan" });
448
+ const created = !fs.existsSync(file);
449
+ fs.mkdirSync(path.dirname(file), { recursive: true });
450
+ fs.writeFileSync(file, markdown);
451
+ if (created && w.by && !subscriptions(readEvents(project.eventsFile)).some((e) => e.page === name && e.by === w.by)) appendEvent(project.eventsFile, {
452
+ page: name,
453
+ type: SUBSCRIBE
454
+ }, "cli", w.by);
455
+ return sendJson(res, 200, {
456
+ page: name,
457
+ file,
458
+ url: pageUrl(base, name),
459
+ created
460
+ });
461
+ }
462
+ /** How to write pages here, as markdown: the pages' own docs, then each plugin's. */
463
+ async function docs() {
464
+ const { pages, errors } = await config();
465
+ const plugins = await Promise.all((await pluginHooks()).map(async (h) => ({
466
+ name: h.name,
467
+ error: h.error?.message ?? null,
468
+ docs: h.plugin.docs ? await h.plugin.docs() : null,
469
+ blocks: Object.keys(h.plugin.blocks ?? {}),
470
+ menu: Object.values(h.plugin.blocks ?? {}).some((b) => b?.menu),
471
+ routes: describeRoutes(h.table),
472
+ commands: pluginCommands(h.plugin).map((c) => ({
473
+ name: c.name,
474
+ usage: usage(c.command),
475
+ description: c.command.description
476
+ })),
477
+ events: Object.entries(h.plugin.events ?? {}).map(([type, spec]) => ({
478
+ type,
479
+ handOut: !!spec?.handOut,
480
+ description: spec?.description ?? ""
481
+ }))
482
+ })));
483
+ return {
484
+ errors: errors.map((e) => e.message),
485
+ pages: pages?.docs(context()) ?? null,
486
+ plugins
487
+ };
488
+ }
489
+ /**
490
+ * What the browser runs and how it looks, as two stamps: one over its code (the runtime, the page's
491
+ * module, the plugins' scripts), one over its stylesheets (the engine's, the plugins', the
492
+ * project's in .workpad/). A page gets them with its HTML and asks again when its live channel
493
+ * is back: what changed while it was away (a restart, a background tab whose browser held its
494
+ * timers), it would otherwise never hear of. Made from the files themselves, not from what was
495
+ * served since the server started, so a fresh server gives the same stamps for the same files.
496
+ */
497
+ function stamps() {
498
+ const files = [RUNTIME];
499
+ const add = (dir, deep) => {
500
+ let entries;
501
+ try {
502
+ entries = fs.readdirSync(dir, { withFileTypes: true });
503
+ } catch {
504
+ return;
505
+ }
506
+ for (const e of entries) {
507
+ const full = path.join(dir, e.name);
508
+ if (e.isDirectory()) {
509
+ if (deep) add(full, deep);
510
+ } else files.push(full);
511
+ }
512
+ };
513
+ add(path.dirname(PAGE_CLIENT), false);
514
+ for (const dir of publicDirs) add(dir, true);
515
+ for (const f of fs.readdirSync(project.wp).filter((f) => f.endsWith(".css"))) files.push(path.join(project.wp, f));
516
+ const of = (list) => {
517
+ const hash = crypto.createHash("sha1");
518
+ for (const f of [...new Set(list)].toSorted()) try {
519
+ const st = fs.statSync(f);
520
+ hash.update(`${f}\0${st.mtimeMs}\0${st.size}\n`);
521
+ } catch {}
522
+ return hash.digest("hex").slice(0, 16);
523
+ };
524
+ return {
525
+ code: of(files.filter((f) => !f.endsWith(".css"))),
526
+ style: of(files.filter((f) => f.endsWith(".css")))
527
+ };
528
+ }
529
+ const registry = createRegistry();
530
+ /** The agents' names (`workpad agent name`), as the log says now; told to the pages when they change. */
531
+ let names = namesOf(readEvents(project.eventsFile));
532
+ const listenersFor = (page) => registry.list(page).map((l) => l.agent && names.has(l.agent) ? {
533
+ ...l,
534
+ name: names.get(l.agent)
535
+ } : l);
536
+ const channels = /* @__PURE__ */ new Map();
537
+ /** the codes of pings sent and not confirmed yet: the channel each went to */
538
+ const pings = /* @__PURE__ */ new Map();
539
+ const pingCode = () => crypto.randomBytes(3).toString("hex");
540
+ const clients = /* @__PURE__ */ new Set();
541
+ /** what the browser appended lately, by id: a send it retries is answered with what it got */
542
+ const appended = /* @__PURE__ */ new Map();
543
+ function notify(client, kind) {
544
+ client.pending ??= /* @__PURE__ */ new Set();
545
+ if (client.pending.size === 0) setTimeout(() => {
546
+ for (const k of client.pending) client.send(k);
547
+ client.pending.clear();
548
+ }, 60);
549
+ client.pending.add(kind);
550
+ }
551
+ const notifyAll = (kind) => {
552
+ for (const c of clients) notify(c, kind);
553
+ };
554
+ registry.onChange(() => {
555
+ notifyAll("listeners");
556
+ onChange?.();
557
+ });
558
+ function pageChanged(id) {
559
+ onChange?.();
560
+ for (const c of clients) if (c.isDir ? !c.page || id.startsWith(c.page + "/") : c.page === id || c.page + "/index" === id) notify(c, "change");
561
+ for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
562
+ }
563
+ /** A file in the project changed; `f` is its path relative to the project folder, with / separators. */
564
+ function fileChanged(f) {
565
+ if (!f.startsWith(".workpad/") && !FILTER.shows(f)) return;
566
+ if (f.startsWith(".workpad/")) {
567
+ const inner = f.slice(9);
568
+ if (inner === "events.ndjson") {
569
+ onChange?.();
570
+ const now = namesOf(readEvents(project.eventsFile));
571
+ if (JSON.stringify([...now]) !== JSON.stringify([...names])) {
572
+ names = now;
573
+ notifyAll("listeners");
574
+ }
575
+ return notifyAll("events");
576
+ }
577
+ if (inner.startsWith("pages/")) {
578
+ if (inner.endsWith(".md")) pageChanged(inner.slice(6).replace(/\.md$/, ""));
579
+ return;
580
+ }
581
+ if (OWN_FILES.has(inner) || pluginDirs.has(inner.split("/")[0])) return;
582
+ return onSourceChange(path.join(project.dir, f));
583
+ }
584
+ if (!FILES) return;
585
+ pageChanged(`-/${f}`);
586
+ const parent = f.includes("/") ? f.slice(0, f.lastIndexOf("/")) : "";
587
+ pageChanged(`-${parent ? "/" + parent : ""}`);
588
+ }
589
+ let FILES = null;
590
+ let FILTER = fileFilter();
591
+ let projectWatchers = /* @__PURE__ */ new Map();
592
+ function setFiles(files, filter = fileFilter()) {
593
+ if (files === FILES && filter.key === FILTER.key) return;
594
+ FILES = files;
595
+ FILTER = filter;
596
+ for (const w of projectWatchers.values()) {
597
+ w.close();
598
+ watchers.delete(w);
599
+ }
600
+ projectWatchers = /* @__PURE__ */ new Map();
601
+ const add = (key, dir, recursive, prefix) => {
602
+ try {
603
+ const w = fs.watch(dir, { recursive }, (evt, filename) => {
604
+ if (!filename) return;
605
+ const name = filename.toString().replace(/\\/g, "/");
606
+ fileChanged(prefix + name);
607
+ if (!recursive && evt === "rename") {
608
+ const old = projectWatchers.get(name);
609
+ if (old) {
610
+ old.close();
611
+ watchers.delete(old);
612
+ projectWatchers.delete(name);
613
+ }
614
+ watchFolder(name);
615
+ }
616
+ });
617
+ w.on("error", () => {
618
+ w.close();
619
+ watchers.delete(w);
620
+ projectWatchers.delete(key);
621
+ });
622
+ projectWatchers.set(key, w);
623
+ watchers.add(w);
624
+ } catch {}
625
+ };
626
+ const watchFolder = (name) => {
627
+ if (projectWatchers.has(name) || name.includes("/") || name !== ".workpad" && !FILTER.mayHold(name)) return;
628
+ const dir = path.join(project.dir, name);
629
+ let isDir = false;
630
+ try {
631
+ isDir = fs.statSync(dir).isDirectory();
632
+ } catch {}
633
+ if (isDir) add(name, dir, true, name + "/");
634
+ };
635
+ if (!files) return add(".workpad", project.wp, true, ".workpad/");
636
+ add("", project.dir, false, "");
637
+ for (const ent of fs.readdirSync(project.dir, { withFileTypes: true })) if (ent.isDirectory()) watchFolder(ent.name);
638
+ }
639
+ const pageFolders = /* @__PURE__ */ new Map();
640
+ const awaitedIn = /* @__PURE__ */ new Map();
641
+ const isFolder = (dir) => {
642
+ try {
643
+ return fs.statSync(dir).isDirectory();
644
+ } catch {
645
+ return false;
646
+ }
647
+ };
648
+ /** Watch the folder of page `id` (and the folder `id` names, when it is one). */
649
+ function watchPage(id) {
650
+ const target = inside(project.pagesDir, id);
651
+ if (!target) return;
652
+ watchPageFolder(target === project.pagesDir ? target : path.dirname(target));
653
+ if (target !== project.pagesDir && isFolder(target)) watchPageFolder(target);
654
+ }
655
+ function watchPageFolder(folder, made = false) {
656
+ let at = folder;
657
+ while (at !== project.pagesDir && within(at, project.pagesDir) && !isFolder(at)) at = path.dirname(at);
658
+ if (!within(at, project.pagesDir)) return;
659
+ if (at !== folder) {
660
+ if (!awaitedIn.has(at)) awaitedIn.set(at, /* @__PURE__ */ new Set());
661
+ awaitedIn.get(at).add(folder);
662
+ }
663
+ if (pageFolders.has(at)) return;
664
+ const rel = (name) => path.relative(project.dir, path.join(at, name)).split(path.sep).join("/");
665
+ let w;
666
+ try {
667
+ w = fs.watch(at, {}, (_evt, name) => {
668
+ if (name) fileChanged(rel(String(name)));
669
+ if (!isFolder(at)) return drop();
670
+ const awaited = awaitedIn.get(at);
671
+ if (awaited) {
672
+ awaitedIn.delete(at);
673
+ for (const f of awaited) watchPageFolder(f, true);
674
+ }
675
+ });
676
+ } catch {
677
+ return;
678
+ }
679
+ const drop = () => {
680
+ w.close();
681
+ watchers.delete(w);
682
+ if (pageFolders.get(at) === w) pageFolders.delete(at);
683
+ };
684
+ w.on("error", drop);
685
+ pageFolders.set(at, w);
686
+ watchers.add(w);
687
+ if (made) {
688
+ for (const name of fs.readdirSync(at)) if (name.endsWith(".md")) fileChanged(rel(name));
689
+ }
690
+ }
691
+ let reloadTimer;
692
+ async function onSourceChange(file) {
693
+ if (within(file, project.pagesDir)) return;
694
+ if (path.dirname(file) === project.wp && OWN_FILES.has(path.basename(file))) return;
695
+ if ([...pluginDirs].some((name) => within(file, path.join(project.wp, name)))) return;
696
+ if (file.endsWith(".css")) return notifyAll("style");
697
+ if (file.endsWith(".md")) return notifyAll("change");
698
+ if (file === RUNTIME || assets.has(file)) return notifyAll("reload");
699
+ clearTimeout(reloadTimer);
700
+ reloadTimer = setTimeout(() => {
701
+ loader.invalidate();
702
+ config().then(() => notifyAll("change"));
703
+ }, 80);
704
+ }
705
+ const ENGINE_BUILD = path.join(ENGINE_DIR, "dist");
706
+ const ENGINE_WATCHED = !FROM_SOURCE ? [] : [ENGINE_BUILD, ...["plugins"].map((d) => path.join(ENGINE_DIR, d))];
707
+ for (const dir of ENGINE_WATCHED) watch(dir, { recursive: true }, (name) => onSourceChange(path.join(dir, name)));
708
+ function send(res, status, body, type = "text/html; charset=utf-8") {
709
+ res.writeHead(status, {
710
+ "content-type": type,
711
+ "cache-control": "no-store"
712
+ });
713
+ res.end(body);
714
+ }
715
+ const sendJson = (res, status, data) => send(res, status, JSON.stringify(data), "application/json");
716
+ const sendFile = (res, file) => send(res, 200, fs.readFileSync(file), MIME[path.extname(file).toLowerCase()] || "application/octet-stream");
717
+ function readBody(req) {
718
+ return new Promise((resolve, reject) => {
719
+ const chunks = [];
720
+ let size = 0;
721
+ req.on("data", (c) => {
722
+ size += c.length;
723
+ if (size > 1e6) {
724
+ reject(/* @__PURE__ */ new Error("body too large"));
725
+ req.destroy();
726
+ } else chunks.push(c);
727
+ });
728
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
729
+ req.on("error", reject);
730
+ });
731
+ }
732
+ async function resolve(id, requested) {
733
+ await config();
734
+ if (!isRepoId(id) && !id.startsWith("_/")) watchPage(id);
735
+ if (isRepoId(id) && !FILES) return { notFound: "This project does not serve its files: its config sets files: false." };
736
+ if (id === "_/docs") {
737
+ const { pages, plugins } = await docs();
738
+ const source = [pages ?? "", ...plugins.filter((p) => p.docs).map((p) => `<a id="plugin-${p.name}"></a>\n\n${p.docs}`)].join("\n\n---\n\n");
739
+ return { page: {
740
+ kind: "page",
741
+ id,
742
+ file: path.join(project.pagesDir, "_docs.md"),
743
+ mtime: null,
744
+ source,
745
+ body: source,
746
+ frontmatter: {}
747
+ } };
748
+ }
749
+ const found = stored(id);
750
+ if (!found) return { notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? "" : " yet. This page loads as soon as it does"}.` };
751
+ if ("raw" in found) return found;
752
+ if ((found.kind === "folder" || found.kind === "pages" && id) && !requested.endsWith("/")) return { redirect: `${base}/${id}/` };
753
+ if (found.kind === "pages") {
754
+ await withStatus(found.pages);
755
+ if (!found.id && overview) Object.assign(found, await overview());
756
+ }
757
+ return { page: found };
758
+ }
759
+ async function handle$1(req, res) {
760
+ try {
761
+ const url = new URL((req.url ?? "/").replace(/^\/+/, "/"), "http://localhost");
762
+ const p = decodeURIComponent(url.pathname);
763
+ const q = Object.fromEntries(url.searchParams);
764
+ if (p === "/favicon.ico") {
765
+ res.writeHead(204);
766
+ res.end();
767
+ return;
768
+ }
769
+ if (p === "/_/runtime.js") return sendFile(res, RUNTIME);
770
+ if (auth.handle(req, res, p, q)) return;
771
+ if (p.startsWith("/api/")) {
772
+ const hooks = await pluginHooks();
773
+ for (const h of hooks) if (await dispatch(h.table, req, res, url, auth.authorized)) return;
774
+ const owner = hooks.find((h) => p.startsWith(`/api/${h.name}/`) || p === `/api/${h.name}`);
775
+ if (owner) return sendJson(res, 404, { error: `plugin ${owner.name} has no route ${req.method} ${p}` });
776
+ }
777
+ if (p.startsWith("/_/file/")) {
778
+ await config();
779
+ const file = path.resolve(p.slice(7));
780
+ if (!servable(file) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return send(res, 404, "not found", "text/plain");
781
+ asset(file);
782
+ if (TYPESCRIPT.test(file)) try {
783
+ return send(res, 200, typeScriptModule(file), "text/javascript; charset=utf-8");
784
+ } catch (err) {
785
+ return send(res, 200, `throw new SyntaxError(${JSON.stringify(`${path.basename(file)}: ${err.message}`)})`, "text/javascript; charset=utf-8");
786
+ }
787
+ return sendFile(res, file);
788
+ }
789
+ if (p === "/api/health") return sendJson(res, 200, {
790
+ ok: true,
791
+ dir: project.dir,
792
+ pid: process.pid,
793
+ version: VERSION,
794
+ base
795
+ });
796
+ if (p === "/api/events" && req.method === "POST") {
797
+ const body = JSON.parse(await readBody(req));
798
+ if (!body.type) return sendJson(res, 400, { error: "event type required" });
799
+ const again = isEventId(body.id) ? appended.get(body.id) : void 0;
800
+ if (again) return sendJson(res, 200, again);
801
+ const event = appendEvent(project.eventsFile, body);
802
+ appended.set(event.id, event);
803
+ if (appended.size > 1e3) appended.delete(appended.keys().next().value);
804
+ return sendJson(res, 200, event);
805
+ }
806
+ if (p === "/api/scroll" && req.method === "POST") {
807
+ const { page: id, to } = JSON.parse(await readBody(req));
808
+ if (typeof id !== "string" || typeof to !== "string" || !to.trim()) return sendJson(res, 400, { error: "page and to required" });
809
+ appendEvent(project.eventsFile, {
810
+ page: id,
811
+ type: SCROLL,
812
+ data: { to }
813
+ }, "cli");
814
+ let tabs = 0;
815
+ for (const c of clients) if (!c.isDir && (c.page === id || c.page + "/index" === id)) tabs++;
816
+ return sendJson(res, 200, { tabs });
817
+ }
818
+ if (p === "/api/markdown" && req.method === "POST") {
819
+ const { texts } = JSON.parse(await readBody(req));
820
+ if (!Array.isArray(texts)) return sendJson(res, 400, { error: "texts: an array of strings" });
821
+ const { pages } = await config();
822
+ const out = await Promise.all(texts.map((t) => pages ? pages.message(String(t ?? ""), context()) : Promise.resolve({
823
+ html: String(html`${String(t ?? "")}`),
824
+ styles: []
825
+ })));
826
+ return sendJson(res, 200, {
827
+ html: out.map((o) => o.html),
828
+ styles: [...new Set(out.flatMap((o) => o.styles))]
829
+ });
830
+ }
831
+ if (p === "/api/blocks" && req.method === "POST") {
832
+ const { page: id, texts } = JSON.parse(await readBody(req));
833
+ if (typeof id !== "string" || !Array.isArray(texts)) return sendJson(res, 400, { error: "page: a page id; texts: an array of strings" });
834
+ const { pages } = await config();
835
+ if (!pages) return sendJson(res, 200, {
836
+ html: texts.map(() => ""),
837
+ islands: {},
838
+ styles: []
839
+ });
840
+ const file = id.startsWith("-/") ? inside(project.dir, id.slice(2)) : inside(project.pagesDir, `${id}.md`);
841
+ if (!file) return sendJson(res, 400, { error: `no page ${id}` });
842
+ const out = await Promise.all(texts.map((t) => {
843
+ const text = String(t ?? "");
844
+ const prefix = `b${crypto.createHash("sha1").update(text).digest("hex").slice(0, 10)}-`;
845
+ return pages.blocks(text, context(), {
846
+ page: id,
847
+ file,
848
+ prefix
849
+ });
850
+ }));
851
+ return sendJson(res, 200, {
852
+ html: out.map((o) => o.html),
853
+ islands: Object.assign({}, ...out.map((o) => o.islands)),
854
+ styles: [...new Set(out.flatMap((o) => o.styles))]
855
+ });
856
+ }
857
+ if (p === "/api/messages" && req.method === "POST") {
858
+ const { ids } = JSON.parse(await readBody(req));
859
+ if (!Array.isArray(ids)) return sendJson(res, 400, { error: "ids: an array of event ids" });
860
+ const { pages } = await config();
861
+ const events = readEvents(project.eventsFile);
862
+ const out = await Promise.all(ids.map(async (raw) => {
863
+ const e = events.find((x) => x.id === String(raw));
864
+ if (!pages || !e || !isAgentMessage(e)) return null;
865
+ const chat = String(e.data.chat);
866
+ const shown = agentMessagesIn(events, e.page, chat);
867
+ const first = 1 + shown.slice(0, shown.indexOf(e)).reduce((n, x) => n + formsIn(String(x.data.text ?? "")).filter((f) => !f.name).length, 0);
868
+ const file = e.page.startsWith("-/") ? path.join(project.dir, e.page.slice(2)) : path.join(project.pagesDir, `${e.page}.md`);
869
+ return pages.agentMessage(String(e.data.text ?? ""), context(), {
870
+ page: e.page,
871
+ file,
872
+ chat,
873
+ first,
874
+ prefix: `m${e.id}-`
875
+ });
876
+ }));
877
+ return sendJson(res, 200, {
878
+ html: out.map((o) => o?.html ?? ""),
879
+ islands: Object.assign({}, ...out.map((o) => o?.islands ?? {})),
880
+ styles: [...new Set(out.flatMap((o) => o?.styles ?? []))]
881
+ });
882
+ }
883
+ const list = /^\/api\/(\w+)$/.exec(p)?.[1];
884
+ if (req.method === "GET" && list && API_LISTS.includes(list)) return sendJson(res, 200, await readList(list, q));
885
+ if (req.method === "POST" && /^\/api\/forms\/(hold|release|settle)$/.test(p)) return formWrite(p.slice(11), req, res);
886
+ if (p === "/api/handled" && req.method === "POST") return handledWrite(req, res);
887
+ if (p === "/api/page" && req.method === "POST") return pageWrite(req, res);
888
+ if (p === "/api/anchors") {
889
+ const r = await resolve(q.page ?? "", "/");
890
+ if (!("page" in r)) return sendJson(res, 404, { error: "notFound" in r ? r.notFound : "not a page" });
891
+ return sendJson(res, 200, anchorsOf(String((await render(r.page)).out.html)));
892
+ }
893
+ if (p === "/api/stream") {
894
+ res.writeHead(200, {
895
+ "content-type": "text/event-stream",
896
+ "cache-control": "no-store",
897
+ connection: "keep-alive"
898
+ });
899
+ res.write(": streaming\n\n");
900
+ const stop = stream(q, (e) => res.write(`event: event\nid: ${e.id}\ndata: ${JSON.stringify(e)}\n\n`));
901
+ const ping = setInterval(() => res.write(": ping\n\n"), 25e3);
902
+ const end = () => {
903
+ stop();
904
+ clearInterval(ping);
905
+ streams.delete(close);
906
+ };
907
+ const close = () => {
908
+ end();
909
+ res.end();
910
+ };
911
+ streams.add(close);
912
+ req.on("close", end);
913
+ return;
914
+ }
915
+ if (p === "/api/events") {
916
+ const all = after(readEvents(project.eventsFile), q.since);
917
+ const received = receivedIds(all);
918
+ const handled = handledIds(all);
919
+ return sendJson(res, 200, all.filter((e) => matches(e, {
920
+ ...q,
921
+ type: null
922
+ }) && matchesQuery(e, q)).map((e) => ({
923
+ ...e,
924
+ ...received.has(e.id) && { received: true },
925
+ ...handled.has(e.id) && { handled: true }
926
+ })));
927
+ }
928
+ if (p === "/api/docs") return sendJson(res, 200, await docs());
929
+ if (p === "/api/status") return sendJson(res, 200, await status(q.page || null));
930
+ if (p === "/api/listeners") return sendJson(res, 200, listenersFor(q.page ?? null));
931
+ if (p === "/api/stamps") return sendJson(res, 200, stamps());
932
+ if (p === "/api/listen") {
933
+ const remove = registry.add(listenerOf(url.searchParams));
934
+ const stream = holdStream(req, res, () => {
935
+ remove();
936
+ streams.delete(stream.end);
937
+ });
938
+ streams.add(stream.end);
939
+ return;
940
+ }
941
+ if (p === "/api/channels") return sendJson(res, 200, [...channels.values()].map((c) => ({
942
+ session: c.session,
943
+ confirmed: c.confirmed
944
+ })));
945
+ if (p === "/api/channel") {
946
+ const id = q.id;
947
+ if (!id || !q.session) return sendJson(res, 400, { error: "id and session required" });
948
+ const stream = holdStream(req, res, () => {
949
+ if (channels.get(id) === channel) channels.delete(id);
950
+ streams.delete(stream.end);
951
+ });
952
+ const channel = {
953
+ session: q.session,
954
+ confirmed: "confirmed" in q,
955
+ send: stream.send
956
+ };
957
+ channels.set(id, channel);
958
+ streams.add(stream.end);
959
+ return;
960
+ }
961
+ if (p === "/api/ping" && req.method === "POST") {
962
+ const body = JSON.parse(await readBody(req));
963
+ if (typeof body.code === "string") {
964
+ const id = pings.get(body.code);
965
+ const channel = id ? channels.get(id) : void 0;
966
+ if (!channel) return sendJson(res, 404, { error: `no ping with code ${body.code} waits` });
967
+ for (const [code, to] of pings) if (to === id) pings.delete(code);
968
+ channel.confirmed = true;
969
+ channel.send("confirmed", {});
970
+ return sendJson(res, 200, { confirmed: true });
971
+ }
972
+ if (typeof body.session !== "string") return sendJson(res, 400, { error: "session or code required" });
973
+ const theirs = [...channels].filter(([, c]) => c.session === body.session);
974
+ if (theirs.some(([, c]) => c.confirmed)) return sendJson(res, 200, { confirmed: true });
975
+ for (const [id, c] of theirs) {
976
+ const code = pingCode();
977
+ pings.set(code, id);
978
+ c.send("ping", { code });
979
+ }
980
+ return sendJson(res, 200, { sent: theirs.length });
981
+ }
982
+ if (p === "/api/page" || p === "/api/render") {
983
+ const r = await resolve(q.page ?? "", "/");
984
+ if (!("page" in r)) return sendJson(res, 404, { error: "notFound" in r ? r.notFound : "not a page" });
985
+ if (p === "/api/page") return sendJson(res, 200, r.page);
986
+ const { out, notices } = await render(r.page);
987
+ return sendJson(res, 200, {
988
+ ...out,
989
+ notices,
990
+ mtime: r.page.mtime,
991
+ frontmatter: frontmatterOf(r.page)
992
+ });
993
+ }
994
+ if (p === "/api/watch") {
995
+ res.writeHead(200, {
996
+ "content-type": "text/event-stream",
997
+ "cache-control": "no-store",
998
+ connection: "keep-alive"
999
+ });
1000
+ res.write(": connected\n\n");
1001
+ const client = {
1002
+ send: (event, data = {}) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
1003
+ page: q.page || "",
1004
+ isDir: "dir" in q
1005
+ };
1006
+ clients.add(client);
1007
+ client.send("reload");
1008
+ const ping = setInterval(() => res.write(": ping\n\n"), 25e3);
1009
+ const end = () => {
1010
+ clearInterval(ping);
1011
+ clients.delete(client);
1012
+ streams.delete(end);
1013
+ };
1014
+ streams.add(() => {
1015
+ end();
1016
+ res.end();
1017
+ });
1018
+ req.on("close", end);
1019
+ return;
1020
+ }
1021
+ const path_ = p.replace(/^\/+/, "").replace(/\/+$/, "");
1022
+ const id = isRepoId(path_) ? path_ : path_.replace(/\.md$/, "");
1023
+ const r = await resolve(id, p);
1024
+ if ("redirect" in r) {
1025
+ res.writeHead(302, { location: r.redirect + url.search });
1026
+ res.end();
1027
+ return;
1028
+ }
1029
+ if ("raw" in r) return sendFile(res, r.raw);
1030
+ if ("notFound" in r) {
1031
+ const md = `# Not found\n\n${r.notFound.replace(/[\\`*_[\]{}()<>#!:|~&-]/g, "\\$&")}\n`;
1032
+ const missing = {
1033
+ kind: "page",
1034
+ id,
1035
+ file: "",
1036
+ mtime: null,
1037
+ source: md,
1038
+ body: md,
1039
+ frontmatter: {}
1040
+ };
1041
+ return send(res, 404, await page(req, missing, await render(missing)));
1042
+ }
1043
+ return send(res, 200, await page(req, r.page, await render(r.page)));
1044
+ } catch (err) {
1045
+ console.error(err);
1046
+ send(res, 500, String(err?.stack || err), "text/plain");
1047
+ }
1048
+ }
1049
+ /** The live channel: /api/live, a WebSocket from a page of this server's (see ws.ts). */
1050
+ function upgrade(req, conn, _head) {
1051
+ const url = new URL((req.url ?? "/").replace(/^\/+/, "/"), "http://localhost");
1052
+ if (decodeURIComponent(url.pathname) !== "/api/live") return refuse(conn, 404, "Not Found");
1053
+ if (!sameSite(req, origins())) return refuse(conn, 403, "Forbidden");
1054
+ const socket = accept(req, conn);
1055
+ if (!socket) return;
1056
+ const client = {
1057
+ send: (event, data = {}) => socket.send(JSON.stringify({
1058
+ event,
1059
+ data
1060
+ })),
1061
+ page: url.searchParams.get("page") ?? "",
1062
+ isDir: url.searchParams.has("dir")
1063
+ };
1064
+ if (!isRepoId(client.page) && !client.page.startsWith("_/")) watchPage(client.page);
1065
+ clients.add(client);
1066
+ const stop = () => socket.close();
1067
+ streams.add(stop);
1068
+ socket.onClose(() => {
1069
+ clients.delete(client);
1070
+ streams.delete(stop);
1071
+ });
1072
+ }
1073
+ return {
1074
+ handle: handle$1,
1075
+ upgrade,
1076
+ listeners: () => listenersFor(null),
1077
+ async files() {
1078
+ await config();
1079
+ return !!FILES;
1080
+ },
1081
+ touch() {
1082
+ for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
1083
+ },
1084
+ elsewhere: () => notifyAll("elsewhere"),
1085
+ addListener: (l) => registry.add(l),
1086
+ onListeners: (fn) => registry.onChange(fn),
1087
+ status: (page = null) => status(page),
1088
+ read: readList,
1089
+ stream,
1090
+ config,
1091
+ build: (options) => build({
1092
+ project,
1093
+ config,
1094
+ hooks: pluginHooks,
1095
+ files: () => !!FILES
1096
+ }, options),
1097
+ close() {
1098
+ for (const w of watchers) w.close();
1099
+ watchers.clear();
1100
+ for (const stop of [...streams]) stop();
1101
+ clearTimeout(reloadTimer);
1102
+ }
1103
+ };
1104
+ }
1105
+ export { API_LISTS, createServer };