create-guren-app 1.0.0 → 1.2.0

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.
Files changed (27) hide show
  1. package/dist/cli.js +27 -5
  2. package/package.json +1 -1
  3. package/templates/api-only/.env.example +3 -0
  4. package/templates/api-only/config/database.ts +13 -1
  5. package/templates/api-only/package.json +1 -0
  6. package/templates/api-only/tsconfig.json +1 -1
  7. package/templates/default/.env.example +3 -0
  8. package/templates/default/.guren/api-client.gen.ts +1 -1
  9. package/templates/default/app/Http/Controllers/HomeController.ts +1 -1
  10. package/templates/default/config/database.ts +13 -1
  11. package/templates/default/package.json +1 -0
  12. package/templates/default/resources/js/app.tsx +1 -1
  13. package/templates/default/tsconfig.json +1 -1
  14. package/templates/default-ssr/resources/js/ssr.tsx +1 -1
  15. package/templates/default/.claude/agents/code-review.md +0 -130
  16. package/templates/default/.claude/agents/test-writer.md +0 -192
  17. package/templates/default/.claude/rules/controllers-http.md +0 -95
  18. package/templates/default/.claude/rules/orm-models.md +0 -118
  19. package/templates/default/.claude/rules/routes-codegen.md +0 -96
  20. package/templates/default/.claude/rules/testing.md +0 -93
  21. package/templates/default/.claude/skills/db-manage/SKILL.md +0 -97
  22. package/templates/default/.claude/skills/dev-workflow/SKILL.md +0 -74
  23. package/templates/default/.claude/skills/feature/SKILL.md +0 -195
  24. package/templates/default/.claude/skills/guren-api/SKILL.md +0 -431
  25. package/templates/default/.claude/skills/scaffold/SKILL.md +0 -83
  26. package/templates/default/.mcp.json +0 -8
  27. package/templates/default/CLAUDE.md +0 -173
