@hamur/devtools 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +24 -2
  3. package/dist/src/client.js +780 -0
  4. package/dist/src/index.js +1711 -0
  5. package/dist/types/src/apps/locator.d.ts +3 -0
  6. package/dist/types/src/bridge.d.ts +8 -0
  7. package/dist/types/src/client.d.ts +3 -0
  8. package/dist/types/src/dev/analyze.d.ts +31 -0
  9. package/dist/types/src/dev/assets.d.ts +33 -0
  10. package/dist/types/src/dev/authz.d.ts +49 -0
  11. package/dist/types/src/dev/bundle.d.ts +22 -0
  12. package/dist/types/src/dev/config.d.ts +24 -0
  13. package/dist/types/src/dev/handler.d.ts +20 -0
  14. package/dist/types/src/dev/modules.d.ts +28 -0
  15. package/dist/types/src/dev/overview.d.ts +20 -0
  16. package/dist/types/src/dev/processes.d.ts +4 -0
  17. package/dist/types/src/dev/server-routes.d.ts +7 -0
  18. package/dist/types/src/dev/tasks.d.ts +26 -0
  19. package/dist/types/src/dev/timeline.d.ts +20 -0
  20. package/dist/types/src/dev/virtual.d.ts +9 -0
  21. package/dist/types/src/icons.d.ts +24 -0
  22. package/dist/types/src/index.d.ts +8 -0
  23. package/dist/types/src/locator.d.ts +17 -0
  24. package/dist/types/src/mask.d.ts +8 -0
  25. package/dist/types/src/module.d.ts +27 -0
  26. package/dist/types/src/open-in-editor.d.ts +4 -0
  27. package/dist/types/src/options.d.ts +14 -0
  28. package/dist/types/src/panel/document.d.ts +16 -0
  29. package/dist/types/src/panel/groups.d.ts +14 -0
  30. package/dist/types/src/panel/index.d.ts +1 -0
  31. package/dist/types/src/panel/settings.d.ts +69 -0
  32. package/dist/types/src/panel/style.d.ts +1 -0
  33. package/dist/types/src/panel/ui.d.ts +34 -0
  34. package/dist/types/src/server/authz.d.ts +30 -0
  35. package/dist/types/src/server/index.d.ts +3 -0
  36. package/dist/types/src/server/routes.d.ts +6 -0
  37. package/dist/types/src/server/storage.d.ts +56 -0
  38. package/dist/types/src/source-link.d.ts +2 -0
  39. package/dist/types/src/tabs/analyze-model.d.ts +31 -0
  40. package/dist/types/src/tabs/analyze.d.ts +2 -0
  41. package/dist/types/src/tabs/assets.d.ts +11 -0
  42. package/dist/types/src/tabs/audit-model.d.ts +42 -0
  43. package/dist/types/src/tabs/audit.d.ts +2 -0
  44. package/dist/types/src/tabs/authz-model.d.ts +11 -0
  45. package/dist/types/src/tabs/authz.d.ts +2 -0
  46. package/dist/types/src/tabs/config.d.ts +8 -0
  47. package/dist/types/src/tabs/inspect.d.ts +7 -0
  48. package/dist/types/src/tabs/modules.d.ts +4 -0
  49. package/dist/types/src/tabs/overview.d.ts +2 -0
  50. package/dist/types/src/tabs/pages.d.ts +2 -0
  51. package/dist/types/src/tabs/payload.d.ts +6 -0
  52. package/dist/types/src/tabs/plugins-model.d.ts +15 -0
  53. package/dist/types/src/tabs/plugins.d.ts +2 -0
  54. package/dist/types/src/tabs/seo-model.d.ts +36 -0
  55. package/dist/types/src/tabs/seo.d.ts +2 -0
  56. package/dist/types/src/tabs/server-routes.d.ts +2 -0
  57. package/dist/types/src/tabs/storage.d.ts +13 -0
  58. package/dist/types/src/tabs/tasks-model.d.ts +16 -0
  59. package/dist/types/src/tabs/tasks.d.ts +2 -0
  60. package/dist/types/src/tabs/terminals-model.d.ts +53 -0
  61. package/dist/types/src/tabs/terminals.d.ts +2 -0
  62. package/dist/types/src/tabs/timeline-model.d.ts +58 -0
  63. package/dist/types/src/tabs/timeline.d.ts +2 -0
  64. package/dist/types/src/tester.d.ts +43 -0
  65. package/dist/types/src/toolbar/element.d.ts +28 -0
  66. package/dist/types/src/toolbar/shortcut.d.ts +14 -0
  67. package/dist/types/src/toolbar/style.d.ts +3 -0
  68. package/dist/types/src/view-context.d.ts +13 -0
  69. package/package.json +28 -4
  70. package/src/apps/locator.ts +131 -0
  71. package/src/bridge.ts +172 -0
  72. package/src/client.ts +10 -0
  73. package/src/dev/analyze.ts +128 -0
  74. package/src/dev/assets.ts +208 -0
  75. package/src/dev/authz.ts +162 -0
  76. package/src/dev/bundle.ts +91 -0
  77. package/src/dev/config.ts +132 -0
  78. package/src/dev/handler.ts +161 -0
  79. package/src/dev/modules.ts +60 -0
  80. package/src/dev/overview.ts +57 -0
  81. package/src/dev/processes.ts +34 -0
  82. package/src/dev/server-routes.ts +14 -0
  83. package/src/dev/tasks.ts +93 -0
  84. package/src/dev/timeline.ts +43 -0
  85. package/src/dev/virtual.ts +40 -0
  86. package/src/env.d.ts +21 -0
  87. package/src/icons.ts +48 -0
  88. package/src/index.ts +12 -0
  89. package/src/locator.ts +31 -0
  90. package/src/mask.ts +16 -0
  91. package/src/module.ts +352 -0
  92. package/src/open-in-editor.ts +18 -0
  93. package/src/options.ts +36 -0
  94. package/src/panel/document.ts +60 -0
  95. package/src/panel/groups.ts +41 -0
  96. package/src/panel/index.ts +429 -0
  97. package/src/panel/settings.ts +224 -0
  98. package/src/panel/style.ts +321 -0
  99. package/src/panel/ui.ts +52 -0
  100. package/src/server/authz.ts +110 -0
  101. package/src/server/index.ts +25 -0
  102. package/src/server/routes.ts +51 -0
  103. package/src/server/storage.ts +251 -0
  104. package/src/source-link.ts +29 -0
  105. package/src/tabs/analyze-model.ts +97 -0
  106. package/src/tabs/analyze.ts +217 -0
  107. package/src/tabs/assets.ts +375 -0
  108. package/src/tabs/audit-model.ts +216 -0
  109. package/src/tabs/audit.ts +223 -0
  110. package/src/tabs/authz-model.ts +28 -0
  111. package/src/tabs/authz.ts +337 -0
  112. package/src/tabs/config.ts +250 -0
  113. package/src/tabs/inspect.ts +101 -0
  114. package/src/tabs/modules.ts +58 -0
  115. package/src/tabs/overview.ts +104 -0
  116. package/src/tabs/pages.ts +188 -0
  117. package/src/tabs/payload.ts +224 -0
  118. package/src/tabs/plugins-model.ts +44 -0
  119. package/src/tabs/plugins.ts +95 -0
  120. package/src/tabs/seo-model.ts +140 -0
  121. package/src/tabs/seo.ts +162 -0
  122. package/src/tabs/server-routes.ts +469 -0
  123. package/src/tabs/storage.ts +313 -0
  124. package/src/tabs/tasks-model.ts +59 -0
  125. package/src/tabs/tasks.ts +287 -0
  126. package/src/tabs/terminals-model.ts +127 -0
  127. package/src/tabs/terminals.ts +294 -0
  128. package/src/tabs/timeline-model.ts +200 -0
  129. package/src/tabs/timeline.ts +260 -0
  130. package/src/tester.ts +158 -0
  131. package/src/toolbar/element.ts +428 -0
  132. package/src/toolbar/shortcut.ts +56 -0
  133. package/src/toolbar/style.ts +94 -0
  134. package/src/view-context.ts +93 -0
