@hamur/devtools 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +24 -2
  3. package/dist/src/client.js +780 -0
  4. package/dist/src/index.js +1711 -0
  5. package/dist/types/src/apps/locator.d.ts +3 -0
  6. package/dist/types/src/bridge.d.ts +8 -0
  7. package/dist/types/src/client.d.ts +3 -0
  8. package/dist/types/src/dev/analyze.d.ts +31 -0
  9. package/dist/types/src/dev/assets.d.ts +33 -0
  10. package/dist/types/src/dev/authz.d.ts +49 -0
  11. package/dist/types/src/dev/bundle.d.ts +22 -0
  12. package/dist/types/src/dev/config.d.ts +24 -0
  13. package/dist/types/src/dev/handler.d.ts +20 -0
  14. package/dist/types/src/dev/modules.d.ts +28 -0
  15. package/dist/types/src/dev/overview.d.ts +20 -0
  16. package/dist/types/src/dev/processes.d.ts +4 -0
  17. package/dist/types/src/dev/server-routes.d.ts +7 -0
  18. package/dist/types/src/dev/tasks.d.ts +26 -0
  19. package/dist/types/src/dev/timeline.d.ts +20 -0
  20. package/dist/types/src/dev/virtual.d.ts +9 -0
  21. package/dist/types/src/icons.d.ts +24 -0
  22. package/dist/types/src/index.d.ts +8 -0
  23. package/dist/types/src/locator.d.ts +17 -0
  24. package/dist/types/src/mask.d.ts +8 -0
  25. package/dist/types/src/module.d.ts +27 -0
  26. package/dist/types/src/open-in-editor.d.ts +4 -0
  27. package/dist/types/src/options.d.ts +14 -0
  28. package/dist/types/src/panel/document.d.ts +16 -0
  29. package/dist/types/src/panel/groups.d.ts +14 -0
  30. package/dist/types/src/panel/index.d.ts +1 -0
  31. package/dist/types/src/panel/settings.d.ts +69 -0
  32. package/dist/types/src/panel/style.d.ts +1 -0
  33. package/dist/types/src/panel/ui.d.ts +34 -0
  34. package/dist/types/src/server/authz.d.ts +30 -0
  35. package/dist/types/src/server/index.d.ts +3 -0
  36. package/dist/types/src/server/routes.d.ts +6 -0
  37. package/dist/types/src/server/storage.d.ts +56 -0
  38. package/dist/types/src/source-link.d.ts +2 -0
  39. package/dist/types/src/tabs/analyze-model.d.ts +31 -0
  40. package/dist/types/src/tabs/analyze.d.ts +2 -0
  41. package/dist/types/src/tabs/assets.d.ts +11 -0
  42. package/dist/types/src/tabs/audit-model.d.ts +42 -0
  43. package/dist/types/src/tabs/audit.d.ts +2 -0
  44. package/dist/types/src/tabs/authz-model.d.ts +11 -0
  45. package/dist/types/src/tabs/authz.d.ts +2 -0
  46. package/dist/types/src/tabs/config.d.ts +8 -0
  47. package/dist/types/src/tabs/inspect.d.ts +7 -0
  48. package/dist/types/src/tabs/modules.d.ts +4 -0
  49. package/dist/types/src/tabs/overview.d.ts +2 -0
  50. package/dist/types/src/tabs/pages.d.ts +2 -0
  51. package/dist/types/src/tabs/payload.d.ts +6 -0
  52. package/dist/types/src/tabs/plugins-model.d.ts +15 -0
  53. package/dist/types/src/tabs/plugins.d.ts +2 -0
  54. package/dist/types/src/tabs/seo-model.d.ts +36 -0
  55. package/dist/types/src/tabs/seo.d.ts +2 -0
  56. package/dist/types/src/tabs/server-routes.d.ts +2 -0
  57. package/dist/types/src/tabs/storage.d.ts +13 -0
  58. package/dist/types/src/tabs/tasks-model.d.ts +16 -0
  59. package/dist/types/src/tabs/tasks.d.ts +2 -0
  60. package/dist/types/src/tabs/terminals-model.d.ts +53 -0
  61. package/dist/types/src/tabs/terminals.d.ts +2 -0
  62. package/dist/types/src/tabs/timeline-model.d.ts +58 -0
  63. package/dist/types/src/tabs/timeline.d.ts +2 -0
  64. package/dist/types/src/tester.d.ts +43 -0
  65. package/dist/types/src/toolbar/element.d.ts +28 -0
  66. package/dist/types/src/toolbar/shortcut.d.ts +14 -0
  67. package/dist/types/src/toolbar/style.d.ts +3 -0
  68. package/dist/types/src/view-context.d.ts +13 -0
  69. package/package.json +28 -4
  70. package/src/apps/locator.ts +131 -0
  71. package/src/bridge.ts +172 -0
  72. package/src/client.ts +10 -0
  73. package/src/dev/analyze.ts +128 -0
  74. package/src/dev/assets.ts +208 -0
  75. package/src/dev/authz.ts +162 -0
  76. package/src/dev/bundle.ts +91 -0
  77. package/src/dev/config.ts +132 -0
  78. package/src/dev/handler.ts +161 -0
  79. package/src/dev/modules.ts +60 -0
  80. package/src/dev/overview.ts +57 -0
  81. package/src/dev/processes.ts +34 -0
  82. package/src/dev/server-routes.ts +14 -0
  83. package/src/dev/tasks.ts +93 -0
  84. package/src/dev/timeline.ts +43 -0
  85. package/src/dev/virtual.ts +40 -0
  86. package/src/env.d.ts +21 -0
  87. package/src/icons.ts +48 -0
  88. package/src/index.ts +12 -0
  89. package/src/locator.ts +31 -0
  90. package/src/mask.ts +16 -0
  91. package/src/module.ts +352 -0
  92. package/src/open-in-editor.ts +18 -0
  93. package/src/options.ts +36 -0
  94. package/src/panel/document.ts +60 -0
  95. package/src/panel/groups.ts +41 -0
  96. package/src/panel/index.ts +429 -0
  97. package/src/panel/settings.ts +224 -0
  98. package/src/panel/style.ts +321 -0
  99. package/src/panel/ui.ts +52 -0
  100. package/src/server/authz.ts +110 -0
  101. package/src/server/index.ts +25 -0
  102. package/src/server/routes.ts +51 -0
  103. package/src/server/storage.ts +251 -0
  104. package/src/source-link.ts +29 -0
  105. package/src/tabs/analyze-model.ts +97 -0
  106. package/src/tabs/analyze.ts +217 -0
  107. package/src/tabs/assets.ts +375 -0
  108. package/src/tabs/audit-model.ts +216 -0
  109. package/src/tabs/audit.ts +223 -0
  110. package/src/tabs/authz-model.ts +28 -0
  111. package/src/tabs/authz.ts +337 -0
  112. package/src/tabs/config.ts +250 -0
  113. package/src/tabs/inspect.ts +101 -0
  114. package/src/tabs/modules.ts +58 -0
  115. package/src/tabs/overview.ts +104 -0
  116. package/src/tabs/pages.ts +188 -0
  117. package/src/tabs/payload.ts +224 -0
  118. package/src/tabs/plugins-model.ts +44 -0
  119. package/src/tabs/plugins.ts +95 -0
  120. package/src/tabs/seo-model.ts +140 -0
  121. package/src/tabs/seo.ts +162 -0
  122. package/src/tabs/server-routes.ts +469 -0
  123. package/src/tabs/storage.ts +313 -0
  124. package/src/tabs/tasks-model.ts +59 -0
  125. package/src/tabs/tasks.ts +287 -0
  126. package/src/tabs/terminals-model.ts +127 -0
  127. package/src/tabs/terminals.ts +294 -0
  128. package/src/tabs/timeline-model.ts +200 -0
  129. package/src/tabs/timeline.ts +260 -0
  130. package/src/tester.ts +158 -0
  131. package/src/toolbar/element.ts +428 -0
  132. package/src/toolbar/shortcut.ts +56 -0
  133. package/src/toolbar/style.ts +94 -0
  134. package/src/view-context.ts +93 -0
