Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251// Words drops raw HTML, so markdown.ts writes tag-shaped text as `<`// first; a mistake there either loses text a model wrote or lets markup// through. Render generated Markdown through the real Words build and check// both, and that splitting a document into blocks changes nothing else.import assert from 'node:assert/strict';import { readFile } from 'node:fs/promises';import { stripTypeScriptTypes } from 'node:module';import test from 'node:test';import { createHtmlRenderer } from '@pierre/words/html';import { check, fc } from './property.mjs';
const source = stripTypeScriptTypes( await readFile(new URL('../src/lib/markdown.ts', import.meta.url), 'utf8'),).replace( /from '(@pierre\/words\/[\w-]+)'/g, (_, name) => `from '${import.meta.resolve(name)}'`,);const { prepareMarkdown, preparer, markdownOptions, documentHtml } = await import( `data:text/javascript;base64,${Buffer.from(source).toString('base64')}` );
function words(prepared, text, streaming = false) { const formatter = createHtmlRenderer(markdownOptions(text, 't-')); const html = formatter.render(prepared, streaming, streaming).html; formatter.dispose(); return html;}const render = (text, streaming = false) => words(prepareMarkdown(text, streaming), text, streaming);
const decode = (text) => text.replace( /&(lt|gt|quot|#39|amp);/g, (_, name) => ({ lt: '<', gt: '>', quot: '"', '#39': "'", amp: '&' })[name], );// The code header's language label is hidden (Markdown.svelte).const visible = (html) => decode( html .replace(/<div data-markdown="code-header">.*?<\/div>/g, '') .replace(/<[^>]*>/g, ''), );
// What Words and the hooks in markdown.ts make; anything else came from the text.const TAGS = new Set( 'p h1 h2 h3 h4 h5 h6 em strong del code pre span div a ul ol li input table thead tbody tr th td blockquote hr br sup section button svg g text rect path line polyline polygon'.split( ' ', ),);const ATTRIBUTES = new Set( 'data-markdown data-incomplete data-markdown-incomplete data-streaming data-language data-code data-meta data-code-action data-footnotes data-footnote-ref data-footnote-backref data-footnote-backref-idx class id href target rel type checked disabled readonly start style dir aria-label aria-hidden role xmlns width height viewbox fill color font-family font-size font-style font-weight x y x1 y1 x2 y2 d points stroke stroke-width transform'.split( ' ', ),);
function markup(html) { const problems = []; for (const [, name, attributes] of html.matchAll( /<([A-Za-z][\w-]*)([^>]*)>/g, )) { if (!TAGS.has(name.toLowerCase())) problems.push(`<${name}>`); for (const [, attribute, value = ''] of attributes.matchAll( /([^\s=]+)(?:="([^"]*)")?/g, )) { if (!ATTRIBUTES.has(attribute.toLowerCase())) problems.push(`${name} ${attribute}`); if (attribute === 'href' && !/^(?:https?:|mailto:|#)/.test(decode(value))) problems.push(`href ${value}`); } } return problems;}
// Pieces models write: prose, tags in and out of code and maths, fences and// both maths delimiters. No brackets or colons, so no link or autolink takes// a `<` into an address; single spaces, so nothing turns into indented code;// and a fence ends its line, since its info string is never shown.const piece = fc.constantFrom( 'word', 'Vec<String>', '<think>', '</think>', '<b>bold</b>', '<div class="x">', '<!-- note -->', '<script>alert(1)</script>', '<img src=x onerror=alert(1)>', '<details>', '<?xml?>', 'x<y', 'a < b', '`', '``', '`<b>`', '$', '$$', '$x<y$', '\\(', '\\)', '\\(a<b\\)', '\\[', '\\]', '\\', '```\n', '```js\n', '~~~\n', '- ', '> ', '# ', '| a | b |', '|---|---|', '**', '_', '1. ', ' ', '\n', '\n\n',);const markdown = fc .array(piece, { maxLength: 40 }) .map((pieces) => pieces.join('')) .filter((text) => !/^[\s>\d.*+-]*(?:`{3,}|~{3,})[^\n]*</m.test(text));
// Links and images, safe and not, for the hooks that check addresses.const linked = fc .array( fc.oneof( piece, fc.constantFrom( '[x](https://a.example/)', '[x](javascript:alert(1))', '[x](/relative)', '[x](//evil.example)', '', ')', '', '<https://a.example>', 'www.a.example', 'me@a.example', '[x][r]', '\n\n[r]: data:text/html,hi\n', 'note[^1]', '\n\n[^1]: the note\n', ), ), { maxLength: 30 }, ) .map((pieces) => pieces.join(''));
test('rendered text holds only markup Words makes, safe links and no images', () => { check( fc.property(linked, fc.boolean(), (text, streaming) => { const html = render(text, streaming); assert.deepEqual(markup(html), []); for (const [link] of html.matchAll(/<a [^>]*href="(?!#)[^>]*>/g)) assert.match(link, /target="_blank" rel="noopener noreferrer"/); }), 300, );});
test('every tag-shaped character a model wrote still shows', () => { check( fc.property(markdown, (text) => { const count = (value) => value.split('<').length - 1; assert.equal(count(visible(render(text))), count(text), render(text)); }), 300, );});
test('a reply prepared delta by delta ends as the whole reply prepared at once', () => { check( fc.property( markdown, fc.array(fc.integer({ min: 1, max: 40 }), { minLength: 1, maxLength: 20, }), (text, steps) => { const prepare = preparer(); for ( let at = 0, step = 0; at < text.length; at += steps[step++ % steps.length] ) prepare(text.slice(0, at), true); assert.equal(words(prepare(text, false), text), render(text)); }, ), );});
// Documents of blocks separated by blank lines, some of them lists and fences.const block = fc.oneof( fc.constantFrom( 'a paragraph\nthat wraps', '# heading', '> a quote', '| a | b |\n|---|---|\n| 1 | 2 |', '$$\nx^2\n$$', 'see [the docs][d]', ), fc .integer({ min: 1, max: 3 }) .map((n) => Array.from({ length: n }, (_, i) => `- item ${i}`).join('\n')), fc .integer({ min: 1, max: 3 }) .map( (n) => '```\n' + Array.from({ length: n }, () => 'code\n\nmore').join('\n') + '\n```', ),);const document = fc .array(block, { minLength: 1, maxLength: 8 }) .map((blocks) => blocks.join('\n\n') + '\n\n[d]: https://example.com\n');
test('a document split into blocks renders as the whole document does', () => { check( fc.property(document, (text) => { const blocks = documentHtml(text, new Set(), 't-'); const unwrapped = blocks.replace( /<div class="block[^"]*" data-from="\d+" data-to="\d+">|<\/div>(?=<div class="block|$)/g, '', ); assert.equal(unwrapped, render(text).replaceAll('t-', 't-')); }), );});
test('a changed line marks the block holding it', () => { const text = '# title\n\nfirst paragraph\n\n- one\n- two\n\n```\ncode\n\ncode\n```\n'; const marked = (line) => [ ...documentHtml(text, new Set([line])).matchAll( /class="block( changed)?" data-from="(\d+)" data-to="(\d+)"/g, ), ] .filter((m) => m[1]) .map((m) => `${m[2]}-${m[3]}`); assert.deepEqual(marked(1), ['1-1']); assert.deepEqual(marked(3), ['3-3']); assert.deepEqual(marked(6), ['5-6']); assert.deepEqual(marked(10), ['8-12']); assert.deepEqual(marked(2), []);});