oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package chatmarkdown
2
3// This test-only projection observes Render/RenderDraft's HTML, not a second
4// interpretation of Markdown. Changing production output changes the goldens.
5import (
6 "bytes"
7 "encoding/json"
8 "fmt"
9 "math/rand/v2"
10 "os"
11 "path/filepath"
12 "regexp"
13 "strconv"
14 "strings"
15 "sync"
16 "testing"
17 "unicode/utf8"
18
19 xhtml "golang.org/x/net/html"
20 "golang.org/x/net/html/atom"
21)
22
23type nativeNode struct {
24 Kind string `json:"kind"`
25 Text string `json:"text,omitempty"`
26 Target string `json:"target,omitempty"`
27 Label string `json:"label,omitempty"`
28 Copy string `json:"copy,omitempty"`
29 Copied string `json:"copied,omitempty"`
30 Wrap bool `json:"wrap,omitempty"`
31 CopyEnabled *bool `json:"copyEnabled,omitempty"`
32 Children []nativeNode `json:"children"`
33}
34
35type nativeFixture struct {
36 Name string `json:"name"`
37 Source string `json:"source"`
38 Draft bool `json:"draft"`
39 Tree []nativeNode `json:"tree"`
40}
41
42func nativeLeaf(kind, text string) nativeNode {
43 return nativeNode{Kind: kind, Text: text, Children: []nativeNode{}}
44}
45func nativeAttr(n *xhtml.Node, key string) string {
46 for _, a := range n.Attr {
47 if a.Key == key {
48 return a.Val
49 }
50 }
51 return ""
52}
53func nativeText(n *xhtml.Node) string {
54 if n.Type == xhtml.TextNode {
55 return n.Data
56 }
57 var b strings.Builder
58 for c := n.FirstChild; c != nil; c = c.NextSibling {
59 b.WriteString(nativeText(c))
60 }
61 return b.String()
62}
63func nativeFind(n *xhtml.Node, tag string) *xhtml.Node {
64 if n.Type == xhtml.ElementNode && n.Data == tag {
65 return n
66 }
67 for c := n.FirstChild; c != nil; c = c.NextSibling {
68 if found := nativeFind(c, tag); found != nil {
69 return found
70 }
71 }
72 return nil
73}
74func nativeChildren(n *xhtml.Node) []nativeNode {
75 out := []nativeNode{}
76 for c := n.FirstChild; c != nil; c = c.NextSibling {
77 if c.Type == xhtml.TextNode && c.Data == "\n" && (n.Data == "div" || n.Data == "ul" || n.Data == "ol" || n.Data == "li" || c.PrevSibling != nil && c.PrevSibling.Data == "br") {
78 continue
79 }
80 if c.Type == xhtml.TextNode && c.PrevSibling != nil && (c.PrevSibling.Data == "br" || n.Data == "div" && c.PrevSibling.Type == xhtml.ElementNode) {
81 c.Data = strings.TrimPrefix(c.Data, "\n")
82 }
83 for _, next := range nativeWalk(c) {
84 if next.Kind == "text" && next.Text == "" {
85 continue
86 }
87 if next.Kind == "text" && len(out) > 0 && out[len(out)-1].Kind == "text" {
88 out[len(out)-1].Text += next.Text
89 } else {
90 out = append(out, next)
91 }
92 }
93 }
94 return out
95}
96func nativeWalk(n *xhtml.Node) []nativeNode {
97 if n.Type == xhtml.TextNode {
98 return []nativeNode{nativeLeaf("text", n.Data)}
99 }
100 if n.Type != xhtml.ElementNode {
101 return nil
102 }
103 if kind := nativeAttr(n, "equipo-paste"); kind != "" {
104 box := nativeLeaf("paste", nativeText(nativeFind(n, "pre")))
105 box.Wrap = kind == "prose"
106 bar := n.FirstChild
107 if span := nativeFind(bar, "span"); span != nil && nativeAttr(span, "equipo-paste-lang") == "" {
108 // Attribute presence matters: its HTML value is empty.
109 for _, a := range span.Attr {
110 if a.Key == "equipo-paste-lang" {
111 box.Label = nativeText(span)
112 }
113 }
114 }
115 button := nativeFind(bar, "button")
116 enabled := nativeAttr(button, "aria-disabled") != "true"
117 box.CopyEnabled = &enabled
118 box.Copied = nativeAttr(button, "data-copied")
119 for c := button.FirstChild; c != nil; c = c.NextSibling {
120 if nativeAttr(c, "equipo-paste-word") == "" {
121 for _, a := range c.Attr {
122 if a.Key == "equipo-paste-word" {
123 box.Copy = nativeText(c)
124 }
125 }
126 }
127 }
128 return []nativeNode{box}
129 }
130 kinds := map[string]string{"p": "paragraph", "em": "emphasis", "strong": "strong", "code": "code", "ul": "unordered", "ol": "ordered", "li": "item", "a": "link", "br": "break"}
131 if n.Data == "pre" {
132 return []nativeNode{nativeLeaf("codeBlock", nativeText(n))}
133 }
134 if kind := kinds[n.Data]; kind != "" {
135 node := nativeLeaf(kind, "")
136 if kind == "code" {
137 node.Text = nativeText(n)
138 } else {
139 node.Children = nativeChildren(n)
140 }
141 if kind == "link" {
142 node.Target = nativeAttr(n, "href")
143 }
144 return []nativeNode{node}
145 }
146 return nativeChildren(n)
147}
148
149var nativeWords Labels
150var nativeWordsOnce sync.Once
151
152func nativeLabels(t *testing.T) Labels {
153 nativeWordsOnce.Do(func() { nativeWords = readNativeLabels(t) })
154 return nativeWords
155}
156func readNativeLabels(t *testing.T) Labels {
157 t.Helper()
158 source, err := os.ReadFile(filepath.Join("..", "equipo", "copy.go"))
159 if err != nil {
160 t.Fatal(err)
161 }
162 words := map[string]string{}
163 for _, match := range regexp.MustCompile(`"chat\.paste\.(\w+)":\s*("(?:[^"\\]|\\.)*")`).FindAllSubmatch(source, -1) {
164 value, err := strconv.Unquote(string(match[2]))
165 if err != nil {
166 t.Fatal(err)
167 }
168 words[string(match[1])] = value
169 }
170 if len(words) != 6 {
171 t.Fatalf("expected all six paste-box labels, got %d", len(words))
172 }
173 return Labels{Copy: words["copy"], Copied: words["copied"], Selected: words["selected"], Prompt: words["prompt"], Text: words["text"], Command: words["command"]}
174}
175
176func nativeTree(t *testing.T, source string, draft bool) []nativeNode {
177 t.Helper()
178 words := nativeLabels(t)
179 rendered := words.Render(source)
180 if draft {
181 rendered = words.RenderDraft(source)
182 }
183 context := &xhtml.Node{Type: xhtml.ElementNode, Data: "div", DataAtom: atom.Div}
184 nodes, err := xhtml.ParseFragment(strings.NewReader(string(rendered)), context)
185 if err != nil {
186 t.Fatal(err)
187 }
188 for _, n := range nodes {
189 context.AppendChild(n)
190 }
191 return nativeChildren(context)
192}
193
194const phoneReply = "I found the cause and logged it as [Operator confirm page on oficina.works looks plainer than on id.oficina.works](/tasks/tkwkpraqeeer). Engineering is working on it now.\n\n**Why they look different:** the id.oficina.works page is shown in estilo's sign-in card on the sky. The oficina.works page never got that treatment, so it shows as a plain page. The fix moves it into the same card. The page's content stays the same.\n\nI've also put a hold on the merge, so it won't merge until you've seen it. I asked Engineering to include before and after screenshots so you can compare the two pages side by side."
195
196// Regenerate intentionally: EQUIPO_UPDATE_MARKDOWN=1 go test
197// ./internal/chatmarkdown -run '^TestNativeMarkdownFixtures$' -count=1.
198func TestNativeMarkdownFixtures(t *testing.T) {
199 inputs := append(append([]string{phoneReply}, corpus...), reviewInputs...)
200 inputs = append(inputs,
201 "[query](https://example.test/?q=%zz) [opaque](mailto:a%zz@example.test) [opaque](https:bad%zz) [fragment](https://example.test/#%zz)",
202 "[host](https://%41.example.test) [host](https://example.test:bad) [host](https://[::1]/) [bad](https://[127.0.0.1]/) [bad](https://[:::]/) [query](https://example.test/?q=%zz#valid)",
203 "[x](HTTPS://example.test) [x](mailto:a@example.test?subject=Hi) [bad](https://[broken) [bad](https://example.test/%zz)",
204 "[x](https://example.test/a\\_b) [x](https://example.test/a%20b) [x](https://example.test/a\\(b\\))",
205 "~~no strike~~ | no | table |\n| --- | --- |\n| a | b |\n\n- [x] no task control",
206 "***three*** ____four____ __outer _inner_ outer__ a***b***c \\*literal \\_literal \\`literal",
207 "` a b ` and `` a`b `` and `a\nb` and ``\n``",
208 "- fenced\n\n ```prompt\n nested prose\n ```\n\n> ~~~~sh\n> ls\n> ~~~~\n",
209 "<div>\nraw **text** &amp;\n</div>\n\n<!-- comment -->\n\n<scr",
210 "a\r\nb\r\n\r\n```text\r\n<raw>\r\n```\r\n",
211 "[nested **strong** and *em*](/tasks/tk1) ![image *alt*](https://example.test/a)",
212 "[x](/tasks/tk"+strings.Repeat("a", 33)+") [x](/projects/p_"+strings.Repeat("a", 41)+")",
213 "# Heading\n## Smaller\n\nsetext\n===\n\n---\n\n***\n\nend",
214 "***nested*** **outer *inner* end** *outer **inner** end* a_b_c &amp; &#x1F642; \\*escaped\\*",
215 "<script>alert(1)</script>\n\n<b>raw</b> <img src=x onerror=evil>\n\n![alt **words**](https://evil.test/x)",
216 "[task](/tasks/tk1) [project](/projects/p_abc123) [web](https://example.test/a?q=1&b=2) [mail](mailto:a@example.test)",
217 "[no](javascript:alert%281%29) [no](data:text/html,evil) [no](//evil.test) [no](/settings) [no](/tasks/tk1?a=b) [no](/tasks/tk1/../../logout)",
218 "[no](jav&#x61;script:evil) [no](/tasks/TK1) [no](tasks/tk1) [no](/\\\\evil.test) [yes](http://example.test)",
219 "<https://example.test> <a@example.test> [reference][id]\n\n[id]: /tasks/tk1",
220 "7. seven\n8. eight\n\n- loose\n\n paragraph\n\n - nested\n\n> quote\n>\n> second",
221 " indented\n <raw> &amp;\n\n```go\nif a < b {\n\tprint(\"&amp;\") \n}\n```",
222 "``````text\n``` inside\n`````\n``````\n\n~~~prompt\nwrap me\n~~~",
223 "CRLF\r\n\r\n**strong**\r\n\r\n```sh\r\nls\r\n```\r\n",
224 "Para **open\n\nNext", "2 * 3", "it*", "a**b", "`one``two", "See [partial](/tasks/tk1", "Code `a[b`",
225 "- **Guest:** a\n- **", "1. owner\n2", "Text\n--", "## Pl", "## **open\n", "soft\nbreak \nhard\\\nbreak",
226 )
227 for _, lang := range []string{"", "prompt", "PROMPT", "text", "Text", "bash", "sh", "zsh", "shell", "console", "Bash", "go", "Python", "c++", "c#", ".env", "objective-c", "<script>", "a&amp;b", "a\"onmouseover=x", "-x", "é", strings.Repeat("a", 25)} {
228 inputs = append(inputs, "```"+lang+"\nx & <y>\n```\n")
229 }
230 for _, label := range []string{"", "a", "ab", "prompt", "sh"} {
231 for _, before := range []string{"", " ", "\t"} {
232 for _, after := range []string{"", " ", "\t", "\r"} {
233 inputs = append(inputs, "```"+before+label+after)
234 }
235 }
236 }
237 inputs = append(inputs, "`*_test.go", "`a_b_c", "`resizeReply(_:)", "`[text](url)", "`![alt](src)")
238 fixtures := []nativeFixture{}
239 for i, s := range inputs {
240 for _, draft := range []bool{false, true} {
241 fixtures = append(fixtures, nativeFixture{fmt.Sprintf("case-%03d-%t", i, draft), s, draft, nativeTree(t, s, draft)})
242 }
243 }
244 streams := append([]string{phoneReply}, corpus...)
245 streams = append(streams, "Glob `**/*.go`", "a \\*escaped* and `a\\`b`", ">*word", "```prompt")
246 streams = append(streams, "Intro\r\n\r\n```sh\r\nls\r\n```\r\n", "````prompt\n``` inside\n````\n", "- nested\n ~~~~text\n body\n ~~~~\n", "***nested*** and \\*literal* and `a[b`.")
247 for _, prefix := range []string{"", ">", "> ", "- ", "a ", "a\\", "a\\\\"} {
248 for _, span := range []string{"*word", "**word", "`**/*.go`", "\\*word*", "*a\\*b*", "`a\\`b`", "a_\\_b", "[a\\]b](/tasks/tk1)"} {
249 streams = append(streams, prefix+span)
250 }
251 }
252 streams = append(streams, "`*_test.go`", "`a_b_c`", "`resizeReply(_:)`", "`[text](url)`", "`![alt](src)`")
253 for i, s := range streams {
254 for cut := 0; cut <= len(s); cut++ {
255 if cut < len(s) && !utf8.RuneStart(s[cut]) {
256 continue
257 }
258 fixtures = append(fixtures, nativeFixture{fmt.Sprintf("stream-%d-%04d", i, cut), s[:cut], true, nativeTree(t, s[:cut], true)})
259 }
260 }
261 var encoded bytes.Buffer
262 encoded.WriteString("[\n")
263 for i, fixture := range fixtures {
264 data, err := json.Marshal(fixture)
265 if err != nil {
266 t.Fatal(err)
267 }
268 if i > 0 {
269 encoded.WriteString(",\n")
270 }
271 encoded.Write(data)
272 }
273 encoded.WriteString("\n]\n")
274 data := encoded.Bytes()
275 path := filepath.Join("..", "..", "native", "apple", "Tests", "EquipoKitTests", "Fixtures", "markdown", "golden.json")
276 if os.Getenv("EQUIPO_UPDATE_MARKDOWN") == "1" {
277 if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
278 t.Fatal(err)
279 }
280 if err := os.WriteFile(path, data, 0644); err != nil {
281 t.Fatal(err)
282 }
283 }
284 held, err := os.ReadFile(path)
285 if err != nil {
286 t.Fatal(err)
287 }
288 if !bytes.Equal(held, data) {
289 t.Fatal("native markdown fixtures differ from Render/RenderDraft; regenerate and check Swift parity")
290 }
291 t.Logf("%d native markdown cases", len(fixtures))
292}
293
294// Every review reproduction is kept independently of the generated grammar.
295var reviewInputs = []string{
296 "```ts\nconst a = 1\n\nfoo[i](<T<U>>x)\n```\n",
297 "[x](< HTTPS:>)", "[x](<\thttp://b>)", "```prompt", "```ab",
298 "= \n]", "paragraph\n<div>raw</div>", "a\rb", "- one\r- two",
299 "Glob `**/*.go`", "\\*escaped*", ">*word",
300
301 `[good](https://good.test/x "](https://evil.test)")`,
302 `[good](https://good.test/x?value=](https://evil.test))`,
303
304 "[x](https://[fe80::1%25eth0]/) [x](https://[fe80::1%25]/) [x](<https://[fe80::1%25bad zone]/>) [x](https://[fe80::1%25a%20b]/) [x](https://[fe80::1%25a%2fb]/)",
305 "```go\tlinenos\nx\n```\n", "```&#103;o\nx\n```\n", "```go\u00a0extra\nx\n```\n",
306 "[x](https://x/?q=&#38;amp;) [x](https://x/?q=&notarealentity;) [x](https://x/?q=&#0000000000038;)",
307 "&#38;amp; &#010; &#08; &#x00000000041; &#128; &#13; &notarealentity;",
308
309 strings.Repeat("> ", 1000) + "x",
310 "```sh\n[x](<<>)\n```\n", "<div>[x](<<>)</div>",
311 strings.Repeat("~", 300) + "sh\nx\n" + strings.Repeat("~", 299) + "\n",
312 strings.Repeat("`", 300) + "sh\nx\n" + strings.Repeat("`", 300) + "\n",
313 "[x](file:/tmp/x) [x](ftp://x) [x](tel:1) [x](sms:1) [x](blob:https://x) [x](vbscript:x) [x](custom:x)",
314 "[x](//x) [x](///x) [x](https://x@evil.test) [x](https://x:bad) [x](https://x\\evil.test)",
315 "Here is the plan:\n run `make ci` first.",
316 "- Deploy steps\n run `make deploy` after `make ci`",
317 "Here:\n [good](https://good.test/x) [bad](https://evil.test)",
318 "```md\nUse this:\n ```\n", "- item\n ```md\n Use this:\n ```\n",
319 "✅**[Fix](/tasks/tk1)**", "€**bold**", "```b", "\\&amp;amp;",
320 "- one\r\n- two\r\n", "`a\r\nb`", "[x](<<>)",
321 "[x](https://\";@)", "[x](http://&#10)", "[x](http://])",
322 "[x](https://example.test/?from=1&timestamp=2&region=us)",
323 "[x](\u2028https://example.test)", "[x](\u0085https://example.test)",
324 "<div>raw</div>", "<div>raw</div>\n", "<!-- x -->\n\nnext",
325}
326
327// A fixed seed and an unfiltered grammar: both completed messages and random
328// Unicode-safe streaming cuts. The generated artifact is not checked in.
329func TestNativeMarkdownDifferential(t *testing.T) {
330 path := os.Getenv("EQUIPO_MARKDOWN_DIFFERENTIAL")
331 if path == "" {
332 t.Skip("set EQUIPO_MARKDOWN_DIFFERENTIAL to generate the Swift differential corpus")
333 }
334 r := rand.New(rand.NewPCG(0x45515549504f, 0x4d41524b444f574e))
335 words := []string{"words", "✅", "€", "£", "🙂", "a_b", "&amp;", "&amp;amp;", "&timestamp=2&region=us", "&#10;", "\\&amp;amp;", "&#38;amp;", "&#010;", "&#08;", "&#128;", "&#13;", "\u2028", "\u0085"}
336 targets := []string{"/tasks/tk1", "/projects/p_abc", "/settings", "https://good.test/x", "https://evil.test", "http://]", "https://\";@", "http://&#10", "https://x/?from=1&timestamp=2&region=us", "https://x/a\\_b", "https://x/%zz", "https://%41.test", "http://[:::]", "//example.test", "///tasks/tk1", "file:/tmp/x", "ftp://x", "tel:1", "sms:1", "blob:https://x", "vbscript:x", "custom:x", "javascript:x", "mailto:a@b.test", "https:opaque%zz", "https://x/#%zz", "<<>", "\u2028https://x", "\u0085https://x"}
337 pick := func(a []string) string { return a[r.IntN(len(a))] }
338 var out bytes.Buffer
339 out.WriteString("[\n")
340 unique := map[string]bool{}
341 count := 0
342 for i := 0; count < 32000; i++ {
343 w, target := pick(words), pick(targets)
344 if r.IntN(2) == 0 {
345 w += pick([]string{"", " ", "\t"}) + pick(words)
346 }
347 if r.IntN(3) == 0 {
348 target += pick([]string{"?case=", "#"}) + strconv.Itoa(r.IntN(65536))
349 }
350 var s string
351 switch i % 21 {
352 case 0:
353 s = "[" + w + "](" + target + ")"
354 case 1:
355 s = w + "**[Fix](" + target + ")** end"
356 case 2:
357 s = "Plan:\n" + strings.Repeat(" ", r.IntN(7)) + "run `" + w + "` and [x](" + target + ")"
358 case 3:
359 s = "- Deploy\n" + strings.Repeat(" ", r.IntN(7)) + "run `" + w + "` after `make ci`"
360 case 4:
361 s = pick([]string{"*", "**", "_", "__", "***"}) + w + pick([]string{"*", "**", "_", "__", "***"})
362 case 5:
363 s = "```" + pick([]string{"sh", "text", "prompt", "b", ""}) + "\n" + w + "\n" + strings.Repeat(" ", r.IntN(6)) + "```\n"
364 case 6:
365 s = "[" + w + "][ref]\n\n[ref]: " + target
366 case 7:
367 s = strings.Repeat("> ", r.IntN(15)) + w + " **bold**"
368 case 8:
369 for j := 0; j < 1+r.IntN(8); j++ {
370 s += strings.Repeat(" ", j) + "- " + w + "\n"
371 }
372 case 9:
373 s = pick([]string{"<div>", "<!-- ", "<b>"}) + w + pick([]string{"</div>", " -->", "</b>"}) + pick([]string{"", "\n", "\n\nnext"})
374 case 10:
375 s = "`` " + w + "\nnext `` and " + w
376 case 11:
377 s = pick(reviewInputs) + "\n\n" + w
378 case 12:
379 s = "[" + w + "](<" + pick([]string{" ", "\t", "\r", ""}) + target + pick([]string{" ", "\t", ""}) + ">)"
380 case 13:
381 s = "```" + pick([]string{"a", "ab", "prompt", "text", "sh", "go", ""}) + pick([]string{"", " ", "\t"}) + w
382 case 14:
383 s = w + pick([]string{" ", "\t", " ", " \t"}) + "\n] " + target
384 case 15:
385 s = w + "\n<div>" + target + "</div>"
386 case 16:
387 s = "[" + w + "][ref]\n\n[ref]: <" + pick([]string{" ", "\t", ""}) + target + ">"
388 case 17:
389 s = pick([]string{"Glob `**/*.go`", "\\*escaped*", ">*word", "a `a\\`b`", "**a\\*b**"}) + " " + w
390 case 20:
391 s = pick([]string{"", "Before ", "> ", "- "}) + "`" + pick([]string{"", "!"}) + "[" + w + "](" + pick([]string{"url", "/tasks/tk1", "https://example.test", "src"}) + pick([]string{"", ")", ") after", ")`"})
392 case 19:
393 s = pick([]string{"", "See ", "> ", "- "}) + "`" + pick([]string{"*", "_", "**", "__", "a_", "a*", "resizeReply("}) + pick([]string{"_test.go", "b_c", "*word", "_:)", "a_b_c", "*a_b*", "**/*.go"}) + pick([]string{"", "`", " " + w, "\\_"})
394 case 18:
395 s = "```ts\n" + w + "\n\nfoo[i](<T<U>>x)\n```\n"
396
397 }
398 switch r.IntN(5) {
399 case 0:
400 s = strings.ReplaceAll(s, "\n", "\r\n")
401 case 1:
402 s = strings.ReplaceAll(s, "\n", "\r")
403 }
404 draft := r.IntN(2) == 1
405 if draft && r.IntN(2) == 0 {
406 runes := []rune(s)
407 s = string(runes[:r.IntN(len(runes)+1)])
408 }
409 if unique[s] {
410 continue
411 }
412 unique[s] = true
413 f := nativeFixture{fmt.Sprintf("seed-%05d", count), s, draft, nativeTree(t, s, draft)}
414 b, err := json.Marshal(f)
415 if err != nil {
416 t.Fatal(err)
417 }
418 if count > 0 {
419 out.WriteString(",\n")
420 }
421 out.Write(b)
422 count++
423 }
424 out.WriteString("\n]\n")
425 if err := os.WriteFile(path, out.Bytes(), 0644); err != nil {
426 t.Fatal(err)
427 }
428 t.Logf("%d seeded differential cases", count)
429}
430