appstruct-codegen 0.2.0

Deterministic Rust, SQL, OpenAPI, TypeScript, and React generation for AppStruct
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
mod app;
mod controllers;
mod module_tests;
mod modules;
mod resources;
pub mod symbols;

use crate::{Artifact, ArtifactKind, generated_header};
use appstruct_ir::AppIr;

pub(crate) fn plan(ir: &AppIr) -> Vec<Artifact> {
    let mut artifacts = framework_files(ir)
        .into_iter()
        .chain(page_files(ir))
        .chain(controllers::files())
        .chain(module_tests::files(ir))
        .map(|(path, content)| Artifact::text(path, content, ArtifactKind::Web))
        .collect::<Vec<_>>();
    modules::extend_artifacts(ir, &mut artifacts);
    artifacts.extend([
        Artifact::text("web/tsconfig.json", tsconfig(), ArtifactKind::Web),
        Artifact::text("web/rsbuild.config.ts", rsbuild_config(), ArtifactKind::Web),
        Artifact::text("web/rstest.config.ts", rstest_config(), ArtifactKind::Web),
        Artifact::text(
            "web/src/generated/resources.ts",
            resources::source(ir),
            ArtifactKind::TypeScript,
        ),
        Artifact::text(
            "web/src/generated/registry.ts",
            registry_source(ir),
            ArtifactKind::TypeScript,
        ),
    ]);
    artifacts
}

fn framework_files(ir: &AppIr) -> Vec<(&'static str, String)> {
    let title = app_display_name(&ir.app.name);
    let main = if app::requires_registry(ir) {
        include_str!("../templates/web/main_with_registry.tsx")
    } else {
        include_str!("../templates/web/main.tsx")
    };
    vec![
        (
            "web/index.html",
            with_app_title(include_str!("../templates/web/index.html"), &title),
        ),
        (
            "web/.gitignore",
            include_str!("../templates/web/gitignore").to_owned(),
        ),
        (
            "web/eslint.config.js",
            include_str!("../templates/web/eslint.config.js").to_owned(),
        ),
        ("web/src/main.tsx", main.to_owned()),
        (
            "web/src/ui.tsx",
            include_str!("../templates/web/ui.tsx").to_owned(),
        ),
        (
            "web/src/ui-messages.ts",
            include_str!("../templates/web/ui-messages.ts").to_owned(),
        ),
        (
            "web/src/ui.test.tsx",
            include_str!("../templates/web/ui.test.tsx").to_owned(),
        ),
        (
            "web/src/field-values.ts",
            include_str!("../templates/web/field-values.ts").to_owned(),
        ),
        (
            "web/src/relation-options.ts",
            include_str!("../templates/web/relation-options.ts").to_owned(),
        ),
        (
            "web/src/pages/resource-list/revisions.ts",
            include_str!("../templates/web/pages/resource-list/revisions.ts").to_owned(),
        ),
        (
            "web/src/field-values.test.ts",
            include_str!("../templates/web/field-values.test.ts").to_owned(),
        ),
        (
            "web/src/resource.ts",
            include_str!("../templates/web/resource.ts").to_owned(),
        ),
        (
            "web/src/query.ts",
            include_str!("../templates/web/query.ts").to_owned(),
        ),
        (
            "web/src/components/Dialog.tsx",
            include_str!("../templates/web/Dialog.tsx").to_owned(),
        ),
        (
            "web/src/components/AsyncState.tsx",
            include_str!("../templates/web/AsyncState.tsx").to_owned(),
        ),
        (
            "web/src/navigation.tsx",
            include_str!("../templates/web/navigation.tsx").to_owned(),
        ),
        (
            "web/src/framework.test.ts",
            include_str!("../templates/web/framework.test.ts").to_owned(),
        ),
        (
            "web/src/interaction.test.tsx",
            include_str!("../templates/web/interaction.test.tsx").to_owned(),
        ),
        (
            "web/src/product-workflows.test.tsx",
            include_str!("../templates/web/product-workflows.test.tsx").to_owned(),
        ),
        ("web/src/app/App.tsx", app::source(ir)),
        (
            "web/src/app/ResourceRoutes.tsx",
            include_str!("../templates/web/ResourceRoutes.tsx").to_owned(),
        ),
        ("web/src/app/Layout.tsx", app::layout_source(ir)),
        (
            "web/src/pages/ResourceList.tsx",
            include_str!("../templates/web/ResourceList.tsx").to_owned(),
        ),
    ]
}

