@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,1194 @@
1
+ // src/html.ts
2
+ /** A piece of HTML that is not escaped again. `String(piece)` is its markup. */
3
+ var Html = class {
4
+ value;
5
+ constructor(value) {
6
+ this.value = value;
7
+ }
8
+ toString() {
9
+ return this.value;
10
+ }
11
+ };
12
+ const ESCAPE = {
13
+ "&": "&",
14
+ "<": "&lt;",
15
+ ">": "&gt;",
16
+ "\"": "&quot;",
17
+ "'": "&#39;"
18
+ };
19
+ /** Text → HTML that shows it as text. */
20
+ const escape = (value) => String(value).replace(/[&<>"']/g, (c) => ESCAPE[c]);
21
+ function part(value) {
22
+ if (value == null || value === false) return "";
23
+ if (value instanceof Html) return value.value;
24
+ if (Array.isArray(value)) return value.map(part).join("");
25
+ return escape(value);
26
+ }
27
+ function html(strings, ...values) {
28
+ let out = strings[0];
29
+ for (let i = 0; i < values.length; i++) out += part(values[i]) + strings[i + 1];
30
+ return new Html(out);
31
+ }
32
+ // src/status.ts
33
+ /**
34
+ * Can this be a question's name, the type of its answers? Not with a colon: types with one belong
35
+ * to workpad (`workpad:handled`) or a plugin (`comments:reply`, `chat:message`),
36
+ * named after its owner, so a form's answers never mix with their events.
37
+ */
38
+ const isQuestionName = (name) => !!name && !name.includes(":");
39
+ /** The states, in the order a reader should see them: what waits on them first. */
40
+ const STATES = [
41
+ "open",
42
+ "pending",
43
+ "received",
44
+ "handled",
45
+ "held",
46
+ "settled"
47
+ ];
48
+ /** Does this event of an agent's name `name` among its `forms`? (SETTLE, HOLD, RELEASE) */
49
+ const names = (e, type, name) => e.type === type && !fromReader(e) && Array.isArray(e.data?.forms) && e.data.forms.includes(name);
50
+ /**
51
+ * The hold on question `name` in force, or null: the latest HOLD naming it, unless a RELEASE or a
52
+ * SETTLE came after it. Only the command line's count, as with SETTLE.
53
+ */
54
+ function holdOf(name, events) {
55
+ for (let i = events.length - 1; i >= 0; i--) {
56
+ const e = events[i];
57
+ if (names(e, "workpad:release", name) || names(e, "workpad:settle", name)) return null;
58
+ if (names(e, "workpad:hold", name)) return {
59
+ reason: String(e.data.reason ?? ""),
60
+ since: e.ts,
61
+ by: e.by ?? null
62
+ };
63
+ }
64
+ return null;
65
+ }
66
+ /**
67
+ * The questions of a page with the nested ones settled: a form in a message in the chat under a form
68
+ * (`<form>/<name>`) that is still open once that form is decided (handled) asks nothing any more.
69
+ * The server and the page both go by it, so they never disagree.
70
+ */
71
+ function settleNested(questions) {
72
+ const handled = new Set(questions.filter((q) => q.state === "handled").map((q) => q.name));
73
+ return questions.map((q) => {
74
+ const outer = q.name.includes("/") ? q.name.slice(0, q.name.indexOf("/")) : null;
75
+ return outer && q.state === "open" && handled.has(outer) ? {
76
+ ...q,
77
+ state: "settled"
78
+ } : q;
79
+ });
80
+ }
81
+ /**
82
+ * Was this event written by the reader (a form submit, a comment), not by an agent? Agents write
83
+ * through the command line, which marks its events `from: 'cli'`: an agent's reply, a claim, a mark.
84
+ */
85
+ const fromReader = (event) => event.from !== "cli";
86
+ /**
87
+ * Where the question `name` stands. `events` are the page's, `listeners` the running waits and
88
+ * watches that cover the page (only one asking for it by name counts: it asks again), `marks`
89
+ * what became of each answer. `last` is its latest answer: the reader's latest event of its name.
90
+ * Open, and settled (SETTLE) since that answer or without one: settled.
91
+ */
92
+ function questionState(name, events, listeners, marks) {
93
+ const last = events.findLast((e) => e.type === name && fromReader(e));
94
+ const askedAgain = listeners.some((l) => l.type === name);
95
+ const settled = events.findLastIndex((e) => names(e, SETTLE, name));
96
+ const shut = settled >= 0 && settled > (last ? events.lastIndexOf(last) : -1);
97
+ const state = !last ? "open" : marks.handled(last.id) ? askedAgain ? "open" : "handled" : marks.received(last.id) ? "received" : "pending";
98
+ const hold = holdOf(name, last ? events.slice(events.lastIndexOf(last) + 1) : events);
99
+ return {
100
+ state: state !== "open" ? state : hold ? "held" : shut ? "settled" : "open",
101
+ last,
102
+ hold
103
+ };
104
+ }
105
+ /** The type of the event the page appends once messages were in view: `{ ids }`. */
106
+ const READ = "workpad:read";
107
+ /**
108
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type
109
+ * `isMessage` says is for the reader, not named by a `workpad:read` from the reader, not
110
+ * replaced by a later one (`replaces`), and, given the page's `chats`, not in a chat (`data.chat`)
111
+ * that is no longer among them.
112
+ */
113
+ function unreadMessages(events, isMessage, chats) {
114
+ const read = /* @__PURE__ */ new Set();
115
+ const replaced = /* @__PURE__ */ new Set();
116
+ for (const e of events) {
117
+ if (e.type === "workpad:read" && fromReader(e)) for (const id of e.data?.ids ?? []) read.add(String(id));
118
+ if (e.data?.replaces) replaced.add(String(e.data.replaces));
119
+ }
120
+ const offPage = (e) => !!chats && typeof e.data?.chat === "string" && !chats.has(e.data.chat);
121
+ return events.filter((e) => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e));
122
+ }
123
+ /**
124
+ * The type of the event that settles questions (`workpad settle`): `{ forms: [<name>…] }`. An
125
+ * agent settles those a conclusion reached elsewhere (in a chat, the design moving on) answered:
126
+ * open, they'd stay "unanswered" for good. Only the command line's count, as with RECEIVED.
127
+ */
128
+ const SETTLE = "workpad:settle";
129
+ // src/client/reactive.ts
130
+ function reactive(get) {
131
+ const listeners = /* @__PURE__ */ new Set();
132
+ const value = (() => get());
133
+ value.on = (fn) => {
134
+ listeners.add(fn);
135
+ return () => {
136
+ listeners.delete(fn);
137
+ };
138
+ };
139
+ value.notify = () => {
140
+ const now = get();
141
+ for (const fn of [...listeners]) fn(now);
142
+ };
143
+ return value;
144
+ }
145
+ const base = (() => {
146
+ try {
147
+ return JSON.parse(document.getElementById("wp-page")?.textContent ?? "{}");
148
+ } catch {
149
+ return {};
150
+ }
151
+ })().base ?? "";
152
+ /** A path of the project's server (`/api/events`) as this page requests it. */
153
+ const url = (path) => base + path;
154
+ /** A localStorage key, kept apart from other projects' on the same origin. */
155
+ const storageKey = (key) => base ? `${base}|${key}` : key;
156
+ // src/client/forms.ts
157
+ let root$1;
158
+ let api$1;
159
+ let page$1 = "";
160
+ /** The forms the core looks after: named (a name without a colon: see isQuestionName), without an action. */
161
+ const managed = (form) => isQuestionName(form.getAttribute("name") ?? "") && !form.hasAttribute("action");
162
+ const forms = () => [...root$1.querySelectorAll("form")].filter(managed);
163
+ const keepsOwnFields = (form) => !!form.closest("[data-wp-self]");
164
+ const otherText = (option) => option.closest("label")?.querySelector("[data-wp-other-text]") ?? null;
165
+ const isOther = (el) => el instanceof HTMLInputElement && el.hasAttribute("data-wp-other");
166
+ function readForm(form) {
167
+ const data = {};
168
+ const elements = [...form.elements];
169
+ const boxes = {};
170
+ for (const el of elements) if (el.name && el.type === "checkbox") boxes[el.name] = (boxes[el.name] ?? 0) + 1;
171
+ for (const el of elements) {
172
+ if (!el.name || el.type === "submit" || el.type === "button" || el.type === "reset" || el.type === "file") continue;
173
+ const value = isOther(el) ? otherText(el)?.value.trim() ?? "" : el.value;
174
+ if (el.type === "checkbox") {
175
+ if (boxes[el.name] > 1) {
176
+ const list = data[el.name] ??= [];
177
+ if (el.checked) list.push(value);
178
+ } else data[el.name] = el.checked;
179
+ } else if (el.type === "radio") {
180
+ if (el.checked) data[el.name] = value;
181
+ else data[el.name] ??= null;
182
+ } else if (el instanceof HTMLSelectElement && el.multiple) data[el.name] = [...el.selectedOptions].map((o) => o.value);
183
+ else data[el.name] = el.value;
184
+ }
185
+ return data;
186
+ }
187
+ function writeForm(form, data) {
188
+ const elements = [...form.elements];
189
+ const listed = (name) => elements.filter((e) => e.name === name && !isOther(e) && (e.type === "radio" || e.type === "checkbox")).map((e) => e.value);
190
+ for (const el of elements) {
191
+ if (!el.name || !(el.name in data) || [
192
+ "submit",
193
+ "button",
194
+ "hidden",
195
+ "file"
196
+ ].includes(el.type)) continue;
197
+ const v = data[el.name];
198
+ if (isOther(el)) {
199
+ const own = listed(el.name);
200
+ const rest = (Array.isArray(v) ? v : [v]).filter((x) => typeof x === "string" && x !== "" && !own.includes(x));
201
+ el.checked = rest.length > 0;
202
+ const text = otherText(el);
203
+ if (text && text !== document.activeElement) text.value = rest.join(", ");
204
+ continue;
205
+ }
206
+ if (el.type === "checkbox") el.checked = Array.isArray(v) ? v.includes(el.value) : !!v;
207
+ else if (el.type === "radio") el.checked = v === el.value;
208
+ else el.value = v == null ? "" : String(v);
209
+ }
210
+ }
211
+ /** Typing in an other-option's box picks it (and an empty box, for a checkbox, unpicks it). */
212
+ function onOtherInput(e) {
213
+ const text = e.target;
214
+ if (!text.matches?.("[data-wp-other-text]")) return;
215
+ const option = text.closest("label")?.querySelector("[data-wp-other]");
216
+ if (!option) return;
217
+ if (text.value.trim()) option.checked = true;
218
+ else if (option.type === "checkbox") option.checked = false;
219
+ }
220
+ const draftKey = (form) => storageKey(`wp-draft:${page$1}:${form.getAttribute("name")}`);
221
+ function saveDraft(e) {
222
+ const form = e.target?.closest?.("form");
223
+ if (!form || !managed(form) || !root$1.contains(form) || keepsOwnFields(form)) return;
224
+ try {
225
+ localStorage.setItem(draftKey(form), JSON.stringify(readForm(form)));
226
+ } catch {}
227
+ }
228
+ /** Unsent drafts back into their forms; a form being typed in is left alone. */
229
+ function restoreDrafts() {
230
+ for (const form of forms()) {
231
+ if (keepsOwnFields(form) || form.contains(document.activeElement)) continue;
232
+ let draft = null;
233
+ try {
234
+ draft = JSON.parse(localStorage.getItem(draftKey(form)) ?? "null");
235
+ } catch {}
236
+ if (draft) writeForm(form, draft);
237
+ }
238
+ }
239
+ const dropDraft = (form) => {
240
+ try {
241
+ localStorage.removeItem(draftKey(form));
242
+ } catch {}
243
+ };
244
+ /** Each form's last answer: its button in data-wp-sent, and with `prefill` its fields. */
245
+ function restoreLast(prefill) {
246
+ for (const form of forms()) {
247
+ const last = api$1.last(form.getAttribute("name"));
248
+ if (!last) continue;
249
+ form.dataset.wpSent = last.action ?? "";
250
+ if (prefill && !keepsOwnFields(form)) writeForm(form, last.data);
251
+ }
252
+ }
253
+ /** What each form is sending now, as sent: the same answer again is not sent twice. */
254
+ const inFlight = /* @__PURE__ */ new WeakMap();
255
+ /** A button's own label, while it says how a send goes. */
256
+ const labelOf = (button) => {
257
+ const el = document.createElement("div");
258
+ el.innerHTML = labels.get(button).html;
259
+ return el.textContent?.trim() ?? "";
260
+ };
261
+ const SEND_TEXT = {
262
+ sending: "Sending…",
263
+ sent: "✓ Sent",
264
+ failed: "Try again"
265
+ };
266
+ const labels = /* @__PURE__ */ new WeakMap();
267
+ function sendState(button, state) {
268
+ if (!button) return;
269
+ let saved = labels.get(button);
270
+ clearTimeout(saved?.timer);
271
+ if (!state) {
272
+ if (!saved) return;
273
+ button.innerHTML = saved.html;
274
+ button.style.minWidth = "";
275
+ delete button.dataset.wpSend;
276
+ labels.delete(button);
277
+ return;
278
+ }
279
+ if (!saved) {
280
+ saved = { html: button.innerHTML };
281
+ labels.set(button, saved);
282
+ button.style.minWidth = `${button.getBoundingClientRect().width}px`;
283
+ }
284
+ button.dataset.wpSend = state;
285
+ button.textContent = SEND_TEXT[state];
286
+ if (state === "sent") saved.timer = setTimeout(() => sendState(button, null), 2e3);
287
+ }
288
+ async function onSubmit(e) {
289
+ const form = e.target;
290
+ if (!managed(form) || !root$1.contains(form)) return;
291
+ e.preventDefault();
292
+ const button = e.submitter;
293
+ const label = button ? labels.get(button) ? labelOf(button) : button.textContent?.trim() : null;
294
+ const action = button ? button.value || label || null : null;
295
+ const data = readForm(form);
296
+ const sent = JSON.stringify([action, data]);
297
+ if (inFlight.get(form) === sent) return;
298
+ inFlight.set(form, sent);
299
+ const before = form.dataset.wpSent;
300
+ form.dataset.wpState = "sending";
301
+ form.dataset.wpSent = action ?? "";
302
+ form.removeAttribute("data-wp-just-sent");
303
+ sendState(button, "sending");
304
+ showStatus(form);
305
+ try {
306
+ await api$1.append(form.getAttribute("name"), data, action);
307
+ if (inFlight.get(form) !== sent) return;
308
+ dropDraft(form);
309
+ form.dataset.wpState = "sent";
310
+ sendState(button, "sent");
311
+ form.toggleAttribute("data-wp-just-sent", true);
312
+ clearTimeout(justSent.get(form));
313
+ justSent.set(form, setTimeout(() => {
314
+ form.removeAttribute("data-wp-just-sent");
315
+ showStatus(form);
316
+ }, 3e3));
317
+ showStatus(form);
318
+ } catch (err) {
319
+ if (inFlight.get(form) !== sent) return;
320
+ form.dataset.wpState = "failed";
321
+ sendState(button, "failed");
322
+ if (before == null) delete form.dataset.wpSent;
323
+ else form.dataset.wpSent = before;
324
+ showStatus(form);
325
+ console.error(err);
326
+ } finally {
327
+ if (inFlight.get(form) === sent) inFlight.delete(form);
328
+ }
329
+ }
330
+ const sendButtons = (form) => [...form.querySelectorAll("button, input[type=submit]")].filter((b) => (b instanceof HTMLInputElement || b.type !== "button" && b.type !== "reset") && b.form === form);
331
+ function showStatus(form) {
332
+ const text = form.dataset.wpState === "failed" ? ["couldn't send it", "bad"] : form.dataset.wpState === "sending" ? null : form.hasAttribute("data-wp-pending") ? ["waiting for an agent to receive it", null] : form.hasAttribute("data-wp-received") ? ["the agent has it", null] : null;
333
+ let el = form.querySelector(".wp-form-status");
334
+ const last = sendButtons(form).at(-1);
335
+ if (!text || !last) return void el?.remove();
336
+ if (!el) el = Object.assign(document.createElement("span"), { className: "wp-form-status" });
337
+ el.setAttribute("role", "status");
338
+ if (el.previousElementSibling !== last) last.after(el);
339
+ el.textContent = text[0];
340
+ if (text[1]) el.dataset.kind = text[1];
341
+ else delete el.dataset.kind;
342
+ }
343
+ const ATTR = {
344
+ open: "data-wp-open",
345
+ pending: "data-wp-pending",
346
+ received: "data-wp-received",
347
+ handled: "data-wp-handled",
348
+ held: "data-wp-held",
349
+ settled: "data-wp-settled"
350
+ };
351
+ /**
352
+ * A held form says why at its top, under its title: "⏸ on hold: waits for !2145". The line is the
353
+ * page's, put back after each update; it goes once the form is released.
354
+ */
355
+ function showHold(form, reason) {
356
+ let el = form.querySelector(":scope > .wp-form-held");
357
+ if (reason == null) return void el?.remove();
358
+ if (!el) {
359
+ el = Object.assign(document.createElement("p"), { className: "wp-form-held" });
360
+ el.setAttribute("role", "note");
361
+ const title = form.querySelector(":scope > .wp-form-title");
362
+ if (title) title.after(el);
363
+ else form.prepend(el);
364
+ }
365
+ el.textContent = reason ? `⏸ on hold: ${reason}` : "⏸ on hold";
366
+ }
367
+ /** One line quoting an answer: what was chosen, then what was written. */
368
+ /**
369
+ * An answer, told apart: the button it was sent with (none for a plain Send), what was chosen
370
+ * (options, short values), and what was written.
371
+ */
372
+ function answerParts(data, action) {
373
+ const chosen = [], written = [];
374
+ for (const [k, v] of Object.entries(data)) {
375
+ if (k.includes(":") || v == null || v === "" || v === false) continue;
376
+ if (Array.isArray(v)) {
377
+ if (v.length) chosen.push(v.join(", "));
378
+ } else if (v === true) continue;
379
+ else if (String(v).length > 60 || String(v).includes("\n")) written.push(String(v));
380
+ else chosen.push(String(v));
381
+ }
382
+ return {
383
+ action: action && !["Send", "Submit"].includes(action) ? action : null,
384
+ chosen,
385
+ written
386
+ };
387
+ }
388
+ /** One line quoting an answer: what was chosen, then what was written. */
389
+ function outcome(data, action) {
390
+ const { action: button, chosen, written } = answerParts(data, action);
391
+ return [[button, ...chosen].filter(Boolean).join(" · ") || "sent", ...written.map((w) => `“${w.length > 240 ? w.slice(0, 240) + "…" : w}”`)].join("\n");
392
+ }
393
+ let current = [];
394
+ const justSent = /* @__PURE__ */ new WeakMap();
395
+ /** Mark every form from the log and the listeners, then tell whoever follows. */
396
+ function mark() {
397
+ const listening = api$1.listeners();
398
+ const found = forms().map((form) => {
399
+ const name = form.getAttribute("name");
400
+ return {
401
+ form,
402
+ name,
403
+ ...questionState(name, api$1.events(), listening, api$1.marks)
404
+ };
405
+ });
406
+ const holds = new Map(found.map((f) => [f.form, f.hold]));
407
+ current = settleNested(found).map(({ form, name, state, last }) => {
408
+ for (const st of STATES) form.toggleAttribute(ATTR[st], st === state);
409
+ const hold = state === "held" ? holds.get(form) ?? null : null;
410
+ if (hold) form.setAttribute(ATTR.held, hold.reason);
411
+ showHold(form, hold ? hold.reason : null);
412
+ if (state === "received" || state === "handled") form.dataset.wpOutcome = outcome(last.data, last.action);
413
+ else delete form.dataset.wpOutcome;
414
+ showStatus(form);
415
+ return {
416
+ form,
417
+ name,
418
+ state,
419
+ last,
420
+ hold
421
+ };
422
+ });
423
+ forms_.notify();
424
+ }
425
+ /** After the page re-rendered: answers, drafts and marks back on its forms. */
426
+ function refresh() {
427
+ restoreLast(false);
428
+ restoreDrafts();
429
+ mark();
430
+ }
431
+ /** Look after the page's named forms; called once the page has mounted. */
432
+ function trackForms(el, pageId, core) {
433
+ root$1 = el;
434
+ page$1 = pageId;
435
+ api$1 = core;
436
+ document.addEventListener("input", onOtherInput);
437
+ document.addEventListener("input", saveDraft);
438
+ document.addEventListener("change", saveDraft);
439
+ document.addEventListener("submit", onSubmit, { capture: true });
440
+ api$1.onRendered(refresh);
441
+ api$1.listeners.on(mark);
442
+ api$1.events.on(() => {
443
+ restoreLast(false);
444
+ mark();
445
+ });
446
+ restoreLast(true);
447
+ restoreDrafts();
448
+ mark();
449
+ let known = new Set(forms());
450
+ new MutationObserver(() => {
451
+ const now = forms();
452
+ const fresh = now.filter((f) => !known.has(f));
453
+ known = new Set(now);
454
+ if (!fresh.length) return;
455
+ for (const form of fresh) {
456
+ const last = api$1.last(form.getAttribute("name"));
457
+ if (!last) continue;
458
+ form.dataset.wpSent = last.action ?? "";
459
+ if (!keepsOwnFields(form)) writeForm(form, last.data);
460
+ }
461
+ restoreDrafts();
462
+ mark();
463
+ }).observe(root$1, {
464
+ childList: true,
465
+ subtree: true
466
+ });
467
+ }
468
+ /** For the api: every named form and where it stands, as it changes. */
469
+ const forms_ = reactive(() => current);
470
+ const formsApi = { forms: forms_ };
471
+ // src/client/toast.ts
472
+ let box = null;
473
+ function place(corner) {
474
+ if (box?.isConnected) return box;
475
+ box = document.createElement("div");
476
+ box.className = "wp-toasts";
477
+ box.setAttribute("role", "status");
478
+ box.setAttribute("aria-live", "polite");
479
+ corner.append(box);
480
+ return box;
481
+ }
482
+ function createToast(corner) {
483
+ return function toast(text, { kind = "info", ms = 7e3, onClick, onDismiss, name, order = 0, details } = {}) {
484
+ const el = document.createElement("button");
485
+ let timer;
486
+ const close = () => {
487
+ clearTimeout(timer);
488
+ el.remove();
489
+ };
490
+ el.type = "button";
491
+ el.className = "wp-toast";
492
+ el.dataset.kind = kind;
493
+ if (name) el.dataset.toast = name;
494
+ el.style.order = String(order);
495
+ const label = document.createElement("span");
496
+ label.className = "wp-toast-text";
497
+ label.textContent = text;
498
+ el.append(label);
499
+ let more = null;
500
+ let detail = null;
501
+ if (details) {
502
+ more = document.createElement("span");
503
+ more.className = "wp-toast-more";
504
+ detail = document.createElement("span");
505
+ detail.className = "wp-toast-details";
506
+ detail.textContent = details;
507
+ el.setAttribute("aria-description", details);
508
+ el.append(more, detail);
509
+ fold(false);
510
+ }
511
+ function fold(open) {
512
+ el.toggleAttribute("data-open", open);
513
+ detail.hidden = !open;
514
+ more.textContent = open ? "▾" : "▸";
515
+ more.title = open ? "Less" : "More";
516
+ clearTimeout(timer);
517
+ if (!open && ms) timer = setTimeout(close, ms);
518
+ }
519
+ if (onDismiss) {
520
+ const x = document.createElement("span");
521
+ x.className = "wp-toast-dismiss";
522
+ x.textContent = "✕";
523
+ x.title = x.ariaLabel = "Dismiss";
524
+ el.append(x);
525
+ }
526
+ el.addEventListener("click", (e) => {
527
+ const target = e.target;
528
+ if (onDismiss && target.closest(".wp-toast-dismiss")) {
529
+ close();
530
+ onDismiss();
531
+ return;
532
+ }
533
+ if (details && target.closest(".wp-toast-more, .wp-toast-details")) return fold(!el.hasAttribute("data-open"));
534
+ if (ms) close();
535
+ onClick?.();
536
+ });
537
+ if (ms && !details) timer = setTimeout(close, ms);
538
+ place(corner()).append(el);
539
+ return {
540
+ close,
541
+ update: (next) => {
542
+ label.textContent = next;
543
+ },
544
+ hide: () => {
545
+ el.hidden = true;
546
+ },
547
+ show: () => {
548
+ if (!el.isConnected) place(corner()).append(el);
549
+ el.hidden = false;
550
+ }
551
+ };
552
+ };
553
+ }
554
+ // src/client/read.ts
555
+ let isMessage = () => false;
556
+ let getEvents = () => [];
557
+ let send = () => {};
558
+ let chats = () => null;
559
+ const sending$1 = /* @__PURE__ */ new Set();
560
+ const unread$1 = () => unreadMessages(getEvents(), isMessage, chats()).filter((e) => !sending$1.has(e.id));
561
+ /**
562
+ * The chats the page's content shows, by name: the one under every form and each chat block; null
563
+ * while there is no page content (a folder, raw text), when every chat's messages count.
564
+ */
565
+ function chatsShown() {
566
+ const main = document.getElementById("wp-main");
567
+ if (!main) return null;
568
+ return new Set([...[...main.querySelectorAll("form[name]")].map((f) => f.getAttribute("name")), ...[...main.querySelectorAll("[data-chat]")].map((c) => c.getAttribute("data-chat"))].filter((name) => !!name));
569
+ }
570
+ const queued = /* @__PURE__ */ new Set();
571
+ let timer = 0;
572
+ function markRead(ids) {
573
+ const open = new Set(unread$1().map((e) => e.id));
574
+ const fresh = ids.filter((id) => open.has(id));
575
+ if (!fresh.length) return;
576
+ for (const id of fresh) {
577
+ sending$1.add(id);
578
+ queued.add(id);
579
+ }
580
+ clearTimeout(timer);
581
+ timer = window.setTimeout(() => {
582
+ const batch = [...queued];
583
+ queued.clear();
584
+ if (batch.length) send(batch);
585
+ }, 300);
586
+ }
587
+ /** Once the log has the reads, they need no holding. */
588
+ function readsArrived(events) {
589
+ for (const e of events) if (e.type === "workpad:read") for (const id of e.data?.ids ?? []) sending$1.delete(String(id));
590
+ }
591
+ const MOSTLY = .6;
592
+ function mostlyInView(entry) {
593
+ if (!entry.isIntersecting) return false;
594
+ if (entry.intersectionRatio >= MOSTLY) return true;
595
+ const viewport = entry.rootBounds?.height ?? window.innerHeight;
596
+ return entry.intersectionRect.height >= MOSTLY * viewport;
597
+ }
598
+ const inView = /* @__PURE__ */ new Set();
599
+ const seen = new IntersectionObserver((entries) => {
600
+ for (const entry of entries) {
601
+ const id = entry.target.dataset.wpMessage;
602
+ if (mostlyInView(entry)) inView.add(id);
603
+ else inView.delete(id);
604
+ }
605
+ readVisible();
606
+ }, { threshold: Array.from({ length: 21 }, (_, i) => i / 20) });
607
+ function readVisible() {
608
+ if (document.visibilityState === "visible" && inView.size) markRead([...inView]);
609
+ }
610
+ const observed = /* @__PURE__ */ new WeakSet();
611
+ function observeMessages() {
612
+ const open = new Set(unread$1().map((e) => e.id));
613
+ for (const el of document.querySelectorAll("[data-wp-message]")) {
614
+ if (observed.has(el) || !open.has(el.dataset.wpMessage)) continue;
615
+ observed.add(el);
616
+ seen.observe(el);
617
+ }
618
+ }
619
+ function trackReading(options) {
620
+ const types = new Set(options.messages);
621
+ isMessage = (type) => types.has(type);
622
+ getEvents = options.events;
623
+ send = options.send;
624
+ chats = chatsShown;
625
+ new MutationObserver(observeMessages).observe(document.body, {
626
+ childList: true,
627
+ subtree: true
628
+ });
629
+ document.addEventListener("visibilitychange", readVisible);
630
+ observeMessages();
631
+ }
632
+ /** After the events changed: messages that came since may already be on screen. */
633
+ const messagesChanged = () => observeMessages();
634
+ // src/client/markdown.ts
635
+ const cache = /* @__PURE__ */ new Map();
636
+ let queue = [];
637
+ async function flush() {
638
+ const batch = queue;
639
+ queue = [];
640
+ try {
641
+ const res = await fetch(url("/api/markdown"), {
642
+ method: "POST",
643
+ headers: { "content-type": "application/json" },
644
+ body: JSON.stringify({ texts: batch.map((b) => b.text) })
645
+ });
646
+ if (!res.ok) throw new Error(await res.text());
647
+ const { html, styles } = await res.json();
648
+ linkStyles(styles);
649
+ batch.forEach((b, i) => b.resolve(html[i] ?? ""));
650
+ } catch (err) {
651
+ for (const b of batch) {
652
+ cache.delete(b.text);
653
+ b.reject(err);
654
+ }
655
+ }
656
+ }
657
+ function markdown(text) {
658
+ let got = cache.get(text);
659
+ if (!got) {
660
+ got = new Promise((resolve, reject) => {
661
+ if (!queue.length) queueMicrotask(flush);
662
+ queue.push({
663
+ text,
664
+ resolve,
665
+ reject
666
+ });
667
+ });
668
+ cache.set(text, got);
669
+ }
670
+ return got;
671
+ }
672
+ const messages = /* @__PURE__ */ new Map();
673
+ let pending = [];
674
+ function linkStyles(styles) {
675
+ for (const href of styles) if (![...document.querySelectorAll("link[rel=stylesheet]")].some((l) => new URL(l.href).pathname === new URL(href, location.href).pathname)) document.head.insertAdjacentHTML("beforeend", `<link rel="stylesheet" href="${href.replace(/"/g, "&quot;")}">`);
676
+ }
677
+ async function flushMessages() {
678
+ const batch = pending;
679
+ pending = [];
680
+ try {
681
+ const res = await fetch(url("/api/messages"), {
682
+ method: "POST",
683
+ headers: { "content-type": "application/json" },
684
+ body: JSON.stringify({ ids: batch.map((b) => b.id) })
685
+ });
686
+ if (!res.ok) throw new Error(await res.text());
687
+ const { html, islands, styles } = await res.json();
688
+ linkStyles(styles);
689
+ document.dispatchEvent(new CustomEvent("wp-islands", { detail: islands }));
690
+ batch.forEach((b, i) => b.resolve(html[i] ?? ""));
691
+ } catch (err) {
692
+ for (const b of batch) {
693
+ messages.delete(b.key);
694
+ b.reject(err);
695
+ }
696
+ }
697
+ }
698
+ /** An agent's chat message as HTML, rendered by the server as a small page (Api.message). */
699
+ function message(event) {
700
+ const key = `${event.id}\0${String(event.data.text ?? "")}`;
701
+ let got = messages.get(key);
702
+ if (!got) {
703
+ got = new Promise((resolve, reject) => {
704
+ if (!pending.length) queueMicrotask(flushMessages);
705
+ pending.push({
706
+ id: event.id,
707
+ resolve,
708
+ reject,
709
+ key
710
+ });
711
+ });
712
+ messages.set(key, got);
713
+ }
714
+ return got;
715
+ }
716
+ const rendered = /* @__PURE__ */ new Map();
717
+ let asked = [];
718
+ async function flushBlocks(page) {
719
+ const batch = asked;
720
+ asked = [];
721
+ try {
722
+ const res = await fetch(url("/api/blocks"), {
723
+ method: "POST",
724
+ headers: { "content-type": "application/json" },
725
+ body: JSON.stringify({
726
+ page,
727
+ texts: batch.map((b) => b.text)
728
+ })
729
+ });
730
+ if (!res.ok) throw new Error(await res.text());
731
+ const { html, islands, styles } = await res.json();
732
+ linkStyles(styles);
733
+ document.dispatchEvent(new CustomEvent("wp-islands", { detail: islands }));
734
+ batch.forEach((b, i) => b.resolve(html[i] ?? ""));
735
+ } catch (err) {
736
+ for (const b of batch) {
737
+ rendered.delete(b.text);
738
+ b.reject(err);
739
+ }
740
+ }
741
+ }
742
+ /** Markdown with every block, as on page `page`, as HTML (Api.blocks). */
743
+ function blocks(page, text) {
744
+ let got = rendered.get(text);
745
+ if (!got) {
746
+ got = new Promise((resolve, reject) => {
747
+ if (!asked.length) queueMicrotask(() => flushBlocks(page));
748
+ asked.push({
749
+ text,
750
+ resolve,
751
+ reject
752
+ });
753
+ });
754
+ rendered.set(text, got);
755
+ }
756
+ return got;
757
+ }
758
+ // src/client/scroll.ts
759
+ const norm = (s) => s.replace(/\s+/g, " ").trim().toLowerCase();
760
+ function findTarget(root, where) {
761
+ const exact = document.getElementById(where.trim());
762
+ if (exact && root.contains(exact)) return exact;
763
+ const want = norm(where);
764
+ const headings = [...root.querySelectorAll("h1, h2, h3, h4, h5, h6, summary")];
765
+ const heading = headings.find((h) => norm(h.textContent ?? "") === want) ?? headings.find((h) => norm(h.textContent ?? "").includes(want));
766
+ if (heading) return heading;
767
+ const byName = [...root.querySelectorAll("form[name]")].find((f) => f.getAttribute("name") === where.trim());
768
+ if (byName) return byName;
769
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
770
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) if (norm(n.textContent ?? "").includes(want) && n.parentElement && !n.parentElement.closest("script, style")) return n.parentElement;
771
+ return null;
772
+ }
773
+ /** How long a link's target is waited for when the page doesn't have it yet (a chat's messages, drawn after it). */
774
+ const LATE = 3e3;
775
+ /** Go to the element the location's hash names (src/anchors.ts), now or once it is drawn. */
776
+ function scrollToAnchor(root) {
777
+ let id;
778
+ try {
779
+ id = decodeURIComponent(location.hash.slice(1));
780
+ } catch {
781
+ return;
782
+ }
783
+ if (!id.trim() || id.startsWith("wp-")) return;
784
+ const find = () => {
785
+ const el = document.getElementById(id);
786
+ return el && root.contains(el) ? el : null;
787
+ };
788
+ if (goTo(find())) return;
789
+ const seen = new MutationObserver(() => {
790
+ if (goTo(find())) seen.disconnect();
791
+ });
792
+ seen.observe(root, {
793
+ childList: true,
794
+ subtree: true
795
+ });
796
+ setTimeout(() => seen.disconnect(), LATE);
797
+ }
798
+ function scrollToTarget(root, where) {
799
+ return goTo(findTarget(root, where));
800
+ }
801
+ function goTo(target) {
802
+ if (!target) return false;
803
+ target.dispatchEvent(new CustomEvent("wp-reveal", { bubbles: true }));
804
+ for (let d = (target.tagName === "SUMMARY" ? target.parentElement?.parentElement : target)?.closest("details"); d; d = d.parentElement?.closest("details")) d.open = true;
805
+ requestAnimationFrame(() => {
806
+ let offset = (document.querySelector(".wp-nav")?.getBoundingClientRect().height ?? 0) + 12;
807
+ for (let d = target.parentElement?.closest("details"); d; d = d.parentElement?.closest("details")) {
808
+ const summary = d.querySelector(":scope > summary");
809
+ if (summary && summary !== target) offset += summary.getBoundingClientRect().height;
810
+ }
811
+ scrollTo({
812
+ top: Math.max(0, scrollY + target.getBoundingClientRect().top - offset),
813
+ behavior: "smooth"
814
+ });
815
+ target.classList.remove("wp-flash");
816
+ target.offsetWidth;
817
+ target.classList.add("wp-flash");
818
+ setTimeout(() => target.classList.remove("wp-flash"), 2e3);
819
+ });
820
+ return true;
821
+ }
822
+ // src/client/runtime.ts
823
+ const handoff = JSON.parse(document.getElementById("wp-page").textContent);
824
+ const root = document.getElementById("wp-root");
825
+ const page = handoff.id;
826
+ const isDir = handoff.kind === "pages" || handoff.kind === "folder";
827
+ const live = handoff.live !== false;
828
+ const moduleUrl = (path) => new URL(path, document.baseURI).href;
829
+ let events = [];
830
+ const eventsValue = reactive(() => events);
831
+ const unread = reactive(unread$1);
832
+ function setEvents(next) {
833
+ events = next;
834
+ readsArrived(events);
835
+ eventsValue.notify();
836
+ unread.notify();
837
+ messagesChanged();
838
+ }
839
+ async function loadEvents() {
840
+ if (!live) return;
841
+ const all = (await (await fetch(url(`/api/events?page=${encodeURIComponent(page)}`))).json()).filter((e) => e.page === page);
842
+ const known = new Set(all.map((e) => e.id));
843
+ for (const [id, e] of sending) if (known.has(id)) sending.delete(id);
844
+ setEvents([...all, ...[...sending.values()]]);
845
+ scrollFromLog();
846
+ }
847
+ let scrolledTo;
848
+ function scrollFromLog() {
849
+ const last = events.findLast((e) => e.type === "workpad:scroll" && !fromReader(e));
850
+ if (scrolledTo === void 0) return void (scrolledTo = last?.id ?? null);
851
+ if (!last || last.id === scrolledTo) return;
852
+ scrolledTo = last.id;
853
+ const to = String(last.data?.to ?? "");
854
+ if (!scrollToTarget(root, to)) console.warn(`workpad scroll: nothing on the page matches ${JSON.stringify(to)}`);
855
+ }
856
+ /** How long one send may take before it is tried again, in ms; and how many tries in all. */
857
+ const SEND_TIMEOUT = 8e3;
858
+ const TRIES = 4;
859
+ /** Events appended here that the server hasn't confirmed: kept in the events when they are loaded. */
860
+ const sending = /* @__PURE__ */ new Map();
861
+ /** An id as the server makes them (isEventId): the time in base 36, a dash, random hex. */
862
+ const newId = () => `${Date.now().toString(36)}-${[...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6))].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
863
+ async function append(type, data = {}, action = null) {
864
+ if (!live) throw new Error("a built page is a file: there is no log to append to");
865
+ const id = newId();
866
+ const shown = {
867
+ id,
868
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
869
+ page,
870
+ type,
871
+ action,
872
+ data,
873
+ sending: true
874
+ };
875
+ sending.set(id, shown);
876
+ setEvents([...events, shown]);
877
+ const body = JSON.stringify({
878
+ id,
879
+ page,
880
+ type,
881
+ action,
882
+ data
883
+ });
884
+ let failure;
885
+ for (let attempt = 0; attempt < TRIES; attempt++) {
886
+ if (attempt) await new Promise((r) => setTimeout(r, 500 * 2 ** attempt));
887
+ try {
888
+ const res = await fetch(url("/api/events"), {
889
+ method: "POST",
890
+ headers: { "content-type": "application/json" },
891
+ body,
892
+ signal: AbortSignal.timeout(SEND_TIMEOUT)
893
+ });
894
+ if (res.status >= 400 && res.status < 500) {
895
+ failure = new Error(await res.text());
896
+ break;
897
+ }
898
+ if (!res.ok) throw new Error(await res.text());
899
+ const saved = await res.json();
900
+ sending.delete(id);
901
+ setEvents([...events.filter((e) => e.id !== id && e.id !== saved.id), saved].toSorted(byTime));
902
+ return saved;
903
+ } catch (err) {
904
+ failure = err;
905
+ }
906
+ }
907
+ const arrived = !sending.has(id) && events.find((e) => e.id === id && !e.sending);
908
+ if (arrived) return arrived;
909
+ sending.delete(id);
910
+ setEvents(events.filter((e) => e.id !== id));
911
+ throw failure;
912
+ }
913
+ const byTime = (a, b) => a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0;
914
+ let listeners = [];
915
+ const listenersValue = reactive(() => listeners);
916
+ async function loadListeners() {
917
+ if (!live) return;
918
+ listeners = await (await fetch(url(`/api/listeners?page=${encodeURIComponent(page)}`))).json();
919
+ listenersValue.notify();
920
+ }
921
+ const renderedListeners = /* @__PURE__ */ new Set();
922
+ const corner = document.getElementById("wp-dock") ?? document.body.appendChild(Object.assign(document.createElement("div"), { id: "wp-dock" }));
923
+ let baseTitle = document.title;
924
+ const badges = /* @__PURE__ */ new Map();
925
+ let badgeCount = 0;
926
+ function writeTitle() {
927
+ const list = [...badges.values()].toSorted((a, b) => a.order - b.order || a.since - b.since);
928
+ document.title = `${list.map((b) => `(${b.text}) `).join("")}${baseTitle}`;
929
+ }
930
+ /** The plugins in their order, which is the order of their elements in a slot. */
931
+ const pluginOrder = (handoff.plugins ?? []).map((p) => p.name);
932
+ /**
933
+ * Mount `owner`'s element in a slot (Api.slot): the one the server rendered with its markup, or a
934
+ * new one, put among the others in plugin order. What `mount` returns runs when it is taken away.
935
+ */
936
+ function slotFor(owner, name, mount) {
937
+ const holder = name === "corner" ? corner : name === "header" ? root.querySelector("[data-wp-slot=header]") : document.querySelector(`body > [data-wp-slot=${name}]`);
938
+ if (!holder) return () => {};
939
+ let el = [...holder.children].find((c) => c instanceof HTMLElement && c.dataset.plugin === owner);
940
+ if (!el) {
941
+ el = document.createElement("div");
942
+ el.dataset.plugin = owner;
943
+ const at = pluginOrder.indexOf(owner);
944
+ const next = [...holder.children].find((c) => c instanceof HTMLElement && c.dataset.plugin != null && pluginOrder.indexOf(c.dataset.plugin) > at);
945
+ holder.insertBefore(el, next ?? null);
946
+ }
947
+ const unmount = mount(el);
948
+ let gone = false;
949
+ return () => {
950
+ if (gone) return;
951
+ gone = true;
952
+ unmount?.();
953
+ el.remove();
954
+ };
955
+ }
956
+ /** The page's own element in the corner (its toasts), made the first time it is asked for. */
957
+ let pageCorner = null;
958
+ const cornerOfPage = () => {
959
+ if (!pageCorner) slotFor("", "corner", (el) => void (pageCorner = el));
960
+ return pageCorner ?? corner;
961
+ };
962
+ const api = {
963
+ page,
964
+ url,
965
+ events: eventsValue,
966
+ last: (type) => events.findLast((e) => e.type === type),
967
+ marks: {
968
+ received: (id) => !!events.find((e) => e.id === id)?.received,
969
+ handled: (id) => !!events.find((e) => e.id === id)?.handled
970
+ },
971
+ unread,
972
+ markRead: (ids) => {
973
+ markRead(ids);
974
+ unread.notify();
975
+ },
976
+ markdown,
977
+ message,
978
+ blocks: (text) => blocks(page, text),
979
+ append,
980
+ listeners: listenersValue,
981
+ rendered() {
982
+ const frontmatterChanged = JSON.stringify(nextFrontmatter) !== JSON.stringify(frontmatter);
983
+ data = nextData;
984
+ frontmatter = nextFrontmatter;
985
+ unread.notify();
986
+ for (const fn of renderedListeners) fn();
987
+ dataValue.notify();
988
+ if (frontmatterChanged) frontmatterValue.notify();
989
+ },
990
+ onRendered(fn) {
991
+ renderedListeners.add(fn);
992
+ return () => renderedListeners.delete(fn);
993
+ },
994
+ slot: (name, mount) => slotFor("", name, mount),
995
+ badge(key, text, order = 0) {
996
+ if (text == null) badges.delete(key);
997
+ else badges.set(key, {
998
+ text,
999
+ order,
1000
+ since: badges.get(key)?.since ?? badgeCount++
1001
+ });
1002
+ writeTitle();
1003
+ },
1004
+ title(title) {
1005
+ baseTitle = title;
1006
+ writeTitle();
1007
+ },
1008
+ toast: createToast(cornerOfPage),
1009
+ ...formsApi
1010
+ };
1011
+ const changeListeners = /* @__PURE__ */ new Set();
1012
+ async function getJson(url) {
1013
+ const res = await fetch(url);
1014
+ if (!res.ok) throw new Error(`${url}: ${res.status}`);
1015
+ return res.json();
1016
+ }
1017
+ let data = handoff.data;
1018
+ let nextData = data;
1019
+ let frontmatter = handoff.frontmatter ?? {};
1020
+ let nextFrontmatter = frontmatter;
1021
+ const dataValue = reactive(() => data);
1022
+ const frontmatterValue = reactive(() => frontmatter);
1023
+ const handle = {
1024
+ settings: reactive(() => void 0),
1025
+ id: page,
1026
+ kind: handoff.kind,
1027
+ live,
1028
+ data: dataValue,
1029
+ frontmatter: frontmatterValue,
1030
+ onChange(fn) {
1031
+ changeListeners.add(fn);
1032
+ return () => changeListeners.delete(fn);
1033
+ },
1034
+ render: async () => {
1035
+ const next = await getJson(url(`/api/render?page=${encodeURIComponent(page)}`));
1036
+ nextData = next.data ?? null;
1037
+ nextFrontmatter = next.frontmatter ?? {};
1038
+ return next;
1039
+ },
1040
+ stored: () => getJson(url(`/api/page?page=${encodeURIComponent(page)}`))
1041
+ };
1042
+ /** Did the page change since it was rendered here (its file's time, or it came to be)? Then say so. */
1043
+ async function caughtUp() {
1044
+ let now;
1045
+ try {
1046
+ now = (await getJson(url(`/api/render?page=${encodeURIComponent(page)}`))).mtime ?? null;
1047
+ } catch {
1048
+ now = null;
1049
+ }
1050
+ const shown = data?.mtime ?? null;
1051
+ if (now !== shown) for (const fn of changeListeners) fn();
1052
+ }
1053
+ if (!handoff.client) handle.onChange(async () => {
1054
+ root.innerHTML = (await handle.render()).html;
1055
+ api.rendered();
1056
+ });
1057
+ const reloadWhenUp = async () => {
1058
+ try {
1059
+ if ((await fetch(url("/api/health"), { cache: "no-store" })).ok) return location.reload();
1060
+ } catch {}
1061
+ setTimeout(reloadWhenUp, 500);
1062
+ };
1063
+ /** What the server says on the live channel, by its name. */
1064
+ const onLive = {
1065
+ change: () => {
1066
+ for (const fn of changeListeners) fn();
1067
+ },
1068
+ events: () => loadEvents(),
1069
+ listeners: () => loadListeners(),
1070
+ elsewhere: () => document.dispatchEvent(new Event("wp-elsewhere")),
1071
+ reload: () => reloadWhenUp(),
1072
+ style: () => {
1073
+ stamps = null;
1074
+ for (const link of document.querySelectorAll("link[rel=stylesheet]")) {
1075
+ const url = new URL(link.href);
1076
+ if (url.origin !== location.origin) continue;
1077
+ url.searchParams.set("t", String(Date.now()));
1078
+ link.href = url.pathname + url.search;
1079
+ }
1080
+ }
1081
+ };
1082
+ let stamps = handoff.stamps ?? null;
1083
+ /**
1084
+ * Back on the live channel: what changed while this page wasn't on it, it never heard of. Browser
1085
+ * code that changed reloads the page; stylesheets that changed are refreshed in place.
1086
+ */
1087
+ async function compareStamps() {
1088
+ let now;
1089
+ try {
1090
+ now = await (await fetch(url("/api/stamps"), { cache: "no-store" })).json();
1091
+ } catch {
1092
+ return;
1093
+ }
1094
+ if (stamps && now.code !== stamps.code) return reloadWhenUp();
1095
+ if (stamps && now.style !== stamps.style) onLive.style(null);
1096
+ stamps = now;
1097
+ }
1098
+ let socket = null;
1099
+ let retries = 0;
1100
+ let retryTimer;
1101
+ function connect() {
1102
+ clearTimeout(retryTimer);
1103
+ if (socket && socket.readyState <= WebSocket.OPEN) return;
1104
+ const at = new URL(url(`/api/live?page=${encodeURIComponent(page)}${isDir ? "&dir" : ""}`), location.href);
1105
+ at.protocol = location.protocol === "https:" ? "wss:" : "ws:";
1106
+ const ws = socket = new WebSocket(at);
1107
+ ws.onopen = () => {
1108
+ retries = 0;
1109
+ document.documentElement.dataset.wpLive = "";
1110
+ loadListeners();
1111
+ loadEvents();
1112
+ compareStamps();
1113
+ document.dispatchEvent(new Event("wp-elsewhere"));
1114
+ caughtUp();
1115
+ };
1116
+ ws.onmessage = (e) => {
1117
+ let message;
1118
+ try {
1119
+ message = JSON.parse(String(e.data));
1120
+ } catch {
1121
+ return;
1122
+ }
1123
+ if (message.event) onLive[message.event]?.(message.data);
1124
+ };
1125
+ ws.onclose = () => {
1126
+ if (socket !== ws) return;
1127
+ socket = null;
1128
+ delete document.documentElement.dataset.wpLive;
1129
+ retryTimer = setTimeout(connect, Math.min(250 * 2 ** retries++, 5e3));
1130
+ };
1131
+ }
1132
+ document.addEventListener("visibilitychange", () => {
1133
+ if (document.visibilityState === "visible" && !socket) connect();
1134
+ });
1135
+ addEventListener("online", () => {
1136
+ if (!socket) connect();
1137
+ });
1138
+ await Promise.all([loadEvents(), loadListeners()]);
1139
+ if (handoff.client) try {
1140
+ const mount = (await import(moduleUrl(handoff.client))).default;
1141
+ await mount(root, handle, api);
1142
+ } catch (err) {
1143
+ console.error("page:", err);
1144
+ root.insertAdjacentHTML("afterbegin", String(html`<pre class="wp-error" role="alert">the page failed to start: ${err.message}</pre>`));
1145
+ }
1146
+ if (live) {
1147
+ trackForms(root, page, api);
1148
+ trackReading({
1149
+ messages: handoff.messages ?? [],
1150
+ events: () => events,
1151
+ send: (ids) => {
1152
+ append(READ, { ids }).catch((err) => console.error("marking read:", err));
1153
+ }
1154
+ });
1155
+ }
1156
+ scrollToAnchor(root);
1157
+ addEventListener("hashchange", () => scrollToAnchor(root));
1158
+ /**
1159
+ * A plugin's page handle: the page's, with its own settings, the page's frontmatter under `plugins:`
1160
+ * by its name, heard of only when they changed.
1161
+ */
1162
+ function handleFor(name) {
1163
+ const own = () => {
1164
+ const plugins = frontmatter.plugins;
1165
+ return plugins && typeof plugins === "object" ? plugins[name] : void 0;
1166
+ };
1167
+ const settings = reactive(own);
1168
+ let last = JSON.stringify(own() ?? null);
1169
+ frontmatterValue.on(() => {
1170
+ const now = JSON.stringify(own() ?? null);
1171
+ if (now === last) return;
1172
+ last = now;
1173
+ settings.notify();
1174
+ });
1175
+ return {
1176
+ ...handle,
1177
+ settings
1178
+ };
1179
+ }
1180
+ await Promise.all((handoff.plugins ?? []).map(async (ext) => {
1181
+ try {
1182
+ const mount = (await import(moduleUrl(ext.client))).default;
1183
+ if (typeof mount !== "function") throw new Error("the client module must export a mount(root, page, api) function as default");
1184
+ await mount(root, handleFor(ext.name), {
1185
+ ...api,
1186
+ slot: (name, mount) => slotFor(ext.name, name, mount)
1187
+ });
1188
+ } catch (err) {
1189
+ console.error(`plugin ${ext.name}:`, err);
1190
+ root.insertAdjacentHTML("afterbegin", String(html`<pre class="wp-error" role="alert">
1191
+ plugin "${ext.name}" failed in the browser: ${err.message}</pre>`));
1192
+ }
1193
+ }));
1194
+ if (live) connect();