import type { StartedServer } from 'devframe/internal' import { existsSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import process from 'node:process' import { createOgDevframe } from '@devframes/plugin-og' import { DEVFRAME_CONNECTION_META_FILENAME } from 'devframe/constants' import { createH3DevframeHost } from 'devframe/internal' import { createHostContext } from 'devframe/node' import { resolveBasePath } from 'devframe/node/hub-internals' import { getPort } from 'devframe/utils/get-port' import { resolveStaticAssetsSource } from 'devframe/utils/remote-assets' import { mountStaticHandler } from 'devframe/utils/serve-static' import { H3 } from 'h3' import { serveTestContext } from '../../../tests/helpers/serve-test-context' export async function testFetch(_url: string): Promise { return new Response(` OG test `, { status: 200, headers: { 'content-type': 'text/html' }, }) } const testDevframe = createOgDevframe({ fetch: testFetch }) /** Resolve the SPA to a local dir: the workspace-linked `--assets` package in dev. */ function localSpaDir(): string { const resolved = resolveStaticAssetsSource(testDevframe.clientAssets!, path.join(os.tmpdir(), 'devframes_plugin_og-test'), testDevframe.importMetaUrl) if (typeof resolved !== 'string') throw new TypeError('Open Graph client SPA missing. Run the plugin build first.') return resolved } export function assertSpaBuilt(): void { if (!existsSync(path.join(localSpaDir(), 'index.html'))) throw new Error('Open Graph SPA missing. Run the plugin build first.') } export interface OgServer extends StartedServer { basePath: string } export async function startOgServer(): Promise { const distDir = localSpaDir() const basePath = resolveBasePath(testDevframe, 'standalone') const host = '127.0.0.1' const port = await getPort({ host, random: true }) const app = new H3() const origin = `http://${host}:${port}` const h3Host = createH3DevframeHost({ origin, appName: testDevframe.id, mount: (base, dir) => mountStaticHandler(app, base, dir), }) const ctx = await createHostContext({ cwd: process.cwd(), mode: 'dev', host: h3Host, }) await testDevframe.setup(ctx) app.use(`${basePath}${DEVFRAME_CONNECTION_META_FILENAME}`, () => ({ backend: 'websocket', websocket: port })) mountStaticHandler(app, basePath, path.resolve(distDir)) const server = await serveTestContext({ context: ctx, host, port, app, auth: false, }) return Object.assign(server, { basePath }) }