@huaqiu/hardware-artifacts 0.7.18 → 0.7.19

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/src/routes.ts CHANGED
@@ -2,9 +2,13 @@
2
2
  import type { IncomingMessage, ServerResponse } from 'node:http'
3
3
  import { readFileSync } from 'node:fs'
4
4
  import type { ArtifactKind, HardwareArtifactService, NativeApplication } from './service.js'
5
+ import type { ToolchainId, ToolchainManager } from './toolchain/index.js'
5
6
 
6
7
  export const HARDWARE_ROUTE_PREFIX = '/api/v1/hardware'
7
8
 
9
+ /** Prefix owned by the toolchain capability, beside the artifact routes. */
10
+ export const TOOLCHAIN_ROUTE_PREFIX = `${HARDWARE_ROUTE_PREFIX}/toolchain`
11
+
8
12
  /**
9
13
  * Resolve the workspace root of one DSH session, host-side.
10
14
  *
@@ -16,6 +20,8 @@ export type WorkspaceResolver = (sessionId: string) => Promise<string | undefine
16
20
 
17
21
  export interface HardwareHandlerOptions {
18
22
  readonly resolveWorkspace?: WorkspaceResolver
23
+ /** Toolchain status/validation/discovery/install surface, when mounted. */
24
+ readonly toolchain?: ToolchainManager
19
25
  }
20
26
 
