oficina / docs Public

Add bounded typed contract rendering and PDF fidelity checks

Paul Campbell pushed by paul@keymail.dev 2f380334ae9227540d0dbe220a83d81c80905512 parent 86faeba
6 files changed, +1,125 −7
  • docs/superpowers/specs/2026-10-25-contract-workflow-design.md +14 −0
  • docs/superpowers/specs/2026-10-26-contract-rendering-design.md +132 −0
  • internal/contract/contract_test.go +399 −0
  • internal/contract/resolve.go +220 −0
  • internal/contract/template.go +316 −0
  • internal/export/pdf.go +44 −7

CI passed — run details

diff --git a/docs/superpowers/specs/2026-10-25-contract-workflow-design.md b/docs/superpowers/specs/2026-10-25-contract-workflow-design.md
index 7e4929a..7b31d55 100644
--- a/docs/superpowers/specs/2026-10-25-contract-workflow-design.md
+++ b/docs/superpowers/specs/2026-10-25-contract-workflow-design.md
@@ -303,3 +303,17 @@ boundary; card visibility does not grant agreement-status visibility; PDF
review needs an accessible equivalent tied to the issued content. The
reviewer did not repeat live endpoint or discussion-12 checks; those remain
author-session observations.
+
+## 12. Implementation progress, 2026-10-26
+
+Paul asked to proceed. The first implemented unit is the bounded internal
+template renderer specified in `2026-10-26-contract-rendering-design.md`:
+structural fields, typed values, exact integer money, strict validation,
+PDF fidelity checks, byte/digest output and resource limits. Its independent
+GPT-6 code review approved that scope subject to repository gates.
+
+This is not a user-facing template editor or the integrated Fichas preview.
+The live editor schema remains unchanged to avoid dropping fields in older
+native clients. Source authorisation, handoff, preparation persistence,
+authoring UI and native signing are still required. The first renderer uses
+explicit ISO formatting; locale-specific formatting is not yet supported.
diff --git a/docs/superpowers/specs/2026-10-26-contract-rendering-design.md b/docs/superpowers/specs/2026-10-26-contract-rendering-design.md
new file mode 100644
index 0000000..d9573a7
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-26-contract-rendering-design.md
@@ -0,0 +1,132 @@
+# Contract rendering foundation
+
+Status: implemented on `feat/contract-workflow`, 2026-10-26; independently
+reviewed by GPT-6 / Codex. Repository merge gates remain separate.
+Accepted for implementation with its cumulative-indentation finding
+addressed by the fatal overflow diagnostic below.
+Consumes the 2026-10-25 contract workflow design §5 and §9. Paul asked to
+continue implementation on 2026-10-26. This is the first implementation
+unit; it is not the integrated Fichas preview or the signing workflow.
+
+## Scope
+
+Add `internal/contract`, a pure, bounded renderer for a versioned template
+tree and explicitly supplied typed values. It resolves structural field
+nodes into text, validates that the entire tree is renderable, and renders
+an actual PDF with the existing Docs exporter. It has no HTTP route,
+credential, database, source fetch, or send/sign operation. App handlers
+must authorise and pin their source revisions before calling it later.
+
+Keep this format separate from the live CRDT/editor schema until web and
+native clients can preserve field nodes. Adding a live schema node now
+would allow older clients to discard fields. This package's tests exercise
+real merge and PDF output but are not evidence of an integrated workflow.
+
+## Data contract
+
+`Template` has version 1, a title, a document root and field definitions.
+Nodes use Docs' exported tree vocabulary plus an inline `merge_field`
+node whose `attrs.key` names a definition. A field definition has a stable
+key, display label, kind (`text`, `date`, `money`), optional flag, and a
+currency for money. No expressions or arbitrary HTML. Repeated field
+occurrences use the same value. Definition order must not affect output.
+Reject duplicate definitions, unused definitions and dangling field nodes.
+
+Values are keyed by field key and typed. Missing map entries differ from
+explicit empty text. Required text rejects empty or whitespace-only input;
+optional missing/empty text produces no text. Zero money is a real value.
+Date values are strict calendar dates `YYYY-MM-DD` with no timezone.
+Money is signed int64 minor units plus an explicit ISO currency agreeing
+with its definition. No float conversion, including at int64 limits.
+
+The first supported format is explicitly `iso`: dates are ISO dates and
+money is `EUR 1234.56`, with the currency's standard minor-unit exponent
+(JPY 0, EUR 2, KWD 3). Locale-specific formatting is a later, explicit
+format version. Refuse unsupported formats instead of guessing locale.
+This narrows the initial workflow proposal's locale option deliberately;
+it does not claim localised presentation that is not implemented.
+
+The supported document subset is doc/paragraph/heading/bullet_list/
+ordered_list/list_item/blockquote/code_block/text/hard_break. Enforce the
+parent/child grammar, heading levels 1–6, indentation 0–8, and the existing
+alignment values. Only attributes the renderer actually supports may be
+used on each node. Known font/size marks and strong/em/code are permitted
+on text/fields/breaks; reject unknown or contradictory marks rather than
+quietly discarding their meaning. Link/image/table and unknown nodes are
+errors, not flattened content. Return diagnostics with field key/node path
+and stable code, not submitted field values or PDF/text content.
+
+## Bounds and failure semantics
+
+Bounds are constants with reasons: encoded template 1 MiB; 10,000 tree
+nodes and depth 32; 128 definitions; 64 KiB per value and 1 MiB total
+resolved text. These fit ordinary contracts while bounding recursive and
+repeated-field expansion. Validate UTF-8 and refuse control characters
+other than supported text whitespace. Titles and labels are bounded too.
+Decode a single JSON value strictly, including unknown properties. Typed
+callers go through the same semantic validation as decoded callers.
+
+Independent code review additionally identified quadratic shaping of long
+unbroken runs in the existing PDF exporter. Cap each word at 1,024 UTF-8
+bytes, interactive PDF text at 128 KiB, and PDF output at 100 pages. Refuse
+excess before returning an artifact. Page exhaustion returns no truncated
+PDF; empty paragraphs count toward that budget. Bound expanded node count
+too, including hard breaks introduced for multiline values. These are
+explicit supported-subset limits, not silently truncated inputs.
+
+Merge builds a fresh tree and never mutates the template or input map.
+Values are literal text even when they contain field syntax or markup.
+An error returns no resolved document or PDF. PDF font-substitution reports
+are fatal for this package even though ordinary Docs export is permissive.
+Errors expose codes/coordinates, not the offending characters.
+
+The PDF exporter must also report layout overflow (including cumulative
+quote/list/paragraph indentation). The contract adapter treats that report
+as fatal and returns no preview. Test nested lists/quotes combined with
+maximum paragraph indentation, and single glyphs too wide for the remaining
+line. A successful glyph report alone is not evidence all text fits.
+
+`Preview` returns the resolved document, exact PDF bytes, SHA-256 digest,
+template-format version and renderer-format identifier. It does not claim
+those bytes are persisted, approved, issued, cryptographically signed or
+authorised. A later preparation store must freeze the returned bytes, not
+re-render them on send. An accessible HTML view must escape the resolved
+text; this package does not mint trusted HTML.
+
+## Evidence
+
+Tests cover repeated fields, labels independent from keys, input
+immutability, literal markup, missing/empty/zero, leap dates, currency
+scale/mismatch, int64 bounds, unsupported format/schema/node/mark,
+contradictory formatting, malformed grammar, resource caps, and missing
+glyph refusal. A PDF integration case extracts text from the real output
+and checks substituted contract terms and its digest; it must fail when
+substitution is disabled. Refusal cases must return no preview artifact.
+
+After independent review: implement the types/strict parser, resolver and
+PDF adapter; run the focused tests and adversarial mutation; run repository
+checks and independent branch review before any merge. The next app-level
+unit is template authoring/persistence with client compatibility, followed
+by the authenticated Fichas transport already identified in suite #14.
+
+## Implementation and review record
+
+`internal/contract` implements strict parsing, semantic validation, typed
+resolution and real PDF generation. `export.PDFBounded` adds a page budget
+without capping ordinary export; `Report.LayoutOverflow` lets the contract
+adapter refuse overflow without silently changing ordinary export policy.
+The PDF bytes and SHA-256 digest are returned together. No persistence,
+editor schema change, UI, Fichas source fetch or signing route is exposed.
+
+Independent GPT-6 code review found the unbroken-word shaping issue above;
+limits and adversarial tests addressed it. Final review approved the
+isolated foundation subject to CI/merge gates and independently ran
+`go test ./internal/contract ./internal/export` successfully. The parent
+also ran race-enabled contract tests, extracted the fictional sample's PDF
+text with Poppler, and visually inspected its page. An overlay mutation
+disabling field substitution made the expected-value test fail for missing
+contract terms; no working-tree code was changed by that mutation.
+
+Formatting v1 is ISO, explicitly not locale-specific. This foundation is
+not the completed integrated-preview milestone; the remaining app-level
+work in the workflow design still applies.
diff --git a/internal/contract/contract_test.go b/internal/contract/contract_test.go
new file mode 100644
index 0000000..5f733ae
--- /dev/null
+++ b/internal/contract/contract_test.go
@@ -0,0 +1,399 @@
+package contract_test
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "math"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/docs/internal/contract"
+ "github.com/carlosframework/docs/internal/export"
+)
+
+func field(key string) contract.Node {
+ return contract.Node{Type: "merge_field", Attrs: contract.Attrs{Key: key}}
+}
+
+func template() contract.Template {
+ return contract.Template{Version: 1, Title: "Service agreement", Fields: []contract.Field{
+ {Key: "customer", Label: "Customer name", Kind: contract.Text},
+ {Key: "start", Label: "Start date", Kind: contract.Date},
+ {Key: "fee", Label: "Fee", Kind: contract.Money, Currency: "EUR"},
+ }, Root: contract.Node{Type: "doc", Content: []contract.Node{
+ {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Prepared for "}, field("customer")}},
+ {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Effective "}, field("start")}},
+ {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Fee: "}, field("fee")}},
+ {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Accepted by "}, field("customer")}},
+ }}}
+}
+
+func values() map[string]contract.Value {
+ return map[string]contract.Value{
+ "customer": {Kind: contract.Text, Text: "Acme Workshops"},
+ "start": {Kind: contract.Date, Text: "2028-02-29"},
+ "fee": {Kind: contract.Money, MinorUnits: 125050, Currency: "EUR"},
+ }
+}
+
+func code(t *testing.T, err error, want string) {
+ t.Helper()
+ var d *contract.Diagnostic
+ if !errors.As(err, &d) || d.Code != want {
+ t.Fatalf("error = %v, want code %s", err, want)
+ }
+}
+
+func text(n export.Node) string {
+ s := n.Text
+ for _, c := range n.Content {
+ s += text(c)
+ }
+ return s
+}
+
+func TestResolveSubstitutesStructuralFieldsWithoutChangingInputs(t *testing.T) {
+ t.Parallel()
+ tpl, vals := template(), values()
+ tpl.Root.Content[0].Content[1].Marks = []export.Mark{{Type: "strong"}}
+ before, _ := json.Marshal(tpl)
+ doc, err := contract.Resolve(tpl, vals, contract.ISOFormat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := text(doc.Root)
+ if strings.Count(got, "Acme Workshops") != 2 || !strings.Contains(got, "2028-02-29") || !strings.Contains(got, "EUR 1250.50") {
+ t.Fatal(got)
+ }
+ if doc.Root.Content[0].Content[1].Marks[0].Type != "strong" {
+ t.Fatal("lost field formatting")
+ }
+ // Mutating the returned slices must not edit the template's slices.
+ doc.Root.Content[0].Content[1].Marks[0].Type = "em"
+ doc.Root.Content[0].Content[0].Text = "changed"
+ after, _ := json.Marshal(tpl)
+ if !bytes.Equal(before, after) || !reflect.DeepEqual(vals, values()) {
+ t.Fatal("inputs mutated")
+ }
+ tpl.Fields[0].Label = "Renamed label"
+ again, err := contract.Resolve(tpl, vals, contract.ISOFormat)
+ if err != nil || text(again.Root) != got {
+ t.Fatal("label rename changed binding", err)
+ }
+}
+
+func TestValuesAreLiteralAndZeroIsPresent(t *testing.T) {
+ t.Parallel()
+ v := values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: `<script>{{fee}}</script>`}
+ v["fee"] = contract.Value{Kind: contract.Money, Currency: "EUR"}
+ doc, err := contract.Resolve(template(), v, contract.ISOFormat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(text(doc.Root), `<script>{{fee}}</script>`) || !strings.Contains(text(doc.Root), "EUR 0.00") {
+ t.Fatal(text(doc.Root))
+ }
+}
+
+func TestMultilineValuesPreserveLineBreaks(t *testing.T) {
+ t.Parallel()
+ v := values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: "Acme\nWorkshop\n"}
+ doc, err := contract.Resolve(template(), v, contract.ISOFormat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodes := doc.Root.Content[0].Content
+ if len(nodes) != 5 || nodes[1].Text != "Acme" || nodes[2].Type != "hard_break" || nodes[3].Text != "Workshop" || nodes[4].Type != "hard_break" {
+ t.Fatalf("lost line breaks: %#v", nodes)
+ }
+ v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("a\n", 6000)}
+ _, err = contract.Resolve(template(), v, contract.ISOFormat)
+ code(t, err, "expanded_node_limit")
+}
+
+func TestMissingEmptyAndWrongValuesRefuseWithoutDocument(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name, key, code string
+ value contract.Value
+ remove bool
+ }{
+ {"absent", "customer", "required_value", contract.Value{}, true},
+ {"empty", "customer", "required_value", contract.Value{Kind: contract.Text}, false},
+ {"space", "customer", "required_value", contract.Value{Kind: contract.Text, Text: " \n "}, false},
+ {"kind", "customer", "value_type", contract.Value{Kind: contract.Date, Text: "2026-01-01"}, false},
+ {"bad leap", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "2027-02-29"}, false},
+ {"timestamp", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "2028-02-29T00:00:00Z"}, false},
+ {"year zero", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "0000-01-01"}, false},
+ {"currency", "fee", "currency_mismatch", contract.Value{Kind: contract.Money, Currency: "GBP"}, false},
+ {"unused money", "customer", "unexpected_money", contract.Value{Kind: contract.Text, Text: "Acme", MinorUnits: 1}, false},
+ {"invalid unicode", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: "\xff"}, false},
+ {"control", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: "secret\x00"}, false},
+ {"oversized", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: strings.Repeat("x", contract.MaxValueBytes+1)}, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ v := values()
+ if tc.remove {
+ delete(v, tc.key)
+ } else {
+ v[tc.key] = tc.value
+ }
+ doc, err := contract.Resolve(template(), v, contract.ISOFormat)
+ code(t, err, tc.code)
+ if !reflect.DeepEqual(doc, export.Document{}) {
+ t.Fatal("partial result returned")
+ }
+ if strings.Contains(err.Error(), "secret") {
+ t.Fatal("error leaked value")
+ }
+ })
+ }
+
+ tpl, v := template(), values()
+ tpl.Fields[0].Optional = true
+ delete(v, "customer")
+ doc, err := contract.Resolve(tpl, v, contract.ISOFormat)
+ if err != nil || len(doc.Root.Content[0].Content) != 1 {
+ t.Fatal("optional missing field", err)
+ }
+ v["customer"] = contract.Value{Kind: contract.Text}
+ if _, err := contract.Resolve(tpl, v, contract.ISOFormat); err != nil {
+ t.Fatal(err)
+ }
+ v["unknown_secret_key"] = contract.Value{Kind: contract.Text}
+ _, err = contract.Resolve(tpl, v, contract.ISOFormat)
+ code(t, err, "unexpected_values")
+ if strings.Contains(err.Error(), "unknown_secret_key") {
+ t.Fatal("untrusted key leaked")
+ }
+}
+
+func TestMoneyUsesExactMinorUnits(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ currency string
+ minor int64
+ want string
+ }{
+ {"EUR", math.MinInt64, "EUR -92233720368547758.08"},
+ {"EUR", math.MaxInt64, "EUR 92233720368547758.07"},
+ {"EUR", -1, "EUR -0.01"}, {"JPY", 100, "JPY 100"},
+ {"KWD", 1, "KWD 0.001"}, {"KWD", 1234567, "KWD 1234.567"},
+ } {
+ t.Run(tc.want, func(t *testing.T) {
+ tpl, v := template(), values()
+ tpl.Fields[2].Currency = tc.currency
+ v["fee"] = contract.Value{Kind: contract.Money, Currency: tc.currency, MinorUnits: tc.minor}
+ doc, err := contract.Resolve(tpl, v, contract.ISOFormat)
+ if err != nil || !strings.Contains(text(doc.Root), tc.want) {
+ t.Fatal(text(doc.Root), err)
+ }
+ })
+ }
+}
+
+func TestTemplateValidation(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name, code string
+ change func(*contract.Template)
+ }{
+ {"version", "unsupported_version", func(t *contract.Template) { t.Version = 2 }},
+ {"title", "invalid_title", func(t *contract.Template) { t.Title = "\xff" }},
+ {"duplicate", "duplicate_field", func(t *contract.Template) { t.Fields = append(t.Fields, t.Fields[0]) }},
+ {"unused", "unused_field", func(t *contract.Template) {
+ t.Fields = append(t.Fields, contract.Field{Key: "unused", Label: "Unused", Kind: contract.Text})
+ }},
+ {"currency", "invalid_currency", func(t *contract.Template) { t.Fields[2].Currency = "xxx" }},
+ {"unknown", "unknown_field", func(t *contract.Template) { t.Root.Content[0].Content[1].Attrs.Key = "absent" }},
+ {"image", "unsupported_structure", func(t *contract.Template) { t.Root.Content[0].Content[0].Type = "image" }},
+ {"leaf children", "unexpected_children", func(t *contract.Template) { t.Root.Content[0].Content[0].Content = []contract.Node{field("fee")} }},
+ {"no children", "missing_children", func(t *contract.Template) { t.Root.Content = nil }},
+ {"bad heading", "invalid_heading", func(t *contract.Template) { t.Root.Content[0].Type = "heading" }},
+ {"block marks", "unexpected_marks", func(t *contract.Template) { t.Root.Marks = []export.Mark{{Type: "strong"}} }},
+ {"unknown mark", "unsupported_mark", func(t *contract.Template) { t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "link"}} }},
+ {"two sizes", "conflicting_marks", func(t *contract.Template) {
+ t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "size_8"}, {Type: "size_14"}}
+ }},
+ {"two fonts", "conflicting_marks", func(t *contract.Template) {
+ t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "font_sans"}, {Type: "font_mono"}}
+ }},
+ {"code font", "conflicting_marks", func(t *contract.Template) {
+ t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "code"}, {Type: "font_sans"}}
+ }},
+ {"indent", "invalid_indent", func(t *contract.Template) { t.Root.Content[0].Attrs.Indent = 9 }},
+ {"alignment", "invalid_alignment", func(t *contract.Template) { t.Root.Content[0].Attrs.Align = "justify" }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tpl := template()
+ tc.change(&tpl)
+ code(t, tpl.Validate(), tc.code)
+ })
+ }
+ _, err := contract.Resolve(template(), values(), "en-IE")
+ code(t, err, "unsupported_format")
+}
+
+func TestStrictJSON(t *testing.T) {
+ t.Parallel()
+ b, _ := json.Marshal(template())
+ parsed, err := contract.Parse(b)
+ if err != nil || !reflect.DeepEqual(parsed, template()) {
+ t.Fatal(err)
+ }
+ for _, input := range [][]byte{
+ append(append([]byte(nil), b...), []byte(` {}`)...),
+ []byte(strings.Replace(string(b), `"version":1`, `"version":1,"version":1`, 1)),
+ []byte(strings.Replace(string(b), `"version":1`, `"version":1,"unexpected":"secret"`, 1)),
+ []byte(strings.Replace(string(b), `"Service agreement"`, `"\ud800"`, 1)),
+ []byte(strings.Replace(string(b), `"paragraph"`, `"paragraph","attrs":{"surprise":true}`, 1)),
+ } {
+ _, err := contract.Parse(input)
+ code(t, err, "invalid_json")
+ }
+ _, err = contract.Parse(bytes.Repeat([]byte(" "), contract.MaxTemplateBytes+1))
+ code(t, err, "template_too_large")
+}
+
+func TestResourceBounds(t *testing.T) {
+ t.Parallel()
+ tpl := template()
+ for i := 0; i <= contract.MaxDepth; i++ {
+ tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}}
+ }
+ code(t, tpl.Validate(), "tree_limit")
+ tpl = template()
+ tpl.Root.Content = append(tpl.Root.Content, make([]contract.Node, contract.MaxNodes)...)
+ for i := 4; i < len(tpl.Root.Content); i++ {
+ tpl.Root.Content[i] = contract.Node{Type: "paragraph"}
+ }
+ code(t, tpl.Validate(), "tree_limit")
+ tpl = template()
+ for i := 0; i < 20; i++ {
+ tpl.Root.Content[0].Content = append(tpl.Root.Content[0].Content, field("customer"))
+ }
+ v := values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("x ", contract.MaxValueBytes/2)}
+ _, err := contract.Resolve(tpl, v, contract.ISOFormat)
+ code(t, err, "expanded_text_limit")
+}
+
+func TestRenderPDF(t *testing.T) {
+ t.Parallel()
+ p, err := contract.Render(template(), values(), contract.ISOFormat)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.HasPrefix(p.PDF, []byte("%PDF-")) || !bytes.Contains(p.PDF, []byte("%%EOF")) || p.SHA256 != sha256.Sum256(p.PDF) {
+ t.Fatal("invalid PDF or digest")
+ }
+ if p.TemplateVersion != 1 || p.Renderer == "" {
+ t.Fatal("missing version")
+ }
+ // Optional local QA artifact, always using the fictional fixture above.
+ // The independent pdftotext check is run against these exact output bytes.
+ if path := os.Getenv("CONTRACT_PREVIEW_PDF"); path != "" {
+ if err := os.WriteFile(path, p.PDF, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func TestRenderRefusesLossyPDF(t *testing.T) {
+ t.Parallel()
+ t.Run("missing glyph", func(t *testing.T) {
+ v := values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: "\U0010ffff"}
+ p, err := contract.Render(template(), v, contract.ISOFormat)
+ code(t, err, "missing_glyphs")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial artifact")
+ }
+ })
+ t.Run("nested indentation", func(t *testing.T) {
+ tpl := template()
+ tpl.Root.Content[0].Attrs.Indent = 8
+ for i := 0; i < 20; i++ {
+ tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}}
+ }
+ p, err := contract.Render(tpl, values(), contract.ISOFormat)
+ code(t, err, "layout_overflow")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial artifact")
+ }
+ })
+ t.Run("single glyph wider than column", func(t *testing.T) {
+ tpl, v := template(), values()
+ tpl.Root.Content[0].Attrs.Indent = 8
+ tpl.Root.Content[0].Content[1].Marks = []export.Mark{{Type: "size_72"}}
+ v["customer"] = contract.Value{Kind: contract.Text, Text: "W"}
+ for i := 0; i < 14; i++ {
+ tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}}
+ }
+ p, err := contract.Render(tpl, v, contract.ISOFormat)
+ code(t, err, "layout_overflow")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial artifact")
+ }
+ })
+}
+
+func TestRenderWorkLimits(t *testing.T) {
+ t.Parallel()
+ for _, literal := range []bool{false, true} {
+ tpl, v := template(), values()
+ long := strings.Repeat("x", contract.MaxWordBytes+1)
+ if literal {
+ tpl.Root.Content[0].Content[0].Text = long
+ } else {
+ v["customer"] = contract.Value{Kind: contract.Text, Text: long}
+ }
+ p, err := contract.Render(tpl, v, contract.ISOFormat)
+ code(t, err, "word_limit")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial output")
+ }
+ }
+ tpl, v := template(), values()
+ v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("x ", contract.MaxValueBytes/2)}
+ tpl.Root.Content[0].Content = append(tpl.Root.Content[0].Content, field("customer"))
+ p, err := contract.Render(tpl, v, contract.ISOFormat)
+ code(t, err, "render_text_limit")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("partial output")
+ }
+
+ tpl = template()
+ // Empty paragraphs are real blank lines: byte caps alone cannot bound pages.
+ for i := 0; i < 5000; i++ {
+ tpl.Root.Content = append(tpl.Root.Content, contract.Node{Type: "paragraph"})
+ }
+ p, err = contract.Render(tpl, values(), contract.ISOFormat)
+ code(t, err, "page_limit")
+ if !reflect.DeepEqual(p, contract.Preview{}) {
+ t.Fatal("truncated output")
+ }
+}
+
+func TestLongestWordInNarrowColumn(t *testing.T) {
+ t.Parallel()
+ tpl, v := template(), values()
+ tpl.Root.Content[0].Attrs.Indent = 8
+ // 468pt content - 288pt paragraph indent - 14*12pt quote indent =
+ // 12pt remaining. A regular W fits, but nearly every glyph wraps.
+ for i := 0; i < 14; i++ {
+ tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}}
+ }
+ v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("W", contract.MaxWordBytes)}
+ p, err := contract.Render(tpl, v, contract.ISOFormat)
+ if err != nil || len(p.PDF) == 0 {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/contract/resolve.go b/internal/contract/resolve.go
new file mode 100644
index 0000000..d0c20f8
--- /dev/null
+++ b/internal/contract/resolve.go
@@ -0,0 +1,220 @@
+package contract
+
+import (
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/docs/internal/export"
+ "golang.org/x/text/currency"
+)
+
+// Value represents a supplied value, including zero money. Absence is a
+// missing map entry. Text is used for text/date, MinorUnits for money.
+type Value struct {
+ Kind Kind
+ Text string
+ MinorUnits int64
+ Currency string
+}
+
+const ISOFormat = "iso"
+
+func currencyScale(code string) (int, bool) {
+ if len(code) != 3 || code != strings.ToUpper(code) || code == "XXX" || code == "XTS" {
+ return 0, false
+ }
+ u, err := currency.ParseISO(code)
+ if err != nil {
+ return 0, false
+ }
+ scale, _ := currency.Standard.Rounding(u)
+ return scale, true
+}
+
+func formatValue(f Field, v Value, path string) (string, error) {
+ if v.Kind != f.Kind {
+ return "", problem("value_type", path)
+ }
+ if !validText(v.Text, MaxValueBytes) {
+ return "", problem("invalid_value", path)
+ }
+ if wordTooLong(v.Text) {
+ return "", problem("word_limit", path)
+ }
+ if v.Kind != Money && (v.MinorUnits != 0 || v.Currency != "") {
+ return "", problem("unexpected_money", path)
+ }
+ switch v.Kind {
+ case Text:
+ if strings.TrimSpace(v.Text) == "" && !f.Optional {
+ return "", problem("required_value", path)
+ }
+ return v.Text, nil
+ case Date:
+ date, err := time.Parse("2006-01-02", v.Text)
+ if err != nil || date.Year() < 1 || date.Format("2006-01-02") != v.Text {
+ return "", problem("invalid_date", path)
+ }
+ return v.Text, nil
+ case Money:
+ if v.Text != "" || v.Currency != f.Currency {
+ return "", problem("currency_mismatch", path)
+ }
+ scale, _ := currencyScale(f.Currency) // definition already validated
+ digits := strconv.FormatInt(v.MinorUnits, 10)
+ sign := ""
+ if strings.HasPrefix(digits, "-") {
+ sign, digits = "-", digits[1:]
+ }
+ if scale > 0 {
+ if len(digits) <= scale {
+ digits = strings.Repeat("0", scale+1-len(digits)) + digits
+ }
+ digits = digits[:len(digits)-scale] + "." + digits[len(digits)-scale:]
+ }
+ return f.Currency + " " + sign + digits, nil
+ }
+ return "", problem("unsupported_kind", path)
+}
+
+// Resolve validates all input before producing a fresh tree. It never mutates
+// the template or reinterprets a value as field syntax, markup or an expression.
+func Resolve(t Template, values map[string]Value, format string) (export.Document, error) {
+ if format != ISOFormat {
+ return export.Document{}, problem("unsupported_format", "format")
+ }
+ if err := t.Validate(); err != nil {
+ return export.Document{}, err
+ }
+ if len(values) > len(t.Fields) {
+ return export.Document{}, problem("unexpected_values", "values")
+ }
+ resolved := make(map[string]string, len(t.Fields))
+ for i, f := range t.Fields {
+ path := fmt.Sprintf("fields[%d]", i)
+ v, present := values[f.Key]
+ if !present {
+ if !f.Optional {
+ return export.Document{}, problem("required_value", path)
+ }
+ resolved[f.Key] = ""
+ continue
+ }
+ text, err := formatValue(f, v, path)
+ if err != nil {
+ return export.Document{}, err
+ }
+ resolved[f.Key] = text
+ }
+ for key := range values {
+ if _, ok := resolved[key]; !ok {
+ return export.Document{}, problem("unexpected_values", "values")
+ }
+ }
+ remaining := expansionBudget{text: MaxTextBytes - len(t.Title), nodes: MaxNodes}
+ root, err := resolveNode(t.Root, resolved, &remaining)
+ if err != nil {
+ return export.Document{}, err
+ }
+ return export.Document{Title: t.Title, Root: root}, nil
+}
+
+type expansionBudget struct{ text, nodes int }
+
+func resolveNode(n Node, values map[string]string, remaining *expansionBudget) (export.Node, error) {
+ remaining.nodes--
+ if remaining.nodes < 0 {
+ return export.Node{}, problem("expanded_node_limit", "root")
+ }
+ out := export.Node{Type: n.Type, Text: n.Text,
+ Attrs: export.Attrs{Level: n.Attrs.Level, Align: n.Attrs.Align, Indent: n.Attrs.Indent},
+ Marks: append([]export.Mark(nil), n.Marks...)}
+ if n.Type == "merge_field" {
+ out.Type, out.Text = "text", values[n.Attrs.Key]
+ }
+ remaining.text -= len(out.Text)
+ if remaining.text < 0 {
+ return export.Node{}, problem("expanded_text_limit", "root")
+ }
+ for _, child := range n.Content {
+ c, err := resolveNode(child, values, remaining)
+ if err != nil {
+ return export.Node{}, err
+ }
+ // An optional absent field becomes no node, not an invalid empty text.
+ if c.Type == "text" && c.Text == "" {
+ continue
+ }
+ if c.Type == "text" && strings.Contains(c.Text, "\n") {
+ // The exporter treats newlines inside a text run as whitespace.
+ // Explicit breaks preserve multiline values and code-block lines.
+ parts := strings.Split(c.Text, "\n")
+ remaining.nodes -= 2 * (len(parts) - 1)
+ if remaining.nodes < 0 {
+ return export.Node{}, problem("expanded_node_limit", "root")
+ }
+ for i, part := range parts {
+ if i > 0 {
+ out.Content = append(out.Content, export.Node{Type: "hard_break", Marks: append([]export.Mark(nil), c.Marks...)})
+ }
+ if part != "" {
+ run := c
+ run.Text = part
+ run.Marks = append([]export.Mark(nil), c.Marks...)
+ out.Content = append(out.Content, run)
+ }
+ }
+ continue
+ }
+ out.Content = append(out.Content, c)
+ }
+ return out, nil
+}
+
+// Preview is an in-memory rendering, not a persisted or authorised agreement.
+// Persist PDF exactly if it later becomes the subject of a signing operation.
+type Preview struct {
+ Document export.Document
+ PDF []byte
+ SHA256 [32]byte
+ TemplateVersion int
+ Renderer string
+}
+
+// Render refuses output that would substitute glyphs or overflow the page.
+// Errors return the zero Preview, never a partially usable document or PDF.
+func Render(t Template, values map[string]Value, format string) (Preview, error) {
+ doc, err := Resolve(t, values, format)
+ if err != nil {
+ return Preview{}, err
+ }
+ if renderedBytes(doc.Root)+len(doc.Title) > MaxRenderTextBytes {
+ return Preview{}, problem("render_text_limit", "document")
+ }
+ data, report, err := export.PDFBounded(doc, MaxPreviewPages)
+ if errors.Is(err, export.ErrPageLimit) {
+ return Preview{}, problem("page_limit", "document")
+ }
+ if err != nil {
+ return Preview{}, problem("render_failed", "document")
+ }
+ if !report.Empty() {
+ return Preview{}, problem("missing_glyphs", "document")
+ }
+ if report.LayoutOverflow {
+ return Preview{}, problem("layout_overflow", "document")
+ }
+ return Preview{Document: doc, PDF: data, SHA256: sha256.Sum256(data), TemplateVersion: Version, Renderer: "docs-contract-pdf-v1"}, nil
+}
+
+func renderedBytes(n export.Node) int {
+ total := len(n.Text)
+ for _, c := range n.Content {
+ total += renderedBytes(c)
+ }
+ return total
+}
diff --git a/internal/contract/template.go b/internal/contract/template.go
new file mode 100644
index 0000000..6579b3b
--- /dev/null
+++ b/internal/contract/template.go
@@ -0,0 +1,316 @@
+// Package contract resolves versioned contract templates into PDF previews.
+// It performs no source lookup or authorisation and does not issue agreements.
+// Callers must authorise and pin their inputs before invoking it.
+package contract
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/carlosframework/docs/internal/export"
+ "github.com/carlosframework/docs/internal/fonts"
+ json "github.com/go-json-experiment/json"
+)
+
+const (
+ Version = 1
+ // Limits bound decoding, recursive traversal and repeated-field expansion
+ // while leaving room for a substantial contract, without attachments.
+ MaxTemplateBytes = 1 << 20
+ MaxNodes = 10000
+ MaxDepth = 32
+ MaxFields = 128
+ MaxValueBytes = 64 << 10
+ MaxTextBytes = 1 << 20
+ // Titles and field labels are short display metadata, not contract bodies.
+ MaxLabelBytes = 256
+ // The exporter reshapes a word when wrapping it; bounding each word
+ // prevents a long identifier from causing quadratic shaping work.
+ MaxWordBytes = 1024
+ // Rendering is more expensive than structural resolution. These caps
+ // bound an interactive preview to an ordinary contract, not a book.
+ MaxRenderTextBytes = 128 << 10
+ MaxPreviewPages = 100
+)
+
+type Kind string
+
+const (
+ Text Kind = "text"
+ Date Kind = "date"
+ Money Kind = "money"
+)
+
+type Field struct {
+ Key string `json:"key"`
+ Label string `json:"label"`
+ Kind Kind `json:"kind"`
+ Optional bool `json:"optional,omitempty"`
+ Currency string `json:"currency,omitempty"`
+}
+
+// Attrs deliberately names only attributes the contract renderer understands.
+// Key belongs only to merge_field; the others are the Docs export vocabulary.
+type Attrs struct {
+ Level int `json:"level,omitempty"`
+ Align string `json:"align,omitempty"`
+ Indent int `json:"indent,omitempty"`
+ Key string `json:"key,omitempty"`
+}
+
+// Node is a template node, not a change to the live editor/CRDT schema.
+type Node struct {
+ Type string `json:"type"`
+ Attrs Attrs `json:"attrs,omitempty"`
+ Content []Node `json:"content,omitempty"`
+ Text string `json:"text,omitempty"`
+ Marks []export.Mark `json:"marks,omitempty"`
+}
+
+type Template struct {
+ Version int `json:"version"`
+ Title string `json:"title"`
+ Fields []Field `json:"fields"`
+ Root Node `json:"root"`
+}
+
+// Diagnostic contains only a stable code and structural coordinate. Labels,
+// text, raw parser errors and submitted values never enter an error string.
+type Diagnostic struct {
+ Code string
+ Path string
+}
+
+func (e *Diagnostic) Error() string { return "contract: " + e.Code + " at " + e.Path }
+func problem(code, path string) error { return &Diagnostic{Code: code, Path: path} }
+
+// Parse rejects duplicate/unknown JSON properties and invalid Unicode using
+// the same strict decoder already pinned by Docs. Validate also serves typed
+// callers, so decoding is not the only enforcement point.
+func Parse(data []byte) (Template, error) {
+ if len(data) > MaxTemplateBytes {
+ return Template{}, problem("template_too_large", "template")
+ }
+ var t Template
+ if err := json.Unmarshal(data, &t, json.RejectUnknownMembers(true)); err != nil {
+ return Template{}, problem("invalid_json", "template")
+ }
+ if err := t.Validate(); err != nil {
+ return Template{}, err
+ }
+ return t, nil
+}
+
+var keyPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]{0,63}$`)
+
+func validText(s string, max int) bool {
+ if len(s) > max || !utf8.ValidString(s) {
+ return false
+ }
+ for _, r := range s {
+ if (unicode.IsControl(r) && r != '\n' && r != '\t') || unicode.In(r, unicode.Cf) {
+ return false
+ }
+ }
+ return true
+}
+
+func wordTooLong(s string) bool {
+ length := 0
+ for _, r := range s {
+ if r == ' ' || r == '\n' || r == '\t' {
+ length = 0
+ } else {
+ length += utf8.RuneLen(r)
+ }
+ if length > MaxWordBytes {
+ return true
+ }
+ }
+ return false
+}
+
+func (t Template) Validate() error {
+ if t.Version != Version {
+ return problem("unsupported_version", "version")
+ }
+ if !validText(t.Title, MaxLabelBytes) || strings.ContainsAny(t.Title, "\n\t") {
+ return problem("invalid_title", "title")
+ }
+ if len(t.Fields) > MaxFields {
+ return problem("too_many_fields", "fields")
+ }
+ defs := make(map[string]Field, len(t.Fields))
+ for i, f := range t.Fields {
+ path := fmt.Sprintf("fields[%d]", i)
+ if !keyPattern.MatchString(f.Key) || !validText(f.Label, MaxLabelBytes) || strings.TrimSpace(f.Label) == "" {
+ return problem("invalid_field", path)
+ }
+ if _, exists := defs[f.Key]; exists {
+ return problem("duplicate_field", path)
+ }
+ switch f.Kind {
+ case Text, Date:
+ if f.Currency != "" {
+ return problem("unexpected_currency", path)
+ }
+ case Money:
+ if _, ok := currencyScale(f.Currency); !ok {
+ return problem("invalid_currency", path)
+ }
+ default:
+ return problem("unsupported_kind", path)
+ }
+ defs[f.Key] = f
+ }
+ v := validator{defs: defs, used: map[string]bool{}}
+ if err := v.node(t.Root, "", "root", 0); err != nil {
+ return err
+ }
+ for i, f := range t.Fields {
+ if !v.used[f.Key] {
+ return problem("unused_field", fmt.Sprintf("fields[%d]", i))
+ }
+ }
+ // Bound the encoded representation for typed callers too, after bounded
+ // traversal has excluded extreme depth and cyclic slice-backed trees.
+ b, err := json.Marshal(t)
+ if err != nil || len(b) > MaxTemplateBytes {
+ return problem("template_too_large", "template")
+ }
+ return nil
+}
+
+type validator struct {
+ defs map[string]Field
+ used map[string]bool
+ nodes, bytes int
+}
+
+func isBlock(s string) bool {
+ switch s {
+ case "paragraph", "heading", "blockquote", "code_block", "bullet_list", "ordered_list":
+ return true
+ }
+ return false
+}
+
+func childAllowed(parent, child string) bool {
+ switch parent {
+ case "":
+ return child == "doc"
+ case "doc", "blockquote", "list_item":
+ return isBlock(child)
+ case "bullet_list", "ordered_list":
+ return child == "list_item"
+ case "paragraph", "heading":
+ return child == "text" || child == "hard_break" || child == "merge_field"
+ case "code_block":
+ return child == "text"
+ }
+ return false
+}
+
+func (v *validator) node(n Node, parent, path string, depth int) error {
+ v.nodes++
+ if depth > MaxDepth || v.nodes > MaxNodes {
+ return problem("tree_limit", path)
+ }
+ if !childAllowed(parent, n.Type) {
+ return problem("unsupported_structure", path)
+ }
+ inline := n.Type == "text" || n.Type == "hard_break" || n.Type == "merge_field"
+ if inline && len(n.Content) != 0 {
+ return problem("unexpected_children", path)
+ }
+ if !inline && n.Type != "paragraph" && n.Type != "heading" && n.Type != "code_block" && len(n.Content) == 0 {
+ return problem("missing_children", path)
+ }
+ if n.Type == "list_item" && n.Content[0].Type != "paragraph" {
+ return problem("list_item_paragraph", path)
+ }
+ if n.Type != "text" && n.Text != "" {
+ return problem("unexpected_text", path)
+ }
+ if !validText(n.Text, MaxTextBytes) {
+ return problem("invalid_text", path)
+ }
+ if wordTooLong(n.Text) {
+ return problem("word_limit", path)
+ }
+ v.bytes += len(n.Text)
+ if v.bytes > MaxTextBytes {
+ return problem("text_limit", path)
+ }
+ a := n.Attrs
+ if n.Type == "heading" {
+ if a.Level < 1 || a.Level > 6 {
+ return problem("invalid_heading", path)
+ }
+ } else if a.Level != 0 {
+ return problem("unexpected_level", path)
+ }
+ if a.Indent < 0 || a.Indent > export.MaxIndent || (a.Indent != 0 && n.Type != "paragraph" && n.Type != "heading") {
+ return problem("invalid_indent", path)
+ }
+ if a.Align != "" && (n.Type != "paragraph" || (a.Align != "left" && a.Align != "center" && a.Align != "right")) {
+ return problem("invalid_alignment", path)
+ }
+ if n.Type == "merge_field" {
+ if _, ok := v.defs[a.Key]; !ok {
+ return problem("unknown_field", path)
+ }
+ v.used[a.Key] = true
+ } else if a.Key != "" {
+ return problem("unexpected_key", path)
+ }
+ if !inline && len(n.Marks) != 0 {
+ return problem("unexpected_marks", path)
+ }
+ if err := validateMarks(n.Marks, path); err != nil {
+ return err
+ }
+ if parent == "code_block" && len(n.Marks) != 0 {
+ return problem("unexpected_marks", path)
+ }
+ for i, child := range n.Content {
+ if err := v.node(child, n.Type, fmt.Sprintf("%s.content[%d]", path, i), depth+1); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func validateMarks(marks []export.Mark, path string) error {
+ groups := map[string]bool{}
+ for _, m := range marks {
+ group := m.Type
+ switch {
+ case m.Type == "strong" || m.Type == "em" || m.Type == "code":
+ case strings.HasPrefix(m.Type, "font_"):
+ if _, ok := fonts.ByKey(strings.TrimPrefix(m.Type, "font_")); !ok {
+ return problem("unsupported_mark", path)
+ }
+ group = "font"
+ case strings.HasPrefix(m.Type, "size_"):
+ if _, ok := export.SizePt(m.Type); !ok {
+ return problem("unsupported_mark", path)
+ }
+ group = "size"
+ default:
+ return problem("unsupported_mark", path)
+ }
+ if groups[group] {
+ return problem("conflicting_marks", path)
+ }
+ groups[group] = true
+ }
+ // The exporter forces the code family even if a font mark is present.
+ if groups["code"] && groups["font"] {
+ return problem("conflicting_marks", path)
+ }
+ return nil
+}
diff --git a/internal/export/pdf.go b/internal/export/pdf.go
index 1f41c52..6362ed9 100644
--- a/internal/export/pdf.go
+++ b/internal/export/pdf.go
@@ -1,6 +1,7 @@
package export
import (
+ "errors"
"sort"
"strconv"
"strings"
@@ -319,6 +320,10 @@ func Lines(doc Document) []string {
type Report struct {
// MissingRunes is sorted and deduplicated.
MissingRunes []rune
+ // LayoutOverflow reports text beyond its available line width. Ordinary
+ // export remains permissive; contract previews must refuse this report.
+ // Empty retains its existing meaning: no glyph substitutions.
+ LayoutOverflow bool
}
// Empty reports whether the export was fully faithful.
@@ -441,14 +446,34 @@ type blockContext struct {
// PDF lays a document out and returns the file.
func PDF(doc Document) ([]byte, Report, error) {
+ return renderPDF(doc, 0)
+}
+
+// ErrPageLimit means a bounded export did not fit. No truncated PDF is returned.
+var ErrPageLimit = errors.New("pdf: page limit exceeded")
+
+// PDFBounded bounds page allocation for interactive contract previews.
+// Normal exports continue to use PDF without this cap.
+func PDFBounded(doc Document, maxPages int) ([]byte, Report, error) {
+ if maxPages <= 0 {
+ return nil, Report{}, ErrPageLimit
+ }
+ return renderPDF(doc, maxPages)
+}
+
+func renderPDF(doc Document, maxPages int) ([]byte, Report, error) {
l := &layout{
- b: pdf.New(PageWidthPt, PageHeightPt),
- missing: map[rune]bool{},
- shaper: fonts.NewShaper(),
+ b: pdf.New(PageWidthPt, PageHeightPt),
+ missing: map[rune]bool{},
+ shaper: fonts.NewShaper(),
+ stopAfterPage: maxPages,
}
l.b.Title = doc.Title
l.newPage()
l.document(doc)
+ if l.stopped {
+ return nil, l.report(), ErrPageLimit
+ }
out, err := l.b.Bytes()
if err != nil {
@@ -545,9 +570,10 @@ type layout struct {
// once that many are complete. Nothing is drawn or reported after
// stopped is set, so a caller that wants one page pays for one page
// of layout rather than for all of a long document's.
- pages int
- stopAfterPage int
- stopped bool
+ pages int
+ stopAfterPage int
+ stopped bool
+ layoutOverflow bool
missing map[rune]bool
@@ -597,7 +623,7 @@ func (l *layout) newPage() {
}
func (l *layout) report() Report {
- out := Report{}
+ out := Report{LayoutOverflow: l.layoutOverflow}
for r := range l.missing {
out.MissingRunes = append(out.MissingRunes, r)
}
@@ -809,6 +835,9 @@ func (l *layout) paragraph(content []Node, ctx blockContext, lineHeight float64)
}
maxWidth := contentWidthPt - ctx.indent
+ if maxWidth <= 0 {
+ l.layoutOverflow = true
+ }
var line []token
var lineWidth float64
@@ -926,6 +955,14 @@ func (l *layout) drawLine(line []token, ctx blockContext, lineHeight float64) {
// instead would put a right-aligned line's right edge an inch off
// the paper.
x := MarginPt + ctx.indent
+ var measuredWidth float64
+ for _, t := range line {
+ measuredWidth += t.width
+ }
+ // A tiny tolerance absorbs floating-point sums, not a visible glyph.
+ if measuredWidth > contentWidthPt-ctx.indent+0.001 {
+ l.layoutOverflow = true
+ }
if ctx.align != "" {
var lineWidth float64
for _, t := range line {