Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/devframe/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"crossws": "catalog:deps",
"h3": "catalog:deps",
"nostics": "catalog:deps",
"package-manager-detector": "catalog:deps",
"pathe": "catalog:deps"
},
"devDependencies": {
Expand Down
6 changes: 6 additions & 0 deletions packages/devframe/src/types/remote-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

/**
Expand Down
38 changes: 38 additions & 0 deletions packages/devframe/src/utils/package-manager.test.ts
Original file line number Diff line number Diff line change
@@ -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')
})
})
18 changes: 18 additions & 0 deletions packages/devframe/src/utils/package-manager.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
const agent = (await detect({ cwd }))?.agent
if (!agent || agent === 'npm')
return `npm install ${spec}`
const resolved = resolveCommand(agent, 'add', [spec])
Comment thread
btea marked this conversation as resolved.
Resolved
return resolved
? [resolved.command, ...resolved.args].join(' ')
: `npm install ${spec}`
}
34 changes: 32 additions & 2 deletions packages/devframe/src/utils/remote-assets.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -375,9 +376,9 @@ describe('resolveStaticAssetsSource (validation)', () => {
})

describe('serveStaticHandler with a remote store', () => {
async function serve(store: RemoteAssetsStore): Promise<{ url: string, close: () => Promise<void> }> {
async function serve(store: RemoteAssetsStore, options?: ServeStaticOptions): Promise<{ url: string, close: () => Promise<void> }> {
const app = new H3()
app.use(serveStaticHandler(store))
app.use(serveStaticHandler(store, options))
const server = createServer(toNodeHandler(app))
await new Promise<void>(r => server.listen(0, '127.0.0.1', r))
return {
Expand Down Expand Up @@ -421,6 +422,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: '*/*' },
Expand All @@ -432,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()
}
})
})
32 changes: 22 additions & 10 deletions packages/devframe/src/utils/serve-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -21,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 {
Expand Down Expand Up @@ -170,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,
}
}

Expand All @@ -184,16 +193,18 @@ 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<Response> {
async function remoteResponse(store: RemoteAssetsStore, urlPath: string, accept: string | null | undefined, cwd?: string): Promise<Response> {
try {
return (await store.serve(urlPath)) ?? new Response(null, { status: 404 })
}
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}`, cwd)
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' },
Expand All @@ -204,15 +215,15 @@ 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') {
event.res.status = 405
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') {
Expand All @@ -239,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
Expand Down Expand Up @@ -317,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
Expand Down Expand Up @@ -371,7 +382,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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
const name = esc(pkg)
const ver = esc(version)
Expand All @@ -380,6 +391,7 @@ function remoteErrorPage(pkg: string, version: string, reason: string): string {
package: pkg,
version,
reason,
installCommand,
}
// `</script>` inside the JSON would end the block early; `<` is the only
// character that can do that, and escaping it keeps the literal valid JS.
Expand Down Expand Up @@ -409,7 +421,7 @@ function remoteErrorPage(pkg: string, version: string, reason: string): string {
<p>The UI for this tool is served from <code>${name}@${ver}</code>, which could not be reached.</p>
<pre>${esc(reason)}</pre>
<p>To use it without network access, install the assets package locally:</p>
<pre>npm install ${name}@${ver}</pre>
<pre>${esc(installCommand)}</pre>
<button onclick="location.reload()">Retry</button>
<p class="muted">devframe remote assets</p>
</main>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions packages/hub-ui/src/client/components/views/ViewIframe.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
: {},
}
}

Expand Down
5 changes: 4 additions & 1 deletion packages/hub/src/node/initiate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
10 changes: 4 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions tests/__snapshots__/tsnapi/devframe/index.snapshot.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,7 @@ export interface RemoteAssetsErrorMessage {
package: string;
version: string;
reason: string;
installCommand?: string;
}
export interface RemoteAssetsProviderCustom {
fileUrl: (_: string, _: string, _: string) => string;
Expand Down
1 change: 1 addition & 0 deletions tests/__snapshots__/tsnapi/devframe/types.snapshot.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,7 @@ export interface RemoteAssetsErrorMessage {
package: string;
version: string;
reason: string;
installCommand?: string;
}
export interface RemoteAssetsProviderCustom {
fileUrl: (_: string, _: string, _: string) => string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
export interface ServeStaticOptions {
indexNames?: string[];
single?: boolean;
cwd?: string;
}
// #endregion

Expand Down
Loading