fn page_files(ir: &AppIr) -> Vec<(&'static str, String)> {
    let realtime_resource = if ir.realtime.enabled {
        include_str!("../templates/web/realtime/useRealtimeResource.ts")
    } else {
        include_str!("../templates/web/realtime/useRealtimeResourceDisabled.ts")
    };
    vec![
        (
            "web/src/pages/ResourceFilters.tsx",
            include_str!("../templates/web/ResourceFilters.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/filter-expression.ts",
            include_str!("../templates/web/pages/resource-list/filter-expression.ts").to_owned(),
        ),
        (
            "web/src/pages/resource-list/AdvancedFilters.tsx",
            include_str!("../templates/web/pages/resource-list/AdvancedFilters.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/BulkActions.tsx",
            include_str!("../templates/web/pages/resource-list/BulkActions.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/ResourceTable.tsx",
            include_str!("../templates/web/pages/resource-list/ResourceTable.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/ResourceInsights.tsx",
            include_str!("../templates/web/pages/resource-list/ResourceInsights.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/report-query.ts",
            include_str!("../templates/web/pages/resource-list/report-query.ts").to_owned(),
        ),
        (
            "web/src/pages/resource-list/AggregateChart.tsx",
            include_str!("../templates/web/pages/resource-list/AggregateChart.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/InlineEditor.tsx",
            include_str!("../templates/web/pages/resource-list/InlineEditor.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/SavedViews.tsx",
            include_str!("../templates/web/pages/resource-list/SavedViews.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/ViewOptions.tsx",
            include_str!("../templates/web/pages/resource-list/ViewOptions.tsx").to_owned(),
        ),
        (
            "web/src/pages/resource-list/useCsvTransfer.ts",
            include_str!("../templates/web/pages/resource-list/useCsvTransfer.ts").to_owned(),
        ),
        (
            "web/src/pages/resource-list/csv-import.ts",
            include_str!("../templates/web/pages/resource-list/csv-import.ts").to_owned(),
        ),
        (
            "web/src/pages/resource-list/CsvImportDialog.tsx",
            include_str!("../templates/web/pages/resource-list/CsvImportDialog.tsx").to_owned(),
        ),
        (
            "web/src/pages/ResourceForm.tsx",
            include_str!("../templates/web/ResourceForm.tsx").to_owned(),
        ),
        (
            "web/src/pages/WorkflowActions.tsx",
            include_str!("../templates/web/WorkflowActions.tsx").to_owned(),
        ),
        (
            "web/src/pages/ResourceDetail.tsx",
            resource_detail_source(ir),
        ),
        (
            "web/src/realtime/useRealtimeResource.ts",
            realtime_resource.to_owned(),
        ),
        (
            "web/src/styles.css",
            include_str!("../templates/web/styles.css").to_owned(),
        ),
        (
            "web/package.json",
            include_str!("../templates/web/package.json").to_owned(),
        ),
        (
            "web/pnpm-lock.yaml",
            include_str!("../templates/web/pnpm-lock.yaml").to_owned(),
        ),
    ]
}

fn resource_detail_source(ir: &AppIr) -> String {
    let mut detail_imports = Vec::new();
    let mut detail_extras = Vec::new();
    if ir.audit.enabled {
        detail_imports.push("import { RecordHistory } from \"../audit/RecordHistory\";");
        detail_extras.push("{id && <RecordHistory entity={resource.id} recordId={id} />}");
    }
    if ir.activity.enabled {
        detail_imports.push("import { ActivityTimeline } from \"../activity/ActivityTimeline\";");
        detail_extras.push(
            "{id && resource.activity && <ActivityTimeline resource={resource} recordId={id} />}",
        );
    }
    let detail_imports = if detail_imports.is_empty() {
        String::new()
    } else {
        format!("\n{}", detail_imports.join("\n"))
    };
    let detail_extras = if detail_extras.is_empty() {
        String::new()
    } else {
        format!("\n          {}", detail_extras.join("\n          "))
    };
    include_str!("../templates/web/ResourceDetail.tsx")
        .replace("__DETAIL_IMPORTS__", &detail_imports)
        .replace("__DETAIL_EXTRAS__", &detail_extras)
}

fn tsconfig() -> &'static str {
    r#"{
  "compilerOptions": {
    "target": "ES2022",
    "useDefineForClassFields": true,
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "types": ["@rsbuild/core/types"]
    ,"paths": { "@appstruct/ui": ["./src/ui.tsx"] }
  },
  "include": ["src", "rsbuild.config.ts", "rstest.config.ts", "../../app/web"]
}
"#
}

fn rsbuild_config() -> &'static str {
    r#"import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { defineConfig, loadEnv } from "@rsbuild/core";
import { pluginReact } from "@rsbuild/plugin-react";

const { publicVars } = loadEnv({ prefixes: ["PUBLIC_", "VITE_"] });
const setup = resolve(import.meta.dirname, "../../app/web/setup.ts");

export default defineConfig({
  plugins: [pluginReact()],
  source: {
    entry: {
      index: [
        "./src/styles.css",
        ...(existsSync(setup) ? [setup] : []),
        "./src/main.tsx",
      ],
    },
    define: publicVars,
  },
  resolve: {
    alias: { "@appstruct/ui": resolve(import.meta.dirname, "src/ui.tsx") },
  },
  html: { template: "./index.html" },
  server: { host: "127.0.0.1", port: 5173 },
});
"#
}

fn rstest_config() -> &'static str {
    r#"import { defineConfig } from "@rstest/core";
import { pluginReact } from "@rsbuild/plugin-react";

export default defineConfig({
  plugins: [pluginReact()],
  testEnvironment: "happy-dom",
});
"#
}

fn registry_source(ir: &AppIr) -> String {
    let field_components = ir
        .entities
        .iter()
        .flat_map(|entity| &entity.fields)
        .filter_map(|field| field.ui_component.as_deref())
        .collect::<std::collections::BTreeSet<_>>();
    let field_members = field_components
        .iter()
        .map(|component| format!("    {component}: ComponentType<FieldComponentProps>;"))
        .collect::<Vec<_>>()
        .join("\n");
    let page_components = ir
        .pages
        .iter()
        .map(|page| page.component.as_str())
        .collect::<std::collections::BTreeSet<_>>();
    let page_members = page_components
        .iter()
        .map(|component| format!("    {component}: ComponentType<PageComponentProps>;"))
        .collect::<Vec<_>>()
        .join("\n");
    let component_import = if field_components.is_empty() && page_components.is_empty() {
        ""
    } else {
        "import type { ComponentType } from \"react\";\n\n"
    };
    let field_registry = if field_members.is_empty() {
        "Record<string, never>".to_owned()
    } else {
        format!("{{\n{field_members}\n  }}")
    };
    let page_registry = if page_members.is_empty() {
        "Record<string, never>".to_owned()
    } else {
        format!("{{\n{page_members}\n  }}")
    };
    let pages = ir
        .pages
        .iter()
        .map(|page| {
            format!(
                "  {{ name: {:?}, label: {:?}, path: {:?}, component: {:?} }},",
                page.rust_name, page.label, page.path, page.component
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    format!(
        "{}{component_import}import type {{ ResourceDefinition }} from \"../resource\";\n\nexport interface FieldComponentProps {{\n  id: string;\n  label: string;\n  required: boolean;\n  value: string | boolean | undefined;\n  error?: string;\n  readOnly: boolean;\n  onChange(value: string | boolean): void;\n}}\n\nexport interface PageComponentProps {{\n  resources: readonly ResourceDefinition[];\n}}\n\nexport interface AppStructRegistry {{\n  fields: {field_registry};\n  pages: {page_registry};\n}}\n\nexport interface CustomPageDefinition {{\n  name: string;\n  label: string;\n  path: string;\n  component: keyof AppStructRegistry[\"pages\"];\n}}\n\nexport function defineAppStructRegistry<T extends AppStructRegistry>(registry: T): T {{ return registry; }}\n\nexport const customPages: readonly CustomPageDefinition[] = [\n{pages}\n];\n",
        generated_header("//"),
    )
}

pub(super) fn app_display_name(name: &str) -> String {
    name.split('-')
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut characters = part.chars();
            characters.next().map_or_else(String::new, |first| {
                format!("{}{}", first.to_uppercase(), characters.as_str())
            })
        })
        .collect::<Vec<_>>()
        .join(" ")
}

pub(super) fn with_app_title(source: &str, title: &str) -> String {
    source.replace("__APP_TITLE__", title)
}

#[cfg(test)]
mod tests {
    use super::{app_display_name, with_app_title};

    #[test]
    fn app_display_name_title_cases_hyphenated_package_names() {
        assert_eq!(app_display_name("notes"), "Notes");
        assert_eq!(app_display_name("project-manager"), "Project Manager");
    }

    #[test]
    fn with_app_title_replaces_the_placeholder() {
        assert_eq!(
            with_app_title("<title>__APP_TITLE__</title>", "Notes"),
            "<title>Notes</title>"
        );
    }
}