vsra 0.1.11

The vsr command-line interface for very_simple_rest
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
use crate::error::{Error, Result};
use clap::ValueEnum;
use colored::Colorize;
use dialoguer::{Select, theme::ColorfulTheme};
use std::fs::{File, create_dir_all};
use std::io::{IsTerminal, Write};
use std::path::Path;

const DEFAULT_DB_URL: &str = "sqlite:var/data/app.db?mode=rwc";
const DEFAULT_BIND_ADDR: &str = "127.0.0.1:8080";

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum StarterKind {
    Commented,
    Minimal,
}

impl StarterKind {
    fn label(self) -> &'static str {
        match self {
            Self::Commented => "Commented starter (Recommended)",
            Self::Minimal => "Minimal CRUD starter",
        }
    }

    fn description(self) -> &'static str {
        match self {
            Self::Commented => {
                "A starter `api.eon` with commented examples of current VSR features."
            }
            Self::Minimal => "A lean `api.eon` with one resource and the smallest runnable shape.",
        }
    }
}

pub fn create_project(
    name: &str,
    description: String,
    author: String,
    license: &str,
    output_dir: String,
    repository: Option<String>,
    starter: Option<StarterKind>,
) -> Result<()> {
    let project_dir = Path::new(&output_dir).join(name);
    if project_dir.exists() {
        return Err(Error::Config(format!(
            "Directory already exists: {}",
            project_dir.display()
        )));
    }

    create_dir_all(&project_dir)?;
    create_dir_all(project_dir.join("migrations"))?;
    create_dir_all(project_dir.join("var/data"))?;
    println!(
        "{} {}",
        "Created project directory:".green(),
        project_dir.display()
    );

    let starter = resolve_starter_kind(starter)?;
    let module_name = sanitize_module_name(name);

    write_file(
        &project_dir.join("api.eon"),
        &match starter {
            StarterKind::Commented => {
                commented_service_template(module_name.as_str(), name, description.as_str())
            }
            StarterKind::Minimal => minimal_service_template(module_name.as_str()),
        },
    )?;
    write_file(&project_dir.join(".env.example"), &env_example())?;
    write_file(
        &project_dir.join("README.md"),
        &readme_template(
            name,
            description.as_str(),
            author.as_str(),
            license,
            repository,
        ),
    )?;
    write_file(&project_dir.join(".gitignore"), gitignore_template())?;
    write_file(&project_dir.join("var/data/.gitkeep"), "")?;

    println!(
        "\n{} {}",
        "Project created successfully at:".green().bold(),
        project_dir.display()
    );
    println!("\nStarter kind: {}", starter.label());
    println!("\nTo get started:");
    println!("  cd {}", name);
    println!("  cp .env.example .env");
    println!("  vsr migrate generate --input api.eon --output migrations/0001_init.sql");
    println!("  vsr serve api.eon");

    Ok(())
}

fn resolve_starter_kind(starter: Option<StarterKind>) -> Result<StarterKind> {
    if let Some(starter) = starter {
        return Ok(starter);
    }

    if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
        return Ok(StarterKind::Commented);
    }

    let options = [StarterKind::Commented, StarterKind::Minimal];
    let labels = options
        .iter()
        .map(|starter| format!("{} - {}", starter.label(), starter.description()))
        .collect::<Vec<_>>();

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("Choose a VSR starter")
        .default(0)
        .items(&labels)
        .interact()
        .map_err(|error| Error::Config(format!("Failed to read init selection: {error}")))?;

    Ok(options[selection])
}

fn sanitize_module_name(name: &str) -> String {
    let mut module = String::new();
    let mut last_was_separator = false;

    for ch in name.chars() {
        if ch.is_ascii_alphanumeric() {
            if last_was_separator && !module.is_empty() {
                module.push('_');
            }
            last_was_separator = false;
            module.push(ch.to_ascii_lowercase());
        } else {
            last_was_separator = true;
        }
    }

    if module.is_empty() {
        "app".to_owned()
    } else if module
        .chars()
        .next()
        .map(|ch| ch.is_ascii_digit())
        .unwrap_or(false)
    {
        format!("app_{module}")
    } else {
        module
    }
}

fn write_file(path: &Path, content: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        create_dir_all(parent)?;
    }
    let mut file = File::create(path)?;
    file.write_all(content.as_bytes())?;
    println!("{} {}", "Created:".green(), path.display());
    Ok(())
}

fn env_example() -> String {
    format!(
        r#"# Copy this file to `.env` and adjust values for your environment.
DATABASE_URL={DEFAULT_DB_URL}
TURSO_ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
BIND_ADDR={DEFAULT_BIND_ADDR}

# Only required when you enable built-in auth or auth-managed routes.
JWT_SECRET=change-me-in-development
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=change-me
"#
    )
}

fn gitignore_template() -> &'static str {
    r#".env
