@terreno/ai 0.3.2
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/.claude/CLAUDE.local.md +208 -0
- package/.cursor/rules/00-root.mdc +342 -0
- package/.cursorrules +221 -0
- package/.github/copilot-instructions.md +337 -0
- package/AGENTS.md +337 -0
- package/biome.jsonc +20 -0
- package/bunfig.toml +3 -0
- package/dist/aiApp.d.ts +59 -0
- package/dist/aiApp.js +67 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +23 -0
- package/dist/models/aiRequest.d.ts +2 -0
- package/dist/models/aiRequest.js +76 -0
- package/dist/models/aiRequest.test.d.ts +1 -0
- package/dist/models/aiRequest.test.js +187 -0
- package/dist/models/fileAttachment.d.ts +2 -0
- package/dist/models/fileAttachment.js +25 -0
- package/dist/models/fileAttachment.test.d.ts +1 -0
- package/dist/models/fileAttachment.test.js +217 -0
- package/dist/models/gptHistory.d.ts +2 -0
- package/dist/models/gptHistory.js +56 -0
- package/dist/models/gptHistory.test.d.ts +1 -0
- package/dist/models/gptHistory.test.js +336 -0
- package/dist/models/index.d.ts +3 -0
- package/dist/models/index.js +9 -0
- package/dist/routes/aiRequestsExplorer.d.ts +2 -0
- package/dist/routes/aiRequestsExplorer.js +153 -0
- package/dist/routes/files.d.ts +5 -0
- package/dist/routes/files.js +168 -0
- package/dist/routes/gpt.d.ts +2 -0
- package/dist/routes/gpt.js +593 -0
- package/dist/routes/gptHistories.d.ts +3 -0
- package/dist/routes/gptHistories.js +29 -0
- package/dist/routes/index.d.ts +5 -0
- package/dist/routes/index.js +13 -0
- package/dist/routes/mcp.d.ts +2 -0
- package/dist/routes/mcp.js +133 -0
- package/dist/routes/routes.test.d.ts +1 -0
- package/dist/routes/routes.test.js +303 -0
- package/dist/service/aiService.d.ts +24 -0
- package/dist/service/aiService.js +453 -0
- package/dist/service/aiService.test.d.ts +1 -0
- package/dist/service/aiService.test.js +367 -0
- package/dist/service/fileStorage.d.ts +24 -0
- package/dist/service/fileStorage.js +143 -0
- package/dist/service/index.d.ts +4 -0
- package/dist/service/index.js +15 -0
- package/dist/service/mcpService.d.ts +14 -0
- package/dist/service/mcpService.js +271 -0
- package/dist/service/prompts.d.ts +4 -0
- package/dist/service/prompts.js +14 -0
- package/dist/tests/bunSetup.d.ts +1 -0
- package/dist/tests/bunSetup.js +227 -0
- package/dist/types/index.d.ts +170 -0
- package/dist/types/index.js +7 -0
- package/package.json +55 -0
- package/src/aiApp.ts +110 -0
- package/src/index.ts +6 -0
- package/src/models/aiRequest.test.ts +101 -0
- package/src/models/aiRequest.ts +45 -0
- package/src/models/fileAttachment.test.ts +119 -0
- package/src/models/fileAttachment.ts +31 -0
- package/src/models/gptHistory.test.ts +209 -0
- package/src/models/gptHistory.ts +71 -0
- package/src/models/index.ts +3 -0
- package/src/routes/aiRequestsExplorer.ts +107 -0
- package/src/routes/files.ts +128 -0
- package/src/routes/gpt.ts +503 -0
- package/src/routes/gptHistories.ts +31 -0
- package/src/routes/index.ts +5 -0
- package/src/routes/mcp.ts +76 -0
- package/src/routes/routes.test.ts +168 -0
- package/src/service/aiService.test.ts +242 -0
- package/src/service/aiService.ts +269 -0
- package/src/service/fileStorage.ts +74 -0
- package/src/service/index.ts +9 -0
- package/src/service/mcpService.ts +120 -0
- package/src/service/prompts.ts +18 -0
- package/src/tests/bunSetup.ts +163 -0
- package/src/types/index.ts +224 -0
- package/tsconfig.json +31 -0
package/.cursorrules
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
# @terreno/ai
|
|
2
|
+
|
|
3
|
+
AI service layer for Terreno apps providing GPT chat, request logging, and admin tools. Provider-agnostic via Vercel AI SDK. This is a **backend-only** package — no React, no UI components, no frontend code.
|
|
4
|
+
|
|
5
|
+
## Commands
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun run compile # Compile TypeScript
|
|
9
|
+
bun run dev # Watch mode
|
|
10
|
+
bun run test # Run tests
|
|
11
|
+
bun run lint # Lint code
|
|
12
|
+
bun run lint:fix # Fix lint issues
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Architecture
|
|
16
|
+
|
|
17
|
+
### File Structure
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
src/
|
|
21
|
+
index.ts # All package exports
|
|
22
|
+
models/
|
|
23
|
+
aiRequest.ts # AI request logging model
|
|
24
|
+
gptHistory.ts # Conversation history model
|
|
25
|
+
index.ts # Model exports
|
|
26
|
+
routes/
|
|
27
|
+
gpt.ts # GPT chat streaming and remix endpoints
|
|
28
|
+
gptHistories.ts # GPT history CRUD via modelRouter
|
|
29
|
+
aiRequestsExplorer.ts # Admin-only AI request explorer
|
|
30
|
+
index.ts # Route exports
|
|
31
|
+
service/
|
|
32
|
+
aiService.ts # Provider-agnostic AI service class
|
|
33
|
+
prompts.ts # System prompt constants
|
|
34
|
+
index.ts # Service exports
|
|
35
|
+
types/
|
|
36
|
+
index.ts # All type definitions
|
|
37
|
+
tests/
|
|
38
|
+
bunSetup.ts # Test environment setup
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## AIService
|
|
42
|
+
|
|
43
|
+
Provider-agnostic AI service using Vercel AI SDK's `LanguageModel` interface. Consuming apps provide their own model instance.
|
|
44
|
+
|
|
45
|
+
### Usage
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
import {AIService} from "@terreno/ai";
|
|
49
|
+
import {google} from "@ai-sdk/google";
|
|
50
|
+
|
|
51
|
+
const aiService = new AIService({
|
|
52
|
+
model: google("gemini-2.5-flash"),
|
|
53
|
+
defaultTemperature: 1.0, // optional
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Methods
|
|
58
|
+
|
|
59
|
+
| Method | Description |
|
|
60
|
+
|--------|-------------|
|
|
61
|
+
| `generateText(options)` | Generate text (non-streaming) |
|
|
62
|
+
| `generateTextStream(options)` | Stream text chunks (AsyncGenerator) |
|
|
63
|
+
| `generateRemix({text, userId?})` | Reword text naturally |
|
|
64
|
+
| `generateSummary({text, userId?})` | Summarize text |
|
|
65
|
+
| `translateText({text, targetLanguage, sourceLanguage?, userId?})` | Translate text |
|
|
66
|
+
| `generateChatStream({messages, systemPrompt?, userId?})` | Stream chat response |
|
|
67
|
+
|
|
68
|
+
All methods automatically log requests to the AIRequest model.
|
|
69
|
+
|
|
70
|
+
### Temperature Presets
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
import {TemperaturePresets} from "@terreno/ai";
|
|
74
|
+
|
|
75
|
+
TemperaturePresets.DETERMINISTIC // 0
|
|
76
|
+
TemperaturePresets.LOW // 0.3
|
|
77
|
+
TemperaturePresets.BALANCED // 0.7
|
|
78
|
+
TemperaturePresets.DEFAULT // 1.0
|
|
79
|
+
TemperaturePresets.HIGH // 1.5
|
|
80
|
+
TemperaturePresets.MAXIMUM // 2.0
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Models
|
|
84
|
+
|
|
85
|
+
### AIRequest
|
|
86
|
+
|
|
87
|
+
Logs all AI requests with metrics for monitoring and debugging.
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
// Fields
|
|
91
|
+
aiModel: string // Model identifier (e.g., "gemini-2.5-flash")
|
|
92
|
+
prompt: string // Input prompt
|
|
93
|
+
requestType: "general" | "remix" | "summarization" | "translation"
|
|
94
|
+
response?: string // AI response text
|
|
95
|
+
responseTime?: number // Response time in ms
|
|
96
|
+
tokensUsed?: number // Total tokens consumed
|
|
97
|
+
userId?: ObjectId // User who made the request
|
|
98
|
+
error?: string // Error message if failed
|
|
99
|
+
metadata?: Mixed // Additional data
|
|
100
|
+
|
|
101
|
+
// Static method
|
|
102
|
+
await AIRequest.logRequest({aiModel, prompt, requestType, ...});
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Plugins: `createdUpdatedPlugin`, `isDeletedPlugin`, `findOneOrNone`, `findExactlyOne`
|
|
106
|
+
|
|
107
|
+
### GptHistory
|
|
108
|
+
|
|
109
|
+
Persists conversation history with auto-generated titles.
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
// Fields
|
|
113
|
+
title?: string // Auto-generated from first assistant response
|
|
114
|
+
userId: ObjectId // Owner (required)
|
|
115
|
+
prompts: Array<{ // Conversation messages
|
|
116
|
+
text: string,
|
|
117
|
+
type: "user" | "assistant" | "system",
|
|
118
|
+
model?: string
|
|
119
|
+
}>
|
|
120
|
+
|
|
121
|
+
// Virtual
|
|
122
|
+
ownerId // Alias for userId (Permissions.IsOwner compatibility)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Pre-save hook auto-generates title from first assistant response (first 50 chars).
|
|
126
|
+
|
|
127
|
+
## Routes
|
|
128
|
+
|
|
129
|
+
### addGptRoutes(router, options)
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import {addGptRoutes} from "@terreno/ai";
|
|
133
|
+
|
|
134
|
+
addGptRoutes(router, {aiService, openApiOptions: options});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
| Endpoint | Method | Description |
|
|
138
|
+
|----------|--------|-------------|
|
|
139
|
+
| `/gpt/prompt` | POST | SSE streaming chat with history persistence |
|
|
140
|
+
| `/gpt/remix` | POST | Non-streaming text remix |
|
|
141
|
+
|
|
142
|
+
Both require authentication. `/gpt/prompt` accepts `{prompt, historyId?, systemPrompt?}` and streams via Server-Sent Events.
|
|
143
|
+
|
|
144
|
+
### addGptHistoryRoutes(router, options)
|
|
145
|
+
|
|
146
|
+
Standard modelRouter CRUD at `/gpt/histories`:
|
|
147
|
+
- **Create/List**: `IsAuthenticated`
|
|
148
|
+
- **Read/Update/Delete**: `IsOwner`
|
|
149
|
+
- Query filtered by `userId`
|
|
150
|
+
- Sorted by `-updated`
|
|
151
|
+
|
|
152
|
+
### addAiRequestsExplorerRoutes(router, options)
|
|
153
|
+
|
|
154
|
+
Admin-only endpoint at `GET /aiRequestsExplorer`:
|
|
155
|
+
- Paginated with `?page=1&limit=20`
|
|
156
|
+
- Filters: `requestType`, `model`, `startDate`, `endDate`
|
|
157
|
+
- Aggregation pipeline with user lookup
|
|
158
|
+
- Returns `{data, total, page, limit, more}`
|
|
159
|
+
|
|
160
|
+
## Integration
|
|
161
|
+
|
|
162
|
+
Consuming apps wire up routes in their `setupServer` call:
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
import {AIService, addGptRoutes, addGptHistoryRoutes, addAiRequestsExplorerRoutes} from "@terreno/ai";
|
|
166
|
+
import {google} from "@ai-sdk/google";
|
|
167
|
+
|
|
168
|
+
const aiService = new AIService({model: google("gemini-2.5-flash")});
|
|
169
|
+
|
|
170
|
+
setupServer({
|
|
171
|
+
addRoutes: (router, options) => {
|
|
172
|
+
addGptHistoryRoutes(router, options);
|
|
173
|
+
addGptRoutes(router, {aiService, openApiOptions: options});
|
|
174
|
+
addAiRequestsExplorerRoutes(router, {openApiOptions: options});
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## Conventions
|
|
180
|
+
|
|
181
|
+
- Uses `aiModel` field name (not `model`) to avoid Mongoose internal property conflicts
|
|
182
|
+
- GptHistory uses `userId` field with `ownerId` virtual for `Permissions.IsOwner` compatibility
|
|
183
|
+
- Custom query filter `(user) => ({userId: user?.id})` instead of `OwnerQueryFilter`
|
|
184
|
+
- All AI calls are logged via private `logRequest()` — logging failures never break the main flow
|
|
185
|
+
- Express user accessed via `(req as any).user` casting pattern
|
|
186
|
+
- Error handling: `throw new APIError({status: 400, title: "..."})` — check conditions early
|
|
187
|
+
|
|
188
|
+
## Testing
|
|
189
|
+
|
|
190
|
+
- Framework: bun test with expect
|
|
191
|
+
- HTTP testing: supertest
|
|
192
|
+
- Mock AI model: Create mock with `doGenerate`/`doStream` methods returning `ReadableStream`
|
|
193
|
+
- Test DB: `mongodb://127.0.0.1/terreno-ai-test`
|
|
194
|
+
- Preload: `./src/tests/bunSetup.ts` (MongoDB connection, log silencing, Sentry mock)
|
|
195
|
+
- **Never mock @terreno/api or models** — test against real functionality
|
|
196
|
+
|
|
197
|
+
### Mock Model Pattern
|
|
198
|
+
|
|
199
|
+
```typescript
|
|
200
|
+
const createMockModel = () => ({
|
|
201
|
+
doGenerate: mock(async () => ({
|
|
202
|
+
finishReason: "stop" as const,
|
|
203
|
+
rawCall: {rawPrompt: "", rawSettings: {}},
|
|
204
|
+
text: "response text",
|
|
205
|
+
usage: {completionTokens: 10, promptTokens: 5},
|
|
206
|
+
})),
|
|
207
|
+
doStream: mock(async () => ({
|
|
208
|
+
rawCall: {rawPrompt: "", rawSettings: {}},
|
|
209
|
+
stream: new ReadableStream({
|
|
210
|
+
start(controller) {
|
|
211
|
+
controller.enqueue({type: "text-delta" as const, textDelta: "chunk "});
|
|
212
|
+
controller.enqueue({type: "finish" as const, finishReason: "stop" as const, usage: {completionTokens: 10, promptTokens: 5}});
|
|
213
|
+
controller.close();
|
|
214
|
+
},
|
|
215
|
+
}),
|
|
216
|
+
})),
|
|
217
|
+
modelId: "mock-model",
|
|
218
|
+
provider: "mock-provider",
|
|
219
|
+
specificationVersion: "v1" as const,
|
|
220
|
+
});
|
|
221
|
+
```
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
# Terreno
|
|
2
|
+
|
|
3
|
+
A monorepo containing shared packages for building full-stack applications with React Native and Express/Mongoose.
|
|
4
|
+
|
|
5
|
+
## Packages
|
|
6
|
+
|
|
7
|
+
- **api/** - REST API framework built on Express/Mongoose (`@terreno/api`)
|
|
8
|
+
- **ui/** - React Native UI component library (`@terreno/ui`)
|
|
9
|
+
- **rtk/** - Redux Toolkit Query utilities for API backends (`@terreno/rtk`)
|
|
10
|
+
- **admin-backend/** - Admin panel backend plugin for @terreno/api (`@terreno/admin-backend`)
|
|
11
|
+
- **admin-frontend/** - Admin panel frontend screens for @terreno/api backends (`@terreno/admin-frontend`)
|
|
12
|
+
- **mcp-server/** - MCP server for AI assistant integration (`@terreno/mcp-server`)
|
|
13
|
+
- **demo/** - Demo app for showcasing and testing UI components
|
|
14
|
+
- **example-frontend/** - Example Expo app demonstrating full stack usage
|
|
15
|
+
- **example-backend/** - Example Express backend using @terreno/api
|
|
16
|
+
|
|
17
|
+
## Development
|
|
18
|
+
|
|
19
|
+
Uses [Bun](https://bun.sh/) as the package manager.
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
bun install # Install dependencies
|
|
23
|
+
bun run compile # Compile all packages
|
|
24
|
+
bun run lint # Lint all packages
|
|
25
|
+
bun run lint:fix # Fix lint issues
|
|
26
|
+
bun run test # Run tests in api and ui
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Package-specific commands
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
bun run api:test # Test API package
|
|
33
|
+
bun run ui:test # Test UI package
|
|
34
|
+
bun run demo:start # Start demo app
|
|
35
|
+
bun run frontend:web # Start frontend example
|
|
36
|
+
bun run backend:dev # Start backend example
|
|
37
|
+
bun run mcp:build # Build MCP server
|
|
38
|
+
bun run mcp:start # Start MCP server
|
|
39
|
+
bun run admin-backend:compile # Compile admin backend
|
|
40
|
+
bun run admin-frontend:compile # Compile admin frontend
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## How the Packages Work Together
|
|
44
|
+
|
|
45
|
+
The three core packages form a complete full-stack framework:
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
BACKEND
|
|
49
|
+
@terreno/api
|
|
50
|
+
- Mongoose models with modelRouter -> CRUD endpoints
|
|
51
|
+
- Built-in auth (JWT + Passport)
|
|
52
|
+
- Automatic OpenAPI spec generation
|
|
53
|
+
|
|
|
54
|
+
/openapi.json
|
|
55
|
+
|
|
|
56
|
+
RTK Query SDK Codegen
|
|
57
|
+
|
|
|
58
|
+
FRONTEND
|
|
59
|
+
@terreno/rtk
|
|
60
|
+
- Generated hooks from OpenAPI spec
|
|
61
|
+
- Auth slice with JWT token management
|
|
62
|
+
- Automatic token refresh
|
|
63
|
+
+
|
|
64
|
+
@terreno/ui
|
|
65
|
+
- React Native components (Box, Button, TextField, etc.)
|
|
66
|
+
- TerrenoProvider for theming
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Integration Flow
|
|
70
|
+
|
|
71
|
+
1. **Backend (api)**: Define Mongoose models, use `modelRouter` to create CRUD endpoints with permissions
|
|
72
|
+
2. **OpenAPI Generation**: `setupServer` automatically generates `/openapi.json`
|
|
73
|
+
3. **SDK Codegen**: Frontend runs `bun run sdk` to generate RTK Query hooks from OpenAPI spec
|
|
74
|
+
4. **Frontend (rtk + ui)**: Use generated hooks with UI components for type-safe API calls
|
|
75
|
+
|
|
76
|
+
## Example Apps (Keep These Updated!)
|
|
77
|
+
|
|
78
|
+
The `example-frontend/` and `example-backend/` directories serve as both documentation and integration tests. When adding features to api, ui, or rtk:
|
|
79
|
+
|
|
80
|
+
1. **Add examples** demonstrating new features
|
|
81
|
+
2. **Update SDK** after backend changes: `cd example-frontend && bun run sdk`
|
|
82
|
+
3. **Verify integration** by running both examples together
|
|
83
|
+
|
|
84
|
+
### Running the Full Stack
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
# Terminal 1: Start backend
|
|
88
|
+
bun run backend:dev
|
|
89
|
+
|
|
90
|
+
# Terminal 2: Start frontend
|
|
91
|
+
bun run frontend:web
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Code Style
|
|
95
|
+
|
|
96
|
+
### TypeScript/JavaScript
|
|
97
|
+
- Use ES module syntax and TypeScript for all code
|
|
98
|
+
- Prefer interfaces over types; avoid enums, use maps
|
|
99
|
+
- Prefer const arrow functions over `function` keyword
|
|
100
|
+
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`)
|
|
101
|
+
- Use camelCase directories (e.g., `components/authWizard`)
|
|
102
|
+
- Favor named exports
|
|
103
|
+
- Use the RORO pattern (Receive an Object, Return an Object)
|
|
104
|
+
|
|
105
|
+
### Dates and Time
|
|
106
|
+
- Always use Luxon instead of Date or dayjs
|
|
107
|
+
|
|
108
|
+
### Error Handling
|
|
109
|
+
- Check error conditions at start of functions and return early
|
|
110
|
+
- Limit nested if statements
|
|
111
|
+
- Use multiline syntax with curly braces for all conditionals
|
|
112
|
+
|
|
113
|
+
### Testing
|
|
114
|
+
- Use bun test with expect for testing
|
|
115
|
+
|
|
116
|
+
### Logging
|
|
117
|
+
- Frontend: Use `console.info`, `console.debug`, `console.warn`, or `console.error` for permanent logs
|
|
118
|
+
- Backend: Use `logger.info/warn/error/debug` for permanent logs
|
|
119
|
+
- Use `console.log` only for debugging (to be removed)
|
|
120
|
+
|
|
121
|
+
### Development Practices
|
|
122
|
+
- Don't apologize for errors: fix them
|
|
123
|
+
- Prioritize modularity, DRY, performance, and security
|
|
124
|
+
- Focus on readability over performance
|
|
125
|
+
- Write complete, functional code without TODOs when possible
|
|
126
|
+
- Comments should describe purpose, not effect
|
|
127
|
+
|
|
128
|
+
## Package Reference
|
|
129
|
+
|
|
130
|
+
### @terreno/api
|
|
131
|
+
|
|
132
|
+
REST API framework providing:
|
|
133
|
+
|
|
134
|
+
- **modelRouter**: Auto-generates CRUD endpoints for Mongoose models
|
|
135
|
+
- **Permissions**: `IsAuthenticated`, `IsOwner`, `IsAdmin`, `IsAuthenticatedOrReadOnly`
|
|
136
|
+
- **Query Filters**: `OwnerQueryFilter` for filtering list queries by owner
|
|
137
|
+
- **setupServer**: Express server setup with auth, OpenAPI, and middleware
|
|
138
|
+
- **APIError**: Standardized error handling
|
|
139
|
+
- **logger**: Winston-based logging
|
|
140
|
+
|
|
141
|
+
Key imports:
|
|
142
|
+
```typescript
|
|
143
|
+
import {
|
|
144
|
+
modelRouter,
|
|
145
|
+
setupServer,
|
|
146
|
+
Permissions,
|
|
147
|
+
OwnerQueryFilter,
|
|
148
|
+
APIError,
|
|
149
|
+
logger,
|
|
150
|
+
asyncHandler,
|
|
151
|
+
authenticateMiddleware,
|
|
152
|
+
} from "@terreno/api";
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
#### modelRouter Usage
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import {modelRouter, modelRouterOptions, Permissions} from "@terreno/api";
|
|
159
|
+
|
|
160
|
+
const router = modelRouter(YourModel, {
|
|
161
|
+
permissions: {
|
|
162
|
+
list: [Permissions.IsAuthenticated],
|
|
163
|
+
create: [Permissions.IsAuthenticated],
|
|
164
|
+
read: [Permissions.IsOwner],
|
|
165
|
+
update: [Permissions.IsOwner],
|
|
166
|
+
delete: [], // Disabled
|
|
167
|
+
},
|
|
168
|
+
sort: "-created",
|
|
169
|
+
queryFields: ["_id", "type", "name"],
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
#### Custom Routes
|
|
174
|
+
|
|
175
|
+
For non-CRUD endpoints, use the OpenAPI builder:
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
import {asyncHandler, authenticateMiddleware, createOpenApiBuilder} from "@terreno/api";
|
|
179
|
+
|
|
180
|
+
router.get("/yourRoute/:id", [
|
|
181
|
+
authenticateMiddleware(),
|
|
182
|
+
createOpenApiBuilder(options)
|
|
183
|
+
.withTags(["yourTag"])
|
|
184
|
+
.withSummary("Brief summary")
|
|
185
|
+
.withPathParameter("id", {type: "string"})
|
|
186
|
+
.withResponse(200, {data: {type: "object"}})
|
|
187
|
+
.build(),
|
|
188
|
+
], asyncHandler(async (req, res) => {
|
|
189
|
+
return res.json({data: result});
|
|
190
|
+
}));
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
#### API Conventions
|
|
194
|
+
|
|
195
|
+
- Throw `APIError` with appropriate status codes: `throw new APIError({status: 400, title: "Message"})`
|
|
196
|
+
- Do not use `Model.findOne` - use `Model.findExactlyOne` or `Model.findOneOrThrow`
|
|
197
|
+
- Define statics/methods by direct assignment: `schema.methods = {bar() {}}`
|
|
198
|
+
- All model types live in `src/modelInterfaces.ts`
|
|
199
|
+
- In routes: `req.user` is `UserDocument | undefined`
|
|
200
|
+
- In @terreno/api callbacks: cast with `const user = u as unknown as UserDocument`
|
|
201
|
+
|
|
202
|
+
### @terreno/ui
|
|
203
|
+
|
|
204
|
+
React Native component library with 88+ components:
|
|
205
|
+
|
|
206
|
+
- **Layout**: Box, Page, SplitPage, Card
|
|
207
|
+
- **Forms**: TextField, SelectField, DateTimeField, CheckBox
|
|
208
|
+
- **Display**: Text, Heading, Badge, DataTable
|
|
209
|
+
- **Actions**: Button, IconButton, Link
|
|
210
|
+
- **Feedback**: Spinner, Modal, Toast
|
|
211
|
+
- **Theming**: TerrenoProvider, useTheme
|
|
212
|
+
|
|
213
|
+
Key imports:
|
|
214
|
+
```typescript
|
|
215
|
+
import {
|
|
216
|
+
Box,
|
|
217
|
+
Button,
|
|
218
|
+
Card,
|
|
219
|
+
Page,
|
|
220
|
+
Text,
|
|
221
|
+
TextField,
|
|
222
|
+
TerrenoProvider,
|
|
223
|
+
} from "@terreno/ui";
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
#### UI Component Examples
|
|
227
|
+
|
|
228
|
+
Layout with Box:
|
|
229
|
+
```typescript
|
|
230
|
+
<Box direction="row" padding={4} gap={2} alignItems="center">
|
|
231
|
+
<Text>Content</Text>
|
|
232
|
+
<Button text="Action" />
|
|
233
|
+
</Box>
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Buttons:
|
|
237
|
+
```typescript
|
|
238
|
+
<Button
|
|
239
|
+
text="Submit"
|
|
240
|
+
variant="primary" // 'primary' | 'secondary' | 'outline' | 'ghost'
|
|
241
|
+
onClick={handleSubmit}
|
|
242
|
+
loading={isLoading}
|
|
243
|
+
iconName="check"
|
|
244
|
+
/>
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Forms:
|
|
248
|
+
```typescript
|
|
249
|
+
<TextField
|
|
250
|
+
label="Email"
|
|
251
|
+
value={email}
|
|
252
|
+
onChangeText={setEmail}
|
|
253
|
+
error={emailError}
|
|
254
|
+
helperText="Enter a valid email"
|
|
255
|
+
/>
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Modals:
|
|
259
|
+
```typescript
|
|
260
|
+
<Modal
|
|
261
|
+
title="Confirm Action"
|
|
262
|
+
visible={isVisible}
|
|
263
|
+
primaryButtonText="Confirm"
|
|
264
|
+
secondaryButtonText="Cancel"
|
|
265
|
+
onDismiss={() => setIsVisible(false)}
|
|
266
|
+
onPrimaryAction={handleConfirm}
|
|
267
|
+
>
|
|
268
|
+
<Text>Are you sure?</Text>
|
|
269
|
+
</Modal>
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
#### UI Common Pitfalls
|
|
273
|
+
|
|
274
|
+
- Don't use inline styles when theme values are available
|
|
275
|
+
- Don't use raw `View`/`Text` when `Box`/@terreno/ui `Text` are available
|
|
276
|
+
- Don't forget loading and error states
|
|
277
|
+
- Don't use `style` prop when equivalent props exist (`padding`, `margin`)
|
|
278
|
+
- Never modify `openApiSdk.ts` manually
|
|
279
|
+
|
|
280
|
+
### @terreno/rtk
|
|
281
|
+
|
|
282
|
+
Redux Toolkit Query integration:
|
|
283
|
+
|
|
284
|
+
- **generateAuthSlice**: Creates auth reducer and middleware with JWT handling
|
|
285
|
+
- **emptyApi**: Base RTK Query API for code generation
|
|
286
|
+
- **Platform utilities**: Secure token storage (expo-secure-store for native, AsyncStorage for web)
|
|
287
|
+
|
|
288
|
+
Key imports:
|
|
289
|
+
```typescript
|
|
290
|
+
import {generateAuthSlice} from "@terreno/rtk";
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Always use generated SDK hooks - never use `axios` or `request` directly:
|
|
294
|
+
|
|
295
|
+
```typescript
|
|
296
|
+
// Correct
|
|
297
|
+
import {useGetYourRouteQuery} from "@/store/openApiSdk";
|
|
298
|
+
const {data, isLoading, error} = useGetYourRouteQuery({id: "value"});
|
|
299
|
+
|
|
300
|
+
// Wrong - don't use axios directly
|
|
301
|
+
// const result = await axios.get("/api/yourRoute/value");
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
## React Best Practices (Frontend Packages)
|
|
305
|
+
|
|
306
|
+
- Use functional components with `React.FC` type
|
|
307
|
+
- Import hooks directly: `import {useEffect, useMemo} from 'react'`
|
|
308
|
+
- Always provide return types for functions
|
|
309
|
+
- Add explanatory comment above each `useEffect`
|
|
310
|
+
- Wrap callbacks in `useCallback`
|
|
311
|
+
- Prefer const arrow functions
|
|
312
|
+
- Use inline styles over `StyleSheet.create`
|
|
313
|
+
- Use Luxon for date operations
|
|
314
|
+
- Place static content and interfaces at beginning of file
|
|
315
|
+
- Minimize `use client`, `useEffect`, and `setState`
|
|
316
|
+
- Always support React-Native Web
|
|
317
|
+
|
|
318
|
+
## CI/CD Workflows
|
|
319
|
+
|
|
320
|
+
### Required Secret Validation
|
|
321
|
+
|
|
322
|
+
GitHub Actions workflows that use secrets or environment variables must validate all required variables are set before using them. Add a validation step early in the job that fails fast with a clear error message listing any missing variables.
|
|
323
|
+
|
|
324
|
+
```yaml
|
|
325
|
+
- name: Validate required secrets
|
|
326
|
+
run: |
|
|
327
|
+
missing=()
|
|
328
|
+
if [ -z "$VAR_NAME" ]; then missing+=("VAR_NAME"); fi
|
|
329
|
+
if [ ${#missing[@]} -ne 0 ]; then
|
|
330
|
+
echo "::error::Missing required secrets: ${missing[*]}"
|
|
331
|
+
exit 1
|
|
332
|
+
fi
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
## Dependency Management
|
|
336
|
+
|
|
337
|
+
Uses [Bun Catalogs](https://bun.sh/docs/install/catalogs) - shared versions defined in root `package.json` under `catalog`. Reference with `catalog:` in workspace packages.
|