Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions app/base/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ export default defineConfig({
test: {
name: 'base',
environment: 'node',
// Core ships no storage default; restore the embedded PGlite engine
// for tests that don't inject their own `storage`.
setupFiles: ['@tanstack/cms-store-postgres/testing'],
// Core ships no storage default; restore the embedded PGlite engine for
// tests that don't inject their own `storage`. Base uses the on-disk
// variant: the recover-owner test spawns a subprocess that reads the
// database file, so it needs real persistence, not the shared in-memory VM.
setupFiles: ['@tanstack/cms-store-postgres/testing-disk'],
include: ['tests/**/*.test.ts'],
fileParallelism: false,
// Tests drive the embedded PGlite engine (WASM init) and multi-step
Expand Down
12 changes: 9 additions & 3 deletions kody/blog/src/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ export default {
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 })
return new Response('expected a postgres:// connection string', {
status: 400,
})
}
await setConnectionString(body)
return Response.json({ ok: true, saved: true })
Expand All @@ -54,8 +56,12 @@ export default {
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)
const doc = await getDocument(store, 'post', id, {
publishedOnly: true,
})
return doc
? page(renderPost(base, doc))
: page(renderNotFound(base), 404)
}

if (path === '/' || path === '') {
Expand Down
15 changes: 12 additions & 3 deletions kody/blog/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,20 @@ export function renderHome(
.map(
({ id, doc }) =>
`<li><a href="${base}/post/${encodeURIComponent(id)}">${escapeHtml(doc.title)}</a>${
str(doc.excerpt) ? `<span class="excerpt"> — ${escapeHtml(doc.excerpt)}</span>` : ''
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)]
const meta = [
str(doc.author) ? `by ${escapeHtml(doc.author)}` : '',
escapeHtml(doc.publishedDate),
]
.filter(Boolean)
.join(' · ')
const body = `<article><h1>${escapeHtml(doc.title)}</h1>${
Expand All @@ -45,7 +50,11 @@ export function renderPost(base: string, doc: Doc): string {
}

export function renderNotFound(base: string): string {
return layout(base, 'Not found', `<h1>Not found</h1><p><a href="${base}/">← home</a></p>`)
return layout(
base,
'Not found',
`<h1>Not found</h1><p><a href="${base}/">← home</a></p>`,
)
}

const CSS = `
Expand Down
12 changes: 9 additions & 3 deletions packages/core/src/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,23 @@ export type BlockRenderer = (block: Block, ctx: RenderContext) => string
export const defaultBlockRenderers: Record<string, BlockRenderer> = {
hero: (b, c) =>
`<section class="cms-hero"><h1>${c.escapeHtml(b.heading)}</h1>${
asString(b.subheading) ? `<p class="cms-lede">${c.escapeHtml(b.subheading)}</p>` : ''
asString(b.subheading)
? `<p class="cms-lede">${c.escapeHtml(b.subheading)}</p>`
: ''
}</section>`,
richText: (b, c) => c.renderMarkdown(asString(b.markdown)),
quote: (b, c) =>
`<blockquote><p>${c.escapeHtml(b.text)}</p>${
asString(b.attribution) ? `<cite>${c.escapeHtml(b.attribution)}</cite>` : ''
asString(b.attribution)
? `<cite>${c.escapeHtml(b.attribution)}</cite>`
: ''
}</blockquote>`,
image: (b, c) =>
asString(b.image)
? `<figure><img src="${c.escapeHtml(b.image)}" alt="${c.escapeHtml(b.caption)}"/>${
asString(b.caption) ? `<figcaption>${c.escapeHtml(b.caption)}</figcaption>` : ''
asString(b.caption)
? `<figcaption>${c.escapeHtml(b.caption)}</figcaption>`
: ''
}</figure>`
: '',
cta: (b, c) =>
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/server/cms-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ export async function cmsTools(actor: string, options?: CmsToolsOptions) {
// A type-only `import()` keeps the precise `@tanstack/ai` type without a
// value import (which would pull it into core's bundle).
// oxlint-disable-next-line typescript/consistent-type-imports
const toolDefinition = runtime.toolDefinition as typeof import('@tanstack/ai').toolDefinition
const toolDefinition =
runtime.toolDefinition as typeof import('@tanstack/ai').toolDefinition
const buildSession = options?.access?.session
const observe = (
result: Omit<CmsToolResult, 'result'> & { result: unknown },
Expand Down
52 changes: 38 additions & 14 deletions packages/core/tests/read.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,18 @@ import {

describe('read: html + markdown primitives', () => {
it('escapes html-significant characters', () => {
expect(escapeHtml('<a href="x">&y')).toBe('&lt;a href=&quot;x&quot;&gt;&amp;y')
expect(escapeHtml('<a href="x">&y')).toBe(
'&lt;a href=&quot;x&quot;&gt;&amp;y',
)
expect(escapeHtml(null)).toBe('')
expect(escapeHtml(42)).toBe('')
})

it('renders tiny markdown (paragraphs, bold, code)', () => {
expect(renderMarkdown('a\n\nb')).toBe('<p>a</p><p>b</p>')
expect(renderMarkdown('**bold** and `x`')).toBe('<p><strong>bold</strong> and <code>x</code></p>')
expect(renderMarkdown('**bold** and `x`')).toBe(
'<p><strong>bold</strong> and <code>x</code></p>',
)
expect(renderMarkdown('')).toBe('')
// escapes before formatting
expect(renderMarkdown('<script>')).toBe('<p>&lt;script&gt;</p>')
Expand All @@ -44,18 +48,24 @@ describe('read: block rendering', () => {
})

it('skips unknown block types and ignores non-arrays', () => {
expect(renderBlocks([{ _type: 'nope' }, { _type: 'code', code: 'ok' }])).toBe(
'<pre><code>ok</code></pre>',
)
expect(
renderBlocks([{ _type: 'nope' }, { _type: 'code', code: 'ok' }]),
).toBe('<pre><code>ok</code></pre>')
expect(renderBlocks(undefined)).toBe('')
expect(renderBlocks('not an array')).toBe('')
})

it('allows overriding and extending renderers', () => {
const html = renderBlocks([{ _type: 'hero', heading: 'X' }, { _type: 'custom', label: 'C' }], {
hero: (b, c) => `<h2>${c.escapeHtml(b.heading)}</h2>`,
custom: (b, c) => `<div>${c.escapeHtml(b.label)}</div>`,
})
const html = renderBlocks(
[
{ _type: 'hero', heading: 'X' },
{ _type: 'custom', label: 'C' },
],
{
hero: (b, c) => `<h2>${c.escapeHtml(b.heading)}</h2>`,
custom: (b, c) => `<div>${c.escapeHtml(b.label)}</div>`,
},
)
expect(html).toBe('<h2>X</h2><div>C</div>')
})

Expand All @@ -79,8 +89,16 @@ describe('read: published queries over a ReadStore', () => {
},
async queryDocuments({ collections, limit = 100 }) {
const all = [
{ id: 'live', collection: collections[0], doc: { title: 'Live', published: true } },
{ id: 'draft', collection: collections[0], doc: { title: 'Draft', published: false } },
{
id: 'live',
collection: collections[0],
doc: { title: 'Live', published: true },
},
{
id: 'draft',
collection: collections[0],
doc: { title: 'Draft', published: false },
},
]
return { items: all.slice(0, limit), total: all.length }
},
Expand All @@ -94,11 +112,17 @@ describe('read: published queries over a ReadStore', () => {
})

it('getDocument gates drafts only when publishedOnly', async () => {
expect(await getDocument(store, 'post', 'live', { publishedOnly: true })).toMatchObject({
expect(
await getDocument(store, 'post', 'live', { publishedOnly: true }),
).toMatchObject({
title: 'Live',
})
expect(await getDocument(store, 'post', 'draft', { publishedOnly: true })).toBeNull()
expect(await getDocument(store, 'post', 'draft')).toMatchObject({ title: 'Draft' })
expect(
await getDocument(store, 'post', 'draft', { publishedOnly: true }),
).toBeNull()
expect(await getDocument(store, 'post', 'draft')).toMatchObject({
title: 'Draft',
})
expect(await getDocument(store, 'post', 'missing')).toBeNull()
})

Expand Down
5 changes: 5 additions & 0 deletions packages/store-postgres/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
".": "./src/index.ts",
"./pglite": "./src/pglite.ts",
"./testing": "./src/testing.ts",
"./testing-disk": "./src/testing-disk.ts",
"./package.json": "./package.json"
},
"main": "./src/index.ts",
Expand All @@ -47,6 +48,10 @@
"types": "./dist/testing.d.ts",
"import": "./dist/testing.js"
},
"./testing-disk": {
"types": "./dist/testing-disk.d.ts",
"import": "./dist/testing-disk.js"
},
"./package.json": "./package.json"
},
"main": "./dist/index.js",
Expand Down
14 changes: 14 additions & 0 deletions packages/store-postgres/src/testing-disk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Vitest setup variant that wires the default storage to an **on-disk** PGlite
* per `<dataDir>/pglite` (one VM per data dir). Use this instead of
* `@tanstack/cms-store-postgres/testing` (shared in-memory) when a suite needs
* real file persistence — e.g. an integration test that spawns a subprocess
* reading the same database. Slower (each distinct `dataDir` boots a VM), but
* faithful to a deployed app's on-disk engine.
*
* test: { setupFiles: ['@tanstack/cms-store-postgres/testing-disk'] }
*/
import { setDefaultStorageFactory } from '@tanstack/cms-core/server'
import { createPgliteStorage } from './pglite'

setDefaultStorageFactory(createPgliteStorage)
44 changes: 40 additions & 4 deletions packages/store-postgres/src/testing.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,51 @@
/**
* Vitest setup module: restore the embedded Postgres engine (PGlite) as the
* process-wide default storage, so tests that call `defineCms(...)` without an
* explicit `storage` get the embedded engine — exactly the pre-seam dev
* default. Reference it from a package's vitest config:
* explicit `storage` get the embedded engine. Reference it from a package's
* vitest config:
*
* test: { setupFiles: ['@tanstack/cms-store-postgres/testing'] }
*
* Booting a PGlite VM costs ~400ms (WASM + baked catalog); the CMS migrations
* on top are only ~13ms. So rather than a fresh VM per `defineCms`, this shares
* ONE in-memory VM per test process and gives each config an isolated, prefixed
* schema — the 400ms boot is paid once, each config pays ~13ms. A passed-in
* pool is never closed by `storage.close()` (see createPostgresStorage), so the
* shared VM survives per-config teardown and is dropped when the process exits.
*
* Isolation is keyed by the resolved data directory, exactly mirroring the old
* embedded default (which keyed its on-disk PGlite by `<dataDir>/pglite`):
* configs with the same `dataDir` share a schema — so a close + re-`defineCms`
* at the same `dataDir` still sees its data (cross-restart tests) — and distinct
* `dataDir`s are isolated. Tests wanting on-disk files inject an explicit
* `createPgliteStorage({ dataDir })` and get their own VM.
*
* This is test-only wiring. Shipped apps inject `storage` explicitly; core
* never imports a storage package of its own.
*/
import { setDefaultStorageFactory } from '@tanstack/cms-core/server'
import { createPgliteStorage } from './pglite'
import { createPostgresStorage } from './index'
import { createPglitePool } from './pglite'
import type { PgPoolLike } from './types'

let sharedPool: PgPoolLike | undefined
let seq = 0
// Resolved data dir -> table prefix, so the same dir always maps to the same
// schema (persistence across reopen) and distinct dirs never collide.
const prefixByDataDir = new Map<string, string>()

setDefaultStorageFactory(createPgliteStorage)
setDefaultStorageFactory((ctx) => {
// One in-memory PGlite VM for the whole process; opened lazily on first query.
if (!sharedPool) sharedPool = createPglitePool()
let prefix = prefixByDataDir.get(ctx.dataDir)
if (!prefix) {
prefix = `t${(seq++).toString(36)}_cms_`
prefixByDataDir.set(ctx.dataDir, prefix)
}
return createPostgresStorage({
pool: sharedPool,
migrationPool: sharedPool,
acquisitionTimeoutMs: 30_000,
prefix,
})
})
7 changes: 6 additions & 1 deletion packages/store-postgres/tsdown.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { defineConfig } from 'tsdown'

export default defineConfig({
entry: ['src/index.ts', 'src/pglite.ts', 'src/testing.ts'],
entry: [
'src/index.ts',
'src/pglite.ts',
'src/testing.ts',
'src/testing-disk.ts',
],
format: 'esm',
platform: 'neutral',
unbundle: true,
Expand Down
Loading