@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.
- package/LICENSE +21 -0
- package/README.md +781 -2
- package/bin/workpad.ts +1509 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
- package/dist/bin/workpad.js +1190 -0
- package/dist/client/runtime.js +1194 -0
- package/dist/define.js +27 -0
- package/dist/plugins/alert/README.md +18 -0
- package/dist/plugins/alert/index.js +40 -0
- package/dist/plugins/alert/public/style.css +40 -0
- package/dist/plugins/ansi/README.md +36 -0
- package/dist/plugins/ansi/index.js +63 -0
- package/dist/plugins/ansi/public/style.css +28 -0
- package/dist/plugins/badge/README.md +32 -0
- package/dist/plugins/badge/index.js +28 -0
- package/dist/plugins/badge/public/style.css +30 -0
- package/dist/plugins/chat/README.md +81 -0
- package/dist/plugins/chat/index.js +96 -0
- package/dist/plugins/chat/public/client.js +3 -0
- package/dist/plugins/chat/public/style.css +143 -0
- package/dist/plugins/claude/README.md +116 -0
- package/dist/plugins/claude/channel.js +130 -0
- package/dist/plugins/claude/doctor.js +316 -0
- package/dist/plugins/claude/index.js +199 -0
- package/dist/plugins/claude/session.js +68 -0
- package/dist/plugins/code/README.md +54 -0
- package/dist/plugins/code/diff.js +75 -0
- package/dist/plugins/code/index.js +105 -0
- package/dist/plugins/code/public/client.js +1 -0
- package/dist/plugins/code/public/style.css +99 -0
- package/dist/plugins/comments/README.md +30 -0
- package/dist/plugins/comments/index.js +39 -0
- package/dist/plugins/comments/public/client.js +24 -0
- package/dist/plugins/comments/public/style.css +224 -0
- package/dist/plugins/details/README.md +24 -0
- package/dist/plugins/details/index.js +28 -0
- package/dist/plugins/details/public/style.css +7 -0
- package/dist/plugins/draft/README.md +14 -0
- package/dist/plugins/draft/index.js +27 -0
- package/dist/plugins/draft/public/style.css +21 -0
- package/dist/plugins/forge/README.md +22 -0
- package/dist/plugins/forge/index.js +83 -0
- package/dist/plugins/form/README.md +126 -0
- package/dist/plugins/form/index.js +179 -0
- package/dist/plugins/form/public/style.css +172 -0
- package/dist/plugins/grid/README.md +45 -0
- package/dist/plugins/grid/index.js +35 -0
- package/dist/plugins/grid/public/style.css +98 -0
- package/dist/plugins/iframe/README.md +18 -0
- package/dist/plugins/iframe/index.js +49 -0
- package/dist/plugins/iframe/public/style.css +28 -0
- package/dist/plugins/index.js +44 -0
- package/dist/plugins/lightbox/README.md +24 -0
- package/dist/plugins/lightbox/index.js +20 -0
- package/dist/plugins/lightbox/public/client.js +4 -0
- package/dist/plugins/lightbox/public/style.css +66 -0
- package/dist/plugins/mermaid/README.md +21 -0
- package/dist/plugins/mermaid/index.js +42 -0
- package/dist/plugins/mermaid/public/style.css +21 -0
- package/dist/plugins/opencode/README.md +48 -0
- package/dist/plugins/opencode/channel.js +92 -0
- package/dist/plugins/opencode/index.js +64 -0
- package/dist/plugins/opencode/shim.js +150 -0
- package/dist/plugins/quiet/README.md +26 -0
- package/dist/plugins/quiet/index.js +23 -0
- package/dist/plugins/tabs/README.md +44 -0
- package/dist/plugins/tabs/index.js +75 -0
- package/dist/plugins/tabs/public/client.js +1 -0
- package/dist/plugins/tabs/public/style.css +98 -0
- package/dist/plugins/terminal/README.md +63 -0
- package/dist/plugins/terminal/host.js +338 -0
- package/dist/plugins/terminal/index.js +170 -0
- package/dist/plugins/terminal/modes.js +32 -0
- package/dist/plugins/terminal/public/client.js +41 -0
- package/dist/plugins/terminal/public/style.css +511 -0
- package/dist/plugins/terminal/server.js +256 -0
- package/dist/plugins/terminal/sizes.js +58 -0
- package/dist/plugins/timeline/README.md +48 -0
- package/dist/plugins/timeline/index.js +83 -0
- package/dist/plugins/timeline/public/style.css +138 -0
- package/dist/plugins/toc/README.md +40 -0
- package/dist/plugins/toc/index.js +29 -0
- package/dist/plugins/toc/public/client.js +1 -0
- package/dist/plugins/toc/public/style.css +117 -0
- package/dist/plugins/window/README.md +51 -0
- package/dist/plugins/window/index.js +91 -0
- package/dist/solid/index.js +41 -0
- package/dist/src/agents.js +81 -0
- package/dist/src/anchors.js +52 -0
- package/dist/src/api.js +282 -0
- package/dist/src/archive.js +49 -0
- package/dist/src/auth.js +67 -0
- package/dist/src/build.js +159 -0
- package/dist/src/client/page/base.css +1762 -0
- package/dist/src/client/page/main.js +2098 -0
- package/dist/src/config.js +76 -0
- package/dist/src/document.js +93 -0
- package/dist/src/entries.js +264 -0
- package/dist/src/events.js +322 -0
- package/dist/src/files.js +47 -0
- package/dist/src/formstate.js +65 -0
- package/dist/src/help.js +211 -0
- package/dist/src/html.js +34 -0
- package/dist/src/hub.js +341 -0
- package/dist/src/icons.js +6 -0
- package/dist/src/listen.js +132 -0
- package/dist/src/listeners.js +64 -0
- package/dist/src/load.js +81 -0
- package/dist/src/loader.js +179 -0
- package/dist/src/migrate.js +314 -0
- package/dist/src/package.js +52 -0
- package/dist/src/pages/blocks.js +67 -0
- package/dist/src/pages/board.js +59 -0
- package/dist/src/pages/index.js +27 -0
- package/dist/src/pages/markdown.js +863 -0
- package/dist/src/pages/render.js +665 -0
- package/dist/src/pages/window.js +29 -0
- package/dist/src/plugins.js +283 -0
- package/dist/src/public.js +24 -0
- package/dist/src/rename.js +130 -0
- package/dist/src/running.js +146 -0
- package/dist/src/serve.js +188 -0
- package/dist/src/server.js +1105 -0
- package/dist/src/site.js +179 -0
- package/dist/src/state.js +155 -0
- package/dist/src/status.js +323 -0
- package/dist/src/thread.js +68 -0
- package/dist/src/watchdog.js +38 -0
- package/dist/src/ws.js +128 -0
- package/package.json +154 -4
- package/plugins/README.md +304 -0
- package/plugins/alert/README.md +18 -0
- package/plugins/alert/index.ts +50 -0
- package/plugins/alert/public/style.css +40 -0
- package/plugins/ansi/README.md +36 -0
- package/plugins/ansi/index.ts +95 -0
- package/plugins/ansi/public/style.css +28 -0
- package/plugins/badge/README.md +32 -0
- package/plugins/badge/index.ts +36 -0
- package/plugins/badge/public/style.css +30 -0
- package/plugins/chat/README.md +81 -0
- package/plugins/chat/autosize.ts +139 -0
- package/plugins/chat/client.tsx +187 -0
- package/plugins/chat/index.ts +146 -0
- package/plugins/chat/public/style.css +143 -0
- package/plugins/claude/README.md +116 -0
- package/plugins/claude/channel.ts +136 -0
- package/plugins/claude/doctor.ts +274 -0
- package/plugins/claude/index.ts +248 -0
- package/plugins/claude/session.ts +70 -0
- package/plugins/code/README.md +54 -0
- package/plugins/code/client.ts +73 -0
- package/plugins/code/diff.ts +96 -0
- package/plugins/code/index.ts +136 -0
- package/plugins/code/public/style.css +99 -0
- package/plugins/comments/README.md +30 -0
- package/plugins/comments/client.ts +723 -0
- package/plugins/comments/index.ts +48 -0
- package/plugins/comments/public/style.css +224 -0
- package/plugins/details/README.md +24 -0
- package/plugins/details/index.ts +30 -0
- package/plugins/details/public/style.css +7 -0
- package/plugins/draft/README.md +14 -0
- package/plugins/draft/index.ts +23 -0
- package/plugins/draft/public/style.css +21 -0
- package/plugins/forge/README.md +22 -0
- package/plugins/forge/index.ts +84 -0
- package/plugins/form/README.md +126 -0
- package/plugins/form/index.ts +199 -0
- package/plugins/form/public/style.css +172 -0
- package/plugins/grid/README.md +45 -0
- package/plugins/grid/index.ts +41 -0
- package/plugins/grid/public/style.css +98 -0
- package/plugins/iframe/README.md +18 -0
- package/plugins/iframe/index.ts +53 -0
- package/plugins/iframe/public/style.css +28 -0
- package/plugins/index.ts +49 -0
- package/plugins/lightbox/README.md +24 -0
- package/plugins/lightbox/client.ts +109 -0
- package/plugins/lightbox/index.ts +25 -0
- package/plugins/lightbox/public/style.css +66 -0
- package/plugins/mermaid/README.md +21 -0
- package/plugins/mermaid/index.ts +46 -0
- package/plugins/mermaid/public/style.css +21 -0
- package/plugins/opencode/README.md +48 -0
- package/plugins/opencode/channel.ts +112 -0
- package/plugins/opencode/index.ts +91 -0
- package/plugins/opencode/shim.ts +166 -0
- package/plugins/quiet/README.md +26 -0
- package/plugins/quiet/index.ts +28 -0
- package/plugins/tabs/README.md +44 -0
- package/plugins/tabs/client.ts +96 -0
- package/plugins/tabs/index.ts +103 -0
- package/plugins/tabs/public/style.css +98 -0
- package/plugins/terminal/README.md +63 -0
- package/plugins/terminal/client.ts +391 -0
- package/plugins/terminal/host.ts +434 -0
- package/plugins/terminal/index.ts +199 -0
- package/plugins/terminal/modes.ts +30 -0
- package/plugins/terminal/public/style.css +225 -0
- package/plugins/terminal/server.ts +266 -0
- package/plugins/terminal/sizes.ts +72 -0
- package/plugins/timeline/README.md +48 -0
- package/plugins/timeline/index.ts +82 -0
- package/plugins/timeline/public/style.css +138 -0
- package/plugins/toc/README.md +40 -0
- package/plugins/toc/client.ts +236 -0
- package/plugins/toc/index.ts +55 -0
- package/plugins/toc/public/style.css +117 -0
- package/plugins/window/README.md +51 -0
- package/plugins/window/index.ts +92 -0
- package/skills/workpad/SKILL.md +588 -0
- package/solid/index.tsx +80 -0
- package/src/agents.ts +133 -0
- package/src/anchors.ts +85 -0
- package/src/api.ts +444 -0
- package/src/archive.ts +75 -0
- package/src/auth.ts +99 -0
- package/src/build.ts +213 -0
- package/src/client/base.ts +19 -0
- package/src/client/forms.ts +420 -0
- package/src/client/markdown.ts +147 -0
- package/src/client/page/base.css +1762 -0
- package/src/client/page/board.ts +137 -0
- package/src/client/page/elsewhere.ts +153 -0
- package/src/client/page/fresh.ts +343 -0
- package/src/client/page/heading-link.ts +32 -0
- package/src/client/page/live.ts +134 -0
- package/src/client/page/main.ts +398 -0
- package/src/client/page/orphans.ts +64 -0
- package/src/client/page/place.ts +260 -0
- package/src/client/page/sort.ts +49 -0
- package/src/client/page/sticky.ts +58 -0
- package/src/client/page/theme.ts +36 -0
- package/src/client/page/view.ts +9 -0
- package/src/client/page/waiting.ts +278 -0
- package/src/client/page/window.ts +40 -0
- package/src/client/reactive.ts +19 -0
- package/src/client/read.ts +111 -0
- package/src/client/runtime.ts +499 -0
- package/src/client/scroll.ts +90 -0
- package/src/client/toast.ts +99 -0
- package/src/config.ts +111 -0
- package/src/define.ts +997 -0
- package/src/document.ts +191 -0
- package/src/entries.ts +352 -0
- package/src/events.ts +463 -0
- package/src/files.ts +74 -0
- package/src/formstate.ts +72 -0
- package/src/help.ts +238 -0
- package/src/html.ts +44 -0
- package/src/hub.ts +426 -0
- package/src/icons.ts +18 -0
- package/src/listen.ts +171 -0
- package/src/listeners.ts +89 -0
- package/src/load.ts +113 -0
- package/src/loader.ts +227 -0
- package/src/migrate.ts +352 -0
- package/src/package.ts +62 -0
- package/src/pages/blocks.ts +106 -0
- package/src/pages/board.ts +89 -0
- package/src/pages/index.ts +79 -0
- package/src/pages/markdown.ts +976 -0
- package/src/pages/render.ts +748 -0
- package/src/pages/window.ts +69 -0
- package/src/plugins.ts +319 -0
- package/src/public.ts +39 -0
- package/src/rename.ts +147 -0
- package/src/running.ts +171 -0
- package/src/serve.ts +221 -0
- package/src/server.ts +1385 -0
- package/src/site.ts +170 -0
- package/src/state.ts +327 -0
- package/src/status.ts +466 -0
- package/src/thread.ts +98 -0
- package/src/watchdog.ts +53 -0
- package/src/ws.ts +155 -0
package/src/agents.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// What the plugins of coding agents (claude, opencode) share: how the agent runs workpad,
|
|
2
|
+
// what their channels push into a session (the pong for `workpad agent ping`, an answer in one line),
|
|
3
|
+
// and what is left on the session's pages when a turn ends (`stopReminder`): questions nobody
|
|
4
|
+
// listens for, answers no agent received or that it was given and didn't handle, chats where the
|
|
5
|
+
// reader wrote last. The plugin continues the turn once with it.
|
|
6
|
+
import fs from 'node:fs'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import { spawnSync } from 'node:child_process'
|
|
9
|
+
import type { CommandContext, PageStatus, WpEvent } from './define.ts'
|
|
10
|
+
import { CHAT_MESSAGE, fromReader, statusLines } from './status.ts'
|
|
11
|
+
import { read } from './events.ts'
|
|
12
|
+
|
|
13
|
+
const relFile = (file: string) => path.relative(process.cwd(), file) || file
|
|
14
|
+
|
|
15
|
+
/** What is open on a page, in short phrases; the command that picks it up comes last, once. */
|
|
16
|
+
const openOn = (p: PageStatus, options?: { waiting?: boolean }) => statusLines(p, relFile(p.file), options)
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Who an agent session is on the boards: `WORKPAD_AGENT` when set (any harness can set it), else the
|
|
20
|
+
* session its plugin knows. The command line resolves it the same way (after `--agent`).
|
|
21
|
+
*/
|
|
22
|
+
export const identity = (session: string | null): string | null => process.env.WORKPAD_AGENT || session
|
|
23
|
+
|
|
24
|
+
/** The one listen for these pages, stopping at the first answer: a --page each. */
|
|
25
|
+
const waitOn = (pages: PageStatus[]) => `workpad listen --wait ${pages.map(p => `--page ${relFile(p.file)}`).join(' ')}`
|
|
26
|
+
|
|
27
|
+
/** For a page nobody listens on: a channel the session has may bring the answers instead. */
|
|
28
|
+
const PING = 'run `workpad agent ping` if you haven\'t this session (answers may come to you); else'
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A turn of `session` ends: nothing when its pages have nothing left for it; else what to tell the
|
|
33
|
+
* agent to do before it ends its turn (`reason`), and what is open in one line, for the reader (`shown`).
|
|
34
|
+
*/
|
|
35
|
+
export async function stopReminder(
|
|
36
|
+
ctx: CommandContext,
|
|
37
|
+
session: string | null,
|
|
38
|
+
/**
|
|
39
|
+
* answers the session's channel sent that haven't reached it yet: Claude Code holds a channel's
|
|
40
|
+
* message while a turn runs, and gives it to the agent once the turn ends, which starts a turn of
|
|
41
|
+
* its own. Holding this one up for them would send it on about an answer it is about to get.
|
|
42
|
+
*/
|
|
43
|
+
inFlight: Set<string> = new Set(),
|
|
44
|
+
): Promise<{ reason: string; shown: string } | null> {
|
|
45
|
+
if (!session) return null
|
|
46
|
+
// what is on its way to the session is no reason to hold the turn up (see `inFlight`)
|
|
47
|
+
const events = inFlight.size ? read(ctx.eventsFile).events : []
|
|
48
|
+
const mine = (await ctx.status())
|
|
49
|
+
.filter(p => p.subscribers.includes(session))
|
|
50
|
+
.map(p => {
|
|
51
|
+
if (!inFlight.size) return p
|
|
52
|
+
// the chats whose last message from the reader is on its way
|
|
53
|
+
const lastFromReader = new Map<string, string>()
|
|
54
|
+
for (const e of events)
|
|
55
|
+
if (e.page === p.page && e.type === CHAT_MESSAGE && fromReader(e)) lastFromReader.set(String(e.data?.chat), e.id)
|
|
56
|
+
return {
|
|
57
|
+
...p,
|
|
58
|
+
unhandled: p.unhandled.filter(e => !inFlight.has(e.id)),
|
|
59
|
+
awaitingReply: p.awaitingReply.filter(chat => !inFlight.has(lastFromReader.get(chat) ?? '')),
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
const loose = mine.filter(p => p.unheard.length || p.unreceived.length || p.unhandled.length || p.awaitingReply.length)
|
|
63
|
+
if (!loose.length) return null
|
|
64
|
+
// what is left, without the command line: the reason says what to do
|
|
65
|
+
const said = (p: PageStatus) =>
|
|
66
|
+
openOn(p, { waiting: false })
|
|
67
|
+
.filter(l => !l.startsWith('→'))
|
|
68
|
+
.join('; ')
|
|
69
|
+
const shown = `workpad: ${loose.map(p => `${p.page}: ${said(p)}`).join(' · ')}`
|
|
70
|
+
// what to do about each: wait for what nobody listens for, handle what it was given, reply in
|
|
71
|
+
// the chats waiting for it. Pages to wait on: one wait for all of them, said once at the end
|
|
72
|
+
const toWait = loose.filter(p => p.unheard.length || p.unreceived.length)
|
|
73
|
+
const reason = loose
|
|
74
|
+
.map(p => {
|
|
75
|
+
const todo: string[] = []
|
|
76
|
+
if (toWait.length === 1 && toWait[0] === p)
|
|
77
|
+
todo.push(`${PING} run \`workpad listen --wait --page ${relFile(p.file)}\` in the background`)
|
|
78
|
+
if (p.unhandled.length)
|
|
79
|
+
todo.push(
|
|
80
|
+
`act on the answers you were given and reply in their chat, or \`workpad handled ${p.unhandled.map(e => e.id).join(' ')}\``,
|
|
81
|
+
)
|
|
82
|
+
if (p.awaitingReply.length)
|
|
83
|
+
todo.push(`reply in the chat${p.awaitingReply.length > 1 ? 's' : ''} ${p.awaitingReply.join(', ')}`)
|
|
84
|
+
return `On your workpad page ${p.page}: ${said(p)}.${todo.length ? ` Before ending your turn: ${todo.join('; ')}.` : ''}`
|
|
85
|
+
})
|
|
86
|
+
.concat(
|
|
87
|
+
toWait.length > 1
|
|
88
|
+
? [`Before ending your turn, ${PING} run one listen for these pages in the background: \`${waitOn(toWait)}\`.`]
|
|
89
|
+
: [],
|
|
90
|
+
)
|
|
91
|
+
.join('\n')
|
|
92
|
+
return { reason, shown }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** One line per answer, for a message pushed into a session: what the reader did, in words. */
|
|
96
|
+
export function describe(e: WpEvent): string {
|
|
97
|
+
const d = (e.data ?? {}) as Record<string, unknown>
|
|
98
|
+
if (e.type === CHAT_MESSAGE) return `chat ${d.chat}: "${d.text}"`
|
|
99
|
+
if (e.type === 'comments:new') return `comment on "${d.quote ?? d.at ?? ''}": "${d.text}"`
|
|
100
|
+
// what was chosen or written; the button only when it is the answer itself (no fields)
|
|
101
|
+
const fields = Object.entries(d).filter(([, v]) => v !== '' && v != null && !(Array.isArray(v) && !v.length))
|
|
102
|
+
const said = fields.map(([k, v]) => (fields.length === 1 ? JSON.stringify(v) : `${k}: ${JSON.stringify(v)}`))
|
|
103
|
+
if (said.length) return `form ${e.type}: ${said.join(', ')}`
|
|
104
|
+
return `form ${e.type}: clicked ${e.action ?? 'send'}`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* How the agent runs workpad here: the project's own copy when it depends on it (the version it
|
|
109
|
+
* pins, for everyone who clones it), else the one on the PATH, else from npm. The agent runs these
|
|
110
|
+
* outside any node_modules/.bin; npx finds the project's copy, and names the package, since
|
|
111
|
+
* `npx workpad` alone would fetch another one.
|
|
112
|
+
*/
|
|
113
|
+
export function workpadCommand(dir: string): string[] {
|
|
114
|
+
for (let d = dir; ; d = path.dirname(d)) {
|
|
115
|
+
if (fs.existsSync(path.join(d, 'node_modules', '@bigmistqke', 'workpad'))) return NPX
|
|
116
|
+
if (path.dirname(d) === d) break
|
|
117
|
+
}
|
|
118
|
+
const onPath = spawnSync('sh', ['-c', 'command -v workpad'], { encoding: 'utf8' }).status === 0
|
|
119
|
+
return onPath ? ['workpad'] : NPX
|
|
120
|
+
}
|
|
121
|
+
const NPX = ['npx', '@bigmistqke/workpad']
|
|
122
|
+
|
|
123
|
+
/** The pong a channel pushes into its session for `workpad agent ping`: what it means, and how to confirm it. */
|
|
124
|
+
export const pong = (code: string) =>
|
|
125
|
+
`workpad: pong. Answers on your workpad pages will reach you like this message did, and count as received once they do: no \`workpad listen\` needs to run for them (\`workpad listen --channel\` makes more pages yours). Run \`workpad agent ping ${code}\` to confirm.`
|
|
126
|
+
|
|
127
|
+
/** An answer a channel pushes into its session, in one line: the page, what the reader did, how to see its question. */
|
|
128
|
+
export const answerLine = (e: WpEvent, again = false) =>
|
|
129
|
+
`${e.page}: ${describe(e)}${again ? ' (received before, not handled yet)' : ''} (id ${e.id}; \`workpad thread ${e.id}\` shows it with its question)`
|
|
130
|
+
|
|
131
|
+
/** What to do about answers a channel brought: the same for every agent. */
|
|
132
|
+
export const ANSWERS_NOTE =
|
|
133
|
+
'Act on each as on an answer from `workpad listen`. Then handle it with one of: a reply in its chat (`workpad append`), when you have something to say; else `workpad handled <id>`. Nothing more is needed.'
|
package/src/anchors.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Anchors: what a link's `#…` goes to on a page. A heading's id is its slug, as GitHub and GitLab
|
|
2
|
+
// make it (`#open-questions`); a block's is `<type>:<name>` (`#form:logger`, `#chat:notes`,
|
|
3
|
+
// `#tab:intro`), given out while the page renders (BaseContext.anchor). A slug never holds a colon,
|
|
4
|
+
// so the two never meet; ids starting `wp-` are the page's own.
|
|
5
|
+
import { html, type Html } from './html.ts'
|
|
6
|
+
|
|
7
|
+
/** Text as a forge makes it an anchor, without numbering repeats: lowercased, punctuation dropped, spaces as hyphens. */
|
|
8
|
+
export const slugText = (text: string): string =>
|
|
9
|
+
text
|
|
10
|
+
.toLowerCase()
|
|
11
|
+
.trim()
|
|
12
|
+
.replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, '')
|
|
13
|
+
.replace(/ /g, '-')
|
|
14
|
+
|
|
15
|
+
/** What a block shows in place of its id when the page has one of that type and name already. */
|
|
16
|
+
export const anchorTaken = (type: string, name: string): Html =>
|
|
17
|
+
html`<p class="wp-error" role="note">
|
|
18
|
+
another ${type} on this page is named "${name}" already: links to #${type}:${name} go to that one
|
|
19
|
+
</p>`
|
|
20
|
+
|
|
21
|
+
/** What a page can be linked to (`workpad anchors`): an id, what kind of thing it is, what it says. */
|
|
22
|
+
export interface Anchor {
|
|
23
|
+
/** the id, the `#…` that goes to it */
|
|
24
|
+
id: string
|
|
25
|
+
/** its type (`form`, `chat`, `tab`, `details`, a plugin's own), or `heading` */
|
|
26
|
+
kind: string
|
|
27
|
+
/** what the reader sees of it, short: a heading's text, a details' label; the name when nothing else */
|
|
28
|
+
label: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const decode = (s: string) =>
|
|
32
|
+
s
|
|
33
|
+
.replace(/"/g, '"')
|
|
34
|
+
.replace(/'|'/g, "'")
|
|
35
|
+
.replace(/</g, '<')
|
|
36
|
+
.replace(/>/g, '>')
|
|
37
|
+
.replace(/&/g, '&')
|
|
38
|
+
|
|
39
|
+
const textOf = (s: string) =>
|
|
40
|
+
decode(s.replace(/<[^>]+>/g, ' '))
|
|
41
|
+
.replace(/\s+/g, ' ')
|
|
42
|
+
.trim()
|
|
43
|
+
|
|
44
|
+
/** The text of the element with id `id` in the HTML (what an aria-labelledby points at). */
|
|
45
|
+
function labelOf(html: string, id: string): string | undefined {
|
|
46
|
+
const m = new RegExp(`<(\\w+)\\b[^>]*?\\sid="${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"[^>]*>`).exec(html)
|
|
47
|
+
if (!m) return undefined
|
|
48
|
+
const after = html.slice(m.index + m[0].length)
|
|
49
|
+
return textOf(after.slice(0, after.indexOf(`</${m[1]}>`)))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The anchors in a page's HTML as the server renders it, in page order: its headings' ids and the
|
|
54
|
+
* ids blocks asked for (BaseContext.anchor). What a page's script draws later (a chat's messages,
|
|
55
|
+
* `#message:<id>`) isn't in it.
|
|
56
|
+
*/
|
|
57
|
+
export function anchorsOf(html: string): Anchor[] {
|
|
58
|
+
const out: Anchor[] = []
|
|
59
|
+
for (const m of html.matchAll(/<(\w+)\b[^>]*?\sid="([^"]+)"[^>]*>/g)) {
|
|
60
|
+
const [tag, id] = [m[1].toLowerCase(), decode(m[2])]
|
|
61
|
+
const labelledBy = /\saria-labelledby="([^"]*)"/.exec(m[0])?.[1]
|
|
62
|
+
const named = /\saria-label="([^"]*)"/.exec(m[0])?.[1]
|
|
63
|
+
const after = html.slice(m.index! + m[0].length)
|
|
64
|
+
if (/^h[1-6]$/.test(tag)) {
|
|
65
|
+
out.push({ id, kind: 'heading', label: textOf(after.slice(0, after.indexOf(`</${tag}>`))) })
|
|
66
|
+
continue
|
|
67
|
+
}
|
|
68
|
+
const typed = /^([a-z][\w-]*):(.+)$/.exec(id)
|
|
69
|
+
if (!typed || id.startsWith('wp-')) continue
|
|
70
|
+
const [, kind, name] = typed
|
|
71
|
+
// what names it: its aria-label or the element it's labelled by (a tab's title), a details' summary, else its name
|
|
72
|
+
const label = named
|
|
73
|
+
? decode(named)
|
|
74
|
+
: labelledBy && labelOf(html, labelledBy) !== undefined
|
|
75
|
+
? labelOf(html, labelledBy)!
|
|
76
|
+
: kind === 'details'
|
|
77
|
+
? textOf(/<summary>([\s\S]*?)<\/summary>/.exec(after)?.[1] ?? name)
|
|
78
|
+
: name
|
|
79
|
+
out.push({ id, kind, label })
|
|
80
|
+
}
|
|
81
|
+
return out
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A hash as a link writes it: escaped where it must be, the colon and slash of an id left readable. */
|
|
85
|
+
export const hashOf = (id: string): string => '#' + encodeURIComponent(id).replace(/%3A/gi, ':').replace(/%2F/gi, '/')
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
// `@bigmistqke/workpad/api`: a typed way into workpad's state, for a script that builds boards
|
|
2
|
+
// of its own (every form waiting across projects, a kanban) or acts on them (hold a merge's form
|
|
3
|
+
// until another lands). Every call is an HTTP request to a workpad server, so it works from
|
|
4
|
+
// another process, a container or another machine as well as from a project's folder:
|
|
5
|
+
//
|
|
6
|
+
// import { connect } from '@bigmistqke/workpad/api'
|
|
7
|
+
//
|
|
8
|
+
// const wp = await connect() // this folder's project, else the shared server
|
|
9
|
+
// for (const form of await wp.forms({ state: 'open' }))
|
|
10
|
+
// console.log(form.project, form.page, form.question, form.options.map(o => o.label))
|
|
11
|
+
// await wp.hold({ page: 'awaiting-you', name: 'merge-2152' }, 'waits for !2145')
|
|
12
|
+
// for await (const e of wp.live({ kind: ['answer', 'chat'] })) console.log(e.project, e.page, e.type, e.data)
|
|
13
|
+
//
|
|
14
|
+
// A command gets the same client as `ctx.wp` (CommandContext), connected to its project.
|
|
15
|
+
//
|
|
16
|
+
// It sits on the server's HTTP API (the README's API section), which any language can call:
|
|
17
|
+
// GET /api/projects | pages | forms | chats | subscriptions | agents the lists (state.ts)
|
|
18
|
+
// GET /api/status, /api/events, /api/listeners, /api/anchors per project
|
|
19
|
+
// GET /api/stream the log as it grows (server-sent events)
|
|
20
|
+
// POST /api/forms/hold | release | settle, /api/handled, /api/page the writes (the project's token)
|
|
21
|
+
// A project's server answers for its project; the shared server answers the lists and the stream
|
|
22
|
+
// for every project it serves, each item with its project's path (`project`), and each project's
|
|
23
|
+
// own routes under that path.
|
|
24
|
+
//
|
|
25
|
+
// The live stream is server-sent events rather than the pages' WebSocket (/api/live): that one tells
|
|
26
|
+
// a page that something changed so it asks again, and checks it is opened from a page of the
|
|
27
|
+
// server's; a script wants the events themselves, over plain HTTP that any proxy passes and fetch
|
|
28
|
+
// reads, resumed after a dropped connection from the last event it had (`since`).
|
|
29
|
+
import fs from 'node:fs'
|
|
30
|
+
import path from 'node:path'
|
|
31
|
+
import { findProjectDir, project as projectAt } from './config.ts'
|
|
32
|
+
import { machineServerFile } from './entries.ts'
|
|
33
|
+
import { projectServer, recordedOrigin, sharedServer } from './running.ts'
|
|
34
|
+
import type { FormState, Listener, PageStatus, WpEvent } from './define.ts'
|
|
35
|
+
import type { Anchor } from './anchors.ts'
|
|
36
|
+
import { kindOf } from './state.ts'
|
|
37
|
+
import type {
|
|
38
|
+
AgentInfo,
|
|
39
|
+
ChatInfo,
|
|
40
|
+
EventKind,
|
|
41
|
+
EventQuery,
|
|
42
|
+
FormInfo,
|
|
43
|
+
FormOption,
|
|
44
|
+
HoldInfo,
|
|
45
|
+
LiveEvent,
|
|
46
|
+
PageInfo,
|
|
47
|
+
ProjectInfo,
|
|
48
|
+
SubscriptionInfo,
|
|
49
|
+
} from './state.ts'
|
|
50
|
+
|
|
51
|
+
export type {
|
|
52
|
+
AgentInfo,
|
|
53
|
+
Anchor,
|
|
54
|
+
ChatInfo,
|
|
55
|
+
EventKind,
|
|
56
|
+
EventQuery,
|
|
57
|
+
FormInfo,
|
|
58
|
+
FormOption,
|
|
59
|
+
FormState,
|
|
60
|
+
HoldInfo,
|
|
61
|
+
Listener,
|
|
62
|
+
LiveEvent,
|
|
63
|
+
PageInfo,
|
|
64
|
+
PageStatus,
|
|
65
|
+
ProjectInfo,
|
|
66
|
+
SubscriptionInfo,
|
|
67
|
+
WpEvent,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Where to connect, and as whom. */
|
|
71
|
+
export interface ConnectOptions {
|
|
72
|
+
/**
|
|
73
|
+
* A server's address: a project's own (`http://localhost:4777`), the shared server
|
|
74
|
+
* (`http://localhost:4790`), or a project under it (`https://workpad.local/rg/develop`).
|
|
75
|
+
*/
|
|
76
|
+
url?: string
|
|
77
|
+
/** a project's folder (or a folder inside it): the server that serves it, its own or the shared one */
|
|
78
|
+
dir?: string
|
|
79
|
+
/** the machine's shared server, as its record in the machine folder says */
|
|
80
|
+
shared?: boolean
|
|
81
|
+
/**
|
|
82
|
+
* The token the writes send (each project has its own, in `.workpad/token`): one for every
|
|
83
|
+
* project, or one per project. Without it, a project's token is read from its folder when this
|
|
84
|
+
* machine has it.
|
|
85
|
+
*/
|
|
86
|
+
token?: string | ((project: ProjectInfo) => string | null | undefined)
|
|
87
|
+
/** who writes: the `by` of what is appended (default: WORKPAD_AGENT) */
|
|
88
|
+
agent?: string | null
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A form, by where it is: `{ page, name }`, with `project` under the shared server; or `page#name`. */
|
|
92
|
+
export type FormRef = string | { project?: string; page: string; name: string }
|
|
93
|
+
|
|
94
|
+
/** Which page (and those below it), and in which project; without a project, every one the server serves. */
|
|
95
|
+
export interface Scope {
|
|
96
|
+
project?: string
|
|
97
|
+
page?: string
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** An error the server answered with: its status and what it said. */
|
|
101
|
+
export class WorkpadError extends Error {
|
|
102
|
+
readonly status: number
|
|
103
|
+
constructor(message: string, status: number) {
|
|
104
|
+
super(message)
|
|
105
|
+
this.status = status
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** A connection to a workpad server: every call an HTTP request. */
|
|
110
|
+
export interface Workpad {
|
|
111
|
+
/** the server's address: its origin, and the project's path under it when connected to one project */
|
|
112
|
+
url(): Promise<string>
|
|
113
|
+
/** the projects it serves: one for a project's server */
|
|
114
|
+
projects(): Promise<ProjectInfo[]>
|
|
115
|
+
/** the pages, each with its title, address, subscribers, questions and how much waits on it */
|
|
116
|
+
pages(scope?: Scope): Promise<PageInfo[]>
|
|
117
|
+
/** what is open on each page, as `workpad status` reports it (PageStatus), with its project */
|
|
118
|
+
status(scope?: Scope): Promise<(PageStatus & { project: string })[]>
|
|
119
|
+
/**
|
|
120
|
+
* The forms: each question with its text, options, anchor, when it was asked, where it stands
|
|
121
|
+
* (open, pending, received, handled, held, settled), why it is held and its latest answer.
|
|
122
|
+
*/
|
|
123
|
+
forms(query?: Scope & { state?: FormState | FormState[]; name?: string | string[] }): Promise<FormInfo[]>
|
|
124
|
+
/** one form, or null when there is none of that name */
|
|
125
|
+
form(ref: FormRef): Promise<FormInfo | null>
|
|
126
|
+
/** the chats on the pages: their messages, and whether one waits for a reply */
|
|
127
|
+
chats(query?: Scope & { chat?: string }): Promise<ChatInfo[]>
|
|
128
|
+
/** the events in the log that match, oldest first (`since`: those after an event's id or a time) */
|
|
129
|
+
events(query?: EventQuery & { project?: string }): Promise<LiveEvent[]>
|
|
130
|
+
/**
|
|
131
|
+
* The events as they come, for as long as it is iterated (break, or abort `signal`, to stop):
|
|
132
|
+
* those after `since` first, when given. A dropped connection is made again, from the last event.
|
|
133
|
+
*/
|
|
134
|
+
live(query?: EventQuery & { project?: string; signal?: AbortSignal }): AsyncIterable<LiveEvent>
|
|
135
|
+
/** who is subscribed to which pages */
|
|
136
|
+
subscriptions(query?: Scope & { agent?: string }): Promise<SubscriptionInfo[]>
|
|
137
|
+
/** the agents each project knows: their name, subscriptions, what they listen on now, when last seen */
|
|
138
|
+
agents(scope?: { project?: string }): Promise<AgentInfo[]>
|
|
139
|
+
/** who listens now (a running `workpad listen`, a channel) */
|
|
140
|
+
listeners(scope?: Scope): Promise<(Listener & { project: string })[]>
|
|
141
|
+
/** what a page can be linked to: `#form:pick`, a heading's slug… */
|
|
142
|
+
anchors(page: string, scope?: { project?: string }): Promise<Anchor[]>
|
|
143
|
+
/**
|
|
144
|
+
* Write a page: its markdown, as a whole. A page made here is subscribed to by whoever writes it
|
|
145
|
+
* (`agent`). As with its file, a form keeps its answers while it keeps its name.
|
|
146
|
+
*/
|
|
147
|
+
writePage(
|
|
148
|
+
page: string,
|
|
149
|
+
markdown: string,
|
|
150
|
+
scope?: { project?: string },
|
|
151
|
+
): Promise<{ page: string; file: string; url: string; created: boolean }>
|
|
152
|
+
/** hold a form, with why ("waits for !2145"): it doesn't wait for the reader until released */
|
|
153
|
+
hold(form: FormRef, reason: string): Promise<WpEvent>
|
|
154
|
+
/** release a held form: open again */
|
|
155
|
+
release(form: FormRef): Promise<WpEvent>
|
|
156
|
+
/** settle a form answered elsewhere: it no longer counts as unanswered */
|
|
157
|
+
settle(form: FormRef): Promise<{ event: WpEvent | null; forms: string[]; skipped: { name: string; state: string }[] }>
|
|
158
|
+
/** say the agent is done with these events (answers): no listen hands them out again */
|
|
159
|
+
handled(
|
|
160
|
+
events: string | LiveEvent | (string | LiveEvent)[],
|
|
161
|
+
scope?: { project?: string },
|
|
162
|
+
): Promise<{ handled: WpEvent[]; already: string[] }>
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** What a client needs of where it connects: the server's origin, and the project's path when it is one project's. */
|
|
166
|
+
export interface Target {
|
|
167
|
+
origin: string
|
|
168
|
+
/** the project's path when connected to one project; null for the shared server, all of its projects */
|
|
169
|
+
base: string | null
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Connect to a workpad server: a URL (`'http://localhost:4777'`, `'https://workpad.local/rg/develop'`),
|
|
174
|
+
* a project's folder, or options. Without any: the project of the current folder (its own server, or
|
|
175
|
+
* the shared server's path for it), else the shared server. It asks the server once, to know what it
|
|
176
|
+
* is; a server that doesn't run is an error that says so.
|
|
177
|
+
*/
|
|
178
|
+
export async function connect(target?: string | ConnectOptions): Promise<Workpad> {
|
|
179
|
+
const options: ConnectOptions =
|
|
180
|
+
typeof target === 'string' ? (/^https?:\/\//.test(target) ? { url: target } : { dir: target }) : (target ?? {})
|
|
181
|
+
const at = await locate(options)
|
|
182
|
+
const wp = client(async () => at, options)
|
|
183
|
+
await wp.projects()
|
|
184
|
+
return wp
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Where `options` point: a URL as it is; a folder's project; else this folder's, else the shared server. */
|
|
188
|
+
async function locate(options: ConnectOptions): Promise<Target> {
|
|
189
|
+
if (options.url) return probe(options.url)
|
|
190
|
+
const dir = options.shared ? null : findProjectDir(options.dir ?? process.cwd())
|
|
191
|
+
if (options.dir && !dir)
|
|
192
|
+
throw new Error(`${options.dir} is not in a workpad project (no .workpad/ folder in it or above it)`)
|
|
193
|
+
if (dir) {
|
|
194
|
+
const url = await projectServer(projectAt(dir)!)
|
|
195
|
+
if (!url)
|
|
196
|
+
throw new Error(
|
|
197
|
+
`no server serves ${dir}: \`workpad show <page>\` there starts its own, and the shared server is started outside the agents' sandboxes`,
|
|
198
|
+
)
|
|
199
|
+
return probe(url)
|
|
200
|
+
}
|
|
201
|
+
const shared = await sharedServer(machineServerFile())
|
|
202
|
+
if (!shared)
|
|
203
|
+
throw new Error(
|
|
204
|
+
`the shared server is not running${recordedOrigin(machineServerFile()) ? '' : ' (it has no record in the machine folder)'}: give a project's folder or a server's url`,
|
|
205
|
+
)
|
|
206
|
+
return { origin: shared.origin, base: null }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** What a server at `url` is: the shared one (all its projects), or a project's, at its path. */
|
|
210
|
+
export async function probe(url: string): Promise<Target> {
|
|
211
|
+
const clean = url.replace(/\/+$/, '')
|
|
212
|
+
let health: { hub?: boolean; base?: string }
|
|
213
|
+
try {
|
|
214
|
+
const res = await fetch(`${clean}/api/health`, { signal: AbortSignal.timeout(5000) })
|
|
215
|
+
health = (await res.json()) as typeof health
|
|
216
|
+
} catch (err) {
|
|
217
|
+
throw new Error(`no workpad server answers at ${clean}: ${(err as Error).message}`)
|
|
218
|
+
}
|
|
219
|
+
const { origin, pathname } = new URL(clean)
|
|
220
|
+
if (health.hub) return { origin: `${origin}${pathname === '/' ? '' : pathname}`, base: null }
|
|
221
|
+
const base = typeof health.base === 'string' ? health.base : ''
|
|
222
|
+
// the address up to the project's path is the server's
|
|
223
|
+
const prefix = pathname.replace(/\/+$/, '')
|
|
224
|
+
return { origin: `${origin}${prefix.endsWith(base) ? prefix.slice(0, prefix.length - base.length) : prefix}`, base }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const query = (q: Record<string, unknown>) => {
|
|
228
|
+
const params = new URLSearchParams()
|
|
229
|
+
for (const [k, v] of Object.entries(q))
|
|
230
|
+
if (v != null && v !== '' && !(Array.isArray(v) && !v.length))
|
|
231
|
+
params.set(k, Array.isArray(v) ? v.join(',') : String(v))
|
|
232
|
+
const s = params.toString()
|
|
233
|
+
return s ? `?${s}` : ''
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* A client whose calls go to the server `target` says, asked for at the first call, so that one
|
|
238
|
+
* made before a server runs can start it then.
|
|
239
|
+
*/
|
|
240
|
+
export function client(
|
|
241
|
+
target: () => Promise<Target>,
|
|
242
|
+
options: Omit<ConnectOptions, 'url' | 'dir' | 'shared'> = {},
|
|
243
|
+
): Workpad {
|
|
244
|
+
let at: Promise<Target> | null = null
|
|
245
|
+
const where = () => (at ??= target().catch(err => ((at = null), Promise.reject(err))))
|
|
246
|
+
const agent = options.agent !== undefined ? options.agent : (process.env.WORKPAD_AGENT ?? null)
|
|
247
|
+
let known: ProjectInfo[] | null = null
|
|
248
|
+
|
|
249
|
+
async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
|
250
|
+
const res = await fetch(url, init)
|
|
251
|
+
const text = await res.text()
|
|
252
|
+
let body: unknown
|
|
253
|
+
try {
|
|
254
|
+
body = text ? JSON.parse(text) : null
|
|
255
|
+
} catch {
|
|
256
|
+
throw new WorkpadError(`${url}: not JSON (${res.status})`, res.status)
|
|
257
|
+
}
|
|
258
|
+
if (!res.ok) throw new WorkpadError((body as { error?: string } | null)?.error ?? res.statusText, res.status)
|
|
259
|
+
return body as T
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async function projects(): Promise<ProjectInfo[]> {
|
|
263
|
+
const t = await where()
|
|
264
|
+
known = await request<ProjectInfo[]>(`${t.origin}${t.base ?? ''}/api/projects`)
|
|
265
|
+
return known
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The project a call is about: the one connected to, else the one named (by its path, folder or name). */
|
|
269
|
+
async function projectOf(name: string | undefined): Promise<ProjectInfo | null> {
|
|
270
|
+
const t = await where()
|
|
271
|
+
const all = known ?? (await projects())
|
|
272
|
+
if (t.base !== null) return all[0] ?? null
|
|
273
|
+
if (name == null) return null
|
|
274
|
+
const found =
|
|
275
|
+
all.find(p => p.base === name) ??
|
|
276
|
+
all.find(p => p.dir === name) ??
|
|
277
|
+
(await projects()).find(p => p.base === name || p.dir === name || p.label === name || p.name === name)
|
|
278
|
+
if (!found) throw new Error(`the server serves no project ${name}: it serves ${all.map(p => p.base).join(', ')}`)
|
|
279
|
+
return found
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** A project's own route. */
|
|
283
|
+
const at_ = async (p: ProjectInfo, route: string) => `${(await where()).origin}${p.base}${route}`
|
|
284
|
+
|
|
285
|
+
/** A list: of the project named or connected to, else of every project (the shared server puts them together). */
|
|
286
|
+
async function list<T>(what: string, q: Record<string, unknown>, project?: string): Promise<T[]> {
|
|
287
|
+
const p = await projectOf(project)
|
|
288
|
+
const t = await where()
|
|
289
|
+
return request<T[]>(`${p ? await at_(p, `/api/${what}`) : `${t.origin}/api/${what}`}${query(q)}`)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** A route each project answers for its own: of the one named or connected to, else of each, put together. */
|
|
293
|
+
async function each<T>(
|
|
294
|
+
route: string,
|
|
295
|
+
q: Record<string, unknown>,
|
|
296
|
+
project?: string,
|
|
297
|
+
): Promise<(T & { project: string })[]> {
|
|
298
|
+
const p = await projectOf(project)
|
|
299
|
+
const ps = p ? [p] : (known ?? (await projects()))
|
|
300
|
+
const all = await Promise.all(
|
|
301
|
+
ps.map(async x =>
|
|
302
|
+
(await request<T[]>(`${await at_(x, route)}${query(q)}`)).map(item => ({ ...item, project: x.base })),
|
|
303
|
+
),
|
|
304
|
+
)
|
|
305
|
+
return all.flat()
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** A project's token, for its writes: given, or read from its folder. */
|
|
309
|
+
function tokenOf(p: ProjectInfo): string | null {
|
|
310
|
+
const t = typeof options.token === 'function' ? options.token(p) : options.token
|
|
311
|
+
if (t) return t
|
|
312
|
+
try {
|
|
313
|
+
return fs.readFileSync(path.join(p.dir, '.workpad', 'token'), 'utf8').trim()
|
|
314
|
+
} catch {
|
|
315
|
+
return null
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function write<T>(project: string | undefined, route: string, body: Record<string, unknown>): Promise<T> {
|
|
320
|
+
const p = await projectOf(project)
|
|
321
|
+
if (!p) throw new Error(`name the project: the server serves ${(known ?? []).map(x => x.base).join(', ')}`)
|
|
322
|
+
const token = tokenOf(p)
|
|
323
|
+
return request<T>(await at_(p, route), {
|
|
324
|
+
method: 'POST',
|
|
325
|
+
headers: { 'content-type': 'application/json', ...(token ? { 'x-workpad-token': token } : {}) },
|
|
326
|
+
body: JSON.stringify({ ...body, ...(agent ? { agent } : {}) }),
|
|
327
|
+
})
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** A form's page, name and project, from a ref: `page#name` (`#form:name` too), or the parts. */
|
|
331
|
+
function parse(ref: FormRef): { project?: string; page: string; name: string } {
|
|
332
|
+
if (typeof ref !== 'string') return ref
|
|
333
|
+
const hash = ref.lastIndexOf('#')
|
|
334
|
+
if (hash < 0) throw new Error(`a form is <page>#<name>: ${ref}`)
|
|
335
|
+
return { page: ref.slice(0, hash), name: ref.slice(hash + 1).replace(/^form:/, '') }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async function formWrite<T>(action: string, ref: FormRef, extra: Record<string, unknown> = {}): Promise<T> {
|
|
339
|
+
const f = parse(ref)
|
|
340
|
+
return write<T>(f.project, `/api/forms/${action}`, { page: f.page, forms: [f.name], ...extra })
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async function* live(q: EventQuery & { project?: string; signal?: AbortSignal } = {}): AsyncGenerator<LiveEvent> {
|
|
344
|
+
const { project, signal, ...filter } = q
|
|
345
|
+
const p = await projectOf(project)
|
|
346
|
+
const t = await where()
|
|
347
|
+
let since = filter.since ?? null
|
|
348
|
+
const stop = new AbortController()
|
|
349
|
+
const onAbort = () => stop.abort()
|
|
350
|
+
signal?.addEventListener('abort', onAbort)
|
|
351
|
+
try {
|
|
352
|
+
while (!stop.signal.aborted) {
|
|
353
|
+
const url = `${p ? await at_(p, '/api/stream') : `${t.origin}/api/stream`}${query({ ...filter, since })}`
|
|
354
|
+
let res: Response
|
|
355
|
+
try {
|
|
356
|
+
res = await fetch(url, { signal: stop.signal })
|
|
357
|
+
} catch {
|
|
358
|
+
if (stop.signal.aborted) return
|
|
359
|
+
await new Promise(r => setTimeout(r, 1000))
|
|
360
|
+
continue
|
|
361
|
+
}
|
|
362
|
+
if (!res.ok || !res.body) throw new WorkpadError(`${url}: ${res.status} ${res.statusText}`, res.status)
|
|
363
|
+
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader()
|
|
364
|
+
let buf = ''
|
|
365
|
+
try {
|
|
366
|
+
for (;;) {
|
|
367
|
+
const { value, done } = await reader.read()
|
|
368
|
+
if (done) break
|
|
369
|
+
buf += value
|
|
370
|
+
let end
|
|
371
|
+
while ((end = buf.indexOf('\n\n')) >= 0) {
|
|
372
|
+
const block = buf.slice(0, end)
|
|
373
|
+
buf = buf.slice(end + 2)
|
|
374
|
+
const data = /^data: (.*)$/m.exec(block)?.[1]
|
|
375
|
+
if (!/^event: event$/m.test(block) || !data) continue
|
|
376
|
+
const e = JSON.parse(data) as LiveEvent
|
|
377
|
+
since = e.id
|
|
378
|
+
yield e
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
} catch {
|
|
382
|
+
if (stop.signal.aborted) return
|
|
383
|
+
} finally {
|
|
384
|
+
reader.releaseLock()
|
|
385
|
+
}
|
|
386
|
+
// the connection dropped (a restart): again, from the last event it had
|
|
387
|
+
if (!stop.signal.aborted) await new Promise(r => setTimeout(r, 1000))
|
|
388
|
+
}
|
|
389
|
+
} finally {
|
|
390
|
+
signal?.removeEventListener('abort', onAbort)
|
|
391
|
+
stop.abort()
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
return {
|
|
396
|
+
async url() {
|
|
397
|
+
const t = await where()
|
|
398
|
+
return `${t.origin}${t.base ?? ''}`
|
|
399
|
+
},
|
|
400
|
+
projects,
|
|
401
|
+
pages: ({ project, ...q } = {}) => list<PageInfo>('pages', q, project),
|
|
402
|
+
status: ({ project, ...q } = {}) => each<PageStatus>('/api/status', q, project),
|
|
403
|
+
forms: ({ project, ...q } = {}) => list<FormInfo>('forms', q, project),
|
|
404
|
+
async form(ref) {
|
|
405
|
+
const f = parse(ref)
|
|
406
|
+
return (
|
|
407
|
+
(await list<FormInfo>('forms', { page: f.page, name: f.name }, f.project)).find(x => x.page === f.page) ?? null
|
|
408
|
+
)
|
|
409
|
+
},
|
|
410
|
+
chats: ({ project, ...q } = {}) => list<ChatInfo>('chats', q, project),
|
|
411
|
+
async events({ project, ...q } = {}) {
|
|
412
|
+
return (await each<WpEvent>('/api/events', q, project)).map(e => ({ ...e, kind: kindOf(e) }))
|
|
413
|
+
},
|
|
414
|
+
live,
|
|
415
|
+
subscriptions: ({ project, ...q } = {}) => list<SubscriptionInfo>('subscriptions', q, project),
|
|
416
|
+
agents: ({ project } = {}) => list<AgentInfo>('agents', {}, project),
|
|
417
|
+
listeners: ({ project, ...q } = {}) => each<Listener>('/api/listeners', q, project),
|
|
418
|
+
async anchors(page, { project } = {}) {
|
|
419
|
+
const p = await projectOf(project)
|
|
420
|
+
if (!p) throw new Error('name the project the page is in')
|
|
421
|
+
return request<Anchor[]>(`${await at_(p, '/api/anchors')}${query({ page })}`)
|
|
422
|
+
},
|
|
423
|
+
writePage: (page, markdown, { project } = {}) => write(project, '/api/page', { page, markdown }),
|
|
424
|
+
hold: (ref, reason) => formWrite<{ event: WpEvent }>('hold', ref, { reason }).then(r => r.event),
|
|
425
|
+
release: ref => formWrite<{ event: WpEvent }>('release', ref).then(r => r.event),
|
|
426
|
+
settle: ref => formWrite('settle', ref),
|
|
427
|
+
async handled(events, { project } = {}) {
|
|
428
|
+
const all = Array.isArray(events) ? events : [events]
|
|
429
|
+
// by project: an event from the stream says whose it is
|
|
430
|
+
const byProject = new Map<string | undefined, string[]>()
|
|
431
|
+
for (const e of all) {
|
|
432
|
+
const key = typeof e === 'string' ? project : (e.project ?? project)
|
|
433
|
+
byProject.set(key, [...(byProject.get(key) ?? []), typeof e === 'string' ? e : e.id])
|
|
434
|
+
}
|
|
435
|
+
const out = { handled: [] as WpEvent[], already: [] as string[] }
|
|
436
|
+
for (const [p, ids] of byProject) {
|
|
437
|
+
const r = await write<{ handled: WpEvent[]; already: string[] }>(p, '/api/handled', { ids })
|
|
438
|
+
out.handled.push(...r.handled)
|
|
439
|
+
out.already.push(...r.already)
|
|
440
|
+
}
|
|
441
|
+
return out
|
|
442
|
+
},
|
|
443
|
+
}
|
|
444
|
+
}
|