Add on-page editor for the go-graph-cms
Injectable React editor that is side-loaded onto the statically rendered page and edits through the CMS HTTP API (POST /api/edit). - Shadow-root UI over server HTML; patches morphed in, undo/redo from server inverses (reuses @k6n/cms-editor EditClient/morph/markdown editor) - Sign-in via go-auth device grant as the CMS client (aud matches), token refresh + 401 retry; live preview swapped in on load and on tab focus - Schema-driven property form (arrays, maps, variants, $ref, validation) - Every string property editable where it is rendered (value-bound inline fields and attribute chips), markdown WYSIWYG for marked fields - Block palette + drag & drop with ghost drop targets, insertion slots, sort snapping between siblings (Alt to nest) - x-style annotations: on-page padding/margin/gap handles, Style panel, wrap-in-layout; x-graph label/group for titles and grouping - Dev workflow: Vite proxy to the live site (token injected server-side) or an offline in-memory mock CMS; jsdom test suite Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
1af9ec3172
67 files changed
+12322
No files matched your search
@@ -0,0 +1,91 @@
|
||||
// Dev server for the *live* CMS: everything is proxied to CMS_TARGET, and the
|
||||
// page HTML (which the proxy can't rewrite reliably - compression, streaming)
|
||||
// is fetched server-side so the editor's dev entry can be injected into it.
|
||||
//
|
||||
// Auth never reaches the browser: CMS_TOKEN / CMS_API_KEY / CMS_COOKIE are added
|
||||
// to every upstream request here.
|
||||
import type { Plugin, ViteDevServer } from 'vite'
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import { injectDevEntry, isPageRequest, isViteOwned, upstreamHeaders } from './shared'
|
||||
|
||||
export function cmsLivePlugin(env: Record<string, string>): Plugin {
|
||||
const target = (env.CMS_TARGET || 'https://k6n.net').replace(/\/$/, '')
|
||||
const fixed = { token: env.CMS_TOKEN, apiKey: env.CMS_API_KEY, cookie: env.CMS_COOKIE }
|
||||
// Token the browser got through the in-editor device login (POST /__dev/token). Env credentials win.
|
||||
let runtimeToken: string | undefined
|
||||
const creds = () => ({ ...fixed, token: fixed.token || runtimeToken })
|
||||
|
||||
return {
|
||||
name: 'cms-live',
|
||||
config: () => ({
|
||||
server: {
|
||||
proxy: {
|
||||
// Anything Vite doesn't own goes to the real site (assets, /api, /editor, fonts...).
|
||||
'^/(?!@|src/|node_modules/|__).*': {
|
||||
target,
|
||||
changeOrigin: true,
|
||||
secure: true,
|
||||
cookieDomainRewrite: '',
|
||||
cookiePathRewrite: '/',
|
||||
bypass: (req) => (isViteOwned(req.url ?? '') ? req.url : undefined),
|
||||
configure: (proxy) => {
|
||||
proxy.on('proxyReq', (proxyReq, req) => {
|
||||
const h = upstreamHeaders(req.headers, creds())
|
||||
for (const [k, v] of Object.entries(h)) proxyReq.setHeader(k, v)
|
||||
})
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
configureServer(server: ViteDevServer) {
|
||||
// Registered directly (not in a returned fn) so it runs BEFORE the proxy.
|
||||
server.middlewares.use(async (req: IncomingMessage, res: ServerResponse, next) => {
|
||||
if (req.url === '/__dev/token') {
|
||||
if (req.method === 'DELETE') runtimeToken = undefined
|
||||
else if (req.method === 'POST') {
|
||||
const chunks: Buffer[] = []
|
||||
for await (const c of req) chunks.push(c as Buffer)
|
||||
try {
|
||||
runtimeToken = (JSON.parse(Buffer.concat(chunks).toString()) as { accessToken?: string }).accessToken
|
||||
} catch {
|
||||
/* ignore malformed */
|
||||
}
|
||||
}
|
||||
res.statusCode = 204
|
||||
return void res.end()
|
||||
}
|
||||
if (!isPageRequest(req)) return next()
|
||||
try {
|
||||
const upstream = await fetch(target + req.url, {
|
||||
headers: upstreamHeaders(req.headers, creds(), { identity: true }),
|
||||
redirect: 'manual',
|
||||
})
|
||||
const type = upstream.headers.get('content-type') ?? ''
|
||||
res.statusCode = upstream.status
|
||||
upstream.headers.forEach((v, k) => {
|
||||
// fetch() already decoded the body; CSP would block our injected module.
|
||||
if (['content-encoding', 'content-length', 'transfer-encoding', 'content-security-policy', 'strict-transport-security'].includes(k)) return
|
||||
if (k === 'location') v = v.replace(target, '')
|
||||
if (k === 'set-cookie') return
|
||||
res.setHeader(k, v)
|
||||
})
|
||||
for (const c of upstream.headers.getSetCookie()) {
|
||||
res.appendHeader('set-cookie', c.replace(/;\s*domain=[^;]*/i, '').replace(/;\s*secure/i, ''))
|
||||
}
|
||||
let body = await upstream.text()
|
||||
if (type.includes('text/html')) {
|
||||
body = await server.transformIndexHtml(req.url!, injectDevEntry(body))
|
||||
res.setHeader('x-cms-dev', 'injected')
|
||||
res.setHeader('cache-control', 'no-store') // never let the browser reuse a stale published page
|
||||
}
|
||||
res.end(body)
|
||||
} catch (e) {
|
||||
res.statusCode = 502
|
||||
res.setHeader('content-type', 'text/plain')
|
||||
res.end(`dev proxy: cannot reach ${target}: ${(e as Error).message}`)
|
||||
}
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// `npm run dev:mock`: no network, no login. Serves a fixture page and the mock API.
|
||||
import type { Plugin } from 'vite'
|
||||
import { createMockCms } from '../mock/server'
|
||||
import { injectDevEntry } from './shared'
|
||||
|
||||
export function cmsMockPlugin(): Plugin {
|
||||
// CMS_MOCK_AUTH=1 makes the mock require the device-login flow (approve on the mock /device page) so the login UI can be developed.
|
||||
const cms = createMockCms(process.env.CMS_MOCK_AUTH ? { auth: true } : {})
|
||||
return {
|
||||
name: 'cms-mock',
|
||||
configureServer(server) {
|
||||
server.middlewares.use(async (req, res, next) => {
|
||||
const url = req.url ?? '/'
|
||||
if (url.startsWith('/__dev/')) return void ((res.statusCode = 204), res.end())
|
||||
const isApi = url.startsWith('/api/')
|
||||
const isReset = url === '/__mock/reset' && req.method === 'POST'
|
||||
const isMock = url === '/device' || url.startsWith('/device?') || url === '/__mock/approve'
|
||||
const isPage = req.method === 'GET' && !/^\/(@|src\/|node_modules\/|mock\/|__)/.test(url) && String(req.headers.accept ?? '').includes('text/html')
|
||||
if (!isApi && !isReset && !isPage && !isMock) return next()
|
||||
if (isReset) {
|
||||
cms.reset()
|
||||
res.statusCode = 204
|
||||
return void res.end()
|
||||
}
|
||||
const chunks: Buffer[] = []
|
||||
for await (const c of req) chunks.push(c as Buffer)
|
||||
const body = chunks.length ? Buffer.concat(chunks) : undefined
|
||||
const resp = await cms.handle(
|
||||
new Request(new URL(url, `http://${req.headers.host ?? 'localhost'}`), { method: req.method, headers: req.headers as Record<string, string>, body: body && req.method !== 'GET' ? body : undefined }),
|
||||
)
|
||||
res.statusCode = resp.status
|
||||
resp.headers.forEach((v, k) => res.setHeader(k, v))
|
||||
let text = await resp.text()
|
||||
if (resp.headers.get('x-cms-page')) text = await server.transformIndexHtml(url, injectDevEntry(text))
|
||||
res.end(text)
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { IncomingHttpHeaders, IncomingMessage } from 'node:http'
|
||||
|
||||
/** Paths Vite itself serves (HMR client, source modules, deps). */
|
||||
export const isViteOwned = (url: string) =>
|
||||
/^\/(@|src\/|node_modules\/|__|mock\/|test\/)/.test(url)
|
||||
|
||||
/** A navigation to a page we should fetch + inject, as opposed to an asset/API call. */
|
||||
export function isPageRequest(req: IncomingMessage): boolean {
|
||||
const url = req.url ?? '/'
|
||||
if (req.method !== 'GET' || isViteOwned(url)) return false
|
||||
if (/^\/(api|editor|assets|js|css|fonts|static)(\/|$)/.test(url)) return false
|
||||
if (/\.[a-z0-9]{2,5}($|\?)/i.test(url.split('?')[0])) return false // has a file extension
|
||||
return String(req.headers.accept ?? '').includes('text/html')
|
||||
}
|
||||
|
||||
export interface Auth {
|
||||
token?: string
|
||||
apiKey?: string
|
||||
cookie?: string
|
||||
}
|
||||
|
||||
const hasPreviewCookie = (cookie?: string) => /(?:^|;\s*)cms_preview=1/.test(cookie ?? '')
|
||||
|
||||
/** Headers for an upstream request: browser cookies + configured credentials + preview flag. */
|
||||
export function upstreamHeaders(
|
||||
incoming: IncomingHttpHeaders,
|
||||
auth: Auth,
|
||||
opts: { identity?: boolean } = {},
|
||||
): Record<string, string> {
|
||||
const h: Record<string, string> = {}
|
||||
if (incoming.accept) h.accept = String(incoming.accept)
|
||||
if (incoming['accept-language']) h['accept-language'] = String(incoming['accept-language'])
|
||||
if (opts.identity) h['accept-encoding'] = 'identity'
|
||||
const cookie = [incoming.cookie, auth.cookie].filter(Boolean).join('; ')
|
||||
if (cookie) h.cookie = cookie
|
||||
// The edge routes on the cookie OR this header; send both so a proxy hop can't lose it.
|
||||
if (hasPreviewCookie(cookie)) h['x-cms-preview'] = '1'
|
||||
if (auth.token) h.authorization = `Bearer ${auth.token}`
|
||||
else if (incoming.authorization) h.authorization = String(incoming.authorization)
|
||||
if (auth.apiKey) h['x-api-key'] = auth.apiKey
|
||||
return h
|
||||
}
|
||||
|
||||
/** Put the dev entry in front of </body> (or at the end). */
|
||||
export function injectDevEntry(html: string): string {
|
||||
const tag = '<script type="module" src="/src/dev.ts"></script>'
|
||||
return /<\/body>/i.test(html) ? html.replace(/<\/body>/i, `${tag}</body>`) : html + tag
|
||||
}
|
||||
Reference in new issue
Block a user