CodeSampleX

サンプル

golang.org/x/net v0.47.0: html.Node

検証済みサンプル — golang golang.org/x/net v0.47.0: html.Node. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました: html.Parse parses HTML documents into a…

sha256:d640cc7826d846584d9dd12e00733a7951fdb814cc77dcb1b9dd116336bbd624

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 go linux 24 · ubuntu · glibc 2.39 x64 go go go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-10-10

ケース

HOW
ゴール
verify golang.org/x/net/html.Node in pkg:golang/golang.org/x/net@v0.47.0
パッケージ
シンボル
  • golang.org/x/net/html.Node
環境
go
作成日
2026-10-10T19:25:24Z

コントラクト

  1. html.Parse parses HTML documents into a DocumentNode tree maintaining hierarchical Parent, FirstChild, LastChild, PrevSibling, and NextSibling pointer links.
  2. html.Node DOM manipulation methods (AppendChild, InsertBefore, RemoveChild) update child lists and bidirectional sibling links without breaking existing subtree structures.
  3. html.Node represents HTML elements, text, and comments with accurate NodeType, DataAtom, Data, and slice of Attribute key-value pairs.
  4. html.Render serializes an html.Node tree back to standard HTML matching the in-memory DOM mutations.
  5. html.ParseFragment parses HTML fragments within a specified context element node, returning isolated root nodes suitable for DOM insertion.

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • node_test.go
  • spec.json

ソースアーティファクトをダウンロード (tar.gz)

ソース

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify golang.org/x/net/html.Node in pkg:golang/golang.org/x/net@v0.47.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/net@v0.47.0
Demonstrate these symbols/APIs:
  - golang.org/x/net/html.Node

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:0179f61480158de28f8eba549b4b13ab904db3bd6bd51ac5f924b0f9dd89d23e","contract":["html.Parse parses HTML documents into a DocumentNode tree maintaining hierarchical Parent, FirstChild, LastChild, PrevSibling, and NextSibling pointer links.","html.Node DOM manipulation methods (AppendChild, InsertBefore, RemoveChild) update child lists and bidirectional sibling links without breaking existing subtree structures.","html.Node represents HTML elements, text, and comments with accurate NodeType, DataAtom, Data, and slice of Attribute key-value pairs.","html.Render serializes an html.Node tree back to standard HTML matching the in-memory DOM mutations.","html.ParseFragment parses HTML fragments within a specified context element node, returning isolated root nodes suitable for DOM insertion."],"goal":"verify golang.org/x/net/html.Node in pkg:golang/golang.org/x/net@v0.47.0","kind":"HOW","packages":["pkg:golang/golang.org/x/net@v0.47.0"],"schemaVersion":1,"symbols":["golang.org/x/net/html.Node"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/net@v0.47.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/net@v0.47.0","symbols":["golang.org/x/net/html.Node"],"verifierAdapter":"golang@1"}
go.mod
module example.com/htmlnode

go 1.24.0

require golang.org/x/net v0.47.0
go.sum
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
node_test.go
package htmlnode

import (
	"bytes"
	"strings"
	"testing"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
)

// Helper function to find a node by element tag name recursively
func findFirstElementByTag(n *html.Node, tag string) *html.Node {
	if n == nil {
		return nil
	}
	if n.Type == html.ElementNode && n.Data == tag {
		return n
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if found := findFirstElementByTag(c, tag); found != nil {
			return found
		}
	}
	return nil
}

// Helper function to get attribute value by key
func getAttr(n *html.Node, key string) (string, bool) {
	for _, attr := range n.Attr {
		if attr.Key == key {
			return attr.Val, true
		}
	}
	return "", false
}

