@vibes.diy/api-types 0.0.0-smoke-70d942c5-1774564530
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/LICENSE.md +232 -0
- package/README.md +539 -0
- package/auth.d.ts +13 -0
- package/auth.js +2 -0
- package/auth.js.map +1 -0
- package/cf-env.d.ts +23 -0
- package/cf-env.js +2 -0
- package/cf-env.js.map +1 -0
- package/index.d.ts +34 -0
- package/index.js +19 -0
- package/index.js.map +1 -0
- package/invite.d.ts +856 -0
- package/invite.js +241 -0
- package/invite.js.map +1 -0
- package/msg-types.d.ts +4215 -0
- package/msg-types.js +1089 -0
- package/msg-types.js.map +1 -0
- package/package.json +23 -0
- package/screen-shotter.d.ts +7 -0
- package/screen-shotter.js +10 -0
- package/screen-shotter.js.map +1 -0
- package/tsconfig.json +18 -0
- package/types.d.ts +72 -0
- package/types.js +70 -0
- package/types.js.map +1 -0
- package/vibes-diy-api.d.ts +52 -0
- package/vibes-diy-api.js +8 -0
- package/vibes-diy-api.js.map +1 -0
- package/vibes-diy-serv-ctx.d.ts +44 -0
- package/vibes-diy-serv-ctx.js +29 -0
- package/vibes-diy-serv-ctx.js.map +1 -0
- package/vibes-types.d.ts +41 -0
- package/vibes-types.js +14 -0
- package/vibes-types.js.map +1 -0
package/README.md
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
# vibes.diy API
|
|
2
|
+
|
|
3
|
+
WebSocket-based API for vibes.diy chat persistence and app deployment. Supports both HTTP POST and WebSocket connections using the same handler via the Evento event-driven framework.
|
|
4
|
+
|
|
5
|
+
## Package Structure
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
api/
|
|
9
|
+
├── types/ @vibes.diy/api-types SHARED (client + server)
|
|
10
|
+
│ ├── msg-types.ts Request/response types, VibeFile, MsgBase envelope, arktype schemas
|
|
11
|
+
│ ├── types.ts FileSystemItem with transform support
|
|
12
|
+
│ └── vibes-diy-serv-ctx.ts Server context for wrapper/iframe rendering
|
|
13
|
+
│
|
|
14
|
+
├── pkg/ @vibes.diy/api-pkg SHARED (client + server)
|
|
15
|
+
│ ├── api.ts VibesDiyApiIface interface (3 methods)
|
|
16
|
+
│ ├── encoder.ts Evento encoders: ReqRes, W3CWebSocket, Combined
|
|
17
|
+
│ ├── index.ts Re-exports
|
|
18
|
+
│ └── react/ React components (client only in practice)
|
|
19
|
+
│
|
|
20
|
+
├── impl/ @vibes.diy/api-impl CLIENT
|
|
21
|
+
│ └── index.ts VibeDiyApi class (WebSocket client, WIP - no reconnection)
|
|
22
|
+
│
|
|
23
|
+
├── svc/ @vibes.diy/api-svc SERVER (Cloudflare Workers)
|
|
24
|
+
│ ├── cf-serve.ts Cloudflare Worker entry point (HTTP + WebSocket)
|
|
25
|
+
│ ├── create-handler.ts Evento pipeline setup with all handlers
|
|
26
|
+
│ ├── check-auth.ts Auth middleware (clerk, device-id verification)
|
|
27
|
+
│ ├── unwrap-msg-base.ts MsgBase envelope unwrapping for validation
|
|
28
|
+
│ ├── api.ts VibesApiSQLCtx type + VibesFPApiParameters
|
|
29
|
+
│ ├── entry-point-utils.ts URL construction for deployed apps
|
|
30
|
+
│ │
|
|
31
|
+
│ ├── public/ Public API handlers (Evento handlers)
|
|
32
|
+
│ │ ├── ensure-app-slug-item.ts App deployment with CID-based storage
|
|
33
|
+
│ │ ├── ensure-chat-context.ts Chat session creation/retrieval
|
|
34
|
+
│ │ ├── append-chat-section.ts Message persistence with seq numbers
|
|
35
|
+
│ │ └── serv-entry-point.ts Serves deployed app HTML
|
|
36
|
+
│ │
|
|
37
|
+
│ ├── intern/ Internal helpers
|
|
38
|
+
│ │ ├── ensure-slug-binding.ts User/app slug management (random-words)
|
|
39
|
+
│ │ ├── ensure-storage.ts CID calculation (SHA-256 + base58btc)
|
|
40
|
+
│ │ ├── import-map.ts ESM import map generation (esm.sh)
|
|
41
|
+
│ │ ├── render-vibes.tsx HTML rendering with import map injection
|
|
42
|
+
│ │ └── write-apps.ts App record creation with transforms (sucrase, acorn)
|
|
43
|
+
│ │
|
|
44
|
+
│ └── sql/
|
|
45
|
+
│ └── vibes-diy-api-schema.ts Drizzle schema (D1)
|
|
46
|
+
│
|
|
47
|
+
└── tests/ @vibes.diy/api-test
|
|
48
|
+
└── api.test.ts
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Package Summary
|
|
52
|
+
|
|
53
|
+
| Package | Runs On | Purpose |
|
|
54
|
+
| ---------------------- | ------- | --------------------------------------- |
|
|
55
|
+
| `@vibes.diy/api-types` | Both | arktype schemas, request/response types |
|
|
56
|
+
| `@vibes.diy/api-pkg` | Both | Interface + encoders (shared contract) |
|
|
57
|
+
| `@vibes.diy/api-impl` | Client | `VibeDiyApi` WebSocket client class |
|
|
58
|
+
| `@vibes.diy/api-svc` | Server | Cloudflare Worker handlers, D1/Drizzle |
|
|
59
|
+
|
|
60
|
+
## Architecture
|
|
61
|
+
|
|
62
|
+
### Message Envelope
|
|
63
|
+
|
|
64
|
+
All requests are wrapped in a `MsgBase` envelope:
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
interface MsgBase {
|
|
68
|
+
tid: string; // Transaction ID for request/response correlation
|
|
69
|
+
src: string; // Source identifier
|
|
70
|
+
dst: string; // Destination identifier
|
|
71
|
+
ttl: number; // Time-to-live
|
|
72
|
+
payload: unknown; // The actual request/response
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Evento Pipeline
|
|
77
|
+
|
|
78
|
+
The server uses Evento (from `@adviser/cement`) for request routing. Handlers are registered in order:
|
|
79
|
+
|
|
80
|
+
1. **CORS preflight** - Handles OPTIONS requests
|
|
81
|
+
2. **servEntryPoint** - Serves deployed app HTML (hostname routing: `{appSlug}--{userSlug}.{host}/~{fsId}~/`)
|
|
82
|
+
3. **Request logging** - Logs incoming POST/PUT requests, rejects other methods with 503
|
|
83
|
+
4. **ensureAppSlugItem** - App deployment handler
|
|
84
|
+
5. **ensureChatContext** - Chat session handler
|
|
85
|
+
6. **appendChatSection** - Message persistence handler
|
|
86
|
+
7. **Not-found handler** - Returns 501 for unmatched requests (semantically "Not Implemented")
|
|
87
|
+
8. **Error handler** - Catches and formats errors as 500
|
|
88
|
+
|
|
89
|
+
Each handler has `validate` (arktype schema check) and `handle` (business logic) phases. Some handlers also have a `post` phase for cleanup/logging.
|
|
90
|
+
|
|
91
|
+
## Data Flow
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
Client (browser) Server (CF Worker)
|
|
95
|
+
───────────────── ──────────────────
|
|
96
|
+
VibeDiyApi.ensureAppSlug() → cf-serve.ts
|
|
97
|
+
↓ ↓
|
|
98
|
+
WebSocket.send(MsgBox<Req>) → WebSocketPair upgrade
|
|
99
|
+
↓
|
|
100
|
+
CombinedEventoEnDecoder.encode()
|
|
101
|
+
↓
|
|
102
|
+
Evento.trigger() with handlers
|
|
103
|
+
↓
|
|
104
|
+
unwrapMsgBase() → extract payload
|
|
105
|
+
↓
|
|
106
|
+
checkAuth() → verify token
|
|
107
|
+
↓
|
|
108
|
+
handler.handle() → business logic
|
|
109
|
+
↓
|
|
110
|
+
D1 queries (Drizzle ORM)
|
|
111
|
+
↓
|
|
112
|
+
MsgBox<Res> ← SendResponseProvider.send()
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## API Methods
|
|
116
|
+
|
|
117
|
+
### `ensureAppSlug()`
|
|
118
|
+
|
|
119
|
+
Deploy an app with a filesystem. Process:
|
|
120
|
+
|
|
121
|
+
1. Verify auth token (clerk/device-id)
|
|
122
|
+
2. Create or retrieve user slug binding
|
|
123
|
+
3. Create or retrieve app slug binding
|
|
124
|
+
4. Calculate CIDs for all file contents
|
|
125
|
+
5. Store assets in D1 `Assets` table
|
|
126
|
+
6. Apply transforms (jsx-to-js, import map generation)
|
|
127
|
+
7. Create `Apps` record with filesystem manifest
|
|
128
|
+
8. Return `entryPointUrl` for iframe loading
|
|
129
|
+
|
|
130
|
+
### `ensureChatContext()`
|
|
131
|
+
|
|
132
|
+
Create or retrieve a chat session:
|
|
133
|
+
|
|
134
|
+
1. If `contextId` provided, verify it exists and belongs to user
|
|
135
|
+
2. Otherwise, generate new contextId (12-char ID)
|
|
136
|
+
3. Insert into `ChatContexts` table
|
|
137
|
+
4. Return `contextId`
|
|
138
|
+
|
|
139
|
+
### `appendChatSection()`
|
|
140
|
+
|
|
141
|
+
Add messages to a chat context:
|
|
142
|
+
|
|
143
|
+
1. Verify context exists and belongs to user
|
|
144
|
+
2. Get max `seq` for context, increment
|
|
145
|
+
3. Insert into `ChatSections` with `origin` ('user' or 'llm')
|
|
146
|
+
4. Blocks use `BlockMsgs | PromptMsg` types from `@vibes.diy/call-ai-v2`
|
|
147
|
+
5. Return `seq` number
|
|
148
|
+
|
|
149
|
+
## CI/CD
|
|
150
|
+
|
|
151
|
+
The API is bundled into the main vibes.diy Cloudflare Worker (not a separate deployment).
|
|
152
|
+
|
|
153
|
+
### Workflow
|
|
154
|
+
|
|
155
|
+
`.github/workflows/vibes-diy-deploy.yaml`
|
|
156
|
+
|
|
157
|
+
**Triggers:**
|
|
158
|
+
|
|
159
|
+
- Push to `vibes.diy/**/*` paths
|
|
160
|
+
- Tags: `vibes-diy@*`
|
|
161
|
+
- Manual dispatch
|
|
162
|
+
|
|
163
|
+
### Environments
|
|
164
|
+
|
|
165
|
+
| Trigger | Environment | Domain |
|
|
166
|
+
| ----------------------- | ----------- | ------------------------ |
|
|
167
|
+
| Tag `vibes-diy@s*` | staging | `*.dev-v2.vibesdiy.net` |
|
|
168
|
+
| Tag `vibes-diy@p*` | production | `*.prod-v2.vibesdiy.net` |
|
|
169
|
+
| Path push or other tags | dev | `*.dev-v2.vibesdiy.net` |
|
|
170
|
+
|
|
171
|
+
### Deploy Steps
|
|
172
|
+
|
|
173
|
+
Deployment is handled by the GitHub Action (`vibes.diy/actions/deploy`). The action runs:
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
pnpm run build # Build React app + bundle worker
|
|
177
|
+
pnpm run drizzle:d1-remote # Run D1 migrations
|
|
178
|
+
core-cli writeEnv | wrangler secret bulk # Push secrets
|
|
179
|
+
pnpm run deploy:${ENV} # wrangler deploy
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Do not run these manually - push a tag or merge to trigger the workflow.
|
|
183
|
+
|
|
184
|
+
### Infrastructure
|
|
185
|
+
|
|
186
|
+
| Resource | Binding | Purpose |
|
|
187
|
+
| ------------- | -------- | ----------------------------- |
|
|
188
|
+
| D1 Database | `DB` | Chat contexts, sections, apps |
|
|
189
|
+
| Static Assets | `ASSETS` | React app build |
|
|
190
|
+
|
|
191
|
+
### Server Context (VibesApiSQLCtx)
|
|
192
|
+
|
|
193
|
+
All handlers receive a shared context via `ctx.ctx.getOrThrow<VibesApiSQLCtx>("vibesApiCtx")`:
|
|
194
|
+
|
|
195
|
+
```typescript
|
|
196
|
+
interface VibesApiSQLCtx {
|
|
197
|
+
sthis: SuperThis; // Fireproof utilities (logger, nextId, env)
|
|
198
|
+
db: VibesSqlite; // Drizzle DB instance
|
|
199
|
+
tokenApi: Record<string, FPApiToken>; // Auth verifiers by type
|
|
200
|
+
deviceCA: DeviceIdCAIf; // Device ID certificate authority
|
|
201
|
+
logger: Logger; // Structured logger
|
|
202
|
+
params: VibesFPApiParameters; // Service configuration
|
|
203
|
+
cache: CfCacheIf; // Cloudflare cache API
|
|
204
|
+
fetchPkgVersion(pkg): Promise<string | undefined>; // npm registry lookup
|
|
205
|
+
waitUntil<T>(promise): void; // CF worker lifecycle
|
|
206
|
+
ensureStorage(...items): Promise<Result<StorageResult[]>>; // Asset storage
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
### D1 Schema
|
|
211
|
+
|
|
212
|
+
Defined in `svc/sql/vibes-diy-api-schema.ts` using Drizzle ORM.
|
|
213
|
+
|
|
214
|
+
**Assets** - Binary content storage (could move to R2)
|
|
215
|
+
| Column | Type | Description |
|
|
216
|
+
|--------|------|-------------|
|
|
217
|
+
| `assetId` | text PK | CID of content |
|
|
218
|
+
| `content` | blob | Actual content |
|
|
219
|
+
| `created` | text | ISO timestamp |
|
|
220
|
+
|
|
221
|
+
**UserSlugBindings** - Maps users to their human-friendly slugs
|
|
222
|
+
| Column | Type | Description |
|
|
223
|
+
|--------|------|-------------|
|
|
224
|
+
| `userId` | text | User identifier |
|
|
225
|
+
| `userSlug` | text | Human-friendly user slug (unique) |
|
|
226
|
+
| `created` | text | ISO timestamp |
|
|
227
|
+
|
|
228
|
+
Primary key: `(userSlug, userId)`. Unique index on `userSlug`.
|
|
229
|
+
|
|
230
|
+
**AppSlugBindings** - Maps apps to slugs within a user's namespace
|
|
231
|
+
| Column | Type | Description |
|
|
232
|
+
|--------|------|-------------|
|
|
233
|
+
| `userSlug` | text FK | References UserSlugBindings.userSlug |
|
|
234
|
+
| `appSlug` | text | Human-friendly app slug |
|
|
235
|
+
| `created` | text | ISO timestamp |
|
|
236
|
+
|
|
237
|
+
Primary key: `(appSlug, userSlug)`.
|
|
238
|
+
|
|
239
|
+
**Apps** - Deployed app versions with filesystem and environment
|
|
240
|
+
| Column | Type | Description |
|
|
241
|
+
|--------|------|-------------|
|
|
242
|
+
| `appSlug` | text | App identifier |
|
|
243
|
+
| `userId` | text | Owner |
|
|
244
|
+
| `userSlug` | text | Owner's slug |
|
|
245
|
+
| `releaseSeq` | int | Incremented on each deployment |
|
|
246
|
+
| `fsId` | text | CID of filesystem manifest |
|
|
247
|
+
| `env` | json | Environment variables (VibesEnv) |
|
|
248
|
+
| `fileSystem` | json | Array of FileSystemItem with transforms |
|
|
249
|
+
| `mode` | text | 'production' or 'dev' |
|
|
250
|
+
| `created` | text | ISO timestamp |
|
|
251
|
+
|
|
252
|
+
Primary key: `(appSlug, userId, releaseSeq)`. Indexes on `fsId` and `created`.
|
|
253
|
+
|
|
254
|
+
**ChatContexts** - Chat session containers
|
|
255
|
+
| Column | Type | Description |
|
|
256
|
+
|--------|------|-------------|
|
|
257
|
+
| `contextId` | text PK | UUID v4 |
|
|
258
|
+
| `userId` | text | Owner |
|
|
259
|
+
| `created` | text | ISO timestamp |
|
|
260
|
+
|
|
261
|
+
**ChatSections** - Individual messages/blocks within a chat
|
|
262
|
+
| Column | Type | Description |
|
|
263
|
+
|--------|------|-------------|
|
|
264
|
+
| `contextId` | text FK | References ChatContexts.contextId |
|
|
265
|
+
| `seq` | int | Section sequence number (0-indexed, auto-incremented) |
|
|
266
|
+
| `origin` | text | 'user' or 'llm' |
|
|
267
|
+
| `blocks` | json | Array of BlockMsgs or PromptMsg from call-ai-v2 |
|
|
268
|
+
| `created` | text | ISO timestamp |
|
|
269
|
+
|
|
270
|
+
Primary key: `(seq, contextId)`.
|
|
271
|
+
|
|
272
|
+
### Environment Variables
|
|
273
|
+
|
|
274
|
+
**Required:**
|
|
275
|
+
| Variable | Purpose |
|
|
276
|
+
|----------|---------|
|
|
277
|
+
| `CLOUD_SESSION_TOKEN_PUBLIC` | Public key for cloud session tokens |
|
|
278
|
+
| `CLERK_PUBLISHABLE_KEY` | Clerk auth verification |
|
|
279
|
+
| `DEVICE_ID_CA_PRIV_KEY` | Device ID certificate authority private key |
|
|
280
|
+
| `DEVICE_ID_CA_CERT` | Device ID certificate authority cert |
|
|
281
|
+
| `FP_VERSION` | Fireproof version for import maps |
|
|
282
|
+
| `VIBES_SVC_HOSTNAME_BASE` | Base hostname for deployed apps (e.g., `vibes.app`) |
|
|
283
|
+
|
|
284
|
+
**Optional (with defaults):**
|
|
285
|
+
| Variable | Default | Purpose |
|
|
286
|
+
|----------|---------|---------|
|
|
287
|
+
| `VIBES_SVC_PROTOCOL` | `https` | Protocol for deployed apps |
|
|
288
|
+
| `MAX_APP_SLUG_PER_USER_ID` | `10` | Max app slugs per user |
|
|
289
|
+
| `MAX_USER_SLUG_PER_USER_ID` | `10` | Max user slugs per user |
|
|
290
|
+
| `MAX_APPS_PER_USER_ID` | `50` | Max app deployments per user |
|
|
291
|
+
|
|
292
|
+
## Message Types
|
|
293
|
+
|
|
294
|
+
### VibeFile (for deployment)
|
|
295
|
+
|
|
296
|
+
Six variants for different content types:
|
|
297
|
+
|
|
298
|
+
| Type | Content | Use Case |
|
|
299
|
+
| ------------------- | ------------------------------------ | ------------------------------ |
|
|
300
|
+
| `code-block` | Inline string, `lang: 'jsx' \| 'js'` | JSX/JS source code |
|
|
301
|
+
| `code-ref` | `refId` reference | Code stored elsewhere |
|
|
302
|
+
| `str-asset-block` | Inline string | CSS, JSON, text files |
|
|
303
|
+
| `str-asset-ref` | `refId` reference | String assets stored elsewhere |
|
|
304
|
+
| `uint8-asset-block` | `Uint8Array` | Images, fonts, binaries |
|
|
305
|
+
| `uint8-asset-ref` | `refId` reference | Binary assets stored elsewhere |
|
|
306
|
+
|
|
307
|
+
All file types share base properties:
|
|
308
|
+
|
|
309
|
+
```typescript
|
|
310
|
+
{
|
|
311
|
+
filename: string; // Must start with /, no //, /../, /./
|
|
312
|
+
entryPoint?: boolean; // Last one wins, marks app entry
|
|
313
|
+
mimetype?: string; // Derived from filename if not set
|
|
314
|
+
}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
### FileSystemItem (stored result)
|
|
318
|
+
|
|
319
|
+
After processing, files become `FileSystemItem`:
|
|
320
|
+
|
|
321
|
+
```typescript
|
|
322
|
+
{
|
|
323
|
+
fileName: string;
|
|
324
|
+
mimeType: string;
|
|
325
|
+
assetId: string; // CID of content
|
|
326
|
+
assetURI: string; // sql://Assets.assetId, s3://..., r2://...
|
|
327
|
+
entryPoint?: boolean;
|
|
328
|
+
size: number;
|
|
329
|
+
transform?: {
|
|
330
|
+
type: 'jsx-to-js' | 'imports' | 'import-map' | 'transformed';
|
|
331
|
+
// ... transform-specific fields
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
### Auth Types
|
|
337
|
+
|
|
338
|
+
```typescript
|
|
339
|
+
type DashAuthType = {
|
|
340
|
+
type: "clerk" | "device-id";
|
|
341
|
+
token: string;
|
|
342
|
+
};
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
Auth is verified via `tokenApi` which supports:
|
|
346
|
+
|
|
347
|
+
- **clerk** - Clerk JWT verification using `CLERK_PUB_JWT_KEY` / `CLERK_PUB_JWT_URL` env vars
|
|
348
|
+
- **device-id** - Device certificate verification using `DEVICE_ID_CA_*` keys
|
|
349
|
+
|
|
350
|
+
## Client Usage
|
|
351
|
+
|
|
352
|
+
> [!WARNING]
|
|
353
|
+
> The client (`@vibes.diy/api-impl`) is currently a work-in-progress. While it can send requests over WebSocket, the response correlation logic (matching server responses to requests via `tid`) is not yet fully implemented. It is currently primarily used for testing with direct handler calls.
|
|
354
|
+
|
|
355
|
+
The client is currently used in tests. The main vibes.diy app doesn't use it yet - integration is in progress.
|
|
356
|
+
|
|
357
|
+
### Creating a Client
|
|
358
|
+
|
|
359
|
+
```typescript
|
|
360
|
+
import { VibeDiyApi } from "@vibes.diy/api-impl";
|
|
361
|
+
import { Result } from "@adviser/cement";
|
|
362
|
+
|
|
363
|
+
const api = new VibeDiyApi({
|
|
364
|
+
apiUrl: "wss://api.vibes.diy/v1/ws", // Default if omitted
|
|
365
|
+
getToken: async () => {
|
|
366
|
+
// Return auth token (Clerk or device-id)
|
|
367
|
+
return Result.Ok({ type: "clerk", token: clerkToken });
|
|
368
|
+
},
|
|
369
|
+
timeoutMs: 10000, // Default: 10s request timeout
|
|
370
|
+
});
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
The client uses `KeyedResolvOnce` for connection pooling - multiple `VibeDiyApi` instances with the same `apiUrl` share a WebSocket connection. (See `impl/index.ts` for custom message routing options via the `msg` config.)
|
|
374
|
+
|
|
375
|
+
### Deploying an App
|
|
376
|
+
|
|
377
|
+
```typescript
|
|
378
|
+
const res = await api.ensureAppSlug({
|
|
379
|
+
mode: "dev", // 'dev' or 'production'
|
|
380
|
+
appSlug: "my-app", // optional, server generates 3-word slug
|
|
381
|
+
userSlug: "my-user", // optional, server generates 3-word slug
|
|
382
|
+
env: { API_KEY: "..." }, // optional, passed to app runtime
|
|
383
|
+
fileSystem: [
|
|
384
|
+
{
|
|
385
|
+
type: "code-block",
|
|
386
|
+
lang: "jsx",
|
|
387
|
+
filename: "/App.jsx", // Must start with /, becomes entry point
|
|
388
|
+
entryPoint: true,
|
|
389
|
+
content: "export default function App() { return <div>Hello</div>; }",
|
|
390
|
+
},
|
|
391
|
+
],
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
if (res.isOk()) {
|
|
395
|
+
const { entryPointUrl, fsId, userSlug, appSlug, fileSystem } = res.Ok();
|
|
396
|
+
// entryPointUrl -> https://{appSlug}--{userSlug}.{hostnameBase}/~{fsId}~/
|
|
397
|
+
// e.g. https://my-app--my-user.vibes.app/~zABC123~/
|
|
398
|
+
// fsId -> CID of filesystem manifest
|
|
399
|
+
// fileSystem -> Array<FileSystemItem> with assetIds and transforms
|
|
400
|
+
}
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
**Response includes:**
|
|
404
|
+
|
|
405
|
+
- `entryPointUrl` - URL to load in iframe (constructed from `VIBES_SVC_*` config)
|
|
406
|
+
- `wrapperUrl` - URL for wrapper page with auth handoff
|
|
407
|
+
- `fsId` - CID of the filesystem manifest
|
|
408
|
+
- `fileSystem` - Processed `FileSystemItem[]` with CIDs and transforms applied
|
|
409
|
+
|
|
410
|
+
### Chat Context Management
|
|
411
|
+
|
|
412
|
+
```typescript
|
|
413
|
+
// Create a new chat context (server generates contextId)
|
|
414
|
+
const ctx = await api.ensureChatContext({});
|
|
415
|
+
|
|
416
|
+
// Or retrieve/create with a specific contextId
|
|
417
|
+
const ctx = await api.ensureChatContext({ contextId: "my-context-id" });
|
|
418
|
+
|
|
419
|
+
if (ctx.isOk()) {
|
|
420
|
+
const { contextId } = ctx.Ok();
|
|
421
|
+
|
|
422
|
+
// Append a user message
|
|
423
|
+
const userRes = await api.appendChatSection({
|
|
424
|
+
contextId,
|
|
425
|
+
origin: "user", // 'user' | 'llm'
|
|
426
|
+
blocks: [
|
|
427
|
+
// BlockMsgs or PromptMsg from @vibes.diy/call-ai-v2
|
|
428
|
+
{
|
|
429
|
+
type: "prompt.txt",
|
|
430
|
+
streamId: "stream-1",
|
|
431
|
+
request: { model: "gpt-4", messages: [{ role: "user", content: "Hello" }] },
|
|
432
|
+
timestamp: new Date(),
|
|
433
|
+
},
|
|
434
|
+
],
|
|
435
|
+
});
|
|
436
|
+
// userRes.Ok().seq -> 0 (first section)
|
|
437
|
+
|
|
438
|
+
// Append LLM response
|
|
439
|
+
const llmRes = await api.appendChatSection({
|
|
440
|
+
contextId,
|
|
441
|
+
origin: "llm",
|
|
442
|
+
blocks: sectionBlocks, // BlockMsgs from call-ai sections stream
|
|
443
|
+
});
|
|
444
|
+
// llmRes.Ok().seq -> 1 (second section)
|
|
445
|
+
}
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
**Note:** Context ownership is enforced - you can only append to contexts created by your userId.
|
|
449
|
+
|
|
450
|
+
### Testing
|
|
451
|
+
|
|
452
|
+
Tests use a local handler directly rather than WebSocket. See `api/tests/api.test.ts` for the full setup including:
|
|
453
|
+
|
|
454
|
+
- Creating a local D1/libsql database
|
|
455
|
+
- Setting up test device-id auth
|
|
456
|
+
- Calling the handler directly
|
|
457
|
+
|
|
458
|
+
Note: The test passes an ad-hoc `fetch` property via TypeScript structural typing, but this isn't part of the official `VibeDiyApiParam` interface. A proper `fetch` override may be added in the future.
|
|
459
|
+
|
|
460
|
+
## Running Tests
|
|
461
|
+
|
|
462
|
+
```bash
|
|
463
|
+
cd vibes.diy/api/tests
|
|
464
|
+
pnpm test
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
## Implementation Details
|
|
468
|
+
|
|
469
|
+
### URL Structure
|
|
470
|
+
|
|
471
|
+
Deployed apps are served via hostname-based routing:
|
|
472
|
+
|
|
473
|
+
```
|
|
474
|
+
https://{appSlug}--{userSlug}.{hostnameBase}/~{fsId}~/
|
|
475
|
+
└────────────────────┘ └──────────┘ └──────┘
|
|
476
|
+
hostname base domain version path
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
Example: `https://my-app--fuzzy-purple-elephant.vibes.app/~z4PhNX7vuL~/`
|
|
480
|
+
|
|
481
|
+
The `extractHostToBindings()` function parses:
|
|
482
|
+
|
|
483
|
+
- Hostname pattern: `{appSlug}--{userSlug}.{rest}`
|
|
484
|
+
- Path pattern: `/~{fsId}~/` (fsId starts with `z`, 8+ chars)
|
|
485
|
+
- If no fsId in path, serves latest production release
|
|
486
|
+
|
|
487
|
+
### Slug Generation
|
|
488
|
+
|
|
489
|
+
When `appSlug` or `userSlug` are not provided, the server generates 3-word slugs using the `random-words` package:
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
492
|
+
generate({ exactly: 1, wordsPerString: 3, separator: "-" });
|
|
493
|
+
// → "fuzzy-purple-elephant"
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
Up to 5 attempts are made to find a unique slug before failing.
|
|
497
|
+
|
|
498
|
+
### Transform Pipeline
|
|
499
|
+
|
|
500
|
+
The `write-apps.ts` module applies transforms to uploaded files:
|
|
501
|
+
|
|
502
|
+
1. **JSX → JS** (`sucrase` with automatic JSX runtime)
|
|
503
|
+
- Input: `code-block` with `lang: "jsx"`
|
|
504
|
+
- Output: `/~~transformed~~/{cid}` with `transform: { type: "transformed", action: "jsx-to-js" }`
|
|
505
|
+
|
|
506
|
+
2. **Import Extraction** (`acorn` parser)
|
|
507
|
+
- Parses all JS files for `import`/`export` statements
|
|
508
|
+
- Extracts bare specifiers (e.g., `react`, `@fireproof/core`)
|
|
509
|
+
|
|
510
|
+
3. **Import Map Generation**
|
|
511
|
+
- Unknown packages → npm registry lookup for version → `esm.sh` URL
|
|
512
|
+
- Predefined mappings for React 19.2.1, Fireproof, Clerk, etc.
|
|
513
|
+
- Output: `/~~calculated~~/import-map.json` with `transform: { type: "import-map" }`
|
|
514
|
+
|
|
515
|
+
### fsId Calculation
|
|
516
|
+
|
|
517
|
+
The `fsId` is a deterministic CID computed from:
|
|
518
|
+
|
|
519
|
+
```typescript
|
|
520
|
+
hash(sortedFilenames + mimetypes + contentCIDs + sortedEnvJSON);
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
Same files + same env = same fsId (enables deduplication).
|
|
524
|
+
|
|
525
|
+
### Asset Caching
|
|
526
|
+
|
|
527
|
+
`serv-entry-point.ts` uses two-tier Cloudflare caching:
|
|
528
|
+
|
|
529
|
+
1. **Global cache** by CID: `assetCacheUrl/{assetId}`
|
|
530
|
+
2. **Path cache** by request URL
|
|
531
|
+
|
|
532
|
+
On cache miss: D1 query → populate both caches via `waitUntil()`.
|
|
533
|
+
|
|
534
|
+
### App Eviction
|
|
535
|
+
|
|
536
|
+
When a user exceeds `MAX_APPS_PER_USER_ID`:
|
|
537
|
+
|
|
538
|
+
- Oldest `dev` mode apps are evicted first (10% of total + 1)
|
|
539
|
+
- `production` apps are preserved
|
package/auth.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { DashAuthType, VerifiedAuthResult } from "@fireproof/core-types-protocols-dashboard";
|
|
2
|
+
export type ReqWithVerifiedAuth<REQ extends {
|
|
3
|
+
type: string;
|
|
4
|
+
auth: DashAuthType;
|
|
5
|
+
}> = REQ & {
|
|
6
|
+
readonly _auth: VerifiedAuthResult;
|
|
7
|
+
};
|
|
8
|
+
export type ReqWithOptionalAuth<REQ extends {
|
|
9
|
+
type: string;
|
|
10
|
+
auth?: DashAuthType;
|
|
11
|
+
}> = REQ & {
|
|
12
|
+
readonly _auth?: VerifiedAuthResult;
|
|
13
|
+
};
|
package/auth.js
ADDED
package/auth.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../jsr/auth.ts"],"names":[],"mappings":""}
|
package/cf-env.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { D1Database, DurableObjectNamespace, Queue, Fetcher, R2Bucket } from "@cloudflare/workers-types";
|
|
2
|
+
export interface CFEnv {
|
|
3
|
+
DB: D1Database;
|
|
4
|
+
ASSETS: Fetcher;
|
|
5
|
+
ENVIRONMENT: string;
|
|
6
|
+
FS_IDS_BUCKET: R2Bucket;
|
|
7
|
+
VIBES_SVC_HOSTNAME_BASE: string;
|
|
8
|
+
VIBES_SVC_PROTOCOL: string;
|
|
9
|
+
VIBES_SVC_PORT?: string;
|
|
10
|
+
MAX_TENANTS?: number;
|
|
11
|
+
MAX_ADMIN_USERS?: number;
|
|
12
|
+
MAX_MEMBER_USERS?: number;
|
|
13
|
+
MAX_INVITES?: number;
|
|
14
|
+
MAX_LEDGERS?: number;
|
|
15
|
+
MAX_APPID_BINDINGS?: number;
|
|
16
|
+
CLERK_PUBLISHABLE_KEY: string;
|
|
17
|
+
CLOUD_SESSION_TOKEN_PUBLIC: string;
|
|
18
|
+
DB_FLAVOUR?: string;
|
|
19
|
+
NEON_DATABASE_URL?: string;
|
|
20
|
+
CHAT_SESSIONS: DurableObjectNamespace;
|
|
21
|
+
VIBES_SERVICE: Queue;
|
|
22
|
+
BROWSER: Fetcher;
|
|
23
|
+
}
|
package/cf-env.js
ADDED
package/cf-env.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cf-env.js","sourceRoot":"","sources":["../jsr/cf-env.ts"],"names":[],"mappings":""}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Result } from "@adviser/cement";
|
|
2
|
+
export * from "./types.js";
|
|
3
|
+
export * from "./vibes-diy-serv-ctx.js";
|
|
4
|
+
export * from "./msg-types.js";
|
|
5
|
+
export * from "./vibes-types.js";
|
|
6
|
+
export * from "./screen-shotter.js";
|
|
7
|
+
export * from "./vibes-diy-api.js";
|
|
8
|
+
export * from "./invite.js";
|
|
9
|
+
export * from "./cf-env.js";
|
|
10
|
+
export * from "./auth.js";
|
|
11
|
+
export interface FetchOkResult {
|
|
12
|
+
type: "fetch.ok";
|
|
13
|
+
url: string;
|
|
14
|
+
data: ReadableStream<Uint8Array>;
|
|
15
|
+
}
|
|
16
|
+
export declare function isFetchOkResult(result: FetchResult): result is FetchOkResult;
|
|
17
|
+
export declare function isFetchErrResult(result: FetchResult): result is FetchErrResult;
|
|
18
|
+
export interface FetchErrResult {
|
|
19
|
+
type: "fetch.err";
|
|
20
|
+
url: string;
|
|
21
|
+
error: Error;
|
|
22
|
+
}
|
|
23
|
+
export interface FetchNotFoundResult {
|
|
24
|
+
type: "fetch.notfound";
|
|
25
|
+
url: string;
|
|
26
|
+
}
|
|
27
|
+
export declare function isFetchNotFoundResult(result: FetchResult): result is FetchNotFoundResult;
|
|
28
|
+
export type FetchResult = FetchOkResult | FetchErrResult | FetchNotFoundResult;
|
|
29
|
+
export interface S3Api {
|
|
30
|
+
genId: () => string;
|
|
31
|
+
get(iurl: string): Promise<FetchResult>;
|
|
32
|
+
put(iurl: string): Promise<WritableStream<Uint8Array>>;
|
|
33
|
+
rename(fromUrl: string, toUrl: string): Promise<Result<void>>;
|
|
34
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export * from "./types.js";
|
|
2
|
+
export * from "./vibes-diy-serv-ctx.js";
|
|
3
|
+
export * from "./msg-types.js";
|
|
4
|
+
export * from "./vibes-types.js";
|
|
5
|
+
export * from "./screen-shotter.js";
|
|
6
|
+
export * from "./vibes-diy-api.js";
|
|
7
|
+
export * from "./invite.js";
|
|
8
|
+
export * from "./cf-env.js";
|
|
9
|
+
export * from "./auth.js";
|
|
10
|
+
export function isFetchOkResult(result) {
|
|
11
|
+
return result.type === "fetch.ok";
|
|
12
|
+
}
|
|
13
|
+
export function isFetchErrResult(result) {
|
|
14
|
+
return result.type === "fetch.err";
|
|
15
|
+
}
|
|
16
|
+
export function isFetchNotFoundResult(result) {
|
|
17
|
+
return result.type === "fetch.notfound";
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=index.js.map
|
package/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../jsr/index.ts"],"names":[],"mappings":"AAEA,cAAc,YAAY,CAAC;AAC3B,cAAc,yBAAyB,CAAC;AACxC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,qBAAqB,CAAC;AAEpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,aAAa,CAAC;AAE5B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAQ1B,MAAM,UAAU,eAAe,CAAC,MAAmB;IACjD,OAAO,MAAM,CAAC,IAAI,KAAK,UAAU,CAAC;AACpC,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,MAAmB;IAClD,OAAO,MAAM,CAAC,IAAI,KAAK,WAAW,CAAC;AACrC,CAAC;AAUD,MAAM,UAAU,qBAAqB,CAAC,MAAmB;IACvD,OAAO,MAAM,CAAC,IAAI,KAAK,gBAAgB,CAAC;AAC1C,CAAC"}
|