package/dist/cli.js CHANGED
@@ -1618,7 +1618,6 @@ function toPackageName(value) {
1618
1618
  var APP_BLUEPRINTS = ["default", "api", "blog", "worker"];
1619
1619
  var DATABASE_DRIVERS = ["sqlite", "postgres", "mysql"];
1620
1620
  var DEFAULT_TRANSFORM_FILES = [
1621
- "CLAUDE.md",
1622
1621
  "README.md",
1623
1622
  "package.json",
1624
1623
  "public/index.html",
@@ -1848,10 +1847,22 @@ export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDa
1848
1847
  }
1849
1848
  return `import { createSqliteDatabase } from '@guren/orm'
1850
1849
 
1850
+ // \`bun test\` sets NODE_ENV=test automatically, so the test suite reads and
1851
+ // writes a separate SQLite file and never touches the development database \u2014
1852
+ // this takes priority over DATABASE_URL, which .env sets unconditionally.
1853
+ // Override the test DB path itself with TEST_DATABASE_URL if needed (e.g. to
1854
+ // shard parallel CI runs); DATABASE_URL is still authoritative outside tests.
1855
+ function resolveDatabaseFilename(): string {
1856
+ if (process.env.NODE_ENV === 'test') {
1857
+ return process.env.TEST_DATABASE_URL ?? './data/guren.test.db'
1858
+ }
1859
+ return process.env.DATABASE_URL ?? '${url}'
1860
+ }
1861
+
1851
1862
  const database = createSqliteDatabase({
1852
1863
  migrationsFolder: new URL('../db/migrations', import.meta.url),
1853
1864
  seedersFolder: new URL('../db/seeders', import.meta.url),
1854
- filename: () => process.env.DATABASE_URL ?? '${url}',
1865
+ filename: resolveDatabaseFilename,
1855
1866
  })
1856
1867
 
1857
1868
  export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database
@@ -2123,10 +2134,10 @@ async function updateSsrPackageJson(destination) {
2123
2134
  await writeFile2(packageJsonPath, `${JSON.stringify(pkg, null, 2)}
2124
2135
  `, "utf8");
2125
2136
  }
2126
- async function installAuthBlueprint(targetDir) {
2137
+ async function runAppCli(targetDir, cliArgs) {
2127
2138
  const { spawnSync } = await import("child_process");
2128
2139
  const cliBin = resolve(targetDir, "node_modules/@guren/cli/dist/bin.js");
2129
- const result = spawnSync("bun", [cliBin, "add", "auth", "--force"], {
2140
+ const result = spawnSync("bun", [cliBin, ...cliArgs], {
2130
2141
  cwd: targetDir,
2131
2142
  stdio: "inherit"
2132
2143
  });
@@ -2265,11 +2276,22 @@ var command = defineCommand({
2265
2276
  if (shouldInstall) {
2266
2277
  installed = await installDependencies(targetDir);
2267
2278
  }
2279
+ let harnessInstalled = false;
2280
+ if (installed) {
2281
+ consola.start("Setting up AI agent harness...");
2282
+ harnessInstalled = await runAppCli(targetDir, ["agent:init"]);
2283
+ if (harnessInstalled) {
2284
+ consola.success("AI agent harness installed (CLAUDE.md, .claude/, .mcp.json)");
2285
+ }
2286
+ }
2287
+ if (!harnessInstalled) {
2288
+ consola.warn("AI agent harness was not installed automatically. Run `bunx guren agent:init` inside the app after installing dependencies.");
2289
+ }
2268
2290
  let authInstalled = false;
2269
2291
  if (includeAuth) {
2270
2292
  if (installed) {
2271
2293
  consola.start("Adding authentication scaffolding...");
2272
- authInstalled = await installAuthBlueprint(targetDir);
2294
+ authInstalled = await runAppCli(targetDir, ["add", "auth", "--force"]);
2273
2295
  if (authInstalled) {
2274
2296
  consola.success("Authentication scaffolding added");
2275
2297
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-guren-app",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -7,6 +7,9 @@ APP_URL=http://localhost:3333
7
7
  PORT=3333
8
8
  HOST=0.0.0.0
9
9
 
10
+ # bun test automatically sets NODE_ENV=test, which points the app at
11
+ # ./data/guren.test.db instead — this line is only used outside tests.
12
+ # Override the test DB path itself with TEST_DATABASE_URL if you need to.
10
13
  DATABASE_URL=./data/guren.db
11
14
 
12
15
  REDIS_URL=
@@ -1,9 +1,21 @@
1
1
  import { createSqliteDatabase } from '@guren/orm'
2
2
 
3
+ // `bun test` sets NODE_ENV=test automatically, so the test suite reads and
4
+ // writes a separate SQLite file and never touches the development database —
5
+ // this takes priority over DATABASE_URL, which .env sets unconditionally.
6
+ // Override the test DB path itself with TEST_DATABASE_URL if needed (e.g. to
7
+ // shard parallel CI runs); DATABASE_URL is still authoritative outside tests.
8
+ function resolveDatabaseFilename(): string {
9
+ if (process.env.NODE_ENV === 'test') {
10
+ return process.env.TEST_DATABASE_URL ?? './data/guren.test.db'
11
+ }
12
+ return process.env.DATABASE_URL ?? './data/guren.db'
13
+ }
14
+
3
15
  const database = createSqliteDatabase({
4
16
  migrationsFolder: new URL('../db/migrations', import.meta.url),
5
17
  seedersFolder: new URL('../db/seeders', import.meta.url),
6
- filename: () => process.env.DATABASE_URL ?? './data/guren.db',
18
+ filename: resolveDatabaseFilename,
7
19
  })
8
20
 
9
21
  export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database
@@ -23,6 +23,7 @@
23
23
  "drizzle-orm": "1.0.0-rc.4"
24
24
  },
25
25
  "devDependencies": {
26
+ "@guren/testing": "^1.0.0",
26
27
  "bun-types": "^1.3.1",
27
28
  "drizzle-kit": "1.0.0-rc.4",
28
29
  "mysql2": "^3.11.3",
@@ -12,7 +12,7 @@
12
12
  "types": ["bun-types"],
13
13
  "baseUrl": ".",
14
14
  "paths": {
15
- "@/*": ["./app/*"]
15
+ "@/*": ["./*"]
16
16
  }
17
17
  },
18
18
  "include": ["src/**/*", "app/**/*", "routes/**/*", "config/**/*", "db/**/*", "bin/**/*"],
@@ -7,6 +7,9 @@ APP_URL=http://localhost:3333
7
7
  PORT=3333
8
8
  HOST=0.0.0.0
9
9
 
10
+ # bun test automatically sets NODE_ENV=test, which points the app at
11
+ # ./data/guren.test.db instead — this line is only used outside tests.
12
+ # Override the test DB path itself with TEST_DATABASE_URL if you need to.
10
13
  DATABASE_URL=./data/guren.db
11
14
 
12
15
  REDIS_URL=
@@ -28,7 +28,7 @@ export type ApiRequestOptions<T extends ApiRouteName> =
28
28
  *
29
29
  * @example
30
30
  * ```typescript
31
- * import type { ApiRoutes } from '../.guren/api-client.gen'
31
+ * import type { ApiRoutes } from '@/.guren/api-client.gen'
32
32
  *
33
33
  * const client = createApiClient<ApiRoutes>({ baseUrl: 'http://localhost:3000' })
34
34
  * const posts = await client.request('posts.index')
@@ -1,5 +1,5 @@
1
1
  import { Controller } from '@guren/core'
2
- import { pages } from '../../../.guren/pages.gen.js'
2
+ import { pages } from '@/.guren/pages.gen'
3
3
 
4
4
  export default class HomeController extends Controller {
5
5
  async index(): Promise<Response> {
@@ -1,9 +1,21 @@
1
1
  import { createSqliteDatabase } from '@guren/orm'
2
2
 
3
+ // `bun test` sets NODE_ENV=test automatically, so the test suite reads and
4
+ // writes a separate SQLite file and never touches the development database —
5
+ // this takes priority over DATABASE_URL, which .env sets unconditionally.
6
+ // Override the test DB path itself with TEST_DATABASE_URL if needed (e.g. to
7
+ // shard parallel CI runs); DATABASE_URL is still authoritative outside tests.
8
+ function resolveDatabaseFilename(): string {
9
+ if (process.env.NODE_ENV === 'test') {
10
+ return process.env.TEST_DATABASE_URL ?? './data/guren.test.db'
11
+ }
12
+ return process.env.DATABASE_URL ?? './data/guren.db'
13
+ }
14
+
3
15
  const database = createSqliteDatabase({
4
16
  migrationsFolder: new URL('../db/migrations', import.meta.url),
5
17
  seedersFolder: new URL('../db/seeders', import.meta.url),
6
- filename: () => process.env.DATABASE_URL ?? './data/guren.db',
18
+ filename: resolveDatabaseFilename,
7
19
  })
8
20
 
9
21
  export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database
@@ -28,6 +28,7 @@
28
28
  "zod": "^4.4.3"
29
29
  },
30
30
  "devDependencies": {
31
+ "@guren/testing": "^1.0.0",
31
32
  "@types/react": "^19.0.0",
32
33
  "@types/react-dom": "^19.0.0",
33
34
  "bun-types": "^1.3.1",
@@ -1,5 +1,5 @@
1
1
  import '../css/app.css'
2
- import { pageManifest } from '../../.guren/pages.gen.ts'
2
+ import { pageManifest } from '@/.guren/pages.gen'
3
3
 
4
4
  let pages: Record<string, () => Promise<unknown>> | undefined
5
5
 
@@ -13,7 +13,7 @@
13
13
  "baseUrl": ".",
14
14
  "paths": {
15
15
  "@/*": [
16
- "./app/*"
16
+ "./*"
17
17
  ]
18
18
  },
19
19
  "types": [
@@ -1,7 +1,7 @@
1
1
  import type { Page } from '@inertiajs/core'
2
2
  import { renderInertiaServer } from '@guren/inertia-client'
3
3
  import type { InertiaSsrContext, InertiaSsrResult } from '@guren/core'
4
- import { pageManifest } from '../../.guren/pages.gen.ts'
4
+ import { pageManifest } from '@/.guren/pages.gen'
5
5
 
6
6
  let pages: Record<string, () => Promise<unknown>> | undefined
7
7
 
@@ -1,130 +0,0 @@
1
- ---
2
- name: code-review
3
- description: Expert code reviewer for Guren applications. Use proactively after code changes to review quality, patterns, security, and best practices. Invoked when user says "review", "check my code", or asks for feedback.
4
- tools: Read, Grep, Glob, Bash
5
- model: sonnet
6
- ---
7
-
8
- # Code Review Agent
9
-
10
- You are an expert code reviewer for a Guren framework application, a Laravel-inspired TypeScript fullstack framework running on Bun.
11
-
12
- ## Your Mission
13
-
14
- Review code changes and provide constructive, actionable feedback.
15
-
16
- ## Review Process
17
-
18
- 1. **Get changes to review**
19
- ```bash
20
- git diff --cached # Staged changes
21
- git diff # Unstaged changes
22
- git diff main...HEAD # All changes vs main
23
- ```
24
-
25
- 2. **Analyze against project standards**
26
- - Read `.claude/rules/coding-standards.md`
27
- - Check patterns in `CLAUDE.md`
28
-
29
- 3. **Run integrity check**
30
- ```bash
31
- bunx guren check --json
32
- ```
33
- This validates route↔controller↔page consistency, missing tests, and generated manifests.
34
-
35
- 4. **Review systematically**
36
-
37
- ## Review Checklist
38
-
39
- ### Code Quality
40
- - [ ] TypeScript strict mode compliance
41
- - [ ] ESM imports only (no CommonJS)
42
- - [ ] Proper async/await error handling
43
- - [ ] No console.log in production code
44
- - [ ] DRY - no unnecessary duplication
45
- - [ ] Single responsibility principle
46
-
47
- ### Guren Patterns
48
- - [ ] Controllers extend `Controller` base class
49
- - [ ] Models use `Model<T>` pattern
50
- - [ ] Routes follow DSL conventions
51
- - [ ] Middleware uses `defineMiddleware`
52
-
53
- ### Events & Jobs
54
- - [ ] Events registered in `EventServiceProvider`
55
- - [ ] Job classes implement `handle()` method
56
- - [ ] Listeners are properly bound to events
57
- - [ ] Events extend base `Event` class
58
-
59
- ### Authorization
60
- - [ ] Gate/Policy used for resource authorization (not inline checks)
61
- - [ ] Authorization middleware applied to protected routes
62
- - [ ] Policy methods match controller actions
63
-
64
- ### Validation
65
- - [ ] Input validated via `validateBody/validateQuery/validateParams`, `FormRequest`, or `Validator`
66
- - [ ] Prefer `validateBody/Query/Params` with Zod schemas over manual `safeParse` + error handling
67
- - [ ] `findOrFail` used instead of `find` + null check where appropriate
68
- - [ ] `userOrFail()` used instead of `user()` + null check where appropriate
69
- - [ ] Validation rules are appropriate for data types
70
- - [ ] Custom error messages provided where needed
71
-
72
- ### Cache
73
- - [ ] Cache keys follow a consistent naming convention (e.g., `entity:id:field`)
74
- - [ ] Cache TTL is appropriate for the data type
75
- - [ ] Cache invalidation on data mutation
76
-
77
- ### Mail
78
- - [ ] Mailable classes extend `Mail` base class
79
- - [ ] Mail content is properly structured
80
- - [ ] Queue used for sending (not blocking request)
81
-
82
- ### Container & Providers
83
- - [ ] `register()` only binds services (no boot logic)
84
- - [ ] `boot()` for setup that depends on other services
85
- - [ ] Providers registered in app configuration
86
-
87
- ### Security
88
- - [ ] Input validation present
89
- - [ ] No SQL injection risks
90
- - [ ] No hardcoded secrets
91
- - [ ] Authentication checks where needed
92
- - [ ] CSRF protection on state-changing routes
93
- - [ ] Rate limiting on public endpoints
94
-
95
- ### Testing
96
- - [ ] Tests added for new functionality
97
- - [ ] Edge cases covered
98
- - [ ] Test names are descriptive
99
- - [ ] Event/job/mail fakes used where appropriate
100
-
101
- ## Output Format
102
-
103
- ```
104
- ## Code Review Summary
105
-
106
- **Files:** 3 changed (+45/-12 lines)
107
- **Risk Level:** Low/Medium/High
108
-
109
- ### Strengths
110
- - Point 1
111
- - Point 2
112
-
113
- ### Suggestions
114
- - file.ts:23 - Consider adding validation
115
- - helper.ts:45 - Could extract to utility
116
-
117
- ### Issues (Must Fix)
118
- - query.ts:12 - Potential SQL injection
119
- - auth.ts:8 - Missing authentication check
120
-
121
- ### Security: No critical issues
122
- ### Tests: Adequate coverage
123
- ```
124
-
125
- ## Be Constructive
126
-
127
- - Explain **why** something is an issue
128
- - Suggest **how** to fix it
129
- - Praise good patterns you see
130
- - Prioritize feedback by importance
@@ -1,192 +0,0 @@
1
- ---
2
- name: test-writer
3
- description: Generate comprehensive tests for Guren application code. Creates unit tests, controller tests, model tests, event tests, job tests, mail tests, and notification tests following project patterns. Use when user says "write tests", "add tests", "test this", or wants to improve test coverage.
4
- tools: Read, Grep, Glob, Write, Edit, Bash
5
- model: sonnet
6
- ---
7
-
8
- # Test Writer Agent
9
-
10
- You are a testing expert for a Guren framework application, a Laravel-inspired TypeScript fullstack framework running on Bun.
11
-
12
- ## Your Mission
13
-
14
- Generate comprehensive, well-structured tests for existing code.
15
-
16
- ## Test Strategy
17
-
18
- 1. **Analyze the code to test**
19
- - Read the source file
20
- - Understand function signatures
21
- - Identify dependencies
22
- - Find edge cases
23
-
24
- 2. **Determine test type**
25
- - Unit test: isolated function/class
26
- - Controller test: HTTP endpoints
27
- - Model test: database operations
28
- - Event test: event dispatching
29
- - Job test: queue processing
30
- - Mail test: mailable output
31
- - Integration test: multiple components
32
-
33
- 3. **Write tests following project patterns**
34
-
35
- ## Test Patterns
36
-
37
- ### Unit Test (Bun)
38
- ```typescript
39
- import { describe, test, expect, beforeEach } from 'bun:test'
40
-
41
- describe('ClassName', () => {
42
- describe('methodName', () => {
43
- test('should handle normal case', () => {
44
- const input = 'test'
45
- const result = method(input)
46
- expect(result).toBe('expected')
47
- })
48
-
49
- test('should handle edge case', () => {
50
- expect(() => method(null)).toThrow()
51
- })
52
- })
53
- })
54
- ```
55
-
56
- ### Controller Test
57
- ```typescript
58
- import { describe, test, beforeAll } from 'bun:test'
59
- import { TestApp } from '@guren/testing'
60
-
61
- describe('PostController', () => {
62
- let app: TestApp
63
-
64
- beforeAll(async () => {
65
- app = await TestApp.create()
66
- })
67
-
68
- test('GET /posts returns list', async () => {
69
- await app.get('/posts').assertOk()
70
- })
71
-
72
- test('POST /posts creates new post', async () => {
73
- await app.post('/posts', {
74
- title: 'Test',
75
- content: 'Content'
76
- }).assertStatus(201)
77
- })
78
- })
79
- ```
80
-
81
- ### Model Test
82
- ```typescript
83
- import { describe, test, expect, beforeEach } from 'bun:test'
84
- import { ModelNotFoundException } from '@guren/orm'
85
-
86
- describe('Post Model', () => {
87
- beforeEach(async () => {
88
- await db.delete(posts)
89
- })
90
-
91
- test('create returns new record', async () => {
92
- const post = await Post.create({ title: 'Test' })
93
- expect(post.id).toBeDefined()
94
- })
95
-
96
- test('findOrFail throws for non-existent', async () => {
97
- expect(() => Post.findOrFail(99999)).toThrow(ModelNotFoundException)
98
- })
99
- })
100
- ```
101
-
102
- ### Event Test
103
- ```typescript
104
- import { describe, test, expect, beforeEach } from 'bun:test'
105
- import { fakeEvents } from '@guren/testing'
106
-
107
- describe('UserRegistered Event', () => {
108
- let events: ReturnType<typeof fakeEvents>
109
-
110
- beforeEach(() => {
111
- events = fakeEvents()
112
- })
113
-
114
- test('should dispatch UserRegistered on registration', async () => {
115
- await registerUser({ email: 'test@example.com' })
116
- events.assertDispatched('UserRegistered')
117
- })
118
- })
119
- ```
120
-
121
- ### Job Test
122
- ```typescript
123
- import { describe, test, expect, beforeEach } from 'bun:test'
124
- import { fakeQueue } from '@guren/testing'
125
-
126
- describe('SendWelcomeEmailJob', () => {
127
- let queue: ReturnType<typeof fakeQueue>
128
-
129
- beforeEach(() => {
130
- queue = fakeQueue()
131
- })
132
-
133
- test('should dispatch job on user creation', async () => {
134
- await createUser({ email: 'test@example.com' })
135
- queue.assertPushed('SendWelcomeEmailJob')
136
- })
137
- })
138
- ```
139
-
140
- ### Mail Test
141
- ```typescript
142
- import { describe, test, expect, beforeEach } from 'bun:test'
143
- import { fakeMail } from '@guren/testing'
144
-
145
- describe('WelcomeMail', () => {
146
- let mail: ReturnType<typeof fakeMail>
147
-
148
- beforeEach(() => {
149
- mail = fakeMail()
150
- })
151
-
152
- test('should send welcome email', async () => {
153
- await sendWelcomeEmail('user@example.com')
154
- mail.assertSent('WelcomeMail')
155
- })
156
- })
157
- ```
158
-
159
- ## Test File Locations
160
-
161
- ```
162
- Source Test
163
- ------ ----
164
- app/Http/Controllers/PostController.ts -> tests/controllers/PostController.test.ts
165
- app/Models/Post.ts -> tests/models/Post.test.ts
166
- app/Jobs/SendEmailJob.ts -> tests/jobs/SendEmailJob.test.ts
167
- app/Events/UserRegistered.ts -> tests/events/UserRegistered.test.ts
168
- ```
169
-
170
- ## Coverage Guidelines
171
-
172
- For each function, include tests for:
173
- 1. **Happy path** - Normal expected behavior
174
- 2. **Edge cases** - Empty, null, boundaries
175
- 3. **Error cases** - Invalid input, exceptions
176
- 4. **Async** - Promise resolution/rejection
177
-
178
- ## After Writing Tests
179
-
180
- 1. Run the tests:
181
- ```bash
182
- bun test tests/path/to/file.test.ts
183
- ```
184
-
185
- 2. Verify they pass — if not, fix the test code
186
-
187
- 3. Run full suite to ensure no regressions:
188
- ```bash
189
- bun run test
190
- ```
191
-
192
- 4. Suggest additional test cases if coverage seems low
@@ -1,95 +0,0 @@
1
- ---
2
- description: Guren controllers — validation signatures, 422 shape, Inertia pages, auth helpers, resources
3
- globs:
4
- - "app/Http/**"
5
- ---
6
-
7
- # Controllers & HTTP (@guren/core)
8
-
9
- Controllers extend `Controller` and expose one async method per route action.
10
-
11
- ## Validation — exact signatures
12
-
13
- Any Zod-like schema (anything with `safeParse`) is accepted:
14
-
15
- ```typescript
16
- protected async validateBody<T>(schema: ZodLikeSchema<T>): Promise<T> // request body
17
- protected validateQuery<T>(schema: ZodLikeSchema<T>): T // query string
18
- protected validateParams<T>(schema: ZodLikeSchema<T>): T // route params
19
- ```
20
-
21
- All throw `ValidationException` on failure, rendered as **HTTP 422** with body:
22
-
23
- ```json
24
- { "message": "The given data was invalid.", "errors": { "field": ["msg1", "msg2"] } }
25
- ```
26
-
27
- Non-throwing variants return a discriminated union — note errors flatten to
28
- **one string per field** here (`Record<string, string>`, not `string[]`):
29
-
30
- ```typescript
31
- protected async validateBodySafe<T>(schema): Promise<SafeValidationResult<T>>
32
- protected validateQuerySafe<T>(schema): SafeValidationResult<T>
33
- protected validateParamsSafe<T>(schema): SafeValidationResult<T>
34
- // SafeValidationResult<T> = { success: true; data: T } | { success: false; errors: Record<string, string> }
35
- ```
36
-
37
- Business-logic errors: `throw ValidationException.withMessages({ email: 'Already registered' })`
38
- (values may be `string` or `string[]`).
39
-
40
- ## Inertia responses
41
-
42
- ```typescript
43
- import { pages } from '@/.guren/pages.gen'
44
- return this.inertia(pages.posts.Show, { post }) // props compile-checked via PagePropsMap
45
- return this.inertia('posts/Show', { post }) // string overload, untyped props
46
- ```
47
-
48
- Page prop types come from each page component's `interface Props`, extracted by
49
- `bunx guren codegen` into `PagePropsMap`. If props don't type-check, re-run codegen.
50
- Optional third arg: `InertiaResponseOptions` (e.g. `{ status: 422 }`).
51
-
52
- ## Route model binding
53
-
54
- ```typescript
55
- // routes: router.get('/posts/:id', { bind: { id: Post }, name: 'posts.show' }, [PostController, 'show'])
56
- async show() {
57
- const post = this.model(Post) // typed record, already resolved via findOrFail (404 on miss)
58
- }
59
- ```
60
-
61
- ## Auth helpers
62
-
63
- `this.auth` (requires `AuthServiceProvider`) exposes:
64
- `check(): Promise<boolean>` · `guest(): Promise<boolean>` · `user<T>(): Promise<T | null>` ·
65
- `userOrFail<T>(): Promise<T>` (throws → 401) · `id(): Promise<unknown>` ·
66
- `login(user, remember?)` · `attempt(credentials, remember?): Promise<boolean>` · `logout()`
67
-
68
- Authorization (policies/gates):
69
- `await this.authorize('update', [Post, post])` (throws 403) ·
70
- `await this.can('update', [Post, post]): Promise<boolean>` ·
71
- API tokens: `this.apiToken()` → `{ userId, abilities }` or throws 401.
72
-
73
- ## Response helpers
74
-
75
- - `this.json(data, init?)` / `this.text(body, init?)`
76
- - `this.redirect(url, { status?, headers? })` — defaults 302 for GET, **303 for non-GET** (correct for Inertia form posts)
77
- - `await this.files('avatar')` → `File[]` (uploaded files, empties filtered)
78
-
79
- ## API Resources (app/Http/Resources)
80
-
81
- ```typescript
82
- import { Resource } from '@guren/core'
83
-
84
- export class PostResource extends Resource<PostRecord> {
85
- toArray() { // abstract — must implement; typed toArray is exported as Data.Post by codegen
86
- return { id: this.resource.id, title: this.resource.title }
87
- }
88
- }
89
- new PostResource(post).toJSON() // toArray() + additional() data
90
- PostResource.collection(posts) // ResourceData[]
91
- new PostResource(post).additional({ meta: 1 })
92
- this.when(cond, value) // conditional field inside toArray()
93
- ```
94
-
95
- `JsonResource<T>` is a no-transform passthrough (`toArray()` returns `{ ...resource }`).