From 7d398e2dc9901441a0c6698c0da4b37ecc884d9c Mon Sep 17 00:00:00 2001 From: jherr Date: Wed, 2 Dec 2026 08:49:08 -0800 Subject: [PATCH 1/3] feat(core): add tree-shakeable @tanstack/cms-core/read (edge read+render, no engine) Pre-publication: free to restructure (see AGENTS.md). New /read entry is self-contained (4KB, no config/schema/server/pglite/ai/mcp/node:*), providing block/markdown renderers + a minimal ReadStore query API for edge deploys. Refs #63. --- AGENTS.md | 31 +++++++ packages/core/package.json | 5 ++ packages/core/src/read.ts | 157 +++++++++++++++++++++++++++++++++ packages/core/tsdown.config.ts | 1 + 4 files changed, 194 insertions(+) create mode 100644 AGENTS.md create mode 100644 packages/core/src/read.ts diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..8ebe1cc4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,31 @@ +# AGENTS — TanStack CMS monorepo + +## Status: pre-publication — restructure freely + +This library is **pre-publication**. None of the `@tanstack/cms-*` / `@tanstack/search-*` +packages are on npm, and **nothing outside this repo depends on them**. That means: + +- **Break public APIs at will.** Rename, move, split, merge, or delete modules, + exports, entry points, and types whenever it makes the design better. No + backward-compatibility burden, no deprecation cycles, no changesets required + for consumer-facing breaks. +- **Reshape package boundaries freely** — new entry points (e.g. a tree-shakeable + `/read` surface), new packages, re-layering of `core` internals, etc. +- The only bar is **internal consistency**: the monorepo must still build and its + tests must pass after a change. Update all in-repo call sites (apps, examples, + starters) as part of the same change. + +Don't preserve an awkward API out of compat fear — spindle, fold, and mutilate +as needed, then make the whole repo green. + +## Architectural direction (edge-first reads) + +Deploying to edge runtimes (e.g. Kody/workerd) proved that the **read/render +path must be tree-shakeable to a tiny bundle with no server engine** — no +`@tanstack/cms-core/server` barrel, no embedded PGlite (WASM/eval), no AI / +code-mode / MCP, no `node:*`. See issues #63 (edge-read refactor) and #64 (Kody +platform ask for the write/admin engine). Target split: + +- **read path** (public pages): pure query + renderers, edge-deployable. +- **write / admin / migrate path**: the heavy engine, runs on a warm/Node-ish + runtime, never in the hot read worker. diff --git a/packages/core/package.json b/packages/core/package.json index 242c8173..8cd79293 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -22,6 +22,7 @@ "exports": { ".": "./src/index.ts", "./definition": "./src/definition.ts", + "./read": "./src/read.ts", "./server": "./src/server.ts", "./flags": "./src/flags.ts", "./storage": "./src/storage.ts", @@ -49,6 +50,10 @@ "types": "./dist/definition.d.ts", "import": "./dist/definition.js" }, + "./read": { + "types": "./dist/read.d.ts", + "import": "./dist/read.js" + }, "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" diff --git a/packages/core/src/read.ts b/packages/core/src/read.ts new file mode 100644 index 00000000..6ecca766 --- /dev/null +++ b/packages/core/src/read.ts @@ -0,0 +1,157 @@ +/** + * `@tanstack/cms-core/read` — the tree-shakeable read + render surface for + * public pages on any runtime, including the edge (Kody/workerd, Cloudflare + * Workers, etc.). + * + * This module is deliberately **self-contained**: it imports nothing from + * `config`, `schema`, `server`, the storage engine, AI/MCP/code-mode, or + * `node:*`. That is what lets a public site bundle to a few KB with no WASM, + * no `eval`, and no server engine. The write/admin/migrate engine + * (`@tanstack/cms-core/server`) is a separate, heavier world; this is the half + * a blog, docs site, or marketing site needs to render. + */ + +// --- Document shape ------------------------------------------------------- + +/** A stored document's content (the `doc` JSONB in the CMS schema). */ +export type Doc = Record + +/** A content block: `{ _type, ...fields }`. */ +export type Block = { _type?: string; [key: string]: unknown } + +/** A document as returned from a store: its id + content. */ +export interface ReadRecord { + id: string + collection?: string + doc: Doc +} + +const asString = (v: unknown): string => (typeof v === 'string' ? v : '') + +export function isPublished(doc: Doc | null | undefined): boolean { + return !!doc && doc.published !== false +} + +// --- HTML + markdown primitives ------------------------------------------- + +export function escapeHtml(value: unknown): string { + return asString(value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') +} + +/** + * Intentionally tiny markdown: blank-line paragraphs, `**bold**`, `` `code` ``. + * Enough for block/body text without pulling a markdown dependency into an edge + * bundle. Swap in a full renderer app-side if you need one. + */ +export function renderMarkdown(text: string): string { + return asString(text) + .split(/\n{2,}/) + .filter((p) => p.trim()) + .map((p) => { + const inner = escapeHtml(p) + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/`([^`]+)`/g, '$1') + return `

