@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.
- package/LICENSE +22 -0
- package/README.md +24 -2
- package/dist/src/client.js +780 -0
- package/dist/src/index.js +1711 -0
- package/dist/types/src/apps/locator.d.ts +3 -0
- package/dist/types/src/bridge.d.ts +8 -0
- package/dist/types/src/client.d.ts +3 -0
- package/dist/types/src/dev/analyze.d.ts +31 -0
- package/dist/types/src/dev/assets.d.ts +33 -0
- package/dist/types/src/dev/authz.d.ts +49 -0
- package/dist/types/src/dev/bundle.d.ts +22 -0
- package/dist/types/src/dev/config.d.ts +24 -0
- package/dist/types/src/dev/handler.d.ts +20 -0
- package/dist/types/src/dev/modules.d.ts +28 -0
- package/dist/types/src/dev/overview.d.ts +20 -0
- package/dist/types/src/dev/processes.d.ts +4 -0
- package/dist/types/src/dev/server-routes.d.ts +7 -0
- package/dist/types/src/dev/tasks.d.ts +26 -0
- package/dist/types/src/dev/timeline.d.ts +20 -0
- package/dist/types/src/dev/virtual.d.ts +9 -0
- package/dist/types/src/icons.d.ts +24 -0
- package/dist/types/src/index.d.ts +8 -0
- package/dist/types/src/locator.d.ts +17 -0
- package/dist/types/src/mask.d.ts +8 -0
- package/dist/types/src/module.d.ts +27 -0
- package/dist/types/src/open-in-editor.d.ts +4 -0
- package/dist/types/src/options.d.ts +14 -0
- package/dist/types/src/panel/document.d.ts +16 -0
- package/dist/types/src/panel/groups.d.ts +14 -0
- package/dist/types/src/panel/index.d.ts +1 -0
- package/dist/types/src/panel/settings.d.ts +69 -0
- package/dist/types/src/panel/style.d.ts +1 -0
- package/dist/types/src/panel/ui.d.ts +34 -0
- package/dist/types/src/server/authz.d.ts +30 -0
- package/dist/types/src/server/index.d.ts +3 -0
- package/dist/types/src/server/routes.d.ts +6 -0
- package/dist/types/src/server/storage.d.ts +56 -0
- package/dist/types/src/source-link.d.ts +2 -0
- package/dist/types/src/tabs/analyze-model.d.ts +31 -0
- package/dist/types/src/tabs/analyze.d.ts +2 -0
- package/dist/types/src/tabs/assets.d.ts +11 -0
- package/dist/types/src/tabs/audit-model.d.ts +42 -0
- package/dist/types/src/tabs/audit.d.ts +2 -0
- package/dist/types/src/tabs/authz-model.d.ts +11 -0
- package/dist/types/src/tabs/authz.d.ts +2 -0
- package/dist/types/src/tabs/config.d.ts +8 -0
- package/dist/types/src/tabs/inspect.d.ts +7 -0
- package/dist/types/src/tabs/modules.d.ts +4 -0
- package/dist/types/src/tabs/overview.d.ts +2 -0
- package/dist/types/src/tabs/pages.d.ts +2 -0
- package/dist/types/src/tabs/payload.d.ts +6 -0
- package/dist/types/src/tabs/plugins-model.d.ts +15 -0
- package/dist/types/src/tabs/plugins.d.ts +2 -0
- package/dist/types/src/tabs/seo-model.d.ts +36 -0
- package/dist/types/src/tabs/seo.d.ts +2 -0
- package/dist/types/src/tabs/server-routes.d.ts +2 -0
- package/dist/types/src/tabs/storage.d.ts +13 -0
- package/dist/types/src/tabs/tasks-model.d.ts +16 -0
- package/dist/types/src/tabs/tasks.d.ts +2 -0
- package/dist/types/src/tabs/terminals-model.d.ts +53 -0
- package/dist/types/src/tabs/terminals.d.ts +2 -0
- package/dist/types/src/tabs/timeline-model.d.ts +58 -0
- package/dist/types/src/tabs/timeline.d.ts +2 -0
- package/dist/types/src/tester.d.ts +43 -0
- package/dist/types/src/toolbar/element.d.ts +28 -0
- package/dist/types/src/toolbar/shortcut.d.ts +14 -0
- package/dist/types/src/toolbar/style.d.ts +3 -0
- package/dist/types/src/view-context.d.ts +13 -0
- package/package.json +28 -4
- package/src/apps/locator.ts +131 -0
- package/src/bridge.ts +172 -0
- package/src/client.ts +10 -0
- package/src/dev/analyze.ts +128 -0
- package/src/dev/assets.ts +208 -0
- package/src/dev/authz.ts +162 -0
- package/src/dev/bundle.ts +91 -0
- package/src/dev/config.ts +132 -0
- package/src/dev/handler.ts +161 -0
- package/src/dev/modules.ts +60 -0
- package/src/dev/overview.ts +57 -0
- package/src/dev/processes.ts +34 -0
- package/src/dev/server-routes.ts +14 -0
- package/src/dev/tasks.ts +93 -0
- package/src/dev/timeline.ts +43 -0
- package/src/dev/virtual.ts +40 -0
- package/src/env.d.ts +21 -0
- package/src/icons.ts +48 -0
- package/src/index.ts +12 -0
- package/src/locator.ts +31 -0
- package/src/mask.ts +16 -0
- package/src/module.ts +352 -0
- package/src/open-in-editor.ts +18 -0
- package/src/options.ts +36 -0
- package/src/panel/document.ts +60 -0
- package/src/panel/groups.ts +41 -0
- package/src/panel/index.ts +429 -0
- package/src/panel/settings.ts +224 -0
- package/src/panel/style.ts +321 -0
- package/src/panel/ui.ts +52 -0
- package/src/server/authz.ts +110 -0
- package/src/server/index.ts +25 -0
- package/src/server/routes.ts +51 -0
- package/src/server/storage.ts +251 -0
- package/src/source-link.ts +29 -0
- package/src/tabs/analyze-model.ts +97 -0
- package/src/tabs/analyze.ts +217 -0
- package/src/tabs/assets.ts +375 -0
- package/src/tabs/audit-model.ts +216 -0
- package/src/tabs/audit.ts +223 -0
- package/src/tabs/authz-model.ts +28 -0
- package/src/tabs/authz.ts +337 -0
- package/src/tabs/config.ts +250 -0
- package/src/tabs/inspect.ts +101 -0
- package/src/tabs/modules.ts +58 -0
- package/src/tabs/overview.ts +104 -0
- package/src/tabs/pages.ts +188 -0
- package/src/tabs/payload.ts +224 -0
- package/src/tabs/plugins-model.ts +44 -0
- package/src/tabs/plugins.ts +95 -0
- package/src/tabs/seo-model.ts +140 -0
- package/src/tabs/seo.ts +162 -0
- package/src/tabs/server-routes.ts +469 -0
- package/src/tabs/storage.ts +313 -0
- package/src/tabs/tasks-model.ts +59 -0
- package/src/tabs/tasks.ts +287 -0
- package/src/tabs/terminals-model.ts +127 -0
- package/src/tabs/terminals.ts +294 -0
- package/src/tabs/timeline-model.ts +200 -0
- package/src/tabs/timeline.ts +260 -0
- package/src/tester.ts +158 -0
- package/src/toolbar/element.ts +428 -0
- package/src/toolbar/shortcut.ts +56 -0
- package/src/toolbar/style.ts +94 -0
- package/src/view-context.ts +93 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import { ISLAND_ELEMENT } from "hamur/adapter"
|
|
3
|
+
import { defineDevtoolsApp } from "hamur/app"
|
|
4
|
+
import { baseURL } from "#hamur/devtools/config"
|
|
5
|
+
import { describeIsland, nearestLocation } from "../locator.ts"
|
|
6
|
+
import { editorEndpoint, openInEditor } from "../open-in-editor.ts"
|
|
7
|
+
|
|
8
|
+
const TOOLBAR = "hamur-devtools"
|
|
9
|
+
const OUTLINE =
|
|
10
|
+
"position:fixed;box-sizing:border-box;pointer-events:none;border:2px solid #7c5cff;background:rgba(124,92,255,.14)"
|
|
11
|
+
const LABEL =
|
|
12
|
+
"position:absolute;left:-2px;padding:2px 6px;border-radius:4px;background:#7c5cff;color:#fff;font:11px/16px ui-monospace,monospace;white-space:nowrap"
|
|
13
|
+
const BAR =
|
|
14
|
+
"position:fixed;left:12px;top:12px;display:flex;gap:4px;padding:4px;border-radius:8px;background:#161622;pointer-events:auto;font:12px system-ui,sans-serif"
|
|
15
|
+
const BUTTON =
|
|
16
|
+
"padding:4px 8px;border:0;border-radius:5px;background:transparent;color:#fff;font:inherit;cursor:pointer"
|
|
17
|
+
|
|
18
|
+
type Mode = "element" | "islands"
|
|
19
|
+
|
|
20
|
+
function rectOf(element: Element): DOMRect {
|
|
21
|
+
const rect = element.getBoundingClientRect()
|
|
22
|
+
return rect.width === 0 && rect.height === 0 && element.firstElementChild
|
|
23
|
+
? element.firstElementChild.getBoundingClientRect()
|
|
24
|
+
: rect
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function outline(element: Element, text: string, data: Record<string, string>): HTMLElement {
|
|
28
|
+
const rect = rectOf(element)
|
|
29
|
+
const box = document.createElement("div")
|
|
30
|
+
box.style.cssText = `${OUTLINE};left:${rect.left}px;top:${rect.top}px;width:${rect.width}px;height:${rect.height}px`
|
|
31
|
+
Object.assign(box.dataset, data)
|
|
32
|
+
const label = document.createElement("span")
|
|
33
|
+
label.style.cssText = `${LABEL};top:${rect.top < 22 ? 0 : -22}px`
|
|
34
|
+
label.textContent = text
|
|
35
|
+
box.append(label)
|
|
36
|
+
return box
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Outlines the element under the pointer with its component file and opens it on click; the island view outlines every island. */
|
|
40
|
+
export default defineDevtoolsApp({
|
|
41
|
+
init(canvas) {
|
|
42
|
+
const endpoint = editorEndpoint(baseURL)
|
|
43
|
+
const layer = document.createElement("div")
|
|
44
|
+
const bar = document.createElement("div")
|
|
45
|
+
bar.style.cssText = BAR
|
|
46
|
+
const buttons = new Map<Mode, HTMLButtonElement>()
|
|
47
|
+
for (const [mode, text] of [
|
|
48
|
+
["element", "Elements"],
|
|
49
|
+
["islands", "Islands"],
|
|
50
|
+
] as const) {
|
|
51
|
+
const button = document.createElement("button")
|
|
52
|
+
button.type = "button"
|
|
53
|
+
button.textContent = text
|
|
54
|
+
button.dataset.mode = mode
|
|
55
|
+
button.style.cssText = BUTTON
|
|
56
|
+
button.addEventListener("click", () => select(mode))
|
|
57
|
+
buttons.set(mode, button)
|
|
58
|
+
bar.append(button)
|
|
59
|
+
}
|
|
60
|
+
canvas.append(layer, bar)
|
|
61
|
+
|
|
62
|
+
let mode: Mode = "element"
|
|
63
|
+
let hovered: Element | undefined
|
|
64
|
+
let timer: ReturnType<typeof setInterval> | undefined
|
|
65
|
+
|
|
66
|
+
const draw = () => {
|
|
67
|
+
if (mode === "element") {
|
|
68
|
+
const found = nearestLocation(hovered ?? null)
|
|
69
|
+
layer.replaceChildren(
|
|
70
|
+
...(found
|
|
71
|
+
? [
|
|
72
|
+
outline(found.element, `${found.location.file}:${found.location.line}`, {
|
|
73
|
+
file: found.location.file,
|
|
74
|
+
line: String(found.location.line),
|
|
75
|
+
column: String(found.location.column),
|
|
76
|
+
}),
|
|
77
|
+
]
|
|
78
|
+
: []),
|
|
79
|
+
)
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
layer.replaceChildren(
|
|
83
|
+
...[...document.querySelectorAll(ISLAND_ELEMENT)].map((island) => {
|
|
84
|
+
const { name, directive } = describeIsland(island.getAttribute("component"), island.getAttribute("on"))
|
|
85
|
+
return outline(island, `${name} · ${directive}`, { island: name, directive })
|
|
86
|
+
}),
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function select(next: Mode): void {
|
|
91
|
+
mode = next
|
|
92
|
+
hovered = undefined
|
|
93
|
+
for (const [name, button] of buttons) {
|
|
94
|
+
button.ariaPressed = String(name === next)
|
|
95
|
+
button.style.background = name === next ? "#7c5cff" : "transparent"
|
|
96
|
+
}
|
|
97
|
+
clearInterval(timer)
|
|
98
|
+
timer = next === "islands" ? setInterval(draw, 500) : undefined
|
|
99
|
+
draw()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const inside = (event: Event) => (event.target as Element | null)?.closest?.(TOOLBAR) != null
|
|
103
|
+
const move = (event: PointerEvent) => {
|
|
104
|
+
if (mode !== "element" || inside(event)) return
|
|
105
|
+
hovered = event.target as Element
|
|
106
|
+
draw()
|
|
107
|
+
}
|
|
108
|
+
const click = (event: MouseEvent) => {
|
|
109
|
+
if (mode !== "element" || inside(event)) return
|
|
110
|
+
const found = nearestLocation(event.target as Element)
|
|
111
|
+
if (!found) return
|
|
112
|
+
event.preventDefault()
|
|
113
|
+
event.stopImmediatePropagation()
|
|
114
|
+
void openInEditor(endpoint, found.location.file, found.location.line, found.location.column)
|
|
115
|
+
}
|
|
116
|
+
const redraw = () => draw()
|
|
117
|
+
document.addEventListener("pointermove", move, true)
|
|
118
|
+
document.addEventListener("click", click, true)
|
|
119
|
+
window.addEventListener("scroll", redraw, true)
|
|
120
|
+
window.addEventListener("resize", redraw)
|
|
121
|
+
select("element")
|
|
122
|
+
|
|
123
|
+
return () => {
|
|
124
|
+
clearInterval(timer)
|
|
125
|
+
document.removeEventListener("pointermove", move, true)
|
|
126
|
+
document.removeEventListener("click", click, true)
|
|
127
|
+
window.removeEventListener("scroll", redraw, true)
|
|
128
|
+
window.removeEventListener("resize", redraw)
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
})
|
package/src/bridge.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { DevtoolsCurrentRoute, DevtoolsPage, DevtoolsPayload } from "hamur/app"
|
|
2
|
+
|
|
3
|
+
/** The channel the panel's own window reads the page hook through. */
|
|
4
|
+
export const BRIDGE_CHANNEL = "hamur:devtools"
|
|
5
|
+
export const OWN_WINDOW = "hamur-devtools"
|
|
6
|
+
|
|
7
|
+
type BridgeEvent = "mark" | "hydration" | "badge"
|
|
8
|
+
const EVENTS: BridgeEvent[] = ["mark", "hydration", "badge"]
|
|
9
|
+
const CALLS = ["navigate", "setState", "refresh"] as const
|
|
10
|
+
type BridgeCall = (typeof CALLS)[number]
|
|
11
|
+
|
|
12
|
+
interface Snapshot {
|
|
13
|
+
route: DevtoolsCurrentRoute
|
|
14
|
+
pending: boolean
|
|
15
|
+
payload: DevtoolsPayload
|
|
16
|
+
head: ReturnType<DevtoolsPage["head"]>
|
|
17
|
+
marks: unknown[]
|
|
18
|
+
hydration: ReturnType<DevtoolsPage["hydration"]>
|
|
19
|
+
badge: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type PageMessage =
|
|
23
|
+
| { type: "snapshot"; snapshot: Snapshot }
|
|
24
|
+
| { type: "event"; event: BridgeEvent; data: unknown }
|
|
25
|
+
| { type: "answer"; id: number; error?: string }
|
|
26
|
+
type WindowMessage = { type: "hello" } | { type: "call"; id: number; method: BridgeCall; args: unknown[] }
|
|
27
|
+
|
|
28
|
+
const HELLO_MS = 1000
|
|
29
|
+
const ATTACHED_MS = 3000
|
|
30
|
+
const ANSWER_MS = 5000
|
|
31
|
+
|
|
32
|
+
const message = (error: unknown): string => (error instanceof Error ? error.message : String(error))
|
|
33
|
+
|
|
34
|
+
function snapshotOf(page: DevtoolsPage): Snapshot {
|
|
35
|
+
return {
|
|
36
|
+
route: page.router.current(),
|
|
37
|
+
pending: page.router.pending(),
|
|
38
|
+
payload: page.payload(),
|
|
39
|
+
head: page.head(),
|
|
40
|
+
marks: page.marks().map((entry) => entry.toJSON()),
|
|
41
|
+
hydration: page.hydration(),
|
|
42
|
+
badge: page.badge(),
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The page side: while a panel window says `hello`, sends it a snapshot of `page` every second, its events and the answers to its calls. */
|
|
47
|
+
export function serveBridge(page: DevtoolsPage): void {
|
|
48
|
+
if (typeof BroadcastChannel === "undefined") return
|
|
49
|
+
const channel = new BroadcastChannel(BRIDGE_CHANNEL)
|
|
50
|
+
let lastHello = 0
|
|
51
|
+
const attached = (): boolean => Date.now() - lastHello < ATTACHED_MS
|
|
52
|
+
const send = (data: PageMessage): boolean => {
|
|
53
|
+
try {
|
|
54
|
+
channel.postMessage(data)
|
|
55
|
+
return true
|
|
56
|
+
} catch {
|
|
57
|
+
return false
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const push = (): void => {
|
|
61
|
+
if (!attached()) return
|
|
62
|
+
const snapshot = snapshotOf(page)
|
|
63
|
+
if (!send({ type: "snapshot", snapshot }))
|
|
64
|
+
send({
|
|
65
|
+
type: "snapshot",
|
|
66
|
+
snapshot: { ...snapshot, payload: { ...snapshot.payload, data: {}, state: {} }, marks: [] },
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
setInterval(push, HELLO_MS)
|
|
70
|
+
for (const event of EVENTS) {
|
|
71
|
+
page.on(event, (data) => {
|
|
72
|
+
if (attached())
|
|
73
|
+
send({
|
|
74
|
+
type: "event",
|
|
75
|
+
event,
|
|
76
|
+
data: event === "mark" && data instanceof PerformanceEntry ? data.toJSON() : data,
|
|
77
|
+
})
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
channel.onmessage = (event: MessageEvent<WindowMessage>) => {
|
|
81
|
+
const data = event.data
|
|
82
|
+
if (data?.type === "hello") {
|
|
83
|
+
lastHello = Date.now()
|
|
84
|
+
push()
|
|
85
|
+
} else if (data?.type === "call" && CALLS.includes(data.method)) {
|
|
86
|
+
const { id, method, args } = data
|
|
87
|
+
lastHello = Date.now()
|
|
88
|
+
const run = async (): Promise<void> => {
|
|
89
|
+
if (method === "setState") page.setState(String(args[0]), args[1])
|
|
90
|
+
else if (method === "navigate") await page.router.navigate(String(args[0]))
|
|
91
|
+
else await page.refresh(String(args[0]))
|
|
92
|
+
}
|
|
93
|
+
run().then(
|
|
94
|
+
() => void send({ type: "answer", id }),
|
|
95
|
+
(error: unknown) => void send({ type: "answer", id, error: message(error) }),
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The window side: a `DevtoolsPage` whose reads return the last snapshot; `undefined` when no page answers within `timeout` ms. */
|
|
102
|
+
export function connectBridge(timeout = 1500): Promise<DevtoolsPage | undefined> {
|
|
103
|
+
if (typeof BroadcastChannel === "undefined") return Promise.resolve(undefined)
|
|
104
|
+
const channel = new BroadcastChannel(BRIDGE_CHANNEL)
|
|
105
|
+
let latest: Snapshot | undefined
|
|
106
|
+
const listeners: Record<BridgeEvent, Set<(data: unknown) => void>> = {
|
|
107
|
+
mark: new Set(),
|
|
108
|
+
hydration: new Set(),
|
|
109
|
+
badge: new Set(),
|
|
110
|
+
}
|
|
111
|
+
const calls = new Map<
|
|
112
|
+
number,
|
|
113
|
+
{ resolve: () => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }
|
|
114
|
+
>()
|
|
115
|
+
let counter = 0
|
|
116
|
+
const call = (method: BridgeCall, args: unknown[]): Promise<void> =>
|
|
117
|
+
new Promise<void>((resolve, reject) => {
|
|
118
|
+
const id = ++counter
|
|
119
|
+
const timer = setTimeout(() => {
|
|
120
|
+
calls.delete(id)
|
|
121
|
+
reject(new Error("The app page did not answer"))
|
|
122
|
+
}, ANSWER_MS)
|
|
123
|
+
calls.set(id, { resolve, reject, timer })
|
|
124
|
+
channel.postMessage({ type: "call", id, method, args } satisfies WindowMessage)
|
|
125
|
+
})
|
|
126
|
+
const now = (): Snapshot => latest!
|
|
127
|
+
const page: DevtoolsPage = {
|
|
128
|
+
version: 1,
|
|
129
|
+
router: { current: () => now().route, pending: () => now().pending, navigate: (path) => call("navigate", [path]) },
|
|
130
|
+
payload: () => now().payload,
|
|
131
|
+
setState(key, value) {
|
|
132
|
+
call("setState", [key, value]).catch((error: unknown) =>
|
|
133
|
+
console.error(`[hamur] devtools setState failed: ${message(error)}`),
|
|
134
|
+
)
|
|
135
|
+
},
|
|
136
|
+
refresh: (key) => call("refresh", [key]),
|
|
137
|
+
head: () => now().head,
|
|
138
|
+
marks: () => now().marks as PerformanceEntry[],
|
|
139
|
+
hydration: () => now().hydration,
|
|
140
|
+
badge: () => now().badge,
|
|
141
|
+
on(event, fn) {
|
|
142
|
+
listeners[event].add(fn)
|
|
143
|
+
return () => void listeners[event].delete(fn)
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
return new Promise((resolve) => {
|
|
147
|
+
const timer = setTimeout(() => resolve(undefined), timeout)
|
|
148
|
+
channel.onmessage = (event: MessageEvent<PageMessage>) => {
|
|
149
|
+
const data = event.data
|
|
150
|
+
if (data?.type === "snapshot") {
|
|
151
|
+
const first = latest === undefined
|
|
152
|
+
latest = data.snapshot
|
|
153
|
+
if (first) {
|
|
154
|
+
clearTimeout(timer)
|
|
155
|
+
resolve(page)
|
|
156
|
+
}
|
|
157
|
+
} else if (data?.type === "event") {
|
|
158
|
+
for (const fn of listeners[data.event] ?? []) fn(data.data)
|
|
159
|
+
} else if (data?.type === "answer") {
|
|
160
|
+
const waiting = calls.get(data.id)
|
|
161
|
+
if (!waiting) return
|
|
162
|
+
calls.delete(data.id)
|
|
163
|
+
clearTimeout(waiting.timer)
|
|
164
|
+
if (data.error === undefined) waiting.resolve()
|
|
165
|
+
else waiting.reject(new Error(data.error))
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const hello = (): void => channel.postMessage({ type: "hello" } satisfies WindowMessage)
|
|
169
|
+
hello()
|
|
170
|
+
setInterval(hello, HELLO_MS)
|
|
171
|
+
})
|
|
172
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/// <reference path="./env.d.ts" />
|
|
2
|
+
import { definePlugin } from "hamur/app"
|
|
3
|
+
import { apps } from "#hamur/devtools/apps"
|
|
4
|
+
import { baseURL, placement, shortcut } from "#hamur/devtools/config"
|
|
5
|
+
import { mountToolbar } from "./toolbar/element.ts"
|
|
6
|
+
|
|
7
|
+
/** The client app plugin the module adds in `hamur dev`; an app never imports it. */
|
|
8
|
+
export default definePlugin((app) => {
|
|
9
|
+
app.hooks.hookOnce("app:mounted", () => mountToolbar({ baseURL, shortcut, placement, apps }))
|
|
10
|
+
})
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"
|
|
2
|
+
import { join, resolve, sep } from "node:path"
|
|
3
|
+
import { renderAnalyzeTreemap, type DevAnalyzeReport } from "hamur/kit"
|
|
4
|
+
|
|
5
|
+
/** `api/analyze/<ISO time>`: a saved run with the treemap SVG made from it at answer time. */
|
|
6
|
+
export interface AnalyzeAnswer extends DevAnalyzeReport {
|
|
7
|
+
id: string
|
|
8
|
+
treemap: string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** GET `api/analyze`: one saved run's totals. */
|
|
12
|
+
export interface AnalyzeListRow {
|
|
13
|
+
id: string
|
|
14
|
+
bytes: number
|
|
15
|
+
gzip: number
|
|
16
|
+
chunks: number
|
|
17
|
+
routes: number
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** An error with the status a data route answers it with. */
|
|
21
|
+
export class AnalyzeError extends Error {
|
|
22
|
+
constructor(
|
|
23
|
+
message: string,
|
|
24
|
+
readonly status: number,
|
|
25
|
+
) {
|
|
26
|
+
super(message)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const RUN_ID = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
|
|
31
|
+
|
|
32
|
+
const isReport = (value: unknown): value is DevAnalyzeReport => {
|
|
33
|
+
const report = value as DevAnalyzeReport | null
|
|
34
|
+
return (
|
|
35
|
+
typeof report === "object" &&
|
|
36
|
+
report !== null &&
|
|
37
|
+
Array.isArray(report.client?.chunks) &&
|
|
38
|
+
Array.isArray(report.routes)
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface Analyzer {
|
|
43
|
+
run(): Promise<AnalyzeAnswer>
|
|
44
|
+
list(): Promise<AnalyzeListRow[]>
|
|
45
|
+
read(id: string): Promise<AnalyzeAnswer>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The saved runs of `dir`; a run asked for while one builds joins that build and answers its result, so one build runs at a time. */
|
|
49
|
+
export function createAnalyzer({
|
|
50
|
+
dir,
|
|
51
|
+
build,
|
|
52
|
+
now = () => new Date(),
|
|
53
|
+
}: {
|
|
54
|
+
dir: string
|
|
55
|
+
build: () => Promise<DevAnalyzeReport | undefined>
|
|
56
|
+
now?: () => Date
|
|
57
|
+
}): Analyzer {
|
|
58
|
+
const root = resolve(dir)
|
|
59
|
+
const answer = (id: string, report: DevAnalyzeReport): AnalyzeAnswer => ({
|
|
60
|
+
id,
|
|
61
|
+
client: report.client,
|
|
62
|
+
routes: report.routes,
|
|
63
|
+
treemap: renderAnalyzeTreemap(report.client),
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
async function load(id: string): Promise<DevAnalyzeReport> {
|
|
67
|
+
if (!RUN_ID.test(id)) throw new AnalyzeError(`Invalid analyze run id ${JSON.stringify(id)}`, 400)
|
|
68
|
+
const file = resolve(root, `${id}.json`)
|
|
69
|
+
if (!file.startsWith(`${root}${sep}`)) throw new AnalyzeError(`Invalid analyze run id ${JSON.stringify(id)}`, 400)
|
|
70
|
+
let text: string
|
|
71
|
+
try {
|
|
72
|
+
text = await readFile(file, "utf8")
|
|
73
|
+
} catch {
|
|
74
|
+
throw new AnalyzeError(`No analyze run ${JSON.stringify(id)}`, 404)
|
|
75
|
+
}
|
|
76
|
+
let parsed: unknown
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(text)
|
|
79
|
+
} catch {
|
|
80
|
+
throw new AnalyzeError(`Analyze run ${JSON.stringify(id)} is not valid JSON`, 500)
|
|
81
|
+
}
|
|
82
|
+
if (!isReport(parsed)) throw new AnalyzeError(`Analyze run ${JSON.stringify(id)} is not an analyze report`, 500)
|
|
83
|
+
return parsed
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function save(): Promise<AnalyzeAnswer> {
|
|
87
|
+
const report = await build()
|
|
88
|
+
if (!report) throw new AnalyzeError("The analyze build runs only under hamur dev", 503)
|
|
89
|
+
const id = now().toISOString()
|
|
90
|
+
await mkdir(root, { recursive: true })
|
|
91
|
+
await writeFile(join(root, `${id}.json`), `${JSON.stringify({ client: report.client, routes: report.routes })}\n`)
|
|
92
|
+
return answer(id, report)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let running: Promise<AnalyzeAnswer> | undefined
|
|
96
|
+
return {
|
|
97
|
+
run() {
|
|
98
|
+
return (running ??= save().finally(() => {
|
|
99
|
+
running = undefined
|
|
100
|
+
}))
|
|
101
|
+
},
|
|
102
|
+
async list() {
|
|
103
|
+
const names = await readdir(root).catch(() => [] as string[])
|
|
104
|
+
const ids = names
|
|
105
|
+
.filter((name) => name.endsWith(".json") && RUN_ID.test(name.slice(0, -5)))
|
|
106
|
+
.map((name) => name.slice(0, -5))
|
|
107
|
+
ids.sort().reverse()
|
|
108
|
+
const rows = await Promise.all(
|
|
109
|
+
ids.map(async (id): Promise<AnalyzeListRow | undefined> => {
|
|
110
|
+
const report = await load(id).catch(() => undefined)
|
|
111
|
+
return (
|
|
112
|
+
report && {
|
|
113
|
+
id,
|
|
114
|
+
bytes: report.client.bytes,
|
|
115
|
+
gzip: report.client.gzip,
|
|
116
|
+
chunks: report.client.chunks.length,
|
|
117
|
+
routes: report.routes.length,
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
}),
|
|
121
|
+
)
|
|
122
|
+
return rows.filter((row): row is AnalyzeListRow => row !== undefined)
|
|
123
|
+
},
|
|
124
|
+
async read(id) {
|
|
125
|
+
return answer(id, await load(id))
|
|
126
|
+
},
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { link, lstat, mkdir, open, realpath, rename, unlink } from "node:fs/promises"
|
|
2
|
+
import { dirname, extname, isAbsolute, join, relative, sep } from "node:path"
|
|
3
|
+
import type { DevPublicAsset } from "hamur/kit"
|
|
4
|
+
import { json } from "./handler.ts"
|
|
5
|
+
|
|
6
|
+
export type AssetType = "image" | "font" | "text" | "other"
|
|
7
|
+
|
|
8
|
+
const shown = (rootDir: string, path: string): string => {
|
|
9
|
+
if (!isAbsolute(path)) return path
|
|
10
|
+
const inside = relative(rootDir, path)
|
|
11
|
+
return inside.startsWith("..") || isAbsolute(inside) ? path : inside.split(sep).join("/")
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** `api/assets`: one public file; `module` marks a module's asset, which the tab shows read-only. */
|
|
15
|
+
export interface AssetRow {
|
|
16
|
+
url: string
|
|
17
|
+
file?: string
|
|
18
|
+
bytes: number
|
|
19
|
+
type: AssetType
|
|
20
|
+
width?: number
|
|
21
|
+
height?: number
|
|
22
|
+
module?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024
|
|
26
|
+
|
|
27
|
+
const MULTIPART_SLACK = 64 * 1024
|
|
28
|
+
|
|
29
|
+
const TOO_LARGE = "File is over 50 MB"
|
|
30
|
+
const NOT_MULTIPART = "The body must be multipart/form-data with one file part"
|
|
31
|
+
const BAD_NAME = "A file name may not hold .. or a slash"
|
|
32
|
+
|
|
33
|
+
const EXTENSIONS: Record<AssetType, string[]> = {
|
|
34
|
+
image: ["png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "ico", "bmp", "tif", "tiff", "heic"],
|
|
35
|
+
font: ["woff", "woff2", "ttf", "otf", "eot"],
|
|
36
|
+
text: [
|
|
37
|
+
"txt",
|
|
38
|
+
"md",
|
|
39
|
+
"json",
|
|
40
|
+
"xml",
|
|
41
|
+
"csv",
|
|
42
|
+
"css",
|
|
43
|
+
"js",
|
|
44
|
+
"mjs",
|
|
45
|
+
"html",
|
|
46
|
+
"htm",
|
|
47
|
+
"webmanifest",
|
|
48
|
+
"yml",
|
|
49
|
+
"yaml",
|
|
50
|
+
"toml",
|
|
51
|
+
"map",
|
|
52
|
+
],
|
|
53
|
+
other: [],
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const TYPES = new Map(
|
|
57
|
+
Object.entries(EXTENSIONS).flatMap(([type, extensions]) =>
|
|
58
|
+
extensions.map((extension) => [`.${extension}`, type as AssetType] as const),
|
|
59
|
+
),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
/** Bun.Image decodes no SVG or icon. */
|
|
63
|
+
const RASTER = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".bmp", ".tif", ".tiff", ".heic"])
|
|
64
|
+
|
|
65
|
+
export const assetType = (path: string): AssetType => TYPES.get(extname(path).toLowerCase() as `.${string}`) ?? "other"
|
|
66
|
+
|
|
67
|
+
/** Width and height from the image's header with `Bun.Image`; `undefined` when it does not decode. */
|
|
68
|
+
export async function imageSize(input: Blob | Uint8Array): Promise<{ width: number; height: number } | undefined> {
|
|
69
|
+
try {
|
|
70
|
+
const { width, height } = await new Bun.Image(input).metadata()
|
|
71
|
+
return { width, height }
|
|
72
|
+
} catch {
|
|
73
|
+
return undefined
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** One row of `api/assets`; `undefined` for a file gone since it was listed. */
|
|
78
|
+
export async function assetRow(rootDir: string, baseURL: string, asset: DevPublicAsset): Promise<AssetRow | undefined> {
|
|
79
|
+
let bytes: number
|
|
80
|
+
let input: Blob | Uint8Array
|
|
81
|
+
if (asset.bytes) {
|
|
82
|
+
bytes = asset.bytes.length
|
|
83
|
+
input = asset.bytes
|
|
84
|
+
} else {
|
|
85
|
+
const file = Bun.file(asset.file!)
|
|
86
|
+
const info = await file.stat().catch(() => undefined)
|
|
87
|
+
if (!info?.isFile()) return undefined
|
|
88
|
+
bytes = info.size
|
|
89
|
+
input = file
|
|
90
|
+
}
|
|
91
|
+
const type = assetType(asset.path)
|
|
92
|
+
const size = type === "image" && RASTER.has(extname(asset.path).toLowerCase()) ? await imageSize(input) : undefined
|
|
93
|
+
return {
|
|
94
|
+
url: `${baseURL}${asset.path.slice(1)}`,
|
|
95
|
+
...(asset.file ? { file: shown(rootDir, asset.file) } : {}),
|
|
96
|
+
bytes,
|
|
97
|
+
type,
|
|
98
|
+
...size,
|
|
99
|
+
...(asset.source === "public"
|
|
100
|
+
? {}
|
|
101
|
+
: { module: asset.module ?? (asset.source === "dir" ? "addPublicAssets" : "emitPublicAsset") }),
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** GET `api/assets`: `public/` files, then module assets, sorted by URL. */
|
|
106
|
+
export async function assetsAnswer(rootDir: string, baseURL: string, assets: DevPublicAsset[]): Promise<AssetRow[]> {
|
|
107
|
+
const rows = await Promise.all(assets.map((asset) => assetRow(rootDir, baseURL, asset)))
|
|
108
|
+
return rows.filter((row): row is AssetRow => row !== undefined)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The reason `name` cannot be written as `public/<name>`, or `undefined`. */
|
|
112
|
+
export function nameProblem(name: string): string | undefined {
|
|
113
|
+
if (name === "") return "The file part has no name"
|
|
114
|
+
if (name.includes("..") || name.includes("/") || name.includes("\\")) return BAD_NAME
|
|
115
|
+
if (/[\u0000-\u001f\u007f]/.test(name)) return "A file name may not hold a control character"
|
|
116
|
+
if (name.startsWith(".")) return "A file name may not start with a dot"
|
|
117
|
+
return undefined
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The body, read until it passes `limit` bytes; past it the stream errors and the rest is not read. */
|
|
121
|
+
function capped(
|
|
122
|
+
body: ReadableStream<Uint8Array>,
|
|
123
|
+
limit: number,
|
|
124
|
+
): { stream: ReadableStream<Uint8Array>; over: () => boolean } {
|
|
125
|
+
let seen = 0
|
|
126
|
+
const stream = body.pipeThrough(
|
|
127
|
+
new TransformStream<Uint8Array, Uint8Array>({
|
|
128
|
+
transform(chunk, controller) {
|
|
129
|
+
seen += chunk.byteLength
|
|
130
|
+
if (seen > limit) controller.error(new Error(TOO_LARGE))
|
|
131
|
+
else controller.enqueue(chunk)
|
|
132
|
+
},
|
|
133
|
+
}),
|
|
134
|
+
)
|
|
135
|
+
return { stream, over: () => seen > limit }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface UploadOptions {
|
|
139
|
+
rootDir: string
|
|
140
|
+
publicDir: string
|
|
141
|
+
baseURL: string
|
|
142
|
+
rows: () => Promise<AssetRow[]>
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A case-insensitive disk holds one file for `/Logo.png` and `/logo.png`. */
|
|
146
|
+
const foldCase = (url: string): string => url.normalize("NFC").toLowerCase()
|
|
147
|
+
|
|
148
|
+
const isCode = (error: unknown, code: string): boolean => (error as { code?: unknown } | null)?.code === code
|
|
149
|
+
|
|
150
|
+
/** POST `api/assets`: writes the one `file` part as `public/<name>`; an existing file needs `?overwrite=1`. */
|
|
151
|
+
export async function uploadAsset(request: Request, options: UploadOptions): Promise<Response> {
|
|
152
|
+
const type = request.headers.get("content-type") ?? ""
|
|
153
|
+
if (!type.toLowerCase().startsWith("multipart/form-data") || !request.body) return json({ error: NOT_MULTIPART }, 400)
|
|
154
|
+
const limit = MAX_UPLOAD_BYTES + MULTIPART_SLACK
|
|
155
|
+
if (Number(request.headers.get("content-length") ?? 0) > limit) return json({ error: TOO_LARGE }, 413)
|
|
156
|
+
const body = capped(request.body, limit)
|
|
157
|
+
let form: FormData
|
|
158
|
+
try {
|
|
159
|
+
form = await new Response(body.stream, { headers: { "content-type": type } }).formData()
|
|
160
|
+
} catch {
|
|
161
|
+
return json({ error: body.over() ? TOO_LARGE : NOT_MULTIPART }, body.over() ? 413 : 400)
|
|
162
|
+
}
|
|
163
|
+
const parts = form.getAll("file")
|
|
164
|
+
const file = parts[0]
|
|
165
|
+
if (parts.length !== 1 || file === undefined || typeof file === "string") return json({ error: NOT_MULTIPART }, 400)
|
|
166
|
+
if (file.size > MAX_UPLOAD_BYTES) return json({ error: TOO_LARGE }, 413)
|
|
167
|
+
const problem = nameProblem(file.name)
|
|
168
|
+
if (problem) return json({ error: problem }, 400)
|
|
169
|
+
|
|
170
|
+
const url = `${options.baseURL}${file.name}`
|
|
171
|
+
const folded = foldCase(url)
|
|
172
|
+
const held = (await options.rows()).find((row) => row.module !== undefined && foldCase(row.url) === folded)
|
|
173
|
+
if (held) return json({ error: `${url} comes from ${held.module}; module assets are read-only` }, 409)
|
|
174
|
+
|
|
175
|
+
await mkdir(options.publicDir, { recursive: true })
|
|
176
|
+
const dir = await realpath(options.publicDir)
|
|
177
|
+
const target = join(dir, file.name)
|
|
178
|
+
if (dirname(target) !== dir) return json({ error: BAD_NAME }, 400)
|
|
179
|
+
const overwrite = new URL(request.url).searchParams.get("overwrite") === "1"
|
|
180
|
+
const existing = await lstat(target).catch(() => undefined)
|
|
181
|
+
if (existing && !existing.isFile()) return json({ error: `public/${file.name} is not a regular file` }, 409)
|
|
182
|
+
const exists = `public/${file.name} exists; send overwrite=1 to replace it`
|
|
183
|
+
if (existing && !overwrite) return json({ error: exists }, 409)
|
|
184
|
+
const temp = join(dir, `.hamur-upload-${crypto.randomUUID()}`)
|
|
185
|
+
try {
|
|
186
|
+
await (await open(temp, "wx")).close()
|
|
187
|
+
await Bun.write(temp, file)
|
|
188
|
+
if (overwrite) await rename(temp, target)
|
|
189
|
+
else {
|
|
190
|
+
const linked = await link(temp, target).then(
|
|
191
|
+
() => true,
|
|
192
|
+
(error: unknown) => {
|
|
193
|
+
if (isCode(error, "EEXIST")) return false
|
|
194
|
+
throw error
|
|
195
|
+
},
|
|
196
|
+
)
|
|
197
|
+
if (!linked) return json({ error: exists }, 409)
|
|
198
|
+
}
|
|
199
|
+
} finally {
|
|
200
|
+
await unlink(temp).catch(() => {})
|
|
201
|
+
}
|
|
202
|
+
const row = await assetRow(options.rootDir, options.baseURL, {
|
|
203
|
+
path: `/${file.name}`,
|
|
204
|
+
source: "public",
|
|
205
|
+
file: join(options.publicDir, file.name),
|
|
206
|
+
})
|
|
207
|
+
return json(row, existing ? 200 : 201)
|
|
208
|
+
}
|