01Project Layout & Mental Model
A SpacePress application is a regular TypeScript repository whose single source of truth is typedpress.config.ts and the modules under tp/. Instead of running a separate Node.js backend beside WordPress, SpacePress compiles your TypeScript directly into native PHP, SQL migrations, TypeScript types, OpenAPI 3.1, and standard WordPress plugins.
Pre-release package & CLI naming: SpacePress is the framework and platform brand (spacepress.dev). While preparing its 1.0 release, the Rust CLI binary, npm package, config filename, and virtual imports remain spelled typedpress (typedpress.config.ts, tp/, import ... from "typedpress", typedpress:db).
my-app/
typedpress.config.ts Config entry & re-exports
tsconfig.json TypeScript paths ("typedpress", "typedpress:db")
tp/
schema.ts Collections, SQL tables, globals, taxonomies
server.ts Actions, background jobs, helpers
app/
layout.tsx Root layout & shared metadata
page.tsx Home page (/)
not-found.tsx Custom 404 page
posts/[slug]/page.tsx Dynamic item route
api/feed.json/route.ts Custom HTTP route
components/ Server & "use client" components
wp-hooks/ Typed WordPress core actions & filters
_generated/ Compiler-emitted db.d.ts, routes.d.ts, client/, migrations/
dist/wp-content/ Built WordPress plugins (ready to deploy)
content/ Markdown/JSON files synced with WordPress
emails/ React Email templates rendered by mail.render()
public/ Static assets served at site rootExplore a complete multi-file SpacePress app
Click any file in the tree below to inspect how schema, server actions, layouts, dynamic routes, and interactive client islands fit together in a single project.
import { action, integer, HttpError } from "typedpress";
import { articles, claps } from "typedpress:db";
export const clap = action({
access: "anyone",
input: { articleId: integer() },
async handler({ articleId }) {
const article = await articles.get(articleId);
if (!article) throw new HttpError(404, "not_found", "Article not found");
const existing = await claps.system.get({ articleId });
if (existing) {
const updated = await claps.system.update(existing.id, { count: existing.count + 1 });
return { count: updated.count };
}
const created = await claps.system.create({ articleId, count: 1 });
return { count: created.count };
},
});
import { Content, Link, type PageProps } from "typedpress/app";
import { claps } from "typedpress:db";
import { ClapButton } from "../../../components/ClapButton";
export const metadata = ({ item }: PageProps<"articles/[slug]">) => ({
title: item.title,
description: item.summary ?? undefined,
});
export default async function ArticlePage({ item }: PageProps<"articles/[slug]">) {
const row = await claps.get({ articleId: item.id });
return (
<article>
<p><Link href="/">← All articles</Link></p>
<h1>{item.title}</h1>
<Content value={item.body} />
<ClapButton articleId={item.id} initial={row?.count ?? 0} />
</article>
);
}
import { Link, type LayoutProps } from "typedpress/app";
export const template = "blank";
export const metadata = {
title: { default: "Editorial", template: "%s · Editorial" },
description: "Server-rendered TSX pages backed by WordPress.",
};
export default function Layout({ children }: LayoutProps) {
return (
<div className="shell">
<header>
<Link href="/">Editorial</Link>
</header>
<main>{children}</main>
</div>
);
}
"use client";
import { useState } from "typedpress/client";
import { clap } from "../actions";
export function ClapButton({ articleId, initial }: { articleId: number; initial: number }) {
const [count, setCount] = useState(initial);
const [busy, setBusy] = useState(false);
return (
<button
type="button"
disabled={busy}
onClick={async () => {
setBusy(true);
const res = await clap({ articleId });
setCount(res.count);
setBusy(false);
}}
>
{count} {count === 1 ? "clap" : "claps"}
</button>
);
}
import { collection, table, text, integer, richText, slug, ref, timestamp } from "typedpress";
export const articles = collection({
title: text().min(1).max(140),
slug: slug({ source: "title" }).optional(),
summary: text({ multiline: true }).max(260).optional(),
body: richText().optional(),
updatedAt: timestamp().defaultNow().$onUpdate(() => new Date()),
}, {
label: "Articles",
title: "title",
content: "body",
url: "/articles/:slug",
sync: "content/articles/*.md",
access: { read: "anyone", create: "author", update: "editor", delete: "editor" },
});
export const claps = table({
articleId: ref(articles).unique().onDelete("cascade"),
count: integer().default(0),
}, {
access: { read: "anyone", create: "admin", update: "admin", delete: "admin" },
});
import { defineConfig } from "typedpress";
export * from "./tp/schema";
export * from "./tp/actions";
export default defineConfig({
name: "editorial",
seed: true,
});
02How the Rust & OXC Compiler Works
SpacePress parses your TypeScript and TSX files with OXC in Rust. There is no Node.js runtime, V8 isolate, or JavaScript execution layer in production — every server artifact runs as plain, idiomatic PHP inside WordPress. During compilation, the OXC AST pass also runs non-fatal lint checks including capital_P_dangit (flagging a lowercase “p” in WordPress or SpacePress copy, auto-fixable via typedpress check --fix or in the live sandboxes below).
| What you author | What the compiler emits | Where it runs |
|---|
collection(), table(), global(), taxonomy(), store() | tp/app/schema.php + numbered SQL migrations in tp/_generated/migrations/ | WordPress PHP runtime & MySQL/SQLite |
action(), job(), .on() hooks, .validate(), access functions, route.ts | tp/app/functions.php | Native PHP in WordPress / Action Scheduler |
tp/app/**/page.tsx & layout.tsx | Server-rendered PHP functions inside functions.php | Native PHP (or prebuilt HTML with output: "static") |
"use client" components | Server-rendered PHP HTML + WordPress Interactivity API ES module | PHP first paint + browser Interactivity API hydration |
| Schema & actions graph | tp/_generated/db.d.ts, routes.d.ts, openapi.json, client/ | IDE type checking, external browsers, React & Astro |
Try the live compiler right here
Switch output tabs on the right to inspect every generated artifact from this single TypeScript file, or edit the code on the left to watch compilation happen in milliseconds inside WebAssembly.
import { collection, table, text, integer, slug, ref, action, db, defineConfig } from "typedpress";
export const guides = collection({
title: text().min(1).max(120),
slug: slug({ source: "title" }).optional(),
}, {
label: "Guides",
url: "/guides/:slug",
access: { read: "anyone", create: "editor", update: "editor", delete: "editor" },
});
export const votes = table({
guideId: ref(guides).onDelete("cascade"),
score: integer().min(1).max(5),
}, {
access: { read: "anyone", create: "anyone", update: "admin", delete: "admin" },
});
export const rateGuide = action({
input: { guideId: integer(), score: integer().min(1).max(5) },
access: "anyone",
async handler({ guideId, score }) {
const [row] = await db.insert(votes).values({ guideId, score }).returning();
return row;
},
});
export default defineConfig({ name: "guide-demo" });
03Data Modeling: Collections, Tables, Globals & WordPress Kinds
SpacePress gives you six storage primitives — each chosen for a distinct job, all unified under one query and access API:
| Builder | Backing Storage | Best For |
|---|
collection(fields, opts) | WordPress custom post type (wp_posts + meta) | Editorial content needing Gutenberg, drafts, revisions, staged versions, comments, hierarchical paths, or Markdown sync |
table(fields, opts) | Dedicated SQL table with automatic migrations | Relational app data, high-volume records, logs, shares, votes, compound indexes (.index([...])) |
global(fields, opts) | Singleton WordPress options record | Site settings, navigation links, banner copy, feature flags (db.globals.<key>) |
wp.posts.extend() / .clone() | WordPress built-in post type (or cloned CPT) | Extending native WordPress blog posts with typed custom fields, URL pattern, and sync |
userProjection(fields, opts) | wp_users + wp_usermeta | Typed member profiles and account attributes without creating a duplicate user table |
taxonomy(fields, opts) | WordPress taxonomy & term tables | Hierarchical or flat vocabularies attached to collections via on: [posts] or terms(tax) |
Field Builders & Modifiers
Every field is required (NOT NULL) by default unless marked .optional(). Defaults (.default(), .defaultNow(), .$default(), .$onUpdate()) make fields omittable on insert.
| Category | Builders | Key Modifiers |
|---|
| Scalars | text({ multiline? }), integer(), number(), boolean(), date(), timestamp(), json<T>() | .optional(), .default(v), .defaultNow(), .$default(fn), .$onUpdate(fn), .unique(), .min(n), .max(n), .pattern(/re/) |
| Semantic & Editorial | email(), url(), slug({ source }), richText(), select([...]) | select([...]).many() (JSON list filtered with { has: x }), .validate((v, ctx) => ...) |
| Media, Files & Relations | media({ accept }), file(bucket), ref(kind), terms(tax) | .many(), .onDelete("cascade" | "restrict" | "setNull"), .reverse("name") |
| Structured & Flexible | group(fields), repeater(fields), blocks(layouts) | .min(n) / .max(n) item counts, .ui({ label, help, placeholder, width }), .showIf({ ... }) |
| Migrations & Renames | field.was("oldName"), table(..., { was: "old_table", existingTable }) | Preserves existing rows and column values across deploys without data loss |
Interactive Schema Evolution & SQL Migration Diff
The sandbox below compiles against a baseline snapshot containing a 3-column bookmarks table. Edit the evolved schema — add a field, change a constraint, or rename title using .was("title") — and watch the numbered 0002_*.sql migration update live.
import { table, text, boolean, defineConfig } from "typedpress";
export const bookmarks = table({
title: text().max(140),
url: text().max(191),
archived: boolean().default(false),
});
export default defineConfig({ name: "bookmarks" });import { table, text, boolean, select, integer, timestamp, defineConfig } from "typedpress";
// Try renaming `title` -> `label: text().max(140).was("title")` or adding another column!
export const bookmarks = table({
title: text().max(140),
url: text().max(191).unique(),
category: select(["docs", "article", "tool"]).default("article"),
rating: integer().min(1).max(5).optional(),
archived: boolean().default(false),
updatedAt: timestamp().defaultNow().$onUpdate(() => new Date()),
}).index(["category", "archived"]);
export default defineConfig({ name: "bookmarks" });
04Queries, Mutations, Validation & Declarative Access Rules
SpacePress provides two database interfaces so authorization is always explicit:
- Visitor-scoped Kind API (
import { posts } from "typedpress:db"): Every call (list, paginate, get, count, create, update, delete) enforces the current visitor's access rules, draft visibility, and field masks. Use posts.system.* only when intentionally escalating to trusted system access. - Trusted Database API (
import { db } from "typedpress"): Drizzle-inspired relational queries (db.query.<kind>.findMany(), findFirst()), writes (db.insert(), db.update(), db.delete() with .returning()), and db.globals.<key>.get() / .update(). Ideal inside hooks, background jobs, and already-authorized server actions.
import { db } from "typedpress";
import { posts } from "typedpress:db";
// Visitor-scoped: enforces read rules, draft visibility & field masks
const { rows, cursor } = await posts.paginate({
where: { tags: { has: "release" } },
orderBy: { publishedAt: "desc" },
with: { authorId: true, cover: true },
limit: 20,
});
// Trusted system query inside an action or background job
const draftCount = await db.query.posts.findMany({
where: { OR: [{ status: "draft" }, { status: "scheduled" }] },
columns: { id: true },
});Role Ladder & Declarative Access Control
Roles form an ordered ladder: guest < subscriber < author < editor < admin. Naming a role admits that role and every role above it. Shorthands also include "anyone", "authenticated", "self" (for user projections), or a boolean. For row-level authorization, pass a function returning either a boolean or a filter object — SpacePress compiles it to PHP and pushes row filters into SQL queries so unauthorized rows return 404.
import {
collection, table, userProjection, text, email, integer, select, ref, defineConfig,
} from "typedpress";
const STAFF = ["author", "editor", "admin"];
export const profiles = userProjection({
email: email().unique().max(191),
displayName: text().max(80),
plan: select(["free", "pro"]).default("free"),
}, {
access: { read: "self", create: "anyone", update: "self", delete: "admin" },
});
export const projects = collection({
title: text().min(1).max(120),
ownerId: integer(),
// Field-level access: never exposed to non-staff readers
budgetNotes: text({ multiline: true })
.access({ read: "editor", create: "editor", update: "editor" })
.optional(),
}, {
label: "Projects",
access: {
read: (ctx) => STAFF.includes(ctx.user?.role ?? "") ? true : { status: "published" },
create: "author",
update: (ctx) => ctx.user?.role === "admin" ? true : { ownerId: ctx.user?.id ?? -1 },
delete: "editor",
},
});
export const comments = table({
projectId: ref(projects).onDelete("cascade"),
body: text({ multiline: true })
.min(2)
.max(2000)
.validate((v) => v.includes("http://") ? "Use https:// links only" : true),
}, {
access: { read: "anyone", create: "authenticated", update: "editor", delete: "editor" },
});
export default defineConfig({ name: "access-guide" });
05Hooks & Lifecycle Events
Attach lifecycle hooks directly to any collection or SQL table with .on({ ... }). Every hook compiles to native PHP and executes inside the write's transaction: throwing an HttpError (or any error) aborts the request and rolls back all changes cleanly.
beforeCreate(data, ctx) / afterCreate(row, ctx) — normalize input, enforce invariants, compute derived fields, or enqueue post-commit jobs.beforeUpdate(patch, existing, ctx) / afterUpdate(row, previous, ctx) — react to field transitions with both old and new rows.beforeDelete(row, ctx) / afterDelete(row, ctx) — run on permanent delete (trashing a WordPress post fires update hooks; emptying trash fires delete hooks).afterPublish(row, ctx) — fires whenever a collection item transitions to published (on create, update, or scheduled publish).
import { table, text, integer, timestamp, job, jobs, db, HttpError, defineConfig } from "typedpress";
export const invoices = table({
customer: text().max(120),
cents: integer().min(1),
code: text().max(40).optional(),
syncedAt: timestamp().optional(),
}).on({
beforeCreate(data) {
data.customer = data.customer.trim();
if (data.customer === "") {
throw new HttpError(422, "invalid_input", "Customer name is required");
}
data.code = `INV-${crypto.randomUUID().slice(0, 8).toUpperCase()}`;
},
async afterCreate(row) {
await jobs.syncInvoice.enqueue({ invoiceId: row.id }, { key: `inv-${row.id}` });
},
});
export const syncInvoice = job({
input: { invoiceId: integer() },
retries: 3,
async handler({ invoiceId }) {
await db.update(invoices)
.set({ syncedAt: new Date().toISOString() })
.where({ id: invoiceId });
},
});
export default defineConfig({ name: "hooks-demo" });
Typed WordPress Core Hooks (tp/wp-hooks/)
Need to tap directly into WordPress core filters or actions (the_content, pre_get_posts, wp_head, wp_mail, save_post, etc.)? Place a file in tp/wp-hooks/<hook>.ts using the typed Handler<"..."> helper from "php/wordpress".
// tp/wp-hooks/the_content.ts
import type { Handler } from "php/wordpress";
export const priority = 20;
const wrapContent: Handler<"the_content"> = (content) => {
return `<div class="prose-frame">${content}</div>`;
};
export default wrapContent;06Server Actions, Background Jobs, HTTP Routes & Files
Beyond CRUD endpoints, SpacePress compiles three server primitives directly into WordPress:
- Server Actions (
action()): Mounted at POST /__tp/api/v1/actions/<name>, validated with the same column builders, protected by access (default "editor"), optionally signed via HMAC webhook verification (signature), and annotated with idempotent, readonly, or destructive for AI agents. - Background Jobs (
job()): Dispatched via jobs.<name>.enqueue(input, { delay?, key? }) onto WordPress's Action Scheduler. Enqueueing inside a hook or action commits atomically with the database write, supports automatic retries, dedupe keys, and idempotency guards via once(key, fn). - Custom HTTP Routes (
tp/app/.../route.ts): Export GET, POST, PUT, PATCH, or DELETE handlers plus export const guard to serve JSON feeds, webhooks, robots.txt, or custom endpoints at any clean URL outside /wp-json. - Private File Buckets (
files()) & Signed Webhooks: Store private uploads locally or on S3-compatible storage (uploads: { backend: "s3", ... }) with automatic 5-minute signed download URLs, and emit signed TypedPress-Signature HMAC webhooks on any <kind>.created|updated|deleted event.
import {
table, text, integer, file, files, action, job, jobs, env, db, HttpError, defineConfig,
} from "typedpress";
// Private file bucket: downloads use signed 5-minute URLs when loaded via `with`
export const briefs = files({
accept: ["application/pdf"],
maxBytes: 15_000_000,
access: { read: "owner", create: "authenticated", delete: "editor" },
});
export const submissions = table({
title: text().min(1).max(140),
brief: file(briefs).optional(),
status: text().default("pending"),
});
// Annotated readonly/destructive actions also become typed WordPress Abilities
export const approveSubmission = action({
input: { id: integer() },
access: "editor",
idempotent: true,
async handler({ id }) {
const [row] = await db.update(submissions)
.set({ status: "approved" })
.where({ id })
.returning();
if (!row) throw new HttpError(404, "not_found", "Submission not found");
await jobs.notifyReviewer.enqueue({ id }, { delay: 10, key: `approved-${id}` });
return row;
},
});
export const notifyReviewer = job({
input: { id: integer() },
retries: 2,
async handler({ id }) {
await db.query.submissions.findFirst({ where: { id } });
},
});
export default defineConfig({
name: "workflow",
uploads: { backend: "local" },
webhooks: [
{
url: env("WORKFLOW_WEBHOOK_URL"),
secret: env("WORKFLOW_WEBHOOK_SECRET"),
events: ["submissions.created", "submissions.updated"],
},
],
});
// tp/app/api/feed.json/route.ts
import { db, type RouteRequest } from "typedpress";
export const guard = "anyone";
export async function GET(req: RouteRequest) {
const limit = Number(req.query.get("limit") ?? "10");
const rows = await db.query.posts.findMany({
where: { status: "published" },
orderBy: { id: "desc" },
limit: limit > 0 && limit <= 50 ? limit : 10,
});
return {
headers: { "content-type": "application/feed+json" },
body: JSON.stringify({
version: "https://jsonfeed.org/version/1.1",
title: "SpacePress Feed",
items: rows.map((p) => ({ id: String(p.id), title: p.title })),
}),
};
}07Pages, Layouts, Server Components & "use client" Islands
Drop TSX files into tp/app/ to build full server-rendered websites and apps without leaving TypeScript. SpacePress compiles every page and layout into PHP that executes directly inside WordPress.
| Convention / Export | Behavior |
|---|
tp/app/page.tsx, [slug]/page.tsx, [...path]/page.tsx, (group)/ | File-based routing. When a folder matches a collection's url pattern (e.g. /blog/:slug), SpacePress injects the fetched item automatically and returns 404 for drafts/missing slugs. |
layout.tsx, not-found.tsx, login.tsx | Nested shared layouts, custom 404 view, and custom wp-login.php screen with <LoginForm />. |
export const metadata / function | Title templates ({ default, template }), description, canonical, robots, Open Graph, Twitter cards, custom <link> tags, and scripts from public/. |
export const template | "theme" (wraps page in active block theme header/footer), "blank" (layout draws its own shell), or any block template slug. |
export const search & guard | Typed query-string parsing (e.g. { page: integer().default(1) }) and route-level access guards. |
output: "static" + staticParams() | Prebuilds pages into standalone HTML via typedpress export — no WordPress server needed at serve time. |
Built-in UI primitives (typedpress/app) | <Link> (client-side router navigation), <Content>, <Html>, <Comments>, <Pagination>, <Search>, <SearchResults>, <TemplatePart>, <Live>, useFormState(). |
"use client" (typedpress/client) | Compiles server HTML + a WordPress Interactivity API module supporting useState, useEffect, useMount, useEvent, useRef, sharedState, and real-time useLive() subscriptions. |
CSS imports (import "./site.css") and CSS Modules (import styles from "./card.module.css") are content-hashed and copied automatically into the built app plugin. Inspect the layout, page, and "use client" island from our editorial example:
import { action, integer, HttpError } from "typedpress";
import { articles, claps } from "typedpress:db";
export const clap = action({
access: "anyone",
input: { articleId: integer() },
async handler({ articleId }) {
const article = await articles.get(articleId);
if (!article) throw new HttpError(404, "not_found", "Article not found");
const existing = await claps.system.get({ articleId });
if (existing) {
const updated = await claps.system.update(existing.id, { count: existing.count + 1 });
return { count: updated.count };
}
const created = await claps.system.create({ articleId, count: 1 });
return { count: created.count };
},
});
import { Content, Link, type PageProps } from "typedpress/app";
import { claps } from "typedpress:db";
import { ClapButton } from "../../../components/ClapButton";
export const metadata = ({ item }: PageProps<"articles/[slug]">) => ({
title: item.title,
description: item.summary ?? undefined,
});
export default async function ArticlePage({ item }: PageProps<"articles/[slug]">) {
const row = await claps.get({ articleId: item.id });
return (
<article>
<p><Link href="/">← All articles</Link></p>
<h1>{item.title}</h1>
<Content value={item.body} />
<ClapButton articleId={item.id} initial={row?.count ?? 0} />
</article>
);
}
import { Link, type LayoutProps } from "typedpress/app";
export const template = "blank";
export const metadata = {
title: { default: "Editorial", template: "%s · Editorial" },
description: "Server-rendered TSX pages backed by WordPress.",
};
export default function Layout({ children }: LayoutProps) {
return (
<div className="shell">
<header>
<Link href="/">Editorial</Link>
</header>
<main>{children}</main>
</div>
);
}
"use client";
import { useState } from "typedpress/client";
import { clap } from "../actions";
export function ClapButton({ articleId, initial }: { articleId: number; initial: number }) {
const [count, setCount] = useState(initial);
const [busy, setBusy] = useState(false);
return (
<button
type="button"
disabled={busy}
onClick={async () => {
setBusy(true);
const res = await clap({ articleId });
setCount(res.count);
setBusy(false);
}}
>
{count} {count === 1 ? "clap" : "claps"}
</button>
);
}
import { collection, table, text, integer, richText, slug, ref, timestamp } from "typedpress";
export const articles = collection({
title: text().min(1).max(140),
slug: slug({ source: "title" }).optional(),
summary: text({ multiline: true }).max(260).optional(),
body: richText().optional(),
updatedAt: timestamp().defaultNow().$onUpdate(() => new Date()),
}, {
label: "Articles",
title: "title",
content: "body",
url: "/articles/:slug",
sync: "content/articles/*.md",
access: { read: "anyone", create: "author", update: "editor", delete: "editor" },
});
export const claps = table({
articleId: ref(articles).unique().onDelete("cascade"),
count: integer().default(0),
}, {
access: { read: "anyone", create: "admin", update: "admin", delete: "admin" },
});
import { defineConfig } from "typedpress";
export * from "./tp/schema";
export * from "./tp/actions";
export default defineConfig({
name: "editorial",
seed: true,
});
08Generated Typed Client, React Hooks & Astro Integration
Want to pair a SpacePress backend with a React SPA, Next.js, TanStack Start, Vite, or Astro frontend? Every build writes a zero-dependency typed client into tp/_generated/client/ alongside framework-agnostic React hooks (react.ts) that accept your own React 18+ or Preact instance via createHooks(React).
import * as React from "react";
import { createClient } from "./tp/_generated/client/index";
import { createHooks } from "./tp/_generated/client/react";
export const client = createClient({ baseUrl: "https://api.example.com" });
export const { useQuery, useMutation } = createHooks(React);
export function TaskCounter() {
const { data, loading } = useQuery(client.tasks.list({ where: { done: false } }));
const toggle = useMutation(
(id: number) => client.actions.completeTask({ id }),
{
optimistic: (apply, id) => {
apply(client.tasks.list({ where: { done: false } }), (rows) =>
rows.filter((t) => t.id !== id),
);
},
},
);
if (loading) return <p>Loading…</p>;
return <p>{data?.length ?? 0} open tasks</p>;
}First-Class Astro Integration (@typedpress/astro)
Use @typedpress/astro to connect any SpacePress backend to Astro's Content Layer with build-time (tpLoader) or on-demand live collections (tpLiveLoader), automatic cache tags, signed webhook invalidation (tpWebhook), and frontend: "https://..." in defineConfig() so WordPress permalinks and previews point to your external frontend.
// src/content.config.ts (Astro 7+)
import { defineCollection } from "astro:content";
import { tpLoader, tpLiveLoader } from "@typedpress/astro";
export const collections = {
// Build-time static collection
docs: defineCollection({
loader: tpLoader("docs", { where: { status: "published" } }),
}),
// Live on-demand collection with cacheHint.tags (<kind>, <kind>:<id>)
posts: defineCollection({
loader: tpLiveLoader("posts", { rendered: "entries" }),
}),
};
// src/pages/api/tp-webhook.ts — verifies TypedPress-Signature & invalidates tags
import { tpWebhook } from "@typedpress/astro";
export const POST = tpWebhook();09WooCommerce Native Storefront
SpacePress treats WooCommerce as a first-class typed runtime rather than an afterthought. Declare store(), product(), productCategory(), productTag(), and order() in TypeScript — or scaffold a complete storefront into any project with typedpress add shop.
- Declarative Store Settings: Currency, store country & address, selling regions, weight/dimension units, shipping zones & methods (
flatRate, freeShipping, localPickup), payment gateways, and store email sender. - Synced Catalogs: Products, categories, and tags support
sync: "content/products/*.md" and clean URL patterns like /products/:slug. - Optimistic Cart Client & React Hooks: Whenever a project exports a
store(), typedpress build automatically emits commerce.ts, cart-store.ts, and cart-react.ts into tp/_generated/client/ with optimistic quantity updates and rollback.
import {
store, product, productCategory, productTag, order, defineConfig,
} from "typedpress";
export const shop = store({
currency: "EUR",
country: "DE",
address: { line1: "Torstrasse 1", city: "Berlin", postcode: "10119" },
sellTo: ["DE", "PL", "NL", "FR"],
units: { weight: "kg", dimension: "cm" },
shipping: [
{
name: "EU Standard",
countries: ["DE", "PL", "NL", "FR"],
methods: [
{ type: "flatRate", title: "Tracked Courier", cost: "12.00" },
{ type: "freeShipping", title: "Free over 150 EUR", minimum: "150.00" },
],
},
],
payments: ["cod"],
email: { fromName: "SpacePress Store", fromAddress: "store@example.com" },
});
export const products = product({ sync: "content/products/*.md", url: "/products/:slug" });
export const categories = productCategory({ sync: "content/product-categories/*.md", url: "/shop/:path" });
export const tags = productTag();
export const orders = order();
export default defineConfig({ name: "eu-shop" });
import * as React from "react";
import { createCartHooks } from "./tp/_generated/client/cart-react";
export const { useCart, useCartCount } = createCartHooks(React);
export function CartBadge() {
const count = useCartCount();
return <a href="/cart">Cart ({count ?? 0})</a>;
}10React Email Templates & Transactional Mail
Author transactional emails as React components under emails/*.tsx using react-email. Inside hooks, actions, routes, or background jobs, render them to both HTML and plain text with mail.render(Template, props) and queue delivery with mail.send().
Every mail.send() call participates in the handler's database transaction: the message is handed off to the site's mail transport only after commit (with automatic retries on failure), and a rollback sends nothing.
// emails/invitation.tsx
import { Body, Button, Html, Text } from "react-email";
export interface InvitationProps {
name: string;
url: string;
}
export default function Invitation({ name, url }: InvitationProps) {
return (
<Html lang="en">
<Body>
<Text>Hello, {name}!</Text>
<Button href={url}>Accept invitation</Button>
</Body>
</Html>
);
}
// tp/server.ts — transactional send queued in-transaction & retried after commit
import { action, email, text, mail } from "typedpress";
import Invitation from "../emails/invitation";
export const inviteMember = action({
access: "admin",
input: { to: email(), name: text().max(80) },
async handler({ to, name }) {
const rendered = mail.render(Invitation, {
name,
url: "https://example.com/accept",
});
return await mail.send({
to,
subject: `You're invited, ${name}`,
html: rendered.html,
text: rendered.text,
});
},
});11WordPress Admin, Gutenberg, Custom Screens & Plugins
Every SpacePress build ships SpacePress Admin (typedpress-admin) at /wp-admin/new/ alongside classic wp-admin (opt out with admin: false). Collections automatically get Gutenberg editing, drafts, revisions, and staged versions (save a parallel staged edit, compare, promote, or discard via CLI or Admin).
- Custom Admin Screens (
adminScreen()): Build rich DataViews tables/grids or DataForms backed by your readonly: true and mutation actions. One declarative definition renders in both /wp-admin/new/screens/<slug> and classic wp-admin. - Gutenberg Blocks & Block Themes in TSX (
@typedpress/blocks): Author real Gutenberg post content and complete block themes in TSX — HTML tags map to core blocks (<p> → core/paragraph) while blockComponent() and <Block name="..." /> target any registered block. - Locked WordPress Plugins & Sealed Mode: Declare WordPress.org or URL plugins in
defineConfig({ plugins: { ... }, sealed: true }) with exact versions and SHA-256 checksums locked in tp/_generated/wp-plugins.lock.json. In sealed: true mode, activating any undeclared plugin is refused. - TypeScript Plugin Packages (
definePlugin() + use): Compose reusable SpacePress packages with use: [myPlugin(...)]. The compiler infers exact capabilities from compiled code and locks grants in tp/_generated/plugins.lock.json.
import {
table, text, integer, action, adminScreen, item, db, HttpError, defineConfig,
} from "typedpress";
export const tickets = table({
subject: text().max(160),
priority: integer().default(2),
state: text().default("open"),
});
export const listOpenTickets = action({
access: "editor",
readonly: true,
input: {},
async handler() {
return await db.query.tickets.findMany({ where: { state: "open" }, orderBy: { priority: "asc" } });
},
});
export const closeTicket = action({
access: "editor",
destructive: true,
input: { id: integer() },
async handler({ id }) {
const [row] = await db.update(tickets).set({ state: "closed" }).where({ id }).returning();
if (!row) throw new HttpError(404, "not_found", "Ticket not found");
return row;
},
});
// Renders in both /wp-admin/new/screens/open-tickets and classic wp-admin
export const openTickets = adminScreen({
title: "Open Tickets",
description: "Triage and resolve incoming support tickets.",
access: "editor",
view: {
action: listOpenTickets,
fields: {
subject: { label: "Subject", type: "text" },
priority: { label: "Priority", type: "integer" },
state: { label: "State", type: "text" },
},
layout: { type: "table", titleField: "subject", fields: ["subject", "priority", "state"] },
},
actions: [
{
id: "close",
label: "Close ticket",
action: closeTicket,
input: { id: item("id") },
confirm: "Mark this ticket as closed?",
},
],
});
export default defineConfig({ name: "support-desk" });
12Two-Way Markdown & Git Sync
Add sync: "content/docs/**/*.md" (hierarchical folder tree) or sync: "content/posts/*.md" (flat folder) to any collection or taxonomy. SpacePress assigns each record a permanent uid and keeps your repository and WordPress database synchronized in both directions.
---
uid: zr_8f31c902a1d44b8e72a1
title: Getting Started with SpacePress
description: Install the CLI and launch your first local WordPress site.
order: 1
status: published
publishedAt: 2026-11-21T09:00:00.000Z
---
Write documentation or blog posts in plain Markdown. Front matter keys are validated
against your TypeScript schema at sync time — typos fail with the exact file and line.npx typedpress sync- 3-way merge & conflict detection: Tracks the last synced base state so non-overlapping edits in Git and WordPress merge cleanly, while true conflicts are flagged explicitly.
- GitHub workflow automation: Run
typedpress init --github to scaffold automated sync workflows and configure typedpress git-dispatch so saves in WordPress Admin notify your repository automatically. - Standalone seeding: Enable
seed: true in defineConfig() so fresh deployments seed synced content on plugin activation without overwriting existing editorial changes.
13MCP, WordPress Abilities & AI Agents
SpacePress is built from day one for coding agents and runtime AI workflows:
- Project MCP Server (
typedpress mcp): Serves your project's schema, routes, diagnostics, and embedded version-matched documentation over stdio MCP. Run typedpress init to generate AGENTS.md, .mcp.json, and agent skills automatically. - WordPress Abilities API: Collections, globals, actions, and jobs are exposed as WordPress Abilities by default (
agents: false opts out). Annotate actions with readonly: true or destructive: true so AI agents know when to ask for confirmation. Call any installed site ability with full type safety via abilities.call() after running typedpress abilities pull --site <url>. - Runtime Schema Versions (
runtimeSchema: true): Allow live sites to evolve collections and fields as numbered schema versions, then pull them back into source control with typedpress pull.
import { action, text } from "typedpress";
import { abilities } from "php/wordpress";
// Call any registered WordPress Ability with compiled input/output types
export const runSiteCheck = action({
access: "admin",
readonly: true,
input: { target: text().max(120) },
async handler({ target }) {
return await abilities.call("core/get-site-info", {});
},
});14Hosting, Deployment, Packaging & CLI Reference
Because SpacePress compiles down to standard PHP and WordPress plugins, you can deploy anywhere WordPress runs — Spacefast, Pressable, WordPress.com, self-hosted WordPress (VPS/Docker/LAMP), or static CDN hosting (with output: "static").
| Command | Purpose |
|---|
typedpress dev / dev stop / dev status | Start, stop, or inspect the local WordPress + SQLite dev server with automatic rebuilds on file change. |
typedpress check | Type-check and validate schemas, hooks, actions, pages, and migrations without writing output (supports --json and --frozen for CI). |
typedpress build | Emit WordPress plugins into tp/dist/wp-content/plugins/, SQL migrations, db.d.ts, openapi.json, and typed client. |
typedpress export | Export tp/app/ as a standalone static HTML site to tp/dist/static/ (when output: "static"). |
typedpress sync | Two-way sync between local Markdown/JSON content files and the WordPress database. |
typedpress add <shop|db|api-reference> | Add starter modules into your project as source files you own (never overwrites existing files). |
typedpress plugin | Write uploadable typedpress.zip for manual activation inside wp-admin. |
typedpress login <url> & typedpress push | Authenticate via WordPress Application Passwords and deploy your compiled app, plugins, and migrations directly to a live site. |
typedpress doctor | Verify build integrity, plugin versions, live site state, and (with --links) crawl every internal link and anchor. |
typedpress wp ..., migrate, jobs, staged, identity | Direct site operations via WP-CLI against local dev or remote --site targets. |
Boot a full multi-file SpacePress app in WordPress Playground
Try editing Field Notes (full-site) below — it combines collections, field-level access rules, a SQL applause table, a server action, dynamic TSX routes, a custom JSON Feed route, and a "use client" island. Compile it live and click Run in WordPress to test it in-tab.