Release 2.7.0: executable handbooks and native user-site workflows

This commit is contained in:
cflmy committed 2026-11-10 17:03:06 +08:00
1 parent aa0c4d0f55
commit d9aef957f7
562 files changed
+21064 -20387

No files matched your search

+339 -74
View File
@@ -2,10 +2,12 @@
package artifact
import (
"encoding/json"
"fmt"
"html"
"os"
"path/filepath"
"sort"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/render"
@@ -94,9 +96,17 @@ func ParseFrontmatter(src string) (meta map[string]string, body string) {
// RenderNodes renders the existing five-column View schema recursively. Container
// value cells hold more View rows; markdown leaves hold ordinary Markdown text.
func RenderNodes(nodes any) (string, error) {
return RenderNodesWithResources(nodes, nil)
}
// ResourceRenderer resolves a typed Resource at the request boundary.
// Ordinary View construction remains pure; a nil renderer never starts IO.
type ResourceRenderer func(map[string]any) (string, error)
func RenderNodesWithResources(nodes any, resources ResourceRenderer) (string, error) {
var b strings.Builder
b.WriteString(`<style>` + LayoutCSS + `</style><div class="mq-view">`)
if err := renderNodes(&b, nodes, 0); err != nil {
if err := renderNodes(&b, nodes, 0, resources); err != nil {
return "", err
}
b.WriteString(`</div>`)
@@ -105,7 +115,7 @@ func RenderNodes(nodes any) (string, error) {
// Fixed runtime geometry, shared by offline previews and served Documents.
// Authors choose row/column instead of embedding CSS or HTML in content cells.
const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}`
const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0;overflow-wrap:anywhere}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}.mq-view input,.mq-view textarea,.mq-view select{max-width:100%;font:inherit}.mq-view textarea{width:100%}`
// Preserve typed value cells when normalizing column tables. General AsRows
// treats @ cells as text, which would stringify nested component tables.
@@ -148,7 +158,85 @@ func viewRows(nodes any) ([]any, error) {
}
}
func renderNodes(b *strings.Builder, nodes any, depth int) error {
func containerTag(kind string) (string, string) {
switch kind {
case "row", "横排":
return "div", " mq-row"
case "column", "纵排":
return "div", " mq-column"
case "nav", "导航":
return "nav", ""
case "header", "页头":
return "header", ""
case "footer", "页脚":
return "footer", ""
case "section", "区域":
return "section", ""
case "aside", "侧栏":
return "aside", ""
case "form", "表单":
return "form", ""
case "list", "列表":
return "ul", ""
case "item", "列表项":
return "li", ""
case "select", "选择":
return "select", ""
}
return "", ""
}
// FindSlot selects one declared View region without resolving any Resources.
// Container traversal is identical to rendering and never descends into a
// Resource's private map as if it were another View table.
func FindSlot(nodes any, slot string) (any, bool, error) {
var selected []any
var walk func(any, int) error
walk = func(nodes any, depth int) error {
if depth > 64 {
return fmt.Errorf("View: nesting exceeds 64 levels")
}
rows, err := viewRows(nodes)
if err != nil {
return err
}
for _, value := range rows {
row, ok := value.(map[string]any)
if !ok {
return fmt.Errorf("View slot: expected a row map")
}
if first(row, "slot", "槽") == slot {
selected = append(selected, row)
}
kind := strings.ToLower(first(row, "type", "类型"))
if tag, _ := containerTag(kind); tag != "" {
children := row["value"]
if children == nil {
children = row["值"]
}
if children == nil {
return fmt.Errorf("View %s: missing child rows", kind)
}
if err := walk(children, depth+1); err != nil {
return err
}
}
}
return nil
}
if err := walk(nodes, 0); err != nil {
return nil, false, err
}
if len(selected) > 1 {
return nil, false, fmt.Errorf("View slot %q is ambiguous", slot)
}
if len(selected) == 0 {
return nil, false, nil
}
return selected, true, nil
}
func renderNodes(b *strings.Builder, nodes any, depth int, resources ResourceRenderer) error {
if depth > 64 {
return fmt.Errorf("View: nesting exceeds 64 levels")
}
@@ -165,6 +253,10 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
slot := first(row, "slot", "槽")
val := first(row, "value", "值")
attrs := first(row, "attrs", "属性")
attributes, err := renderAttributes(row)
if err != nil {
return fmt.Errorf("View row %d: %w", i+1, err)
}
style := first(row, "style", "样式")
class := "mq-node"
if style != "" {
@@ -173,25 +265,8 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
if slot != "" {
class += " slot-" + html.EscapeString(slot)
}
tag := ""
switch ty {
case "row", "横排":
tag = "div"
class += " mq-row"
case "column", "纵排":
tag = "div"
class += " mq-column"
case "nav", "导航":
tag = "nav"
case "header", "页头":
tag = "header"
case "footer", "页脚":
tag = "footer"
case "section", "区域":
tag = "section"
case "aside", "侧栏":
tag = "aside"
}
tag, geometry := containerTag(ty)
class += geometry
if tag != "" {
children := row["value"]
if children == nil {
@@ -200,23 +275,72 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
if children == nil {
return fmt.Errorf("View row %d (%s): missing child rows in value", i+1, ty)
}
b.WriteString(`<` + tag + ` class="` + class + `">`)
if err := renderNodes(b, children, depth+1); err != nil {
b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>`)
if err := renderNodes(b, children, depth+1, resources); err != nil {
return fmt.Errorf("View %s/%s: %w", ty, slot, err)
}
b.WriteString(`</` + tag + `>`)
continue
}
switch ty {
case "resource", "资源":
value := row["value"]
if value == nil {
value = row["值"]
}
resource, ok := value.(map[string]any)
if !ok || first(resource, "_type") == "" {
return fmt.Errorf("View row %d: resource value must be a typed Resource", i+1)
}
if first(resource, "_type") == "document_head" {
if _, err := ParseDocumentHead(resource); err != nil {
return err
}
continue
}
if resources == nil {
return fmt.Errorf("View row %d: resource requires an explicit request renderer", i+1)
}
fragment, err := resources(resource)
if err != nil {
return fmt.Errorf("View resource %s: %w", slot, err)
}
b.WriteString(`<section class="` + class + `"` + attributes + `>` + fragment + `</section>`)
case "markdown", "正文":
b.WriteString(`<div class="` + class + `">` + render.MarkdownToHTML(val) + `</div>`)
b.WriteString(`<div class="` + class + `"` + attributes + `>` + render.MarkdownToHTML(val) + `</div>`)
case "title", "标题":
b.WriteString(`<h1 class="` + class + `">` + inline(val) + `</h1>`)
b.WriteString(`<h1 class="` + class + `"` + attributes + `>` + inline(val) + `</h1>`)
case "link", "链接":
if attrs == "" {
attrs = "#"
if !hasAttributeMap(row) {
if attrs == "" {
attrs = "#"
}
attributes = ` href="` + html.EscapeString(attrs) + `"`
}
b.WriteString(`<a class="` + class + `"` + attributes + `>` + inline(val) + `</a>`)
case "input", "输入":
b.WriteString(`<input class="` + class + `"` + attributes + ` value="` + html.EscapeString(val) + `">`)
case "button", "按钮", "textarea", "多行输入", "label", "标签", "pre", "预格式", "option", "选项":
tags := map[string]string{"button": "button", "按钮": "button", "textarea": "textarea", "多行输入": "textarea", "label": "label", "标签": "label", "pre": "pre", "预格式": "pre", "option": "option", "选项": "option"}
tag := tags[ty]
b.WriteString(`<` + tag + ` class="` + class + `"` + attributes + `>` + html.EscapeString(val) + `</` + tag + `>`)
case "script", "脚本", "stylesheet", "样式表":
url := strings.ToLower(strings.TrimSpace(val))
if url == "" || strings.ContainsAny(url, "\r\n\t") || strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") {
return fmt.Errorf("View row %d: resource requires a nonempty non-script URL", i+1)
}
if attrs, ok := attributeValue(row).(map[string]any); ok {
for _, reserved := range []string{"href", "src", "rel"} {
if _, exists := attrs[reserved]; exists {
return fmt.Errorf("View row %d: resource URL and relation belong to its kind/value, not attrs.%s", i+1, reserved)
}
}
}
if ty == "script" || ty == "脚本" {
b.WriteString(`<script src="` + html.EscapeString(val) + `"` + attributes + `></script>`)
} else {
b.WriteString(`<link rel="stylesheet" href="` + html.EscapeString(val) + `"` + attributes + `>`)
}
b.WriteString(`<a class="` + class + `" href="` + html.EscapeString(attrs) + `">` + inline(val) + `</a>`)
case "html", "原文":
b.WriteString(`<div class="` + class + `">` + val + `</div>`)
default:
@@ -228,31 +352,137 @@ func renderNodes(b *strings.Builder, nodes any, depth int) error {
case []any, map[string]any:
return fmt.Errorf("View row %d: unknown structural type %q", i+1, ty)
}
b.WriteString(`<p class="` + class + `">` + inline(val) + `</p>`)
b.WriteString(`<p class="` + class + `"` + attributes + `>` + inline(val) + `</p>`)
}
}
return nil
}
// Attribute records keep controls in the same five-column View schema.
// Legacy link rows may still carry a plain href string. Names and scalar values
// are checked before emission; handlers and inline style remain explicit escapes.
func attributeValue(row map[string]any) any {
if value, ok := row["attrs"]; ok && value != nil {
return value
}
return row["属性"]
}
func hasAttributeMap(row map[string]any) bool {
_, ok := attributeValue(row).(map[string]any)
return ok
}
func renderAttributes(row map[string]any) (string, error) {
value := attributeValue(row)
if value == nil || value == "" {
return "", nil
}
attrs, ok := value.(map[string]any)
if !ok {
if _, legacy := value.(string); legacy {
return "", nil
}
return "", fmt.Errorf("attrs must be a scalar attribute record or legacy link URL")
}
allowed := map[string]bool{
"id": true, "title": true, "role": true, "name": true, "type": true,
"href": true, "src": true, "action": true, "method": true, "enctype": true,
"placeholder": true, "for": true, "rows": true, "cols": true, "size": true,
"min": true, "max": true, "step": true, "minlength": true, "maxlength": true,
"pattern": true, "autocomplete": true, "target": true, "rel": true,
"tabindex": true, "download": true, "accept": true, "alt": true,
"integrity": true, "crossorigin": true, "media": true, "referrerpolicy": true,
}
booleans := map[string]bool{"hidden": true, "disabled": true, "required": true, "readonly": true, "checked": true, "selected": true, "multiple": true, "autofocus": true, "async": true, "defer": true, "nomodule": true}
keys := make([]string, 0, len(attrs))
for name := range attrs {
keys = append(keys, name)
}
sort.Strings(keys)
var out strings.Builder
for _, name := range keys {
if !(allowed[name] || booleans[name] || validCustomAttribute(name)) {
return "", fmt.Errorf("unsupported attribute %q; use attrs data/aria keys for client state", name)
}
v := attrs[name]
if v == nil {
continue
}
if booleans[name] {
flag, ok := v.(bool)
if !ok {
return "", fmt.Errorf("attribute %s requires a boolean", name)
}
if flag {
out.WriteString(" " + name)
}
continue
}
switch v.(type) {
case string, bool, float64, int, int64, json.Number:
default:
return "", fmt.Errorf("attribute %s requires a scalar value", name)
}
text := fmt.Sprint(v)
if name == "href" || name == "src" || name == "action" {
url := strings.ToLower(strings.TrimSpace(text))
if strings.HasPrefix(url, "javascript:") || strings.HasPrefix(url, "vbscript:") {
return "", fmt.Errorf("attribute %s cannot execute a script URL", name)
}
}
out.WriteString(" " + name + `="` + html.EscapeString(text) + `"`)
}
return out.String(), nil
}
func validCustomAttribute(name string) bool {
if !(strings.HasPrefix(name, "data-") || strings.HasPrefix(name, "aria-")) {
return false
}
if strings.HasSuffix(name, "-") {
return false
}
for _, char := range name {
if !(char >= 'a' && char <= 'z' || char >= '0' && char <= '9' || char == '-' || char == '_') {
return false
}
}
return true
}
// RenderFile explicitly opts a Document into startup-time component assembly.
// Documents without view: main retain their existing Markdown/data-source path.
func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) {
// AssembleView runs the existing startup entry once and retains typed rows.
// Request resources are deliberately not resolved during assembly.
func AssembleView(f ArtifactFile, run func(string, map[string]any) (any, error)) (any, bool, error) {
view := metaString(f.Meta, "view", "视图")
if view == "" {
return MarkdownHTML(f.Body), false, nil
return nil, false, nil
}
if view != "main" {
return "", false, fmt.Errorf("%s: view/视图 must be main", f.Rel)
return nil, false, fmt.Errorf("%s: view/视图 must be main", f.Rel)
}
if metaString(f.Meta, "data_source", "数据源") != "" {
return "", false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel)
return nil, false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel)
}
nodes, err := run(f.Path, nil)
if err != nil {
return "", false, fmt.Errorf("%s: view main: %w", f.Rel, err)
return nil, false, fmt.Errorf("%s: view main: %w", f.Rel, err)
}
if nodes == nil {
return "", false, fmt.Errorf("%s: view main must return View rows", f.Rel)
return nil, false, fmt.Errorf("%s: view main must return View rows", f.Rel)
}
return nodes, true, nil
}
func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) {
nodes, structured, err := AssembleView(f, run)
if err != nil {
return "", false, err
}
if !structured {
return MarkdownHTML(f.Body), false, nil
}
html, err := RenderNodes(nodes)
if err != nil {
@@ -285,8 +515,12 @@ func RenderHTMLPage(title, innerHTML string) string {
if t == "" {
t = "Marqdo"
}
return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>" + t +
"</title></head><body class=\"mq-document\"><main>" + innerHTML + "</main></body></html>"
return renderHTMLPageWithHead("<title>"+t+"</title>", innerHTML)
}
func renderHTMLPageWithHead(head, innerHTML string) string {
return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" + head +
"</head><body class=\"mq-document\"><main>" + innerHTML + "</main></body></html>"
}
// MarkdownHTML exposes render helper.
@@ -385,6 +619,7 @@ func SystemRoutes() []map[string]any {
return []map[string]any{
{"method": "GET", "path": "/_part/*", "kind": "system"},
{"method": "GET|POST", "path": "/_form/*", "kind": "system"},
{"method": "POST", "path": "/_md", "kind": "system"},
{"method": "POST", "path": "/_runtime/tasks", "kind": "system"},
{"method": "GET", "path": "/_runtime/tasks/{id}", "kind": "system"},
{"method": "POST", "path": "/_runtime/tasks/{id}/cancel", "kind": "system"},
@@ -392,55 +627,85 @@ func SystemRoutes() []map[string]any {
}
}
// InspectBag builds {declared, system} from an app bag and/or scanned files.
// InspectBag reads declarations only. A prepared app's actual handler inventory
// is generated by httpx.InspectApp through the same registrar as NewHandler.
func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any {
var dec []map[string]any
for _, a := range declared {
dec = append(dec, map[string]any{
"method": a.Method,
"path": a.Route,
"kind": a.Kind,
"file": a.Rel,
})
entries := map[string]map[string]any{}
add := func(row map[string]any) {
path := first(row, "path")
method := first(row, "method")
if method == "" {
method = "GET"
}
if path == "" {
return
}
key := method + " " + path
if _, exists := entries[key]; !exists {
entries[key] = row
}
}
for _, file := range declared {
add(map[string]any{"method": file.Method, "path": file.Route, "kind": file.Kind, "file": file.Rel})
}
if app != nil {
switch rows := app["artifact_declared"].(type) {
case []map[string]any:
for _, row := range rows {
add(row)
}
case []any:
for _, value := range rows {
if row, ok := value.(map[string]any); ok {
add(row)
}
}
}
if app["page"] != nil {
add(map[string]any{"method": "GET", "path": "/", "kind": "document"})
}
if routes, ok := app["routes"].(map[string]any); ok {
for path := range routes {
dec = append(dec, map[string]any{"method": "GET", "path": path, "kind": "declared"})
add(map[string]any{"method": "GET", "path": path, "kind": "document"})
}
}
if inv, ok := app["invoke_routes"].(map[string]any); ok {
for key, v := range inv {
row := map[string]any{"path": key, "kind": "endpoint"}
if m, ok := v.(map[string]any); ok {
if c, ok := m["class"].(string); ok && c != "" {
row["class"] = c
for _, group := range []string{"artifact_routes", "invoke_routes"} {
if routes, ok := app[group].(map[string]any); ok {
for key, value := range routes {
spec, _ := value.(map[string]any)
method, path := first(spec, "method"), first(spec, "path")
if parts := strings.SplitN(key, " ", 2); len(parts) == 2 {
if method == "" {
method = parts[0]
}
if path == "" {
path = parts[1]
}
} else if path == "" {
path = key
}
if method, ok := m["method"].(string); ok && method != "" {
row["method"] = method
if method == "" {
method = "GET"
}
if fn, ok := m["fn"].(string); ok && fn != "" {
row["fn"] = fn
row := map[string]any{"method": method, "path": path, "kind": "endpoint"}
for _, name := range []string{"file", "class", "fn"} {
if value := first(spec, name); value != "" {
row[name] = value
}
}
add(row)
}
dec = append(dec, row)
}
}
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{
"_type": "web_inspection",
"declared": dec,
"system": SystemRoutes(),
keys := make([]string, 0, len(entries))
for key := range entries {
keys = append(keys, key)
}
sort.Strings(keys)
rows := make([]map[string]any, 0, len(keys))
for _, key := range keys {
rows = append(rows, entries[key])
}
return map[string]any{"_type": "web_inspection", "scope": "metadata", "declared": rows, "system": SystemRoutes()}
}
@@ -142,3 +142,48 @@ func TestViewDocumentRejectsAnEmptyAssemblyAndAutomaticDataSource(t *testing.T)
t.Fatalf("data source silently ignored: %v", err)
}
}
func TestInteractiveControlsUseTypedAttributesAndEscapedText(t *testing.T) {
nodes := []any{map[string]any{"type":"form", "attrs":map[string]any{"id":"editor", "method":"post", "action":"/save"}, "value":[]any{
map[string]any{"type":"label", "value":"Title", "attrs":map[string]any{"for":"title"}},
map[string]any{"type":"input", "value":`"><script>alert(1)</script>`, "attrs":map[string]any{"id":"title", "name":"title", "required":true, "disabled":false, "maxlength":float64(120)}},
map[string]any{"type":"textarea", "value":"</textarea><script>x</script>", "attrs":map[string]any{"id":"doc", "rows":float64(16), "aria-label":"Document"}},
map[string]any{"type":"button", "value":"Save & return", "attrs":map[string]any{"type":"submit", "data-action":"save"}},
map[string]any{"类型":"预格式", "值":"<waiting>", "属性":map[string]any{"id":"log","hidden":false}},
}}}
got,err := RenderNodes(nodes)
if err != nil { t.Fatal(err) }
for _, expected := range []string{`<form`,`action="/save"`,`for="title"`,`maxlength="120"`,` required`,`rows="16"`,`aria-label="Document"`,`data-action="save"`,`Save &amp; return`,`&lt;/textarea&gt;`,`&lt;waiting&gt;`} {
if !strings.Contains(got,expected) { t.Fatalf("missing %s: %s",expected,got) }
}
if strings.Contains(got,"<script>") || strings.Contains(got," disabled") || strings.Contains(got," hidden") || strings.Contains(got,"map[") { t.Fatalf("control values leaked into markup: %s",got) }
}
func TestAttributeRecordsApplyToContainersAndLinks(t *testing.T) {
got,err:=RenderNodes([]any{map[string]any{"type":"section","attrs":map[string]any{"id":"view-detail","hidden":true},"value":[]any{
map[string]any{"type":"link","value":"Open","attrs":map[string]any{"href":"/a?x=1&y=2","title":"Detail"}},
}}})
if err != nil || !strings.Contains(got,`id="view-detail"`) || !strings.Contains(got," hidden") || !strings.Contains(got,`href="/a?x=1&amp;y=2"`) { t.Fatalf("%v: %s",err,got) }
for _,attrs:=range []map[string]any{
{"onclick":"alert(1)"},{"style":"position:fixed"},{"data-x\" onload":"x"},{"href":"javascript:alert(1)"},{"required":"true"},{"title":[]any{"nested"}},
} {
if _,err:=RenderNodes([]any{map[string]any{"type":"button","value":"Run","attrs":attrs}});err==nil { t.Fatalf("accepted invalid attributes: %v",attrs) }
}
}
func TestResourcesStayStructuredAndEscapeTheirURLs(t *testing.T) {
got,err:=RenderNodes([]any{
map[string]any{"type":"script","value":"/static/marqdo-bridge.js","attrs":map[string]any{"type":"module","data-mq-wasm":"/static/runtime.wasm","data-mq-source-url":"/static/client.mq.md"}},
map[string]any{"type":"stylesheet","value":"/static/theme.css?x=1&y=2"},
})
if err!=nil {t.Fatal(err)}
for _,want:=range []string{`<script src="/static/marqdo-bridge.js"`,`type="module"`,`data-mq-source-url="/static/client.mq.md"`,`<link rel="stylesheet" href="/static/theme.css?x=1&amp;y=2"`} {
if !strings.Contains(got,want) {t.Fatalf("missing %s: %s",want,got)}
}
for _,node:=range []map[string]any{
{"type":"script","value":"javascript:alert(1)"},
{"type":"script","value":"/static/a.js","attrs":map[string]any{"src":"/other.js"}},
{"type":"stylesheet","value":"/theme.css","attrs":map[string]any{"rel":"preload"}},
} {
if _,err:=RenderNodes([]any{node});err==nil {t.Fatalf("accepted invalid resource: %v",node)}
}
}
+245
View File
@@ -0,0 +1,245 @@
package artifact
import (
"fmt"
"net/url"
"reflect"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/assets"
"github.com/marqdo/marqdo/plugins/web/internal/render"
"github.com/marqdo/marqdo/plugins/web/internal/table"
)
// DocumentHead is a closed, pure View Resource. It contributes only metadata
// and existing native head links; it cannot mutate page layout or server state.
type DocumentHead struct {
Meta map[string]any
Links []assets.HeadLink
}
func headRows(value any) ([]map[string]any, error) {
if value == nil {
return nil, nil
}
switch data := value.(type) {
case []any:
rows := make([]map[string]any, 0, len(data))
for _, value := range data {
row, ok := value.(map[string]any)
if !ok {
return nil, fmt.Errorf("document_head: expected table records")
}
rows = append(rows, row)
}
return rows, nil
case map[string]any:
if len(data) == 0 {
return nil, nil
}
arrays, scalars, count := 0, 0, -1
for _, value := range data {
if column, ok := value.([]any); ok {
arrays++
if count >= 0 && count != len(column) {
return nil, fmt.Errorf("document_head: column lengths differ")
}
count = len(column)
} else {
scalars++
}
}
if arrays > 0 && scalars > 0 {
return nil, fmt.Errorf("document_head: mixed column and scalar cells")
}
if arrays > 0 && count == 0 {
return nil, nil
}
rows, _ := table.AsRows(data).([]any)
return headRows(rows)
default:
return nil, fmt.Errorf("document_head: expected a table or None")
}
}
func headURL(raw string) error {
if raw == "" || strings.ContainsAny(raw, "\r\n\t") || raw != strings.TrimSpace(raw) ||
strings.Contains(raw, "\\") || strings.HasPrefix(raw, "//") {
return fmt.Errorf("document_head: resource URL must be site-relative or http(s)")
}
parsed, err := url.Parse(raw)
if err != nil || parsed == nil {
return fmt.Errorf("document_head: invalid resource URL")
}
if parsed.Scheme == "" {
if !strings.HasPrefix(raw, "/") {
return fmt.Errorf("document_head: relative URL must start with /")
}
} else if (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
return fmt.Errorf("document_head: resource URL must be site-relative or http(s)")
}
return nil
}
// ParseDocumentHead validates before either preview or listening. No URL is
// fetched and no script is executed by this native projection.
func ParseDocumentHead(resource map[string]any) (DocumentHead, error) {
out := DocumentHead{Meta: map[string]any{}}
if first(resource, "_type") != "document_head" {
return out, fmt.Errorf("document_head: incorrect resource type")
}
for key := range resource {
if key != "_type" && key != "meta" && key != "links" {
return out, fmt.Errorf("document_head: unsupported field %q", key)
}
}
rows, err := headRows(resource["meta"])
if err != nil {
return out, err
}
for _, row := range rows {
for key, value := range row {
if key != "key" && key != "键" && key != "name" && key != "value" && key != "值" && key != "@" && key != "行" && key != "row" && key != "id" {
return out, fmt.Errorf("document_head: unsupported metadata field %q", key)
}
switch value.(type) {
case nil, string, bool, float64:
default:
return out, fmt.Errorf("document_head: metadata cells must be scalar values")
}
}
key := first(row, "键", "key", "name")
value := first(row, "值", "value")
if key == "" {
return out, fmt.Errorf("document_head: metadata requires key/value rows")
}
if strings.EqualFold(key, "charset") || strings.EqualFold(key, "viewport") || strings.EqualFold(key, "csrf-token") {
return out, fmt.Errorf("document_head: %s is owned by the document runtime", key)
}
if key == "canonical" || key == "icon" || key == "favicon" {
if err := headURL(value); err != nil {
return out, err
}
}
if existing, ok := out.Meta[key]; ok && existing != value {
return out, fmt.Errorf("document_head: conflicting metadata %q", key)
}
out.Meta[key] = value
}
rows, err = headRows(resource["links"])
if err != nil {
return out, err
}
// Use the same link field aliases and native rendering as ordinary Documents.
for _, row := range rows {
for key, value := range row {
switch value.(type) {
case nil, string, bool, float64:
default:
return out, fmt.Errorf("document_head: link cells must be scalar values")
}
if value == nil {
continue
}
switch key {
case "关系", "rel", "Rel", "地址", "href", "src", "url", "Href", "Src", "URL",
"类型", "type", "Type", "尺寸", "sizes", "Sizes", "媒体", "media", "Media",
"作为", "as", "As", "跨域", "crossorigin", "crossOrigin",
"推迟", "defer", "Defer", "异步", "async", "Async", "版本", "version", "Version", "v", "@", "行", "row", "id":
default:
return out, fmt.Errorf("document_head: unsupported link field %q", key)
}
}
if err := headURL(first(row, "地址", "href", "src", "url", "Href", "Src", "URL")); err != nil {
return out, err
}
links := assets.AsHeadLinks([]any{row})
if len(links) != 1 {
return out, fmt.Errorf("document_head: each link requires href")
}
if err := headURL(links[0].Href); err != nil {
return out, err
}
out.Links = append(out.Links, links[0])
}
return out, nil
}
// CollectDocumentHead traverses only real View containers. Resource private
// records are never interpreted as nodes, and conflicting declarations fail.
func CollectDocumentHead(nodes any) (DocumentHead, error) {
out := DocumentHead{Meta: map[string]any{}}
var walk func(any, int) error
walk = func(nodes any, depth int) error {
if depth > 64 {
return fmt.Errorf("View: nesting exceeds 64 levels")
}
rows, err := viewRows(nodes)
if err != nil {
return err
}
for _, value := range rows {
row, ok := value.(map[string]any)
if !ok {
return fmt.Errorf("View: expected row map")
}
kind := strings.ToLower(first(row, "type", "类型"))
child := row["value"]
if child == nil {
child = row["值"]
}
if tag, _ := containerTag(kind); tag != "" {
if child == nil {
return fmt.Errorf("View %s: missing child rows", kind)
}
if err := walk(child, depth+1); err != nil {
return err
}
} else if kind == "resource" || kind == "资源" {
resource, ok := child.(map[string]any)
if !ok || first(resource, "_type") != "document_head" {
continue
}
head, err := ParseDocumentHead(resource)
if err != nil {
return err
}
for key, value := range head.Meta {
if existing, ok := out.Meta[key]; ok && existing != value {
return fmt.Errorf("document_head: conflicting metadata %q", key)
}
out.Meta[key] = value
}
for _, link := range head.Links {
duplicate := false
for _, existing := range out.Links {
if reflect.DeepEqual(existing, link) {
duplicate = true
break
}
}
if !duplicate {
out.Links = append(out.Links, link)
}
}
}
}
return nil
}
err := walk(nodes, 0)
return out, err
}
// RenderViewDocument shares a single pure shell for offline and request-time
// nodes. Metadata never becomes visible content or a fragment response.
func RenderViewDocument(title string, nodes any, resources ResourceRenderer) (string, error) {
head, err := CollectDocumentHead(nodes)
if err != nil {
return "", err
}
body, err := RenderNodesWithResources(nodes, resources)
if err != nil {
return "", err
}
return renderHTMLPageWithHead(render.DocumentHead(title, head.Meta, head.Links), body), nil
}
+104
View File
@@ -0,0 +1,104 @@
package artifact
import (
"strings"
"testing"
)
func headNode(meta, links any) any {
return map[string]any{"type": "resource", "slot": "head", "value": map[string]any{"_type": "document_head", "meta": meta, "links": links}}
}
func TestDocumentHeadPreservesMetadataAndLinksInTheActualHeadOnly(t *testing.T) {
meta := map[string]any{"key": []any{"description", "og:title", "canonical"}, "value": []any{`Text <tag> "quote" & literal`, "Actual OG", "/articles"}}
links := []any{
map[string]any{"关系": "preconnect", "地址": "https://fonts.example.test", "跨域": "anonymous"},
map[string]any{"rel": "stylesheet", "href": "/theme.css?x=1&y=2"},
map[string]any{"rel": "module", "href": "/client.js", "defer": false},
}
// Repeated imports should deduplicate equal links, including boolean flags.
nodes := []any{map[string]any{"type": "column", "value": []any{
headNode(meta, links), headNode(nil, links),
map[string]any{"type": "markdown", "value": "# Actual page"},
}}}
got, err := RenderViewDocument("Actual document", nodes, nil)
if err != nil {
t.Fatal(err)
}
head, body, ok := strings.Cut(got, "</head>")
if !ok {
t.Fatal(got)
}
for _, want := range []string{
"<title>Actual document</title>", `<meta name="description" content="Text &lt;tag&gt; &quot;quote&quot; &amp; literal"`,
`<meta property="og:title" content="Actual OG"`, `<link rel="canonical" href="/articles"`,
`<link rel="preconnect" href="https://fonts.example.test" crossorigin="anonymous"`,
`<link rel="stylesheet" href="/theme.css?x=1&amp;y=2"`, `<script type="module" src="/client.js"></script>`,
} {
if !strings.Contains(head, want) {
t.Fatalf("missing %s: %s", want, head)
}
}
if strings.Count(head, `href="/theme.css`) != 1 || strings.Count(head, `src="/client.js"`) != 1 {
t.Fatal("duplicate head resource: " + head)
}
if strings.Contains(body, "Actual OG") || strings.Contains(body, "fonts.example") || strings.Contains(body, "slot-head") || !strings.Contains(body, "Actual page") {
t.Fatal(body)
}
calls := 0
fragment, err := RenderNodesWithResources(nodes, func(map[string]any) (string, error) { calls++; return "unexpected", nil })
if err != nil || calls != 0 || strings.Contains(fragment, "<meta") || strings.Contains(fragment, "fonts.example") {
t.Fatalf("%d %v %s", calls, err, fragment)
}
}
func TestDocumentHeadRejectsConflictsMalformedTablesAndOpaqueMutation(t *testing.T) {
valid := map[string]any{"_type": "document_head", "meta": nil, "links": nil}
for _, resource := range []map[string]any{
{"_type": "other"},
{"_type": "document_head", "html": "<script>x</script>"},
{"_type": "document_head", "body_class": "admin"},
{"_type": "document_head", "meta": []any{42}},
{"_type": "document_head", "meta": map[string]any{"key": []any{"a", "b"}, "value": []any{"one"}}},
{"_type": "document_head", "meta": map[string]any{"key": "description", "value": []any{"nested"}}},
{"_type": "document_head", "meta": map[string]any{"key": "viewport", "value": "owned"}},
{"_type": "document_head", "meta": []any{map[string]any{"key": "description", "value": "a"}, map[string]any{"key": "description", "value": "b"}}},
{"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": "/a.js", "onclick": "x"}}},
{"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet", "href": "/a.css", "media": map[string]any{"x": "nested"}}}},
{"_type": "document_head", "links": []any{map[string]any{"rel": "stylesheet"}}},
} {
if _, err := ParseDocumentHead(resource); err == nil {
t.Fatalf("accepted %#v", resource)
}
}
if _, err := ParseDocumentHead(valid); err != nil {
t.Fatal(err)
}
for _, url := range []string{"javascript:alert(1)", "data:text/javascript,x", "//other.test/a", "relative.css", "/\\other.test/a", "https://", "/a\n.js"} {
for _, resource := range []map[string]any{
{"_type": "document_head", "links": []any{map[string]any{"rel": "script", "href": url}}},
{"_type": "document_head", "meta": map[string]any{"key": "canonical", "value": url}},
} {
if _, err := ParseDocumentHead(resource); err == nil {
t.Fatalf("accepted %q", url)
}
}
}
conflict := []any{headNode(map[string]any{"key": "description", "value": "first"}, nil),
map[string]any{"类型": "纵排", "值": []any{headNode(map[string]any{"键": "description", "值": "second"}, nil)}}}
if _, err := CollectDocumentHead(conflict); err == nil {
t.Fatal("nested head conflict silently overwrote metadata")
}
private := []any{map[string]any{"type": "resource", "value": map[string]any{"_type": "data_query", "where": headNode(nil, nil)}}}
head, err := CollectDocumentHead(private)
if err != nil || len(head.Links) != 0 || len(head.Meta) != 0 {
t.Fatalf("walked private Resource: %v %#v", err, head)
}
var deep any = []any{headNode(nil, nil)}
for i := 0; i < 66; i++ {
deep = []any{map[string]any{"type": "row", "value": deep}}
}
if _, err := CollectDocumentHead(deep); err == nil {
t.Fatal("unbounded head traversal")
}
}
@@ -0,0 +1,41 @@
package artifact
import (
"strings"
"testing"
)
func TestFindSlotKeepsNestedTypedResourcesAndRejectsAmbiguity(t *testing.T) {
descriptor := map[string]any{"_type": "data_query", "source": "articles", "slot": "not-a-view-slot"}
nodes := []any{map[string]any{"type": "row", "slot": "layout", "value": []any{
map[string]any{"类型": "纵排", "槽": "main", "值": []any{
map[string]any{"type": "resource", "slot": "articles", "value": descriptor},
}},
map[string]any{"type": "markdown", "slot": "sidebar", "value": "Separate"},
}}}
selected, found, err := FindSlot(nodes, "articles")
if err != nil || !found {
t.Fatalf("%v %v", found, err)
}
calls := 0
html, err := RenderNodesWithResources(selected, func(value map[string]any) (string, error) {
calls++
if value["source"] != "articles" {
t.Fatal(value)
}
return "<p>Actual request value</p>", nil
})
if err != nil || calls != 1 || !strings.Contains(html, "Actual request value") || strings.Contains(html, "Separate") {
t.Fatalf("%d %v %s", calls, err, html)
}
if _, found, err := FindSlot(nodes, "not-a-view-slot"); err != nil || found {
t.Fatalf("walked Resource internals: %v %v", found, err)
}
duplicate := append(nodes, map[string]any{"type": "text", "slot": "articles", "value": "Ambiguous"})
if _, _, err := FindSlot(duplicate, "articles"); err == nil {
t.Fatal("duplicate slot accepted")
}
if _, _, err := FindSlot([]any{42}, "articles"); err == nil {
t.Fatal("malformed View accepted")
}
}