target/
.vsr-build/
*.bundle/
var/data/*.db
var/data/*.sqlite
var/data/*.sqlite3
"#
}

fn readme_template(
    project_name: &str,
    description: &str,
    author: &str,
    license: &str,
    repository: Option<String>,
) -> String {
    let repository_line = repository
        .map(|value| format!("- Repository: {value}\n"))
        .unwrap_or_default();

    format!(
        r#"# {project_name}

{description}

## Project

- Author: {author}
- License: {license}
{repository_line}
## Files

- `api.eon`: VSR service contract
- `.env.example`: local environment template
- `migrations/`: generated SQL migrations

## First Run

```bash
cp .env.example .env
vsr migrate generate --input api.eon --output migrations/0001_init.sql
vsr serve api.eon
```

## Next Steps

- Edit `api.eon` to match your resources and policies
- Run `vsr docs --output docs/eon-reference.md` for a local reference snapshot
- Use `vsr build api.eon --release` when you want a standalone binary
"#
    )
}

fn minimal_service_template(module_name: &str) -> String {
    format!(
        r#"module: "{module_name}"

resources: [
    {{
        name: "Post"
        api_name: "posts"
        fields: [
            {{ name: "id", type: I64, id: true }}
            {{ name: "title", type: String }}
            {{ name: "body", type: String, nullable: true }}
            {{ name: "created_at", type: DateTime }}
            {{ name: "updated_at", type: DateTime }}
        ]
    }}
]
"#
    )
}

fn commented_service_template(module_name: &str, project_name: &str, description: &str) -> String {
    format!(
        r#"// {project_name}
// {description}
//
// This starter is intentionally comment-heavy so `vsr init` gives you a current
// `.eon` contract to edit directly instead of copying a fragile example app.
//
// Common commands:
//   vsr serve api.eon
//   vsr migrate generate --input api.eon --output migrations/0001_init.sql
//   vsr build api.eon --release
//   vsr docs --output docs/eon-reference.md

module: "{module_name}"

// Service-level defaults. These are optional.
database: {{
    engine: {{
        kind: TursoLocal
        path: "var/data/app.db"
        encryption_key: {{ env_or_file: "TURSO_ENCRYPTION_KEY" }}
    }}
}}

// Optional runtime knobs:
// logging: {{
//     filter_env: "RUST_LOG"
//     default_filter: "info"
//     timestamp: Millis
// }}
// runtime: {{
//     compression: {{
//         enabled: true
//         static_precompressed: false
//     }}
// }}
// tls: {{
//     cert_path: "certs/dev-cert.pem"
//     key_path: "certs/dev-key.pem"
// }}
// static: {{
//     mounts: [
//         {{
//             mount: "/"
//             dir: "public"
//             mode: Spa
//             index_file: "index.html"
//             fallback_file: "index.html"
//             cache: NoStore
//         }}
//     ]
// }}
// security: {{
//     cors: {{
//         origins: ["http://localhost:3000"]
//     }}
//     // Uncomment when you want built-in auth and account flows.
//     // auth: {{
//     //     issuer: "example_api"
//     //     audience: "example_clients"
//     //     access_token_ttl_seconds: 3600
//     //     session_cookie: {{
//     //         secure: false
//     //     }}
//     // }}
// }}

// Optional reusable pieces:
enums: {{
    PostStatus: ["draft", "review", "published"]
}}
// mixins: {{
//     Timestamps: {{
//         fields: {{
//             created_at: {{ type: DateTime, generated: CreatedAt }}
//             updated_at: {{ type: DateTime, generated: UpdatedAt }}
//         }}
//     }}
// }}

resources: [
    {{
        name: "Post"
        table: "post"
        api_name: "posts"

        // Resource-level access rules.
        roles: {{
            update: "editor"
            delete: "editor"
        }}

        // Optional list tuning.
        list: {{
            default_limit: 20
            max_limit: 100
        }}

        // Optional API shape controls.
        // api: {{
        //     default_context: "view"
        //     fields: {{
        //         title: {{ from: "title_text" }}
        //         permalink: {{ template: "/posts/{{slug}}" }}
        //     }}
        //     contexts: {{
        //         view: ["id", "title", "slug", "status", "created_at", "permalink"]
        //         edit: ["id", "title", "slug", "status", "body", "meta", "created_at", "updated_at"]
        //     }}
        // }}

        // Optional declarative actions.
        // actions: [
        //     {{
        //         name: "publish"
        //         behavior: {{
        //             kind: "UpdateFields"
        //             set: {{
        //                 status: "published"
        //             }}
        //         }}
        //     }}
        //     {{
        //         name: "rename"
        //         behavior: {{
        //             kind: "UpdateFields"
        //             set: {{
        //                 title: {{ input: "newTitle" }}
        //                 slug: {{ input: "newSlug" }}
        //             }}
        //         }}
        //     }}
        //     {{
        //         name: "purge"
        //         behavior: {{
        //             kind: "DeleteResource"
        //         }}
        //     }}
        // ]

        fields: [
            {{ name: "id", type: I64, id: true }}

            // Scalars, validation, uniqueness, and transforms.
            {{ name: "title", type: String, garde: {{ length: {{ min: 3, max: 120, mode: Chars }} }} }}
            {{ name: "slug", type: String, unique: true, transforms: [Slugify] }}
            {{ name: "status", type: PostStatus }}

            // Typed object, list, and JSON support.
            {{
                name: "body"
                type: Object
                fields: {{
                    raw: {{ type: String, transforms: [CollapseWhitespace] }}
                    rendered: String
                }}
            }}
            {{ name: "tags", type: List, items: String, nullable: true }}
            {{ name: "meta", type: JsonObject, nullable: true }}

            // Generated timestamps are inferred automatically from these field names.
            {{ name: "created_at", type: DateTime }}
            {{ name: "updated_at", type: DateTime }}

            // Example relation:
            // {{ name: "author_id", type: I64, relation: {{ references: "user.id" }} }}
        ]

        indexes: [
            {{ fields: ["status", "created_at"] }}
        ]
    }}

    // Add more resources as needed. Many-to-many uses an explicit join resource today.
    // {{
    //     name: "Tag"
    //     api_name: "tags"
    //     fields: [
    //         {{ name: "id", type: I64, id: true }}
    //         {{ name: "name", type: String, unique: true }}
    //     ]
    // }}
    // {{
    //     name: "PostTag"
    //     table: "post_tag"
    //     fields: [
    //         {{ name: "post_id", type: I64, relation: {{ references: "post.id" }} }}
    //         {{ name: "tag_id", type: I64, relation: {{ references: "tag.id" }} }}
    //     ]
    // }}
]
"#
    )
}

#[cfg(test)]
mod tests {
    use super::{
        StarterKind, commented_service_template, create_project, env_example, sanitize_module_name,
    };
    use rest_macro_core::compiler;
    use std::fs;
    use std::path::PathBuf;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_root(prefix: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time should advance")
            .as_nanos();
        std::env::temp_dir().join(format!("vsr_init_{prefix}_{nanos}"))
    }

    #[test]
    fn sanitize_module_name_normalizes_project_names() {
        assert_eq!(sanitize_module_name("My API"), "my_api");
        assert_eq!(sanitize_module_name("123 project"), "app_123_project");
        assert_eq!(sanitize_module_name("___"), "app");
    }

    #[test]
    fn create_project_writes_local_comment_config_starter() {
        let root = temp_root("commented");
        fs::create_dir_all(&root).expect("temp root should exist");

        create_project(
            "demo-app",
            "Example API".to_owned(),
            "Tester".to_owned(),
            "MIT",
            root.display().to_string(),
            None,
            Some(StarterKind::Commented),
        )
        .expect("project should generate");

        let project_root = root.join("demo-app");
        let api_eon =
            fs::read_to_string(project_root.join("api.eon")).expect("api.eon should be readable");
        let readme =
            fs::read_to_string(project_root.join("README.md")).expect("README should be readable");
        compiler::load_service_from_path(&project_root.join("api.eon"))
            .expect("commented starter should parse as .eon");

        assert!(api_eon.contains(r#"module: "demo_app""#));
        assert!(api_eon.contains(r#"kind: "DeleteResource""#));
        assert!(api_eon.contains(r#"kind: TursoLocal"#));
        assert!(api_eon.contains(r#"encryption_key: { env_or_file: "TURSO_ENCRYPTION_KEY" }"#));
        assert!(api_eon.contains(r#"garde: { length: { min: 3, max: 120, mode: Chars } }"#));
        assert!(!api_eon.contains("validate:"));
        assert!(api_eon.contains("// Optional declarative actions."));
        assert!(readme.contains("vsr serve api.eon"));
        assert!(project_root.join(".env.example").exists());
        assert!(project_root.join(".gitignore").exists());
        assert!(project_root.join("migrations").is_dir());
        assert!(project_root.join("var/data").is_dir());

        fs::remove_dir_all(root).expect("temp root should clean up");
    }

    #[test]
    fn commented_template_is_comment_rich() {
        let template = commented_service_template("sample_app", "Sample", "Sample API");
        assert!(template.contains("// Service-level defaults."));
        assert!(template.contains("// Optional declarative actions."));
        assert!(template.contains("// Typed object, list, and JSON support."));
    }

    #[test]
    fn env_example_uses_dotenv_comments() {
        let template = env_example();
        assert!(template.starts_with("# Copy this file"));
        assert!(template.contains("DATABASE_URL=sqlite:var/data/app.db?mode=rwc"));
        assert!(!template.contains("// Only required"));
    }
}