func TestNodeDOMTreeStructureAndTraversal(t *testing.T) {
	rawHTML := `<!DOCTYPE html><html><head><title>Sample Title</title></head><body><div id="container" class="box"><p>First Paragraph</p><p>Second Paragraph</p></div></body></html>`

	doc, err := html.Parse(strings.NewReader(rawHTML))
	if err != nil {
		t.Fatalf("html.Parse failed: %v", err)
	}

	if doc.Type != html.DocumentNode {
		t.Fatalf("expected root node to be DocumentNode, got %v", doc.Type)
	}

	// Verify doctype node
	doctypeNode := doc.FirstChild
	if doctypeNode == nil || doctypeNode.Type != html.DoctypeNode {
		t.Fatalf("expected first child of document to be DoctypeNode")
	}
	if doctypeNode.Data != "html" {
		t.Fatalf("expected doctype data 'html', got '%s'", doctypeNode.Data)
	}

	// Verify html element
	htmlNode := doctypeNode.NextSibling
	if htmlNode == nil || htmlNode.Type != html.ElementNode || htmlNode.Data != "html" {
		t.Fatalf("expected html element after doctype")
	}
	if htmlNode.Parent != doc {
		t.Fatalf("html element parent pointer does not point to root document")
	}

	// Traverse to head and body
	headNode := htmlNode.FirstChild
	if headNode == nil || headNode.Data != "head" {
		t.Fatalf("expected head element as first child of html")
	}
	bodyNode := headNode.NextSibling
	if bodyNode == nil || bodyNode.Data != "body" {
		t.Fatalf("expected body element as next sibling of head")
	}
	if bodyNode.PrevSibling != headNode {
		t.Fatalf("body.PrevSibling must point back to head")
	}

	// Locate container div
	divNode := findFirstElementByTag(doc, "div")
	if divNode == nil {
		t.Fatalf("div element not found in parsed tree")
	}
	if divNode.DataAtom != atom.Div {
		t.Fatalf("expected atom.Div, got %v", divNode.DataAtom)
	}

	// Validate attributes
	if idVal, ok := getAttr(divNode, "id"); !ok || idVal != "container" {
		t.Fatalf("expected id attribute 'container', got '%s' (ok=%v)", idVal, ok)
	}
	if classVal, ok := getAttr(divNode, "class"); !ok || classVal != "box" {
		t.Fatalf("expected class attribute 'box', got '%s' (ok=%v)", classVal, ok)
	}

	// Count child p elements
	var pElements []*html.Node
	for c := divNode.FirstChild; c != nil; c = c.NextSibling {
		if c.Type == html.ElementNode && c.Data == "p" {
			pElements = append(pElements, c)
		}
	}
	if len(pElements) != 2 {
		t.Fatalf("expected 2 paragraph child nodes, got %d", len(pElements))
	}

	// Verify text content in first paragraph
	p1Text := pElements[0].FirstChild
	if p1Text == nil || p1Text.Type != html.TextNode || p1Text.Data != "First Paragraph" {
		t.Fatalf("expected TextNode with 'First Paragraph', got %+v", p1Text)
	}
}

func TestNodeDOMTreeManipulation(t *testing.T) {
	rawHTML := `<div id="root"><span id="first">Item 1</span><span id="last">Item 3</span></div>`
	doc, err := html.Parse(strings.NewReader(rawHTML))
	if err != nil {
		t.Fatalf("html.Parse failed: %v", err)
	}

	rootDiv := findFirstElementByTag(doc, "div")
	if rootDiv == nil {
		t.Fatalf("root div not found")
	}

	lastSpan := findFirstElementByTag(rootDiv, "span")
	for c := rootDiv.FirstChild; c != nil; c = c.NextSibling {
		if idVal, _ := getAttr(c, "id"); idVal == "last" {
			lastSpan = c
			break
		}
	}
	if lastSpan == nil {
		t.Fatalf("lastSpan not found")
	}

	// 1. Test InsertBefore: Insert middle span between first and last
	midSpan := &html.Node{
		Type:     html.ElementNode,
		DataAtom: atom.Span,
		Data:     "span",
		Attr:     []html.Attribute{{Key: "id", Val: "middle"}},
	}
	midText := &html.Node{
		Type: html.TextNode,
		Data: "Item 2",
	}
	midSpan.AppendChild(midText)

	rootDiv.InsertBefore(midSpan, lastSpan)

	if midSpan.Parent != rootDiv {
		t.Fatalf("midSpan parent must be rootDiv")
	}
	if midSpan.NextSibling != lastSpan {
		t.Fatalf("midSpan.NextSibling must be lastSpan")
	}
	if lastSpan.PrevSibling != midSpan {
		t.Fatalf("lastSpan.PrevSibling must be midSpan")
	}

	// 2. Test AppendChild: Append a new footer paragraph
	footerP := &html.Node{
		Type:     html.ElementNode,
		DataAtom: atom.P,
		Data:     "p",
		Attr:     []html.Attribute{{Key: "class", Val: "footer"}},
	}
	footerText := &html.Node{
		Type: html.TextNode,
		Data: "Footer Content",
	}
	footerP.AppendChild(footerText)
	rootDiv.AppendChild(footerP)

	if rootDiv.LastChild != footerP {
		t.Fatalf("rootDiv.LastChild must be footerP")
	}
	if footerP.PrevSibling != lastSpan {
		t.Fatalf("footerP.PrevSibling must be lastSpan")
	}

	// 3. Test RemoveChild: Remove the middle span
	rootDiv.RemoveChild(midSpan)
	if midSpan.Parent != nil || midSpan.PrevSibling != nil || midSpan.NextSibling != nil {
		t.Fatalf("midSpan pointers were not cleared on RemoveChild")
	}
	if lastSpan.PrevSibling == midSpan {
		t.Fatalf("lastSpan.PrevSibling should not point to removed midSpan")
	}

	// 4. Render and verify HTML serialization
	var buf bytes.Buffer
	if err := html.Render(&buf, rootDiv); err != nil {
		t.Fatalf("html.Render failed: %v", err)
	}

	rendered := buf.String()
	expectedSubstrings := []string{
		`<span id="first">Item 1</span>`,
		`<span id="last">Item 3</span>`,
		`<p class="footer">Footer Content</p>`,
	}
	for _, substr := range expectedSubstrings {
		if !strings.Contains(rendered, substr) {
			t.Errorf("rendered output missing expected substring %q: got %s", substr, rendered)
		}
	}
	if strings.Contains(rendered, "Item 2") {
		t.Errorf("rendered output contains removed item: %s", rendered)
	}
}

