@hamur/devtools 0.0.0-stage → 0.0.2

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 +34 -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,251 @@
1
+ import { useStorage, type Storage } from "hamur/server"
2
+ import { storageMountDriver, storageMounts } from "hamur/server/internal"
3
+
4
+ /** The keys one answer lists at most. */
5
+ export const KEYS_MAX = 1000
6
+ /** The longest key or prefix the routes take. */
7
+ export const KEY_MAX_LENGTH = 512
8
+ /** The largest `PUT api/storage/item` body. */
9
+ export const ITEM_MAX_BYTES = 1024 * 1024
10
+
11
+ const JSON_HEADERS = {
12
+ "content-type": "application/json",
13
+ "cache-control": "no-store",
14
+ "x-content-type-options": "nosniff",
15
+ }
16
+
17
+ export const answer = (body: unknown, status = 200, headers: Record<string, string> = {}): Response =>
18
+ new Response(JSON.stringify(body), { status, headers: { ...JSON_HEADERS, ...headers } })
19
+
20
+ export const failure = (message: string, status: number, headers: Record<string, string> = {}): Response =>
21
+ answer({ error: message }, status, headers)
22
+
23
+ export const wrongMethod = (name: string, methods: string): Response =>
24
+ failure(`Devtools data route ${JSON.stringify(name)} answers ${methods}`, 405, { allow: methods })
25
+
26
+ /** What `devtools:storage` carries. */
27
+ export interface StorageChange {
28
+ mount: string
29
+ key: string
30
+ op: "set" | "remove"
31
+ }
32
+
33
+ export type StoragePush = (change: StorageChange) => void
34
+
35
+ /** Posts to the dev runner, which sends it to the devtools sockets; this door runs only in the SSR process of `hamur dev`. */
36
+ export const postDevtoolsEvent = (event: string, data: unknown): void =>
37
+ (globalThis as { process?: { send?: (message: unknown) => void } }).process?.send?.({ devtools: { event, data } })
38
+
39
+ export const postToRunner: StoragePush = (change) => postDevtoolsEvent("devtools:storage", change)
40
+
41
+ /** One `watch` per mount for the process, whatever the number of panels; stopped when the server closes. */
42
+ const watched = new Map<string, () => void>()
43
+
44
+ export function watchMount(mount: string, push: StoragePush): void {
45
+ if (watched.has(mount)) return
46
+ watched.set(
47
+ mount,
48
+ useStorage(mount).watch((event, key) => push({ mount, key, op: event === "update" ? "set" : "remove" })),
49
+ )
50
+ }
51
+
52
+ /** Watches every mount there is now, so a new server process pushes changes before any panel asks for the mounts. */
53
+ export function watchMounts(push: StoragePush = postToRunner): void {
54
+ for (const mount of storageMounts()) watchMount(mount, push)
55
+ }
56
+
57
+ export function unwatchMounts(): void {
58
+ for (const stop of watched.values()) stop()
59
+ watched.clear()
60
+ }
61
+
62
+ /** An item as the tab shows it: `raw` when its bytes are not a value `setItem` wrote, so a save writes bytes back with `setItemRaw`. */
63
+ export type ItemValue =
64
+ | { type: "json"; value: unknown; raw?: true }
65
+ | { type: "text"; value: string; raw?: true }
66
+ | { type: "bytes"; value: string; raw?: true }
67
+
68
+ export const toHex = (bytes: Uint8Array): string =>
69
+ Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")
70
+
71
+ /** `undefined` unless `text` is pairs of hex digits (white space ignored). */
72
+ export function fromHex(text: string): Uint8Array | undefined {
73
+ const clean = text.replace(/\s+/g, "")
74
+ if (clean.length % 2 !== 0 || /[^0-9a-f]/i.test(clean)) return undefined
75
+ const bytes = new Uint8Array(clean.length / 2)
76
+ for (let index = 0; index < bytes.length; index++)
77
+ bytes[index] = Number.parseInt(clean.slice(index * 2, index * 2 + 2), 16)
78
+ return bytes
79
+ }
80
+
81
+ function rawValue(bytes: Uint8Array): ItemValue {
82
+ try {
83
+ return { type: "text", value: new TextDecoder("utf-8", { fatal: true }).decode(bytes), raw: true }
84
+ } catch {
85
+ return { type: "bytes", value: toHex(bytes), raw: true }
86
+ }
87
+ }
88
+
89
+ export async function readItem(storage: Storage, key: string): Promise<ItemValue | undefined> {
90
+ const bytes = await storage.getItemRaw(key)
91
+ if (bytes === undefined) return undefined
92
+ let value: unknown
93
+ try {
94
+ value = await storage.getItem(key)
95
+ } catch {
96
+ return rawValue(bytes)
97
+ }
98
+ if (value instanceof Uint8Array) return { type: "bytes", value: toHex(value) }
99
+ if (typeof value === "string") return { type: "text", value }
100
+ try {
101
+ const json = JSON.stringify(value)
102
+ return json === undefined ? rawValue(bytes) : { type: "json", value: JSON.parse(json) }
103
+ } catch {
104
+ return rawValue(bytes)
105
+ }
106
+ }
107
+
108
+ /** Reads a `PUT` body `{ type, value, raw? }`, or the message of what is wrong with it. */
109
+ export function parseItem(body: unknown): ItemValue | string {
110
+ if (typeof body !== "object" || body === null || Array.isArray(body))
111
+ return 'The body must be { type: "json" | "text" | "bytes", value }'
112
+ const { type, value, raw } = body as Record<string, unknown>
113
+ if (raw !== undefined && raw !== true) return "raw must be true when it is given"
114
+ const extra = raw ? { raw: true as const } : {}
115
+ if (type === "json") return value === undefined ? "A json item needs a value" : { type, value, ...extra }
116
+ if (type === "text")
117
+ return typeof value === "string" ? { type, value, ...extra } : "A text item's value must be a string"
118
+ if (type === "bytes") {
119
+ if (typeof value !== "string" || fromHex(value) === undefined)
120
+ return "A bytes item's value must be hex, two digits per byte"
121
+ return { type, value, ...extra }
122
+ }
123
+ return 'type must be "json", "text" or "bytes"'
124
+ }
125
+
126
+ export async function writeItem(storage: Storage, key: string, item: ItemValue): Promise<void> {
127
+ const bytes = item.type === "bytes" ? fromHex(item.value)! : undefined
128
+ if (item.raw) {
129
+ const encoded = bytes ?? new TextEncoder().encode(item.type === "text" ? item.value : JSON.stringify(item.value))
130
+ return storage.setItemRaw(key, encoded)
131
+ }
132
+ return storage.setItem(key, bytes ?? item.value)
133
+ }
134
+
135
+ const CONTROL = /[\u0000-\u001f\u007f]/
136
+
137
+ /** A key or prefix from the query: refused when it is too long, holds a control character, or a `.` or `..` segment. */
138
+ function keyParam(url: URL, name: "key" | "prefix"): string | Response {
139
+ const value = url.searchParams.get(name) ?? ""
140
+ if (name === "key" && value === "") return failure("The key query parameter is missing", 400)
141
+ if (value.length > KEY_MAX_LENGTH) return failure(`A storage ${name} is at most ${KEY_MAX_LENGTH} characters`, 400)
142
+ if (CONTROL.test(value) || value.split(/[:/\\]+/).some((segment) => segment === "." || segment === ".."))
143
+ return failure(`Invalid storage ${name} ${JSON.stringify(value)}`, 400)
144
+ return value
145
+ }
146
+
147
+ function mountParam(url: URL): string | Response {
148
+ const mount = url.searchParams.get("mount")
149
+ if (!mount) return failure("The mount query parameter is missing", 400)
150
+ if (!storageMounts().includes(mount)) return failure(`No storage mount ${JSON.stringify(mount)}`, 404)
151
+ return mount
152
+ }
153
+
154
+ /** The router decodes escapes, so `/_hamur/devtool%73/…` reaches these handlers too; only the literal path is answered. */
155
+ export const literal = (request: Request, name: string): boolean =>
156
+ new URL(request.url).pathname.endsWith(`/_hamur/devtools/api/${name}`)
157
+
158
+ /** A failed storage call: a refused key or a read-only mount is the caller's (400), anything else 500. */
159
+ const storageFailure = (error: unknown): Response =>
160
+ failure(error instanceof Error ? error.message : String(error), error instanceof TypeError ? 400 : 500)
161
+
162
+ /** `GET api/storage/mounts`: every mount with its driver; each one listed is watched from then on. */
163
+ export async function answerMounts(request: Request, push: StoragePush = postToRunner): Promise<Response> {
164
+ if (!literal(request, "storage/mounts")) return answerUnknown(request)
165
+ if (request.method !== "GET") return wrongMethod("storage/mounts", "GET")
166
+ const rows: Array<{ mount: string; driver: string }> = []
167
+ for (const mount of storageMounts()) {
168
+ let driver = "custom"
169
+ try {
170
+ driver = (await storageMountDriver(mount))?.driver ?? driver
171
+ } catch {}
172
+ rows.push({ mount, driver })
173
+ watchMount(mount, push)
174
+ }
175
+ return answer(rows)
176
+ }
177
+
178
+ /** `GET api/storage/keys?mount=<m>&prefix=<p>`: `{ keys, truncated }`, sorted, at most `KEYS_MAX`. */
179
+ export async function answerKeys(request: Request): Promise<Response> {
180
+ if (!literal(request, "storage/keys")) return answerUnknown(request)
181
+ if (request.method !== "GET") return wrongMethod("storage/keys", "GET")
182
+ const url = new URL(request.url)
183
+ const mount = mountParam(url)
184
+ if (mount instanceof Response) return mount
185
+ const prefix = keyParam(url, "prefix")
186
+ if (prefix instanceof Response) return prefix
187
+ try {
188
+ const keys = (await useStorage(mount).getKeys(prefix)).sort()
189
+ return answer({ keys: keys.slice(0, KEYS_MAX), truncated: keys.length > KEYS_MAX })
190
+ } catch (error) {
191
+ return storageFailure(error)
192
+ }
193
+ }
194
+
195
+ export async function readBody(request: Request): Promise<unknown | Response> {
196
+ if (Number(request.headers.get("content-length") ?? 0) > ITEM_MAX_BYTES)
197
+ return failure(`The body is over ${ITEM_MAX_BYTES} bytes`, 413)
198
+ const type = request.headers.get("content-type")?.split(";")[0]!.trim().toLowerCase()
199
+ if (type !== "application/json") return failure("The body must be JSON", 400)
200
+ const bytes = await request.arrayBuffer()
201
+ if (bytes.byteLength > ITEM_MAX_BYTES) return failure(`The body is over ${ITEM_MAX_BYTES} bytes`, 413)
202
+ try {
203
+ return JSON.parse(new TextDecoder().decode(bytes))
204
+ } catch {
205
+ return failure("The body must be JSON", 400)
206
+ }
207
+ }
208
+
209
+ /** `api/storage/item?mount=<m>&key=<k>`: GET the item, PUT `{ type, value, raw? }`, DELETE it (204). */
210
+ export async function answerItem(request: Request): Promise<Response> {
211
+ if (!literal(request, "storage/item")) return answerUnknown(request)
212
+ if (!["GET", "PUT", "DELETE"].includes(request.method)) return wrongMethod("storage/item", "GET, PUT, DELETE")
213
+ const url = new URL(request.url)
214
+ const mount = mountParam(url)
215
+ if (mount instanceof Response) return mount
216
+ const key = keyParam(url, "key")
217
+ if (key instanceof Response) return key
218
+ const storage = useStorage(mount)
219
+ const missing = () => failure(`No item ${JSON.stringify(key)} in storage ${JSON.stringify(mount)}`, 404)
220
+ try {
221
+ if (request.method === "GET")
222
+ return (await readItem(storage, key).then((item) => item && answer(item))) ?? missing()
223
+ if (request.method === "DELETE") {
224
+ if (!(await storage.hasItem(key))) return missing()
225
+ await storage.removeItem(key)
226
+ return new Response(null, { status: 204, headers: { "cache-control": "no-store" } })
227
+ }
228
+ const body = await readBody(request)
229
+ if (body instanceof Response) return body
230
+ const item = parseItem(body)
231
+ if (typeof item === "string") return failure(item, 400)
232
+ await writeItem(storage, key, item)
233
+ return answer((await readItem(storage, key)) ?? null)
234
+ } catch (error) {
235
+ return storageFailure(error)
236
+ }
237
+ }
238
+
239
+ /** Any other `api/<name>` that reached the server process: no module answers it. */
240
+ export function answerUnknown(request: Request): Response {
241
+ const { pathname } = new URL(request.url)
242
+ const at = pathname.indexOf("/_hamur/devtools/api/")
243
+ const encoded = at === -1 ? pathname : pathname.slice(at + "/_hamur/devtools/api/".length)
244
+ let name: string
245
+ try {
246
+ name = decodeURIComponent(encoded)
247
+ } catch {
248
+ name = encoded
249
+ }
250
+ return failure(`No devtools data route ${JSON.stringify(name)}`, 404)
251
+ }
@@ -0,0 +1,29 @@
1
+ import { PANEL_CONFIG_ID, type PanelConfig } from "./panel/document.ts"
2
+ import { editorEndpoint, openInEditor } from "./open-in-editor.ts"
3
+
4
+ let endpoint: string | undefined
5
+
6
+ function openInEditorEndpoint(): string {
7
+ if (endpoint === undefined) {
8
+ const { baseURL } = JSON.parse(
9
+ document.getElementById(PANEL_CONFIG_ID)?.textContent ?? "{}",
10
+ ) as Partial<PanelConfig>
11
+ endpoint = editorEndpoint(baseURL ?? "/")
12
+ }
13
+ return endpoint
14
+ }
15
+
16
+ /** Source links: `file` (relative to `rootDir` or absolute) as a link that opens it in the editor. */
17
+ export function sourceLink(file: string, line?: number, column?: number): HTMLAnchorElement {
18
+ const link = document.createElement("a")
19
+ link.href = "#"
20
+ link.className = "text-inherit no-underline hover:text-fg hover:underline"
21
+ link.textContent = line === undefined ? file : `${file}:${line}`
22
+ link.dataset.file = file
23
+ link.addEventListener("click", (event) => {
24
+ event.preventDefault()
25
+ event.stopPropagation()
26
+ void openInEditor(openInEditorEndpoint(), file, line, column)
27
+ })
28
+ return link
29
+ }
@@ -0,0 +1,97 @@
1
+ import type { DevAnalyzeReport, DevAnalyzeRoute } from "hamur/kit"
2
+
3
+ type Chunk = DevAnalyzeReport["client"]["chunks"][number]
4
+
5
+ export interface Size {
6
+ bytes: number
7
+ gzip: number
8
+ }
9
+
10
+ /** A row of a comparison: the size in each run (absent where the chunk or route does not exist) and `after - before`. */
11
+ export interface Delta {
12
+ name: string
13
+ before?: Size
14
+ after?: Size
15
+ bytes: number
16
+ gzip: number
17
+ }
18
+
19
+ export interface Comparison {
20
+ chunks: Delta[]
21
+ routes: Delta[]
22
+ bytes: number
23
+ gzip: number
24
+ }
25
+
26
+ const HASHED = /^(.*)-[0-9a-z]{8}(\.m?js)$/i
27
+
28
+ /** A chunk's name across builds: its import map key, else its file without the content hash, else (for the anonymous `chunk-<hash>.js`) its largest module. */
29
+ export function chunkName(chunk: Chunk): string {
30
+ if (chunk.key) return chunk.key
31
+ const base = chunk.file.slice(chunk.file.lastIndexOf("/") + 1)
32
+ const hashed = HASHED.exec(base)
33
+ if (hashed && hashed[1] !== "chunk") return `${hashed[1]}${hashed[2]}`
34
+ const largest = chunk.packages
35
+ .flatMap((pkg) => pkg.modules)
36
+ .reduce<{ path: string; bytes: number } | undefined>(
37
+ (best, module) => (!best || module.bytes > best.bytes ? module : best),
38
+ undefined,
39
+ )
40
+ return largest ? largest.path : chunk.file
41
+ }
42
+
43
+ /** Each chunk of a target by `chunkName`, a repeated name numbered `name (2)` in file order. */
44
+ export function namedChunks(chunks: readonly Chunk[]): Map<string, Size> {
45
+ const named = new Map<string, Size>()
46
+ for (const chunk of [...chunks].sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0))) {
47
+ const base = chunkName(chunk)
48
+ let name = base
49
+ for (let n = 2; named.has(name); n++) name = `${base} (${n})`
50
+ named.set(name, { bytes: chunk.bytes, gzip: chunk.gzip })
51
+ }
52
+ return named
53
+ }
54
+
55
+ function delta(before: Map<string, Size>, after: Map<string, Size>): Delta[] {
56
+ const rows = [...new Set([...before.keys(), ...after.keys()])].map((name): Delta => {
57
+ const a = before.get(name)
58
+ const b = after.get(name)
59
+ return {
60
+ name,
61
+ ...(a ? { before: a } : {}),
62
+ ...(b ? { after: b } : {}),
63
+ bytes: (b?.bytes ?? 0) - (a?.bytes ?? 0),
64
+ gzip: (b?.gzip ?? 0) - (a?.gzip ?? 0),
65
+ }
66
+ })
67
+ return rows.sort((a, b) => Math.abs(b.bytes) - Math.abs(a.bytes) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
68
+ }
69
+
70
+ const routeSizes = (routes: readonly DevAnalyzeRoute[]): Map<string, Size> =>
71
+ new Map(routes.map((route) => [route.path, { bytes: route.bytes, gzip: route.gzip }]))
72
+
73
+ /** The size change from `base` to `next`, per chunk and per route (first-load JS), every row of either run, the largest change first. */
74
+ export function compareRuns(base: DevAnalyzeReport, next: DevAnalyzeReport): Comparison {
75
+ return {
76
+ chunks: delta(namedChunks(base.client.chunks), namedChunks(next.client.chunks)),
77
+ routes: delta(routeSizes(base.routes), routeSizes(next.routes)),
78
+ bytes: next.client.bytes - base.client.bytes,
79
+ gzip: next.client.gzip - base.client.gzip,
80
+ }
81
+ }
82
+
83
+ /** `+1.2 KB`, `-300 B`, `0 B`. */
84
+ export function formatDelta(bytes: number): string {
85
+ if (bytes === 0) return "0 B"
86
+ const size = Math.abs(bytes)
87
+ const text =
88
+ size < 1024
89
+ ? `${size} B`
90
+ : size < 1024 * 1024
91
+ ? `${(size / 1024).toFixed(1)} KB`
92
+ : `${(size / 1024 / 1024).toFixed(1)} MB`
93
+ return `${bytes > 0 ? "+" : "-"}${text}`
94
+ }
95
+
96
+ /** A larger bundle is worse: `up` (red), `down` (green) or `same`. */
97
+ export const trend = (bytes: number): "up" | "down" | "same" => (bytes > 0 ? "up" : bytes < 0 ? "down" : "same")
@@ -0,0 +1,217 @@
1
+ import { defineDevtoolsApp } from "hamur/app"
2
+ import type { AnalyzeAnswer, AnalyzeListRow } from "../dev/analyze.ts"
3
+ import { element, UI } from "../panel/ui.ts"
4
+ import { formatBytes } from "./assets.ts"
5
+ import { compareRuns, formatDelta, namedChunks, trend, type Delta, type Size } from "./analyze-model.ts"
6
+
7
+ const NUMBER = "font-mono text-xs text-right whitespace-nowrap tabular-nums"
8
+ const TREND: Record<string, string> = { up: "text-red", down: "text-green", same: "text-fg-3" }
9
+
10
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
11
+
12
+ async function request<T>(url: string, init?: RequestInit): Promise<T> {
13
+ const response = await fetch(url, init)
14
+ const body = (await response.json().catch(() => ({}))) as T & { error?: string }
15
+ if (!response.ok) throw new Error(body.error ?? `${url} answered ${response.status}`)
16
+ return body
17
+ }
18
+
19
+ const runLabel = (row: AnalyzeListRow): string =>
20
+ `${row.id} · ${formatBytes(row.bytes)} raw, ${formatBytes(row.gzip)} gzip`
21
+
22
+ function deltaCell(bytes: number): HTMLElement {
23
+ return element("td", { className: `${UI.td} ${NUMBER} ${TREND[trend(bytes)] ?? "text-fg-3"}` }, formatDelta(bytes))
24
+ }
25
+
26
+ function sizeTable(
27
+ head: string,
28
+ rows: Array<{ name: string } & Size>,
29
+ deltas: Map<string, Delta> | undefined,
30
+ ): HTMLElement {
31
+ const columns = ["", "Raw", "Gzip", ...(deltas ? ["Raw change", "Gzip change"] : [])]
32
+ const header = element(
33
+ "tr",
34
+ {},
35
+ element("th", { className: UI.th }, head),
36
+ ...columns.slice(1).map((column) => element("th", { className: UI.th.replace("text-left", "text-right") }, column)),
37
+ )
38
+ const body = rows.map(({ name, bytes, gzip }) => {
39
+ const change = deltas?.get(name)
40
+ return element(
41
+ "tr",
42
+ { className: UI.tr },
43
+ element("td", { className: `${UI.td} font-mono text-sm font-medium text-fg break-all` }, name),
44
+ element("td", { className: `${UI.td} ${NUMBER} text-fg-2` }, formatBytes(bytes)),
45
+ element("td", { className: `${UI.td} ${NUMBER} text-fg-2` }, formatBytes(gzip)),
46
+ ...(change ? [deltaCell(change.bytes), deltaCell(change.gzip)] : []),
47
+ )
48
+ })
49
+ return element(
50
+ "table",
51
+ { className: "w-full border-collapse" },
52
+ element("thead", {}, header),
53
+ element("tbody", {}, ...body),
54
+ )
55
+ }
56
+
57
+ /** A row a compared run no longer has still shows, at its old size under "removed". */
58
+ function removed(deltas: Map<string, Delta>, present: Set<string>): Delta[] {
59
+ return [...deltas.values()].filter((row) => !present.has(row.name))
60
+ }
61
+
62
+ export default defineDevtoolsApp({
63
+ async init(canvas) {
64
+ canvas.className = "flex flex-col flex-1 min-h-0"
65
+ const run = element("button", { type: "button", className: UI.primary }, "Run analysis")
66
+ const status = element("output", { className: `${UI.hint} empty:hidden` })
67
+ const current = element("select", { name: "run", className: `${UI.field} w-72 font-mono` })
68
+ current.setAttribute("aria-label", "Run")
69
+ const other = element("select", { name: "compare", className: `${UI.field} w-72 font-mono` })
70
+ other.setAttribute("aria-label", "Compare with")
71
+ const field = (label: string, select: HTMLSelectElement) =>
72
+ element("label", { className: "flex items-center gap-1.5 text-xs text-fg-3" }, label, select)
73
+ const bar = element(
74
+ "div",
75
+ { className: UI.strip },
76
+ run,
77
+ field("Run", current),
78
+ field("Compare with", other),
79
+ status,
80
+ )
81
+ const note = element("p", { className: `m-0 px-4 py-1 ${UI.fail} empty:hidden` })
82
+ note.dataset.error = ""
83
+ const result = element("div", { className: "flex-1 min-h-0 overflow-auto flex flex-col gap-3.5 p-4" })
84
+ canvas.append(bar, note, result)
85
+
86
+ let rows: AnalyzeListRow[] = []
87
+ const loaded = new Map<string, AnalyzeAnswer>()
88
+ const fetchRun = async (id: string): Promise<AnalyzeAnswer> => {
89
+ const found = loaded.get(id) ?? (await request<AnalyzeAnswer>(`api/analyze/${encodeURIComponent(id)}`))
90
+ loaded.set(id, found)
91
+ return found
92
+ }
93
+
94
+ function fillPickers(): void {
95
+ const shown = current.value
96
+ const compared = other.value
97
+ current.replaceChildren(...rows.map((row) => element("option", { value: row.id, textContent: runLabel(row) })))
98
+ other.replaceChildren(
99
+ element("option", { value: "", textContent: "Nothing" }),
100
+ ...rows.map((row) => element("option", { value: row.id, textContent: runLabel(row) })),
101
+ )
102
+ current.value = rows.some((row) => row.id === shown) ? shown : (rows[0]?.id ?? "")
103
+ other.value = rows.some((row) => row.id === compared) ? compared : ""
104
+ }
105
+
106
+ async function paint(): Promise<void> {
107
+ note.textContent = ""
108
+ if (!current.value) {
109
+ result.replaceChildren(
110
+ element(
111
+ "p",
112
+ { className: UI.hint },
113
+ "No saved runs. Run an analysis to build the client bundle and save its sizes.",
114
+ ),
115
+ )
116
+ return
117
+ }
118
+ const id = current.value
119
+ const baseId = other.value && other.value !== id ? other.value : undefined
120
+ try {
121
+ const [shown, base] = await Promise.all([fetchRun(id), baseId ? fetchRun(baseId) : undefined])
122
+ if (current.value !== id) return
123
+ const comparison = base ? compareRuns(base, shown) : undefined
124
+ const chunkDeltas = comparison && new Map(comparison.chunks.map((row) => [row.name, row]))
125
+ const routeDeltas = comparison && new Map(comparison.routes.map((row) => [row.name, row]))
126
+ const chunks = [...namedChunks(shown.client.chunks)]
127
+ .map(([name, size]) => ({ name, ...size }))
128
+ .sort((a, b) => b.bytes - a.bytes)
129
+ const routes = shown.routes
130
+ .map((route) => ({ name: route.path, bytes: route.bytes, gzip: route.gzip }))
131
+ .sort((a, b) => b.bytes - a.bytes)
132
+ const map = element("div", {})
133
+ map.dataset.treemap = ""
134
+ map.innerHTML = shown.treemap
135
+ const gone = (deltas: Map<string, Delta> | undefined, names: string[]): Delta[] =>
136
+ deltas ? removed(deltas, new Set(names)) : []
137
+ const goneChunks = gone(
138
+ chunkDeltas,
139
+ chunks.map((chunk) => chunk.name),
140
+ )
141
+ const goneRoutes = gone(
142
+ routeDeltas,
143
+ routes.map((route) => route.name),
144
+ )
145
+ const summary = comparison
146
+ ? ` · ${formatDelta(comparison.bytes)} raw, ${formatDelta(comparison.gzip)} gzip against ${baseId}`
147
+ : ""
148
+ result.replaceChildren(
149
+ element(
150
+ "p",
151
+ { className: "m-0 text-sm text-fg-2" },
152
+ `${shown.client.chunks.length} chunks, ${formatBytes(shown.client.bytes)} raw, ${formatBytes(shown.client.gzip)} gzip${summary}`,
153
+ ),
154
+ map,
155
+ element("h2", { className: "m-0 text-xs font-medium text-fg-2" }, "JS per route (first load)"),
156
+ sizeTable("Route", routes, routeDeltas),
157
+ ...(goneRoutes.length
158
+ ? [
159
+ element(
160
+ "p",
161
+ { className: UI.hint },
162
+ `Not in this run: ${goneRoutes.map((row) => `${row.name} (${formatDelta(row.bytes)} raw)`).join(", ")}`,
163
+ ),
164
+ ]
165
+ : []),
166
+ element("h2", { className: "m-0 text-xs font-medium text-fg-2" }, "Chunks"),
167
+ sizeTable("Chunk", chunks, chunkDeltas),
168
+ ...(goneChunks.length
169
+ ? [
170
+ element(
171
+ "p",
172
+ { className: UI.hint },
173
+ `Not in this run: ${goneChunks.map((row) => `${row.name} (${formatDelta(row.bytes)} raw)`).join(", ")}`,
174
+ ),
175
+ ]
176
+ : []),
177
+ )
178
+ } catch (error) {
179
+ note.textContent = messageOf(error)
180
+ }
181
+ }
182
+
183
+ async function refresh(): Promise<void> {
184
+ rows = await request<AnalyzeListRow[]>("api/analyze")
185
+ fillPickers()
186
+ await paint()
187
+ }
188
+
189
+ current.addEventListener("change", () => void paint())
190
+ other.addEventListener("change", () => void paint())
191
+ run.addEventListener("click", () => {
192
+ run.disabled = true
193
+ status.textContent = "Building…"
194
+ note.textContent = ""
195
+ void request<AnalyzeAnswer>("api/analyze", { method: "POST" })
196
+ .then(async (answer) => {
197
+ loaded.set(answer.id, answer)
198
+ rows = await request<AnalyzeListRow[]>("api/analyze")
199
+ fillPickers()
200
+ current.value = answer.id
201
+ status.textContent = `Saved ${answer.id}`
202
+ await paint()
203
+ })
204
+ .catch((error: unknown) => {
205
+ status.textContent = ""
206
+ note.textContent = messageOf(error)
207
+ })
208
+ .finally(() => {
209
+ run.disabled = false
210
+ })
211
+ })
212
+
213
+ await refresh().catch((error: unknown) => {
214
+ note.textContent = messageOf(error)
215
+ })
216
+ },
217
+ })