kotoba 0.1.3

GP2-based Graph Rewriting Language - ISO GQL-compliant queries, MVCC+Merkle persistence, and distributed execution
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
//! ビルド/バンドルシステムIR定義
//!
//! コード分割、バンドル設定、最適化を表現します。

use crate::types::{Value, Properties, ContentHash, Result, KotobaError};
use crate::frontend::component_ir::ComponentIR;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// ビルド設定IR
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildConfigIR {
    pub entry_points: Vec<EntryPoint>,
    pub output: OutputConfig,
    pub bundler: BundlerType,
    pub optimizations: Vec<OptimizationIR>,
    pub plugins: Vec<PluginIR>,
    pub environment: BuildEnvironment,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EntryPoint {
    pub name: String,
    pub path: String,
    pub component_type: EntryPointType,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EntryPointType {
    Page,
    Component,
    Layout,
    Middleware,
    API,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OutputConfig {
    pub directory: String,
    pub filename_pattern: String,
    pub public_path: String,
    pub source_maps: bool,
    pub clean: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BundlerType {
    Webpack,
    Vite,
    Rollup,
    Esbuild,
    Custom(String),
}

/// 最適化IR
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum OptimizationIR {
    /// コード分割
    CodeSplitting {
        strategy: CodeSplittingStrategy,
        chunks: Vec<ChunkConfig>,
    },
    /// Tree Shaking
    TreeShaking {
        side_effects: Vec<String>,
        unused_exports: bool,
    },
    /// ミニファイ
    Minification {
        compressor: CompressorType,
        mangle: bool,
    },
    /// 圧縮
    Compression {
        algorithm: CompressionAlgorithm,
        level: CompressionLevel,
    },
    /// 画像最適化
    ImageOptimization {
        formats: Vec<ImageFormat>,
        quality: u8,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CodeSplittingStrategy {
    /// エントリーポイントベース
    EntryPoint,
    /// 動的インポートベース
    DynamicImport,
    /// サイズベース
    SizeBased { max_size_kb: usize },
    /// ベンダーベース
    VendorBased,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChunkConfig {
    pub name: String,
    pub test: Option<String>, // 正規表現パターン
    pub priority: i32,
    pub enforce: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CompressorType {
    Terser,
    UglifyJS,
    SWC,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CompressionAlgorithm {
    Gzip,
    Brotli,
    Deflate,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CompressionLevel {
    Fastest = 1,
    Default = 6,
    Best = 9,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ImageFormat {
    WebP,
    AVIF,
    JPEG,
    PNG,
}

/// プラグインIR
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PluginIR {
    /// CSS処理
    CSS {
        preprocessor: Option<CSSPreprocessor>,
        postprocessor: Option<String>,
        modules: bool,
    },
    /// TypeScript
    TypeScript {
        config_path: Option<String>,
        transpile_only: bool,
    },
    /// React
    React {
        runtime: ReactRuntime,
        fast_refresh: bool,
    },
    /// バンドル分析
    BundleAnalyzer {
        open_analyzer: bool,
        generate_stats_file: bool,
    },
    /// PWA
    PWA {
        service_worker: bool,
        manifest: bool,
    },
    /// カスタムプラグイン
    Custom {
        name: String,
        config: Properties,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CSSPreprocessor {
    Sass,
    Less,
    Stylus,
    PostCSS,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ReactRuntime {
    Automatic,
    Classic,
}

/// ビルド環境
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BuildEnvironment {
    Development,
    Production,
    Test,
}

/// バンドル結果IR
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BundleResultIR {
    pub chunks: Vec<ChunkIR>,
    pub assets: Vec<AssetIR>,
    pub stats: BuildStats,
    pub manifest: BundleManifest,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChunkIR {
    pub id: String,
    pub name: Option<String>,
    pub entry: bool,
    pub initial: bool,
    pub files: Vec<String>,
    pub hash: ContentHash,
    pub size: usize,
    pub modules: Vec<ModuleIR>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModuleIR {
    pub id: String,
    pub name: String,
    pub size: usize,
    pub dependencies: Vec<String>,
    pub is_entry: bool,
    pub chunks: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssetIR {
    pub name: String,
    pub path: String,
    pub size: usize,
    pub content_type: String,
    pub hash: ContentHash,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildStats {
    pub build_time_ms: u64,
    pub total_size: usize,
    pub gzip_size: usize,
    pub brotli_size: usize,
    pub chunk_count: usize,
    pub module_count: usize,
    pub asset_count: usize,
    pub warnings: Vec<String>,
    pub errors: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BundleManifest {
    pub entries: HashMap<String, String>, // entry_name -> chunk_id
    pub chunks: HashMap<String, Vec<String>>, // chunk_id -> asset_paths
    pub modules: HashMap<String, ModuleManifest>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModuleManifest {
    pub file: String,
    pub exports: Vec<String>,
    pub imports: Vec<String>,
}

/// コード分割IR
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CodeSplittingIR {
    pub dynamic_imports: Vec<DynamicImportIR>,
    pub lazy_components: Vec<LazyComponentIR>,
    pub preload_hints: Vec<PreloadHintIR>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DynamicImportIR {
    pub module_path: String,
    pub chunk_name: Option<String>,
    pub loading_strategy: LoadingStrategy,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum LoadingStrategy {
    /// 即時読み込み
    Eager,
    /// 遅延読み込み
    Lazy,
    /// ビューポート内読み込み
    Viewport,
    /// インタラクション時読み込み
    Interaction,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LazyComponentIR {
    pub component_id: String,
    pub import_path: String,
    pub fallback: Option<ComponentIR>,
    pub loading_strategy: LoadingStrategy,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreloadHintIR {
    pub resource_path: String,
    pub resource_type: ResourceType,
    pub priority: PreloadPriority,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ResourceType {
    Script,
    Style,
    Font,
    Image,
    Document,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PreloadPriority {
    High,
    Medium,
    Low,
}

/// デプロイメントIR
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeploymentIR {
    pub strategy: DeploymentStrategy,
    pub cdn_config: Option<CDNConfig>,
    pub cache_config: BuildCacheConfig,
    pub monitoring: MonitoringConfig,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DeploymentStrategy {
    StaticHosting,
    ServerSideRendering,
    EdgeFunctions,
    Hybrid,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CDNConfig {
    pub provider: CDNProvider,
    pub distribution_id: String,
    pub regions: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CDNProvider {
    CloudFlare,
    AWSCloudFront,
    Vercel,
    Netlify,
    Custom(String),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildCacheConfig {
    pub static_cache_ttl: u64,
    pub api_cache_ttl: u64,
    pub cache_invalidation: CacheInvalidationStrategy,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CacheInvalidationStrategy {
    TimeBased,
    TagBased,
    Manual,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MonitoringConfig {
    pub performance_monitoring: bool,
    pub error_tracking: bool,
    pub analytics: bool,
    pub real_user_monitoring: bool,
}

/// 開発サーバーIR
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DevServerIR {
    pub port: u16,
    pub host: String,
    pub hot_reload: bool,
    pub fast_refresh: bool,
    pub proxy_config: Vec<ProxyRule>,
    pub middleware: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProxyRule {
    pub path_pattern: String,
    pub target_url: String,
    pub change_origin: bool,
}

impl BuildConfigIR {
    pub fn new(bundler: BundlerType) -> Self {
        Self {
            entry_points: Vec::new(),
            output: OutputConfig {
                directory: "dist".to_string(),
                filename_pattern: "[name].[contenthash].js".to_string(),
                public_path: "/".to_string(),
                source_maps: true,
                clean: true,
            },
            bundler,
            optimizations: Vec::new(),
            plugins: Vec::new(),
            environment: BuildEnvironment::Development,
        }
    }

    pub fn add_entry_point(&mut self, entry: EntryPoint) {
        self.entry_points.push(entry);
    }

    pub fn add_optimization(&mut self, optimization: OptimizationIR) {
        self.optimizations.push(optimization);
    }

    pub fn add_plugin(&mut self, plugin: PluginIR) {
        self.plugins.push(plugin);
    }

    pub fn set_environment(&mut self, env: BuildEnvironment) {
        // 環境に応じて最適化設定を調整
        match env {
            BuildEnvironment::Production => {
                self.output.source_maps = false;
                // プロダクション最適化を追加
                self.add_optimization(OptimizationIR::Minification {
                    compressor: CompressorType::Terser,
                    mangle: true,
                });
                self.add_optimization(OptimizationIR::Compression {
                    algorithm: CompressionAlgorithm::Gzip,
                    level: CompressionLevel::Best,
                });
            }
            BuildEnvironment::Development => {
                self.output.source_maps = true;
            }
            BuildEnvironment::Test => {
                self.output.source_maps = true;
            }
        }
        self.environment = env;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_config_creation() {
        let mut config = BuildConfigIR::new(BundlerType::Vite);

        config.add_entry_point(EntryPoint {
            name: "main".to_string(),
            path: "src/main.tsx".to_string(),
            component_type: EntryPointType::Page,
        });

        config.add_optimization(OptimizationIR::CodeSplitting {
            strategy: CodeSplittingStrategy::DynamicImport,
            chunks: Vec::new(),
        });

        config.add_plugin(PluginIR::React {
            runtime: ReactRuntime::Automatic,
            fast_refresh: true,
        });

        assert_eq!(config.bundler, BundlerType::Vite);
        assert_eq!(config.entry_points.len(), 1);
        assert_eq!(config.optimizations.len(), 1);
        assert_eq!(config.plugins.len(), 1);
    }

    #[test]
    fn test_environment_configuration() {
        let mut config = BuildConfigIR::new(BundlerType::Webpack);

        // 開発環境
        config.set_environment(BuildEnvironment::Development);
        assert!(config.output.source_maps);

        // プロダクション環境
        config.set_environment(BuildEnvironment::Production);
        assert!(!config.output.source_maps);
        assert!(config.optimizations.iter().any(|opt| matches!(opt, OptimizationIR::Minification { .. })));
    }

    #[test]
    fn test_code_splitting() {
        let mut config = BuildConfigIR::new(BundlerType::Rollup);

        config.add_optimization(OptimizationIR::CodeSplitting {
            strategy: CodeSplittingStrategy::SizeBased { max_size_kb: 244 },
            chunks: vec![
                ChunkConfig {
                    name: "vendor".to_string(),
                    test: Some("node_modules".to_string()),
                    priority: 10,
                    enforce: true,
                },
            ],
        });

        match &config.optimizations[0] {
            OptimizationIR::CodeSplitting { strategy, chunks } => {
                match strategy {
                    CodeSplittingStrategy::SizeBased { max_size_kb } => {
                        assert_eq!(*max_size_kb, 244);
                    }
                    _ => panic!("Expected SizeBased strategy"),
                }
                assert_eq!(chunks.len(), 1);
                assert_eq!(chunks[0].name, "vendor");
            }
            _ => panic!("Expected CodeSplitting optimization"),
        }
    }
}