@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.
- 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 +34 -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,260 @@
|
|
|
1
|
+
import { defineDevtoolsApp, type DevtoolsPage } from "hamur/app"
|
|
2
|
+
import type { DevHook } from "hamur/kit"
|
|
3
|
+
import type { SpanRow } from "../dev/timeline.ts"
|
|
4
|
+
import { element, pill, UI } from "../panel/ui.ts"
|
|
5
|
+
import {
|
|
6
|
+
clientEvents,
|
|
7
|
+
formatMs,
|
|
8
|
+
hookRows,
|
|
9
|
+
tickStep,
|
|
10
|
+
timelineRows,
|
|
11
|
+
type MarkLike,
|
|
12
|
+
type ResourceLike,
|
|
13
|
+
type TimelineRow,
|
|
14
|
+
} from "./timeline-model.ts"
|
|
15
|
+
|
|
16
|
+
const POLL_MS = 1000
|
|
17
|
+
const MAX_SPAN_ATTEMPTS = 6
|
|
18
|
+
|
|
19
|
+
type View = "timeline" | "hooks"
|
|
20
|
+
|
|
21
|
+
const BAR_COLORS: Record<string, string> = {
|
|
22
|
+
server: "bg-fg-3",
|
|
23
|
+
fetch: "bg-accent opacity-55",
|
|
24
|
+
chunk: "bg-accent opacity-55",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
|
|
28
|
+
|
|
29
|
+
async function getJson<T>(url: string): Promise<T> {
|
|
30
|
+
const response = await fetch(url)
|
|
31
|
+
const body = (await response.json()) as T & { error?: string }
|
|
32
|
+
if (!response.ok) throw new Error(body.error ?? `${url} answered ${response.status}`)
|
|
33
|
+
return body
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function ruler(total: number): HTMLElement {
|
|
37
|
+
const step = tickStep(total)
|
|
38
|
+
const bar = element("div", { className: "relative h-5 ml-48 mr-18 border-b border-line" })
|
|
39
|
+
for (let at = 0; at <= total; at += step) {
|
|
40
|
+
const tick = element(
|
|
41
|
+
"span",
|
|
42
|
+
{ className: "absolute top-0.5 pl-0.5 border-l border-line font-mono text-2xs text-fg-3" },
|
|
43
|
+
formatMs(at),
|
|
44
|
+
)
|
|
45
|
+
tick.style.left = `${(at / total) * 100}%`
|
|
46
|
+
bar.append(tick)
|
|
47
|
+
}
|
|
48
|
+
return bar
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function rowElement(
|
|
52
|
+
row: TimelineRow,
|
|
53
|
+
t0: number,
|
|
54
|
+
total: number,
|
|
55
|
+
selected: boolean,
|
|
56
|
+
select: (id: string) => void,
|
|
57
|
+
): HTMLElement {
|
|
58
|
+
const button = element("button", {
|
|
59
|
+
type: "button",
|
|
60
|
+
className: `grid grid-cols-[12rem_minmax(0,1fr)_4.5rem] items-center w-full h-7 p-0 border-0 border-b border-line text-left text-fg cursor-pointer hover:bg-hover ${selected ? "bg-accent-soft" : "bg-transparent"}`,
|
|
61
|
+
})
|
|
62
|
+
button.dataset.row = ""
|
|
63
|
+
button.dataset.id = row.id
|
|
64
|
+
button.dataset.kind = row.kind
|
|
65
|
+
button.dataset.depth = String(row.depth)
|
|
66
|
+
button.dataset.label = row.label
|
|
67
|
+
button.setAttribute("aria-current", String(selected))
|
|
68
|
+
const label = element(
|
|
69
|
+
"span",
|
|
70
|
+
{ className: "truncate font-mono text-xs" },
|
|
71
|
+
element("em", { className: "mr-1.5 not-italic text-fg-3" }, row.kind),
|
|
72
|
+
row.label,
|
|
73
|
+
)
|
|
74
|
+
label.style.paddingLeft = `${row.depth * 1}rem`
|
|
75
|
+
const track = element("span", { className: "relative h-3.5" })
|
|
76
|
+
const bar = element("i", { className: `absolute inset-y-0.5 rounded-sm ${BAR_COLORS[row.kind] ?? "bg-accent"}` })
|
|
77
|
+
bar.style.left = `${((row.start - t0) / total) * 100}%`
|
|
78
|
+
bar.style.width = `max(2px, ${((row.end - row.start) / total) * 100}%)`
|
|
79
|
+
track.append(bar)
|
|
80
|
+
button.append(
|
|
81
|
+
label,
|
|
82
|
+
track,
|
|
83
|
+
element("span", { className: "pr-1.5 text-right font-mono text-2xs text-fg-3" }, formatMs(row.end - row.start)),
|
|
84
|
+
)
|
|
85
|
+
button.addEventListener("click", () => select(row.id))
|
|
86
|
+
return button
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function detailPane(row: TimelineRow | undefined, t0: number): HTMLElement {
|
|
90
|
+
const pane = element("aside", { className: "w-64 flex-none p-4 border-l border-line overflow-auto" })
|
|
91
|
+
if (!row) {
|
|
92
|
+
pane.append(element("p", { className: UI.hint }, "Select an event"))
|
|
93
|
+
return pane
|
|
94
|
+
}
|
|
95
|
+
const list = element("dl", { className: "m-0" })
|
|
96
|
+
const add = (term: string, value: string) =>
|
|
97
|
+
list.append(
|
|
98
|
+
element("dt", { className: "mt-2 text-xs text-fg-3" }, term),
|
|
99
|
+
element("dd", { className: "m-0 font-mono text-xs text-fg break-all" }, value),
|
|
100
|
+
)
|
|
101
|
+
add("Kind", row.kind)
|
|
102
|
+
add("Start", `+${formatMs(row.start - t0)}`)
|
|
103
|
+
add("Duration", formatMs(row.end - row.start))
|
|
104
|
+
for (const [key, value] of Object.entries(row.detail)) if (value !== "") add(key, value)
|
|
105
|
+
pane.append(element("h2", { className: "m-0 mb-1 font-mono text-sm font-medium text-fg break-all" }, row.label), list)
|
|
106
|
+
return pane
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function hooksView(rows: ReturnType<typeof hookRows>): HTMLElement {
|
|
110
|
+
if (!rows.length) return element("p", { className: UI.notice }, "No hook has been called yet")
|
|
111
|
+
const body = element("tbody")
|
|
112
|
+
for (const row of rows) {
|
|
113
|
+
const tr = element(
|
|
114
|
+
"tr",
|
|
115
|
+
{ className: UI.tr },
|
|
116
|
+
element("td", { className: `${UI.td} font-mono text-sm text-fg` }, row.hook),
|
|
117
|
+
element("td", { className: `${UI.td} text-xs text-fg-3` }, row.kind),
|
|
118
|
+
element("td", { className: `${UI.td} font-mono text-xs text-fg-2 tabular-nums` }, String(row.calls)),
|
|
119
|
+
element("td", { className: `${UI.td} font-mono text-xs text-fg-2 tabular-nums` }, formatMs(row.totalMs)),
|
|
120
|
+
)
|
|
121
|
+
tr.dataset.hook = row.hook
|
|
122
|
+
tr.dataset.kind = row.kind
|
|
123
|
+
body.append(tr)
|
|
124
|
+
}
|
|
125
|
+
return element(
|
|
126
|
+
"table",
|
|
127
|
+
{ className: "w-full border-collapse" },
|
|
128
|
+
element(
|
|
129
|
+
"thead",
|
|
130
|
+
{ className: "sticky top-0 bg-panel" },
|
|
131
|
+
element("tr", {}, ...["Hook", "Kind", "Calls", "Total"].map((head) => element("th", { className: UI.th }, head))),
|
|
132
|
+
),
|
|
133
|
+
body,
|
|
134
|
+
)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export default defineDevtoolsApp({
|
|
138
|
+
init(canvas, ctx) {
|
|
139
|
+
const page: DevtoolsPage | undefined = ctx.page
|
|
140
|
+
if (!page) {
|
|
141
|
+
canvas.append(element("p", { className: UI.notice }, "Open this tab from the app page"))
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
canvas.className = "flex flex-col flex-1 min-h-0"
|
|
145
|
+
const parent = window.parent
|
|
146
|
+
let view: View = "timeline"
|
|
147
|
+
let selected: string | undefined
|
|
148
|
+
let since = 0
|
|
149
|
+
let runnerHooks: DevHook[] = []
|
|
150
|
+
let problem = ""
|
|
151
|
+
let last = ""
|
|
152
|
+
const spans = new Map<string, SpanRow[]>()
|
|
153
|
+
const attempts = new Map<string, number>()
|
|
154
|
+
const asking = new Set<string>()
|
|
155
|
+
|
|
156
|
+
const bar = element("div", { className: UI.strip })
|
|
157
|
+
const tabs = (["timeline", "hooks"] as const).map((name) => {
|
|
158
|
+
const button = element(
|
|
159
|
+
"button",
|
|
160
|
+
{ type: "button", className: pill(name === view) },
|
|
161
|
+
name === "timeline" ? "Timeline" : "Hooks",
|
|
162
|
+
)
|
|
163
|
+
button.dataset.view = name
|
|
164
|
+
button.addEventListener("click", () => {
|
|
165
|
+
view = name
|
|
166
|
+
last = ""
|
|
167
|
+
void refresh()
|
|
168
|
+
})
|
|
169
|
+
return button
|
|
170
|
+
})
|
|
171
|
+
const clear = element("button", { type: "button", className: UI.button }, "Clear")
|
|
172
|
+
clear.dataset.clear = ""
|
|
173
|
+
clear.addEventListener("click", () => {
|
|
174
|
+
since = Date.now()
|
|
175
|
+
last = ""
|
|
176
|
+
void refresh()
|
|
177
|
+
})
|
|
178
|
+
bar.append(...tabs, element("span", { className: "flex-1" }), clear)
|
|
179
|
+
const body = element("div", { className: "flex-1 min-h-0 overflow-auto" })
|
|
180
|
+
const note = element("p", { className: `m-0 px-4 py-1 ${UI.fail} empty:hidden` })
|
|
181
|
+
note.dataset.error = ""
|
|
182
|
+
canvas.append(bar, note, body)
|
|
183
|
+
|
|
184
|
+
const loadSpans = (trace: string): void => {
|
|
185
|
+
const tried = attempts.get(trace) ?? 0
|
|
186
|
+
if (asking.has(trace) || tried >= MAX_SPAN_ATTEMPTS || (spans.get(trace)?.length ?? 0) > 0) return
|
|
187
|
+
asking.add(trace)
|
|
188
|
+
attempts.set(trace, tried + 1)
|
|
189
|
+
getJson<SpanRow[]>(`api/spans?trace=${trace}`)
|
|
190
|
+
.then(
|
|
191
|
+
(rows) => {
|
|
192
|
+
spans.set(trace, rows)
|
|
193
|
+
if (rows.length) last = ""
|
|
194
|
+
},
|
|
195
|
+
(error: unknown) => void (problem = messageOf(error)),
|
|
196
|
+
)
|
|
197
|
+
.finally(() => asking.delete(trace))
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function refresh(): Promise<void> {
|
|
201
|
+
const marks = page!.marks() as unknown as MarkLike[]
|
|
202
|
+
if (view === "hooks") {
|
|
203
|
+
try {
|
|
204
|
+
runnerHooks = await getJson<DevHook[]>("api/hooks")
|
|
205
|
+
problem = ""
|
|
206
|
+
} catch (error) {
|
|
207
|
+
problem = messageOf(error)
|
|
208
|
+
}
|
|
209
|
+
const rows = hookRows(runnerHooks, marks)
|
|
210
|
+
const snapshot = JSON.stringify(["hooks", problem, rows])
|
|
211
|
+
paint(snapshot, () => hooksView(rows))
|
|
212
|
+
return
|
|
213
|
+
}
|
|
214
|
+
const resources = parent.performance.getEntriesByType("resource") as unknown as ResourceLike[]
|
|
215
|
+
const events = clientEvents(marks, resources, parent.performance.timeOrigin).filter((event) => event.end >= since)
|
|
216
|
+
for (const event of events) if (event.trace) loadSpans(event.trace)
|
|
217
|
+
const rows = timelineRows(events, spans)
|
|
218
|
+
const snapshot = JSON.stringify(["timeline", selected, problem, rows.map((row) => [row.id, row.start, row.end])])
|
|
219
|
+
paint(snapshot, () => {
|
|
220
|
+
if (!rows.length)
|
|
221
|
+
return element(
|
|
222
|
+
"p",
|
|
223
|
+
{ className: UI.notice },
|
|
224
|
+
"No events yet. Navigate in the app; marks are written while devServer.timing is on.",
|
|
225
|
+
)
|
|
226
|
+
const t0 = Math.min(...rows.map((row) => row.start))
|
|
227
|
+
const total = Math.max(1, Math.max(...rows.map((row) => row.end)) - t0)
|
|
228
|
+
const chosen = rows.find((row) => row.id === selected)
|
|
229
|
+
const list = element(
|
|
230
|
+
"div",
|
|
231
|
+
{ className: "flex-1 min-w-0" },
|
|
232
|
+
ruler(total),
|
|
233
|
+
...rows.map((row) =>
|
|
234
|
+
rowElement(row, t0, total, row.id === selected, (id) => ((selected = id), (last = ""), void refresh())),
|
|
235
|
+
),
|
|
236
|
+
)
|
|
237
|
+
return element("div", { className: "flex items-start" }, list, detailPane(chosen, t0))
|
|
238
|
+
})
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function paint(snapshot: string, make: () => HTMLElement): void {
|
|
242
|
+
for (const button of tabs) {
|
|
243
|
+
button.setAttribute("aria-pressed", String(button.dataset.view === view))
|
|
244
|
+
button.className = pill(button.dataset.view === view)
|
|
245
|
+
}
|
|
246
|
+
note.textContent = problem
|
|
247
|
+
if (snapshot === last) return
|
|
248
|
+
last = snapshot
|
|
249
|
+
body.replaceChildren(make())
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
void refresh()
|
|
253
|
+
const stop = page.on("mark", () => void refresh())
|
|
254
|
+
const timer = setInterval(() => void refresh(), POLL_MS)
|
|
255
|
+
return () => {
|
|
256
|
+
stop()
|
|
257
|
+
clearInterval(timer)
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
})
|
package/src/tester.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
export const REQUESTS_KEY = "hamur:devtools:requests"
|
|
2
|
+
|
|
3
|
+
const MAX_SAVED = 20
|
|
4
|
+
const MAX_DEPTH = 6
|
|
5
|
+
|
|
6
|
+
type Json = Record<string, unknown>
|
|
7
|
+
|
|
8
|
+
const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value)
|
|
9
|
+
|
|
10
|
+
/** A value that satisfies `schema`, the way a person would start typing one: an `example`, `default`, `const` or first `enum` entry wins, else the type's empty value; an object holds each of its properties. */
|
|
11
|
+
export function prefillBody(schema: unknown, depth = 0): unknown {
|
|
12
|
+
if (!isObject(schema) || depth > MAX_DEPTH) return null
|
|
13
|
+
if (Array.isArray(schema.examples) && schema.examples.length) return schema.examples[0]
|
|
14
|
+
for (const key of ["example", "default", "const"]) if (key in schema) return schema[key]
|
|
15
|
+
if (Array.isArray(schema.enum) && schema.enum.length) return schema.enum[0]
|
|
16
|
+
for (const key of ["oneOf", "anyOf"]) {
|
|
17
|
+
const options = schema[key]
|
|
18
|
+
if (Array.isArray(options) && options.length) return prefillBody(options[0], depth + 1)
|
|
19
|
+
}
|
|
20
|
+
if (Array.isArray(schema.allOf))
|
|
21
|
+
return Object.assign({}, ...schema.allOf.map((part) => (isObject(part) ? prefillBody(part, depth + 1) : {})))
|
|
22
|
+
const declared = Array.isArray(schema.type) ? schema.type.find((type) => type !== "null") : schema.type
|
|
23
|
+
const type = declared ?? (isObject(schema.properties) ? "object" : undefined)
|
|
24
|
+
if (type === "object") {
|
|
25
|
+
const properties = isObject(schema.properties) ? schema.properties : {}
|
|
26
|
+
return Object.fromEntries(
|
|
27
|
+
Object.entries(properties).map(([key, property]) => [key, prefillBody(property, depth + 1)]),
|
|
28
|
+
)
|
|
29
|
+
}
|
|
30
|
+
if (type === "array") return []
|
|
31
|
+
if (type === "string") return ""
|
|
32
|
+
if (type === "number" || type === "integer") return typeof schema.minimum === "number" ? schema.minimum : 0
|
|
33
|
+
if (type === "boolean") return false
|
|
34
|
+
return null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const PARAM = /(\*\*)?:([A-Za-z_]\w*)(\([^)]*\))?/g
|
|
38
|
+
|
|
39
|
+
/** The names a server route pattern (`/api/users/:id`, `/api/**:rest`) reads from the path. */
|
|
40
|
+
export function paramNames(pattern: string): string[] {
|
|
41
|
+
return [...pattern.matchAll(PARAM)].map((match) => match[2]!)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** `pattern` with each `:name` replaced by its value, percent-encoded (a `**:name` keeps its slashes); a name with no value stays as written. */
|
|
45
|
+
export function fillPattern(pattern: string, params: Record<string, string>): string {
|
|
46
|
+
return pattern.replace(PARAM, (whole, rest: string | undefined, name: string) => {
|
|
47
|
+
const value = params[name]
|
|
48
|
+
if (!value) return whole
|
|
49
|
+
return rest ? value.split("/").map(encodeURIComponent).join("/") : encodeURIComponent(value)
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type Pairs = Array<[string, string]>
|
|
54
|
+
|
|
55
|
+
/** `path` with `query` appended after any query it already has; empty names are left out. */
|
|
56
|
+
export function withQuery(path: string, query: Pairs): string {
|
|
57
|
+
const at = path.indexOf("?")
|
|
58
|
+
const base = at === -1 ? path : path.slice(0, at)
|
|
59
|
+
const search = new URLSearchParams(at === -1 ? "" : path.slice(at + 1))
|
|
60
|
+
for (const [name, value] of query) if (name) search.append(name, value)
|
|
61
|
+
const text = search.toString()
|
|
62
|
+
return text ? `${base}?${text}` : base
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The URL `typed` names on `origin`; a URL of another host (a full URL, `//host/…`, a different port or scheme) is refused. */
|
|
66
|
+
export function sameOriginURL(typed: string, origin: string): URL {
|
|
67
|
+
let url: URL
|
|
68
|
+
try {
|
|
69
|
+
url = new URL(typed, origin)
|
|
70
|
+
} catch {
|
|
71
|
+
throw new Error(`"${typed}" is not a URL`)
|
|
72
|
+
}
|
|
73
|
+
if (url.origin !== origin)
|
|
74
|
+
throw new Error(`Only paths of this server can be sent; "${typed}" points at ${url.origin}`)
|
|
75
|
+
return url
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type BodyKind = "none" | "json" | "form"
|
|
79
|
+
|
|
80
|
+
export interface TesterState {
|
|
81
|
+
method: string
|
|
82
|
+
url: string
|
|
83
|
+
params: Record<string, string>
|
|
84
|
+
query: Pairs
|
|
85
|
+
headers: Pairs
|
|
86
|
+
bodyKind: BodyKind
|
|
87
|
+
json: string
|
|
88
|
+
form: Pairs
|
|
89
|
+
cookies: Pairs
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface BuiltRequest {
|
|
93
|
+
url: URL
|
|
94
|
+
init: RequestInit
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const BODYLESS = ["GET", "HEAD", "OPTIONS", "TRACE"]
|
|
98
|
+
|
|
99
|
+
/** The `fetch` arguments of a form state; throws a message for a URL of another origin or a JSON body that does not parse. */
|
|
100
|
+
export function buildRequest(state: TesterState, origin: string): BuiltRequest {
|
|
101
|
+
const url = sameOriginURL(state.url, origin)
|
|
102
|
+
const headers = new Headers()
|
|
103
|
+
for (const [name, value] of state.headers) if (name.trim()) headers.set(name.trim(), value)
|
|
104
|
+
const init: RequestInit = { method: state.method, headers, redirect: "manual", credentials: "same-origin" }
|
|
105
|
+
if (!BODYLESS.includes(state.method) && state.bodyKind === "json") {
|
|
106
|
+
try {
|
|
107
|
+
JSON.parse(state.json)
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw new Error(`The body must be JSON: ${error instanceof Error ? error.message : String(error)}`)
|
|
110
|
+
}
|
|
111
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json")
|
|
112
|
+
init.body = state.json
|
|
113
|
+
} else if (!BODYLESS.includes(state.method) && state.bodyKind === "form") {
|
|
114
|
+
const form = new URLSearchParams()
|
|
115
|
+
for (const [name, value] of state.form) if (name) form.append(name, value)
|
|
116
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/x-www-form-urlencoded")
|
|
117
|
+
init.body = form.toString()
|
|
118
|
+
}
|
|
119
|
+
return { url, init }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The `name=value` cookies to set before a request, as `document.cookie` writes them. */
|
|
123
|
+
export function cookieWrites(cookies: Pairs): string[] {
|
|
124
|
+
return cookies
|
|
125
|
+
.filter(([name]) => name.trim())
|
|
126
|
+
.map(([name, value]) => `${encodeURIComponent(name.trim())}=${encodeURIComponent(value)}; path=/; SameSite=Lax`)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface SavedRequest {
|
|
130
|
+
savedAt: string
|
|
131
|
+
state: TesterState
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export type SavedRequests = Record<string, SavedRequest[]>
|
|
135
|
+
|
|
136
|
+
export const routeKey = (method: string, path: string): string => `${method} ${path}`
|
|
137
|
+
|
|
138
|
+
/** The saved requests of every route; anything that is not the saved shape reads as none. */
|
|
139
|
+
export function readSaved(storage: Pick<Storage, "getItem"> | undefined): SavedRequests {
|
|
140
|
+
try {
|
|
141
|
+
const parsed: unknown = JSON.parse(storage?.getItem(REQUESTS_KEY) ?? "{}")
|
|
142
|
+
if (!isObject(parsed)) return {}
|
|
143
|
+
return Object.fromEntries(Object.entries(parsed).filter(([, list]) => Array.isArray(list))) as SavedRequests
|
|
144
|
+
} catch {
|
|
145
|
+
return {}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** `saved` with `request` added first under `key`, at most `MAX_SAVED` kept. */
|
|
150
|
+
export function addSaved(saved: SavedRequests, key: string, request: SavedRequest): SavedRequests {
|
|
151
|
+
return { ...saved, [key]: [request, ...(saved[key] ?? [])].slice(0, MAX_SAVED) }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function writeSaved(storage: Pick<Storage, "setItem"> | undefined, saved: SavedRequests): void {
|
|
155
|
+
try {
|
|
156
|
+
storage?.setItem(REQUESTS_KEY, JSON.stringify(saved))
|
|
157
|
+
} catch {}
|
|
158
|
+
}
|