feat(web): land Artifact serve/endpoint path and retire compose golds

Wire data_source into Document render, register Endpoint handlers via
run_artifact, restore marqdo-blog as an Artifact site, and replace old
compose_* web golds with ADR 0007 fixtures and docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-28 11:36:45 +08:00
1 parent 67bac1bf02
commit ff252fd469
86 files changed
+952 -4499

No files matched your search

+11
View File
@@ -279,6 +279,17 @@ func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any {
dec = append(dec, map[string]any{"path": key, "kind": "endpoint"})
}
}
if art, ok := app["artifact_routes"].(map[string]any); ok {
for key, v := range art {
m, _ := v.(map[string]any)
dec = append(dec, map[string]any{
"path": key,
"kind": "endpoint",
"method": fmt.Sprint(m["method"]),
"file": fmt.Sprint(m["file"]),
})
}
}
}
return map[string]any{
"declared": dec,
+3
View File
@@ -122,6 +122,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
galleryRoutes: routeMapOf(appBag, "gallery_routes"),
proxyRoutes: routeMapOf(appBag, "proxy_routes"),
invokeRoutes: routeMapOf(appBag, "invoke_routes"),
artifactRoutes: routeMapOf(appBag, "artifact_routes"),
auth: authCfg,
oidc: oidc.ParseConfig(appBag),
tenant: tenant.FromBag(appBag),
@@ -238,6 +239,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
st.mountGalleryRoutes(mux)
st.mountProxyRoutes(mux)
st.mountInvokeRoutes(mux)
st.mountArtifactRoutes(mux)
st.mountAuthRoutes(mux)
mux.HandleFunc("/{path...}", st.handleNotFound)
@@ -307,6 +309,7 @@ type state struct {
galleryRoutes map[string]any
proxyRoutes map[string]any
invokeRoutes map[string]any
artifactRoutes map[string]any
auth authConfig
oidc oidc.Config
tenant tenant.Config
@@ -0,0 +1,142 @@
package httpx
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/plugin"
"github.com/marqdo/marqdo/plugins/web/internal/session"
)
// artifactRoute is one Endpoint file registered by web.serve (ADR 0007).
type artifactRoute struct {
Method string
Path string
File string
Request string // json | form | none | query
Response string // json | text | html
Auth string // role name or "" / "none"
}
func parseArtifactRoute(v any) artifactRoute {
m, _ := v.(map[string]any)
return artifactRoute{
Method: strings.ToUpper(strOpt(m, "method", "GET")),
Path: strOpt(m, "path", ""),
File: strOpt(m, "file", ""),
Request: strings.ToLower(strOpt(m, "request", "json")),
Response: strings.ToLower(strOpt(m, "response", "json")),
Auth: strOpt(m, "auth", ""),
}
}
func (st *state) mountArtifactRoutes(mux *http.ServeMux) {
for _, key := range sortedKeys(st.artifactRoutes) {
cfg := parseArtifactRoute(st.artifactRoutes[key])
if cfg.File == "" || cfg.Path == "" {
continue
}
method := cfg.Method
if method == "" {
method = http.MethodGet
}
pattern := method + " " + goMuxPattern(cfg.Path)
routeCfg := cfg
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
if r.Method != method {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
st.handleArtifact(w, r, routeCfg)
})
}
}
func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route artifactRoute) {
if route.Auth != "" && !strings.EqualFold(route.Auth, "none") {
cookie := r.Header.Get("Cookie")
user := session.UsernameFromCookie(cookie)
if user == "" {
jsonErr(w, http.StatusUnauthorized, "auth required")
return
}
role := session.RoleFromCookie(cookie)
if role != "" && role != route.Auth && role != "admin" && role != "superadmin" {
jsonErr(w, http.StatusForbidden, "forbidden")
return
}
}
payload := map[string]any{}
switch route.Request {
case "none":
payload = queryToMap(r.URL.RawQuery)
case "query":
payload = queryToMap(r.URL.RawQuery)
case "form":
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20))
if err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err))
return
}
payload = formToMap(body)
default: // json
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20))
if err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err))
return
}
q := queryToMap(r.URL.RawQuery)
if len(body) == 0 {
payload = q
} else {
var raw map[string]any
if err := json.Unmarshal(body, &raw); err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("json: %v", err))
return
}
if raw == nil {
payload = q
} else {
for k, v := range q {
if _, exists := raw[k]; !exists {
raw[k] = v
}
}
payload = raw
}
}
}
for _, name := range pathParamNames(route.Path) {
if v := r.PathValue(name); v != "" {
payload[name] = v
}
}
value, err := plugin.RunArtifact(route.File, payload)
if err != nil {
jsonErr(w, http.StatusInternalServerError, err.Error())
return
}
switch route.Response {
case "text":
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, fmt.Sprint(value))
case "html", "text/html":
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, fmt.Sprint(value))
default:
code, body, err := jsonWrapInvokeValue(value)
if err != nil {
jsonErr(w, code, err.Error())
return
}
writeJSON(w, code, body)
}
}
+22
View File
@@ -49,3 +49,25 @@ func CallLibPath(path string, args map[string]any) (any, error) {
}
return v, nil
}
// RunArtifact loads and runs a Document/Endpoint `.mq.md` (ADR 0007).
// Request fields are passed as Metadata Binding overlays (`arg` / `--bind`).
func RunArtifact(path string, args map[string]any) (any, error) {
payload := map[string]any{"path": path}
if len(args) > 0 {
payload["args"] = args
}
raw, err := json.Marshal(payload)
if err != nil {
return nil, err
}
out, err := Query("run_artifact", string(raw))
if err != nil {
return nil, err
}
var v any
if err := json.Unmarshal([]byte(out), &v); err != nil {
return nil, err
}
return v, nil
}
@@ -0,0 +1,88 @@
package render
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/db"
)
func TestResolveMainDataSource(t *testing.T) {
dir := t.TempDir()
url := "sqlite:" + filepath.Join(dir, "t.db")
fields := []any{
map[string]any{"字段": "title", "类型": "text", "可空": false},
map[string]any{"字段": "slug", "类型": "text", "可空": false},
map[string]any{"字段": "summary", "类型": "text", "可空": true},
map[string]any{"字段": "content", "类型": "text", "可空": true},
}
if _, err := db.Init(url, "posts", fields); err != nil {
t.Fatal(err)
}
rows := []any{
map[string]any{
"title": "Hello", "slug": "hello",
"summary": "sum", "content": "# Body",
},
}
if _, err := db.Insert(url, "posts", rows); err != nil {
t.Fatal(err)
}
page := map[string]any{
"intro": "<p>hi</p>",
"data_source": "posts",
"order": "-id",
"link_prefix": "/post/",
}
intro, items, _ := resolveMain(page, url)
if intro != "<p>hi</p>" {
t.Fatalf("intro=%q", intro)
}
if len(items) != 1 {
t.Fatalf("items=%d", len(items))
}
if items[0]["title"] != "Hello" || items[0]["href"] != "hello" {
t.Fatalf("item=%v", items[0])
}
html := RenderPage(page, url, "")
if !strings.Contains(html, `class="card"`) || !strings.Contains(html, "Hello") {
t.Fatalf("html missing card: %s", html[:min(400, len(html))])
}
_ = os.RemoveAll(dir)
}
func TestResolveMainDataWhereDetail(t *testing.T) {
dir := t.TempDir()
url := "sqlite:" + filepath.Join(dir, "t.db")
fields := []any{
map[string]any{"字段": "title", "类型": "text", "可空": false},
map[string]any{"字段": "slug", "类型": "text", "可空": false},
map[string]any{"字段": "content", "类型": "text", "可空": true},
}
if _, err := db.Init(url, "posts", fields); err != nil {
t.Fatal(err)
}
rows := []any{
map[string]any{"title": "A", "slug": "a", "content": "alpha"},
map[string]any{"title": "B", "slug": "b", "content": "beta"},
}
if _, err := db.Insert(url, "posts", rows); err != nil {
t.Fatal(err)
}
page := map[string]any{
"data_source": "posts",
"query": map[string]any{"slug": "{slug}"},
"params": map[string]any{"slug": "b"},
"detail": true,
}
_, items, _ := resolveMain(page, url)
if len(items) != 1 || items[0]["title"] != "B" {
t.Fatalf("items=%v", items)
}
html := RenderPage(page, url, "")
if !strings.Contains(html, "article-title") || !strings.Contains(html, "B") {
t.Fatalf("detail html: %s", html[:min(500, len(html))])
}
}
+73 -21
View File
@@ -420,22 +420,6 @@ func renderULWithMQ(links []navLink, class string, mqPairs [][2]string) string {
func resolveMain(page map[string]any, dbURL string) (intro string, items []map[string]any, total *int64) {
intro, _ = page["intro"].(string)
main, ok := page["main"]
if !ok {
return intro, nil, nil
}
bindsAny := table.AsBind(main)
arr, _ := bindsAny.([]any)
if len(arr) == 0 {
return intro, nil, nil
}
if dbURL == "" {
return intro, nil, nil
}
tn, ok := table.BindTableName(arr)
if !ok {
return intro, nil, nil
}
limit := int64(200)
offset := int64(0)
if p, ok := page["paginate"].(map[string]any); ok {
@@ -446,22 +430,90 @@ func resolveMain(page map[string]any, dbURL string) (intro string, items []map[s
offset = int64(v)
}
}
data := selectPageData(dbURL, tn, page, limit, offset)
// Legacy compose_main bind table (internal); prefer when present.
if main, ok := page["main"]; ok {
bindsAny := table.AsBind(main)
arr, _ := bindsAny.([]any)
if len(arr) > 0 && dbURL != "" {
if tn, ok := table.BindTableName(arr); ok {
data := selectPageData(dbURL, tn, page, limit, offset)
if t, ok := data["total"].(float64); ok {
ti := int64(t)
total = &ti
}
rawRows, _ := data["rows"].([]any)
projected := table.ProjectRows(arr, rawRows)
parr, _ := projected.([]any)
for _, v := range parr {
if m, ok := v.(map[string]any); ok {
items = append(items, m)
}
}
return intro, items, total
}
}
}
// Artifact Document: flat data_source / data_order / data_where (ADR 0007).
src, _ := page["data_source"].(string)
if src == "" || dbURL == "" {
return intro, nil, nil
}
data := selectPageData(dbURL, src, page, limit, offset)
if t, ok := data["total"].(float64); ok {
ti := int64(t)
total = &ti
}
rawRows, _ := data["rows"].([]any)
projected := table.ProjectRows(arr, rawRows)
parr, _ := projected.([]any)
for _, v := range parr {
if m, ok := v.(map[string]any); ok {
for _, v := range rawRows {
if m := projectArtifactRow(v); m != nil {
items = append(items, m)
}
}
return intro, items, total
}
// projectArtifactRow maps a DB row to card/article fields without compose binds.
func projectArtifactRow(row any) map[string]any {
obj, ok := row.(map[string]any)
if !ok || obj == nil {
return nil
}
m := map[string]any{}
if id, ok := obj["id"]; ok {
m["id"] = id
}
if t := text(obj["title"]); t != "" {
m["title"] = t
}
if s := text(obj["slug"]); s != "" {
m["href"] = s
} else if h := text(obj["href"]); h != "" {
m["href"] = h
}
// Detail pages prefer full content; list cards prefer summary.
if c := text(obj["content"]); c != "" {
m["body"] = c
} else if s := text(obj["summary"]); s != "" {
m["body"] = s
} else if b := text(obj["body"]); b != "" {
m["body"] = b
}
if tag := text(obj["tag"]); tag != "" {
m["tag"] = tag
}
if meta := text(obj["created_at"]); meta != "" {
m["meta"] = meta
} else if meta := text(obj["meta"]); meta != "" {
m["meta"] = meta
}
if len(m) == 0 {
return nil
}
return m
}
// listBind is one secondary page list (compose_list / 列表装配).
type listBind struct {
Items []map[string]any