@pylonsync/create-pylon 0.22.68 → 0.22.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/create-pylon.js +173 -46
- package/package.json +2 -1
- package/skill/SKILL.md +1279 -0
- package/templates/ai-studio/functions/_getGeneration.ts +4 -4
- package/templates/ai-studio/functions/pollGeneration.ts +9 -4
- package/templates/backend/b2b/apps/api/functions/archiveProject.ts +4 -6
- package/templates/backend/b2b/apps/api/functions/createOrg.ts +2 -1
- package/templates/backend/b2b/apps/api/functions/createProject.ts +2 -5
- package/templates/backend/b2b/apps/api/functions/inviteMember.ts +2 -10
- package/templates/backend/b2b/apps/api/functions/orgMembers.ts +6 -6
- package/templates/backend/b2b/apps/api/functions/orgProjects.ts +2 -5
- package/templates/backend/b2b/apps/api/functions/removeMember.ts +2 -6
- package/templates/backend/b2b/apps/api/functions/setMemberRole.ts +2 -7
package/skill/SKILL.md
ADDED
|
@@ -0,0 +1,1279 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pylon
|
|
3
|
+
description: Build real full-stack apps with Pylon — schema, policies, server functions, server-rendered React (SSR), sync, and one-command deploy. Agent-native and production-grade. Use when the user is working in a Pylon project or asks to build with Pylon/Pylonsync.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Pylon — the agent-native full-stack framework
|
|
7
|
+
|
|
8
|
+
You are helping build a real application on **Pylon** (pylonsync.com), an agent-native full-stack framework written in Rust with a TypeScript SDK. **Pylon renders your React frontend AND runs your backend** — schema, live queries, auth, server functions, jobs, search, and native server-side rendering, all on one port. It's a Rust server that runs your TypeScript and SSR on Bun. SQLite by default or Postgres. It's production infrastructure, not a sandbox: real auth, row-level policies, and one-command deploy — build like it ships. This skill gives you the shape, conventions, and gotchas to build Pylon apps correctly.
|
|
9
|
+
|
|
10
|
+
**Scaffold a new app with `npm create @pylonsync/pylon@latest my-app`** — the default template (`barebones`) is the smallest full-stack SSR app that runs: one entity, a live list, optimistic create. To pass options through npm, put `--` before them: `npm create @pylonsync/pylon@latest my-app -- --template saas`. **Building an actual product? `--template saas`** — marketing landing, multi-tenant dashboard (orgs, members, tenant-scoped data), first-run onboarding wizard, pricing page, auth (password, email code, Google, reset) and Stripe billing with a trial already wired. **Shipping a mobile app? `--template mobile`** — an Expo Router app with guest-first onboarding, Sign in with Apple / Google / email code, a RevenueCat paywall (`@pylonsync/revenuecat`), offline sync, EAS build profiles, and `STORE.md`, the App Store submission checklist; the backend lives in `apps/api` and also serves the app's public website (landing page, `/support`, `/privacy`, `/terms`, copy in `lib/site.ts`), so the privacy-policy URL both stores demand is live on the same host as the API from the first deploy. `npm create @pylonsync/pylon@latest --help` lists the rest (crm, helpdesk, shop, chat, …). Needs **no global install**: `@pylonsync/cli` ships as a devDependency, so `npm run dev` runs the server. Prefer this. `pylon init` (needs the global CLI) scaffolds a **backend-only** app by default — add `--frontend nextjs|react|tanstack` to pair a separate frontend host. Global CLI install: `curl -fsSL https://www.pylonsync.com/install.sh | bash` (Windows: `powershell -c "irm https://www.pylonsync.com/install.ps1 | iex"`). **Bun ≥ 1.0 must be on PATH** — the Rust server spawns Bun to run your TypeScript + SSR.
|
|
11
|
+
|
|
12
|
+
## Authoritative references
|
|
13
|
+
|
|
14
|
+
This skill is a starting point, not the ceiling. When the user asks something this skill doesn't cover — a specific error code, an edge case, a feature not discussed below — fetch the source of truth:
|
|
15
|
+
|
|
16
|
+
- **Full docs index + concept map:** <https://docs.pylonsync.com/llms.txt> — fetch this first for a condensed overview of every doc page with links.
|
|
17
|
+
- **Docs site:** <https://docs.pylonsync.com/> — human docs covering Get started, Core concepts, Auth, Plugins, Clients, Cloud, Operations, and Compare-vs-X pages.
|
|
18
|
+
- **Source of truth for APIs:** the TypeScript source that ships in each npm package (`node_modules/@pylonsync/sdk`, `@pylonsync/functions`, `@pylonsync/react`, `@pylonsync/react-native`, `@pylonsync/next`), the Swift SDK at <https://github.com/pylonsync/pylon-swift>, and the C# / Unity SDK at <https://github.com/pylonsync/pylon-csharp>. When in doubt about a method name or signature, read the source, not your training data.
|
|
19
|
+
- **Working example apps:** <https://github.com/pylonsync/pylon-examples> — full apps covering CRM, ERP, chat, 3D, dashboards, plus `examples/swift-todo` for the iOS/macOS SDK.
|
|
20
|
+
- **Stack0 Cloud:** <https://cloud.stack0.dev> — managed Pylon. Same binary, same APIs, no infra to run.
|
|
21
|
+
- **This skill file (latest):** <https://www.pylonsync.com/pylon-skill.md> — re-fetch if the user reports the skill is out of date.
|
|
22
|
+
|
|
23
|
+
**Rule:** if you're about to use an API name or pattern you're not 100% sure exists, fetch the source or docs first. The SDK aliases the common naming variants (see the type table below), but anything outside that table that sounds plausible (`v.money()`, `v.enum()`, `v.timestamp()`) is probably hallucinated. (`db.useAggregate`, `db.useReactiveQuery`, `db.useSearch`, `useRoom`, `useShard` ARE real — see the realtime hooks below.)
|
|
24
|
+
|
|
25
|
+
## When to use this skill
|
|
26
|
+
|
|
27
|
+
Use this skill whenever:
|
|
28
|
+
- The user's project has a `pylon.manifest.json`, `app.ts` importing from `@pylonsync/*`, or a `functions/` directory next to an `app.ts`.
|
|
29
|
+
- The user's Swift project imports `PylonClient`, `PylonSync`, `PylonRealtime`, or `PylonSwiftUI`.
|
|
30
|
+
- The user's Unity or C# project uses `Pylon.PylonClient` or `Pylon.Realtime.ShardConnection`.
|
|
31
|
+
- The user says "Pylon", "Pylonsync", "realtime backend", or asks to build a live-syncing feature.
|
|
32
|
+
- The user runs `pylon dev`, `pylon init`, `pylon deploy`, `pylon codegen`, or another `pylon` CLI command.
|
|
33
|
+
- The user mentions Stack0 Cloud, `cloud.stack0.dev`, or `pylon deploy --target cloud`.
|
|
34
|
+
|
|
35
|
+
## Core mental model
|
|
36
|
+
|
|
37
|
+
A Pylon app is five things, all served on one port (a Rust server that runs your TypeScript and SSR on Bun):
|
|
38
|
+
|
|
39
|
+
1. **Entities** — typed tables declared in `app.ts` via the `@pylonsync/sdk` DSL. Pylon auto-migrates your database (SQLite by default, or Postgres via `DATABASE_URL`) to match.
|
|
40
|
+
2. **Policies** — row-level access rules evaluated as string expressions. Live alongside entities.
|
|
41
|
+
3. **Functions** — server TypeScript in `functions/*.ts`. Three flavors: `query`, `mutation`, `action`. RPC-called by the client.
|
|
42
|
+
4. **Live queries** — `db.useQuery(...)` in React subscribes to results. Pylon restreams diffs on every relevant mutation.
|
|
43
|
+
5. **SSR frontend** — your React app under `app/`, server-rendered by the SAME binary. Next-style file routing (`app/**/page.tsx`), `<Link>`/`<Image>`, `metadata`/`generateMetadata`, `loading.tsx`/`error.tsx`/`not-found.tsx`, `sitemap.ts`/`robots.ts`. No separate Next.js host, no `/api` proxy, one shared session on every request. (Headless/native-only apps can skip the frontend; the backend works on its own.)
|
|
44
|
+
|
|
45
|
+
## Directory convention (full-stack SSR app — the default)
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
my-app/
|
|
49
|
+
app.ts # schema + policies + manifest — ENTRY POINT
|
|
50
|
+
functions/ # server functions, one per file, default-exported
|
|
51
|
+
createX.ts
|
|
52
|
+
app/ # SSR frontend — Next-style file routing, server-rendered
|
|
53
|
+
layout.tsx # root layout (wraps every page)
|
|
54
|
+
page.tsx # route "/"
|
|
55
|
+
globals.css # Tailwind v4 entry; Pylon compiles + injects it
|
|
56
|
+
blog/
|
|
57
|
+
page.tsx # route "/blog"
|
|
58
|
+
[slug]/page.tsx # dynamic route "/blog/:slug"
|
|
59
|
+
sitemap.ts # served at /sitemap.xml (optional)
|
|
60
|
+
robots.ts # served at /robots.txt (optional)
|
|
61
|
+
components/ # your components (see the layering table below)
|
|
62
|
+
ui/ # shadcn primitives — button, card, input, label,
|
|
63
|
+
# select, badge, table, textarea
|
|
64
|
+
components.json # shadcn config — `bunx shadcn@latest add <name>` works
|
|
65
|
+
lib/utils.ts # `cn` (clsx + tailwind-merge)
|
|
66
|
+
public/ # static assets served verbatim at the root; a real file
|
|
67
|
+
# beats [param]/catch-all route matches (≥0.3.381),
|
|
68
|
+
# static route paths beat files — Next semantics
|
|
69
|
+
package.json # deps: @pylonsync/sdk, @pylonsync/functions, @pylonsync/react, @pylonsync/client, react, react-dom
|
|
70
|
+
# + @pylonsync/cli as a devDependency (so `npm run dev` needs no global install)
|
|
71
|
+
pylon.manifest.json # GENERATED — never edit by hand
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`pylon dev` watches `app.ts` + `functions/` + `app/` and regenerates the manifest, recompiles Tailwind, and live-reloads the browser on every save. The manifest's routes are discovered from `app/**` by `discoverAppRoutes()` in `app.ts` (see the scaffold). One server serves the SSR HTML, the hydration JS, the API, and the WebSocket — same origin.
|
|
75
|
+
|
|
76
|
+
(A backend-only app omits `app/` and just ships `app.ts` + `functions/`. Older apps may pair a separate Vite/Next frontend with `@pylonsync/react` + `init()`/`configureClient()` against the Pylon URL — still supported, but native SSR is the default and avoids the second host + the `/api` proxy.)
|
|
77
|
+
|
|
78
|
+
## Schema (`app.ts`)
|
|
79
|
+
|
|
80
|
+
Every Pylon app has an `app.ts` that imports from `@pylonsync/sdk`, declares entities + policies, and calls `buildManifest`.
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { entity, field, policy, buildManifest, discoverAppRoutes, discoverFunctions } from "@pylonsync/sdk";
|
|
84
|
+
|
|
85
|
+
const User = entity(
|
|
86
|
+
"User",
|
|
87
|
+
{
|
|
88
|
+
email: field.string().unique(),
|
|
89
|
+
name: field.string(),
|
|
90
|
+
createdAt: field.datetime(),
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
indexes: [{ name: "by_email", fields: ["email"], unique: true }],
|
|
94
|
+
},
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
const Message = entity(
|
|
98
|
+
"Message",
|
|
99
|
+
{
|
|
100
|
+
roomId: field.id("Room"),
|
|
101
|
+
authorId: field.id("User"),
|
|
102
|
+
body: field.richtext(),
|
|
103
|
+
sentAt: field.datetime(),
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
indexes: [
|
|
107
|
+
{ name: "by_room_time", fields: ["roomId", "sentAt"], unique: false },
|
|
108
|
+
],
|
|
109
|
+
},
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
const messagePolicy = policy({
|
|
113
|
+
name: "message_public_read",
|
|
114
|
+
entity: "Message",
|
|
115
|
+
allowRead: "true",
|
|
116
|
+
allowInsert: "auth.userId == data.authorId",
|
|
117
|
+
allowUpdate: "auth.userId == existing.authorId",
|
|
118
|
+
allowDelete: "auth.userId == existing.authorId",
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
const fns = await discoverFunctions(); // walks functions/*.ts
|
|
122
|
+
|
|
123
|
+
const manifest = buildManifest({
|
|
124
|
+
name: "my-app",
|
|
125
|
+
version: "0.1.0",
|
|
126
|
+
entities: [User, Message],
|
|
127
|
+
policies: [messagePolicy],
|
|
128
|
+
queries: fns.queries,
|
|
129
|
+
actions: fns.actions,
|
|
130
|
+
routes: await discoverAppRoutes(), // full-stack SSR: enumerates app/**/page.tsx (a backend-only app can pass routes: [])
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
console.log(JSON.stringify(manifest, null, 2));
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
**The last line is required** — `pylon dev` runs `bun run app.ts` and captures stdout as the manifest. Top-level `await` works because Bun runs `app.ts` as an ES module.
|
|
137
|
+
|
|
138
|
+
**`discoverFunctions()` is what puts your `functions/*.ts` in the manifest** (pylon ≥ 0.4.7). They are callable at `POST /api/fn/<name>` either way — the router loads them independently — but a manifest built with `queries: []` / `actions: []` reports an app with **zero** endpoints, so `/api/manifest`, the OpenAPI spec, and `pylon codegen` all silently under-report. It mirrors the runtime loader exactly (top-level `.ts`/`.js`, name = basename, default export with a `type` and a `handler`) and excludes `internal: true` functions, which aren't externally callable. Mutations and actions both land in `actions` — the manifest's split is read vs write — with `fnType` preserving which was which.
|
|
139
|
+
|
|
140
|
+
### Field types — EXACT API
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
field.string() // TEXT
|
|
144
|
+
field.int() // INTEGER 64-bit
|
|
145
|
+
field.float() // REAL 64-bit
|
|
146
|
+
field.bool() // 0/1 stored as INTEGER; field.boolean() alias also works
|
|
147
|
+
field.datetime() // ISO-8601 string
|
|
148
|
+
field.richtext() // long-form text
|
|
149
|
+
field.json() // arbitrary JSON value (object/array/scalar), parsed-on-read
|
|
150
|
+
field.id("OtherEntity") // FK to another entity's id column
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`field.json()` hands back the PARSED value on every read path (entity API,
|
|
154
|
+
`serverData`, `ctx.db`, sync events) — never a string to `JSON.parse`
|
|
155
|
+
yourself. Codegen types it `unknown` (narrow with your own row type). On CRDT
|
|
156
|
+
entities the whole value is one LWW register; not searchable, not
|
|
157
|
+
encryptable. The matching arg validator is `v.json()`.
|
|
158
|
+
|
|
159
|
+
**Modifiers (chainable):**
|
|
160
|
+
- `.optional()` — nullable
|
|
161
|
+
- `.unique()` — implicit unique index on one column
|
|
162
|
+
- `.default(value)` — static insert-time default (e.g. `field.bool().default(false)`)
|
|
163
|
+
- `.defaultNow()` — datetime defaults to insert time (e.g. `createdAt: field.datetime().defaultNow()`)
|
|
164
|
+
- `.owner()` — stamps the field with `auth.userId` on insert and **rejects a forged value** (403 `OWNER_MISMATCH`); also locked on update. Use for `authorId`/`buyerId`/`createdBy` so optimistic `db.insert` stays secure. Guests count (their stable guest id is stamped).
|
|
165
|
+
- `.serverOnly()` — never serialized in HTTP responses (secrets, `passwordHash`, `stripeCustomerId`). Still readable inside functions via `ctx.db.*`.
|
|
166
|
+
- `.syncOmit()` — stripped from REPLICATION only (snapshots, delta events, WS fanout, reconcile fetches); direct reads (`db.get`, lists, queries, SSR `serverData`) keep it. For heavy-but-not-secret columns — multi-KB JSON blobs, render plans, generated markdown — that would otherwise stream into every browser's replica on every sync. The replica row simply lacks the column; fetch by id when a detail view needs it. Declare such fields `.optional()` so the replica-row type is honest.
|
|
167
|
+
- `.max(n)` — string/richtext only: reject values over `n` characters with `400 FIELD_TOO_LONG` on every write path (entity API, sync push, `ctx.db`, CRDT edits). Put one on every user-writable text field; without it a guest can store up to the 10 MB body cap and every client syncs it. Per-caller limits in a policy: `data.bio == null || len(data.bio) <= 280` (`len` of null is null, which denies, so allow null explicitly on optional fields).
|
|
168
|
+
- `.readonly()` — settable on insert, rejected on client update (closes IDOR-via-PATCH).
|
|
169
|
+
- `entity(name, fields, { audit: true })` — every insert/update/delete lands in the audit log (actor, tenant, row id, changed field names; not values).
|
|
170
|
+
- `entity(name, fields, { retention: { field: "createdAt", after: "365d", hold: "legalHold" } })` — hourly job deletes expired rows (audited as `retention.delete`); omit `after` to treat `field` as a per-row expiry time (per-tenant periods).
|
|
171
|
+
- `.encrypted()` — AEAD-encrypted at rest (needs `PYLON_ENCRYPTION_KEY`; rotate by moving the old key to `PYLON_ENCRYPTION_PREVIOUS_KEYS` — a background pass re-encrypts, `POST /api/admin/encryption/rotate` runs one now).
|
|
172
|
+
- `.crdt("text")` — upgrade string/richtext to LoroText for collaborative merge
|
|
173
|
+
|
|
174
|
+
`field.enum(["pending", "paid", "failed"])` also exists (stored as a string with allowed-values metadata so codegen emits a precise literal union). Note: there is **no `v.enum()`** validator counterpart — validate an enum arg with `v.union(v.literal("pending"), v.literal("paid"), ...)` or a plain `v.string()`.
|
|
175
|
+
|
|
176
|
+
**Common mistakes to avoid:**
|
|
177
|
+
- Both `field.float()` / `field.number()` work (same type). Both `field.bool()` / `field.boolean()` work. Pick whichever reads better.
|
|
178
|
+
- `field.id()` without an entity argument **is invalid** — always pass the target entity name.
|
|
179
|
+
- Scalar fields are LWW by default. Use `field.richtext()` or `.crdt("text")` when concurrent text edits should merge.
|
|
180
|
+
|
|
181
|
+
### Indexes
|
|
182
|
+
|
|
183
|
+
Declare composite indexes in the options block. Live queries use indexed columns for fast fan-out — **index the filter columns you'll query on.**
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
{
|
|
187
|
+
indexes: [
|
|
188
|
+
{ name: "by_user", fields: ["userId"], unique: false },
|
|
189
|
+
{ name: "by_user_created", fields: ["userId", "createdAt"], unique: false },
|
|
190
|
+
],
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Replication — `sync: false` for append-only tables
|
|
195
|
+
|
|
196
|
+
Entities default to **`sync: true`**: bulk-snapshotted and delta-streamed into
|
|
197
|
+
every signed-in browser's local replica. That default is right for the working
|
|
198
|
+
set a page renders from, and **wrong for anything that grows forever.**
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
const UsageWindow = entity(
|
|
202
|
+
"UsageWindow",
|
|
203
|
+
{ projectId: field.id("Project"), periodStart: field.datetime(), requests: field.int() },
|
|
204
|
+
{
|
|
205
|
+
indexes: [{ name: "by_project_period", fields: ["projectId", "periodStart"], unique: true }],
|
|
206
|
+
sync: false, // read it through a function, not the replica
|
|
207
|
+
},
|
|
208
|
+
);
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
**Rule: if the table is append-only, or no component reads it via
|
|
212
|
+
`db.useQuery`, set `sync: false`.** Typical: usage/metering rollups, audit and
|
|
213
|
+
event logs, billing history, job runs, notifier cursors, anything server-only.
|
|
214
|
+
|
|
215
|
+
**When you still want it live, scope it instead of disabling it.** `sync`
|
|
216
|
+
takes an object — the middle setting between "every row you can read" and
|
|
217
|
+
"nothing":
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
const Message = entity(
|
|
221
|
+
"Message",
|
|
222
|
+
{ roomId: field.id("Room"), body: field.richtext(), sentAt: field.datetime() },
|
|
223
|
+
{
|
|
224
|
+
indexes: [{ name: "by_room_time", fields: ["roomId", "sentAt"], unique: false }],
|
|
225
|
+
sync: { where: "data.roomId == auth.tenantId", limit: 5_000 },
|
|
226
|
+
},
|
|
227
|
+
);
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
- `where` is the SAME expression language as policies (`exists(...)` included),
|
|
231
|
+
evaluated per row per caller.
|
|
232
|
+
- **Rolling time window** — the right scope for append-only, timestamp-shaped
|
|
233
|
+
data that must stay live (analytics events, activity feeds):
|
|
234
|
+
`sync: { where: 'data.sentAt >= ago("30d")' }`. The replica and every
|
|
235
|
+
catch-up stay bounded no matter how big the table grows; the periodic
|
|
236
|
+
reconcile sweep evicts rows as they age out of the window. Older rows stay
|
|
237
|
+
reachable through direct reads and queries. Combine with `limit` as the
|
|
238
|
+
hard ceiling.
|
|
239
|
+
- It is applied **on top of** the read policy, never instead of it. A scope
|
|
240
|
+
only ever REMOVES rows from a replica, so getting one wrong is a
|
|
241
|
+
missing-data bug, never a leak — and a malformed one denies rather than
|
|
242
|
+
falling back to replicating everything.
|
|
243
|
+
- `limit` is a hard per-client ceiling that survives snapshot pagination.
|
|
244
|
+
Belt to `where`'s braces.
|
|
245
|
+
- A row that **leaves** scope is pushed as a DELETE, so replicas evict it
|
|
246
|
+
instead of holding a copy that never updates again.
|
|
247
|
+
- Replication only. Direct reads (`/api/entities/X`, `/api/search/X`) are
|
|
248
|
+
unscoped, same promise as `sync: false` — so an archive view or admin report
|
|
249
|
+
still sees everything its policy allows.
|
|
250
|
+
|
|
251
|
+
`sync: false` keeps the entity out of the replica **only**. Policies, direct
|
|
252
|
+
reads (`/api/entities/X`), `db.useSearch`, and `ctx.db.*` inside functions are
|
|
253
|
+
all unchanged — so serve it with a query/action that returns the window the UI
|
|
254
|
+
actually renders (`limit: 168`, not the whole table).
|
|
255
|
+
|
|
256
|
+
Write a `sync: false` entity with a mutation (`ctx.db.insert/update/delete`) or
|
|
257
|
+
`/api/entities/X`, never through the client replica (`db.insert` in the sync
|
|
258
|
+
engine): no change is echoed back for it, so an optimistic row would vanish on
|
|
259
|
+
the next reconcile. `/api/sync/push` refuses such a write with
|
|
260
|
+
`ENTITY_NOT_SYNCED`.
|
|
261
|
+
|
|
262
|
+
Why it matters: the replica bootstrap walks a synced table **one cursor page at
|
|
263
|
+
a time, sequentially** — page N+1 needs page N's last id, so cold-start latency
|
|
264
|
+
is `rows / pageSize × round-trip`. A real app shipped a per-project-per-hour
|
|
265
|
+
rollup with the default on; a page load became ~100 chained requests at ~95ms,
|
|
266
|
+
about ten seconds of loading, for data no component read. It is invisible on
|
|
267
|
+
day one and unbearable by month three, so decide when you declare the entity.
|
|
268
|
+
|
|
269
|
+
## Policies
|
|
270
|
+
|
|
271
|
+
Policies are boolean string expressions. They guard direct `/api/entities/*` access (and sync). Server functions bypass policies — trust yourself to check inside handlers.
|
|
272
|
+
|
|
273
|
+
**Default-deny is the headline rule: an entity with NO registered policy refuses EVERY request** (`_default_deny`). This is the deliberate fix for the "forgot to lock the table" footgun — a new entity is invisible until you write its policy. For an intentionally-public entity, be explicit: `policy({ entity: "X", allowRead: "true" })`.
|
|
274
|
+
|
|
275
|
+
**Bindings available in expressions:**
|
|
276
|
+
- `auth.userId` — `string | null`
|
|
277
|
+
- `auth.isAdmin` — `boolean` (true for the `admin` role / admin token / Studio cookie)
|
|
278
|
+
- `auth.tenantId` — `string | null` (the selected org, for multi-tenant apps)
|
|
279
|
+
- `data.*` — the row: incoming payload on insert; the **stored row** on read/delete; on update, see below
|
|
280
|
+
- `existing.*` — synonym for `data.*`; use whichever reads clearer
|
|
281
|
+
- `now` — current UTC time as an ISO-8601 string, for time windows
|
|
282
|
+
- `ago("30d")` — the instant that long before `now`, for ROLLING windows (`data.createdAt >= ago("30d")`). Units `s/m/h/d/w`, compound allowed (`"1d12h"`); a bad duration fails at boot, not silently at eval
|
|
283
|
+
|
|
284
|
+
Roles are checked with the **`auth.hasRole("x")` / `auth.hasAnyRole("a", "b")` functions** — there is **no `auth.roles` array and no `auth.email`** binding in policy expressions. (The SSR page `auth` prop and the session DO expose roles/email; the policy evaluator does not.)
|
|
285
|
+
|
|
286
|
+
**Actions:**
|
|
287
|
+
- `allowRead` — applied to query results; unmatched rows are filtered out silently.
|
|
288
|
+
- `allowInsert` / `allowUpdate` / `allowDelete` — reject the op with `POLICY_DENIED` if false.
|
|
289
|
+
- **`allowUpdate` runs twice: on the stored row, then on the row after the write** (stored row + patched fields). Both must pass. With `auth.tenantId == data.orgId`, a member can edit their org's rows but a patch of `{ orgId: "<other org>" }` is denied. This applies to every client write path: `PATCH /api/entities`, `/api/sync/push`, `/api/link`, `/api/unlink`, and CRDT pushes. A state change the rule forbids for the new row (`data.status == "draft"` and an edit that publishes) is denied too; do that change in a server function.
|
|
290
|
+
- `allowDelete` runs on the stored row.
|
|
291
|
+
- **Omitted actions default to deny.**
|
|
292
|
+
|
|
293
|
+
**Operators — the COMPLETE set (the policy language is deliberately tiny):**
|
|
294
|
+
```
|
|
295
|
+
== != // equality
|
|
296
|
+
< <= > >= // ordering (numbers; timestamps if both are ISO-8601; else lexicographic)
|
|
297
|
+
&& || ! // boolean logic
|
|
298
|
+
true false null // literals
|
|
299
|
+
42 -3 4.5 // numeric literals (int / float / negative)
|
|
300
|
+
"string" 'string' // string literals (either quote)
|
|
301
|
+
auth.hasRole("admin") // role check
|
|
302
|
+
auth.hasAnyRole("admin", "owner") // any-of role check
|
|
303
|
+
ago("30d") // timestamp <duration> before now (s/m/h/d/w)
|
|
304
|
+
len(data.bio) // string length in characters (not a string → null → deny-safe)
|
|
305
|
+
exists(Entity where field == <expr> [and field == <expr>]*) // correlated subquery
|
|
306
|
+
```
|
|
307
|
+
Ordering is **deny-safe**: comparing null, booleans, or a number against a non-numeric string is always false (so an unresolvable `data.publishAt <= now` denies). Still **no `in`, no `ends_with`/`starts_with`, no arithmetic (`+ - * /`).** Membership ("is the user in this org?") is `exists(...)`, not `in`. String prefix/suffix matching still belongs in a function.
|
|
308
|
+
|
|
309
|
+
**Typical patterns:**
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
// Public read, author-only write
|
|
313
|
+
policy({
|
|
314
|
+
name: "post_public",
|
|
315
|
+
entity: "Post",
|
|
316
|
+
allowRead: "true",
|
|
317
|
+
allowInsert: "auth.userId == data.authorId",
|
|
318
|
+
allowUpdate: "auth.userId == existing.authorId",
|
|
319
|
+
allowDelete: "auth.userId == existing.authorId",
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
// Member-of-org — membership lives in a join entity, checked with exists()
|
|
323
|
+
// NOTE: `Document` must actually HAVE an `orgId` field — see below.
|
|
324
|
+
policy({
|
|
325
|
+
name: "doc_members",
|
|
326
|
+
entity: "Document",
|
|
327
|
+
allowRead: "exists(OrgMember where orgId == existing.orgId and userId == auth.userId)",
|
|
328
|
+
allowInsert: "exists(OrgMember where orgId == data.orgId and userId == auth.userId)",
|
|
329
|
+
allowUpdate: "exists(OrgMember where orgId == existing.orgId and userId == auth.userId)",
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
// Admin-only
|
|
333
|
+
policy({
|
|
334
|
+
name: "audit_admin",
|
|
335
|
+
entity: "AuditLog",
|
|
336
|
+
allowRead: "auth.isAdmin", // or: auth.hasRole("admin")
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
// Multi-tenant row scoping
|
|
340
|
+
policy({
|
|
341
|
+
name: "ticket_tenant",
|
|
342
|
+
entity: "Ticket",
|
|
343
|
+
allowRead: "auth.tenantId == existing.orgId",
|
|
344
|
+
allowInsert: "auth.tenantId == data.orgId",
|
|
345
|
+
});
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
**Tenant-scoped reads make org switching SLOW.** `auth.tenantId == data.orgId`
|
|
349
|
+
means the visible set changes on every org switch, so the sync engine must
|
|
350
|
+
wipe the replica and re-bootstrap from zero (blank dashboard for seconds).
|
|
351
|
+
For apps where users belong to multiple orgs, prefer MEMBERSHIP-scoped reads
|
|
352
|
+
— `allowRead: "exists(OrgMember where orgId == data.orgId and userId ==
|
|
353
|
+
auth.userId)"` — then the replica is valid across all the user's orgs at
|
|
354
|
+
once, and passing `resetOnTenantFlip: false` in the engine/provider config
|
|
355
|
+
makes an org switch instant: no wipe, no re-pull, the UI just filters by the
|
|
356
|
+
live `tenantId` (a background reconcile picks up rows of orgs joined since
|
|
357
|
+
the last snapshot). Do NOT set that flag with tenant-scoped reads — it would
|
|
358
|
+
keep stale rows across switches. Writes and functions may keep using
|
|
359
|
+
`auth.tenantId` either way.
|
|
360
|
+
|
|
361
|
+
```ts
|
|
362
|
+
|
|
363
|
+
// Time window: published posts are public; scheduled ones stay hidden until their time
|
|
364
|
+
policy({
|
|
365
|
+
name: "post_published",
|
|
366
|
+
entity: "Post",
|
|
367
|
+
allowRead: "data.publishAt <= now || auth.userId == data.authorId",
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
// Threshold: only show rows at or above a priority
|
|
371
|
+
policy({
|
|
372
|
+
name: "ticket_priority",
|
|
373
|
+
entity: "Ticket",
|
|
374
|
+
allowRead: "data.priority >= 3",
|
|
375
|
+
});
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
**Read policies run PER ROW. `exists(...)` in one is a query per row.**
|
|
379
|
+
|
|
380
|
+
A tenant gate like
|
|
381
|
+
|
|
382
|
+
```ts
|
|
383
|
+
allowRead: `auth.tenantId == data.orgId && (
|
|
384
|
+
exists(Subscription where referenceId == data.orgId and status == "active") ||
|
|
385
|
+
exists(Subscription where referenceId == data.orgId and status == "trialing")
|
|
386
|
+
)`
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
is evaluated against **every row** of a snapshot, a cursor page, and a list —
|
|
390
|
+
so on a synced stat table it becomes thousands of identical subqueries per
|
|
391
|
+
page load. The runtime memoizes `exists(...)` within a single scan, which
|
|
392
|
+
collapses that to one query per distinct question, but the shape still costs
|
|
393
|
+
more than it looks:
|
|
394
|
+
|
|
395
|
+
- Put the cheap, data-independent test FIRST (`auth.userId != null &&
|
|
396
|
+
exists(...)`) — `&&` short-circuits, so a failing gate never runs the
|
|
397
|
+
subquery.
|
|
398
|
+
- Gate on something already ON the row where you can. `data.orgId ==
|
|
399
|
+
auth.tenantId` needs no subquery at all.
|
|
400
|
+
- A subscription/plan check is per-ORG, not per-row. Prefer denying the whole
|
|
401
|
+
entity via a function, or stamping the row, over re-asking per row.
|
|
402
|
+
- Pair an expensive policy with `sync: false` or a `sync` scope, so the
|
|
403
|
+
expression isn't run across a whole growing table on every connect.
|
|
404
|
+
|
|
405
|
+
**Gotcha: a policy that names a field the entity doesn't have denies
|
|
406
|
+
everything, silently.** An unresolvable reference is null, and null fails
|
|
407
|
+
closed — `exists(OrgMember where orgId == data.orgId ...)` on an entity keyed
|
|
408
|
+
`projectId` (no `orgId`) matches nothing, for everyone, forever. There is no
|
|
409
|
+
error and no warning: it reads exactly like a working membership check, and the
|
|
410
|
+
symptom is "the table looks empty" rather than "access denied".
|
|
411
|
+
|
|
412
|
+
Failing closed is the right default — the alternative leaks reads on a typo —
|
|
413
|
+
but it means **you must check the field exists on THAT entity** when you copy a
|
|
414
|
+
policy between entities. This shipped in a real app and stayed unnoticed
|
|
415
|
+
because the one page that displayed the data read it through a function
|
|
416
|
+
(functions bypass policies), so nothing appeared broken.
|
|
417
|
+
|
|
418
|
+
## Functions (`functions/*.ts`)
|
|
419
|
+
|
|
420
|
+
Three flavors, all default-exported. The **filename** becomes the RPC name — `functions/createIssue.ts` is callable at `POST /api/fn/createIssue`.
|
|
421
|
+
|
|
422
|
+
### Auth levels — read this before you write a public/pre-login feature
|
|
423
|
+
|
|
424
|
+
Every `query` / `mutation` / `action` carries an `auth` level. **The default is `"user"`.** The router enforces it *before* your handler runs — a caller who doesn't meet the bar gets a typed rejection and the handler never executes. The four levels:
|
|
425
|
+
|
|
426
|
+
| `auth:` | Who can call it | Use for |
|
|
427
|
+
|---|---|---|
|
|
428
|
+
| `"user"` **(default)** | A real signed-in user. **Guest sessions are REJECTED.** | Everything behind login. `ctx.auth.userId` narrows to `string`. |
|
|
429
|
+
| `"guest"` | Guest sessions (`/api/auth/guest`) **and** signed-in users | Pre-login state: carts, public demos, "try it before signing up". |
|
|
430
|
+
| `"public"` | Anyone, including fully unauthenticated | Webhook receivers, healthchecks, landing-page form submits. |
|
|
431
|
+
| `"admin"` | `ctx.auth.isAdmin === true` | Ops endpoints. |
|
|
432
|
+
|
|
433
|
+
**THE gotcha (this bites everyone): a guest session cannot call a default (`auth: "user"`) function.** If you mint a guest with `POST /api/auth/guest` and then `callFn("addToCart", …)`, the call fails with `401 AUTH_REQUIRED` ("requires a session — sign in or POST /api/auth/guest first") **unless that function declares `auth: "guest"`**. Public demos, pre-login carts, and anonymous "kick the tires" flows must set `auth: "guest"` (or `"public"`) on **every** function they call. Forgetting this is the #1 reason a scaffolded public demo returns 401s.
|
|
434
|
+
|
|
435
|
+
```ts
|
|
436
|
+
export default mutation({
|
|
437
|
+
auth: "guest", // guest sessions AND users may call this
|
|
438
|
+
args: { sku: v.string() },
|
|
439
|
+
async handler(ctx, args) { /* ctx.auth.userId may be null — check it */ },
|
|
440
|
+
});
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
### Validators — EXACT API
|
|
444
|
+
|
|
445
|
+
Import from `@pylonsync/functions`:
|
|
446
|
+
|
|
447
|
+
```ts
|
|
448
|
+
v.string()
|
|
449
|
+
v.int()
|
|
450
|
+
v.number() / v.float() // 64-bit float (both names work)
|
|
451
|
+
v.boolean() / v.bool() // boolean (both names work)
|
|
452
|
+
v.datetime() // ISO-8601 string
|
|
453
|
+
v.richtext() // richtext string
|
|
454
|
+
v.id("Entity")
|
|
455
|
+
v.optional(v.string())
|
|
456
|
+
v.array(v.string())
|
|
457
|
+
v.literal("open") // exact string/number/bool
|
|
458
|
+
v.object({ k: v.string() })
|
|
459
|
+
v.union(v.literal("a"), v.literal("b")) // discriminated union / enum-of-literals
|
|
460
|
+
v.null()
|
|
461
|
+
v.any()
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
`v.float()` and `v.number()` are aliases for the same 64-bit float validator. Use whichever matches your `field.*` choice.
|
|
465
|
+
|
|
466
|
+
### Mutation pattern
|
|
467
|
+
|
|
468
|
+
```ts
|
|
469
|
+
// functions/createIssue.ts
|
|
470
|
+
import { mutation, v } from "@pylonsync/functions";
|
|
471
|
+
|
|
472
|
+
export default mutation({
|
|
473
|
+
args: {
|
|
474
|
+
teamId: v.id("Team"),
|
|
475
|
+
title: v.string(),
|
|
476
|
+
description: v.optional(v.string()),
|
|
477
|
+
priority: v.optional(v.int()),
|
|
478
|
+
},
|
|
479
|
+
// `auth: "user"` is the default — the framework rejects BOTH anon
|
|
480
|
+
// AND guest callers BEFORE the handler runs, so `ctx.auth.userId` is
|
|
481
|
+
// `string` (not nullable) here. Use `auth: "guest"` for pre-login
|
|
482
|
+
// callers, `auth: "public"` for webhooks/healthchecks.
|
|
483
|
+
async handler(ctx, args) {
|
|
484
|
+
const id = await ctx.db.insert("Issue", {
|
|
485
|
+
teamId: args.teamId,
|
|
486
|
+
title: args.title,
|
|
487
|
+
description: args.description ?? null,
|
|
488
|
+
priority: args.priority ?? 0,
|
|
489
|
+
authorId: ctx.auth.userId,
|
|
490
|
+
createdAt: new Date().toISOString(),
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
return { id };
|
|
494
|
+
},
|
|
495
|
+
});
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
### Query pattern
|
|
499
|
+
|
|
500
|
+
```ts
|
|
501
|
+
// functions/listIssues.ts
|
|
502
|
+
import { query, v } from "@pylonsync/functions";
|
|
503
|
+
|
|
504
|
+
export default query({
|
|
505
|
+
args: { teamId: v.id("Team") },
|
|
506
|
+
async handler(ctx, args) {
|
|
507
|
+
return ctx.db.query("Issue", { teamId: args.teamId });
|
|
508
|
+
},
|
|
509
|
+
});
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
Queries are **live** when called from the React hook — the client subscribes and re-runs on relevant mutations.
|
|
513
|
+
|
|
514
|
+
### Action pattern (side effects — emails, external HTTP)
|
|
515
|
+
|
|
516
|
+
```ts
|
|
517
|
+
// functions/sendInvite.ts
|
|
518
|
+
import { action, v } from "@pylonsync/functions";
|
|
519
|
+
|
|
520
|
+
export default action({
|
|
521
|
+
// Default `auth: "user"` — anon POSTs to this endpoint never reach
|
|
522
|
+
// the handler. CRITICAL for actions: policies don't gate them, so
|
|
523
|
+
// a forgotten auth check on an action that calls Stripe/Resend/etc.
|
|
524
|
+
// = open vulnerability. `auth: "public"` for webhook receivers only.
|
|
525
|
+
args: { email: v.string(), orgId: v.id("Org") },
|
|
526
|
+
async handler(ctx, args) {
|
|
527
|
+
// Built-in transactional email — no HTTP call, uses the runtime's
|
|
528
|
+
// PYLON_EMAIL_* provider (sendgrid / resend / stack0 / webhook):
|
|
529
|
+
await ctx.email.send(args.email, "Invite", "You're invited!");
|
|
530
|
+
// Options form adds HTML + base64 attachments (contentType passes
|
|
531
|
+
// through verbatim, so `text/calendar; method=REQUEST` invites work):
|
|
532
|
+
// await ctx.email.send({ to, subject, text, html?, attachments? });
|
|
533
|
+
// (Or hit an external HTTP API directly with fetch(...) + ctx.env.KEY.)
|
|
534
|
+
return { ok: true };
|
|
535
|
+
},
|
|
536
|
+
});
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
**Actions have NO `ctx.db`.** They're for external I/O and are non-transactional. To read/write data from an action, call a registered function: `ctx.runQuery("listX", args)` / `ctx.runMutation("createX", args)` (each runs in its own transaction). Use mutations for atomic multi-row writes.
|
|
540
|
+
|
|
541
|
+
### `ctx` surface (inside handlers)
|
|
542
|
+
|
|
543
|
+
**The three ctx shapes are NOT the same.** In particular an `action` has **no `ctx.db`**, and a `query` ctx has no `error`/`scheduler`/writes. Don't reach for a field the flavor doesn't have.
|
|
544
|
+
|
|
545
|
+
```ts
|
|
546
|
+
// ---- On EVERY ctx (query / mutation / action) ----
|
|
547
|
+
ctx.auth.userId // string | null (narrows to string when auth: "user"/"admin")
|
|
548
|
+
ctx.auth.isAdmin // boolean
|
|
549
|
+
ctx.auth.tenantId // string | null (selected org)
|
|
550
|
+
ctx.auth.roles // string[] (exact active-org/session role slugs)
|
|
551
|
+
await ctx.auth.elevate({ admin: true, reason: "..." }) // async — promote AFTER you verify a webhook/HMAC
|
|
552
|
+
ctx.env // Record<string,string> — secrets / env (same values as process.env)
|
|
553
|
+
ctx.requireMember(orgId, { role }) // assert org membership/role — throws (UNAUTHENTICATED / MISSING_ORG / FORBIDDEN), fails closed
|
|
554
|
+
// NOTE: there is NO ctx.auth.email on the handler ctx.
|
|
555
|
+
// Need the email? -> const u = await ctx.db.get("User", ctx.auth.userId) (query/mutation only)
|
|
556
|
+
|
|
557
|
+
// ---- query ctx — ctx.db is a READ-ONLY reader (no error, no scheduler, no writes) ----
|
|
558
|
+
ctx.db.get(entity, id) // => row | null
|
|
559
|
+
ctx.db.list(entity) // => row[]
|
|
560
|
+
ctx.db.query(entity, filter) // => row[] filter: { field: value, $gt, $lt, $in, $like, $order, $limit }
|
|
561
|
+
ctx.db.lookup(entity, field, value) // => row | null
|
|
562
|
+
ctx.db.search(entity, spec) // => { hits, facetCounts, total } (needs `.search({...})` on the entity)
|
|
563
|
+
ctx.db.paginate(entity, { cursor, numItems })
|
|
564
|
+
|
|
565
|
+
// ---- mutation ctx — ctx.db ALSO has writes (transactional); + error, scheduler, llm, rooms, stream, connections ----
|
|
566
|
+
ctx.db.insert(entity, data) // => id (string)
|
|
567
|
+
ctx.db.update(entity, id, patch) // => boolean (true if the row existed)
|
|
568
|
+
ctx.db.insertMany(entity, rows) // => ids, in order. Same as insert per row, few round trips: use in imports and loops
|
|
569
|
+
ctx.db.updateMany(entity, [{ id, data }]) // => boolean[] per row. Same as update per row, few round trips
|
|
570
|
+
ctx.db.delete(entity, id) // => boolean
|
|
571
|
+
ctx.db.link(entity, id, relation, targetId) / ctx.db.unlink(entity, id, relation)
|
|
572
|
+
ctx.db.advisoryLock(key) // serialize a TOCTOU-prone quota/uniqueness check
|
|
573
|
+
throw ctx.error("CODE", "message") // typed error → rolls the tx back
|
|
574
|
+
ctx.scheduler.runAfter(delayMs, "fnName", args) // enqueue delayed call; returns the job id
|
|
575
|
+
ctx.scheduler.cancel(jobId) // { cancelled } — false if it already started/finished
|
|
576
|
+
ctx.audit.log({ action: "lead.export", entity, entityId, meta }) // append-only audit event; actor/tenant from session
|
|
577
|
+
ctx.audit.list({ entity, entityId, action, beforeId, limit }) // actions only; caller's tenant (admins: any)
|
|
578
|
+
ctx.scheduler.runAt(unixMs, "fnName", args) // enqueue at a wall-clock time (Unix ms, e.g. new Date(iso).getTime())
|
|
579
|
+
|
|
580
|
+
// ---- action ctx — NO ctx.db. Read/write via runQuery/runMutation; + email, error, scheduler, llm, rooms, stream ----
|
|
581
|
+
ctx.runQuery("fnName", args) // read by invoking a registered query
|
|
582
|
+
ctx.runMutation("fnName", args) // write by invoking a registered mutation (own tx)
|
|
583
|
+
ctx.agents.run("agentName", { input, as: { userId, admin? }, context?, runId? }) // run an agent() as that user; internal or admin (elevated) callers only
|
|
584
|
+
ctx.email.send(to, subject, body) // transactional email via PYLON_EMAIL_* provider
|
|
585
|
+
ctx.email.send({ to, subject, text, html?, attachments? }) // options form: HTML + base64 attachments
|
|
586
|
+
throw ctx.error("CODE", "message")
|
|
587
|
+
ctx.request?.rawBody / ctx.request?.headers // raw HTTP request (verify Stripe/GitHub webhook sigs)
|
|
588
|
+
ctx.request?.url // full public URL (Twilio signs it)
|
|
589
|
+
return ctx.response({ status, contentType, headers, body }) // raw reply from /api/webhooks/<name> (TwiML, empty 200)
|
|
590
|
+
|
|
591
|
+
// ---- mutation + action: LLM, streaming, server push ----
|
|
592
|
+
await ctx.llm.complete(request) // request: { messages, system?, tools?, model?, max_tokens?, temperature? }
|
|
593
|
+
await ctx.llm.stream(request, onEvent, { signal? }) // same request; onEvent fires per delta, resolves with the SAME assembled response. signal aborts → rejects LLM_CANCELLED + closes the provider connection
|
|
594
|
+
ctx.stream.write(text) // SSE chunk → the caller (db.streamFn). RESUMABLE: buffered server-side under a stream id
|
|
595
|
+
await ctx.rooms.broadcast(room, topic, data) // → EVERY subscriber of a presence room; => { delivered: boolean }
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
`ctx.llm` (provider-abstracted completions), `ctx.rooms` (server-originated push), and `ctx.connections` (per-user OAuth tokens) are on **mutation + action** ctx only — never on `query` (reactive purity: a subscribed query must be a pure function of its `ctx.db` reads, and a reactive re-run would re-bill the LLM / re-broadcast the event).
|
|
599
|
+
|
|
600
|
+
**Streaming LLM output.** `ctx.llm.stream` calls `onEvent` for each event as the provider emits it, then resolves with the same response `complete` returns — so you stream text out AND still branch on `stop_reason`:
|
|
601
|
+
|
|
602
|
+
```ts
|
|
603
|
+
// functions/agent.ts
|
|
604
|
+
const tools = [{
|
|
605
|
+
name: "get_order",
|
|
606
|
+
description: "Look up an order by id.",
|
|
607
|
+
input_schema: { type: "object", properties: { orderId: { type: "string" } }, required: ["orderId"] },
|
|
608
|
+
}];
|
|
609
|
+
|
|
610
|
+
export default action({
|
|
611
|
+
args: { question: v.string() },
|
|
612
|
+
timeout: 300, // idle seconds: each stream event resets it; total run capped
|
|
613
|
+
// at 10x. Default PYLON_FN_CALL_TIMEOUT is 30s (Cloud: 300s).
|
|
614
|
+
async handler(ctx, args) {
|
|
615
|
+
const messages: { role: "user" | "assistant"; content: string | any[] }[] = [
|
|
616
|
+
{ role: "user", content: args.question },
|
|
617
|
+
];
|
|
618
|
+
for (let turn = 0; turn < 10; turn++) { // ALWAYS bound the loop
|
|
619
|
+
const res = await ctx.llm.stream({ messages, tools }, (e) => {
|
|
620
|
+
if (e.type === "text_delta") ctx.stream.write(e.text);
|
|
621
|
+
});
|
|
622
|
+
messages.push({ role: "assistant", content: res.content }); // keep tool_use blocks verbatim
|
|
623
|
+
if (res.stop_reason !== "tool_use") return { turns: turn + 1 };
|
|
624
|
+
const results = [];
|
|
625
|
+
for (const b of res.content) {
|
|
626
|
+
if (b.type !== "tool_use") continue;
|
|
627
|
+
const out = await ctx.runQuery("getOrder", { id: (b.input as any).orderId });
|
|
628
|
+
results.push({ type: "tool_result", tool_use_id: b.id, content: JSON.stringify(out) });
|
|
629
|
+
}
|
|
630
|
+
messages.push({ role: "user", content: results });
|
|
631
|
+
}
|
|
632
|
+
throw ctx.error("AGENT_LOOP_LIMIT", "tool loop did not converge");
|
|
633
|
+
},
|
|
634
|
+
});
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
Events: `text_delta {text}` | `tool_use_start {id, name}` | `tool_input_delta {partial_json}` | `done {stop_reason, usage}`. Tool arguments arrive as raw JSON fragments — concatenate, parse ONCE at the end (a single fragment is not valid JSON). Same auth gate and model allowlist as `complete`.
|
|
638
|
+
|
|
639
|
+
**SSE only when the handler streams (≥0.3.380).** `POST /api/fn/:name` with `Accept: text/event-stream` answers as SSE only if the handler actually calls `ctx.stream.write`; a handler that returns without streaming gets plain JSON (the raw return value), same as a JSON-only call. This makes MCP-over-an-action work out of the box — MCP clients advertise SSE on every POST but only parse plain JSON or default-type SSE events, so a non-streaming MCP handler now just works.
|
|
640
|
+
|
|
641
|
+
**`ctx.stream.write` vs `ctx.rooms.broadcast`.** `ctx.stream.write` streams to the one client holding the HTTP response — and every fn stream is RESUMABLE (≥0.4.22): the host buffers frames under a stream id (`X-Pylon-Stream-Id` header) with `id:` sequence lines, `streamFn` auto-reconnects to `GET /api/fn-streams/<id>?since=<cursor>` on a drop, `onStreamId` + `resumeStream(id)` survive a full page reload and deliver the final result even after the handler finished. Buffers are in-memory (default 4MB/stream, 1h retention after completion) — resume survives disconnects, not server restarts. `ctx.rooms.broadcast(room, topic, data)` reaches every CURRENTLY-CONNECTED subscriber of the presence room (second device, live dashboards, jobs with no HTTP caller) but does NOT replay missed messages. `{ delivered: false }` means the room had no members — a no-op, not an error. Doing both in one handler is normal. Clients join with `useRoom(roomId, userId)` and read pushes via `getSync().subscribeRoomMessages(roomId, (m) => ...)`; server broadcasts arrive with an empty `m.from`.
|
|
642
|
+
|
|
643
|
+
**`ctx.files.signedUrl(fileId, { ttlSecs })` (≥0.4.1)** — `GET /api/files/<id>` serves only the file's owner (or an unscoped admin). For authorized cross-user reads (an organizer reviewing a member's upload), a server function mints a short-lived signed path: `await ctx.files.signedUrl(fileId, { ttlSecs: 300 })` → `/api/files/<id>?sig=<hmac>&exp=<unix>`, anonymously fetchable (works in `<img src>`). ttl defaults 300s, capped at 24h. Available on query/mutation/action ctx. WHO gets a URL is your function's job — gate the mint with `ctx.requireMember`. Invalid/expired signatures fall through to the normal owner check; nothing becomes enumerable.
|
|
644
|
+
|
|
645
|
+
**Shard `onStop` (≥0.22.8)** — `shard({ ..., onStop: "fnName" })` runs that function as an admin background job when a shard of the kind ends, with `{ shardId, kind, reason }`; reason is `"stopped"` (ctx.shards.stop), `"idle"`, `"finished"`, or `"failed"`. Not run when the machine shuts down or the shard moves to another machine. Use it for cleanup instead of a polling cron.
|
|
646
|
+
|
|
647
|
+
**`ctx.files.store(data, { name, contentType?, public? })` / `ctx.files.delete(fileId)` (≥0.22.8, actions only)** — write to or delete from the app's file storage (same backend as `/api/files`). `store` returns `{ id, url, size }` (≤25 MiB, or `PYLON_MAX_UPLOAD_BYTES` if lower); the file is owned by the calling user/tenant, or system-owned (signed URL / admin / `public` only) when there is no user. `delete` returns `{ deleted }`. Queries and mutations get `FILES_WRITE_NOT_ALLOWED`.
|
|
648
|
+
|
|
649
|
+
**Functions bypass policies** — a `mutation`/`action` that reads or writes another tenant's
|
|
650
|
+
rows without re-checking membership is an IDOR. Use `ctx.requireMember(orgId, { role })` (it
|
|
651
|
+
looks up the membership row and throws `UNAUTHENTICATED`/`FORBIDDEN`) rather than trusting
|
|
652
|
+
`args` or a client-supplied id.
|
|
653
|
+
|
|
654
|
+
`ctx.error` exists on **mutation/action** ctx but **not on query ctx** — a `query` handler that needs to signal "forbidden" should return a discriminated result (`{ authorized: false }`) rather than throw, or a plain throw will reach the client as a stripped generic `HANDLER_ERROR`.
|
|
655
|
+
|
|
656
|
+
### Typed errors
|
|
657
|
+
|
|
658
|
+
Always throw via `ctx.error(code, message)`. Canonical codes:
|
|
659
|
+
`UNAUTHENTICATED`, `POLICY_DENIED`, `NOT_FOUND`, `INVALID_ARGS`, `RATE_LIMITED`, `CONFLICT`, `INTERNAL`.
|
|
660
|
+
`ctx.error` returns the Error; it does not throw. Write `throw ctx.error(...)`. A handler that
|
|
661
|
+
`return`s the Error is still rejected by the runtime (an Error has no JSON shape, so it is
|
|
662
|
+
treated as thrown), but only `throw` also rolls a mutation's transaction back.
|
|
663
|
+
|
|
664
|
+
## React client (live data)
|
|
665
|
+
|
|
666
|
+
In a **full-stack SSR app you do NOT call `init`/`configureClient`** — the runtime wires the client to its own origin and injects the session on every render. Just import `db` / `callFn` and use them. `db.useQuery` is a live WebSocket subscription that updates on every relevant write.
|
|
667
|
+
|
|
668
|
+
(Only a **standalone** Vite/Next frontend needs manual wiring: `init({ baseUrl, appName })` + `configureClient({ baseUrl, appName })` once at mount, where `appName` matches `manifest.name`.)
|
|
669
|
+
|
|
670
|
+
### Live query
|
|
671
|
+
|
|
672
|
+
```tsx
|
|
673
|
+
import { db } from "@pylonsync/react";
|
|
674
|
+
|
|
675
|
+
function MessageList({ roomId }: { roomId: string }) {
|
|
676
|
+
const { data: messages, loading } = db.useQuery("Message", { where: { roomId } });
|
|
677
|
+
if (loading) return null;
|
|
678
|
+
return (
|
|
679
|
+
<ul>
|
|
680
|
+
{messages.map((m) => <li key={m.id}>{m.body}</li>)}
|
|
681
|
+
</ul>
|
|
682
|
+
);
|
|
683
|
+
}
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
Filter keys must be indexed columns for performant fan-out.
|
|
687
|
+
|
|
688
|
+
`loading` drops as soon as there are rows to show, including rows from a warm local cache that this session has not confirmed with the server. `synced` (on `useQuery` / `useQueryOne`) is true once the engine completed a pull in this session; it resets on an org or account switch and stays false offline. Gate empty states, counts, and billing UI on `synced` so a stale partial cache never reads as complete.
|
|
689
|
+
|
|
690
|
+
### Calling functions
|
|
691
|
+
|
|
692
|
+
```tsx
|
|
693
|
+
import { callFn } from "@pylonsync/react";
|
|
694
|
+
|
|
695
|
+
async function onSend(roomId: string, body: string) {
|
|
696
|
+
const { id } = await callFn("sendMessage", { roomId, body });
|
|
697
|
+
return id;
|
|
698
|
+
}
|
|
699
|
+
```
|
|
700
|
+
|
|
701
|
+
`callFn`, `db.fn`, and `useMutation` all reach the same endpoint and all keep your replica current: the response's `X-Pylon-Change-Seq` header triggers a one-shot pull when the call produced changes the replica hasn't seen. **On pylon < 0.4.7 the exported `callFn` skipped that**, so your own write didn't show up until something else refreshed — if you're pinned below 0.4.7, use `db.fn` instead. Passing an explicit `{ token }` still bypasses the replica by design: that's a call as a different identity, and its results must not land in this user's data.
|
|
702
|
+
|
|
703
|
+
### Realtime hooks beyond `db.useQuery`
|
|
704
|
+
|
|
705
|
+
`db.useQuery` is the workhorse, but the React SDK ships a full realtime surface. Pick the right primitive:
|
|
706
|
+
|
|
707
|
+
| You want | Hook | Notes |
|
|
708
|
+
|---|---|---|
|
|
709
|
+
| Live list of one entity, filtered | `db.useQuery("E", { where: {...} })` | Cached in the local replica; filters offline/sort locally for free. **The cross-tab-reliable primitive.** |
|
|
710
|
+
| One row by id, live | `db.useQueryOne("E", id)` | |
|
|
711
|
+
| Live pagination | `db.useInfiniteQuery("E", { pageSize })` | each page is its own subscription |
|
|
712
|
+
| Server-side join / computed / aggregate value, live | `db.useReactiveQuery("fnName", args)` | Convex-style: a `query()` handler that auto-re-runs when its dep set changes. **See the footgun below.** |
|
|
713
|
+
| Live count / sum / avg / groupBy | `db.useAggregate(...)` | |
|
|
714
|
+
| Live full-text + faceted search | `db.useSearch("E", { query, filters, facets, sort, pageSize })` | re-runs on every keystroke AND every matching write; needs `.search({...})` on the entity |
|
|
715
|
+
| Optimistic write with a "ghost" row | `db.useMutation("fnName")` / `db.useEntity` | inserts locally instantly; server broadcast reconciles in place. `db.insert` / `update` / `delete` (and `useEntity`'s) reject with `MutationRejectedError` (`code`, `message`) after rolling the row back when the server refuses the write, so catch it to show "not sent"; they resolve when the server applies the write or queues it offline |
|
|
716
|
+
| Presence / cursors / typing / broadcast | `useRoom(roomId, userId, { initialPresence })` | ephemeral — `peers`, `setPresence(data)`, `broadcast(topic, data)`. NOT persisted. Receive relayed messages via `getSync().subscribeRoomMessages(roomId, cb)`. |
|
|
717
|
+
| Server-generated output (agent tokens, job progress) pushed to everyone watching live | server side: `ctx.rooms.broadcast(room, topic, data)` | ephemeral, live-only (no replay on reconnect); client joins with `useRoom` + `subscribeRoomMessages` |
|
|
718
|
+
| Server-generated output streamed back to the ONE client that called | server side: `ctx.stream.write(text)` | client reads with `db.streamFn(fn, args)`. RESUMABLE — a dropped connection auto-reconnects from its cursor; persist `onStreamId` + `resumeStream(id)` to survive a reload |
|
|
719
|
+
| Authoritative multiplayer sim (game/MMO tick loop) | `useShard(shardId, { subscriberId, token })` | `{ snapshot, tick, send, connected }`. The server-side sim (`SimState` tick loop) is defined in Rust (`crates/realtime`); `useShard`/`connectShard` are the TS client. |
|
|
720
|
+
| Connection/sync state for a status indicator | `useSyncStatus()` / `useSession()` | |
|
|
721
|
+
| Tab taps that paint at once, with no page fetch | `export const navigation = "client"` in the page (offline routes get it automatically) | The page and its layouts must not read `serverData` or `props.auth` during render; read the replica with `db.useQuery`. Title from static `metadata.title`. `pylon lint` PYL010 flags a "client" page that reads `serverData`. |
|
|
722
|
+
| "A new version is available" in an installed app (`buildManifest({ offline })`) | `useAppUpdate()` / `<AppUpdateBar />` | `{ version, builtAt, latestVersion, updateReady, reinstallRecommended, applying, waitingForSync, apply, check }`. Polls `/_pylon/version`; `apply()` waits for pending writes, activates the new service worker, reloads once. |
|
|
723
|
+
| The signed-in user's OAuth profile picture (≥0.4.2) | `useSession()` → `session.avatarUrl`; also `avatar_url` on `GET /api/auth/me`, `/api/auth/session`, and the org-members listing | Captured from the provider's `picture`/`avatar_url` claim on every OAuth login; `null` for password/magic users — keep the initials fallback. |
|
|
724
|
+
|
|
725
|
+
**Cross-tab realtime footgun (important).** For state that must update across *all* a user's tabs (a live counter, availability, "N slots left"), use **`db.useQuery` over a PII-free projection/aggregate entity** — NOT `db.useReactiveQuery`. Reactive server queries behave as leader-tab-only in practice (a follower tab's reactive subscription may never deliver its initial result), whereas entity sync (`db.useQuery`) reaches every tab. The pattern: keep your sensitive table `allowRead: "false"` (deny-all), and have the mutation also maintain a small public-read projection entity (e.g. `WaitlistStat { count }`, `BookedSlot { serviceId, startsAt }`) with `allowRead: "true"` + client writes denied. Subscribe the UI to the projection.
|
|
726
|
+
|
|
727
|
+
```tsx
|
|
728
|
+
// Live counter that updates in every tab — db.useQuery over a public projection
|
|
729
|
+
const { data: stat } = db.useQuery("WaitlistStat"); // allowRead:"true", count maintained server-side
|
|
730
|
+
const count = stat[0]?.count ?? 0;
|
|
731
|
+
|
|
732
|
+
// Presence (cursors / typing) — ephemeral, not stored
|
|
733
|
+
const room = useRoom(`doc:${docId}`, userId, { initialPresence: { cursor: 0 } });
|
|
734
|
+
room.peers.map((p) => <Cursor key={p.user_id} x={p.data.cursor} />);
|
|
735
|
+
room.setPresence({ cursor: caretPos });
|
|
736
|
+
```
|
|
737
|
+
|
|
738
|
+
Use `db.useReactiveQuery` for **server-side joins / computed values rendered in one (leader) view** (a feed that joins Post→User, a dashboard rollup) — it's the right tool there. Just don't lean on it for cross-tab fan-out of a shared scalar.
|
|
739
|
+
|
|
740
|
+
### Session / auth bootstrap (guest fallback pattern)
|
|
741
|
+
|
|
742
|
+
```tsx
|
|
743
|
+
import { storageKey } from "@pylonsync/react";
|
|
744
|
+
|
|
745
|
+
async function ensureGuest(): Promise<string> {
|
|
746
|
+
const BASE_URL = import.meta.env.VITE_PYLON_URL ?? "http://localhost:4321";
|
|
747
|
+
let token = localStorage.getItem(storageKey("token"));
|
|
748
|
+
let userId = localStorage.getItem(storageKey("user"));
|
|
749
|
+
if (!token || !userId) {
|
|
750
|
+
const res = await fetch(`${BASE_URL}/api/auth/guest`, { method: "POST" });
|
|
751
|
+
const body = await res.json();
|
|
752
|
+
token = body.token;
|
|
753
|
+
userId = body.user_id;
|
|
754
|
+
localStorage.setItem(storageKey("token"), token);
|
|
755
|
+
localStorage.setItem(storageKey("user"), userId);
|
|
756
|
+
}
|
|
757
|
+
return userId;
|
|
758
|
+
}
|
|
759
|
+
```
|
|
760
|
+
|
|
761
|
+
The response is `{ guest: true, token, user_id }`. **Minting a guest is only half of it** — every function this guest then calls must declare `auth: "guest"` (or `"public"`). A guest token against a default `auth: "user"` function still returns `401 AUTH_REQUIRED`. See "Auth levels" above.
|
|
762
|
+
|
|
763
|
+
## Server-side rendering (full-stack frontend)
|
|
764
|
+
|
|
765
|
+
Pylon natively server-renders React from the same server that runs your backend (the Rust server spawns Bun to execute the render) — Next-style, but no Next. Routes are files under `app/`.
|
|
766
|
+
|
|
767
|
+
### Routing & components
|
|
768
|
+
|
|
769
|
+
- `app/page.tsx` → `/`, `app/blog/page.tsx` → `/blog`, `app/blog/[slug]/page.tsx` → `/blog/:slug`, `app/docs/[...slug]/page.tsx` → catch-all, `[[...slug]]` → optional catch-all.
|
|
770
|
+
- `app/layout.tsx` wraps every page (nest `layout.tsx` per segment for sub-layouts).
|
|
771
|
+
- Route groups: a `(group)` directory is stripped from the URL — `app/(marketing)/pricing/page.tsx` still serves `/pricing`. A `layout.tsx` inside the group wraps only that group's pages, so one section gets its chrome (marketing nav + footer) while routes outside it (`/login`, `/dashboard`) render bare. Prefer this over URL-sniffing in the root layout.
|
|
772
|
+
- **A page is a server component by default** (runs only on the server — no JS shipped). Add `"use client"` at the top of a file to make it (and its tree) an interactive island that hydrates in the browser. Proven pattern: a thin server `page.tsx` (for metadata + auth) that renders one `"use client"` view containing the interactive UI.
|
|
773
|
+
- **Compose small components; don't grow one giant page.** A page that fetches, formats, and renders in one file can't be tested without standing up the whole app, and an agent extending it has one huge file to edit. Split along the data boundary:
|
|
774
|
+
|
|
775
|
+
| Layer | Contains | How it's tested |
|
|
776
|
+
|---|---|---|
|
|
777
|
+
| `lib/*.ts` | pure functions — formatting, grouping, derivation. No React, no `db`. | direct unit tests, no DOM, no mocks |
|
|
778
|
+
| `components/*.tsx` | presentational. Data arrives as **props**; writes go out through **callbacks**. Never calls `db.useQuery` itself. | `render(<C {...fixtures} />)` — no mocking, because there's no data layer to mock |
|
|
779
|
+
| `app/**/page.tsx` + one `"use client"` container | the **only** place that touches `db` / `callFn`. Fetch, then hand plain data down. | `pylon verify`, or a container test that mocks just this boundary |
|
|
780
|
+
|
|
781
|
+
Keeping the data boundary in exactly one module is what makes everything below it trivially testable. The `create-pylon` starters are generated in this shape — read one for a worked example.
|
|
782
|
+
|
|
783
|
+
- **Build on the UI kit that's already there.** Scaffolded apps ship `components/ui/` with shadcn primitives (`button`, `card`, `input`, `label`, `select`, `badge`, `table`, `textarea`), `lib/utils.ts` (`cn`), and a configured `components.json`. Use them, and style with the semantic tokens (`bg-background`, `bg-card`, `text-muted-foreground`, `border`) rather than hardcoded palette classes like `bg-zinc-50` — a raw `<input>` or a fixed color renders as an unstyled control next to the kit and breaks dark mode.
|
|
784
|
+
|
|
785
|
+
Need a primitive that isn't there (dialog, dropdown, tabs, popover, …)? Add it rather than hand-rolling:
|
|
786
|
+
|
|
787
|
+
```sh
|
|
788
|
+
bunx shadcn@latest add dialog # npx if you're on Node
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
`components.json` is preconfigured (new-york, zinc, `@/components/ui`), so the component lands with the right imports and tokens.
|
|
792
|
+
|
|
793
|
+
- The page receives props: `{ pathname, host, params, searchParams, auth, response, serverData }` — type them with `PageProps<{ slug: string }>` from `@pylonsync/react` instead of hand-rolling. **`pathname` is the PATH only** (`/blog/hello`), never the query — the router strips the query before the render and hands it over already parsed as `searchParams`. So read a query parameter from `searchParams.next`, NEVER `new URL(props.pathname).searchParams.get("next")`, which compiles and returns null on every request. (`url` is the same value under the old name and is deprecated.) `auth` is `{ user_id, is_admin, tenant_id, roles }` resolved from the shared session. `host` is the request host, lowercased, when the server trusts it (its own URL, `PYLON_TRUSTED_HOSTS`, or a ready customer domain attached with `ctx.domains`), else `""` — it is part of the SSR cache key, so a platform app can pick the customer from it and stay cacheable. **The request's `headers` and `cookies` are intentionally NOT props** — they're server-only and stripped from the hydration payload (a session cookie must never reach client JS), so reading them in a component body would hydrate-mismatch. Read request-derived data through `serverData` or a server function.
|
|
794
|
+
|
|
795
|
+
```tsx
|
|
796
|
+
// app/blog/[slug]/page.tsx (server component)
|
|
797
|
+
import type { Metadata, PageAuth } from "@pylonsync/react";
|
|
798
|
+
|
|
799
|
+
export function generateMetadata({ params }: { params: { slug: string } }): Metadata {
|
|
800
|
+
return { title: `Post: ${params.slug}`, description: "…" };
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
export default function PostPage({ params, auth }: { params: { slug: string }; auth?: PageAuth }) {
|
|
804
|
+
return <Article slug={params.slug} signedIn={Boolean(auth?.user_id)} />;
|
|
805
|
+
}
|
|
806
|
+
```
|
|
807
|
+
|
|
808
|
+
### Loading data during the server render (`serverData`)
|
|
809
|
+
|
|
810
|
+
A server component reads the DB during render through the `serverData` prop — a **read-only, policy-gated** handle (same store + policy gate as a query's `ctx.db`). Await it with React 19 `use()` inside `<Suspense>`; resolved values are replayed into the hydration payload so the client doesn't re-fetch. Writes are rejected (`SSR_WRITE_FORBIDDEN`) — mutations belong in functions.
|
|
811
|
+
|
|
812
|
+
```tsx
|
|
813
|
+
import { use, Suspense } from "react";
|
|
814
|
+
import type { PageProps } from "@pylonsync/react";
|
|
815
|
+
|
|
816
|
+
export default function Page({ serverData }: PageProps) {
|
|
817
|
+
return (
|
|
818
|
+
<Suspense fallback={<Skeleton />}>
|
|
819
|
+
<PostList promise={serverData.list<Post>("Post")} />
|
|
820
|
+
</Suspense>
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
function PostList({ promise }: { promise: Promise<Post[]> }) {
|
|
824
|
+
const posts = use(promise);
|
|
825
|
+
return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
|
|
826
|
+
}
|
|
827
|
+
```
|
|
828
|
+
|
|
829
|
+
`serverData` has `get` / `list` / `lookup` / `query` / `queryGraph` / `paginate` / `search` (same read shapes as `ctx.db`). For live, client-updating data prefer a `"use client"` island with `db.useQuery` instead.
|
|
830
|
+
|
|
831
|
+
**`serverData.fn(name, args)` (≥0.3.385)** — run a registered **query** function during SSR with the page's own auth (anonymous on public pages): `use(serverData.fn<Session[]>("getPublicSchedule", { eventId }))`. Use it when the safe public projection lives in a gated query (published-only rows, stripped fields) instead of open row policies — the query stays the single source of truth for SSR and client. Results replay through the hydration payload like other serverData reads. Mutations/actions are rejected (`FN_TYPE_MISMATCH`). Calling it on a signed-in request opts the render out of shared SSR caching (the query may read `ctx.auth`); anonymous renders stay cacheable.
|
|
832
|
+
|
|
833
|
+
### Navigation, images, metadata
|
|
834
|
+
|
|
835
|
+
- `import { Link, Image } from "@pylonsync/react"` — `<Link href>` = client-side nav; `<Image src width height>` = a built-in optimizer (emits `srcset`; pass `priority` for LCP).
|
|
836
|
+
- **`<Image>` `quality` and `w` are allowlists, not ranges.** An off-list value snaps to the nearest allowed one and the server logs it (`pylon dev` prints to the console) — the image renders, but NOT at the value you asked for. Bounding the set is what stops anyone minting unlimited cache entries.
|
|
837
|
+
- `quality`: **50, 75, 90** (default 75). `quality={80}` is the usual mistake — it silently becomes 75.
|
|
838
|
+
- `w`: `16,32,48,64,96,128,256,384` + `640,750,828,1080,1200,1920,2048,3840`.
|
|
839
|
+
- `format`: `avif`, `webp`, `jpeg` — not snapped (no meaningful "nearest" codec); anything else falls back to `Accept` negotiation. Never SVG: rejected as input and output, it can carry script.
|
|
840
|
+
- Need other values? Set `PYLON_IMAGE_QUALITIES` / `PYLON_IMAGE_DEVICE_SIZES` / `PYLON_IMAGE_IMAGE_SIZES` / `PYLON_IMAGE_FORMATS` (comma-separated). Prefer picking an allowed value over widening the list.
|
|
841
|
+
- SEO: `export const metadata: Metadata = {…}` (static) or `export async function generateMetadata(props)` (dynamic — keep it cheap, e.g. params→title). Fields: `title`, `description`, `canonical`, `robots`, `openGraph`, `twitter`, `icons`. Colocate `opengraph-image.png` / `twitter-image.png` / `icon.png` / `favicon.ico` next to a route and they're auto-wired.
|
|
842
|
+
- Generated share image: `app/opengraph-image.tsx` (or `app/<segment>/opengraph-image.tsx`) is served at `/opengraph-image` (`/<segment>/opengraph-image`), and Pylon sets `og:image` (1200x630, image/png) and `twitter:image` on every page below it. The default export gets `{ params, searchParams }` and returns `new ImageResponse(<jsx/>, { width: 1200, height: 630, fonts })` from `@pylonsync/react`. Rendering is Satori: flexbox only, so an element with more than one child needs `display: "flex"`. `fonts` takes static TTF/OTF data (`{ name, data, weight, style }`), not woff2 and not variable fonts; without it, Inter 400/600 is used. A closer static image or an explicit `metadata.openGraph.image` wins. There is no `twitter-image.tsx` route; `twitter:image` uses the OG image.
|
|
843
|
+
|
|
844
|
+
```tsx
|
|
845
|
+
// app/opengraph-image.tsx
|
|
846
|
+
import { ImageResponse } from "@pylonsync/react";
|
|
847
|
+
export default function OG() {
|
|
848
|
+
return new ImageResponse(
|
|
849
|
+
<div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", background: "#fef3c7", fontSize: 72 }}>
|
|
850
|
+
Rosa's Bakery
|
|
851
|
+
</div>,
|
|
852
|
+
{ width: 1200, height: 630 },
|
|
853
|
+
);
|
|
854
|
+
}
|
|
855
|
+
```
|
|
856
|
+
|
|
857
|
+
### Code splitting
|
|
858
|
+
|
|
859
|
+
Every page is its own entry chunk, sharing one chunk with React + the runtime. That handles many routes; it does nothing for **one route with a heavy dependency**. A page that statically imports an editor puts the whole editor in its entry — and since `<Link>` warms sibling routes on sight, that weight lands on the first load of every page in the section, for a component most visitors never open.
|
|
860
|
+
|
|
861
|
+
`dynamic()` moves it behind a real `import()`: its own chunk, deliberately left out of the route's modulepreload set, fetched only when something renders it.
|
|
862
|
+
|
|
863
|
+
```tsx
|
|
864
|
+
import { dynamic } from "@pylonsync/react";
|
|
865
|
+
|
|
866
|
+
const Composer = dynamic(() => import("./Composer"), {
|
|
867
|
+
loading: () => <ComposerSkeleton />,
|
|
868
|
+
});
|
|
869
|
+
|
|
870
|
+
// …then render <Composer /> behind whatever opens it.
|
|
871
|
+
```
|
|
872
|
+
|
|
873
|
+
Call it at **module level**, never inside a render — a `dynamic()` per render is a new component type each time and remounts the subtree. `ref` reaches the loaded component, so a deferred `forwardRef` editor still exposes its imperative handle.
|
|
874
|
+
|
|
875
|
+
`ssr` defaults to **false**, the opposite of Next, and deliberately: a Pylon page hydrates once after the whole document streams, so the safe contract is that the server HTML and the first client render are identical, which `ssr: false` guarantees by rendering the fallback in both. It's also the only mode that removes bytes from the first load — an `ssr: true` component must be in the client bundle before hydration, so it saves nothing and exists for organizing code, not weight.
|
|
876
|
+
|
|
877
|
+
Note the name collision: the route-segment export `export const dynamic = "force-static" | "force-dynamic"` is a **cache directive**, unrelated to this loader. Same word, different thing, both inherited from Next.
|
|
878
|
+
|
|
879
|
+
**Deferring one component isn't enough on its own.** `dynamic()` removes weight only if nothing else in the route imports the same library statically — a sibling component doing `import { H1, TEXT } from "@react-email/editor/ui"` drags the whole thing back in eagerly, and the only symptom is a heavy chunk in the route's preload set, which looks like a bundler bug. Check with `grep -o 'import[( ]*"[^"]*<chunk>[^"]*"'` against the built entry: a paren means deferred, no paren means something still imports it eagerly.
|
|
880
|
+
|
|
881
|
+
### File conventions (all optional, walked up from the page dir)
|
|
882
|
+
|
|
883
|
+
- `loading.tsx` → the route's pending state, in both directions: the Suspense fallback the SSR stream flushes first (set `export const streaming = true` on a page for progressive streaming), and what the client router paints over the page area when a `<Link>` navigation runs longer than ~100ms. Faster navigations swap straight to content, so it never flashes.
|
|
884
|
+
- `error.tsx` → error boundary; `not-found.tsx` → 404 boundary (call `notFound()` to trigger).
|
|
885
|
+
- `sitemap.ts` → `/sitemap.xml`, `robots.ts` → `/robots.txt`. Default export, **may be async** (enumerate dynamic pages from the DB). Types `Sitemap` / `Robots` from `@pylonsync/react`:
|
|
886
|
+
|
|
887
|
+
```ts
|
|
888
|
+
// app/sitemap.ts
|
|
889
|
+
import type { Sitemap } from "@pylonsync/react";
|
|
890
|
+
export default async function sitemap(): Promise<Sitemap> {
|
|
891
|
+
const posts = await getPosts();
|
|
892
|
+
return [
|
|
893
|
+
{ url: "https://x.com/", changeFrequency: "weekly", priority: 1 },
|
|
894
|
+
...posts.map((p) => ({ url: `https://x.com/blog/${p.slug}`, lastModified: p.updatedAt })),
|
|
895
|
+
];
|
|
896
|
+
}
|
|
897
|
+
// app/robots.ts → export default () => ({ rules: { userAgent: "*", allow: "/" }, sitemap: "https://x.com/sitemap.xml" })
|
|
898
|
+
```
|
|
899
|
+
|
|
900
|
+
### Client hooks & response control
|
|
901
|
+
|
|
902
|
+
- `import { useRouter, useSearchParams, usePathname, useParams, redirect, notFound } from "@pylonsync/react"` — for `"use client"` components.
|
|
903
|
+
- The `response` prop shapes the HTTP reply from a server component: `response.setStatus(404)`, `response.redirect("/login")`, `response.notFound()`, `response.setHeader(...)`, `response.setCookie(...)`.
|
|
904
|
+
- **Never `window.location` for in-app navigation** — use `<Link>` or `useRouter().push/replace`. A full document load tears down the sync engine and rebuilds it: fresh multi-tab election, fresh WebSocket, fresh initial pull, plus a flash of the old page. It's invisible when it works, so it shows up as "why is every login doing four pulls". The ONE case where a hard load is correct is an identity change — after login/logout you WANT a new document so SSR renders under the new session and the replica resets for the new user (this is why the templates' auth forms call `window.location.assign`). Redirecting inside an effect (`window.location.replace` in a landing page) is the common wrong version.
|
|
905
|
+
|
|
906
|
+
### Caching (SSR output cache)
|
|
907
|
+
|
|
908
|
+
Pages are **dynamic by default**. Two opt-ins make a render shareable (a hit skips the Bun render entirely):
|
|
909
|
+
|
|
910
|
+
- **Anonymous cache** — `export const revalidate = 60` (seconds). Stored + reused for ALL anonymous visitors. Cached ONLY if the render never read per-request identity — reading `props.auth`, setting a cookie via `response.setCookie`, a non-200, or streaming opts it out. (Request headers/cookies aren't page props, so there's nothing to accidentally read there.) `export const dynamic = "force-static"` caches until the next deploy; `"force-dynamic"` never caches. Use for fully public pages.
|
|
911
|
+
- **Auth-bucketed cache** — `export const cache = "auth-bucketed"` + `export const revalidate = 60`. Caches TWO identity-free shells keyed on whether the request is signed in. Read `props.session.exists` (a binary signed-in bit, **never** identity) to render a signed-in vs signed-out shell and still get a per-bucket hit. Reading real `props.auth` still opts out (output would be identity-specific), and so does a signed-in render that calls `serverData.get/list/query/...` or `serverData.fn` (those return the caller's rows). Signed-out renders that read serverData still bucket; for public data on a signed-in shell, use `serverData.unsafe.*` only when the rows are public.
|
|
912
|
+
- **Purity contract:** an `auth-bucketed` page MUST be a pure function of its props. NEVER stash request data (auth/cookies/headers, or values derived from them) in module/global scope and render it on a later request — that leaks across users (same rule as Next: no request data in module scope).
|
|
913
|
+
- CDN: bucket responses are browser-`private` by default (the origin still skips the render). A shared-CDN hit requires the operator to set `PYLON_SSR_BUCKET_CDN=1` after adding a CDN cache-key rule on session-cookie presence.
|
|
914
|
+
|
|
915
|
+
To show signed-in nav on a cacheable page, read `props.session.exists` (bucketed) — do NOT read `props.auth` server-side (that makes the render dynamic). Resolve full identity client-side after hydration.
|
|
916
|
+
|
|
917
|
+
**"Why isn't my page caching?"** → run `pylon diagnostics` or open the dev HUD; it reports the exact verdict + reason per route (see "Running the app").
|
|
918
|
+
|
|
919
|
+
### Performance
|
|
920
|
+
|
|
921
|
+
Ordered by how much they actually cost. The first two are where nearly all real
|
|
922
|
+
latency lives; the rest matter once those are clean.
|
|
923
|
+
|
|
924
|
+
**1. Don't serialize waterfalls.** `serverData` reads are promises — start them
|
|
925
|
+
all, then await together. Awaiting one before creating the next turns two 50ms
|
|
926
|
+
reads into 100ms:
|
|
927
|
+
|
|
928
|
+
```tsx
|
|
929
|
+
// Waterfall: the second read doesn't start until the first resolves.
|
|
930
|
+
const org = use(serverData.get("Organization", id));
|
|
931
|
+
const members = use(serverData.query("OrgMember", { orgId: id }));
|
|
932
|
+
|
|
933
|
+
// Parallel: both in flight, one wait.
|
|
934
|
+
const [org, members] = use(
|
|
935
|
+
Promise.all([
|
|
936
|
+
serverData.get("Organization", id),
|
|
937
|
+
serverData.query("OrgMember", { orgId: id }),
|
|
938
|
+
]),
|
|
939
|
+
);
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
Independent sections should be separate `<Suspense>` boundaries so a slow one
|
|
943
|
+
streams in without blocking the rest — that's what `export const streaming =
|
|
944
|
+
true` is for.
|
|
945
|
+
|
|
946
|
+
**2. Ship less to the client.** Resolved `serverData` is replayed into the
|
|
947
|
+
hydration payload so the client doesn't re-fetch — which means over-fetching in
|
|
948
|
+
a server component inflates the HTML for every visitor. Select the fields the UI
|
|
949
|
+
renders; don't pass whole rows into a `"use client"` island to use two of them.
|
|
950
|
+
|
|
951
|
+
**3. Never keep mutable state in module scope.** The SSR runner is warm and
|
|
952
|
+
import-caches route modules, so a module-level variable persists **across
|
|
953
|
+
requests and across users**. This is the same purity contract as the
|
|
954
|
+
`auth-bucketed` cache, and it's a correctness bug before it's a performance one.
|
|
955
|
+
|
|
956
|
+
**4. Prefer `db.useQuery` to per-component `callFn`.** The synced replica already
|
|
957
|
+
dedupes and updates live; N components each calling `callFn` on mount is N
|
|
958
|
+
round-trips for data the client usually already has.
|
|
959
|
+
|
|
960
|
+
**5. Client-render hygiene** — the usual React rules, and the two that bite most:
|
|
961
|
+
never define a component inside another component (it remounts the whole subtree
|
|
962
|
+
every render), and derive values during render instead of syncing them in an
|
|
963
|
+
effect.
|
|
964
|
+
|
|
965
|
+
For the full catalogue — bundle analysis, memoization, hydration, SVG and DOM
|
|
966
|
+
detail — use Vercel's `react-best-practices` skill
|
|
967
|
+
(<https://github.com/vercel-labs/agent-skills/tree/main/skills/react-best-practices>);
|
|
968
|
+
70 rules ranked by impact. It's Next-flavoured, so read `next/dynamic` as a
|
|
969
|
+
plain `import()` and server actions as Pylon functions.
|
|
970
|
+
|
|
971
|
+
## Running the app
|
|
972
|
+
|
|
973
|
+
```bash
|
|
974
|
+
# One port — a Rust server serves the SSR frontend, the API, and the WebSocket (it runs your TypeScript on Bun).
|
|
975
|
+
pylon dev
|
|
976
|
+
```
|
|
977
|
+
|
|
978
|
+
That's it — no second terminal for the UI. `pylon dev` watches `app.ts` + `functions/` + `app/`, recompiles Tailwind, and live-reloads the browser. (A backend-only app runs the same `pylon dev`.) The first run creates `.pylon/dev.db` (SQLite) and auto-migrates. Set `DATABASE_URL=postgres://...` to target Postgres instead — the adapter is chosen at startup, and all schema/policy/function/SSR code is identical either way.
|
|
979
|
+
|
|
980
|
+
In production, use `pylon start` instead of `pylon dev`. Same server, no file watcher, blocks on the server thread so a fatal error exits the process and lets the supervisor (systemd / Docker / Fly init) restart cleanly. Two ways to run it:
|
|
981
|
+
|
|
982
|
+
- `pylon start app.ts` runs the source. The server needs the project and its `node_modules`.
|
|
983
|
+
- `pylon build` writes a production artifact to `dist/` (server bundle, client bundle, `public/`, manifest), and `pylon start dist` runs it with no source tree and no `node_modules`. Data paths (`PYLON_DB_PATH`, default `pylon.db`) resolve outside `dist/`. Browser targets, polyfills, CSS targets, and server externals go in `buildManifest({ build: { target, polyfill, css, server: { external }, include } })`. `pylon build --compile` also copies the `pylon` and `bun` binaries into `dist/bin/`. Docs: https://docs.pylonsync.com/operations/build
|
|
984
|
+
|
|
985
|
+
### Debugging — the dev HUD + `pylon diagnostics` (read this when iterating)
|
|
986
|
+
|
|
987
|
+
`pylon dev` surfaces the framework's hidden decisions so you don't guess. Same data, three ways:
|
|
988
|
+
|
|
989
|
+
- **Dev HUD** — a floating overlay (bottom-left, in the browser) showing each page's cache verdict + WHY, render mode + timing, sync connection + offline-outbox depth, and client error count.
|
|
990
|
+
- **`pylon diagnostics`** (machine-readable, for agents) — prints recent SSR renders: verdict (`cacheable` / `bucketed` / `dynamic`), the reason, and render time per route. `--json` for raw; `--port` if not 4321.
|
|
991
|
+
- **`GET /_pylon/dev/diagnostics`** — the JSON ring the CLI + HUD read.
|
|
992
|
+
- **`pylon dev` stdout** — one `[pylon:dev] SSR <route> → <verdict> · <ms> — <reason>` line per render.
|
|
993
|
+
|
|
994
|
+
When a page won't cache, returns no data, or is slow, check these FIRST — the verdict reason names the exact cause (e.g. "read props.auth", "not opted in", "the render set a cookie"). Dev-only; absent in prod.
|
|
995
|
+
|
|
996
|
+
### Design mode (for design tools)
|
|
997
|
+
|
|
998
|
+
Set `PYLON_DESIGN_MODE=1` with `pylon dev` to get a static, source-mapped render of any page for a design canvas. Dev-only; every part 404s in prod.
|
|
999
|
+
|
|
1000
|
+
- **`PYLON_DESIGN_MODE=1`** — the SSR runner stamps every DOM element under `app/`, `components/` and `.design/` with `data-pylon-src="app/x/page.tsx:12:8"` (file, 1-based line, column of the `<`). Components are not stamped; browser bundles are unchanged.
|
|
1001
|
+
- **`X-Pylon-Design: 1`** request header — the page renders with no hydration tail (no `__PYLON_DATA__`, no module script), no dev HUD, no live-reload snippet, the stylesheet inlined with no size cap, and `<base href="http://127.0.0.1:<port>/">` first in `<head>` so relative assets resolve inside a `srcdoc` iframe. Response is `Cache-Control: no-store` and never written to the SSR cache.
|
|
1002
|
+
- **`GET /_pylon/dev/render?component=<rel module path>&layouts=<csv>&path=<url path>`** — render a module that is not a route (for example `.design/variants/v1`) with the given layout chain, as a design render. `component` and `layouts` are project-relative paths without extension and must exist inside the project. `path` defaults to `/`. Requires `Authorization: Bearer <PYLON_DEV_FILE_API_TOKEN>` when that env is set.
|
|
1003
|
+
- **`X-Pylon-Design-Viewer: <userId>` or `anon`** — render as that user (their most recent session's org, roles, admin flag), so pages that redirect anonymous visitors still render. Only on design renders, and only with `PYLON_DEV_FILE_API_TOKEN` set and sent; otherwise 401.
|
|
1004
|
+
|
|
1005
|
+
## Deployment
|
|
1006
|
+
|
|
1007
|
+
Production env vars to set:
|
|
1008
|
+
|
|
1009
|
+
```bash
|
|
1010
|
+
PYLON_DB_PATH=/data/pylon.db
|
|
1011
|
+
PYLON_FILES_DIR=/data/uploads
|
|
1012
|
+
PYLON_SESSION_DB=/data/sessions.db
|
|
1013
|
+
PYLON_CORS_ORIGIN=https://your-web-ui.vercel.app # EXACT origin — "*" refused in prod
|
|
1014
|
+
PYLON_DEV_MODE=false
|
|
1015
|
+
```
|
|
1016
|
+
|
|
1017
|
+
Scaffolding:
|
|
1018
|
+
|
|
1019
|
+
```bash
|
|
1020
|
+
pylon deploy # default — actual hosted deploy to Stack0 Cloud
|
|
1021
|
+
pylon deploy --target fly # Dockerfile + fly.toml
|
|
1022
|
+
pylon deploy --target docker # Dockerfile
|
|
1023
|
+
pylon deploy --target compose # docker-compose.yml + Dockerfile
|
|
1024
|
+
pylon deploy --target workers # Cloudflare wrangler.toml (experimental)
|
|
1025
|
+
pylon deploy --target systemd # VPS unit file
|
|
1026
|
+
pylon deploy --target manifest # just regenerate manifest + client bindings
|
|
1027
|
+
```
|
|
1028
|
+
|
|
1029
|
+
For Fly.io the common pattern is a 1GB volume mounted at `/data` with `auto_stop_machines = "stop"` — idle machines sleep and wake on request.
|
|
1030
|
+
|
|
1031
|
+
### CLI ops surface (Stack0 Cloud)
|
|
1032
|
+
|
|
1033
|
+
Once logged in (`pylon login`, or via the dashboard's "Hand off to your coding agent" card → `pylon login --code XXXX-XXXX`), the CLI covers every dashboard operation. Use these instead of clicking through `cloud.stack0.dev` for anything scripted.
|
|
1034
|
+
|
|
1035
|
+
```bash
|
|
1036
|
+
pylon whoami # account + cloud + active project
|
|
1037
|
+
pylon projects list # all projects you can see
|
|
1038
|
+
pylon projects create my-app # create + provision a project, set it as context
|
|
1039
|
+
pylon projects use my-app # set current project for this dir
|
|
1040
|
+
pylon secrets list / set KEY=v / rm KEY / import .env
|
|
1041
|
+
pylon logs --limit 100 # last N request-log rows, then exit
|
|
1042
|
+
pylon logs tail # 2s-polling stream (never exits — use --limit instead)
|
|
1043
|
+
pylon status # uptime / requests / jobs / WS clients
|
|
1044
|
+
pylon restart --yes # cycle the machines, same code
|
|
1045
|
+
pylon deployments list / logs [<id>] / rollback <id> --yes
|
|
1046
|
+
pylon domains list / add HOST / verify HOST / rm HOST
|
|
1047
|
+
pylon db list / backup / restore <id> --yes
|
|
1048
|
+
pylon data entities / list <E> / get <E> <id>
|
|
1049
|
+
pylon members list / invite EMAIL [role]
|
|
1050
|
+
pylon billing # plan, month-to-date + projected charge
|
|
1051
|
+
pylon billing upgrade # move the org to Pro (Stripe checkout)
|
|
1052
|
+
```
|
|
1053
|
+
|
|
1054
|
+
Every command accepts `--json` for piping to `jq`. Project context resolves from `--project` flag → `$PYLON_PROJECT` → `.pylon/project` file → interactive picker. The `.pylon/project` file is what `pylon projects use` writes; subsequent commands in that directory tree auto-target.
|
|
1055
|
+
|
|
1056
|
+
**Start with `pylon whoami`** when a command targets the wrong thing. It reports the account, the cloud origin, and which project is active *and where that slug came from* — a `.pylon/project` inherited from a parent directory is the usual culprit. It also flags a slug that resolves locally but names no project on the account.
|
|
1057
|
+
|
|
1058
|
+
**Destructive commands refuse to run unattended without `--yes`**: `restart`, `deployments rollback`, `db restore`, `secrets rm`, `domains rm`. Under `--json` or a non-TTY there is no prompt to answer, so the command errors out instead — pass `--yes` in scripts.
|
|
1059
|
+
|
|
1060
|
+
**API docs.** The server generates an OpenAPI **3.1** spec from the manifest and serves it at `GET /api/openapi.json`; `pylon codegen openapi` writes the same document to `pylon.openapi.json` without booting anything. Point Mintlify, Scalar, or Redoc at either. Every query/mutation/action appears at its real endpoint, `POST /api/fn/<name>`, with `auth: "public"` functions marked as needing no credentials; `internal: true` ones are omitted because they aren't externally callable. The spec is **admin/dev-only by default** — it enumerates your whole surface — so set `PYLON_OPENAPI_PUBLIC=true` if you want hosted docs to fetch it anonymously. A spec with entities but no functions means `app.ts` isn't calling `discoverFunctions()`.
|
|
1061
|
+
|
|
1062
|
+
**The runtime version comes from package.json** (pylon ≥ 0.4.8). The Rust binary and the `@pylonsync/*` packages ship from one release and talk to each other over the function protocol, which carries no version handshake — so a mismatch surfaces as a confusing runtime error, not "version mismatch". A cloud deploy therefore boots the machine on the runtime matching the version the build installed: change the dependency, `pylon deploy`, done. There is no runtime to bump. `pylon runtime` shows what a project is on and still moves it explicitly when you need a binary-only change without a rebuild; a machine pinned to an image *digest* is left alone, since that's an explicit choice.
|
|
1063
|
+
|
|
1064
|
+
**Two different "update" commands, don't mix them up.** `pylon update` bumps every `@pylonsync/*` dependency in the project's package.json files. `pylon upgrade` (pylon ≥ 0.4.6) updates the **pylon binary itself** to the latest release — `pylon upgrade --check` reports without changing anything. A CLI installed by npm or cargo is left alone; upgrade prints the command that manages it. Before 0.4.6, `pylon upgrade` opened a Stripe checkout; that is `pylon billing upgrade` now.
|
|
1065
|
+
|
|
1066
|
+
**`pylon restart`** (pylon ≥ 0.4.5) cycles the running process on the code already deployed. Reach for it when the app is wedged or crash-looping — `pylon deploy` rebuilds for no reason and `deployments rollback` ships older code. A stopped machine is started rather than restarted, and multi-region projects cycle one region at a time. Exits non-zero if any region failed to come back, so a script won't move on from a half-recovered app. Requires org owner or admin.
|
|
1067
|
+
|
|
1068
|
+
**Project creation** (pylon ≥ 0.3.317): `pylon projects create <slug> [--name <name>] [--org <org-slug>] [--region iad] [--db sqlite|postgres] [--no-wait]`. Creates the project, waits for the Fly machine to provision (~30–60s; Postgres adds a managed-DB provision), pins it as the local context, and prints the live `https://<slug>.stack0.app` URL — so login → create → deploy runs end-to-end without the dashboard. `--org` is only needed when the account belongs to multiple orgs. On older CLI versions (or if the account has no org yet), create the project in the dashboard and run `pylon projects use <slug>` instead.
|
|
1069
|
+
|
|
1070
|
+
### Multi-machine (horizontal scaling)
|
|
1071
|
+
|
|
1072
|
+
One machine is the recommended shape (a single machine serves thousands of rps with a CDN in front) — scale up first. When you do need more than one machine (pylon ≥ 0.3.315):
|
|
1073
|
+
|
|
1074
|
+
```bash
|
|
1075
|
+
DATABASE_URL=postgres://… # entities, auth, sync, jobs, workflows
|
|
1076
|
+
PYLON_CLUSTER_BUS=redis://… # self-hosted realtime fanout
|
|
1077
|
+
```
|
|
1078
|
+
|
|
1079
|
+
Postgres provides shared entities, auth state, sync state, jobs, and workflows. Workers claim jobs and workflows with short leases. Another machine can recover work after a lease expires. Execution is at least once, so job and workflow handlers must be idempotent. During a rolling release, each machine claims only jobs that have a local handler.
|
|
1080
|
+
|
|
1081
|
+
Redis relays WS/SSE change events, presence, and CRDT frames for self-hosted deployments. Pylon Cloud configures its built-in relay and does not add Redis to the project. Boot-time DDL is serialized across machines. One elected scheduler adds each cron fire to the shared queue. SQLite mode is single-machine by definition.
|
|
1082
|
+
|
|
1083
|
+
Known per-machine semantics (documented, not bugs): rate-limit counters are per machine (N machines ≈ N× the configured limit — set PYLON_RATE_LIMIT_MAX accordingly), and the SSR output cache is per machine (put a CDN in front).
|
|
1084
|
+
|
|
1085
|
+
Keeping a project current: `pylon update` bumps every @pylonsync/* dependency (workspace members included, `workspace:*` pins untouched) to the latest release and reinstalls — then `pylon verify`.
|
|
1086
|
+
|
|
1087
|
+
## Gotchas & rules
|
|
1088
|
+
|
|
1089
|
+
- **Type names** — schema (`field.*`) and validator (`v.*`) both accept two naming conventions so you don't have to remember which camp a given API belongs to:
|
|
1090
|
+
|
|
1091
|
+
| Type | Schema (`@pylonsync/sdk`) | Validator (`@pylonsync/functions`) |
|
|
1092
|
+
|---|---|---|
|
|
1093
|
+
| string | `field.string()` | `v.string()` |
|
|
1094
|
+
| integer | `field.int()` | `v.int()` |
|
|
1095
|
+
| float | `field.float()` or `field.number()` | `v.float()` or `v.number()` |
|
|
1096
|
+
| boolean | `field.bool()` or `field.boolean()` | `v.bool()` or `v.boolean()` |
|
|
1097
|
+
| datetime | `field.datetime()` | `v.datetime()` or `v.string()` |
|
|
1098
|
+
| richtext | `field.richtext()` | `v.richtext()` or `v.string()` |
|
|
1099
|
+
| FK id | `field.id("X")` | `v.id("X")` |
|
|
1100
|
+
|
|
1101
|
+
What still **doesn't exist**: `v.money()`, `v.enum()`, `v.timestamp()`. When in doubt, read the package source in `node_modules/@pylonsync/`.
|
|
1102
|
+
- **Every function file must `export default`** the `mutation()/query()/action()` result. Named exports are ignored.
|
|
1103
|
+
- **`functions/*.ts` file names are the RPC names.** `functions/create-issue.ts` would be called as `create-issue` — prefer camelCase to match JS identifier conventions.
|
|
1104
|
+
- **Generated files** (`pylon.manifest.json`, `pylon.client.ts`) are rebuilt on every `pylon dev` invocation. Never edit by hand.
|
|
1105
|
+
- **Workspace deps** in examples use `workspace:*` — if you scaffold outside the Pylon monorepo, replace with the published version.
|
|
1106
|
+
- **Dev mode is generous by default** (CORS `*`, rate limits raised). Production requires explicit `PYLON_CORS_ORIGIN` — `*` is rejected.
|
|
1107
|
+
- **Policies filter silently on read** but throw `POLICY_DENIED` on write. If a list query returns fewer rows than expected, check read policies.
|
|
1108
|
+
- **Live queries need indexes** on filter columns. A `db.useQuery("Message", { where: { roomId } })` with no index on `roomId` will still work but scale O(N) per change.
|
|
1109
|
+
- **Always call `ctx.error(code, msg)`** instead of throwing plain `Error` — plain errors become generic `HANDLER_ERROR` on the client with the real message stripped.
|
|
1110
|
+
|
|
1111
|
+
## Quick decision guide
|
|
1112
|
+
|
|
1113
|
+
| User wants | You write |
|
|
1114
|
+
|---|---|
|
|
1115
|
+
| A new table | New `entity(...)` in `app.ts` + matching `policy(...)` + `buildManifest({ entities: [...], policies: [...] })` |
|
|
1116
|
+
| A list in the UI | `db.useQuery("Entity", { where: {...} })` — make sure the `where` keys are indexed |
|
|
1117
|
+
| A live counter / availability across tabs | `db.useQuery` over a public-read projection entity the mutation maintains — NOT `useReactiveQuery` |
|
|
1118
|
+
| A server-side join / computed value, live | `db.useReactiveQuery("fnName", args)` (leader-view; see footgun) |
|
|
1119
|
+
| Live full-text search | `db.useSearch("Entity", { query, facets })` + `.search({...})` on the entity |
|
|
1120
|
+
| Presence / cursors / typing | `useRoom(roomId, userId)` — ephemeral, not persisted |
|
|
1121
|
+
| An AI chat / agent that streams its answer | `action()` with `ctx.llm.stream(req, (e) => ctx.stream.write(e.text))` + `db.streamFn` on the client (auto-resumes on disconnect; `onStreamId` + `resumeStream` survive reloads); set `timeout:` when a tool call can be silent past the idle timeout (30s default; each stream event resets it) |
|
|
1122
|
+
| Agent output fanned to every CONNECTED watcher (second device, no HTTP caller) | `ctx.rooms.broadcast(room, topic, data)` from the mutation/action; live-only, no replay — persist the stream id for gap-proof delivery |
|
|
1123
|
+
| Multiplayer game / tick sim | `useShard(shardId, { subscriberId })` |
|
|
1124
|
+
| A form submission / write | A `mutation()` in `functions/X.ts` + `await callFn("X", args)` in the component (or `db.useMutation` for optimistic UI) |
|
|
1125
|
+
| Auth-gated functions | `auth: "user"` is the default on every `query` / `mutation` / `action`. Anon AND guest callers get `401 AUTH_REQUIRED` before the handler runs. `auth: "guest"` for pre-login callers (carts, public demos), `auth: "public"` for webhooks/healthchecks, `auth: "admin"` for ops. CRITICAL on actions — policies don't gate them. The same gate applies on `/api/webhooks/<name>` and to `db.useReactiveQuery` subscriptions (which also accept only `query` functions), so a webhook receiver must declare `auth: "public"` and verify the provider's signature itself. |
|
|
1126
|
+
| Access rules | `policy({ allowRead: "...", allowInsert: "..." })` — not middleware, not function guards |
|
|
1127
|
+
| Email / external API | `action()` (not `mutation()`) |
|
|
1128
|
+
| A one-shot deferred job | `ctx.scheduler.runAfter(delayMs, "fnName", args)` (or `runAt(unixMs, ...)` — Unix ms, not an ISO string) inside a mutation/action |
|
|
1129
|
+
| A recurring job | a **cron**: `cron("0 * * * *", "fnName")` (import `cron` from `@pylonsync/sdk`) in `buildManifest({ crons: [...] })`; point it at an `internal: true` function |
|
|
1130
|
+
| An LLM agent with tools + a persistent conversation | **`agent()`** — default-export `agent({ system, tools: { name: { description, args: {v...}, handler(ctx, input) } }, model?, maxSteps? })` from `functions/<name>.ts` (import `agent` from `@pylonsync/functions`). Compiles to a streaming action: call with `streamFn("<name>", { input, runId? })`. The framework runs the tool loop, validates tool args, streams tokens + `event: tool` frames, and persists every turn into the injected synced entities `AgentRun`/`AgentMessage` (owner-scoped; clients can't write them). Live transcript on any device: `useAgentRun(runId)`; token-level tail from another device: `resumeStream(run.streamId)`. Continue a conversation by passing `runId`. Sending while it generates QUEUES the message (`queued: true`) and the loop folds it in at its next turn boundary, so a chat composer never has to be disabled. Stop a run with `cancelAgentRun(agentName, runId)` (or `{ runId, cancel: true }`) — durable on the run row, so it reaches a loop on another machine; within ~2s it aborts a model response in flight (the provider stops generating) or a running tool's `ctx.signal`. `maxSteps` defaults to 64 per invocation. Failures mark the run `failed` with the error on the row. Requires a signed-in caller (auth "user" default) + a configured LLM provider. Webhooks/jobs have no user: from an `internal: true` or admin (elevated) action call `ctx.agents.run("<name>", { input, as: { userId, admin? }, context?, runId? })` — the run belongs to that user, and every tool handler gets `(ctx, input, run)` with `run.context` = the server-set context (stored on `AgentRun.context`), so tools find their conversation without smuggling ids through the title. Never mint a session over loopback for this. |
|
|
1131
|
+
| A multi-step process that must survive restarts (onboarding sequence, agent pipeline with approval gates, dunning) | a **durable workflow**: default-export `workflow(name, async (wf, ctx) => {...})` (import `workflow` from `@pylonsync/functions`) from a file in `workflows/` (sibling of `functions/`). `wf.step(name, fn)` runs exactly once (replayed from its recorded output after that); `wf.sleep("24h")` and `wf.waitForEvent(name)` pause without burning compute. Start from app code with `await ctx.workflows.start("name", input)` (mutations/actions; returns `{id}` immediately), deliver events with `ctx.workflows.sendEvent(id, event, data)` (buffered when the run isn't waiting yet, so none are lost); `wf.waitForEvent(name, { timeout: "60s" })` resolves `null` on timeout; `ctx.workflows.start(name, input, { key })` keeps one active run per key; `ctx.workflows.list({ key, status: "active" })` + `ctx.workflows.cancel(id, { reason })` stop runs from code; the admin HTTP routes (`POST /api/workflows/start`, `/api/workflows/<id>/event`) drive the same engine for operators. RULE: the step/sleep/waitForEvent call sequence must be deterministic across replays — branch on `wf.input` and step outputs only, and give steps unique names. |
|
|
1132
|
+
| Deploy | `pylon deploy --target fly` then `fly deploy . --config fly.toml` |
|
|
1133
|
+
|
|
1134
|
+
### Agent tooling — verify, policy dry-runs, MCP (pylon ≥ 0.3.313)
|
|
1135
|
+
|
|
1136
|
+
Three commands exist specifically so you can check your own work:
|
|
1137
|
+
|
|
1138
|
+
```bash
|
|
1139
|
+
# Prove the app actually serves: boots it on a free port (or targets a
|
|
1140
|
+
# running one with --url), checks /health, GETs every static route, and
|
|
1141
|
+
# fetches every referenced JS/CSS asset (catches "renders but ships no
|
|
1142
|
+
# hydration/styles"). Exit 0 only when nothing failed. --json for machine output.
|
|
1143
|
+
pylon verify
|
|
1144
|
+
pylon verify --url https://myapp.stack0.app
|
|
1145
|
+
|
|
1146
|
+
# Deploy. WAITS for the build by default, prints status transitions, and dumps
|
|
1147
|
+
# the build log if it fails — so a non-zero exit means the deploy really failed,
|
|
1148
|
+
# not just that queuing worked. Ctrl-C is safe; the build keeps running.
|
|
1149
|
+
pylon deploy
|
|
1150
|
+
pylon deploy --no-wait # fire-and-forget (CI that tracks status elsewhere)
|
|
1151
|
+
|
|
1152
|
+
# Same, plus walk the live URL with the `pylon verify` checks once it flips:
|
|
1153
|
+
pylon deploy --verify
|
|
1154
|
+
|
|
1155
|
+
# Check a running site the way a search engine and Lighthouse do: title,
|
|
1156
|
+
# description, h1, canonical, lang, viewport, Open Graph (og:image must load),
|
|
1157
|
+
# img alt, JSON-LD (home page needs Organization/LocalBusiness), broken internal
|
|
1158
|
+
# links, robots.txt, sitemap.xml. Lighthouse performance + accessibility when
|
|
1159
|
+
# Chrome is found (CHROME_PATH or chromium on PATH). One-line fix per problem.
|
|
1160
|
+
# Exit 1 on errors; warnings pass. --json for machine output.
|
|
1161
|
+
pylon audit # http://localhost:<PYLON_PORT or 4321>
|
|
1162
|
+
pylon audit https://myapp.stack0.app
|
|
1163
|
+
|
|
1164
|
+
# Dry-run a policy expression with the PRODUCTION evaluator before you
|
|
1165
|
+
# ship it — allow/deny + the exact comparison that failed. Exit 0=allow, 1=deny.
|
|
1166
|
+
pylon policy test 'auth.userId == data.ownerId' --auth userId=u1 --row '{"ownerId":"u2"}'
|
|
1167
|
+
# An update rule: --row is the stored row, --patch the write. Checks both rows.
|
|
1168
|
+
pylon policy test 'auth.tenantId == data.orgId' --auth userId=u1,tenantId=t1 \
|
|
1169
|
+
--row '{"orgId":"t1"}' --patch '{"orgId":"t2"}'
|
|
1170
|
+
```
|
|
1171
|
+
|
|
1172
|
+
And a running app can be attached directly to your tool loop over MCP:
|
|
1173
|
+
|
|
1174
|
+
```bash
|
|
1175
|
+
claude mcp add pylon -- pylon mcp --url http://localhost:4321
|
|
1176
|
+
```
|
|
1177
|
+
|
|
1178
|
+
which exposes `pylon_schema` (entities/policies/routes/functions), `pylon_list` / `pylon_get` (entity reads — row policies apply, no extra authority), `pylon_call` (functions), `pylon_policy_test`, and `pylon_verify`.
|
|
1179
|
+
|
|
1180
|
+
Per-route CSS strategy: `export const inlineCss = true` on a page inlines the compiled stylesheet into that route's SSR `<head>` (kills the render-blocking round trip — right for cold-traffic landing pages); `false` forces the cached `<link>` (right for logged-in pages, where the immutable sheet is fetched once and free forever). Unset defers to `PYLON_SSR_INLINE_CSS`. Sheets over 32KB always link.
|
|
1181
|
+
|
|
1182
|
+
Dev-mode failures are disclosed where you'll see them: unhandled function errors return `Internal handler error (dev): <message> [at <file:line>]` in the HTTP response (prod stays masked), and a failed Tailwind compile paints a red banner on every page instead of silently serving unstyled.
|
|
1183
|
+
|
|
1184
|
+
## Before you finish a task
|
|
1185
|
+
|
|
1186
|
+
- Run `bun run app.ts` in the project root — if it errors, the manifest won't build and `pylon dev` will fail silently on function load.
|
|
1187
|
+
- Run `pylon verify` — it boots the app and fails on any route/asset that doesn't serve. This is the cheap end-to-end check; don't skip it.
|
|
1188
|
+
- Building a public site? With `pylon dev` running, run `pylon audit` and fix every error it reports (missing titles, descriptions, og:image, structured data, broken links, sitemap gaps, slow pages).
|
|
1189
|
+
- Run `pylon lint` — flags wide-open dev policies (`allow*: "true"`) and other policy smells before they ship. Tighten what it reports.
|
|
1190
|
+
- **Test in tiers, cheapest first.** Tier 1: pure helpers in `lib/` (milliseconds, no DOM). Tier 2: components with fixture props via `@testing-library/react` (happy-dom is preloaded through `bunfig.toml`). Tier 3: functions/policies through `pylon policy test` and `pylon verify`. If a component is hard to test, it's usually because it fetches its own data — lift that to the container.
|
|
1191
|
+
- Run `pylon test` — discovers `*.test.ts` / `*.test.tsx` under `tests/` (or `functions/`) and runs them with Bun's test runner (`import { test, expect } from "bun:test"`).
|
|
1192
|
+
- If you added a function, verify it's discoverable by opening the project and checking that `pylon dev` logs list your new function name in the `Loaded N functions` output.
|
|
1193
|
+
- If you changed an entity, schema auto-migration runs — but destructive changes (dropping a required column) will refuse to apply without bumping `manifest.version`.
|
|
1194
|
+
- If you wrote or changed a policy, dry-run it: `pylon policy test '<expr>' --auth ... --row ...` for both the allow case AND the deny case.
|
|
1195
|
+
|
|
1196
|
+
## Beyond the React quickstart — what's available
|
|
1197
|
+
|
|
1198
|
+
This skill focused on the React/TS happy path. Pylon has more — fetch the docs page when these come up:
|
|
1199
|
+
|
|
1200
|
+
### Auth (`/auth/*` in the docs)
|
|
1201
|
+
- **Magic codes** (`/api/auth/magic/send` + `/verify`) — recommended sign-in flow. 6 digits by default (`PYLON_AUTH_CODE_LENGTH`, 4–8), 10-min expiry, throttled, daily wrong-guess limit per email (`429 CODE_LOCKED`).
|
|
1202
|
+
- **Email + password** (`/api/auth/password/register` + `/login`) — Argon2id-hashed.
|
|
1203
|
+
- **OAuth** — Google + GitHub built in (`/api/auth/login/:provider` + `/callback/:provider`). CSRF-protected via state tokens.
|
|
1204
|
+
- **Sessions** — opaque 256-bit tokens, 30-day default. `/api/auth/refresh`, `/sessions` GET/DELETE for management.
|
|
1205
|
+
- **Trusted server-side mint** — `POST /api/auth/sessions/trusted-mint`. HMAC-signed (`X-Pylon-Trusted-Signature: hex(HMAC_SHA256(PYLON_TRUSTED_SECRET, ts + "." + body))`), ±5min freshness window. Reach for this when another trusted system (Stripe Checkout, custom IdP) has verified the email and you want to skip the magic-link roundtrip. Opt-in: 404 unless `PYLON_TRUSTED_SECRET` is set.
|
|
1206
|
+
- **RBAC** — roles on the session; `auth.hasRole('x')` in policies. `admin` role bypasses everything.
|
|
1207
|
+
- **Multi-tenant** — `auth.tenantId` from `/api/auth/select-org`; row-scoped policies via `data.orgId == auth.tenantId`.
|
|
1208
|
+
- **API keys** — via the `api_keys` plugin, scoped + rotatable + Argon2-hashed.
|
|
1209
|
+
|
|
1210
|
+
### Plugins (`/plugins/*` in the docs)
|
|
1211
|
+
Built-ins, declared in `manifest.plugins`:
|
|
1212
|
+
- **Security**: `rate_limit`, `cors`, `csrf`, `net_guard` (SSRF defense), `totp`, `jwt`, `api_keys`, `session_expiry`, `password_auth`
|
|
1213
|
+
- **Data hygiene**: `validation`, `slugify`, `timestamps`, `computed`, `cascade`, `versioning`, `soft_delete`, `tenant_scope`, `organizations`
|
|
1214
|
+
- **Search & AI**: `search` (FTS5 + facets — configured on the entity via `.search({...})`, not the plugin list), `ai_proxy`
|
|
1215
|
+
- **Integrations**: `file_storage` (S3/R2/Stack0), `cache`, `cache_client` (Redis), `email`, `webhooks`, `stripe`, `feature_flags`, `audit_log`
|
|
1216
|
+
|
|
1217
|
+
**npm plugins** (imported, not declared in `manifest.plugins`): `@pylonsync/stripe` (web billing: checkout, portal, webhook, plan limits, trials), `@pylonsync/revenuecat` (native in-app purchases: the RevenueCat webhook and a server-verified `syncEntitlements` action write one `RcEntitlement` row per user + entitlement that syncs to every device; `syncEntitlements` accepts guests by default (`syncAuth: "user"` to require an account); app code gates with `hasEntitlement(rows, "pro")` from **`@pylonsync/revenuecat/client`** — the package root imports `@pylonsync/functions` and breaks Metro/browser bundles). Native sign-in for mobile apps: `POST /api/auth/native/apple|google` verifies a platform id_token against the provider's JWKS (audiences from `PYLON_APPLE_NATIVE_CLIENT_IDS` / `PYLON_GOOGLE_NATIVE_CLIENT_IDS`); `@pylonsync/react-native` exposes `nativeSignIn`, `guestSession`, `sendEmailCode`/`verifyEmailCode`, `signOut`, `deleteAccount`. **Account deletion:** `DELETE /api/auth/account` removes the User row and Pylon's auth rows only. Declare `auth({ onDeleteAccount: "deleteMyData" })` and write that function (`internal: true`, args `{ userId }`, runs as the user) to delete the app's own rows; a throw aborts the deletion. **Mobile session boot:** call `init()` (`@pylonsync/react-native`) before anything reads `db.sync`, and read `useSession().resolved` — `userId` is null until `/api/auth/me` answers, which is not "signed out".
|
|
1218
|
+
|
|
1219
|
+
**Vector search is a field type, not a plugin.** Declare `embedding: field.vector(1536)` (always server-only; dims must match the embedding model), fill it with `ctx.llm.embed(texts)` (OpenAI `text-embedding-3-small` by default when `OPENAI_API_KEY` is set; `PYLON_EMBEDDINGS_PROVIDER=voyage` + `VOYAGE_API_KEY` for Voyage), and query with `ctx.db.vectorSearch("Doc", { field: "embedding", vector, limit, metric?, filter? })` — exact k-NN, cosine default, hits `{id, score, doc}` best-first with vector fields stripped from `doc`. HTTP: `POST /api/vector-search/<Entity>`. Ctx rules compose the usual way: `vectorSearch` lives on `ctx.db` (queries + mutations; actions have no `ctx.db`), and `embed` is NOT available in queries (reactive re-runs re-bill). Standard flow: action embeds → `ctx.runQuery` a query that searches, or `ctx.runMutation` to store the vector. Do NOT put `vector_search` in `manifest.plugins`; that key does nothing.
|
|
1220
|
+
|
|
1221
|
+
**Not implemented — do NOT declare this.** `mcp` appears in the roadmap catalog (`pylon plugins list`) but has no implementation behind it; putting it in `manifest.plugins` does nothing. For MCP, use the CLI's `pylon mcp` (see above) — it is not a manifest plugin.
|
|
1222
|
+
|
|
1223
|
+
### Clients (`/clients/*` in the docs)
|
|
1224
|
+
- `@pylonsync/sdk` — schema DSL + manifest builder
|
|
1225
|
+
- `@pylonsync/react` — hooks (covered in this skill)
|
|
1226
|
+
- `@pylonsync/react-native` — Expo SQLite-backed offline replica
|
|
1227
|
+
- `@pylonsync/next` — Server Actions, RSC data fetching, middleware auth
|
|
1228
|
+
- `@pylonsync/sync` — sync engine standalone (Vue, Svelte, Solid, vanilla)
|
|
1229
|
+
- `@pylonsync/loro` — Loro CRDT integration for collaborative editing
|
|
1230
|
+
- **Swift SDK** at `packages/swift/` — `PylonClient`, `PylonSync`, `PylonRealtime`, `PylonSwiftUI`. iOS 16+, macOS 13+, tvOS 16+, watchOS 9+, Linux. Codegen via `pylon codegen client --target swift`.
|
|
1231
|
+
- **C# / Unity SDK** at `packages/csharp/` (UPM package `com.pylonsync.pylon`, install from `https://github.com/pylonsync/pylon-csharp.git#<version>`) — `PylonClient` (guest/magic-code/password/Apple/Google/Steam sign-in, functions, entities) and `ShardConnection` (shard wire v2, JSON + MessagePack, replication, transfers), plus `Predictor`, `ShardClock`, `EntityInterpolator`. No reflection, IL2CPP-safe; values are `PylonValue`, typed calls take an `IPylonConverter<T>` (`JsonUtilityConverter<T>` in Unity). Create clients on Unity's main thread and events run there. No WebGL, no offline sync engine.
|
|
1232
|
+
|
|
1233
|
+
### Stack0 Cloud
|
|
1234
|
+
Managed Pylon at `cloud.stack0.dev`. Same binary, same APIs.
|
|
1235
|
+
- `pylon login` → `pylon projects create <slug>` → `pylon deploy`
|
|
1236
|
+
- Custom domains via `pylon domains add`
|
|
1237
|
+
- Environment vars via `pylon env set/list/unset`
|
|
1238
|
+
- Includes: managed Postgres, TLS, magic-link email, OAuth (your creds), file storage, Studio, logs/metrics
|
|
1239
|
+
- Pricing: usage-based, no monthly minimums; free tier covers small projects
|
|
1240
|
+
|
|
1241
|
+
### Stack0 Analytics — the relay is a FUNCTION, not a route
|
|
1242
|
+
Hosted at `analytics.stack0.dev`. No package to install; a script tag plus one HTTP endpoint. Full code: https://www.stack0.dev/docs/sdk/analytics
|
|
1243
|
+
|
|
1244
|
+
The bare tag (`<script defer src="https://analytics.stack0.dev/track.js" data-site="SITE_KEY">`) only works on a site with no server of your own. **Anywhere you control the server — which includes every Pylon app — relay through your own origin**, or the Analytics CORS allowlist refuses the browser's preflight and the install looks exactly like "no traffic yet".
|
|
1245
|
+
|
|
1246
|
+
Do NOT reach for the Next.js recipe. `/api/fn/*` is Pylon's own namespace, so `app/api/fn/ingestEvent/route.ts` is never matched, and there is no `next.config.js` to rewrite in.
|
|
1247
|
+
- `functions/ingestEvent.ts` — an `action` with `auth: "public"` that forwards `ctx.request.rawBody` to `https://analytics.stack0.dev/api/fn/ingestEvent` and returns the upstream JSON **verbatim** (`track.js` reads `visitorId` off it). Only actions get `ctx.request`. Forward `rawBody`, not `args` — the beacon carries fields your arg list does not declare. Copy `user-agent`, `x-forwarded-for`, and your edge's geo headers (`cf-ip*` or `x-vercel-ip-*`) or every visitor lands at their country's centre.
|
|
1248
|
+
- Name it `ingestEvent` and `track.js` derives the path itself; any other name needs `data-endpoint`, whose value must contain `/api/fn/` or it is read as an origin.
|
|
1249
|
+
- `app/rt/track.js/route.ts` — a `RawRouteHandler` that fetches and caches `track.js`, so an ad blocker that knows the Analytics host does not take it out. Load it as `<script defer src="/rt/track.js" data-site="SITE_KEY" />` from `app/layout.tsx`.
|
|
1250
|
+
- `stack0Analytics()` is a **browser global** and Pylon renders on the server: call it from an event handler or effect, never during a render. A no-JS `<Form>` + route handler has no client code left to run, so POST the event from the handler.
|
|
1251
|
+
- Never send `revenueCents`, `currency` or `customerId` through `ingestEvent` — the site key is public and cannot authenticate money. Revenue arrives by Stripe webhook to `/api/fn/stripeRevenue`.
|
|
1252
|
+
|
|
1253
|
+
### Stack0 Feedback — a script tag and a guest session
|
|
1254
|
+
Hosted at `feedback.stack0.app`. Boards, votes, comments, roadmaps, changelogs. Full API: https://www.stack0.dev/docs/sdk/feedback
|
|
1255
|
+
|
|
1256
|
+
- Embed: `<script src="https://feedback.stack0.app/widget.js" data-project="SLUG" defer></script>`, straight into `app/layout.tsx`. Pylon server-renders it, so you write no client code.
|
|
1257
|
+
- **There is no API key and no MCP server.** Public reads take no credential: POST JSON to `/api/fn/portalView` `{ slug }`, `portalPostView`, `portalRoadmapView`, `portalChangelogView`, `similarPosts`. An unknown, unpublished or archived portal returns `null`.
|
|
1258
|
+
- Writing on someone's behalf takes a session, not a key: `POST /api/auth/guest` returns `{ token }`, then send `authorization: Bearer <token>` to `submitPost`, `toggleVote`, `addComment`. Call `similarPosts` first and vote on a match rather than filing a duplicate.
|
|
1259
|
+
- Reading your own board from your own app is a plain `fetch` inside a normal query.
|
|
1260
|
+
|
|
1261
|
+
### Compare-vs-X pages
|
|
1262
|
+
If the user asks "Pylon vs Convex/Supabase/Firebase/Colyseus/Playroom/Nakama", point them at `/compare/<vendor>` in the docs — each page has a structured comparison with sources.
|
|
1263
|
+
|
|
1264
|
+
## Swift / iOS / macOS specifics
|
|
1265
|
+
|
|
1266
|
+
When the user is in a Swift project (Xcode, `Package.swift`, `*.swift` files):
|
|
1267
|
+
|
|
1268
|
+
- **Install** via SPM: `.package(url: "https://github.com/pylonsync/pylon-swift.git", from: "0.3.0")`
|
|
1269
|
+
- **Auth**: `try await client.startMagicCode(email:)` then `try await client.verifyMagicCode(email:code:)`
|
|
1270
|
+
- **Sync**: `await SyncEngine(config: cfg, client: client, persistence: SQLitePersistence(...))`, then `await engine.start()`
|
|
1271
|
+
- **Mutations**: `try await engine.insert("Todo", ["title": .string("x")])` (optimistic, queued, idempotent). Throws `MutationRejectedError` (`code`, `message`) after rolling back when the server rejects the write; returns when the server applies it or queues it offline.
|
|
1272
|
+
- **SwiftUI**: `@StateObject var todos = PylonQuery<Todo>(engine: engine, entity: "Todo")` — `todos.rows` re-renders on change
|
|
1273
|
+
- **CRDTs**: `PylonLoroDoc(entity:rowId:)` then `await crdtDoc.attach(to: engine)` — uses `loro-swift` internally
|
|
1274
|
+
- **Codegen**: `pylon codegen client manifest.json --target swift --out PylonGenerated.swift` produces typed structs + `PylonClient` extensions
|
|
1275
|
+
- **Linux**: works via `FoundationNetworking`; needs `apt-get install libsqlite3-dev`
|
|
1276
|
+
|
|
1277
|
+
The Swift SDK is at full TS-sync parity — same wire format, same crash-safety, same offline behavior. CRDT logic is shared with TS via the same Rust Loro core.
|
|
1278
|
+
|
|
1279
|
+
Reference example: `examples/swift-todo/` is a complete SwiftUI iOS/macOS app.
|