21
27
  function sendJson(res: ServerResponse, status: number, body: unknown): void {
@@ -53,14 +59,6 @@ function failure(error: unknown): { status: number; body: unknown } {
53
59
  return { status, body: { ok: false, error: { code, message: error instanceof Error ? error.message : String(error) } } }
54
60
  }
55
61
 
56
- /** Roots a request may read: the caller's workspace, then the host's own. */
57
- function rootsOf(body: unknown): string[] {
58
- if (body === null || typeof body !== 'object') return []
59
- const cwd = asString((body as Record<string, unknown>).cwd)
60
- const workspace = asString((body as Record<string, unknown>).workspace)
61
- return [cwd, workspace].filter((value): value is string => value !== undefined)
62
- }
63
-
64
62
  /** The DSH session a request belongs to: a query field for reads, a body field for writes. */
65
63
  function sessionOf(url: URL, body?: unknown): string | undefined {
66
64
  const fromBody = body === null || typeof body !== 'object'
@@ -69,39 +67,124 @@ function sessionOf(url: URL, body?: unknown): string | undefined {
69
67
  return fromBody ?? asString(url.searchParams.get('session') ?? undefined)
70
68
  }
71
69
 
70
+ /** Narrow one request field to a toolchain id. */
71
+ function toolOf(value: unknown): ToolchainId | undefined {
72
+ return value === 'kicad' || value === 'solidcraft' ? value : undefined
73
+ }
74
+
75
+ /** The source vocabulary the save route accepts (`detected` is written by discovery). */
76
+ function sourceOf(value: unknown): 'manual' | 'browse' | 'download' | 'detected' | undefined {
77
+ return value === 'manual' || value === 'browse' || value === 'download' || value === 'detected' ? value : undefined
78
+ }
79
+
72
80
  /**
73
- * Everything one request may read: the roots it named plus the workspace of the
74
- * session it belongs to.
81
+ * The toolchain surface: status, validate, save, browse, install, cancel,
82
+ * discover, capabilities.
75
83
  *
76
- * The session's workspace is resolved here, not taken from `cwd`: the browser
77
- * sends whichever cwd its session hook held at render time, and a viewer that
78
- * stayed mounted across a workspace switch would otherwise authorize against a
79
- * workspace it no longer shows.
84
+ * Every handler answers a JSON envelope the client can render without guessing,
85
+ * and every failure keeps a stable `code` so the UI can localise it (the same
86
+ * vocabulary the installer uses, §7.2/§17). Nothing here starts work the caller
87
+ * did not ask for: discovery and install are explicit POSTs.
88
+ * @returns true when the request was answered.
80
89
  */
81
- async function authorizeRequest(
82
- options: HardwareHandlerOptions,
90
+ async function handleToolchain(
91
+ req: IncomingMessage,
92
+ res: ServerResponse,
83
93
  url: URL,
84
- body?: unknown,
85
- ): Promise<{ roots: string[]; sessionId?: string }> {
86
- const sessionId = sessionOf(url, body)
87
- const roots = rootsOf(body)
88
- // Reads carry theirs in the query string; writes in the body. Either way they
89
- // only add to the session's workspace, never replace it.
90
- for (const key of ['cwd', 'workspace']) {
91
- const value = asString(url.searchParams.get(key) ?? undefined)
92
- if (value !== undefined && !roots.includes(value)) roots.push(value)
94
+ manager: ToolchainManager,
95
+ ): Promise<boolean> {
96
+ const path = url.pathname
97
+ if (!path.startsWith(TOOLCHAIN_ROUTE_PREFIX)) return false
98
+ const route = path.slice(TOOLCHAIN_ROUTE_PREFIX.length)
99
+ const badRequest = (message: string): true => {
100
+ sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message } })
101
+ return true
102
+ }
103
+
104
+ if (req.method === 'GET' && route === '/status') {
105
+ // `?job=a,b` — both tools can install at once, so the poll carries every id
106
+ // the caller is watching rather than a single "current" one.
107
+ const jobIds = (url.searchParams.get('job') ?? '')
108
+ .split(',')
109
+ .map(entry => entry.trim())
110
+ .filter(entry => entry !== '')
111
+ sendJson(res, 200, { ok: true, ...await manager.status(jobIds.length === 0 ? undefined : jobIds) })
112
+ return true
113
+ }
114
+ if (req.method === 'GET' && route === '/capabilities') {
115
+ sendJson(res, 200, { ok: true, ...await manager.capabilities() })
116
+ return true
117
+ }
118
+ if (req.method === 'GET' && route === '/job') {
119
+ const id = asString(url.searchParams.get('id') ?? undefined)
120
+ const job = id === undefined ? undefined : manager.job(id)
121
+ if (job === undefined) {
122
+ sendJson(res, 404, { ok: false, error: { code: 'unknown-job', message: 'no such installation job' } })
123
+ return true
124
+ }
125
+ sendJson(res, 200, { ok: true, job })
126
+ return true
127
+ }
128
+
129
+ if (req.method !== 'POST') {
130
+ sendJson(res, 405, { ok: false, error: { code: 'method-not-allowed', message: 'method not allowed' } })
131
+ return true
132
+ }
133
+
134
+ const body = await readJson(req) as Record<string, unknown>
135
+ if (route === '/validate' || route === '/save') {
136
+ const tool = toolOf(body.tool)
137
+ const input = asString(body.path)
138
+ if (tool === undefined) return badRequest('tool must be kicad or solidcraft')
139
+ if (input === undefined) return badRequest('path is required')
140
+ const source = sourceOf(body.source) ?? 'manual'
141
+ const outcome = route === '/save'
142
+ ? await manager.save(tool, input, source)
143
+ : await manager.validate(tool, input)
144
+ sendJson(res, 200, { tool, ...outcome })
145
+ return true
146
+ }
147
+ if (route === '/browse') {
148
+ const tool = toolOf(body.tool)
149
+ if (tool === undefined) return badRequest('tool must be kicad or solidcraft')
150
+ const abort = new AbortController()
151
+ const timer = setTimeout(() => { abort.abort() }, 15 * 60_000)
152
+ timer.unref?.()
153
+ try {
154
+ const outcome = await manager.browse(tool, abort.signal)
155
+ sendJson(res, 200, { ok: true, tool, ...outcome })
156
+ } finally {
157
+ clearTimeout(timer)
158
+ }
159
+ return true
160
+ }
161
+ if (route === '/install') {
162
+ const tool = toolOf(body.tool)
163
+ if (tool === undefined) return badRequest('tool must be kicad or solidcraft')
164
+ const started = await manager.install(tool)
165
+ if (started.error !== undefined) {
166
+ // A manifest this host cannot install from is a state, not a crash: the
167
+ // UI falls back to manual configuration (§14.2).
168
+ sendJson(res, 200, { ok: false, tool, error: started.error })
169
+ return true
170
+ }
171
+ sendJson(res, 200, { ok: true, tool, job: started.snapshot })
172
+ return true
93
173
  }
94
- if (sessionId === undefined || options.resolveWorkspace === undefined) {
95
- return { roots }
174
+ if (route === '/cancel') {
175
+ const id = asString(body.id)
176
+ if (id === undefined) return badRequest('id is required')
177
+ sendJson(res, 200, { ok: true, cancelled: manager.cancel(id) })
178
+ return true
96
179
  }
97
- try {
98
- const workspace = await options.resolveWorkspace(sessionId)
99
- if (workspace !== undefined && workspace !== '') roots.push(workspace)
100
- } catch {
101
- // An unresolvable session is not a reason to fail a local read: the caller's
102
- // own roots still apply, and they can only come from this machine.
180
+ if (route === '/discover') {
181
+ const tool = body.tool === undefined ? undefined : toolOf(body.tool)
182
+ if (body.tool !== undefined && tool === undefined) return badRequest('tool must be kicad or solidcraft')
183
+ sendJson(res, 200, { ok: true, ...manager.startDiscovery(tool) })
184
+ return true
103
185
  }
104
- return { roots, sessionId }
186
+ badRequest(`unknown toolchain route ${route}`)
187
+ return true
105
188
  }
106
189
 
107
190
  export function createHardwareHandler(
@@ -117,6 +200,7 @@ export function createHardwareHandler(
117
200
  try {
118
201
  const url = new URL(req.url ?? '/', 'http://dsh.internal')
119
202
  const p = url.pathname
203
+ if (options.toolchain !== undefined && await handleToolchain(req, res, url, options.toolchain)) return
120
204
  if (req.method === 'GET' && p === `${HARDWARE_ROUTE_PREFIX}/projects`) {
121
205
  const sessionId = asString(url.searchParams.get('session') ?? undefined)
122
206
  let workspace = asString(url.searchParams.get('cwd') ?? undefined)
@@ -157,12 +241,11 @@ export function createHardwareHandler(
157
241
  return
158
242
  }
159
243
  const revision = asString(url.searchParams.get('revision') ?? undefined)
160
- const { roots, sessionId } = await authorizeRequest(options, url)
244
+ const sessionId = sessionOf(url)
161
245
  try {
162
246
  const source = await service.readSource({
163
247
  artifactPath,
164
248
  ...(revision === undefined ? {} : { expectedRevision: revision }),
165
- roots,
166
249
  ...(sessionId === undefined ? {} : { sessionId }),
167
250
  })
168
251
  sendJson(res, 200, { ok: true, ...source })
@@ -184,12 +267,11 @@ export function createHardwareHandler(
184
267
  return
185
268
  }
186
269
  const schematic = asString(body.schematic)
187
- const { roots, sessionId } = await authorizeRequest(options, url, body)
270
+ const sessionId = sessionOf(url, body)
188
271
  try {
189
272
  const prepared = await service.fabricate({
190
273
  boardPath: artifactPath,
191
274
  ...(schematic === undefined ? {} : { schematicPath: schematic }),
192
- roots,
193
275
  ...(sessionId === undefined ? {} : { sessionId }),
194
276
  })
195
277
  sendJson(res, 200, {
@@ -199,6 +281,7 @@ export function createHardwareHandler(
199
281
  generatedAt: prepared.generatedAt,
200
282
  facts: prepared.facts,
201
283
  archive: prepared.archive,
284
+ validation: prepared.validation,
202
285
  ...(prepared.assembly === undefined ? {} : { assembly: prepared.assembly }),
203
286
  })
204
287
  } catch (error) {
@@ -225,16 +308,15 @@ export function createHardwareHandler(
225
308
  return
226
309
  }
227
310
  const schematic = asString(body.schematic)
228
- const { roots, sessionId } = await authorizeRequest(options, url, body)
311
+ const sessionId = sessionOf(url, body)
229
312
  try {
230
313
  const placed = await service.placeOrder({
231
314
  kind: 'pcb',
232
315
  boardPath: artifactPath,
233
316
  ...(schematic === undefined ? {} : { schematicPath: schematic }),
234
- roots,
235
317
  ...(sessionId === undefined ? {} : { sessionId }),
236
318
  ...(typeof body.quantity === 'number' ? { quantity: body.quantity } : {}),
237
- ...(body.launch === false ? { launch: false } : {}),
319
+ ...(body.launch === true ? { launch: true } : {}),
238
320
  })
239
321
  sendJson(res, 200, { ok: true, ...placed })
240
322
  } catch (error) {
@@ -261,16 +343,15 @@ export function createHardwareHandler(
261
343
  return
262
344
  }
263
345
  const schematic = asString(body.schematic)
264
- const { roots, sessionId } = await authorizeRequest(options, url, body)
346
+ const sessionId = sessionOf(url, body)
265
347
  try {
266
348
  const placed = await service.placeOrder({
267
349
  kind: 'smt',
268
350
  boardPath: artifactPath,
269
351
  ...(schematic === undefined ? {} : { schematicPath: schematic }),
270
- roots,
271
352
  ...(sessionId === undefined ? {} : { sessionId }),
272
353
  ...(typeof body.quantity === 'number' ? { quantity: body.quantity } : {}),
273
- ...(body.launch === false ? { launch: false } : {}),
354
+ ...(body.launch === true ? { launch: true } : {}),
274
355
  })
275
356
  sendJson(res, 200, { ok: true, ...placed })
276
357
  } catch (error) {
@@ -302,11 +383,10 @@ export function createHardwareHandler(
302
383
  sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'path is required' } })
303
384
  return
304
385
  }
305
- const { roots, sessionId } = await authorizeRequest(options, url, body)
386
+ const sessionId = sessionOf(url, body)
306
387
  try {
307
388
  const bom = await service.exportBom({
308
389
  artifactPath,
309
- roots,
310
390
  ...(sessionId === undefined ? {} : { sessionId }),
311
391
  })
312
392
  sendJson(res, 200, { ok: true, ...bom })
@@ -323,11 +403,10 @@ export function createHardwareHandler(
323
403
  sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'path is required' } })
324
404
  return
325
405
  }
326
- const { roots, sessionId } = await authorizeRequest(options, url, body)
406
+ const sessionId = sessionOf(url, body)
327
407
  try {
328
408
  const glb = await service.exportGlb({
329
409
  artifactPath,
330
- roots,
331
410
  ...(sessionId === undefined ? {} : { sessionId }),
332
411
  })
333
412
  const query = new URLSearchParams({ path: glb.path, revision: glb.revision })