${inner}

` + }) + .join('') +} + +// --- Block rendering ------------------------------------------------------ + +export interface RenderContext { + escapeHtml: (v: unknown) => string + renderMarkdown: (text: string) => string +} + +export type BlockRenderer = (block: Block, ctx: RenderContext) => string + +/** Renderers for the built-in block palette → semantic, unstyled HTML. */ +export const defaultBlockRenderers: Record = { + hero: (b, c) => + `

${c.escapeHtml(b.heading)}

${ + asString(b.subheading) ? `

${c.escapeHtml(b.subheading)}

` : '' + }
`, + richText: (b, c) => c.renderMarkdown(asString(b.markdown)), + quote: (b, c) => + `

${c.escapeHtml(b.text)}

${ + asString(b.attribution) ? `${c.escapeHtml(b.attribution)}` : '' + }
`, + image: (b, c) => + asString(b.image) + ? `
${c.escapeHtml(b.caption)}${ + asString(b.caption) ? `
${c.escapeHtml(b.caption)}
` : '' + }
` + : '', + cta: (b, c) => + `

${ + c.escapeHtml(b.label) || c.escapeHtml(b.heading) + }

`, + callout: (b, c) => + ``, + code: (b, c) => `
${c.escapeHtml(b.code)}
`, +} + +const DEFAULT_CTX: RenderContext = { escapeHtml, renderMarkdown } + +/** + * Render an array of blocks to an HTML string. Pass `renderers` to override or + * extend the built-ins (merged over the defaults); unknown block types render + * to empty string. + */ +export function renderBlocks( + blocks: ReadonlyArray | unknown, + renderers: Record = {}, + ctx: RenderContext = DEFAULT_CTX, +): string { + if (!Array.isArray(blocks)) return '' + const map = { ...defaultBlockRenderers, ...renderers } + return (blocks as Array) + .map((b) => (b && map[String(b._type)] ? map[String(b._type)](b, ctx) : '')) + .join('') +} + +// --- Reading published documents ------------------------------------------ + +/** + * The minimal read surface the helpers below need. Implement it over whatever + * store you like — the full `@tanstack/cms-core/server` storage adapter + * satisfies it, and so does a ~10-line edge adapter over a serverless Postgres + * HTTP driver. Keeping it this small is what keeps the engine out of the bundle. + */ +export interface ReadStore { + getDocument: (collection: string, id: string) => Promise + queryDocuments: (query: { + collections: Array + limit?: number + }) => Promise<{ items: Array; total: number }> +} + +/** Get a single document by id, or null. Pass `publishedOnly` to gate drafts. */ +export async function getDocument( + store: ReadStore, + collection: string, + id: string, + options: { publishedOnly?: boolean } = {}, +): Promise { + const rec = await store.getDocument(collection, id) + if (!rec) return null + if (options.publishedOnly && !isPublished(rec.doc)) return null + return rec.doc +} + +/** List documents in a collection. Published-only by default. */ +export async function listDocuments( + store: ReadStore, + collection: string, + options: { limit?: number; publishedOnly?: boolean } = {}, +): Promise> { + const { limit = 100, publishedOnly = true } = options + const res = await store.queryDocuments({ collections: [collection], limit }) + return publishedOnly ? res.items.filter((r) => isPublished(r.doc)) : res.items +} diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.ts index d61bcbeb..f4a34a2c 100644 --- a/packages/core/tsdown.config.ts +++ b/packages/core/tsdown.config.ts @@ -4,6 +4,7 @@ export default defineConfig({ entry: [ 'src/index.ts', 'src/definition.ts', + 'src/read.ts', 'src/server.ts', 'src/flags.ts', 'src/storage.ts', From e37d99cfcf2a51b2ea6e985e7d4ec552b3dd80ee Mon Sep 17 00:00:00 2001 From: Jack Herrington Date: Wed, 2 Dec 2026 11:21:01 -0800 Subject: [PATCH 2/3] feat(examples): add @jherr/blog edge read worker + /read unit tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kody blog example rebuilt on @tanstack/cms-core/read: a ~15-line ReadStore over Neon (HTTP) plus the shared renderers — no CMS engine, no WebSocket pool. Pre-bundles to ~12KB and renders /, /post/:id stably on workerd. Adds the read.test.ts unit suite (9 tests) for the /read entry. Refs #63. Co-Authored-By: Claude Opus 4.8 (1M context) --- kody/blog/AGENTS.md | 36 ++++++++++ kody/blog/README.md | 32 +++++++++ kody/blog/package.json | 18 +++++ kody/blog/src/db.ts | 57 ++++++++++++++++ kody/blog/src/entry.ts | 75 +++++++++++++++++++++ kody/blog/src/kody-runtime.d.ts | 31 +++++++++ kody/blog/src/render.ts | 74 +++++++++++++++++++++ kody/blog/tsconfig.json | 16 +++++ packages/core/tests/read.test.ts | 111 +++++++++++++++++++++++++++++++ 9 files changed, 450 insertions(+) create mode 100644 kody/blog/AGENTS.md create mode 100644 kody/blog/README.md create mode 100644 kody/blog/package.json create mode 100644 kody/blog/src/db.ts create mode 100644 kody/blog/src/entry.ts create mode 100644 kody/blog/src/kody-runtime.d.ts create mode 100644 kody/blog/src/render.ts create mode 100644 kody/blog/tsconfig.json create mode 100644 packages/core/tests/read.test.ts diff --git a/kody/blog/AGENTS.md b/kody/blog/AGENTS.md new file mode 100644 index 00000000..8be450b9 --- /dev/null +++ b/kody/blog/AGENTS.md @@ -0,0 +1,36 @@ +# AGENTS — TanStack CMS blog on Kody + +## Runtime contract + +- `kody.app.entry` = `./src/entry.ts`, default-exported `{ fetch }`, receives the + mount-stripped Request. Kody bundles source with esbuild; no Vite/Nitro. +- No TCP / no `node:*` / no filesystem in the isolate. Postgres is reached with + `@neondatabase/serverless` (`Pool` over WebSocket) — set + `neonConfig.webSocketConstructor = WebSocket` at module scope. +- Secrets: `packageSecrets.get('DATABASE_URL')` (real value on hosted runs; + placeholder under `kody dev`). Build the pool lazily on first request. + +## Store wiring (stage 2+) + +- Pass a `pool` (Neon) to `createPostgresStorage({ pool })` — NOT a + `connectionString`, which makes store-postgres build stock `pg` (won't load on + workerd). Neon's `Pool` satisfies store-postgres `PgPoolLike` structurally + (`connect()` → client with `query`/`release`, plus `on`/`end`). +- `@tanstack/*` deps are pinned to pkg.pr.new commit URLs (not on npm yet). + +## React SSR + +- Import `renderToReadableStream` from `react-dom/server.edge` (bare + `react-dom/server` resolves to the Node build and crashes on load). +- Two graphs: server entry may import `kody:runtime`; the browser client bundle + must not. Hydrate `#root` with the same data the server embedded. + +## Images + +- No native/WASM. Use Jimp (pure JS) behind the CMS `media.imageTransformer` + seam; lean on the transform cache and cap input dimensions. + +## Smoke + +- Stage 1: `appFetch` `GET /` → `{ ok: true, version: "PostgreSQL …" }`. + `GET /healthz` → `{ ok: true }`. diff --git a/kody/blog/README.md b/kody/blog/README.md new file mode 100644 index 00000000..676e690b --- /dev/null +++ b/kody/blog/README.md @@ -0,0 +1,32 @@ +# TanStack CMS blog on Kody + +A TanStack CMS blog recomposed as a hosted Kody app: a fetch-handler entry that +reuses the framework-agnostic CMS pieces (content model, store, renderers) on +Kody's Worker runtime, backed by Neon serverless Postgres. It is **not** a port +of the TanStack Start blog — Start's Vite/Nitro build does not fit Kody's +source-only, esbuild, two-graph app contract. + +## Prerequisites + +- A Neon (or other serverless/HTTP-reachable) Postgres. Save its pooled + connection string as the package secret `DATABASE_URL`. +- No local build step: Kody installs deps from npm and bundles at publish. + +## Stages + +1. **DB probe (current)** — `GET /` reads the `DATABASE_URL` secret, opens a Neon + Pool over WebSocket, and returns `select version()`. Proves secret-read + + Neon-on-workerd before the CMS is wired in. `/healthz` → `{ ok: true }`. +2. **Public site** — first-boot migrate + seed, then React-SSR published pages + and posts via `@tanstack/cms-core` + `@tanstack/cms-ui-react/site`. +3. **Admin + API** — mount `createCmsApiHandler` and real auth. + +## Done-when + +Stage 1: `GET /` returns `{ ok: true, version: "PostgreSQL …" }` from the hosted +URL. Then advance to stage 2. + +## Intent + +Prove and then ship a TanStack CMS blog deployable to a personal Kody account +with a live URL and zero infra, non-WASM image handling (Jimp), and no AI. diff --git a/kody/blog/package.json b/kody/blog/package.json new file mode 100644 index 00000000..1d94941a --- /dev/null +++ b/kody/blog/package.json @@ -0,0 +1,18 @@ +{ + "name": "@jherr/blog", + "type": "module", + "description": "TanStack CMS blog as a hosted Kody app (Neon serverless store, pre-bundled CMS).", + "exports": { + ".": "./dist/entry.mjs" + }, + "dependencies": { + "@neondatabase/serverless": "^0.10.4" + }, + "kody": { + "description": "A TanStack CMS blog on Kody \u2014 Neon Postgres, server-rendered.", + "category": "apps", + "app": { + "entry": "./dist/entry.mjs" + } + } +} diff --git a/kody/blog/src/db.ts b/kody/blog/src/db.ts new file mode 100644 index 00000000..ca86428f --- /dev/null +++ b/kody/blog/src/db.ts @@ -0,0 +1,57 @@ +import { neon } from '@neondatabase/serverless' +import { packageStorage } from 'kody:runtime' +import type { ReadRecord, ReadStore } from '@tanstack/cms-core/read' + +// Lightweight Neon integration: the HTTP (`neon()`) driver is a stateless +// fetch-per-query — no WebSocket, no pool, nothing to instantiate at boot. + +const DB_KEY = 'DATABASE_URL' + +export async function getConnectionString(): Promise { + const value = await packageStorage().get(DB_KEY) + return typeof value === 'string' && value.length > 0 ? value : undefined +} + +export async function setConnectionString(value: string): Promise { + await packageStorage().set(DB_KEY, value) +} + +function toRecord(row: { id: unknown; doc: unknown }): ReadRecord { + const doc = + row.doc && typeof row.doc === 'object' + ? (row.doc as Record) + : typeof row.doc === 'string' + ? (JSON.parse(row.doc) as Record) + : {} + return { id: String(row.id), doc } +} + +/** + * A ~15-line `ReadStore` (from `@tanstack/cms-core/read`) over the CMS's + * `cms_documents` table via the Neon HTTP driver. This is the whole DB layer a + * public site needs — no engine, no pool. + */ +export function makeReadStore(connectionString: string): ReadStore { + const sql = neon(connectionString) + return { + async getDocument(collection, id) { + const rows = (await sql` + select id, doc from cms_documents + where collection = ${collection} and id = ${id} + limit 1 + `) as Array<{ id: unknown; doc: unknown }> + return rows.length ? toRecord(rows[0]) : null + }, + async queryDocuments({ collections, limit = 100 }) { + const collection = collections[0] + const rows = (await sql` + select id, doc from cms_documents + where collection = ${collection} and published = true + order by (doc->>'publishedDate') desc nulls last + limit ${limit} + `) as Array<{ id: unknown; doc: unknown }> + const items = rows.map(toRecord) + return { items, total: items.length } + }, + } +} diff --git a/kody/blog/src/entry.ts b/kody/blog/src/entry.ts new file mode 100644 index 00000000..4ada921e --- /dev/null +++ b/kody/blog/src/entry.ts @@ -0,0 +1,75 @@ +import { getDocument, listDocuments } from '@tanstack/cms-core/read' +import { kody, packageContext } from 'kody:runtime' +import { getConnectionString, makeReadStore, setConnectionString } from './db' +import { renderHome, renderNotFound, renderPost } from './render' + +// Public blog read worker, built on @tanstack/cms-core/read: a tiny ReadStore +// over Neon (HTTP) + the shared renderers. No CMS engine, no WebSocket pool. + +const base = String(packageContext?.appBasePath ?? '').replace(/\/+$/, '') + +async function isOwner(): Promise { + try { + const me = await kody.metaGetCurrentUser({}) + return me?.role != null + } catch { + return false + } +} + +function page(body: string, status = 200): Response { + return new Response(body, { + status, + headers: { 'content-type': 'text/html; charset=utf-8' }, + }) +} + +export default { + async fetch(request: Request): Promise { + const path = new URL(request.url).pathname.replace(/\/+$/, '') || '/' + + if (path.endsWith('/healthz')) return Response.json({ ok: true }) + + if (request.method === 'POST' && path.endsWith('/_setup')) { + if (!(await isOwner())) return new Response('owner only', { status: 403 }) + const body = (await request.text()).trim() + if (!/^postgres(ql)?:\/\//.test(body)) { + return new Response('expected a postgres:// connection string', { status: 400 }) + } + await setConnectionString(body) + return Response.json({ ok: true, saved: true }) + } + + const conn = await getConnectionString() + if (!conn) { + return new Response( + 'Database not configured. Owner: POST the Neon connection string to /_setup.', + { status: 503, headers: { 'content-type': 'text/plain' } }, + ) + } + + try { + const store = makeReadStore(conn) + + const postMatch = /\/post\/([^/]+)$/.exec(path) + if (postMatch) { + const id = decodeURIComponent(postMatch[1]) + const doc = await getDocument(store, 'post', id, { publishedOnly: true }) + return doc ? page(renderPost(base, doc)) : page(renderNotFound(base), 404) + } + + if (path === '/' || path === '') { + const home = await getDocument(store, 'page', 'home') + const posts = await listDocuments(store, 'post', { limit: 50 }) + return page(renderHome(base, home, posts)) + } + + return page(renderNotFound(base), 404) + } catch (err) { + return new Response( + `render failed: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, + { status: 500, headers: { 'content-type': 'text/plain' } }, + ) + } + }, +} diff --git a/kody/blog/src/kody-runtime.d.ts b/kody/blog/src/kody-runtime.d.ts new file mode 100644 index 00000000..44938930 --- /dev/null +++ b/kody/blog/src/kody-runtime.d.ts @@ -0,0 +1,31 @@ +// Ambient shim for local `tsc`. At publish Kody rewrites `kody:` imports to real +// runtime proxies and supplies the full generated declaration; this covers only +// what the blog app uses. +declare module 'kody:runtime' { + export const packageContext: + | { + appBasePath?: string + assetBasePath?: string + hostedUrl?: string + clientModuleUrl?: string | null + } + | undefined + + // Durable per-package KV the app reads/writes in plaintext (unlike secrets, + // which the gateway only injects into outbound fetch and never hand to code). + export function packageStorage(): { + get: (key: string) => Promise + set: (key: string, value: unknown) => Promise + delete: (key: string) => Promise + } + + export const kody: { + // Verified identity of the current visitor; `role` is their role in the + // owning org (null for non-members). Throws for anonymous visitors. + metaGetCurrentUser: (args: Record) => Promise<{ + user_id: string + username: string + role: string | null + }> + } +} diff --git a/kody/blog/src/render.ts b/kody/blog/src/render.ts new file mode 100644 index 00000000..50f683ff --- /dev/null +++ b/kody/blog/src/render.ts @@ -0,0 +1,74 @@ +import { + escapeHtml, + renderBlocks, + renderMarkdown, + type Doc, + type ReadRecord, +} from '@tanstack/cms-core/read' + +// The app owns layout + styling + page composition; block/markdown rendering +// comes from @tanstack/cms-core/read (the shared, tree-shakeable renderer). + +const str = (v: unknown): string => (typeof v === 'string' ? v : '') + +function layout(base: string, title: string, body: string): string { + return `${escapeHtml( + title, + )}
jherr's blogTanStack CMS · on Kody · Neon
${body}
Served from Postgres by a Kody Worker — rendered by @tanstack/cms-core/read.
` +} + +export function renderHome( + base: string, + page: Doc | null, + posts: Array, +): string { + const blocks = renderBlocks(page?.blocks) + const list = `

