@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,162 @@
1
+ import { existsSync } from "node:fs"
2
+ import { readFile } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+ import type { HamurContext } from "hamur/kit"
5
+
6
+ type State = NonNullable<HamurContext["authz"]>
7
+ type Policy = State["policies"][number]["policy"]
8
+
9
+ interface TypeLike {
10
+ readonly kind: string
11
+ readonly name?: string
12
+ readonly element?: TypeLike
13
+ readonly attributes?: ReadonlyMap<string, { readonly type: TypeLike; readonly required: boolean }>
14
+ }
15
+
16
+ /** One policy of the compiled set. */
17
+ export interface PolicyRow {
18
+ id: string
19
+ effect: "permit" | "forbid"
20
+ principal: string
21
+ action: string
22
+ resource: string
23
+ template: boolean
24
+ /** As the build's messages name it: from the app root, or absolute outside it. */
25
+ file: string
26
+ line: number
27
+ column: number
28
+ text: string
29
+ }
30
+
31
+ /** An entity type. */
32
+ export interface EntityTypeRow {
33
+ name: string
34
+ attributes: Array<{ name: string; type: string; required: boolean }>
35
+ /** Every type it is in, transitively. */
36
+ parents: string[]
37
+ tags?: string
38
+ enum?: string[]
39
+ }
40
+
41
+ /** An action. */
42
+ export interface ActionRow {
43
+ name: string
44
+ groups: string[]
45
+ appliesTo?: { principals: string[]; resources: string[]; context: string }
46
+ }
47
+
48
+ export interface PoliciesAnswer {
49
+ policies: PolicyRow[]
50
+ entityTypes: EntityTypeRow[]
51
+ actions: ActionRow[]
52
+ }
53
+
54
+ /** The tab is shown when the app or a layer has a `server/policies/` folder. */
55
+ export function hasPolicies(options: Pick<HamurContext["options"], "serverDir" | "layers">): boolean {
56
+ return [options.serverDir, ...options.layers.map((layer) => layer.serverDir)].some((dir) =>
57
+ existsSync(join(dir, "policies")),
58
+ )
59
+ }
60
+
61
+ function typeText(type: TypeLike): string {
62
+ switch (type.kind) {
63
+ case "bool":
64
+ return "Bool"
65
+ case "long":
66
+ return "Long"
67
+ case "string":
68
+ return "String"
69
+ case "set":
70
+ return `Set<${typeText(type.element!)}>`
71
+ case "record": {
72
+ const parts = [...type.attributes!].map(
73
+ ([name, { type: attribute, required }]) => `${name}${required ? "" : "?"}: ${typeText(attribute)}`,
74
+ )
75
+ return parts.length ? `{ ${parts.join(", ")} }` : "{}"
76
+ }
77
+ default:
78
+ return type.name!
79
+ }
80
+ }
81
+
82
+ const uid = (target: { kind: string; type?: string; id?: string; name?: string }): string =>
83
+ target.kind === "slot" ? target.name! : `${target.type}::${JSON.stringify(target.id)}`
84
+
85
+ function headText(scope: Policy["principal"]): string {
86
+ if (scope.kind === "any") return "any"
87
+ if (scope.kind === "eq") return `== ${uid(scope.entity)}`
88
+ if (scope.kind === "in") return `in ${uid(scope.entity)}`
89
+ return `is ${scope.type}${scope.in ? ` in ${uid(scope.in)}` : ""}`
90
+ }
91
+
92
+ function actionText(scope: Policy["action"]): string {
93
+ if (scope.kind === "any") return "any"
94
+ if (scope.kind === "eq") return `== ${uid(scope.entity)}`
95
+ return `in [${scope.entities.map(uid).join(", ")}]`
96
+ }
97
+
98
+ /** The lines of a policy: from its first line to the line before the next policy of the file, trailing blank and comment lines dropped. */
99
+ export function policyText(lines: readonly string[], line: number, next: number | undefined): string {
100
+ const end = next !== undefined && next > line ? next - 1 : next === undefined ? lines.length : line
101
+ const kept = lines.slice(line - 1, end)
102
+ while (kept.length > 1 && /^\s*(\/\/.*)?$/.test(kept[kept.length - 1]!)) kept.pop()
103
+ return kept.join("\n")
104
+ }
105
+
106
+ /** The compiled policies, schema and actions of `state`; empty without one. */
107
+ export async function policiesAnswer(state: HamurContext["authz"]): Promise<PoliciesAnswer> {
108
+ if (!state) return { policies: [], entityTypes: [], actions: [] }
109
+ const texts = new Map<string, string[]>()
110
+ for (const { file, shown } of state.files) texts.set(shown, (await readFile(file, "utf8")).split(/\r?\n/))
111
+ const starts = new Map<string, number[]>()
112
+ for (const { policy } of state.policies)
113
+ starts.set(
114
+ policy.loc.file,
115
+ [...(starts.get(policy.loc.file) ?? []), policy.loc.line].sort((a, b) => a - b),
116
+ )
117
+ return {
118
+ policies: state.policies.map(({ id, policy }) => {
119
+ const { file, line, column } = policy.loc
120
+ const after = starts.get(file)?.find((start) => start > line)
121
+ return {
122
+ id,
123
+ effect: policy.effect,
124
+ principal: headText(policy.principal),
125
+ action: actionText(policy.action),
126
+ resource: headText(policy.resource),
127
+ template: policy.template,
128
+ file,
129
+ line,
130
+ column,
131
+ text: policyText(texts.get(file) ?? [], line, after),
132
+ }
133
+ }),
134
+ entityTypes: [...state.schema.entityTypes.values()].map((type) => ({
135
+ name: type.name,
136
+ attributes: [...type.attributes].map(([name, { type: attribute, required }]) => ({
137
+ name,
138
+ type: typeText(attribute),
139
+ required,
140
+ })),
141
+ parents: [...type.ancestors].sort(),
142
+ ...(type.tags ? { tags: typeText(type.tags) } : {}),
143
+ ...(type.enum ? { enum: [...type.enum] } : {}),
144
+ })),
145
+ actions: Object.entries(state.actions).map(([name, action]) => {
146
+ const applies = state.schema.actions.get(`${action.type}::${JSON.stringify(action.id)}`)?.appliesTo
147
+ return {
148
+ name,
149
+ groups: action.groups.map(({ type, id }) => `${type}::${JSON.stringify(id)}`),
150
+ ...(applies
151
+ ? {
152
+ appliesTo: {
153
+ principals: [...applies.principals],
154
+ resources: [...applies.resources],
155
+ context: typeText(applies.context),
156
+ },
157
+ }
158
+ : {}),
159
+ }
160
+ }),
161
+ }
162
+ }
@@ -0,0 +1,91 @@
1
+ import { existsSync, realpathSync } from "node:fs"
2
+ import { dirname, isAbsolute, resolve } from "node:path"
3
+
4
+ export type PanelBuild = { files: Map<string, Blob> } | { error: string }
5
+
6
+ export interface PanelBundle {
7
+ /** The in-memory build, made on the first call and kept until `drop`; a failed one is made again on the next call. */
8
+ build(): Promise<PanelBuild>
9
+ /** Forgets the build when `file` is one of its inputs; true when it did. */
10
+ drop(file: string): boolean
11
+ }
12
+
13
+ export const VIEWS_MODULE = "#hamur/devtools-views"
14
+
15
+ /** The module `#hamur/devtools-views`: one lazy import per module tab, so each view is a chunk of the panel build. */
16
+ export function viewsSource(views: Array<{ name: string; entry: string }>): string {
17
+ return `export const views = {\n${views.map(({ name, entry }) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(entry)}),\n`).join("")}};\n`
18
+ }
19
+
20
+ /** `Bun.build` of the panel and the module tabs' views, kept in memory and served below `<baseURL>_hamur/devtools/`. */
21
+ export function createPanelBundle(
22
+ entry: string,
23
+ views: () => Array<{ name: string; entry: string }> = () => [],
24
+ define: Record<string, string> = {},
25
+ ): PanelBundle {
26
+ const root = dirname(dirname(entry))
27
+ let built: Promise<PanelBuild> | undefined
28
+ let inputs = new Set<string>()
29
+
30
+ /** A metafile input key is relative to a base the build does not name, so each base is tried and the file's real path kept. */
31
+ const realInputs = (input: string): string[] => {
32
+ const candidates = isAbsolute(input) ? [input] : [resolve(root, input), resolve(process.cwd(), input)]
33
+ return [...new Set(candidates.filter((path) => existsSync(path)).map((path) => realpathSync(path)))]
34
+ }
35
+
36
+ async function run(): Promise<PanelBuild> {
37
+ const result = await Bun.build({
38
+ entrypoints: [entry],
39
+ root,
40
+ target: "browser",
41
+ format: "esm",
42
+ splitting: true,
43
+ minify: false,
44
+ sourcemap: "inline",
45
+ metafile: true,
46
+ naming: { entry: "panel.[ext]", chunk: "chunk-[hash].[ext]" },
47
+ define,
48
+ throw: false,
49
+ plugins: [
50
+ {
51
+ name: "hamur-devtools-views",
52
+ setup(build) {
53
+ build.onResolve({ filter: /^#hamur\/devtools-views$/ }, () => ({
54
+ path: "views",
55
+ namespace: "hamur-devtools",
56
+ }))
57
+ build.onLoad({ filter: /^views$/, namespace: "hamur-devtools" }, () => ({
58
+ contents: viewsSource(views()),
59
+ loader: "js",
60
+ }))
61
+ },
62
+ },
63
+ ],
64
+ }).catch((error: unknown) => ({
65
+ success: false as const,
66
+ logs: [error],
67
+ outputs: [] as Bun.BuildArtifact[],
68
+ metafile: undefined,
69
+ }))
70
+ if (!result.success)
71
+ return {
72
+ error: `The devtools panel build failed:\n${result.logs.map((log) => (log instanceof Error ? log.message : String(log))).join("\n")}`,
73
+ }
74
+ inputs = new Set(Object.keys(result.metafile?.inputs ?? {}).flatMap(realInputs))
75
+ return { files: new Map(result.outputs.map((output) => [output.path.replace(/^\.\//, ""), output])) }
76
+ }
77
+
78
+ return {
79
+ build: () =>
80
+ (built ??= run().then((result) => {
81
+ if ("error" in result) built = undefined
82
+ return result
83
+ })),
84
+ drop(file) {
85
+ if (!built || !inputs.has(existsSync(file) ? realpathSync(file) : file)) return false
86
+ built = undefined
87
+ inputs = new Set()
88
+ return true
89
+ },
90
+ }
91
+ }
@@ -0,0 +1,132 @@
1
+ import { REDACTED, type DevServerConfig, type Redactor } from "hamur/kit"
2
+ import { CIRCULAR, MASKED, TOO_DEEP } from "../mask.ts"
3
+
4
+ export const MAX_DEPTH = 8
5
+
6
+ export interface ConfigAnswer {
7
+ options: unknown
8
+ runtimeConfig: { public: unknown; private: unknown }
9
+ }
10
+
11
+ const isPlain = (value: object): boolean => {
12
+ const proto = Object.getPrototypeOf(value)
13
+ return proto === Object.prototype || proto === null
14
+ }
15
+
16
+ /** A value as JSON the panel can show: functions, symbols, bigints, class instances, cycles and depth past `MAX_DEPTH` become strings; redacted keys `[redacted]`. */
17
+ export function serialize(value: unknown, redactor: Redactor, depth = 0, seen: object[] = []): unknown {
18
+ if (typeof value === "function") return `[Function ${value.name || "anonymous"}]`
19
+ if (typeof value === "bigint") return `${value}n`
20
+ if (typeof value === "symbol") return value.toString()
21
+ if (typeof value === "number" && !Number.isFinite(value)) return String(value)
22
+ if (value === null || typeof value !== "object") return value
23
+ if (seen.includes(value)) return CIRCULAR
24
+ if (depth >= MAX_DEPTH) return TOO_DEEP
25
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString()
26
+ if (value instanceof RegExp || value instanceof URL) return String(value)
27
+ const inner = [...seen, value]
28
+ if (Array.isArray(value)) return value.map((item) => serialize(item, redactor, depth + 1, inner) ?? null)
29
+ if (value instanceof Set) return [...value].map((item) => serialize(item, redactor, depth + 1, inner) ?? null)
30
+ if (value instanceof Map)
31
+ return [...value].map(([key, item]) => [
32
+ serialize(key, redactor, depth + 1, inner),
33
+ typeof key === "string" && redactor.test(key) ? REDACTED : serialize(item, redactor, depth + 1, inner),
34
+ ])
35
+ if (value instanceof Error) return `[${value.name}: ${value.message}]`
36
+ if (!isPlain(value)) return `[${value.constructor?.name || "Object"}]`
37
+ const result: Record<string, unknown> = {}
38
+ for (const [key, item] of Object.entries(value)) {
39
+ if (item === undefined) continue
40
+ result[key] = redactor.test(key) ? REDACTED : serialize(item, redactor, depth + 1, inner)
41
+ }
42
+ return result
43
+ }
44
+
45
+ /** The private runtime config with each value that is not a plain object `MASKED`, and each key the redactor matches `[redacted]`. */
46
+ export function maskPrivate(value: unknown, redactor: Redactor, depth = 0): unknown {
47
+ if (value === null || typeof value !== "object") return MASKED
48
+ if (depth >= MAX_DEPTH) return TOO_DEEP
49
+ if (Array.isArray(value) || !isPlain(value)) return MASKED
50
+ const result: Record<string, unknown> = {}
51
+ for (const [key, item] of Object.entries(value))
52
+ result[key] = redactor.test(key) ? REDACTED : maskPrivate(item, redactor, depth + 1)
53
+ return result
54
+ }
55
+
56
+ const withoutPublic = (config: Record<string, unknown>): Record<string, unknown> =>
57
+ Object.fromEntries(Object.entries(config).filter(([key]) => key !== "public"))
58
+
59
+ /** `api/config`: nothing private and nothing the redactor matches leaves the runner as its value. */
60
+ export function configAnswer(
61
+ options: Record<string, unknown>,
62
+ server: DevServerConfig,
63
+ redactor: Redactor,
64
+ ): ConfigAnswer {
65
+ const written = (options.runtimeConfig ?? {}) as Record<string, unknown>
66
+ const shown = serialize({ ...options, runtimeConfig: null }, redactor) as Record<string, unknown>
67
+ shown.runtimeConfig = {
68
+ public: serialize(written.public ?? {}, redactor),
69
+ ...(maskPrivate(withoutPublic(written), redactor) as Record<string, unknown>),
70
+ }
71
+ return {
72
+ options: shown,
73
+ runtimeConfig: {
74
+ public: serialize(server.runtimeConfig.public, redactor),
75
+ private: maskPrivate(withoutPublic(server.runtimeConfig), redactor),
76
+ },
77
+ }
78
+ }
79
+
80
+ const lookup = (root: unknown, keys: readonly string[]): { found: true; value: unknown } | { found: false } => {
81
+ let node = root
82
+ for (const key of keys) {
83
+ if (node === null || typeof node !== "object" || !Object.hasOwn(node, key)) return { found: false }
84
+ node = (node as Record<string, unknown>)[key]
85
+ }
86
+ return { found: true, value: node }
87
+ }
88
+
89
+ /** `api/config/reveal`: one private value by its dot path; a path through a key the redactor matches stays `[redacted]`. */
90
+ export function revealAnswer(server: DevServerConfig, path: unknown, redactor: Redactor): { value: unknown } {
91
+ const keys = typeof path === "string" && path !== "" ? path.split(".") : []
92
+ if (!keys.length || keys[0] === "public")
93
+ throw new Error(`Reveal takes the dot path of a private runtime config value (got ${JSON.stringify(path)})`)
94
+ const hit = lookup(withoutPublic(server.runtimeConfig), keys)
95
+ if (!hit.found) throw new Error(`No private runtime config value at ${JSON.stringify(path)}`)
96
+ if (keys.some((key) => redactor.test(key))) return { value: REDACTED }
97
+ return { value: serialize(hit.value, redactor) }
98
+ }
99
+
100
+ const kind = (value: unknown): string => (value === null ? "null" : Array.isArray(value) ? "array" : typeof value)
101
+
102
+ /** True when `serialize` writes `value`, found at `depth`, back as the same JSON: no redacted key, nothing past the depth cap, JSON types only. */
103
+ function jsonSafe(value: unknown, depth: number, redactor: Redactor): boolean {
104
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true
105
+ if (typeof value === "number") return Number.isFinite(value)
106
+ if (typeof value !== "object" || depth >= MAX_DEPTH || (!Array.isArray(value) && !isPlain(value))) return false
107
+ return Object.entries(value).every(
108
+ ([key, item]) => (Array.isArray(value) || !redactor.test(key)) && jsonSafe(item, depth + 1, redactor),
109
+ )
110
+ }
111
+
112
+ /** `api/config/runtime`: the dot path names a key `runtimeConfig.public` already has, shown whole, and the value has its JSON type. */
113
+ export function publicEdit(
114
+ server: DevServerConfig,
115
+ args: unknown,
116
+ redactor: Redactor,
117
+ ): { path: string; value: unknown } {
118
+ const { path, value } = (typeof args === "object" && args !== null ? args : {}) as { path?: unknown; value?: unknown }
119
+ if (typeof path !== "string" || !path.startsWith("public."))
120
+ throw new Error(`Only runtimeConfig.public values can be edited (got ${JSON.stringify(path)})`)
121
+ if (value === undefined) throw new Error(`The edit of ${JSON.stringify(path)} needs a value`)
122
+ const keys = path.split(".")
123
+ const hit = lookup(server.runtimeConfig, keys)
124
+ if (!hit.found) throw new Error(`runtimeConfig has no key ${JSON.stringify(path)}`)
125
+ if (keys.some((key) => redactor.test(key)) || !jsonSafe(hit.value, keys.length - 1, redactor))
126
+ throw new Error(`runtimeConfig ${JSON.stringify(path)} is shown redacted or cut short, so it cannot be edited`)
127
+ if (kind(value) !== kind(hit.value))
128
+ throw new Error(
129
+ `The value of ${JSON.stringify(path)} must be ${kind(hit.value)} like the current one (got ${kind(value)})`,
130
+ )
131
+ return { path, value }
132
+ }
@@ -0,0 +1,161 @@
1
+ import type { DevHandler, DevtoolsRegistry } from "hamur/kit"
2
+ import { panelDocument, PANEL_HEADERS, type PanelConfig } from "../panel/document.ts"
3
+ import type { PanelBundle } from "./bundle.ts"
4
+
5
+ /** A runner-side devtools data route: the methods it answers and its JSON answer, or a `Response` of its own. */
6
+ export interface DataRoute {
7
+ method: "GET" | "POST" | Array<"GET" | "POST">
8
+ /** The route also answers `<name>/<segment>`, its `answer` getting the decoded segment. */
9
+ param?: boolean
10
+ answer(request: Request, param?: string): unknown
11
+ }
12
+
13
+ const JSON_HEADERS = {
14
+ "content-type": "application/json",
15
+ "cache-control": "no-store",
16
+ "x-content-type-options": "nosniff",
17
+ }
18
+
19
+ export const json = (body: unknown, status = 200, headers: Record<string, string> = {}): Response =>
20
+ new Response(JSON.stringify(body), { status, headers: { ...JSON_HEADERS, ...headers } })
21
+
22
+ export const RPC_MAX_BYTES = 1024 * 1024
23
+
24
+ const NOT_JSON = "The body of a devtools RPC call must be JSON"
25
+
26
+ /** The body as text, or `undefined` once it passes `RPC_MAX_BYTES`. */
27
+ async function readCapped(request: Request): Promise<string | undefined> {
28
+ if (Number(request.headers.get("content-length") ?? 0) > RPC_MAX_BYTES) return undefined
29
+ if (!request.body) return ""
30
+ const reader = request.body.getReader()
31
+ const chunks: Uint8Array[] = []
32
+ let size = 0
33
+ for (;;) {
34
+ const { done, value } = await reader.read()
35
+ if (done) break
36
+ size += value.byteLength
37
+ if (size > RPC_MAX_BYTES) {
38
+ await reader.cancel()
39
+ return undefined
40
+ }
41
+ chunks.push(value)
42
+ }
43
+ return new TextDecoder().decode(Buffer.concat(chunks))
44
+ }
45
+
46
+ /** `POST api/rpc/<name>`; the function gets the parsed body only, never the request's headers or cookies. */
47
+ async function answerRpc(
48
+ rpc: DevtoolsRegistry["rpc"],
49
+ encoded: string,
50
+ request: Request,
51
+ log: (message: string) => void,
52
+ ): Promise<Response> {
53
+ let name: string
54
+ try {
55
+ name = decodeURIComponent(encoded)
56
+ } catch {
57
+ name = encoded
58
+ }
59
+ const fn = rpc.get(name)
60
+ if (!fn) return json({ error: `No devtools RPC ${JSON.stringify(name)}` }, 404)
61
+ if (request.method !== "POST") return json({ error: "Devtools RPC calls answer POST" }, 405, { allow: "POST" })
62
+ const type = request.headers.get("content-type")
63
+ if (type !== null && type.split(";")[0]!.trim().toLowerCase() !== "application/json")
64
+ return json({ error: NOT_JSON }, 400)
65
+ const text = await readCapped(request)
66
+ if (text === undefined) return json({ error: `The body of a devtools RPC call is over ${RPC_MAX_BYTES} bytes` }, 413)
67
+ if (text !== "" && type === null) return json({ error: NOT_JSON }, 400)
68
+ let args: unknown
69
+ try {
70
+ args = text === "" ? undefined : JSON.parse(text)
71
+ } catch {
72
+ return json({ error: NOT_JSON }, 400)
73
+ }
74
+ let result: unknown
75
+ try {
76
+ result = await fn.call(args)
77
+ } catch (error) {
78
+ const message = error instanceof Error ? error.message : String(error)
79
+ log(`devtools RPC ${name} threw: ${message}`)
80
+ return json({ error: message }, 500)
81
+ }
82
+ let body: string
83
+ try {
84
+ body = JSON.stringify({ result })
85
+ } catch (error) {
86
+ return json(
87
+ {
88
+ error: `devtools RPC ${name} returned a value that is not JSON (${error instanceof Error ? error.message : String(error)})`,
89
+ },
90
+ 500,
91
+ )
92
+ }
93
+ return new Response(body, { headers: JSON_HEADERS })
94
+ }
95
+
96
+ /** A name the runner does not answer goes on to the server process, whose doors hold the server-side routes and answer an unknown name 404. */
97
+ async function answerDataRoute(
98
+ routes: Record<string, DataRoute>,
99
+ name: string,
100
+ request: Request,
101
+ ): Promise<Response | undefined> {
102
+ let route = Object.hasOwn(routes, name) ? routes[name] : undefined
103
+ let param: string | undefined
104
+ if (!route) {
105
+ const slash = name.indexOf("/")
106
+ const parent = slash < 0 ? undefined : name.slice(0, slash)
107
+ const parentRoute = parent !== undefined && Object.hasOwn(routes, parent) ? routes[parent] : undefined
108
+ if (!parentRoute?.param) return undefined
109
+ route = parentRoute
110
+ param = name.slice(slash + 1)
111
+ try {
112
+ param = decodeURIComponent(param)
113
+ } catch {}
114
+ }
115
+ const methods: string[] = Array.isArray(route.method) ? route.method : [route.method]
116
+ if (!methods.includes(request.method))
117
+ return json({ error: `Devtools data route ${JSON.stringify(name)} answers ${methods.join(", ")}` }, 405, {
118
+ allow: methods.join(", "),
119
+ })
120
+ const answer = await route.answer(request, param)
121
+ return answer instanceof Response ? answer : json(answer)
122
+ }
123
+
124
+ /** The module's dev handler of `<baseURL>_hamur/devtools/`: the panel document, its bundle and the runner-side `api/*`. */
125
+ export function createDevtoolsHandler(options: {
126
+ config: PanelConfig
127
+ bundle: PanelBundle
128
+ routes: Record<string, DataRoute>
129
+ rpc: DevtoolsRegistry["rpc"]
130
+ log: (message: string) => void
131
+ }): DevHandler {
132
+ const prefix = `${options.config.baseURL}_hamur/devtools`
133
+ return async (request) => {
134
+ const { pathname } = new URL(request.url)
135
+ if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) return undefined
136
+ const rest = pathname.slice(prefix.length + 1)
137
+ if (rest.startsWith("api/rpc/")) return answerRpc(options.rpc, rest.slice("api/rpc/".length), request, options.log)
138
+ if (rest.startsWith("api/")) return answerDataRoute(options.routes, rest.slice("api/".length), request)
139
+ if (request.method !== "GET" && request.method !== "HEAD")
140
+ return new Response(null, { status: 405, headers: { allow: "GET, HEAD", "cache-control": "no-store" } })
141
+ const built = await options.bundle.build()
142
+ if (rest === "")
143
+ return new Response(panelDocument(options.config, "error" in built ? built.error : undefined), {
144
+ headers: PANEL_HEADERS,
145
+ })
146
+ if ("error" in built)
147
+ return new Response(built.error, {
148
+ status: 500,
149
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
150
+ })
151
+ const file = built.files.get(rest)
152
+ if (!file)
153
+ return new Response(`No devtools file ${JSON.stringify(rest)}`, {
154
+ status: 404,
155
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
156
+ })
157
+ return new Response(file, {
158
+ headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-store" },
159
+ })
160
+ }
161
+ }
@@ -0,0 +1,60 @@
1
+ import { existsSync, readFileSync } from "node:fs"
2
+ import { dirname, isAbsolute, join, relative } from "node:path"
3
+ import type { AppPluginInfo, InstalledModule, Redactor } from "hamur/kit"
4
+ import { serialize } from "./config.ts"
5
+
6
+ /** `api/modules`: one configured module; `options` as its `setup` received them, with every key the redactor matches `"[redacted]"`. */
7
+ export interface ModuleRow {
8
+ name: string
9
+ version: string | null
10
+ configKey: string | null
11
+ options: unknown
12
+ }
13
+
14
+ /** `api/plugins`: the app plugins with their file, and the server plugins `defineServer` lists with theirs. */
15
+ export interface PluginsAnswer {
16
+ app: Array<{ name: string; file: string; mode: AppPluginInfo["mode"]; order: number }>
17
+ server: Array<{ file: string; module?: string }>
18
+ }
19
+
20
+ /** The `version` of the nearest `package.json` above `file`, looking no higher than the app's own folder, whose version is not a module's. */
21
+ export function moduleVersion(file: string | undefined, rootDir: string): string | null {
22
+ if (!file) return null
23
+ for (let dir = dirname(file); dir !== rootDir && dir !== dirname(dir); dir = dirname(dir)) {
24
+ const manifest = join(dir, "package.json")
25
+ if (!existsSync(manifest)) continue
26
+ try {
27
+ const version = (JSON.parse(readFileSync(manifest, "utf8")) as { version?: unknown }).version
28
+ if (typeof version === "string") return version
29
+ } catch {}
30
+ }
31
+ return null
32
+ }
33
+
34
+ export function modulesAnswer(modules: readonly InstalledModule[], rootDir: string, redactor: Redactor): ModuleRow[] {
35
+ return modules.map((module) => ({
36
+ name: module.name,
37
+ version: moduleVersion(module.file, rootDir),
38
+ configKey: module.configKey ?? null,
39
+ options: serialize(module.options, redactor),
40
+ }))
41
+ }
42
+
43
+ const shown = (file: string, rootDir: string): string => {
44
+ const path = relative(rootDir, file)
45
+ return isAbsolute(file) && !path.startsWith("..") && !isAbsolute(path) ? path.split("\\").join("/") : file
46
+ }
47
+
48
+ export function pluginsAnswer(
49
+ app: readonly AppPluginInfo[],
50
+ server: ReadonlyArray<{ file: string; module?: string }>,
51
+ rootDir: string,
52
+ ): PluginsAnswer {
53
+ return {
54
+ app: app.map(({ name, file, mode, order }) => ({ name, file: shown(file, rootDir), mode, order })),
55
+ server: server.map(({ file, module }) => ({
56
+ file: shown(file, rootDir),
57
+ ...(module === undefined ? {} : { module }),
58
+ })),
59
+ }
60
+ }
@@ -0,0 +1,57 @@
1
+ import { existsSync, readFileSync } from "node:fs"
2
+ import { dirname, join } from "node:path"
3
+ import type { HamurContext, ServerPlugins } from "hamur/kit"
4
+
5
+ export interface OverviewAnswer {
6
+ versions: { hamur: string | null; adapter: string | null; library: string | null; bun: string }
7
+ counts: { pages: number; serverRoutes: number; modules: number; appPlugins: number; serverPlugins: number | null }
8
+ }
9
+
10
+ const LIBRARIES: Record<string, string | undefined> = { html: undefined, solid: "solid-js" }
11
+
12
+ /** The `version` of the package `name`, found by resolving `specifier` from `from` and walking up to the `package.json` that carries that name. */
13
+ export function packageVersion(specifier: string, name: string, from: string): string | null {
14
+ let dir: string
15
+ try {
16
+ dir = dirname(Bun.resolveSync(specifier, from))
17
+ } catch {
18
+ return null
19
+ }
20
+ for (;;) {
21
+ const file = join(dir, "package.json")
22
+ if (existsSync(file)) {
23
+ const pkg = JSON.parse(readFileSync(file, "utf8")) as { name?: string; version?: string }
24
+ if (pkg.name === name) return pkg.version ?? null
25
+ }
26
+ const parent = dirname(dir)
27
+ if (parent === dir) return null
28
+ dir = parent
29
+ }
30
+ }
31
+
32
+ const pageCount = (routes: ReadonlyArray<{ pathless?: true; children?: readonly unknown[] }>): number =>
33
+ routes.reduce((sum, route) => sum + (route.pathless ? 0 : 1) + pageCount((route.children ?? []) as typeof routes), 0)
34
+
35
+ /** `api/overview`: what the build already knows, counted without a scan; `serverPlugins` comes from `useServerPlugins()`. */
36
+ export function overviewAnswer(
37
+ hamur: Pick<HamurContext, "options" | "routes" | "serverRoutes" | "plugins">,
38
+ serverPlugins: ServerPlugins,
39
+ ): OverviewAnswer {
40
+ const { rootDir, framework } = hamur.options
41
+ const library = LIBRARIES[framework] ?? (framework in LIBRARIES ? undefined : framework)
42
+ return {
43
+ versions: {
44
+ hamur: packageVersion("hamur/kit", "hamur", rootDir),
45
+ adapter: packageVersion(`@hamur/adapter-${framework}`, `@hamur/adapter-${framework}`, rootDir),
46
+ library: library ? packageVersion(library, library, rootDir) : null,
47
+ bun: Bun.version,
48
+ },
49
+ counts: {
50
+ pages: pageCount(hamur.routes),
51
+ serverRoutes: hamur.serverRoutes.length,
52
+ modules: hamur.options.modules.length,
53
+ appPlugins: hamur.plugins.length,
54
+ serverPlugins: serverPlugins.count ?? null,
55
+ },
56
+ }
57
+ }