func TestNodeParseFragment(t *testing.T) {
	contextNode := &html.Node{
		Type:     html.ElementNode,
		DataAtom: atom.Tbody,
		Data:     "tbody",
	}

	fragmentHTML := `<tr><td>Cell 1</td><td>Cell 2</td></tr><!-- row end -->`
	nodes, err := html.ParseFragment(strings.NewReader(fragmentHTML), contextNode)
	if err != nil {
		t.Fatalf("html.ParseFragment failed: %v", err)
	}

	if len(nodes) != 2 {
		t.Fatalf("expected 2 root nodes from fragment, got %d", len(nodes))
	}

	trNode := nodes[0]
	if trNode.Type != html.ElementNode || trNode.Data != "tr" {
		t.Fatalf("expected first node to be tr ElementNode, got %+v", trNode)
	}

	commentNode := nodes[1]
	if commentNode.Type != html.CommentNode || commentNode.Data != " row end " {
		t.Fatalf("expected second node to be CommentNode, got %+v", commentNode)
	}

	// Append parsed fragment nodes into contextNode
	for _, n := range nodes {
		contextNode.AppendChild(n)
	}

	if contextNode.FirstChild != trNode {
		t.Fatalf("contextNode.FirstChild must be trNode")
	}
	if contextNode.LastChild != commentNode {
		t.Fatalf("contextNode.LastChild must be commentNode")
	}

	var buf bytes.Buffer
	if err := html.Render(&buf, contextNode); err != nil {
		t.Fatalf("html.Render failed: %v", err)
	}
	rendered := buf.String()
	if !strings.Contains(rendered, "<tbody><tr><td>Cell 1</td><td>Cell 2</td></tr><!-- row end --></tbody>") {
		t.Fatalf("unexpected rendered fragment: %s", rendered)
	}
}

func TestNodeAttributeModifications(t *testing.T) {
	node := &html.Node{
		Type:     html.ElementNode,
		DataAtom: atom.A,
		Data:     "a",
		Attr: []html.Attribute{
			{Key: "href", Val: "https://example.com"},
			{Key: "target", Val: "_blank"},
		},
	}

	// Mutate attribute value
	for i := range node.Attr {
		if node.Attr[i].Key == "target" {
			node.Attr[i].Val = "_self"
		}
	}

	// Add new attribute
	node.Attr = append(node.Attr, html.Attribute{Key: "rel", Val: "noopener"})

	var buf bytes.Buffer
	if err := html.Render(&buf, node); err != nil {
		t.Fatalf("html.Render failed: %v", err)
	}

	rendered := buf.String()
	if !strings.Contains(rendered, `target="_self"`) {
		t.Errorf("expected mutated target attribute: %s", rendered)
	}
	if !strings.Contains(rendered, `rel="noopener"`) {
		t.Errorf("expected added rel attribute: %s", rendered)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/net/html.Node in pkg:golang/golang.org/x/net@v0.47.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/net@v0.47.0"
  ],
  "symbols": [
    "golang.org/x/net/html.Node"
  ]
}

オリジンシーダー

匿名