package/src/module.ts ADDED
@@ -0,0 +1,352 @@
1
+ import { join } from "node:path"
2
+ import {
3
+ addAppPlugin,
4
+ addDevServerHandler,
5
+ addDevtoolsApp,
6
+ addDevtoolsTab,
7
+ addServer,
8
+ addTemplate,
9
+ cancelDevTaskRun,
10
+ createRedactor,
11
+ createResolver,
12
+ defineModule,
13
+ extendDevtoolsRpc,
14
+ matchDevRoute,
15
+ resetDevRuntimeConfig,
16
+ runDevAnalyze,
17
+ setDevRuntimeConfig,
18
+ useDevChannel,
19
+ useDevHooks,
20
+ useDevRouteTable,
21
+ useDevServerConfig,
22
+ useDevServerRoutes,
23
+ useDevSpans,
24
+ useDevTaskRuns,
25
+ useAppPlugins,
26
+ useDevPublicAssets,
27
+ useDevtoolsRegistry,
28
+ useHamur,
29
+ useInstalledModules,
30
+ useLogger,
31
+ useServerPlugins,
32
+ type DevtoolsRegistry,
33
+ } from "hamur/kit"
34
+ import { AnalyzeError, createAnalyzer } from "./dev/analyze.ts"
35
+ import { hasPolicies, policiesAnswer } from "./dev/authz.ts"
36
+ import { assetsAnswer, uploadAsset, type AssetRow } from "./dev/assets.ts"
37
+ import { createPanelBundle } from "./dev/bundle.ts"
38
+ import { configAnswer, publicEdit, revealAnswer } from "./dev/config.ts"
39
+ import { createDevtoolsHandler, json, type DataRoute } from "./dev/handler.ts"
40
+ import { LOCATOR_ICON, TAB_ICONS } from "./icons.ts"
41
+ import { serverRoutesAnswer } from "./dev/server-routes.ts"
42
+ import { spansAnswer, traceOf } from "./dev/timeline.ts"
43
+ import { modulesAnswer, pluginsAnswer } from "./dev/modules.ts"
44
+ import { overviewAnswer } from "./dev/overview.ts"
45
+ import { createProcessesRoute } from "./dev/processes.ts"
46
+ import { createTasksRoute, tasksAnswer } from "./dev/tasks.ts"
47
+ import { virtualAnswer } from "./dev/virtual.ts"
48
+ import { resolveOptions, type DevtoolsOptions } from "./options.ts"
49
+
50
+ /** `api/tabs`, every tab and app in registration order; module view and app entries stay on the runner. */
51
+ export function tabsAnswer(registry: DevtoolsRegistry) {
52
+ return {
53
+ tabs: registry.tabs.map(({ name, title, icon, view, module }) => ({
54
+ name,
55
+ title,
56
+ icon,
57
+ view: view.type === "module" ? { type: "module" as const } : view,
58
+ module,
59
+ })),
60
+ apps: registry.apps.map(({ name, title, icon, module }) => ({ name, title, icon, module })),
61
+ }
62
+ }
63
+
64
+ const NOT_SERVING = "No server process serves yet; the config shows once the server is built"
65
+
66
+ const readJson = (request: Request): Promise<unknown> =>
67
+ request.json().catch(() => {
68
+ throw new Error("The body of a devtools data route must be JSON")
69
+ })
70
+
71
+ /** A data route that calls one RPC function; what it throws answers 400 with its message. */
72
+ function rpcRoute(
73
+ registry: DevtoolsRegistry,
74
+ method: DataRoute["method"],
75
+ name: string,
76
+ args: (request: Request) => unknown = () => undefined,
77
+ ): DataRoute {
78
+ return {
79
+ method,
80
+ async answer(request) {
81
+ try {
82
+ return await registry.rpc.get(name)!.call(await args(request))
83
+ } catch (error) {
84
+ return json({ error: error instanceof Error ? error.message : String(error) }, 400)
85
+ }
86
+ },
87
+ }
88
+ }
89
+
90
+ /** The template `devtools/apps`, one lazy import per app for the toolbar. */
91
+ export function appsSource(registry: DevtoolsRegistry): string {
92
+ const apps = registry.apps.map(
93
+ ({ name, title, icon, entry }) =>
94
+ ` { name: ${JSON.stringify(name)}, title: ${JSON.stringify(title)}, icon: ${JSON.stringify(icon)}, load: () => import(${JSON.stringify(entry)}) },\n`,
95
+ )
96
+ return `export const apps = [\n${apps.join("")}];\n`
97
+ }
98
+
99
+ export default defineModule<DevtoolsOptions>({
100
+ meta: { name: "devtools", configKey: "devtools" },
101
+ setup(input, hamur) {
102
+ const options = resolveOptions(input)
103
+ if (!hamur.options.dev || !options.enabled) return
104
+ const resolver = createResolver(import.meta.url)
105
+ const registry = useDevtoolsRegistry()
106
+ const context = useHamur()
107
+ addDevtoolsTab({
108
+ name: "overview",
109
+ title: "Overview",
110
+ icon: TAB_ICONS.overview,
111
+ view: { type: "module", entry: resolver.resolve("./tabs/overview.ts") },
112
+ })
113
+ extendDevtoolsRpc("devtools:overview", () => overviewAnswer(context, useServerPlugins()))
114
+ addDevtoolsTab({
115
+ name: "pages",
116
+ title: "Pages",
117
+ icon: TAB_ICONS.pages,
118
+ view: { type: "module", entry: resolver.resolve("./tabs/pages.ts") },
119
+ })
120
+ extendDevtoolsRpc("devtools:routes", () => useDevRouteTable())
121
+ extendDevtoolsRpc("devtools:match", (args: { path?: unknown }) => {
122
+ if (typeof args?.path !== "string") throw new Error("devtools:match needs { path: string }")
123
+ return matchDevRoute(args.path).then((match) => match ?? null)
124
+ })
125
+ addDevtoolsTab({
126
+ name: "payload",
127
+ title: "Payload and state",
128
+ icon: TAB_ICONS.payload,
129
+ view: { type: "module", entry: resolver.resolve("./tabs/payload.ts") },
130
+ })
131
+ addDevtoolsTab({
132
+ name: "config",
133
+ title: "Config",
134
+ icon: TAB_ICONS.config,
135
+ view: { type: "module", entry: resolver.resolve("./tabs/config.ts") },
136
+ })
137
+ addDevtoolsTab({
138
+ name: "server-routes",
139
+ title: "Server routes",
140
+ icon: TAB_ICONS["server-routes"],
141
+ view: { type: "module", entry: resolver.resolve("./tabs/server-routes.ts") },
142
+ })
143
+ extendDevtoolsRpc("devtools:server-routes", async () =>
144
+ serverRoutesAnswer(await useDevRouteTable(), await useDevServerRoutes()),
145
+ )
146
+ addDevtoolsTab({
147
+ name: "storage",
148
+ title: "Storage",
149
+ icon: TAB_ICONS.storage,
150
+ view: { type: "module", entry: resolver.resolve("./tabs/storage.ts") },
151
+ })
152
+ addServer(resolver.resolve("./server/index.ts"))
153
+ addDevtoolsTab({
154
+ name: "assets",
155
+ title: "Assets",
156
+ icon: TAB_ICONS.assets,
157
+ view: { type: "module", entry: resolver.resolve("./tabs/assets.ts") },
158
+ })
159
+ extendDevtoolsRpc("devtools:assets", async () =>
160
+ assetsAnswer(hamur.options.rootDir, hamur.options.app.baseURL, await useDevPublicAssets()),
161
+ )
162
+ addDevtoolsTab({
163
+ name: "tasks",
164
+ title: "Tasks",
165
+ icon: TAB_ICONS.tasks,
166
+ view: { type: "module", entry: resolver.resolve("./tabs/tasks.ts") },
167
+ })
168
+ extendDevtoolsRpc("devtools:tasks", () =>
169
+ tasksAnswer(hamur.tasks, hamur.options.scheduledTasks, hamur.options.rootDir),
170
+ )
171
+ extendDevtoolsRpc("devtools:task-runs", () => useDevTaskRuns())
172
+ extendDevtoolsRpc("devtools:task-cancel", (args: { id?: unknown }) => cancelDevTaskRun(String(args?.id)))
173
+ const policies = hasPolicies(hamur.options)
174
+ if (policies)
175
+ addDevtoolsTab({
176
+ name: "authz",
177
+ title: "Authorization",
178
+ icon: TAB_ICONS.authz,
179
+ view: { type: "module", entry: resolver.resolve("./tabs/authz.ts") },
180
+ })
181
+ const redactor = createRedactor(hamur.options.server.logRedact)
182
+ addDevtoolsTab({
183
+ name: "timeline",
184
+ title: "Timeline",
185
+ icon: TAB_ICONS.timeline,
186
+ view: { type: "module", entry: resolver.resolve("./tabs/timeline.ts") },
187
+ })
188
+ extendDevtoolsRpc("devtools:spans", (args: unknown) => spansAnswer(useDevSpans(traceOf(args)), redactor))
189
+ extendDevtoolsRpc("devtools:hooks", () => useDevHooks())
190
+ addDevtoolsTab({
191
+ name: "plugins",
192
+ title: "Plugins",
193
+ icon: TAB_ICONS.plugins,
194
+ view: { type: "module", entry: resolver.resolve("./tabs/plugins.ts") },
195
+ })
196
+ extendDevtoolsRpc("devtools:plugins", () =>
197
+ pluginsAnswer(useAppPlugins(), useServerPlugins().files, hamur.options.rootDir),
198
+ )
199
+ addDevtoolsTab({
200
+ name: "modules",
201
+ title: "Modules",
202
+ icon: TAB_ICONS.modules,
203
+ view: { type: "module", entry: resolver.resolve("./tabs/modules.ts") },
204
+ })
205
+ extendDevtoolsRpc("devtools:modules", () => modulesAnswer(useInstalledModules(), hamur.options.rootDir, redactor))
206
+ addDevtoolsTab({
207
+ name: "inspect",
208
+ title: "Inspect",
209
+ icon: TAB_ICONS.inspect,
210
+ view: { type: "module", entry: resolver.resolve("./tabs/inspect.ts") },
211
+ })
212
+ extendDevtoolsRpc("devtools:virtual", () => virtualAnswer(hamur))
213
+ addDevtoolsTab({
214
+ name: "analyze",
215
+ title: "Analyze",
216
+ icon: TAB_ICONS.analyze,
217
+ view: { type: "module", entry: resolver.resolve("./tabs/analyze.ts") },
218
+ })
219
+ const analyzer = createAnalyzer({ dir: join(hamur.options.cacheDir, "analyze"), build: () => runDevAnalyze() })
220
+ extendDevtoolsRpc("devtools:analyze", () => analyzer.run())
221
+ const analyzeRoute: DataRoute = {
222
+ method: ["GET", "POST"],
223
+ param: true,
224
+ async answer(request, id) {
225
+ try {
226
+ if (id !== undefined)
227
+ return request.method === "GET"
228
+ ? await analyzer.read(id)
229
+ : json({ error: 'Devtools data route "analyze/<id>" answers GET' }, 405, { allow: "GET" })
230
+ return request.method === "POST"
231
+ ? await (registry.rpc.get("devtools:analyze")!.call(undefined) as Promise<unknown>)
232
+ : await analyzer.list()
233
+ } catch (error) {
234
+ return json(
235
+ { error: error instanceof Error ? error.message : String(error) },
236
+ error instanceof AnalyzeError ? error.status : 500,
237
+ )
238
+ }
239
+ },
240
+ }
241
+ addDevtoolsTab({
242
+ name: "terminals",
243
+ title: "Terminals and logs",
244
+ icon: TAB_ICONS.terminals,
245
+ view: { type: "module", entry: resolver.resolve("./tabs/terminals.ts") },
246
+ })
247
+ addDevtoolsTab({
248
+ name: "audit",
249
+ title: "Audit",
250
+ icon: TAB_ICONS.audit,
251
+ view: { type: "module", entry: resolver.resolve("./tabs/audit.ts") },
252
+ })
253
+ addDevtoolsTab({
254
+ name: "seo",
255
+ title: "SEO",
256
+ icon: TAB_ICONS.seo,
257
+ view: { type: "module", entry: resolver.resolve("./tabs/seo.ts") },
258
+ })
259
+ const processesRoute = createProcessesRoute(registry.processes)
260
+ const serverConfig = async () => {
261
+ const found = await useDevServerConfig()
262
+ if (!found) throw new Error(NOT_SERVING)
263
+ return found
264
+ }
265
+ extendDevtoolsRpc("devtools:config", async () =>
266
+ configAnswer(hamur.options as unknown as Record<string, unknown>, await serverConfig(), redactor),
267
+ )
268
+ extendDevtoolsRpc("devtools:config-reveal", async (args: { path?: unknown }) =>
269
+ revealAnswer(await serverConfig(), args?.path, redactor),
270
+ )
271
+ extendDevtoolsRpc("devtools:config-runtime", async (args: unknown) => {
272
+ const edit = publicEdit(await serverConfig(), args, redactor)
273
+ await setDevRuntimeConfig(edit.path, edit.value)
274
+ return edit
275
+ })
276
+ extendDevtoolsRpc("devtools:config-reset", async () => {
277
+ await resetDevRuntimeConfig()
278
+ return null
279
+ })
280
+ addDevtoolsApp({
281
+ name: "locator",
282
+ title: "Open component source",
283
+ icon: LOCATOR_ICON,
284
+ entry: resolver.resolve("./apps/locator.ts"),
285
+ })
286
+ const config = { baseURL: hamur.options.app.baseURL, shortcut: options.shortcut, placement: options.placement }
287
+ addTemplate({
288
+ filename: "devtools/config",
289
+ getContents: () =>
290
+ Object.entries(config)
291
+ .map(([key, value]) => `export const ${key} = ${JSON.stringify(value)};\n`)
292
+ .join(""),
293
+ })
294
+ addTemplate({ filename: "devtools/apps", getContents: () => appsSource(registry) })
295
+ addAppPlugin({ src: resolver.resolve("./client.ts"), mode: "client" })
296
+ const views = () =>
297
+ registry.tabs.flatMap(({ name, view }) => (view.type === "module" ? [{ name, entry: view.entry }] : []))
298
+ const bundle = createPanelBundle(resolver.resolve("./panel/index.ts"), views, {
299
+ "import.meta.appId": JSON.stringify(hamur.options.appId),
300
+ })
301
+ const logger = useLogger()
302
+ const assetUpload = {
303
+ rootDir: hamur.options.rootDir,
304
+ publicDir: hamur.options.publicDir,
305
+ baseURL: hamur.options.app.baseURL,
306
+ rows: () => registry.rpc.get("devtools:assets")!.call(undefined) as Promise<AssetRow[]>,
307
+ }
308
+ addDevServerHandler({
309
+ route: "/_hamur/devtools/",
310
+ handler: createDevtoolsHandler({
311
+ config,
312
+ bundle,
313
+ routes: {
314
+ tabs: { method: "GET", answer: () => tabsAnswer(registry) },
315
+ overview: { method: "GET", answer: () => registry.rpc.get("devtools:overview")!.call(undefined) },
316
+ routes: { method: "GET", answer: () => registry.rpc.get("devtools:routes")!.call(undefined) },
317
+ "server-routes": rpcRoute(registry, "GET", "devtools:server-routes"),
318
+ config: rpcRoute(registry, "GET", "devtools:config"),
319
+ "config/reveal": rpcRoute(registry, "GET", "devtools:config-reveal", (request) => ({
320
+ path: new URL(request.url).searchParams.get("path"),
321
+ })),
322
+ "config/runtime": rpcRoute(registry, "POST", "devtools:config-runtime", readJson),
323
+ "config/reset": rpcRoute(registry, "POST", "devtools:config-reset"),
324
+ spans: rpcRoute(registry, "GET", "devtools:spans", (request) => ({
325
+ trace: new URL(request.url).searchParams.get("trace"),
326
+ })),
327
+ hooks: rpcRoute(registry, "GET", "devtools:hooks"),
328
+ plugins: rpcRoute(registry, "GET", "devtools:plugins"),
329
+ modules: rpcRoute(registry, "GET", "devtools:modules"),
330
+ virtual: rpcRoute(registry, "GET", "devtools:virtual"),
331
+ assets: {
332
+ method: ["GET", "POST"],
333
+ answer: (request) =>
334
+ request.method === "POST"
335
+ ? uploadAsset(request, assetUpload)
336
+ : registry.rpc.get("devtools:assets")!.call(undefined),
337
+ },
338
+ analyze: analyzeRoute,
339
+ processes: processesRoute,
340
+ tasks: createTasksRoute(registry.rpc),
341
+ ...(policies ? { "authz/policies": { method: "GET", answer: () => policiesAnswer(hamur.authz) } } : {}),
342
+ },
343
+ rpc: registry.rpc,
344
+ log: (message) => logger.error(message),
345
+ }),
346
+ })
347
+ const channel = useDevChannel()
348
+ hamur.hooks.hook("dev:change", (change) => {
349
+ if (bundle.drop(change.file)) channel.send("devtools:reload", {}, "devtools")
350
+ })
351
+ },
352
+ })
@@ -0,0 +1,18 @@
1
+ /** `<baseURL>_hamur/open-in-editor`. */
2
+ export const editorEndpoint = (baseURL: string): string => `${baseURL.replace(/\/+$/, "")}/_hamur/open-in-editor`
3
+
4
+ /** Asks the dev server to open `file` (relative to `rootDir` or absolute) in the editor; a refused answer is logged as a warning. */
5
+ export async function openInEditor(endpoint: string, file: string, line?: number, column?: number): Promise<void> {
6
+ try {
7
+ const response = await fetch(endpoint, {
8
+ method: "POST",
9
+ headers: { "content-type": "application/json" },
10
+ body: JSON.stringify({
11
+ file,
12
+ ...(line === undefined ? {} : { line }),
13
+ ...(column === undefined ? {} : { column }),
14
+ }),
15
+ })
16
+ if (!response.ok) console.warn(`[hamur] open-in-editor: ${await response.text()}`)
17
+ } catch {}
18
+ }
package/src/options.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { PLACEMENTS, type Placement } from "./panel/settings.ts"
2
+ import { parseShortcut } from "./toolbar/shortcut.ts"
3
+ import { DiagnosticError } from "hamur/kit"
4
+
5
+ /** The `devtools` config key. */
6
+ export interface DevtoolsOptions {
7
+ enabled?: boolean
8
+ shortcut?: string | false
9
+ placement?: Placement
10
+ }
11
+
12
+ export interface ResolvedDevtoolsOptions {
13
+ enabled: boolean
14
+ shortcut: string | false
15
+ placement: Placement
16
+ }
17
+
18
+ const show = (value: unknown): string => JSON.stringify(value) ?? String(value)
19
+
20
+ /** The first wrong value throws. */
21
+ export function resolveOptions(input: DevtoolsOptions | undefined): ResolvedDevtoolsOptions {
22
+ const { enabled = true, shortcut = "shift+alt+d", placement = "bottom-center" } = input ?? {}
23
+ if (typeof enabled !== "boolean")
24
+ throw new DiagnosticError("HAMUR_E5601", `devtools.enabled must be a boolean (got ${show(enabled)})`)
25
+ if (shortcut !== false && (typeof shortcut !== "string" || !parseShortcut(shortcut)))
26
+ throw new DiagnosticError(
27
+ "HAMUR_E5602",
28
+ `devtools.shortcut must be a key combination such as "shift+alt+d", or false (got ${show(shortcut)})`,
29
+ )
30
+ if (!PLACEMENTS.includes(placement))
31
+ throw new DiagnosticError(
32
+ "HAMUR_E5603",
33
+ `devtools.placement must be one of ${PLACEMENTS.map((name) => `"${name}"`).join(", ")} (got ${show(placement)})`,
34
+ )
35
+ return { enabled, shortcut, placement }
36
+ }
@@ -0,0 +1,60 @@
1
+ import { HAMUR_MARK, SETTINGS_ICON, WINDOW_ICON } from "../icons.ts"
2
+ import type { Placement } from "./settings.ts"
3
+ import { PANEL_CSS } from "./style.ts"
4
+ import { UI } from "./ui.ts"
5
+
6
+ export interface PanelConfig {
7
+ baseURL: string
8
+ shortcut: string | false
9
+ placement: Placement
10
+ }
11
+
12
+ export const PANEL_CONFIG_ID = "hamur-devtools-config"
13
+
14
+ const escapeHtml = (text: string): string => text.replace(/[&<>"]/g, (char) => `&#${char.charCodeAt(0)};`)
15
+
16
+ /** The fixed panel document; with `error` (a failed bundle) the content area shows it and no script runs. */
17
+ export function panelDocument(config: PanelConfig, error?: string): string {
18
+ const json = JSON.stringify(config).replace(/</g, "\\u003c")
19
+ const main = error === undefined ? "" : `<pre data-error class="${UI.error}">${escapeHtml(error)}</pre>`
20
+ const script =
21
+ error === undefined
22
+ ? `<script type="module" src="${escapeHtml(`${config.baseURL}_hamur/devtools/panel.js`)}"></script>`
23
+ : ""
24
+ const windowButton =
25
+ error === undefined
26
+ ? `<button type="button" data-window aria-label="Open in its own window" title="Open in its own window" class="inline-flex items-center justify-center size-7 border-0 rounded-md bg-transparent text-side-icon cursor-pointer hover:bg-hover hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent">${WINDOW_ICON}</button>`
27
+ : ""
28
+ const shortcut =
29
+ config.shortcut === false
30
+ ? ""
31
+ : `<span class="flex-1"></span><kbd class="inline-flex items-center h-4 px-1 rounded bg-active font-sans font-medium text-2xs text-fg-4 leading-none">${escapeHtml(config.shortcut)}</kbd>`
32
+ return `<!doctype html>
33
+ <html lang="en">
34
+ <head>
35
+ <meta charset="utf-8">
36
+ <meta name="viewport" content="width=device-width, initial-scale=1">
37
+ <title>Hamur devtools</title>
38
+ <style>${PANEL_CSS}</style>
39
+ </head>
40
+ <body class="flex bg-app text-fg text-sm">
41
+ <aside class="flex-none flex flex-col w-56 min-h-0">
42
+ <div data-drag class="flex-none flex items-center gap-2 h-12 px-3.5"><span class="inline-flex items-center justify-center size-5 rounded-md bg-accent text-app">${HAMUR_MARK}</span><span class="flex-1 font-medium text-sm">Hamur</span>${windowButton}</div>
43
+ <nav data-tabs aria-label="Devtools tabs" class="flex-1 min-h-0 overflow-auto flex flex-col px-2 pb-2"></nav>
44
+ <footer class="flex-none flex items-center gap-0.5 h-10 px-2.5 border-t border-line"><button type="button" data-settings aria-label="Settings" title="Settings" class="inline-flex items-center justify-center size-7 border-0 rounded-md bg-transparent text-side-icon cursor-pointer hover:bg-hover hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent">${SETTINGS_ICON}</button>${shortcut}</footer>
45
+ </aside>
46
+ <main data-content class="flex-1 min-w-0 my-2 mr-2 flex flex-col rounded-lg bg-panel ring-1 ring-line overflow-hidden">${main}</main>
47
+ <script type="application/json" id="${PANEL_CONFIG_ID}">${json}</script>
48
+ ${script}
49
+ </body>
50
+ </html>
51
+ `
52
+ }
53
+
54
+ export const PANEL_HEADERS = {
55
+ "content-type": "text/html; charset=utf-8",
56
+ "cache-control": "no-store",
57
+ "content-security-policy": "frame-ancestors 'self'",
58
+ "x-frame-options": "SAMEORIGIN",
59
+ "referrer-policy": "no-referrer",
60
+ }
@@ -0,0 +1,41 @@
1
+ import { orderTabs, type DevtoolsSettings } from "./settings.ts"
2
+
3
+ export const GROUPS = ["App", "Server", "Performance", "Debug", "Modules"] as const
4
+ export type Group = (typeof GROUPS)[number]
5
+
6
+ /** The sidebar group of each built-in tab; every other tab is under "Modules". */
7
+ export const TAB_GROUPS: Record<string, Exclude<Group, "Modules">> = {
8
+ overview: "App",
9
+ pages: "App",
10
+ payload: "App",
11
+ config: "App",
12
+ "server-routes": "Server",
13
+ storage: "Server",
14
+ assets: "Server",
15
+ tasks: "Server",
16
+ authz: "Server",
17
+ timeline: "Performance",
18
+ analyze: "Performance",
19
+ plugins: "Performance",
20
+ modules: "Performance",
21
+ inspect: "Debug",
22
+ terminals: "Debug",
23
+ audit: "Debug",
24
+ seo: "Debug",
25
+ }
26
+
27
+ export const BUILT_IN_MODULE = "devtools"
28
+
29
+ const groupOf = (tab: { name: string; module: string }): Group =>
30
+ tab.module === BUILT_IN_MODULE && Object.hasOwn(TAB_GROUPS, tab.name) ? TAB_GROUPS[tab.name]! : "Modules"
31
+
32
+ /** The tabs of `orderTabs` in their groups, the groups in `GROUPS` order; a group with no tab is left out. */
33
+ export function groupTabs<T extends { name: string; module: string }>(
34
+ tabs: readonly T[],
35
+ settings: Pick<DevtoolsSettings, "hidden" | "order">,
36
+ ): Array<{ group: Group; tabs: T[] }> {
37
+ const ordered = orderTabs(tabs, settings)
38
+ return GROUPS.map((group) => ({ group, tabs: ordered.filter((tab) => groupOf(tab) === group) })).filter(
39
+ (entry) => entry.tabs.length > 0,
40
+ )
41
+ }