From a0f66fb6ed0fa845ffad89239ae9d2a5e578eb27 Mon Sep 17 00:00:00 2001 From: btea <2356281422@qq.com> Date: Tue, 1 Dec 2026 12:12:13 +0800 Subject: [PATCH 1/2] feat(devframe): resolve the assets install command against the project's package manager --- packages/devframe/package.json | 1 + packages/devframe/src/types/remote-assets.ts | 6 +++ .../src/utils/package-manager.test.ts | 38 +++++++++++++++++++ .../devframe/src/utils/package-manager.ts | 18 +++++++++ .../devframe/src/utils/remote-assets.test.ts | 5 +++ packages/devframe/src/utils/serve-static.ts | 14 ++++--- .../components/views/ViewAssetsError.vue | 2 +- .../client/components/views/ViewIframe.vue | 3 ++ pnpm-lock.yaml | 10 ++--- 9 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 packages/devframe/src/utils/package-manager.test.ts create mode 100644 packages/devframe/src/utils/package-manager.ts diff --git a/packages/devframe/package.json b/packages/devframe/package.json index cecf16bda..553d4c48e 100644 --- a/packages/devframe/package.json +++ b/packages/devframe/package.json @@ -98,6 +98,7 @@ "crossws": "catalog:deps", "h3": "catalog:deps", "nostics": "catalog:deps", + "package-manager-detector": "catalog:deps", "pathe": "catalog:deps" }, "devDependencies": { diff --git a/packages/devframe/src/types/remote-assets.ts b/packages/devframe/src/types/remote-assets.ts index 4fccd7f8c..e07d435e0 100644 --- a/packages/devframe/src/types/remote-assets.ts +++ b/packages/devframe/src/types/remote-assets.ts @@ -98,6 +98,12 @@ export interface RemoteAssetsErrorMessage { version: string /** Why the fetch failed, as reported by the provider or the network stack. */ reason: string + /** + * The suggested local-install command line, resolved by the devframe + * against the package manager of the project it runs in. Absent when the + * sender predates this field; viewers then fall back to the npm spelling. + */ + installCommand?: string } /** diff --git a/packages/devframe/src/utils/package-manager.test.ts b/packages/devframe/src/utils/package-manager.test.ts new file mode 100644 index 000000000..1de6db47b --- /dev/null +++ b/packages/devframe/src/utils/package-manager.test.ts @@ -0,0 +1,38 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { resolveInstallCommandLine } from './package-manager' + +const tmps: string[] = [] + +function makeTmp(): string { + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'devframe-package-manager-'))) + tmps.push(dir) + return dir +} + +afterEach(() => { + while (tmps.length) + rmSync(tmps.pop()!, { recursive: true, force: true }) +}) + +describe('resolveInstallCommandLine', () => { + it('uses the package manager named by the lockfile', async () => { + const dir = makeTmp() + writeFileSync(join(dir, 'pnpm-lock.yaml'), 'lockfileVersion: 1\n') + await expect(resolveInstallCommandLine('@scope/demo@1.2.3', dir)).resolves.toBe('pnpm add @scope/demo@1.2.3') + }) + + it('walks up from a nested directory to the project root', async () => { + const dir = makeTmp() + writeFileSync(join(dir, 'package-lock.json'), '{}\n') + const nested = join(dir, 'packages', 'demo') + mkdirSync(nested, { recursive: true }) + await expect(resolveInstallCommandLine('@scope/demo@1.2.3', nested)).resolves.toBe('npm install @scope/demo@1.2.3') + }) + + it('falls back to the npm spelling when nothing identifies the manager', async () => { + await expect(resolveInstallCommandLine('@scope/demo@1.2.3', makeTmp())).resolves.toBe('npm install @scope/demo@1.2.3') + }) +}) diff --git a/packages/devframe/src/utils/package-manager.ts b/packages/devframe/src/utils/package-manager.ts new file mode 100644 index 000000000..e27579c32 --- /dev/null +++ b/packages/devframe/src/utils/package-manager.ts @@ -0,0 +1,18 @@ +import process from 'node:process' +import { detect, resolveCommand } from 'package-manager-detector' + +/** + * The local-install command line for `spec` (a `name@version` string), using + * the package manager of the project at `cwd`. npm projects get the full + * `npm install` spelling (`resolveCommand` shortens it to `npm i`), and the + * same spelling covers projects whose manager cannot be detected. + */ +export async function resolveInstallCommandLine(spec: string, cwd: string = process.cwd()): Promise { + const agent = (await detect({ cwd }))?.agent + if (!agent || agent === 'npm') + return `npm install ${spec}` + const resolved = resolveCommand(agent, 'add', [spec]) + return resolved + ? [resolved.command, ...resolved.args].join(' ') + : `npm install ${spec}` +} diff --git a/packages/devframe/src/utils/remote-assets.test.ts b/packages/devframe/src/utils/remote-assets.test.ts index 4abf7db60..9f500b055 100644 --- a/packages/devframe/src/utils/remote-assets.test.ts +++ b/packages/devframe/src/utils/remote-assets.test.ts @@ -421,6 +421,11 @@ describe('serveStaticHandler with a remote store', () => { const payload = JSON.parse(/postMessage\((\{.*?\}), '\*'\)/.exec(body)![1]) as RemoteAssetsErrorMessage expect(payload).toMatchObject({ package: '@scope/demo-client', version: '1.2.3' }) expect(payload.reason).toContain('network down') + // The page spells out a concrete install command resolved against the + // project's package manager, and reports the same one to the viewer. + expect(payload.installCommand).toBeDefined() + expect(payload.installCommand).toContain('@scope/demo-client@1.2.3') + expect(body).toContain(payload.installCommand!) const asset = await fetch(`${url}/app.js`, { headers: { accept: '*/*' }, diff --git a/packages/devframe/src/utils/serve-static.ts b/packages/devframe/src/utils/serve-static.ts index b338b1cab..4aa850dbc 100644 --- a/packages/devframe/src/utils/serve-static.ts +++ b/packages/devframe/src/utils/serve-static.ts @@ -9,6 +9,7 @@ import { defineHandler, H3 } from 'h3' import { lookup } from 'mrmime' import { extname, join, normalize, resolve, sep } from 'pathe' import { DEVFRAME_EVENTS } from '../events' +import { resolveInstallCommandLine } from './package-manager' /** * What the static-serving engine accepts: a local directory, or a resolved @@ -190,10 +191,12 @@ async function remoteResponse(store: RemoteAssetsStore, urlPath: string, accept: } catch (error) { if (typeof accept === 'string' && accept.includes('text/html')) { + const reason = error instanceof Error + ? error.message + : String(error) + const installCommand = await resolveInstallCommandLine(`${store.assets.package}@${store.assets.version}`) return new Response( - remoteErrorPage(store.assets.package, store.assets.version, error instanceof Error - ? error.message - : String(error)), + remoteErrorPage(store.assets.package, store.assets.version, reason, installCommand), { status: 502, headers: { 'Content-Type': 'text/html; charset=utf-8' }, @@ -371,7 +374,7 @@ export function serveStaticNodeMiddleware( * ({@link DEVFRAME_REMOTE_ASSETS_ERROR_MESSAGE_TYPE}) so the viewer can show * the same failure in its own UI instead. */ -function remoteErrorPage(pkg: string, version: string, reason: string): string { +function remoteErrorPage(pkg: string, version: string, reason: string, installCommand: string): string { const esc = (s: string): string => s.replace(/&/g, '&').replace(//g, '>') const name = esc(pkg) const ver = esc(version) @@ -380,6 +383,7 @@ function remoteErrorPage(pkg: string, version: string, reason: string): string { package: pkg, version, reason, + installCommand, } // `` inside the JSON would end the block early; `<` is the only // character that can do that, and escaping it keeps the literal valid JS. @@ -409,7 +413,7 @@ function remoteErrorPage(pkg: string, version: string, reason: string): string {

The UI for this tool is served from ${name}@${ver}, which could not be reached.

${esc(reason)}

To use it without network access, install the assets package locally:

-
npm install ${name}@${ver}
+
${esc(installCommand)}

devframe remote assets

diff --git a/packages/hub-ui/src/client/components/views/ViewAssetsError.vue b/packages/hub-ui/src/client/components/views/ViewAssetsError.vue index b9d205032..aae0259c3 100644 --- a/packages/hub-ui/src/client/components/views/ViewAssetsError.vue +++ b/packages/hub-ui/src/client/components/views/ViewAssetsError.vue @@ -19,7 +19,7 @@ const emit = defineEmits<{ retry: [] }>() -const installCommand = computed(() => `npm install ${props.error.package}@${props.error.version}`) +const installCommand = computed(() => props.error.installCommand ?? `npm install ${props.error.package}@${props.error.version}`) const hint = computed(() => tAround('assets.hint', 'pkg')) const copied = ref(false) diff --git a/packages/hub-ui/src/client/components/views/ViewIframe.vue b/packages/hub-ui/src/client/components/views/ViewIframe.vue index cd394b7e4..5fe1ac463 100644 --- a/packages/hub-ui/src/client/components/views/ViewIframe.vue +++ b/packages/hub-ui/src/client/components/views/ViewIframe.vue @@ -124,6 +124,9 @@ function onWindowMessage(event: MessageEvent) { package: String(data.package ?? ''), version: String(data.version ?? ''), reason: String(data.reason ?? ''), + ...typeof data.installCommand === 'string' + ? { installCommand: data.installCommand } + : {}, } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index df61a2f05..41daf7c1b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1684,6 +1684,9 @@ importers: nostics: specifier: catalog:deps version: 1.4.0 + package-manager-detector: + specifier: catalog:deps + version: 1.9.0 pathe: specifier: catalog:deps version: 2.0.3 @@ -10657,9 +10660,6 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} - package-manager-detector@1.8.0: - resolution: {integrity: sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A==} - package-manager-detector@1.9.0: resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} @@ -18073,7 +18073,7 @@ snapshots: args-tokenizer: 0.3.0 cac: 7.0.0 jsonc-parser: 3.3.1 - package-manager-detector: 1.8.0 + package-manager-detector: 1.9.0 tinyexec: 1.3.1 tinyglobby: 0.2.17 unconfig: 7.5.0 @@ -21936,8 +21936,6 @@ snapshots: dependencies: p-limit: 3.1.0 - package-manager-detector@1.8.0: {} - package-manager-detector@1.9.0: {} pako@0.2.9: {} From e8f4b1aeea4b82275096bca65adfbb8d49bfd958 Mon Sep 17 00:00:00 2001 From: btea <2356281422@qq.com> Date: Tue, 1 Dec 2026 13:50:30 +0800 Subject: [PATCH 2/2] feat: update --- .../devframe/src/utils/remote-assets.test.ts | 29 +++++++++++++++++-- packages/devframe/src/utils/serve-static.ts | 20 +++++++++---- packages/hub/src/node/initiate.ts | 5 +++- .../tsnapi/devframe/index.snapshot.d.ts | 1 + .../tsnapi/devframe/types.snapshot.d.ts | 1 + .../devframe/utils/serve-static.snapshot.d.ts | 1 + 6 files changed, 48 insertions(+), 9 deletions(-) diff --git a/packages/devframe/src/utils/remote-assets.test.ts b/packages/devframe/src/utils/remote-assets.test.ts index 9f500b055..0bd300874 100644 --- a/packages/devframe/src/utils/remote-assets.test.ts +++ b/packages/devframe/src/utils/remote-assets.test.ts @@ -1,6 +1,7 @@ import type { AddressInfo } from 'node:net' import type { MockInstance } from 'vitest' import type { RemoteAssets, RemoteAssetsErrorMessage, RemoteAssetsProviderCustom, RemoteAssetsStore } from '../types/remote-assets' +import type { ServeStaticOptions } from './serve-static' import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' import { tmpdir } from 'node:os' @@ -375,9 +376,9 @@ describe('resolveStaticAssetsSource (validation)', () => { }) describe('serveStaticHandler with a remote store', () => { - async function serve(store: RemoteAssetsStore): Promise<{ url: string, close: () => Promise }> { + async function serve(store: RemoteAssetsStore, options?: ServeStaticOptions): Promise<{ url: string, close: () => Promise }> { const app = new H3() - app.use(serveStaticHandler(store)) + app.use(serveStaticHandler(store, options)) const server = createServer(toNodeHandler(app)) await new Promise(r => server.listen(0, '127.0.0.1', r)) return { @@ -437,4 +438,28 @@ describe('serveStaticHandler with a remote store', () => { await close() } }) + + it('resolves the install hint against the configured project directory', async () => { + const projectDir = makeTmp() + // The repo itself is a pnpm project, so a yarn lockfile here proves the + // hint follows the configured directory rather than `process.cwd()`. + writeFileSync(join(projectDir, 'yarn.lock'), '') + const store = storeFor({ + fetch: async () => { + throw new Error('network down') + }, + }, makeTmp()) + const { url, close } = await serve(store, { cwd: projectDir }) + try { + const res = await fetch(`${url}/`, { + headers: { accept: 'text/html' }, + }) + const body = await res.text() + const payload = JSON.parse(/postMessage\((\{.*?\}), '\*'\)/.exec(body)![1]) as RemoteAssetsErrorMessage + expect(payload.installCommand).toBe('yarn add @scope/demo-client@1.2.3') + } + finally { + await close() + } + }) }) diff --git a/packages/devframe/src/utils/serve-static.ts b/packages/devframe/src/utils/serve-static.ts index 4aa850dbc..df60e4df6 100644 --- a/packages/devframe/src/utils/serve-static.ts +++ b/packages/devframe/src/utils/serve-static.ts @@ -22,6 +22,12 @@ export interface ServeStaticOptions { indexNames?: string[] /** SPA fallback to `indexNames[0]` on miss. Default: `true`. */ single?: boolean + /** + * Project directory used to pick the package manager named in the + * remote-assets install hint. It does not change file resolution. + * Default: `process.cwd()`. + */ + cwd?: string } interface ResolvedFile { @@ -171,12 +177,14 @@ function applyStaticHeadersToNode(res: ServerResponse, file: ResolvedFile): void interface NormalizedOptions { indexNames: string[] single: boolean + cwd?: string } function normalizeOptions(options: ServeStaticOptions | undefined): NormalizedOptions { return { indexNames: options?.indexNames ?? ['index.html'], single: options?.single ?? true, + cwd: options?.cwd, } } @@ -185,7 +193,7 @@ function normalizeOptions(options: ServeStaticOptions | undefined): NormalizedOp * `Response` on a hit, a 404 on a miss, or a 502 (styled error page for HTML * navigations) on provider failure, shared between the h3 and connect flavors. */ -async function remoteResponse(store: RemoteAssetsStore, urlPath: string, accept: string | null | undefined): Promise { +async function remoteResponse(store: RemoteAssetsStore, urlPath: string, accept: string | null | undefined, cwd?: string): Promise { try { return (await store.serve(urlPath)) ?? new Response(null, { status: 404 }) } @@ -194,7 +202,7 @@ async function remoteResponse(store: RemoteAssetsStore, urlPath: string, accept: const reason = error instanceof Error ? error.message : String(error) - const installCommand = await resolveInstallCommandLine(`${store.assets.package}@${store.assets.version}`) + const installCommand = await resolveInstallCommandLine(`${store.assets.package}@${store.assets.version}`, cwd) return new Response( remoteErrorPage(store.assets.package, store.assets.version, reason, installCommand), { @@ -207,7 +215,7 @@ async function remoteResponse(store: RemoteAssetsStore, urlPath: string, accept: } } -function serveRemoteAssetsHandler(store: RemoteAssetsStore): EventHandler { +function serveRemoteAssetsHandler(store: RemoteAssetsStore, cwd?: string): EventHandler { return defineHandler(async (event) => { const method = event.req.method if (method !== 'GET' && method !== 'HEAD') { @@ -215,7 +223,7 @@ function serveRemoteAssetsHandler(store: RemoteAssetsStore): EventHandler { event.res.headers.set('Allow', 'GET, HEAD') return '' } - const res = await remoteResponse(store, event.url.pathname, event.req.headers.get('accept')) + const res = await remoteResponse(store, event.url.pathname, event.req.headers.get('accept'), cwd) event.res.status = res.status res.headers.forEach((v, k) => event.res.headers.set(k, v)) if (method === 'HEAD') { @@ -242,7 +250,7 @@ export function serveStaticHandler( options?: ServeStaticOptions, ): EventHandler { if (typeof source !== 'string') - return serveRemoteAssetsHandler(source) + return serveRemoteAssetsHandler(source, options?.cwd) const absDir = resolve(source) const opts = normalizeOptions(options) // Canonicalize the served root once; the containment check compares every @@ -320,7 +328,7 @@ export function serveStaticNodeMiddleware( const url = req.url ?? '/' if (absDir === undefined) { - const response = await remoteResponse(source as RemoteAssetsStore, url, req.headers.accept) + const response = await remoteResponse(source as RemoteAssetsStore, url, req.headers.accept, opts.cwd) if (response.status === 404 && next) { next() return diff --git a/packages/hub/src/node/initiate.ts b/packages/hub/src/node/initiate.ts index 461808498..c09d0d06d 100644 --- a/packages/hub/src/node/initiate.ts +++ b/packages/hub/src/node/initiate.ts @@ -362,7 +362,10 @@ async function resolveHubContext( appName: 'devframes', workspaceRoot: cwd, mount: (mountBase, dir) => { - mountStaticHandler(app, mountBase, dir) + // `cwd` is the project the hub serves, which may differ from the + // process directory; the remote-assets install hint must name that + // project's package manager. + mountStaticHandler(app, mountBase, dir, { cwd }) }, }) const host = { diff --git a/tests/__snapshots__/tsnapi/devframe/index.snapshot.d.ts b/tests/__snapshots__/tsnapi/devframe/index.snapshot.d.ts index 466986ee2..0f2c9ef01 100644 --- a/tests/__snapshots__/tsnapi/devframe/index.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/devframe/index.snapshot.d.ts @@ -590,6 +590,7 @@ export interface RemoteAssetsErrorMessage { package: string; version: string; reason: string; + installCommand?: string; } export interface RemoteAssetsProviderCustom { fileUrl: (_: string, _: string, _: string) => string; diff --git a/tests/__snapshots__/tsnapi/devframe/types.snapshot.d.ts b/tests/__snapshots__/tsnapi/devframe/types.snapshot.d.ts index 6dd07e686..8089c8b23 100644 --- a/tests/__snapshots__/tsnapi/devframe/types.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/devframe/types.snapshot.d.ts @@ -590,6 +590,7 @@ export interface RemoteAssetsErrorMessage { package: string; version: string; reason: string; + installCommand?: string; } export interface RemoteAssetsProviderCustom { fileUrl: (_: string, _: string, _: string) => string; diff --git a/tests/__snapshots__/tsnapi/devframe/utils/serve-static.snapshot.d.ts b/tests/__snapshots__/tsnapi/devframe/utils/serve-static.snapshot.d.ts index 6d5c6bdc5..14b89c6ea 100644 --- a/tests/__snapshots__/tsnapi/devframe/utils/serve-static.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/devframe/utils/serve-static.snapshot.d.ts @@ -5,6 +5,7 @@ export interface ServeStaticOptions { indexNames?: string[]; single?: boolean; + cwd?: string; } // #endregion