@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,188 @@
1
+ import { defineDevtoolsApp } from "hamur/app"
2
+ import type { DevRouteMatch, DevRouteTable } from "hamur/kit"
3
+ import { element, UI } from "../panel/ui.ts"
4
+ import { sourceLink } from "../source-link.ts"
5
+
6
+ type Page = DevRouteTable["pages"][number]
7
+
8
+ const NONE = "–"
9
+ const POLL_MS = 500
10
+ const COLUMNS: Array<[string, string, string]> = [
11
+ ["name", "Name", "text-sm font-medium text-fg"],
12
+ ["path", "Pattern", "font-mono text-xs text-fg-2 whitespace-nowrap"],
13
+ ["file", "File", "font-mono text-xs text-fg-4"],
14
+ ["layout", "Layout", "text-xs text-fg-3"],
15
+ ["middleware", "Middleware", "text-xs text-fg-3"],
16
+ ["loader", "Loader", "font-mono text-xs text-fg-4"],
17
+ ["rules", "Route rules", "font-mono text-xs text-fg-3"],
18
+ ["copies", "i18n copies", "font-mono text-xs text-fg-3"],
19
+ ]
20
+
21
+ const rulesOf = (page: Page): string => (Object.keys(page.rules).length ? JSON.stringify(page.rules) : NONE)
22
+
23
+ function chainView(match: DevRouteMatch | null | undefined, data: Record<string, unknown> | undefined): HTMLElement {
24
+ const box = element("div", { className: "flex flex-col gap-1" })
25
+ if (!match) {
26
+ box.append(element("p", { className: "m-0 text-sm text-fg-3" }, "No page matches"))
27
+ return box
28
+ }
29
+ const list = element("ol", { className: "m-0 p-0 list-none flex flex-col gap-1" })
30
+ for (const route of match.chain) {
31
+ const item = element(
32
+ "li",
33
+ { className: UI.row },
34
+ element("span", { className: `${UI.rowKey} truncate` }, route.name),
35
+ element("span", { className: `${UI.rowValue} font-mono text-xs` }, route.path),
36
+ )
37
+ item.dataset.route = route.name
38
+ const value = data?.[route.name]
39
+ if (value !== undefined) {
40
+ item.className = "flex flex-col gap-1 text-sm"
41
+ item.append(
42
+ element(
43
+ "pre",
44
+ { className: "m-0 px-3 py-2.5 rounded-lg bg-field font-mono text-xs text-fg-2 whitespace-pre-wrap" },
45
+ JSON.stringify(value, null, 2),
46
+ ),
47
+ )
48
+ }
49
+ list.append(item)
50
+ }
51
+ const params = element(
52
+ "p",
53
+ { className: "m-0 font-mono text-xs text-fg-3" },
54
+ Object.keys(match.params).length
55
+ ? Object.entries(match.params)
56
+ .map(([name, value]) => `${name}: ${JSON.stringify(value)}`)
57
+ .join(", ")
58
+ : "no params",
59
+ )
60
+ params.dataset.params = ""
61
+ box.append(list, params)
62
+ return box
63
+ }
64
+
65
+ export default defineDevtoolsApp({
66
+ async init(canvas, ctx) {
67
+ canvas.className = "flex flex-1 min-h-0"
68
+ const hook = ctx.page
69
+ const response = await fetch("api/routes")
70
+ const table = (await response.json()) as DevRouteTable & { error?: string }
71
+ if (!response.ok) throw new Error(table.error ?? `api/routes answered ${response.status}`)
72
+
73
+ const input = element("input", {
74
+ type: "text",
75
+ name: "path",
76
+ placeholder: "/blog/a/b",
77
+ className: `${UI.field} w-64 font-mono`,
78
+ })
79
+ input.setAttribute("aria-label", "Path to match")
80
+ const form = element(
81
+ "form",
82
+ { className: UI.strip },
83
+ input,
84
+ element("button", { type: "submit", className: UI.button }, "Match"),
85
+ element("span", { className: "flex-1" }),
86
+ element("span", { className: "text-xs text-fg-4 tabular-nums" }, `${table.pages.length} pages`),
87
+ )
88
+ const result = element("div")
89
+ result.dataset.result = ""
90
+
91
+ const status = element("p", { className: "m-0 text-xs text-fg-3" })
92
+ status.dataset.status = ""
93
+ const current = element("div")
94
+ current.dataset.current = ""
95
+
96
+ const rows = new Map<string, HTMLTableRowElement>()
97
+ const body = element("tbody")
98
+ for (const page of table.pages) {
99
+ const values: Record<string, string | Node> = {
100
+ name: page.name,
101
+ path: page.path,
102
+ file: sourceLink(page.file),
103
+ layout: page.layout ?? NONE,
104
+ middleware: page.middleware.length ? page.middleware.join(", ") : NONE,
105
+ loader: page.loader ? sourceLink(page.loader) : NONE,
106
+ rules: rulesOf(page),
107
+ copies: page.copies?.length ? page.copies.map((copy) => `${copy.locale} ${copy.path}`).join(", ") : NONE,
108
+ }
109
+ const row = element("tr", { className: `${UI.tr} cursor-pointer` })
110
+ row.dataset.name = page.name
111
+ for (const [key, , look] of COLUMNS) {
112
+ const td = element("td", { className: `${UI.td} ${look}` }, values[key]!)
113
+ td.dataset.col = key
114
+ row.append(td)
115
+ }
116
+ row.addEventListener("click", () => {
117
+ if (!/[:*]/.test(page.path) && hook) void hook.router.navigate(page.path)
118
+ else input.value = page.path
119
+ })
120
+ rows.set(page.name, row)
121
+ body.append(row)
122
+ }
123
+ const grid = element(
124
+ "table",
125
+ { className: "w-full border-collapse" },
126
+ element(
127
+ "thead",
128
+ { className: "sticky top-0 bg-panel" },
129
+ element("tr", {}, ...COLUMNS.map(([, title]) => element("th", { className: UI.th }, title))),
130
+ ),
131
+ body,
132
+ )
133
+
134
+ form.addEventListener("submit", async (event) => {
135
+ event.preventDefault()
136
+ result.replaceChildren(
137
+ element("h2", { className: `m-0 ${UI.label}` }, "Match"),
138
+ chainView(await ctx.rpc<DevRouteMatch | null>("devtools:match", { path: input.value }), undefined),
139
+ )
140
+ })
141
+
142
+ let shown = ""
143
+ const refresh = async () => {
144
+ if (!hook) {
145
+ status.textContent = "Open the panel from the app's toolbar to see its current route."
146
+ return
147
+ }
148
+ const route = hook.router.current()
149
+ status.textContent = `Current page ${route.path}${hook.router.pending() ? " (navigation pending)" : ""}`
150
+ if (route.path === shown) return
151
+ shown = route.path
152
+ const match = await ctx.rpc<DevRouteMatch | null>("devtools:match", { path: route.path })
153
+ const names = new Set(match?.chain.map((record) => record.name))
154
+ for (const [name, row] of rows) {
155
+ const on = names.has(name)
156
+ row.classList.toggle("bg-active", on)
157
+ row.toggleAttribute("data-current", on)
158
+ }
159
+ current.replaceChildren(
160
+ chainView(match, Object.fromEntries(route.matches.map((matched) => [matched.name, matched.data]))),
161
+ )
162
+ }
163
+ await refresh()
164
+ const timer = setInterval(() => void refresh().catch(() => undefined), POLL_MS)
165
+
166
+ canvas.append(
167
+ element(
168
+ "div",
169
+ { className: "flex-1 min-w-0 flex flex-col" },
170
+ form,
171
+ element("div", { className: "flex-1 min-h-0 overflow-auto px-1.5 pb-2" }, grid),
172
+ ),
173
+ element(
174
+ "aside",
175
+ { className: "w-80 flex-none flex flex-col gap-5 p-4 border-l border-line overflow-auto" },
176
+ element(
177
+ "div",
178
+ { className: "flex flex-col gap-1" },
179
+ element("h2", { className: `m-0 ${UI.label}` }, "Current page"),
180
+ status,
181
+ current,
182
+ ),
183
+ result,
184
+ ),
185
+ )
186
+ return () => clearInterval(timer)
187
+ },
188
+ })
@@ -0,0 +1,224 @@
1
+ import { defineDevtoolsApp, type DevtoolsCurrentRoute, type DevtoolsPage, type DevtoolsPayload } from "hamur/app"
2
+ import { element, UI } from "../panel/ui.ts"
3
+
4
+ const POLL_MS = 500
5
+ const NONE = "–"
6
+
7
+ /** A value as the tab shows it: JSON, or its string form when JSON cannot write it. */
8
+ export function shown(value: unknown, indent?: number): string {
9
+ if (value === undefined) return "undefined"
10
+ try {
11
+ return JSON.stringify(value, null, indent) ?? String(value)
12
+ } catch {
13
+ return String(value)
14
+ }
15
+ }
16
+
17
+ /** The text typed for a `useState` value, read as JSON; a parse error names the key. */
18
+ export function parseStateValue(key: string, text: string): unknown {
19
+ try {
20
+ return JSON.parse(text)
21
+ } catch (error) {
22
+ throw new Error(
23
+ `The value of ${JSON.stringify(key)} must be JSON: ${error instanceof Error ? error.message : String(error)}`,
24
+ )
25
+ }
26
+ }
27
+
28
+ const errorText = (error: unknown): string =>
29
+ typeof error === "object" && error !== null && typeof (error as { message?: unknown }).message === "string"
30
+ ? (error as { message: string }).message
31
+ : shown(error)
32
+
33
+ function section(name: string, title: string, count: number, ...children: Node[]): HTMLElement {
34
+ const box = element(
35
+ "section",
36
+ {},
37
+ element(
38
+ "h2",
39
+ { className: `m-0 ${UI.groupHead}` },
40
+ element("span", { className: "font-medium text-fg-2" }, title),
41
+ element("span", { className: "text-fg-4" }, String(count)),
42
+ ),
43
+ ...children,
44
+ )
45
+ box.dataset.section = name
46
+ return box
47
+ }
48
+
49
+ function table(heads: string[], rows: HTMLTableRowElement[]): HTMLTableElement {
50
+ return element(
51
+ "table",
52
+ { className: "w-full border-collapse" },
53
+ element("thead", {}, element("tr", {}, ...heads.map((head) => element("th", { className: UI.th }, head)))),
54
+ element("tbody", {}, ...rows),
55
+ )
56
+ }
57
+
58
+ function cell(key: string, look: string, ...children: (Node | string)[]): HTMLTableCellElement {
59
+ const td = element("td", { className: `${UI.td} ${look}` }, ...children)
60
+ td.dataset.col = key
61
+ return td
62
+ }
63
+
64
+ const KEY = "font-mono text-sm font-medium text-fg"
65
+ const VALUE = "font-mono text-xs text-fg-2"
66
+
67
+ function loaderSection(matches: DevtoolsCurrentRoute["matches"]): HTMLElement {
68
+ const list = element(
69
+ "ol",
70
+ { className: "m-0 p-0 list-none" },
71
+ ...matches.map((match) => {
72
+ const item = element(
73
+ "li",
74
+ { className: "flex flex-col gap-1 px-4 py-1.5" },
75
+ element("span", { className: "font-mono text-xs text-fg-3" }, `${match.name} ${match.path}`),
76
+ element(
77
+ "pre",
78
+ { className: "m-0 px-3 py-2.5 rounded-lg bg-field font-mono text-xs text-fg-2 whitespace-pre-wrap" },
79
+ match.data === undefined ? "no loader data" : shown(match.data, 2),
80
+ ),
81
+ )
82
+ item.dataset.route = match.name
83
+ return item
84
+ }),
85
+ )
86
+ return section(
87
+ "data",
88
+ "Loader data",
89
+ matches.length,
90
+ matches.length ? list : element("p", { className: UI.notice }, "No route matches"),
91
+ )
92
+ }
93
+
94
+ function stateSection(hook: DevtoolsPage, state: Record<string, unknown>): HTMLElement {
95
+ const rows = Object.entries(state).map(([key, value]) => {
96
+ const input = element("input", {
97
+ type: "text",
98
+ name: "value",
99
+ value: shown(value),
100
+ className: `${UI.field} flex-1 font-mono`,
101
+ })
102
+ input.setAttribute("aria-label", `Value of ${key}`)
103
+ const problem = element("output", { className: `${UI.fail} empty:hidden` })
104
+ problem.dataset.error = ""
105
+ const form = element(
106
+ "form",
107
+ { className: "flex items-center gap-1.5" },
108
+ input,
109
+ element("button", { type: "submit", className: UI.button }, "Set"),
110
+ problem,
111
+ )
112
+ form.addEventListener("submit", (event) => {
113
+ event.preventDefault()
114
+ try {
115
+ hook.setState(key, parseStateValue(key, input.value))
116
+ problem.textContent = ""
117
+ input.blur()
118
+ } catch (error) {
119
+ problem.textContent = error instanceof Error ? error.message : String(error)
120
+ }
121
+ })
122
+ const row = element("tr", { className: UI.tr }, cell("key", KEY, key), cell("value", "", form))
123
+ row.dataset.state = key
124
+ return row
125
+ })
126
+ return section(
127
+ "state",
128
+ "useState",
129
+ rows.length,
130
+ rows.length ? table(["Key", "Value"], rows) : element("p", { className: UI.notice }, "No useState keys"),
131
+ )
132
+ }
133
+
134
+ function asyncSection(
135
+ hook: DevtoolsPage,
136
+ entries: DevtoolsPayload["asyncData"],
137
+ failed: Map<string, string>,
138
+ repaint: () => void,
139
+ ): HTMLElement {
140
+ const rows = entries.map(({ key, status, error }) => {
141
+ const button = element("button", { type: "button", className: UI.button }, "Refresh")
142
+ button.dataset.refresh = ""
143
+ button.addEventListener("click", () => {
144
+ button.disabled = true
145
+ failed.delete(key)
146
+ hook.refresh(key).then(
147
+ () => repaint(),
148
+ (reason: unknown) => {
149
+ failed.set(key, errorText(reason))
150
+ repaint()
151
+ },
152
+ )
153
+ })
154
+ const row = element(
155
+ "tr",
156
+ { className: UI.tr },
157
+ cell("key", KEY, key),
158
+ cell("status", "text-xs text-fg-3", status),
159
+ cell("error", `${VALUE} break-words`, error === undefined ? (failed.get(key) ?? NONE) : errorText(error)),
160
+ cell("refresh", "text-right", button),
161
+ )
162
+ row.dataset.async = key
163
+ return row
164
+ })
165
+ return section(
166
+ "async",
167
+ "Async data",
168
+ rows.length,
169
+ rows.length
170
+ ? table(["Key", "Status", "Error", ""], rows)
171
+ : element("p", { className: UI.notice }, "No async-data entries"),
172
+ )
173
+ }
174
+
175
+ export default defineDevtoolsApp({
176
+ init(canvas, ctx) {
177
+ const hook = ctx.page
178
+ if (!hook) {
179
+ const config = JSON.parse(document.getElementById("hamur-devtools-config")!.textContent!) as {
180
+ shortcut: string | false
181
+ }
182
+ canvas.append(
183
+ element(
184
+ "p",
185
+ { className: UI.notice },
186
+ `Open this tab from the app page${config.shortcut === false ? "" : ` (${config.shortcut})`}`,
187
+ ),
188
+ )
189
+ return
190
+ }
191
+ canvas.className = "flex flex-col flex-1 min-h-0"
192
+ const bytes = element("span", { className: "text-xs text-fg-3 tabular-nums" })
193
+ bytes.dataset.bytes = ""
194
+ const data = element("div", { className: "flex-1 min-w-0 pb-2" })
195
+ const state = element("div")
196
+ const entries = element("div")
197
+ canvas.append(
198
+ element("div", { className: UI.strip }, bytes),
199
+ element(
200
+ "div",
201
+ { className: "flex-1 min-h-0 flex overflow-auto" },
202
+ data,
203
+ element("aside", { className: "w-96 flex-none border-l border-line pb-2" }, state, entries),
204
+ ),
205
+ )
206
+ const failed = new Map<string, string>()
207
+ let last = ""
208
+ const paint = (force = false) => {
209
+ const payload = hook.payload()
210
+ const route = hook.router.current()
211
+ const snapshot = shown({ payload, matches: route.matches, failed: [...failed] })
212
+ if (!force && snapshot === last) return
213
+ const editing = document.activeElement instanceof HTMLInputElement && state.contains(document.activeElement)
214
+ last = editing ? "" : snapshot
215
+ bytes.textContent = `${payload.bytes} bytes`
216
+ data.replaceChildren(loaderSection(route.matches))
217
+ if (!editing) state.replaceChildren(stateSection(hook, payload.state))
218
+ entries.replaceChildren(asyncSection(hook, payload.asyncData, failed, () => paint(true)))
219
+ }
220
+ paint()
221
+ const timer = setInterval(() => paint(), POLL_MS)
222
+ return () => clearInterval(timer)
223
+ },
224
+ })
@@ -0,0 +1,44 @@
1
+ import type { PluginsAnswer } from "../dev/modules.ts"
2
+ import type { MarkLike } from "./timeline-model.ts"
3
+
4
+ export interface PluginRow {
5
+ kind: "app" | "server"
6
+ name: string
7
+ file: string
8
+ order: number
9
+ mode?: string
10
+ /** The page's `hamur:plugin:<name>` measure in milliseconds; `null` for a server plugin and an app plugin the page has not run. */
11
+ ms: number | null
12
+ }
13
+
14
+ const PREFIX = "hamur:plugin:"
15
+
16
+ /** The setup time of each app plugin the page ran, by name; a plugin measured twice (a reload of the page's app) keeps the latest. */
17
+ export function pluginTimes(marks: readonly MarkLike[]): Map<string, number> {
18
+ const times = new Map<string, number>()
19
+ for (const mark of [...marks].sort((a, b) => a.startTime - b.startTime))
20
+ if (mark.name.startsWith(PREFIX)) times.set(mark.name.slice(PREFIX.length), mark.duration)
21
+ return times
22
+ }
23
+
24
+ /** App plugins in run order with their measured setup time, then server plugins in the order `defineServer` lists them. */
25
+ export function pluginRows(answer: PluginsAnswer, marks: readonly MarkLike[]): PluginRow[] {
26
+ const times = pluginTimes(marks)
27
+ return [
28
+ ...answer.app.map((plugin): PluginRow => ({
29
+ kind: "app",
30
+ name: plugin.name,
31
+ file: plugin.file,
32
+ order: plugin.order,
33
+ mode: plugin.mode,
34
+ ms: plugin.mode === "server" ? null : (times.get(plugin.name) ?? null),
35
+ })),
36
+ ...answer.server.map((plugin, order): PluginRow => ({
37
+ kind: "server",
38
+ name: plugin.module ? `${plugin.file} (${plugin.module})` : plugin.file,
39
+ file: plugin.file,
40
+ order,
41
+ ms: null,
42
+ })),
43
+ ]
44
+ }
@@ -0,0 +1,95 @@
1
+ import { defineDevtoolsApp, type DevtoolsPage } from "hamur/app"
2
+ import type { PluginsAnswer } from "../dev/modules.ts"
3
+ import { element, UI } from "../panel/ui.ts"
4
+ import { pluginRows, type PluginRow } from "./plugins-model.ts"
5
+ import { formatMs, type MarkLike } from "./timeline-model.ts"
6
+
7
+ const POLL_MS = 1000
8
+
9
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
10
+
11
+ function rowElement(row: PluginRow, slowest: number): HTMLTableRowElement {
12
+ const time = element("td", { className: `${UI.td} w-40 font-mono text-xs text-fg-2` })
13
+ if (row.ms !== null) {
14
+ const bar = element("i", { className: "block h-1 mt-1 rounded-full bg-accent" })
15
+ bar.style.width = `${Math.max(2, (row.ms / slowest) * 100)}%`
16
+ time.append(element("span", { className: "tabular-nums" }, formatMs(row.ms)), bar)
17
+ } else time.append("–")
18
+ const tr = element(
19
+ "tr",
20
+ { className: UI.tr },
21
+ element("td", { className: `${UI.td} font-mono text-sm font-medium text-fg` }, row.name),
22
+ element("td", { className: `${UI.td} text-xs text-fg-3` }, row.kind === "app" ? `app (${row.mode})` : "server"),
23
+ element("td", { className: `${UI.td} font-mono text-xs text-fg-4 break-all` }, row.file),
24
+ element("td", { className: `${UI.td} font-mono text-xs text-fg-3 tabular-nums` }, String(row.order)),
25
+ time,
26
+ )
27
+ tr.dataset.kind = row.kind
28
+ tr.dataset.name = row.name
29
+ if (row.ms !== null) tr.dataset.ms = String(row.ms)
30
+ return tr
31
+ }
32
+
33
+ export default defineDevtoolsApp({
34
+ init(canvas, ctx) {
35
+ const page: DevtoolsPage | undefined = ctx.page
36
+ if (!page) {
37
+ canvas.append(element("p", { className: UI.notice }, "Open this tab from the app page"))
38
+ return
39
+ }
40
+ canvas.className = "flex flex-col flex-1 min-h-0"
41
+ let answer: PluginsAnswer | undefined
42
+ let last = ""
43
+ const note = element("p", { className: `m-0 px-4 py-1 ${UI.fail} empty:hidden` })
44
+ note.dataset.error = ""
45
+ const body = element("div", { className: "flex-1 min-h-0 overflow-auto px-1.5 pb-2" })
46
+ canvas.append(note, body)
47
+
48
+ async function load(): Promise<void> {
49
+ try {
50
+ const response = await fetch("api/plugins")
51
+ const found = (await response.json()) as PluginsAnswer & { error?: string }
52
+ if (!response.ok) throw new Error(found.error ?? `api/plugins answered ${response.status}`)
53
+ answer = found
54
+ note.textContent = ""
55
+ } catch (error) {
56
+ note.textContent = messageOf(error)
57
+ }
58
+ }
59
+
60
+ function paint(): void {
61
+ if (!answer) return
62
+ const rows = pluginRows(answer, page!.marks() as unknown as MarkLike[])
63
+ const snapshot = JSON.stringify(rows)
64
+ if (snapshot === last) return
65
+ last = snapshot
66
+ if (!rows.length) return void body.replaceChildren(element("p", { className: UI.notice }, "No plugins"))
67
+ const slowest = Math.max(1, ...rows.map((row) => row.ms ?? 0))
68
+ const head = element(
69
+ "thead",
70
+ { className: "sticky top-0 bg-panel" },
71
+ element(
72
+ "tr",
73
+ {},
74
+ ...["Name", "Kind", "File", "Order", "Setup"].map((title) => element("th", { className: UI.th }, title)),
75
+ ),
76
+ )
77
+ body.replaceChildren(
78
+ element(
79
+ "table",
80
+ { className: "w-full border-collapse" },
81
+ head,
82
+ element("tbody", {}, ...rows.map((row) => rowElement(row, slowest))),
83
+ ),
84
+ )
85
+ }
86
+
87
+ void load().then(paint)
88
+ const stop = page.on("mark", paint)
89
+ const timer = setInterval(paint, POLL_MS)
90
+ return () => {
91
+ stop()
92
+ clearInterval(timer)
93
+ }
94
+ },
95
+ })
@@ -0,0 +1,140 @@
1
+ export interface HeadEntry {
2
+ tag: string
3
+ attrs: Record<string, string>
4
+ text?: string
5
+ }
6
+
7
+ export const NETWORKS = ["x", "facebook", "linkedin", "slack"] as const
8
+ export type Network = (typeof NETWORKS)[number]
9
+
10
+ export const NETWORK_TITLES: Record<Network, string> = {
11
+ x: "X",
12
+ facebook: "Facebook",
13
+ linkedin: "LinkedIn",
14
+ slack: "Slack",
15
+ }
16
+
17
+ export interface SeoCheck {
18
+ name: string
19
+ value?: string
20
+ /** A required check with no value is reported as missing. */
21
+ required: boolean
22
+ }
23
+
24
+ export interface SeoCard {
25
+ network: Network
26
+ /** The host the card shows. */
27
+ domain: string
28
+ title?: string
29
+ description?: string
30
+ /** An absolute URL. */
31
+ image?: string
32
+ /** Slack's `og:site_name`, else the domain. */
33
+ siteName?: string
34
+ layout: "large" | "small"
35
+ }
36
+
37
+ export interface SeoReport {
38
+ checks: SeoCheck[]
39
+ /** The names of the required checks with no value, in the order of `checks`. */
40
+ missing: string[]
41
+ cards: Record<Network, SeoCard>
42
+ }
43
+
44
+ const text = (value: string | undefined): string | undefined => {
45
+ const trimmed = value?.trim()
46
+ return trimmed ? trimmed : undefined
47
+ }
48
+
49
+ /** The `content` of the first `<meta>` whose `property` or `name` is `key`. */
50
+ export function metaValue(head: readonly HeadEntry[], key: string): string | undefined {
51
+ for (const entry of head) {
52
+ if (entry.tag === "meta" && (entry.attrs.property === key || entry.attrs.name === key)) {
53
+ const value = text(entry.attrs.content)
54
+ if (value) return value
55
+ }
56
+ }
57
+ return undefined
58
+ }
59
+
60
+ const titleOf = (head: readonly HeadEntry[]): string | undefined =>
61
+ text(head.find((entry) => entry.tag === "title")?.text)
62
+
63
+ const canonicalOf = (head: readonly HeadEntry[]): string | undefined =>
64
+ text(head.find((entry) => entry.tag === "link" && entry.attrs.rel?.split(/\s+/).includes("canonical"))?.attrs.href)
65
+
66
+ function absolute(url: string | undefined, base: string): string | undefined {
67
+ if (!url) return undefined
68
+ try {
69
+ return new URL(url, base).href
70
+ } catch {
71
+ return undefined
72
+ }
73
+ }
74
+
75
+ function hostOf(url: string): string {
76
+ try {
77
+ return new URL(url).host
78
+ } catch {
79
+ return url
80
+ }
81
+ }
82
+
83
+ const first = (...values: Array<string | undefined>): string | undefined => values.find((value) => value !== undefined)
84
+
85
+ /** The checks and the four card previews of the current head (`lang` is `<html lang>`, `pageUrl` the page's address). */
86
+ export function seoReport(head: readonly HeadEntry[], lang: string, pageUrl: string): SeoReport {
87
+ const title = titleOf(head)
88
+ const description = metaValue(head, "description")
89
+ const canonical = canonicalOf(head)
90
+ const ogTitle = metaValue(head, "og:title")
91
+ const ogDescription = metaValue(head, "og:description")
92
+ const ogImage = metaValue(head, "og:image")
93
+ const twitterCard = metaValue(head, "twitter:card")
94
+ const checks: SeoCheck[] = [
95
+ { name: "title", value: title, required: true },
96
+ { name: "description", value: description, required: true },
97
+ { name: "og:image", value: ogImage, required: true },
98
+ { name: "canonical", value: canonical, required: true },
99
+ { name: "lang", value: text(lang), required: true },
100
+ { name: "og:title", value: ogTitle, required: false },
101
+ { name: "og:description", value: ogDescription, required: false },
102
+ { name: "twitter:card", value: twitterCard, required: false },
103
+ ]
104
+ const shownURL = absolute(first(metaValue(head, "og:url"), canonical), pageUrl) ?? pageUrl
105
+ const domain = hostOf(shownURL)
106
+ const resolved = (key: string | undefined): string | undefined => absolute(key, pageUrl)
107
+ const cards: Record<Network, SeoCard> = {
108
+ x: {
109
+ network: "x",
110
+ domain,
111
+ title: first(metaValue(head, "twitter:title"), ogTitle, title),
112
+ description: first(metaValue(head, "twitter:description"), ogDescription, description),
113
+ image: resolved(first(metaValue(head, "twitter:image"), ogImage)),
114
+ layout: twitterCard === "summary" ? "small" : "large",
115
+ },
116
+ facebook: {
117
+ network: "facebook",
118
+ domain: domain.toUpperCase(),
119
+ title: first(ogTitle, title),
120
+ description: first(ogDescription, description),
121
+ image: resolved(ogImage),
122
+ layout: "large",
123
+ },
124
+ linkedin: { network: "linkedin", domain, title: first(ogTitle, title), image: resolved(ogImage), layout: "large" },
125
+ slack: {
126
+ network: "slack",
127
+ domain,
128
+ title: first(ogTitle, title),
129
+ description: first(ogDescription, description),
130
+ image: resolved(first(ogImage, metaValue(head, "twitter:image"))),
131
+ siteName: first(metaValue(head, "og:site_name"), domain),
132
+ layout: "small",
133
+ },
134
+ }
135
+ return {
136
+ checks,
137
+ missing: checks.filter((check) => check.required && check.value === undefined).map((check) => check.name),
138
+ cards,
139
+ }
140
+ }