Posts

    ${posts + .map( + ({ id, doc }) => + `
  • ${escapeHtml(doc.title)}${ + str(doc.excerpt) ? ` — ${escapeHtml(doc.excerpt)}` : '' + }
  • `, + ) + .join('')}
` + return layout(base, str(page?.title) || 'Blog', blocks + list) +} + +export function renderPost(base: string, doc: Doc): string { + const meta = [str(doc.author) ? `by ${escapeHtml(doc.author)}` : '', escapeHtml(doc.publishedDate)] + .filter(Boolean) + .join(' · ') + const body = `

${escapeHtml(doc.title)}

${ + meta ? `

${meta}

` : '' + }${renderMarkdown(str(doc.body))}

← all posts

` + return layout(base, str(doc.title) || 'Post', body) +} + +export function renderNotFound(base: string): string { + return layout(base, 'Not found', `

Not found

← home

`) +} + +const CSS = ` +:root{color-scheme:light dark;--fg:#1a1a1a;--bg:#fff;--muted:#666;--accent:#0b7285;--line:#e5e5e5} +@media(prefers-color-scheme:dark){:root{--fg:#eee;--bg:#14171a;--muted:#9aa;--accent:#3bc9db;--line:#2a2f33}} +*{box-sizing:border-box} +body{margin:0;font:16px/1.65 system-ui,sans-serif;color:var(--fg);background:var(--bg)} +header.site{display:flex;justify-content:space-between;align-items:center;gap:1rem;flex-wrap:wrap;max-width:46rem;margin:0 auto;padding:1.25rem;border-bottom:1px solid var(--line)} +.brand{font-weight:700;font-size:1.15rem;color:var(--fg);text-decoration:none} +.tag{color:var(--muted);font-size:.8rem} +main{max-width:46rem;margin:0 auto;padding:1.5rem 1.25rem 3rem} +h1{line-height:1.2} +.cms-hero h1{font-size:2.1rem;margin:.2em 0} +.cms-lede{font-size:1.2rem;color:var(--muted)} +a{color:var(--accent)} +blockquote{border-left:3px solid var(--accent);margin:1.5rem 0;padding:.2rem 0 .2rem 1rem;color:var(--muted);font-style:italic} +blockquote cite{display:block;font-style:normal;font-size:.9rem;margin-top:.4rem} +pre{background:rgba(127,127,127,.12);padding:1rem;border-radius:8px;overflow:auto} +.cms-callout{background:rgba(127,127,127,.1);border-radius:8px;padding:.8rem 1rem;margin:1.2rem 0} +.cms-cta a{display:inline-block;margin-top:.5rem} +figure{margin:1.2rem 0}figure img{max-width:100%;border-radius:8px} +.posts{margin-top:2.5rem;border-top:1px solid var(--line);padding-top:1rem} +.posts ul{list-style:none;padding:0}.posts li{padding:.5rem 0;border-bottom:1px solid var(--line)} +.excerpt{color:var(--muted)}.meta{color:var(--muted);font-size:.9rem} +footer{max-width:46rem;margin:0 auto;padding:1.5rem 1.25rem;color:var(--muted);font-size:.85rem;border-top:1px solid var(--line)} +` diff --git a/kody/blog/tsconfig.json b/kody/blog/tsconfig.json new file mode 100644 index 00000000..c0635132 --- /dev/null +++ b/kody/blog/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "module": "esnext", + "moduleResolution": "bundler", + "target": "es2022", + "lib": ["es2023", "dom", "dom.iterable"], + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "verbatimModuleSyntax": true + }, + "include": ["src"] +} diff --git a/packages/core/tests/read.test.ts b/packages/core/tests/read.test.ts new file mode 100644 index 00000000..0b9f8aad --- /dev/null +++ b/packages/core/tests/read.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'vitest' +import { + type Block, + type ReadStore, + defaultBlockRenderers, + escapeHtml, + getDocument, + isPublished, + listDocuments, + renderBlocks, + renderMarkdown, +} from '../src/read' + +describe('read: html + markdown primitives', () => { + it('escapes html-significant characters', () => { + expect(escapeHtml('&y')).toBe('<a href="x">&y') + expect(escapeHtml(null)).toBe('') + expect(escapeHtml(42)).toBe('') + }) + + it('renders tiny markdown (paragraphs, bold, code)', () => { + expect(renderMarkdown('a\n\nb')).toBe('

a

b

') + expect(renderMarkdown('**bold** and `x`')).toBe('

bold and x

') + expect(renderMarkdown('')).toBe('') + // escapes before formatting + expect(renderMarkdown('