← Files Visual TruthARCHIVED FILE

skills/visual-truth/assets/visual-truth-package/dist-lib/vite-plugin.mjs

1.91 KB · Oct 4, 2026 · 12:29 UTC

↓ Download file

import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'

export function visualTruthSourcePlugin(options = {}) {
  const output = options.output ?? 'src/visual-truth.generated.ts'
  return {
    name: 'visual-truth-source-bridge',
    apply: 'serve',
    configureServer(server) {
      server.middlewares.use('/__visual_truth_apply', (request, response) => {
        if (request.method === 'GET') {
          response.setHeader('Content-Type', 'application/json')
          response.end(JSON.stringify({ available: true, output }))
          return
        }
        if (request.method !== 'POST') {
          response.statusCode = 405
          response.end('Method not allowed')
          return
        }
        let body = ''
        request.setEncoding('utf8')
        request.on('data', (chunk) => {
          body += chunk
          if (body.length > 2_000_000) request.destroy()
        })
        request.on('end', async () => {
          try {
            const payload = JSON.parse(body)
            if (typeof payload.source !== 'string' || !payload.source.startsWith('// Generated by Visual Truth.')) throw new Error('Invalid Visual Truth source payload.')
            const filePath = resolve(server.config.root, output)
            await mkdir(dirname(filePath), { recursive: true })
            await writeFile(filePath, payload.source, 'utf8')
            server.ws.send({ type: 'full-reload' })
            response.setHeader('Content-Type', 'application/json')
            response.end(JSON.stringify({ ok: true, file: filePath, changes: Number(payload.changes) || 0 }))
          } catch (error) {
            response.statusCode = 400
            response.setHeader('Content-Type', 'application/json')
            response.end(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : 'Could not write Visual Truth source.' }))
          }
        })
      })
    },
  }
}

SHA-256: e94a09fde7abc390faf0b2e5c0b336869116154a024432b3af9f345bacc99c34