From 220a92f970231f22aa79fff1827770cc7ec2a813 Mon Sep 17 00:00:00 2001 From: Thomas Stokes Date: Tue, 18 Mar 2025 23:12:02 +0800 Subject: [PATCH] initial ssr support (#43) --- build.sh | 20 ++-- package-lock.json | 106 ++++++++++++++++++ package.json | 11 ++ src/html.server.ts | 274 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 403 insertions(+), 8 deletions(-) create mode 100644 src/html.server.ts diff --git a/build.sh b/build.sh index 61ff512..61a8aff 100755 --- a/build.sh +++ b/build.sh @@ -2,13 +2,17 @@ mkdir -p dist -esbuild src/html.js --bundle --minify --format=esm --define:DHTML_PROD=true --mangle-props=^_ --drop:console --drop-labels=DEV | -terser --mangle --compress --module --output dist/html.min.js -printf "min: %d bytes\n" "$(wc -c dist/html.min.js.gz -printf "gzip: %d bytes\n" "$(wc -c dist/$1.min.js.gz + printf "gzip: %d bytes\n" "$(wc -c dist/html.min.js.br -printf "brotli: %d bytes\n" "$(wc -c dist/$1.min.js.br + printf "brotli: %d bytes\n" "$(wc -c =0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", @@ -1740,6 +1813,19 @@ "dev": true, "license": "MIT" }, + "node_modules/entities": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.0.tgz", + "integrity": "sha512-aKstq2TDOndCn4diEyp9Uq/Flu2i1GlLkc6XIDQSDMuaFE3OPW5OphLCyQ5SpSJZTb4reN+kTcYru5yIfXoRPw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-module-lexer": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.6.0.tgz", @@ -1960,6 +2046,26 @@ "dev": true, "license": "MIT" }, + "node_modules/htmlparser2": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.0.0.tgz", + "integrity": "sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==", + "dev": true, + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.1", + "entities": "^6.0.0" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", diff --git a/package.json b/package.json index 658de83..2344d54 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,16 @@ "name": "dhtml", "type": "module", "main": "src/html.js", + "exports": { + ".": { + "production": "./dist/html.min.js", + "default": "./src/html.js" + }, + "./server": { + "production": "./dist/html.server.min.js", + "default": "./src/html.server.js" + } + }, "scripts": { "build": "./build.sh", "format": "prettier --write . --cache", @@ -16,6 +26,7 @@ "@vitest/ui": "^3.0.5", "dhtml": ".", "esbuild": "^0.24.0", + "htmlparser2": "^10.0.0", "playwright": "^1.50.1", "prettier": "^3.4.2", "terser": "^5.37.0", diff --git a/src/html.server.ts b/src/html.server.ts new file mode 100644 index 0000000..7cb58fb --- /dev/null +++ b/src/html.server.ts @@ -0,0 +1,274 @@ +import type { Displayable, Renderable } from './types.ts' +import { Tokenizer } from 'htmlparser2' + +function isRenderable(value: unknown): value is Renderable { + return typeof value === 'object' && value !== null && 'render' in value +} + +function isIterable(value: unknown): value is Iterable { + return typeof value === 'object' && value !== null && Symbol.iterator in value +} + +export function html(statics: TemplateStringsArray, ...dynamics: unknown[]) { + return new BoundTemplateInstance(statics, dynamics) +} + +const singlePartTemplate = (part: Displayable) => html`${part}` + +/* v8 ignore start */ +function assert(value: unknown, message = 'assertion failed'): asserts value { + if (!value) throw new Error(message) +} +/* v8 ignore stop */ + +type PartRenderer = (values: unknown[]) => string | Generator + +interface CompiledTemplate { + statics: string[] + parts: PartRenderer[] +} + +class BoundTemplateInstance { + #template: CompiledTemplate | undefined + #statics: TemplateStringsArray + dynamics: unknown[] + + get template() { + return (this.#template ??= compileTemplate(this.#statics)) + } + + constructor(statics: TemplateStringsArray, dynamics: unknown[]) { + this.#statics = statics + this.dynamics = dynamics + } +} + +const WHITESPACE_WHOLE = /^\s+$/ +const DYNAMIC_WHOLE = /^dyn-\$(\d+)\$$/i +const DYNAMIC_GLOBAL = /dyn-\$(\d+)\$/gi + +const templates = new WeakMap() +function compileTemplate(statics: TemplateStringsArray): CompiledTemplate { + const cached = templates.get(statics) + if (cached) return cached + + const html = statics.reduce((a, v, i) => a + v + (i === statics.length - 1 ? '' : `dyn-$${i}$`), '') + const parts: { + start: number + end: number + render: PartRenderer + }[] = [] + let attribname: [start: number, end: number] | null = null + function noop() {} + + const tokenizer = new Tokenizer( + {}, + { + onattribname(start, end) { + const name = html.slice(start, end) + const match = name.match(DYNAMIC_WHOLE) + if (match) { + const idx = parseInt(match[1]) + parts.push({ start, end, render: values => renderDirective(values[idx]) }) + return + } + + assert(!DYNAMIC_GLOBAL.test(name), `expected a whole dynamic value for ${name}, got a partial one`) + + attribname = [start, end] + }, + onattribdata(start, end) { + assert(attribname) + + const [nameStart, nameEnd] = attribname + const name = html.slice(nameStart, nameEnd) + const value = html.slice(start, end) + + const match = value.match(DYNAMIC_WHOLE) + if (match) { + const idx = parseInt(match[1]) + parts.push({ start: nameStart, end, render: values => renderAttribute(name, values[idx]) }) + return + } + + assert(!DYNAMIC_GLOBAL.test(value), `expected a whole dynamic value for ${name}, got a partial one`) + }, + onattribentity: noop, + onattribend() { + attribname = null + }, + + onopentagname(start, end) {}, + onopentagend() {}, + onclosetag(start, end) {}, + onselfclosingtag: noop, + + ontext(start, end) { + const value = html.slice(start, end) + + for (const match of [...value.matchAll(DYNAMIC_GLOBAL)]) { + const idx = parseInt(match[1]) + parts.push({ + start: start + match.index, + end: start + match.index + match[0].length, + render: values => renderChild(values[idx]), + }) + } + + if (WHITESPACE_WHOLE.test(value)) { + parts.push({ start, end, render: () => ' ' }) + return + } + }, + ontextentity: noop, + + oncomment(start, end) { + const value = html.slice(start, end) + + for (const match of [...value.matchAll(DYNAMIC_GLOBAL)]) { + const idx = parseInt(match[1]) + parts.push({ + start: start + match.index, + end: start + match.index + match[0].length, + render: values => escape(values[idx]), + }) + } + }, + + oncdata(start, end) {}, + ondeclaration(start, end) {}, + onprocessinginstruction(start, end) {}, + + onend: noop, + }, + ) + + tokenizer.write(html) + tokenizer.end() + + const compiled: CompiledTemplate = { + statics: [], + parts: [], + } + + compiled.statics.push(html.slice(0, parts[0]?.start)) + + for (let i = 0; i < parts.length; i++) { + const part = parts[i] + const nextPart = parts[i + 1] + compiled.parts.push(part.render) + compiled.statics.push(html.slice(part.end, nextPart?.start)) + } + + templates.set(statics, compiled) + return compiled +} + +function renderDirective(value: unknown) { + if (value === null) return '' + + assert(typeof value === 'function') + console.log('directive returned:', value()) + + return '' +} + +function renderAttribute(name: string, value: unknown) { + if (value === false || value === null || typeof value === 'function') { + return '' + } + if (value === true) return name + return `${name}="${escape(value)}"` +} + +function* renderChild(value: unknown) { + const seen = new Set() + + while (isRenderable(value)) + try { + if (seen.has(value)) throw new Error('circular render') + seen.add(value) + value = value.render() + } catch (thrown) { + if (thrown instanceof BoundTemplateInstance) { + value = thrown + } else { + throw thrown + } + } + + if (isIterable(value)) { + for (const item of value) yield* renderToIterable(item as Displayable) + } else if (value instanceof BoundTemplateInstance) { + yield* renderToIterable(value) + } else if (value !== null) { + yield escape(value) + } +} + +const ESCAPE_RE = /[&<>"']/g +const ESCAPE_SUBSTITUTIONS = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', +} +function escape(str: unknown) { + return String(str).replace(ESCAPE_RE, c => ESCAPE_SUBSTITUTIONS[c]) +} + +function* renderToIterable(value: Displayable) { + const { template, dynamics } = value instanceof BoundTemplateInstance ? value : singlePartTemplate(value) + + for (let i = 0; i < template.statics.length - 1; i++) { + yield template.statics[i] + yield* template.parts[i](dynamics) + } + yield template.statics[template.statics.length - 1] +} + +export function renderToString(value: Displayable) { + let str = '' + for (const part of renderToIterable(value)) str += part + return str +} + +export function renderToReadableStream(value: Displayable) { + const iter = renderToIterable(value)[Symbol.iterator]() + return new ReadableStream({ + pull(controller) { + const { done, value } = iter.next() + if (done) { + controller.close() + return + } + controller.enqueue(value) + }, + }) +} + +// { +// const displayable = html` +// +//

a${'text'}b

+// {}}> +// +// +// ${{ +// render() { +// return html`
${[1, 2, 3]}
` +// }, +// }} +// ${html`[${'A'}|${'B'}]`} +// ` + +// const stream = renderToReadableStream(displayable).pipeThrough(new TextEncoderStream()) + +// new Response(stream).text().then(rendered => { +// console.log(rendered) +// console.log(rendered === renderToString(displayable)) +// }) +// } -- knotmirror 0.0.1