@@ -0,0 +1,313 @@
1
+ import { defineDevtoolsApp } from "hamur/app"
2
+ import { element, tone, UI } from "../panel/ui.ts"
3
+ import type { ItemValue, StorageChange } from "../server/storage.ts"
4
+
5
+ export type EditorMode = "json" | "text" | "hex"
6
+
7
+ const MODES: Array<[EditorMode, string]> = [
8
+ ["json", "JSON"],
9
+ ["text", "Text"],
10
+ ["hex", "Hex"],
11
+ ]
12
+
13
+ const hexOf = (bytes: Uint8Array): string => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")
14
+
15
+ function bytesOf(hex: string): Uint8Array {
16
+ const clean = hex.replace(/\s+/g, "")
17
+ if (clean.length % 2 !== 0 || /[^0-9a-f]/i.test(clean)) throw new Error("Hex is two digits per byte, 0-9 and a-f")
18
+ return Uint8Array.from({ length: clean.length / 2 }, (_, index) =>
19
+ Number.parseInt(clean.slice(index * 2, index * 2 + 2), 16),
20
+ )
21
+ }
22
+
23
+ /** The editor's mode and text for an item as `api/storage/item` answers it. */
24
+ export function editorOf(item: ItemValue): { mode: EditorMode; text: string } {
25
+ if (item.type === "bytes") return { mode: "hex", text: item.value }
26
+ if (item.type === "text") return { mode: "text", text: item.value }
27
+ return { mode: "json", text: JSON.stringify(item.value, null, 2) }
28
+ }
29
+
30
+ /** The editor's text read in `from` and written in `to`: text and hex convert through UTF-8, JSON is kept as its text. */
31
+ export function convertEditor(text: string, from: EditorMode, to: EditorMode): string {
32
+ if (from === to) return text
33
+ if (to === "hex") return hexOf(new TextEncoder().encode(text))
34
+ if (from === "hex") {
35
+ try {
36
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytesOf(text))
37
+ } catch {
38
+ throw new Error("These bytes are not UTF-8 text; keep the Hex mode")
39
+ }
40
+ }
41
+ return text
42
+ }
43
+
44
+ /** The `PUT` body for the editor's text in `mode`; `raw` is kept from the item that was opened. */
45
+ export function itemOf(text: string, mode: EditorMode, raw: boolean): ItemValue {
46
+ const extra = raw ? { raw: true as const } : {}
47
+ if (mode === "hex") return { type: "bytes", value: hexOf(bytesOf(text)), ...extra }
48
+ if (mode === "text") return { type: "text", value: text, ...extra }
49
+ try {
50
+ return { type: "json", value: JSON.parse(text), ...extra }
51
+ } catch (error) {
52
+ throw new Error(`The value must be JSON: ${error instanceof Error ? error.message : String(error)}`)
53
+ }
54
+ }
55
+
56
+ const mark = (button: HTMLElement, on: boolean): void => {
57
+ if (on) button.setAttribute("aria-current", "true")
58
+ else button.removeAttribute("aria-current")
59
+ button.classList.toggle("bg-active", on)
60
+ }
61
+
62
+ const NOTE = `m-0 px-4 py-1 ${UI.hint} empty:hidden`
63
+ const NOTE_FAIL = `m-0 px-4 py-1 ${UI.fail} empty:hidden`
64
+ const LIST = "m-0 p-0 list-none"
65
+ const ITEM = `${UI.listButton} justify-between`
66
+
67
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
68
+
69
+ async function call<T>(path: string, init?: RequestInit): Promise<T> {
70
+ const response = await fetch(`api/storage/${path}`, init)
71
+ if (response.status === 204) return undefined as T
72
+ const body = (await response.json().catch(() => ({}))) as { error?: string }
73
+ if (!response.ok) throw new Error(body.error ?? `api/storage/${path} answered ${response.status}`)
74
+ return body as T
75
+ }
76
+
77
+ const query = (params: Record<string, string>): string => new URLSearchParams(params).toString()
78
+
79
+ export default defineDevtoolsApp({
80
+ async init(canvas, ctx) {
81
+ canvas.className = "flex flex-1 min-h-0"
82
+ const mountList = element("ul", { className: LIST })
83
+ const prefix = element("input", {
84
+ type: "search",
85
+ placeholder: "Prefix",
86
+ name: "prefix",
87
+ className: `${UI.field} flex-1`,
88
+ })
89
+ prefix.setAttribute("aria-label", "Key prefix")
90
+ const keyList = element("ul", { className: LIST })
91
+ const keyNote = element("p", { className: NOTE })
92
+ const editor = element(
93
+ "section",
94
+ { className: "flex-1 min-w-0 overflow-auto p-4" },
95
+ element("p", { className: UI.hint }, "Choose a key"),
96
+ )
97
+ canvas.append(
98
+ element(
99
+ "aside",
100
+ { className: "w-48 flex-none py-1.5 border-r border-line overflow-auto" },
101
+ element("h2", { className: `m-0 ${UI.groupHead}` }, "Mounts"),
102
+ mountList,
103
+ ),
104
+ element(
105
+ "section",
106
+ { className: "w-72 flex-none flex flex-col py-1.5 border-r border-line min-h-0" },
107
+ element("h2", { className: `m-0 ${UI.groupHead}` }, "Keys"),
108
+ element("div", { className: "flex-none flex px-1.5 py-1.5" }, prefix),
109
+ keyNote,
110
+ element("div", { className: "flex-1 min-h-0 overflow-auto" }, keyList),
111
+ ),
112
+ editor,
113
+ )
114
+
115
+ let mount: string | undefined
116
+ let open:
117
+ { key: string; raw: boolean; dirty: boolean; status: HTMLOutputElement; load: () => Promise<void> } | undefined
118
+
119
+ async function loadKeys(): Promise<void> {
120
+ if (mount === undefined) return
121
+ try {
122
+ const { keys, truncated } = await call<{ keys: string[]; truncated: boolean }>(
123
+ `keys?${query({ mount, prefix: prefix.value })}`,
124
+ )
125
+ keyNote.textContent = truncated ? `The first ${keys.length} keys` : keys.length ? "" : "No keys"
126
+ keyNote.className = NOTE
127
+ keyList.replaceChildren(
128
+ ...keys.map((key) => {
129
+ const button = element("button", { type: "button", className: `${ITEM} break-all` }, key)
130
+ button.dataset.key = key
131
+ mark(button, open?.key === key)
132
+ button.addEventListener("click", () => void openItem(key))
133
+ return element("li", { className: "px-1.5" }, button)
134
+ }),
135
+ )
136
+ } catch (error) {
137
+ keyNote.className = NOTE_FAIL
138
+ keyNote.textContent = messageOf(error)
139
+ keyList.replaceChildren()
140
+ }
141
+ }
142
+
143
+ async function openItem(key: string): Promise<void> {
144
+ const at = mount!
145
+ const textarea = element("textarea", { name: "value", rows: 14, spellcheck: false, className: UI.textarea })
146
+ textarea.setAttribute("aria-label", `Value of ${key}`)
147
+ const modeSelect = element(
148
+ "select",
149
+ { name: "mode", className: `${UI.field} w-24` },
150
+ ...MODES.map(([value, label]) => element("option", { value }, label)),
151
+ )
152
+ modeSelect.setAttribute("aria-label", "Mode")
153
+ const status = element("output")
154
+ tone(status, false)
155
+ const save = element("button", { type: "submit", className: UI.primary }, "Save")
156
+ const remove = element("button", { type: "button", className: UI.button }, "Delete")
157
+ remove.dataset.delete = ""
158
+ const form = element(
159
+ "form",
160
+ { className: "flex flex-col gap-2" },
161
+ element("div", { className: "flex items-center gap-1.5" }, modeSelect, save, remove),
162
+ textarea,
163
+ status,
164
+ )
165
+ editor.replaceChildren(
166
+ element("h2", { className: "m-0 mb-2 font-mono text-sm font-medium text-fg break-all" }, key),
167
+ form,
168
+ )
169
+ editor.dataset.key = key
170
+ let mode: EditorMode = "json"
171
+ const state = {
172
+ key,
173
+ raw: false,
174
+ dirty: false,
175
+ status,
176
+ async load() {
177
+ tone(status, false)
178
+ try {
179
+ const item = await call<ItemValue>(`item?${query({ mount: at, key })}`)
180
+ const shown = editorOf(item)
181
+ mode = shown.mode
182
+ modeSelect.value = mode
183
+ textarea.value = shown.text
184
+ state.raw = item.raw === true
185
+ state.dirty = false
186
+ editor.dataset.type = item.type
187
+ } catch (error) {
188
+ tone(status, true)
189
+ status.textContent = messageOf(error)
190
+ }
191
+ },
192
+ }
193
+ open = state
194
+ for (const button of keyList.querySelectorAll<HTMLButtonElement>("button[data-key]"))
195
+ mark(button, button.dataset.key === key)
196
+ textarea.addEventListener("input", () => void (state.dirty = true))
197
+ modeSelect.addEventListener("change", () => {
198
+ const next = modeSelect.value as EditorMode
199
+ try {
200
+ textarea.value = convertEditor(textarea.value, mode, next)
201
+ mode = next
202
+ tone(status, false)
203
+ status.textContent = ""
204
+ } catch (error) {
205
+ modeSelect.value = mode
206
+ tone(status, true)
207
+ status.textContent = messageOf(error)
208
+ }
209
+ })
210
+ form.addEventListener("submit", async (event) => {
211
+ event.preventDefault()
212
+ tone(status, false)
213
+ let item: ItemValue
214
+ try {
215
+ item = itemOf(textarea.value, mode, state.raw)
216
+ } catch (error) {
217
+ tone(status, true)
218
+ status.textContent = messageOf(error)
219
+ return
220
+ }
221
+ save.disabled = true
222
+ try {
223
+ await call(`item?${query({ mount: at, key })}`, {
224
+ method: "PUT",
225
+ headers: { "content-type": "application/json" },
226
+ body: JSON.stringify(item),
227
+ })
228
+ state.dirty = false
229
+ status.textContent = "Saved"
230
+ editor.dataset.saved = ""
231
+ } catch (error) {
232
+ tone(status, true)
233
+ status.textContent = messageOf(error)
234
+ } finally {
235
+ save.disabled = false
236
+ }
237
+ })
238
+ remove.addEventListener("click", async () => {
239
+ remove.disabled = true
240
+ try {
241
+ await call(`item?${query({ mount: at, key })}`, { method: "DELETE" })
242
+ open = undefined
243
+ editor.replaceChildren(element("p", { className: UI.hint }, `Deleted ${key}`))
244
+ delete editor.dataset.key
245
+ await loadKeys()
246
+ } catch (error) {
247
+ tone(status, true)
248
+ status.textContent = messageOf(error)
249
+ remove.disabled = false
250
+ }
251
+ })
252
+ await state.load()
253
+ }
254
+
255
+ function selectMount(name: string): void {
256
+ mount = name
257
+ open = undefined
258
+ editor.replaceChildren(element("p", { className: UI.hint }, "Choose a key"))
259
+ delete editor.dataset.key
260
+ for (const button of mountList.querySelectorAll<HTMLButtonElement>("button[data-mount]"))
261
+ mark(button, button.dataset.mount === name)
262
+ void loadKeys()
263
+ }
264
+
265
+ let typing: ReturnType<typeof setTimeout> | undefined
266
+ prefix.addEventListener("input", () => {
267
+ clearTimeout(typing)
268
+ typing = setTimeout(() => void loadKeys(), 200)
269
+ })
270
+
271
+ let pending: ReturnType<typeof setTimeout> | undefined
272
+ const off = ctx.on("devtools:storage", (data) => {
273
+ const change = data as StorageChange
274
+ if (change.mount !== mount) return
275
+ clearTimeout(pending)
276
+ pending = setTimeout(() => void loadKeys(), 100)
277
+ if (open?.key !== change.key) return
278
+ if (change.op === "remove") {
279
+ tone(open.status, false)
280
+ open.status.textContent = "Removed on the server; Save writes it again"
281
+ } else if (open.dirty) {
282
+ tone(open.status, false)
283
+ open.status.textContent = "Changed on the server; Save overwrites it"
284
+ } else void open.load()
285
+ })
286
+
287
+ try {
288
+ const mounts = await call<Array<{ mount: string; driver: string }>>("mounts")
289
+ mountList.replaceChildren(
290
+ ...mounts.map(({ mount: name, driver }) => {
291
+ const button = element(
292
+ "button",
293
+ { type: "button", className: ITEM },
294
+ element("code", { className: "truncate" }, name),
295
+ element("span", { className: "text-fg-4" }, driver),
296
+ )
297
+ button.dataset.mount = name
298
+ button.addEventListener("click", () => selectMount(name))
299
+ return element("li", { className: "px-1.5" }, button)
300
+ }),
301
+ )
302
+ if (!mounts.length) mountList.replaceWith(element("p", { className: UI.notice }, "No mounts"))
303
+ } catch (error) {
304
+ mountList.replaceWith(element("p", { className: UI.error }, messageOf(error)))
305
+ }
306
+
307
+ return () => {
308
+ off()
309
+ clearTimeout(pending)
310
+ clearTimeout(typing)
311
+ }
312
+ },
313
+ })
@@ -0,0 +1,59 @@
1
+ import type { TaskRunRecord } from "hamur/kit"
2
+
3
+ /** The tab keeps the newest settled runs the runner keeps. */
4
+ export const KEPT_SETTLED = 200
5
+
6
+ export const isSettled = (run: TaskRunRecord): boolean => run.status !== "pending" && run.status !== "running"
7
+
8
+ /** Puts `incoming` into `runs` by id, then drops the oldest settled runs beyond `KEPT_SETTLED`; a settled run is not replaced by an unsettled one. */
9
+ export function mergeRuns(runs: Map<string, TaskRunRecord>, incoming: readonly TaskRunRecord[]): void {
10
+ for (const run of incoming) {
11
+ const known = runs.get(run.id)
12
+ if (known && isSettled(known) && !isSettled(run)) continue
13
+ runs.delete(run.id)
14
+ runs.set(run.id, run)
15
+ }
16
+ const settled = [...runs.values()].filter(isSettled)
17
+ for (const run of settled.slice(0, Math.max(0, settled.length - KEPT_SETTLED))) runs.delete(run.id)
18
+ }
19
+
20
+ /** Newest `createdAt` first. */
21
+ export const newestFirst = (runs: ReadonlyMap<string, TaskRunRecord>): TaskRunRecord[] =>
22
+ [...runs.values()].sort((a, b) => b.createdAt - a.createdAt)
23
+
24
+ /** The `pending` runs, the soonest start first. */
25
+ export const pendingFirst = (runs: ReadonlyMap<string, TaskRunRecord>): TaskRunRecord[] =>
26
+ [...runs.values()]
27
+ .filter((run) => run.status === "pending")
28
+ .sort((a, b) => (a.startsAt ?? a.createdAt) - (b.startsAt ?? b.createdAt))
29
+
30
+ export function durationText(ms: number | undefined): string {
31
+ if (ms === undefined) return "–"
32
+ return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)} s`
33
+ }
34
+
35
+ export function sizeText(bytes: number): string {
36
+ if (bytes < 1024) return `${bytes} B`
37
+ return bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`
38
+ }
39
+
40
+ /** The payload box's text as a request body: empty is no payload, anything else must be JSON. */
41
+ export function payloadBody(text: string): string {
42
+ const trimmed = text.trim()
43
+ if (trimmed === "") return "{}"
44
+ try {
45
+ return JSON.stringify({ payload: JSON.parse(trimmed) })
46
+ } catch (error) {
47
+ throw new Error(`The payload must be JSON: ${error instanceof Error ? error.message : String(error)}`)
48
+ }
49
+ }
50
+
51
+ /** What a failed task endpoint answer says: its `message`, else its text. */
52
+ export function failureText(status: number, body: string): string {
53
+ try {
54
+ const parsed = JSON.parse(body) as { message?: unknown; error?: unknown }
55
+ const message = typeof parsed.message === "string" ? parsed.message : parsed.error
56
+ if (typeof message === "string" && message) return message
57
+ } catch {}
58
+ return body.trim() || `The task endpoint answered ${status}`
59
+ }
@@ -0,0 +1,287 @@
1
+ import { defineDevtoolsApp } from "hamur/app"
2
+ import type { TaskRunRecord } from "hamur/kit"
3
+ import { element, tab, UI } from "../panel/ui.ts"
4
+ import type { TaskRow } from "../dev/tasks.ts"
5
+ import {
6
+ durationText,
7
+ failureText,
8
+ mergeRuns,
9
+ newestFirst,
10
+ payloadBody,
11
+ pendingFirst,
12
+ sizeText,
13
+ } from "./tasks-model.ts"
14
+
15
+ type Part = "tasks" | "runs" | "pending"
16
+
17
+ const PARTS: Array<[Part, string]> = [
18
+ ["tasks", "Tasks"],
19
+ ["runs", "Runs"],
20
+ ["pending", "Pending"],
21
+ ]
22
+ const STATUS_COLORS: Record<string, string> = {
23
+ running: "text-fg",
24
+ done: "text-green",
25
+ failed: "text-red",
26
+ cancelled: "text-fg-3",
27
+ pending: "text-amber",
28
+ }
29
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
30
+ const time = (epoch: number): string => new Date(epoch).toLocaleTimeString()
31
+
32
+ function status(run: TaskRunRecord): HTMLElement {
33
+ const node = element(
34
+ "span",
35
+ { className: `font-mono text-xs ${STATUS_COLORS[run.status] ?? "text-fg-3"}` },
36
+ run.status,
37
+ )
38
+ node.dataset.status = run.status
39
+ return node
40
+ }
41
+
42
+ export default defineDevtoolsApp({
43
+ async init(canvas, ctx) {
44
+ canvas.className = "flex flex-col flex-1 min-h-0"
45
+ const strip = element("div", {
46
+ className: "flex-none flex gap-0.5 px-3 pt-1 border-b border-line overflow-x-auto",
47
+ role: "tablist",
48
+ })
49
+ strip.setAttribute("aria-label", "Task views")
50
+ const note = element("p", { className: `m-0 px-4 py-1 ${UI.fail} empty:hidden` })
51
+ note.dataset.error = ""
52
+ const body = element("div", { className: "flex-1 min-h-0 overflow-auto" })
53
+ canvas.append(strip, note, body)
54
+
55
+ const runs = new Map<string, TaskRunRecord>()
56
+ const open = new Set<string>()
57
+ let tasks: TaskRow[] = []
58
+ let part: Part = "tasks"
59
+ const outputs = new Map<string, { text: string; failed: boolean }>()
60
+
61
+ function paintStrip(): void {
62
+ const pending = pendingFirst(runs).length
63
+ strip.replaceChildren(
64
+ ...PARTS.map(([name, title]) => {
65
+ const button = element(
66
+ "button",
67
+ { type: "button", role: "tab", className: tab(name === part) },
68
+ name === "pending" && pending ? `${title} (${pending})` : title,
69
+ )
70
+ button.dataset.part = name
71
+ button.setAttribute("aria-selected", String(name === part))
72
+ button.addEventListener("click", () => {
73
+ part = name
74
+ paint()
75
+ })
76
+ return button
77
+ }),
78
+ )
79
+ ctx.setBadge(pending ? String(pending) : undefined)
80
+ }
81
+
82
+ function taskItem(task: TaskRow): HTMLElement {
83
+ const payload = element("textarea", {
84
+ className: `${UI.textarea} min-h-8`,
85
+ rows: 1,
86
+ placeholder: "Payload (JSON)",
87
+ })
88
+ payload.setAttribute("aria-label", `Payload of ${task.name}`)
89
+ const result = element("pre", { className: "m-0 whitespace-pre-wrap break-all font-mono text-xs empty:hidden" })
90
+ const shown = outputs.get(task.name)
91
+ if (shown) {
92
+ result.textContent = shown.text
93
+ result.className += shown.failed ? " text-red" : " text-fg-2"
94
+ }
95
+ const run = element("button", { type: "button", className: UI.button }, "Run")
96
+ run.addEventListener("click", () => {
97
+ void (async () => {
98
+ run.disabled = true
99
+ let output: { text: string; failed: boolean }
100
+ try {
101
+ const response = await fetch(`../tasks/${encodeURIComponent(task.name)}`, {
102
+ method: "POST",
103
+ headers: { "content-type": "application/json" },
104
+ body: payloadBody(payload.value),
105
+ })
106
+ const text = await response.text()
107
+ output = response.ok ? { text, failed: false } : { text: failureText(response.status, text), failed: true }
108
+ } catch (error) {
109
+ output = { text: messageOf(error), failed: true }
110
+ }
111
+ outputs.set(task.name, output)
112
+ result.textContent = output.text
113
+ result.className = `m-0 whitespace-pre-wrap break-all font-mono text-xs ${output.failed ? "text-red" : "text-fg-2"}`
114
+ run.disabled = false
115
+ })()
116
+ })
117
+ const item = element(
118
+ "li",
119
+ { className: "flex flex-col gap-1.5 px-4 py-2.5 border-b border-line" },
120
+ element(
121
+ "div",
122
+ { className: "flex items-center gap-2" },
123
+ element("strong", { className: "font-mono text-sm font-medium text-fg" }, task.name),
124
+ ...(task.listener === undefined
125
+ ? []
126
+ : [
127
+ element("span", { className: UI.chip, title: `Runs on the event ${task.listener}` }, "queued listener"),
128
+ ]),
129
+ run,
130
+ ),
131
+ ...(task.description ? [element("span", { className: UI.hint }, task.description)] : []),
132
+ element("code", { className: "font-mono text-xs text-fg-3" }, task.file),
133
+ ...task.schedules.map(({ cron, next }) =>
134
+ element(
135
+ "span",
136
+ { className: "font-mono text-xs text-fg-2" },
137
+ next === undefined ? cron : `${cron} next ${new Date(next).toLocaleString()}`,
138
+ ),
139
+ ),
140
+ payload,
141
+ result,
142
+ )
143
+ item.dataset.name = task.name
144
+ return item
145
+ }
146
+
147
+ function runItem(run: TaskRunRecord): HTMLElement {
148
+ const details = element("details", { className: "border-b border-line" })
149
+ details.dataset.id = run.id
150
+ details.open = open.has(run.id)
151
+ details.addEventListener("toggle", () => {
152
+ if (details.open) open.add(run.id)
153
+ else open.delete(run.id)
154
+ })
155
+ const summary = element(
156
+ "summary",
157
+ { className: "flex items-center gap-3 min-h-9 px-4 cursor-pointer hover:bg-hover text-sm" },
158
+ element("code", { className: "flex-none w-16 font-mono text-xs text-fg-3" }, run.id.slice(0, 8)),
159
+ element("strong", { className: "flex-1 min-w-0 font-mono text-sm font-medium text-fg break-all" }, run.name),
160
+ element("span", { className: "flex-none w-16 font-mono text-xs text-fg-3" }, run.trigger),
161
+ status(run),
162
+ element(
163
+ "span",
164
+ { className: "flex-none w-20 text-xs text-fg-3" },
165
+ run.startedAt === undefined ? "–" : time(run.startedAt),
166
+ ),
167
+ element("span", { className: "flex-none w-16 text-xs text-fg-3" }, durationText(run.duration)),
168
+ element("span", { className: "flex-none w-16 text-xs text-fg-3" }, sizeText(run.payloadSize)),
169
+ )
170
+ const lines: Array<[string, string | undefined]> = [
171
+ ["Payload", run.payload],
172
+ ["Result", run.result],
173
+ ["Error", run.error && [run.error.message, run.error.stack].filter(Boolean).join("\n")],
174
+ ]
175
+ details.append(
176
+ summary,
177
+ ...lines.flatMap(([label, text]) =>
178
+ text === undefined
179
+ ? []
180
+ : [
181
+ element("span", { className: `block mx-4 mt-1 ${UI.label}` }, label),
182
+ element(
183
+ "pre",
184
+ {
185
+ className: `m-0 mx-4 mb-2 px-3 py-2 rounded-lg bg-field font-mono text-xs overflow-auto ${label === "Error" ? "text-red" : "text-fg-2"}`,
186
+ },
187
+ text,
188
+ ),
189
+ ],
190
+ ),
191
+ )
192
+ return details
193
+ }
194
+
195
+ async function cancel(run: TaskRunRecord, button: HTMLButtonElement): Promise<void> {
196
+ button.disabled = true
197
+ try {
198
+ const response = await fetch("api/tasks/cancel", {
199
+ method: "POST",
200
+ headers: { "content-type": "application/json" },
201
+ body: JSON.stringify({ id: run.id }),
202
+ })
203
+ if (!response.ok)
204
+ throw new Error(
205
+ ((await response.json().catch(() => ({}))) as { error?: string }).error ??
206
+ `api/tasks/cancel answered ${response.status}`,
207
+ )
208
+ note.textContent = ""
209
+ } catch (error) {
210
+ note.textContent = messageOf(error)
211
+ button.disabled = false
212
+ }
213
+ }
214
+
215
+ function pendingItem(run: TaskRunRecord): HTMLElement {
216
+ const button = element("button", { type: "button", className: UI.button }, "Cancel")
217
+ button.addEventListener("click", () => void cancel(run, button))
218
+ const item = element(
219
+ "li",
220
+ { className: "flex items-center gap-3 min-h-9 px-4 border-b border-line text-sm" },
221
+ element("strong", { className: "flex-1 min-w-0 font-mono text-sm font-medium text-fg break-all" }, run.name),
222
+ element("code", { className: "flex-none font-mono text-xs text-fg-3" }, run.id.slice(0, 8)),
223
+ element("span", { className: "flex-none text-xs text-fg-2" }, `starts ${time(run.startsAt ?? run.createdAt)}`),
224
+ element("span", { className: "flex-none w-16 text-xs text-fg-3" }, sizeText(run.payloadSize)),
225
+ button,
226
+ )
227
+ item.dataset.id = run.id
228
+ return item
229
+ }
230
+
231
+ function paint(): void {
232
+ paintStrip()
233
+ if (part === "tasks")
234
+ body.replaceChildren(
235
+ tasks.length
236
+ ? element("ul", { className: "m-0 p-0 list-none" }, ...tasks.map(taskItem))
237
+ : element("p", { className: UI.notice }, "No task yet"),
238
+ )
239
+ else if (part === "runs") {
240
+ const list = newestFirst(runs)
241
+ body.replaceChildren(
242
+ list.length ? element("div", {}, ...list.map(runItem)) : element("p", { className: UI.notice }, "No run yet"),
243
+ )
244
+ } else {
245
+ const list = pendingFirst(runs)
246
+ body.replaceChildren(
247
+ list.length
248
+ ? element("ul", { className: "m-0 p-0 list-none" }, ...list.map(pendingItem))
249
+ : element("p", { className: UI.notice }, "No pending run"),
250
+ )
251
+ }
252
+ }
253
+
254
+ let queued: ReturnType<typeof setTimeout> | undefined
255
+ const repaint = () => {
256
+ if (queued !== undefined) return
257
+ queued = setTimeout(() => {
258
+ queued = undefined
259
+ if (part !== "tasks") paint()
260
+ else paintStrip()
261
+ }, 50)
262
+ }
263
+
264
+ const off = ctx.on("devtools:task", (data) => {
265
+ const pushed = (data as { runs?: TaskRunRecord[] }).runs
266
+ if (!Array.isArray(pushed)) return
267
+ mergeRuns(runs, pushed)
268
+ repaint()
269
+ })
270
+
271
+ try {
272
+ tasks = (await ctx.rpc<{ tasks: TaskRow[] }>("devtools:tasks")).tasks
273
+ const response = await fetch("api/tasks/runs")
274
+ const answer = (await response.json()) as { runs?: TaskRunRecord[]; error?: string }
275
+ if (!response.ok) throw new Error(answer.error ?? `api/tasks/runs answered ${response.status}`)
276
+ mergeRuns(runs, answer.runs ?? [])
277
+ } catch (error) {
278
+ note.textContent = messageOf(error)
279
+ }
280
+ paint()
281
+
282
+ return () => {
283
+ off()
284
+ clearTimeout(queued)
285
+ }
286
+ },
287
+ })