Repository navigation
feat: edge read entry (@tanstack/cms-core/read) + blog read worker #65
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 }`. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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`. | ||
|
Comment on lines
+11
to
+12
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Document the configuration path that the worker reads. If an operator saves only the package secret, As per coding guidelines, “Secrets:
|
||
| - 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. | ||
|
Comment on lines
+26
to
+27
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Replace the obsolete database-probe smoke check. With a configured database, As per coding guidelines, the current smoke instruction requires
|
||
|
|
||
| ## 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. | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -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" | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The app entry points to a build artifact that nothing produces.
Suggested fix
Committable suggestion
|
||||||
| } | ||||||
| } | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
| @@ -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<string | undefined> { | ||||||||
| const value = await packageStorage().get(DB_KEY) | ||||||||
| return typeof value === 'string' && value.length > 0 ? value : undefined | ||||||||
| } | ||||||||
|
|
||||||||
| export async function setConnectionString(value: string): Promise<void> { | ||||||||
| 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<string, unknown>) | ||||||||
| : typeof row.doc === 'string' | ||||||||
| ? (JSON.parse(row.doc) as Record<string, unknown>) | ||||||||
| : {} | ||||||||
| 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 | ||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Trashed posts stay public on the blog. Moving a post to trash sets Suggested fix
Committable suggestion
|
||||||||
| 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 } | ||||||||
| }, | ||||||||
| } | ||||||||
| } | ||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| 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<boolean> { | ||
| try { | ||
| const me = await kody.metaGetCurrentUser({}) | ||
| return me?.role != null | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Only owners can replace the connection string.
Require the platform's owner role or owner capability in
|
||
| } 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<Response> { | ||
| const path = new URL(request.url).pathname.replace(/\/+$/, '') || '/' | ||
|
|
||
| if (path.endsWith('/healthz')) return Response.json({ ok: true }) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Match the health endpoint by its complete path. For a published post with id
|
||
|
|
||
| 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') | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Apply the publication gate to the home document. If
|
||
| 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' } }, | ||
| ) | ||
| } | ||
| }, | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<unknown> | ||
| set: (key: string, value: unknown) => Promise<void> | ||
| delete: (key: string) => Promise<void> | ||
| } | ||
|
|
||
| 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<string, never>) => Promise<{ | ||
| user_id: string | ||
| username: string | ||
| role: string | null | ||
| }> | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| 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 `<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>${escapeHtml( | ||
| title, | ||
| )}</title><style>${CSS}</style></head><body><header class="site"><a href="${base}/" class="brand">jherr's blog</a><span class="tag">TanStack CMS · on Kody · Neon</span></header><main>${body}</main><footer>Served from Postgres by a Kody Worker — rendered by @tanstack/cms-core/read.</footer></body></html>` | ||
| } | ||
|
|
||
| export function renderHome( | ||
| base: string, | ||
| page: Doc | null, | ||
| posts: Array<ReadRecord>, | ||
| ): string { | ||
| const blocks = renderBlocks(page?.blocks) | ||
| const list = `<section class="posts"><h2>Posts</h2><ul>${posts | ||
| .map( | ||
| ({ id, doc }) => | ||
| `<li><a href="${base}/post/${encodeURIComponent(id)}">${escapeHtml(doc.title)}</a>${ | ||
| str(doc.excerpt) | ||
| ? `<span class="excerpt"> — ${escapeHtml(doc.excerpt)}</span>` | ||
| : '' | ||
| }</li>`, | ||
| ) | ||
| .join('')}</ul></section>` | ||
| 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 = `<article><h1>${escapeHtml(doc.title)}</h1>${ | ||
| meta ? `<p class="meta">${meta}</p>` : '' | ||
| }${renderMarkdown(str(doc.body))}<p class="back"><a href="${base}/">← all posts</a></p></article>` | ||
| return layout(base, str(doc.title) || 'Post', body) | ||
| } | ||
|
|
||
| export function renderNotFound(base: string): string { | ||
| return layout( | ||
| base, | ||
| 'Not found', | ||
| `<h1>Not found</h1><p><a href="${base}/">← home</a></p>`, | ||
| ) | ||
| } | ||
|
|
||
| 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)} | ||
| ` |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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"] | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Resolve the database transport contract mismatch.
These instructions require a WebSocket
Pool, butdb.tsusesneon()over HTTP. The stage-2 instructions also direct contributors tocreatePostgresStorage, which this read worker does not use. Reconcile these instructions with the approved HTTP read architecture so later changes do not restore the engine dependency. (raw.githubusercontent.com)As per coding guidelines, Postgres uses “
Poolover WebSocket” and must setneonConfig.webSocketConstructor = WebSocket; the implementation currently violates that local contract.Source: Coding guidelines