oj 0.0.3

Rust-native build tool for React apps
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Raphael Amorim

//! `oj build`: production build via embedded Rolldown 1.x (MIT).
//!
//! oj owns the app-shaped parts: HTML entry discovery, NODE_ENV, hashed-asset
//! HTML rewriting, and the build summary.

use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;

use std::borrow::Cow;
use std::sync::{Arc, Mutex};

use anyhow::{Context, bail};
use rolldown::{
    BundlerBuilder, BundlerOptions, InputItem, OutputFormat, RawMinifyOptions, SourceMapType,
};
use rolldown_plugin::{
    HookLoadArgs, HookLoadOutput, HookLoadReturn, HookRenderChunkArgs, HookRenderChunkOutput,
    HookRenderChunkReturn, HookResolveIdArgs, HookResolveIdOutput, HookResolveIdReturn,
    HookTransformArgs, HookTransformOutput, HookTransformOutputMap, HookTransformReturn, Plugin,
    PluginContext, SharedLoadPluginContext, SharedTransformPluginContext,
};
use rolldown_plugin::__inner::SharedPluginable;
use oj_server::plugins::PluginHost;

/// The oj build plugin: loads `.css`/`.scss` imports as JS stubs (CSS Modules
/// export their scoped class map), collecting compiled CSS into one emitted
/// stylesheet. Its `transform` expands `import.meta.glob` (Rolldown has no
/// native glob), keeping prod builds in sync with dev.
#[derive(Debug)]
struct OjCssPlugin {
    collected: Arc<Mutex<Vec<(String, String)>>>,
    /// App root, so CSS-module class names hash from the same root-relative id
    /// (`/src/x.module.css`) the dev server uses. Keeps `oj dev`, `oj build`,
    /// and the SSR/client bundles consistent, which hydration relies on.
    root: PathBuf,
    /// App has a postcss.config: run all .css through the sidecar (PostCSS),
    /// not just Tailwind-flagged css, as the dev server does.
    has_postcss: bool,
    /// This is a client (browser) build: replace `*.server.*` modules with RPC
    /// stubs so server-only code never ships to the browser. The server build
    /// (`false`) keeps the real implementations.
    client: bool,
}

impl Plugin for OjCssPlugin {
    fn name(&self) -> Cow<'static, str> {
        Cow::Borrowed("oj:build")
    }

    fn register_hook_usage(&self) -> rolldown_plugin::HookUsage {
        rolldown_plugin::HookUsage::ResolveId
            | rolldown_plugin::HookUsage::Load
            | rolldown_plugin::HookUsage::Transform
    }

    // Built-in `virtual:oj-routes` resolves to a synthetic module at the app
    // root (so its `./src/routes/**` glob resolves there); `load` returns the
    // manifest source and `transform` (below) expands the glob. Also handles
    // Vite's `?url` asset imports: resolve the real file, keep the `?url` marker
    // so `load` emits it.
    fn resolve_id(
        &self,
        ctx: &PluginContext,
        args: &HookResolveIdArgs<'_>,
    ) -> impl std::future::Future<Output = HookResolveIdReturn> + Send {
        let is_routes = args.specifier == "virtual:oj-routes";
        let routes_id = self.root.join("oj-routes.tsx").to_string_lossy().into_owned();
        let url_base = args.specifier.strip_suffix("?url").map(str::to_string);
        let importer = args.importer.map(str::to_string);
        let ctx = ctx.clone();
        async move {
            if is_routes {
                return Ok(Some(HookResolveIdOutput::from_id(routes_id)));
            }
            if let Some(base) = url_base {
                // Resolve through Rolldown's resolver (honors alias/tsconfig),
                // then re-attach `?url` so `load` recognizes it.
                if let Ok(Ok(resolved)) = ctx.resolve(&base, importer.as_deref(), None).await {
                    let id = format!("{}?url", resolved.id.as_str());
                    return Ok(Some(HookResolveIdOutput::from_id(id)));
                }
            }
            Ok(None)
        }
    }

    fn transform(
        &self,
        _ctx: SharedTransformPluginContext,
        args: &HookTransformArgs<'_>,
    ) -> impl std::future::Future<Output = HookTransformReturn> + Send {
        let id = args.id.to_string();
        let code = args.code.to_string();
        async move {
            if !code.contains("import.meta.glob") {
                return Ok(None);
            }
            let expanded = oj_compiler::glob::expand_source(&code, std::path::Path::new(&id));
            Ok(Some(rolldown_plugin::HookTransformOutput {
                code: Some(expanded),
                ..Default::default()
            }))
        }
    }

    fn load(
        &self,
        ctx: SharedLoadPluginContext,
        args: &HookLoadArgs<'_>,
    ) -> impl std::future::Future<Output = HookLoadReturn> + Send {
        let id = args.id.to_string();
        let collected = Arc::clone(&self.collected);
        let root = self.root.clone();
        let routes_id = root.join("oj-routes.tsx").to_string_lossy().into_owned();
        let client = self.client;
        async move {
            // Vite `?url` asset import: emit the real file as a build asset and
            // resolve the module to its final (hashed, base-prefixed) URL.
            if let Some(file) = id.strip_suffix("?url") {
                let bytes = std::fs::read(file)
                    .map_err(|e| anyhow::anyhow!("cannot read {file}: {e}"))?;
                let name = std::path::Path::new(file)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("asset")
                    .to_string();
                let reference = ctx
                    .emit_file(
                        rolldown_common::EmittedAsset {
                            name: Some(name),
                            source: rolldown_common::StrOrBytes::Bytes(bytes),
                            ..Default::default()
                        },
                        None,
                        None,
                    )
                    .map_err(|e| anyhow::anyhow!(e))?;
                return Ok(Some(rolldown_plugin::HookLoadOutput {
                    code: arcstr::ArcStr::from(format!(
                        "export default import.meta.ROLLUP_FILE_URL_{reference};"
                    )),
                    module_type: Some(rolldown_common::ModuleType::Js),
                    ..Default::default()
                }));
            }
            let path = id.split('?').next().unwrap_or(&id);
            // Server functions: in the client build, a `*.server.*` module is
            // replaced by RPC stubs so its real code never reaches the browser.
            if client && is_server_module_path(path) {
                let source = std::fs::read_to_string(path)
                    .map_err(|e| anyhow::anyhow!("cannot read {path}: {e}"))?;
                let url = match std::path::Path::new(path).strip_prefix(&root) {
                    Ok(rel) => format!("/{}", rel.display()),
                    Err(_) => path.to_string(),
                };
                let stub = server_fn_prod_stub(&oj_compiler::exports(&source, std::path::Path::new(path)), &url);
                return Ok(Some(rolldown_plugin::HookLoadOutput {
                    code: arcstr::ArcStr::from(stub),
                    module_type: Some(rolldown_common::ModuleType::Js),
                    ..Default::default()
                }));
            }
            // Built-in route manifest (transform expands its glob afterwards).
            if path == routes_id {
                return Ok(Some(rolldown_plugin::HookLoadOutput {
                    code: arcstr::ArcStr::from(oj_server::OJ_ROUTES_JS),
                    module_type: Some(rolldown_common::ModuleType::Js),
                    ..Default::default()
                }));
            }
            if !(path.ends_with(".css") || oj_css::is_sass(path)) {
                return Ok(None);
            }
            let mut source = std::fs::read_to_string(path)
                .map_err(|e| anyhow::anyhow!("cannot read {path}: {e}"))?;
            // Sass/SCSS to CSS first (sibling @use/@import resolve from dir).
            if oj_css::is_sass(path) {
                let dir = std::path::Path::new(path).parent();
                source = oj_css::compile_sass(&source, dir).map_err(|e| anyhow::anyhow!(e))?;
            }
            // Run css through the CSS sidecar (the app's postcss.config or the
            // Tailwind v4 API), as the dev server does: always for Tailwind-
            // flagged css, and for any .css when the app has a postcss.config.
            // Plain css with no postcss config goes straight to Lightning below.
            if oj_server::sidecar::is_tailwind_css(&source)
                || (self.has_postcss && path.ends_with(".css"))
            {
                source = expand_css_via_sidecar(&root, std::path::Path::new(path))?;
            }
            // Hash class names from the dev server's root-relative id form.
            let css_id = match std::path::Path::new(path).strip_prefix(&root) {
                Ok(rel) => format!("/{}", rel.display()),
                Err(_) => path.to_string(),
            };
            let output = oj_css::compile_css(&css_id, &source, true)
                .map_err(|e| anyhow::anyhow!(e))?;
            let js = match &output.exports {
                Some(exports) => {
                    let map: serde_json::Map<String, serde_json::Value> = exports
                        .iter()
                        .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
                        .collect();
                    format!("export default {};", serde_json::Value::Object(map))
                }
                None => "export default void 0;".to_string(),
            };
            collected.lock().unwrap().push((path.to_string(), output.css));
            Ok(Some(rolldown_plugin::HookLoadOutput {
                code: arcstr::ArcStr::from(js),
                module_type: Some(rolldown_common::ModuleType::Js),
                ..Default::default()
            }))
        }
    }
}

/// Expand `@tailwind`/`@apply` (and any `postcss.config.*` plugins) in a CSS
/// file via oj's one-shot CSS sidecar, the same one the dev server runs, so
/// `oj dev` and `oj build` produce identical Tailwind output.
fn expand_css_via_sidecar(root: &Path, css_file: &Path) -> anyhow::Result<String> {
    let script = root.join(".oj-cache").join("css-sidecar.mjs");
    if let Some(parent) = script.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&script, oj_server::sidecar::SIDECAR_JS)?;
    let out = std::process::Command::new("node")
        .args([
            script.to_str().unwrap(),
            "--once",
            css_file.to_str().unwrap(),
            root.to_str().unwrap(),
        ])
        // cwd = app root so Tailwind v3 finds tailwind.config.* + content globs
        // (matches the persistent dev sidecar's current_dir(root)).
        .current_dir(root)
        .output()
        .context("node not found for tailwind/postcss build")?;
    if !out.status.success() {
        bail!("css build failed for {}: {}", css_file.display(), String::from_utf8_lossy(&out.stderr));
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Build Rolldown's `resolve.alias` from the app's `resolve.alias` config for
/// an environment (client/ssr). Relative replacements (`./src`) become absolute
/// against `root`, matching oj's own resolver. Returns `None` when there are no
/// aliases, so Rolldown keeps its defaults (including tsconfig `paths`).
fn rolldown_resolve(
    root: &Path,
    config: &oj_config::OjConfig,
    env: &str,
) -> Option<rolldown_common::ResolveOptions> {
    let alias = oj_config::resolve_alias(config, env);
    if alias.is_empty() {
        return None;
    }
    let alias = alias
        .into_iter()
        .map(|(find, replacement)| {
            let target = if replacement.starts_with('.') {
                root.join(&replacement).to_string_lossy().into_owned()
            } else {
                replacement
            };
            (find, vec![Some(target)])
        })
        .collect();
    Some(rolldown_common::ResolveOptions { alias: Some(alias), ..Default::default() })
}

/// Whether a module path is a server-function module (`*.server.{ts,tsx,js,jsx}`).
fn is_server_module_path(path: &str) -> bool {
    [".server.ts", ".server.tsx", ".server.js", ".server.jsx"].iter().any(|s| path.ends_with(s))
}

/// Client-build stub for a server-function module: each export RPCs to /__oj_fn
/// (the helper is inlined so the stub needs no runtime import in the bundle).
fn server_fn_prod_stub(exports: &[String], url: &str) -> String {
    let mut out = String::from(
        "const __ojCall = (m, n, a) => fetch(\"/__oj_fn\", { method: \"POST\", \
         headers: { \"content-type\": \"application/json\" }, \
         body: JSON.stringify({ module: m, name: n, args: a }) })\
         .then((r) => { if (!r.ok) throw new Error(\"oj server fn \" + n + \": \" + r.status); return r.json(); });\n",
    );
    for name in exports {
        if name == "default" {
            out.push_str(&format!("export default (...a) => __ojCall({url:?}, \"default\", a);\n"));
        } else {
            out.push_str(&format!("export const {name} = (...a) => __ojCall({url:?}, {name:?}, a);\n"));
        }
    }
    out
}

/// Recursively copy the contents of `src` into `dest` (Vite's publicDir copy).
/// No-op if `src` doesn't exist. Existing files (e.g. a generated index.html)
/// are not clobbered by same-named public files.
fn copy_public_dir(src: &Path, dest: &Path) -> anyhow::Result<()> {
    if !src.is_dir() {
        return Ok(());
    }
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let from = entry.path();
        let to = dest.join(entry.file_name());
        if from.is_dir() {
            fs::create_dir_all(&to)?;
            copy_public_dir(&from, &to)?;
        } else if !to.exists() {
            if let Some(parent) = to.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::copy(&from, &to)?;
        }
    }
    Ok(())
}

/// Bridges the Node plugin host into the Rolldown build, so the same
/// Vite/Rollup-style `resolveId`/`load`/`transform` hooks that run in the dev
/// server also run in `oj build`. Runs before `OjCssPlugin` so user transforms
/// see raw source and user resolveId/load win for virtual ids.
#[derive(Debug)]
struct OjUserPlugin {
    host: Arc<PluginHost>,
    /// Cached `has_render_chunk()`: renderChunk fires per chunk, so resolve it
    /// once instead of round-tripping to Node for every chunk.
    render_chunk_enabled: Arc<tokio::sync::OnceCell<bool>>,
}

impl OjUserPlugin {
    fn new(host: Arc<PluginHost>) -> Self {
        Self { host, render_chunk_enabled: Arc::new(tokio::sync::OnceCell::new()) }
    }
}

impl Plugin for OjUserPlugin {
    fn name(&self) -> Cow<'static, str> {
        Cow::Borrowed("oj:user-plugins")
    }

    fn register_hook_usage(&self) -> rolldown_plugin::HookUsage {
        rolldown_plugin::HookUsage::ResolveId
            | rolldown_plugin::HookUsage::Load
            | rolldown_plugin::HookUsage::Transform
            | rolldown_plugin::HookUsage::GenerateBundle
            | rolldown_plugin::HookUsage::RenderChunk
            | rolldown_plugin::HookUsage::WriteBundle
            | rolldown_plugin::HookUsage::RenderStart
            | rolldown_plugin::HookUsage::CloseBundle
    }

    fn resolve_id(
        &self,
        _ctx: &PluginContext,
        args: &HookResolveIdArgs<'_>,
    ) -> impl std::future::Future<Output = HookResolveIdReturn> + Send {
        let host = Arc::clone(&self.host);
        let spec = args.specifier.to_string();
        let importer = args.importer.unwrap_or("").to_string();
        async move {
            Ok(host
                .resolve_id(&spec, &importer)
                .await
                .ok()
                .flatten()
                .map(HookResolveIdOutput::from_id))
        }
    }

    fn load(
        &self,
        _ctx: SharedLoadPluginContext,
        args: &HookLoadArgs<'_>,
    ) -> impl std::future::Future<Output = HookLoadReturn> + Send {
        let host = Arc::clone(&self.host);
        let id = args.id.to_string();
        async move {
            Ok(host.load(&id).await.ok().flatten().map(|code| HookLoadOutput {
                code: arcstr::ArcStr::from(code),
                module_type: Some(rolldown_common::ModuleType::Js),
                ..Default::default()
            }))
        }
    }

    fn transform(
        &self,
        _ctx: SharedTransformPluginContext,
        args: &HookTransformArgs<'_>,
    ) -> impl std::future::Future<Output = HookTransformReturn> + Send {
        let host = Arc::clone(&self.host);
        let code = args.code.to_string();
        let id = args.id.to_string();
        async move {
            match host.transform(&code, &id).await {
                Ok(out) if out != code => Ok(Some(HookTransformOutput {
                    code: Some(out),
                    ..Default::default()
                })),
                _ => Ok(None),
            }
        }
    }

    // Output-phase hook: the plugins see the finished bundle (keyed by
    // fileName), may read it, mutate chunk `code` / asset `source`, or emitFile
    // new assets (collected separately). Skipped when no plugin defines
    // generateBundle.
    async fn generate_bundle(
        &self,
        _ctx: &PluginContext,
        args: &mut rolldown_plugin::HookGenerateBundleArgs<'_>,
    ) -> rolldown_plugin::HookNoopReturn {
        if !self.host.has_generate_bundle().await {
            return Ok(());
        }
        let bundle_json = serialize_bundle(args.bundle);
        if let Ok(Some(mutated)) = self.host.generate_bundle(&bundle_json, args.is_write).await {
            apply_bundle_mutations(args.bundle, &mutated);
        }
        Ok(())
    }

    // Per-chunk output hook: chain the plugins' renderChunk over each chunk's
    // rendered code. Cached `has_render_chunk` avoids a Node round-trip per
    // chunk when nothing uses it. Sourcemap is dropped (Null) on a change.
    fn render_chunk(
        &self,
        _ctx: &PluginContext,
        args: &HookRenderChunkArgs<'_>,
    ) -> impl std::future::Future<Output = HookRenderChunkReturn> + Send {
        let host = Arc::clone(&self.host);
        let enabled = Arc::clone(&self.render_chunk_enabled);
        let code = Arc::clone(&args.code);
        let chunk_json = serialize_rendered_chunk(&args.chunk);
        async move {
            let on = *enabled.get_or_init(|| async { host.has_render_chunk().await }).await;
            if !on {
                return Ok(None);
            }
            match host.render_chunk(&code, &chunk_json).await {
                Ok(Some(out)) if out != *code => {
                    Ok(Some(HookRenderChunkOutput { code: out, map: HookTransformOutputMap::Null }))
                }
                _ => Ok(None),
            }
        }
    }

    // Post-write hook: files are already on disk, so this is a read-only
    // notification (plugins do side effects like extra fs writes / logging).
    async fn write_bundle(
        &self,
        _ctx: &PluginContext,
        args: &mut rolldown_plugin::HookWriteBundleArgs<'_>,
    ) -> rolldown_plugin::HookNoopReturn {
        if !self.host.has_write_bundle().await {
            return Ok(());
        }
        let bundle_json = serialize_bundle(args.bundle);
        let _ = self.host.write_bundle(&bundle_json, true).await;
        Ok(())
    }

    // Output phase begins (after buildEnd, before renderChunk). Side effect.
    async fn render_start(
        &self,
        _ctx: &PluginContext,
        _args: &rolldown_plugin::HookRenderStartArgs<'_>,
    ) -> rolldown_plugin::HookNoopReturn {
        let _ = self.host.render_start().await;
        Ok(())
    }

    // The very last hook, after everything is written. Side effect.
    async fn close_bundle(
        &self,
        _ctx: &PluginContext,
        _args: Option<&rolldown_plugin::HookCloseBundleArgs<'_>>,
    ) -> rolldown_plugin::HookNoopReturn {
        let _ = self.host.close_bundle().await;
        Ok(())
    }
}

/// A Rollup RenderedChunk as the plugin host expects it (metadata only; the
/// code is passed separately as the hook's first argument).
fn serialize_rendered_chunk(chunk: &rolldown_common::RollupRenderedChunk) -> String {
    serde_json::json!({
        "type": "chunk",
        "fileName": chunk.filename.to_string(),
        "name": chunk.name.to_string(),
        "isEntry": chunk.is_entry,
        "isDynamicEntry": chunk.is_dynamic_entry,
        "imports": chunk.imports.iter().map(|i| i.to_string()).collect::<Vec<_>>(),
    })
    .to_string()
}

/// Serialize the Rolldown output bundle to a Rollup-shaped `bundle` object
/// (JSON keyed by fileName) for the plugin host. Binary asset sources are sent
/// as null (readable metadata only; not mutable through this bridge).
fn serialize_bundle(bundle: &[rolldown_common::Output]) -> String {
    use rolldown_common::{Output, StrOrBytes};
    let mut map = serde_json::Map::new();
    for out in bundle {
        match out {
            Output::Chunk(c) => {
                map.insert(
                    c.filename.to_string(),
                    serde_json::json!({
                        "type": "chunk",
                        "fileName": c.filename.to_string(),
                        "name": c.name.to_string(),
                        "isEntry": c.is_entry,
                        "code": c.code,
                    }),
                );
            }
            Output::Asset(a) => {
                let source = match &a.source {
                    StrOrBytes::Str(s) => Some(s.as_str()),
                    StrOrBytes::Bytes(_) => None,
                };
                map.insert(
                    a.filename.to_string(),
                    serde_json::json!({
                        "type": "asset",
                        "fileName": a.filename.to_string(),
                        "source": source,
                    }),
                );
            }
        }
    }
    serde_json::Value::Object(map).to_string()
}

/// Apply a plugin's `generateBundle` edits back onto the Rolldown output: only
/// `code`/`source` changes to existing entries (COW via `Arc::make_mut`). New
/// entries (use `this.emitFile`) and deletions are not applied.
fn apply_bundle_mutations(bundle: &mut [rolldown_common::Output], json: &str) {
    use rolldown_common::{Output, StrOrBytes};
    let Ok(map) = serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(json) else {
        return;
    };
    for out in bundle.iter_mut() {
        match out {
            Output::Chunk(c) => {
                if let Some(code) =
                    map.get(c.filename.as_str()).and_then(|v| v.get("code")).and_then(|x| x.as_str())
                {
                    if c.code != code {
                        Arc::make_mut(c).code = code.to_string();
                    }
                }
            }
            Output::Asset(a) => {
                if let Some(src) =
                    map.get(a.filename.as_str()).and_then(|v| v.get("source")).and_then(|x| x.as_str())
                {
                    if a.source.as_bytes() != src.as_bytes() {
                        Arc::make_mut(a).source = StrOrBytes::Str(src.to_string());
                    }
                }
            }
        }
    }
}

/// Spawn the plugin host for a build (`command: "build"`) if the app declares
/// plugins. Returned so the build can both add it as a Rolldown plugin and run
/// transformIndexHtml on the emitted HTML.
async fn user_plugin_host(
    root: &Path,
    base: &str,
    define: &serde_json::Value,
    environments: &serde_json::Value,
    env_name: &str,
) -> Option<Arc<PluginHost>> {
    // Plugins come from oj.plugins.* or the app's vite.config (same source and
    // format as the dev server), so a vite.config-only app runs its plugins in
    // the build too.
    let (file, plugins_format, label) = match oj_server::plugins::plugin_source(root)? {
        oj_server::plugins::PluginSource::OjPlugins(p) => {
            let label = p.file_name().unwrap().to_string_lossy().into_owned();
            (p, "oj", label)
        }
        oj_server::plugins::PluginSource::ViteConfig(p) => (p, "vite", "vite.config".to_string()),
    };
    let config = serde_json::json!({
        "config": { "root": root.display().to_string(), "base": base, "mode": "production", "command": "build", "define": define, "environments": environments },
        "env": { "command": "build", "mode": "production" },
        // Which Vite environment this build represents ("client" or "ssr").
        "environment": { "name": env_name, "mode": "production" },
        "pluginsFormat": plugins_format,
    })
    .to_string();
    match PluginHost::spawn(root, &file, &config).await {
        Ok(host) => {
            println!("oj build ({env_name}): plugins from {label}");
            Some(host)
        }
        Err(e) => {
            eprintln!("oj build ({env_name}): plugin host failed to start: {e}");
            None
        }
    }
}

pub async fn build(root: PathBuf, out: Option<PathBuf>, ssr: Option<String>) -> anyhow::Result<()> {
    let root = root
        .canonicalize()
        .with_context(|| format!("app root not found: {}", root.display()))?;

    let mut config = oj_config::load(&root).map_err(|e| anyhow::anyhow!("{e}"))?;
    // Adopt vite.config base/define/resolve.alias for vite-configured apps, so
    // `oj build` resolves the same way `oj dev` does.
    oj_server::plugins::adopt_vite_config_values(&mut config, &root);
    let build_cfg = config.build.clone().unwrap_or_default();
    // Precedence: CLI --out > config build.outDir > "dist".
    let out = out
        .or_else(|| build_cfg.out_dir.as_ref().map(PathBuf::from))
        .unwrap_or_else(|| PathBuf::from("dist"));
    let out_dir = if out.is_absolute() { out } else { root.join(&out) };
    let minify = build_cfg.minify.unwrap_or(true);
    let sourcemap = build_cfg.sourcemap.unwrap_or(true);
    if build_cfg.target.is_some() {
        eprintln!("oj build: note: build.target is accepted but not yet applied");
    }

    // SSR mode: build the server bundle, a client hydration bundle, and a
    // streaming production server that ties them together.
    if let Some(entry) = ssr.or_else(|| build_cfg.ssr.clone()) {
        return build_ssr_app(&root, &out_dir, &entry, minify, sourcemap, build_cfg.prerender.clone())
            .await;
    }

    // Library mode: build a distributable, not an app (no index.html).
    if let Some(lib) = build_cfg.lib.clone() {
        return build_library(&root, &out_dir, lib, minify, sourcemap).await;
    }

    let html_path = root.join("index.html");
    let html = fs::read_to_string(&html_path)
        .with_context(|| format!("no index.html in {}", root.display()))?;

    let entries = module_script_srcs(&html);
    if entries.is_empty() {
        bail!("index.html has no <script type=\"module\" src=...> entry");
    }

    let base = normalize_base(config.base.as_deref().unwrap_or("/"));

    let _ = fs::remove_dir_all(&out_dir);
    fs::create_dir_all(&out_dir)?;

    let started = Instant::now();
    let inputs: Vec<InputItem> = entries
        .iter()
        .map(|entry| InputItem {
            name: Some(
                Path::new(entry)
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("entry")
                    .to_string(),
            ),
            import: format!(".{entry}"),
            ..Default::default()
        })
        .collect();

    let collected_css: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
    let plugin_host = user_plugin_host(
        &root,
        &base,
        &serde_json::json!(config.define),
        &serde_json::json!(config.environments),
        "client",
    )
    .await;
    let mut oj_plugins: Vec<SharedPluginable> = Vec::new();
    if let Some(host) = &plugin_host {
        if let Err(e) = host.build_start().await {
            eprintln!("oj build: plugin buildStart failed: {e}");
        }
        oj_plugins.push(Arc::new(OjUserPlugin::new(Arc::clone(host)))); // before oj:build
    }
    oj_plugins.push(Arc::new(OjCssPlugin { collected: Arc::clone(&collected_css), root: root.to_path_buf(), has_postcss: oj_server::has_postcss_config(&root), client: true }));
    let mut bundler = BundlerBuilder::default()
        .with_plugins(oj_plugins)
        .with_options(BundlerOptions {
        input: Some(inputs),
        cwd: Some(root.clone()),
        dir: Some(out_dir.display().to_string()),
        resolve: rolldown_resolve(&root, &config, "client"),
        entry_filenames: Some("assets/[name]-[hash].js".to_string().into()),
        chunk_filenames: Some("assets/[name]-[hash].js".to_string().into()),
        // Per-environment build output: the "client" environment may override
        // minify/sourcemap (Vite Environment API environments.client.build).
        minify: Some(RawMinifyOptions::Bool(
            oj_config::environment_build_bool(&config, "client", "minify").unwrap_or(minify),
        )),
        sourcemap: oj_config::environment_build_bool(&config, "client", "sourcemap")
            .unwrap_or(sourcemap)
            .then_some(SourceMapType::File),
        define: Some({
            // NODE_ENV plus the app's .env-derived import.meta.env.* values,
            // loaded in production mode. BASE_URL reflects the configured base.
            // Then config `define` + the "client" environment's define overrides.
            let env = oj_env::load(&root, "production");
            let mut pairs: Vec<(String, String)> =
                vec![("process.env.NODE_ENV".into(), "'production'".into())];
            pairs.extend(oj_env::import_meta_env_defines(&env, "production", false, &base, "VITE_"));
            pairs.extend(oj_config::config_defines(&config));
            pairs.extend(oj_config::environment_defines(&config, "client"));
            pairs.into_iter().collect()
        }),
            ..Default::default()
        })
        .build()
        .map_err(|errs| anyhow::anyhow!("rolldown init failed: {errs:?}"))?;

    let output = bundler
        .write()
        .await
        .map_err(|errs| anyhow::anyhow!("build failed:\n{errs:?}"))?;
    // Fire the closeBundle hook (the last output hook; write() alone doesn't).
    bundler.close().await.map_err(|errs| anyhow::anyhow!("close failed:\n{errs:?}"))?;

    // The module graph is complete: buildEnd fires before emitting HTML/manifest.
    if let Some(host) = &plugin_host {
        if let Err(e) = host.build_end().await {
            eprintln!("oj build: plugin buildEnd failed: {e}");
        }
        // Write any assets plugins emitted via this.emitFile into the output.
        match host.emitted_files().await {
            Ok(files) => {
                for file in files {
                    let dest = out_dir.join(&file.file_name);
                    if let Some(parent) = dest.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::write(&dest, file.source.as_bytes())?;
                }
            }
            Err(e) => eprintln!("oj build: plugin emitFile collection failed: {e}"),
        }
    }

    for warning in &output.warnings {
        // oj's transform plugins don't emit sourcemaps yet.
        if format!("{warning:?}").contains("SOURCEMAP_BROKEN") {
            continue;
        }
        eprintln!("oj build warning: {warning:?}");
    }

    // Map each entry url to its hashed chunk filename for HTML rewriting.
    let mut rewritten_html = html.clone();
    let mut emitted: Vec<(String, usize)> = Vec::new();
    let mut manifest_entries: Vec<ManifestEntry> = Vec::new();
    for asset in &output.assets {
        if let rolldown_common::Output::Chunk(chunk) = asset {
            emitted.push((chunk.filename.to_string(), chunk.code.len()));
            if !chunk.is_entry {
                continue;
            }
            let Some(facade) = &chunk.facade_module_id else { continue };
            // Root-relative source path is the Vite manifest key.
            let src = Path::new(facade.as_ref())
                .strip_prefix(&root)
                .map(|p| p.to_string_lossy().replace('\\', "/"))
                .unwrap_or_else(|_| chunk.name.to_string());
            manifest_entries.push(ManifestEntry {
                name: chunk.name.to_string(),
                file: chunk.filename.to_string(),
                src: src.clone(),
                is_entry: true,
                imports: chunk.imports.iter().map(|i| i.to_string()).collect(),
                css: Vec::new(),
            });
            for entry in &entries {
                let entry_abs = root.join(entry.trim_start_matches('/'));
                if Path::new(facade.as_ref()) == entry_abs.as_path() {
                    rewritten_html =
                        rewritten_html.replace(entry.as_str(), &with_base(&chunk.filename, &base));
                }
            }
        } else if let rolldown_common::Output::Asset(asset) = asset {
            emitted.push((asset.filename.to_string(), asset.source.as_bytes().len()));
        }
    }

    // Stylesheets and other <link href> statics are copied through as-is
    // (hashed CSS pipeline is future work).
    for href in link_hrefs(&html) {
        let src = root.join(href.trim_start_matches('/'));
        if src.is_file() {
            let dest = out_dir.join(href.trim_start_matches('/'));
            if let Some(parent) = dest.parent() {
                fs::create_dir_all(parent)?;
            }
            let source = fs::read_to_string(&src)?;
            if oj_server::sidecar::is_tailwind_css(&source) {
                // Expand via the CSS sidecar (postcss config / Tailwind v4).
                let css = expand_css_via_sidecar(&root, &src)?;
                let minified = oj_css::compile_css(href.as_str(), &css, true).map_err(|e| anyhow::anyhow!(e))?;
                fs::write(&dest, minified.css)?;
                continue;
            }
            fs::copy(&src, &dest)?;
        }
    }

    // Emit collected css (imports, incl. CSS Modules) as one stylesheet.
    let mut css_entries = collected_css.lock().unwrap().clone();
    if !css_entries.is_empty() {
        css_entries.sort();
        let combined: String =
            css_entries.into_iter().map(|(_, css)| css).collect::<Vec<_>>().join("\n");
        let hash = format!("{:016x}", {
            use std::hash::{Hash, Hasher};
            let mut h = std::collections::hash_map::DefaultHasher::new();
            combined.hash(&mut h);
            h.finish()
        });
        let css_name = format!("assets/style-{}.css", &hash[..8]);
        fs::create_dir_all(out_dir.join("assets"))?;
        fs::write(out_dir.join(&css_name), &combined)?;
        emitted.push((css_name.clone(), combined.len()));
        let link = format!("<link rel=\"stylesheet\" href=\"{}\" />", with_base(&css_name, &base));
        rewritten_html = match rewritten_html.find("</head>") {
            Some(idx) => format!("{}{}\n{}", &rewritten_html[..idx], link, &rewritten_html[idx..]),
            None => format!("{link}\n{rewritten_html}"),
        };
        // The app's css belongs to every entry (no per-entry css splitting yet).
        for entry in &mut manifest_entries {
            entry.css.push(css_name.clone());
        }
    }

    // Vite-compatible manifest for backend integrations (Laravel/Rails/etc.),
    // at the location their plugins expect: dist/.vite/manifest.json.
    fs::create_dir_all(out_dir.join(".vite"))?;
    fs::write(
        out_dir.join(".vite").join("manifest.json"),
        serde_json::to_string_pretty(&build_manifest(&manifest_entries))?,
    )?;

    // Plugin transformIndexHtml runs on the finished document.
    if let Some(host) = &plugin_host {
        if let Ok(out) = host.transform_index_html(&rewritten_html).await {
            rewritten_html = out;
        }
    }
    fs::write(out_dir.join("index.html"), rewritten_html)?;

    // Vite-style publicDir: copy the public dir (config/vite `publicDir`, else
    // <root>/public) verbatim to the output root (favicon.ico, robots.txt,
    // static assets). The dev server serves these live; the build must ship them.
    let public_dir = config.public_dir.as_ref().map(|p| root.join(p)).unwrap_or_else(|| root.join("public"));
    copy_public_dir(&public_dir, &out_dir)?;

    println!("oj build: {} in {:?}", out_dir.display(), started.elapsed());
    emitted.sort_by(|a, b| b.1.cmp(&a.1));
    for (name, bytes) in emitted.iter().take(12) {
        println!("  {:>9}  {}", human_bytes(*bytes), name);
    }
    if emitted.len() > 12 {
        println!("  … and {} more files", emitted.len() - 12);
    }
    Ok(())
}

fn human_bytes(bytes: usize) -> String {
    if bytes >= 1_048_576 {
        format!("{:.1}MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.1}kB", bytes as f64 / 1024.0)
    } else {
        format!("{bytes}B")
    }
}

fn module_script_srcs(html: &str) -> Vec<String> {
    scan_attrs(html, "<script", "src=\"")
        .into_iter()
        .filter(|src| src.starts_with('/'))
        .collect()
}

fn link_hrefs(html: &str) -> Vec<String> {
    scan_attrs(html, "<link", "href=\"")
        .into_iter()
        .filter(|href| href.starts_with('/'))
        .collect()
}

fn scan_attrs(html: &str, tag_prefix: &str, attr_prefix: &str) -> Vec<String> {
    let mut values = Vec::new();
    for (start, _) in html.match_indices(tag_prefix) {
        let Some(end) = html[start..].find('>') else { continue };
        let tag = &html[start..start + end];
        if tag_prefix == "<script" && !tag.contains("type=\"module\"") {
            continue;
        }
        if let Some(at) = tag.find(attr_prefix) {
            let rest = &tag[at + attr_prefix.len()..];
            if let Some(close) = rest.find('"') {
                values.push(rest[..close].to_string());
            }
        }
    }
    values
}

/// Build an SSR server bundle (`build.ssr` / `--ssr`): target Node, keep bare
/// dependencies external (Node resolves them at runtime), emit one ESM
/// `<stem>.mjs`. This is the server-build half of SSR; a dev-server SSR module
/// runner (Environment API) is separate, larger work.
pub(crate) async fn build_ssr(
    root: &Path,
    out_dir: &Path,
    entry: &str,
    sourcemap: bool,
) -> anyhow::Result<()> {
    use rolldown::{IsExternal, Platform};

    let entry_import = if entry.starts_with('.') { entry.to_string() } else { format!("./{entry}") };
    let stem =
        Path::new(entry).file_stem().and_then(|s| s.to_str()).unwrap_or("server").to_string();

    // The caller (`build_ssr_app`) owns wiping the shared out dir; just ensure
    // it exists so the server bundle can sit next to the client assets.
    fs::create_dir_all(out_dir)?;
    let started = Instant::now();
    let collected_css: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));

    // User plugins run in the SSR build as the "ssr" environment, so
    // resolveId/load/transform (and applyToEnvironment("ssr")) apply to server
    // modules, matching the dev SSR runner.
    let mut config = oj_config::load(root).map_err(|e| anyhow::anyhow!("{e}"))?;
    oj_server::plugins::adopt_vite_config_values(&mut config, root);
    let ssr_base = config.base.clone().unwrap_or_else(|| "/".into());
    let plugin_host = user_plugin_host(
        root,
        &ssr_base,
        &serde_json::json!(config.define),
        &serde_json::json!(config.environments),
        "ssr",
    )
    .await;

    // Externalize a module once it resolves into node_modules (Node requires
    // those at runtime); aliases (`@/…`) and relative imports resolve to
    // source and stay bundled.
    let external = IsExternal::Fn(Some(Arc::new(|spec: &str, _importer, is_resolved: bool| {
        let ext = is_resolved && spec.contains("node_modules");
        Box::pin(async move { Ok(ext) })
    })));

    let mut oj_plugins: Vec<SharedPluginable> = Vec::new();
    if let Some(host) = &plugin_host {
        if let Err(e) = host.build_start().await {
            eprintln!("oj build (ssr): plugin buildStart failed: {e}");
        }
        oj_plugins.push(Arc::new(OjUserPlugin::new(Arc::clone(host))));
    }
    oj_plugins.push(Arc::new(OjCssPlugin { collected: Arc::clone(&collected_css), root: root.to_path_buf(), has_postcss: oj_server::has_postcss_config(root), client: false }));
    let mut bundler = BundlerBuilder::default()
        .with_plugins(oj_plugins)
        .with_options(BundlerOptions {
            input: Some(vec![InputItem {
                name: Some(stem.clone()),
                import: entry_import,
                ..Default::default()
            }]),
            cwd: Some(root.to_path_buf()),
            dir: Some(out_dir.display().to_string()),
            resolve: rolldown_resolve(root, &config, "ssr"),
            platform: Some(Platform::Node),
            external: Some(external),
            format: Some(OutputFormat::Esm),
            entry_filenames: Some(format!("{stem}.mjs").into()),
            chunk_filenames: Some(format!("{stem}-[hash].mjs").into()),
            // Per-environment build output: "ssr" defaults to unminified but may
            // override minify/sourcemap (environments.ssr.build).
            minify: Some(RawMinifyOptions::Bool(
                oj_config::environment_build_bool(&config, "ssr", "minify").unwrap_or(false),
            )),
            sourcemap: oj_config::environment_build_bool(&config, "ssr", "sourcemap")
                .unwrap_or(sourcemap)
                .then_some(SourceMapType::File),
            define: Some({
                let mut pairs = vec![
                    ("process.env.NODE_ENV".to_string(), "'production'".to_string()),
                    ("import.meta.env.SSR".to_string(), "true".to_string()),
                    ("import.meta.env.PROD".to_string(), "true".to_string()),
                    ("import.meta.env.DEV".to_string(), "false".to_string()),
                    ("import.meta.env.MODE".to_string(), "\"production\"".to_string()),
                    ("import.meta.env.BASE_URL".to_string(), "\"/\"".to_string()),
                ];
                // config define + the "ssr" environment's define overrides.
                pairs.extend(oj_config::config_defines(&config));
                pairs.extend(oj_config::environment_defines(&config, "ssr"));
                pairs.into_iter().collect()
            }),
            ..Default::default()
        })
        .build()
        .map_err(|errs| anyhow::anyhow!("rolldown init failed: {errs:?}"))?;

    let output = bundler
        .write()
        .await
        .map_err(|errs| anyhow::anyhow!("ssr build failed:\n{errs:?}"))?;
    bundler.close().await.map_err(|errs| anyhow::anyhow!("ssr close failed:\n{errs:?}"))?;

    if let Some(host) = &plugin_host {
        if let Err(e) = host.build_end().await {
            eprintln!("oj build (ssr): plugin buildEnd failed: {e}");
        }
    }

    let mut emitted: Vec<(String, usize)> = Vec::new();
    for asset in &output.assets {
        if let rolldown_common::Output::Chunk(c) = asset {
            emitted.push((c.filename.to_string(), c.code.len()));
        }
    }
    println!("oj build (ssr): {} in {:?}", out_dir.display(), started.elapsed());
    emitted.sort_by(|a, b| b.1.cmp(&a.1));
    for (name, bytes) in &emitted {
        println!("  {:>9}  {}", human_bytes(*bytes), name);
    }
    Ok(())
}

/// Server-function dispatch module: globs the app's `*.server.*` modules (real
/// implementations) and calls the requested export. Bundled to
/// `<out>/_oj_server_fns.mjs` and imported by the production server.
const OJ_SERVER_FNS_JS: &str = r#"const mods = import.meta.glob("./src/**/*.server.*");
const norm = (s) => String(s).replace(/^\.?\/+/, "");
export async function dispatch(url, name, args) {
  const want = norm(url);
  const key = Object.keys(mods).find((k) => norm(k) === want);
  if (!key) throw new Error("oj: no server module " + url);
  const m = await mods[key]();
  const fn = name === "default" ? m.default : m[name];
  if (typeof fn !== "function") throw new Error("oj: no server function " + name + " in " + url);
  return fn(...(Array.isArray(args) ? args : []));
}
"#;

/// Whether the app has any `*.server.*` module under `src/` (so the production
/// build wires the server-function dispatch + client stubs).
fn has_server_modules(root: &Path) -> bool {
    fn walk(dir: &Path) -> bool {
        let Ok(entries) = fs::read_dir(dir) else { return false };
        for entry in entries.flatten() {
            let p = entry.path();
            if p.is_dir() {
                if walk(&p) {
                    return true;
                }
            } else if p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
                [".server.ts", ".server.tsx", ".server.js", ".server.jsx"].iter().any(|s| n.ends_with(s))
            }) {
                return true;
            }
        }
        false
    }
    walk(&root.join("src"))
}

/// Build the server-function dispatch bundle to `<out>/_oj_server_fns.mjs`
/// (node platform, node_modules external, real server code, not stubbed).
async fn build_server_fns(root: &Path, out_dir: &Path) -> anyhow::Result<()> {
    use rolldown::{IsExternal, Platform};
    let entry_path = root.join("_oj_server_fns_entry.tsx");
    fs::write(&entry_path, OJ_SERVER_FNS_JS)?;
    let collected: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
    let external = IsExternal::Fn(Some(Arc::new(|spec: &str, _i, resolved: bool| {
        let ext = resolved && spec.contains("node_modules");
        Box::pin(async move { Ok(ext) })
    })));
    let result = async {
        let mut bundler = BundlerBuilder::default()
            .with_plugins(vec![Arc::new(OjCssPlugin {
                collected: Arc::clone(&collected),
                root: root.to_path_buf(),
                has_postcss: oj_server::has_postcss_config(root),
                client: false, // server build: keep real server code
            })])
            .with_options(BundlerOptions {
                input: Some(vec![InputItem {
                    name: Some("_oj_server_fns".to_string()),
                    import: "./_oj_server_fns_entry.tsx".to_string(),
                    ..Default::default()
                }]),
                cwd: Some(root.to_path_buf()),
                dir: Some(out_dir.display().to_string()),
                platform: Some(Platform::Node),
                external: Some(external),
                format: Some(OutputFormat::Esm),
                entry_filenames: Some("_oj_server_fns.mjs".to_string().into()),
                chunk_filenames: Some("_oj_server_fns-[hash].mjs".to_string().into()),
                minify: Some(RawMinifyOptions::Bool(false)),
                define: Some(
                    vec![
                        ("process.env.NODE_ENV".to_string(), "'production'".to_string()),
                        ("import.meta.env.SSR".to_string(), "true".to_string()),
                    ]
                    .into_iter()
                    .collect(),
                ),
                ..Default::default()
            })
            .build()
            .map_err(|errs| anyhow::anyhow!("server-fns init failed: {errs:?}"))?;
        bundler.write().await.map_err(|errs| anyhow::anyhow!("server-fns build failed:\n{errs:?}"))?;
        bundler.close().await.map_err(|errs| anyhow::anyhow!("server-fns close failed:\n{errs:?}"))?;
        Ok::<(), anyhow::Error>(())
    }
    .await;
    let _ = fs::remove_file(&entry_path);
    result
}

/// One-shot prerender (SSG) script: render each configured path to static HTML
/// with the same shell the SSR server emits, so it hydrates. `__CLIENT_JS__` /
/// `__CLIENT_CSS__` are filled at build time; paths arrive as argv JSON. Run
/// with cwd = the output dir (so `./entry-server.mjs` resolves and files land).
const PRERENDER_JS: &str = r#"import * as entry from "./entry-server.mjs";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";

const CLIENT_JS = "__CLIENT_JS__";
const CLIENT_CSS = "__CLIENT_CSS__";
const serialize = (d) => JSON.stringify(d ?? null).replace(/</g, "\\u003c");
const paths = JSON.parse(process.argv[2] || "[]");
const root = process.cwd();

// Prefer draining renderStream fully: unlike renderToString it waits for every
// Suspense boundary to resolve, so the static HTML is complete and hydrates
// without a mismatch (React error #419). Falls back to render() if unavailable.
async function renderFull(url, data) {
  if (typeof entry.renderStream === "function") {
    const stream = await entry.renderStream(url, data);
    const reader = stream.getReader();
    const dec = new TextDecoder();
    let out = "";
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;
      out += dec.decode(value, { stream: true });
    }
    return out;
  }
  return await entry.render(url, data);
}

for (const url of paths) {
  const data = typeof entry.load === "function" ? await entry.load(url) : null;
  const routeHead = typeof entry.head === "function" ? String(await entry.head(url, data)) : "";
  const body = await renderFull(url, data);
  const html =
    '<!doctype html><html><head><meta charset="utf-8">' +
    routeHead +
    `<script>window.__OJ_DATA__=${serialize(data)}</script>` +
    (CLIENT_CSS ? `<link rel="stylesheet" href="${CLIENT_CSS}">` : "") +
    `<script type="module" src="${CLIENT_JS}"></script></head><body><div id="app">` +
    body +
    "</div></body></html>";
  const file = url === "/" ? "index.html" : join(url.replace(/^\/+/, ""), "index.html");
  const dest = join(root, file);
  await mkdir(dirname(dest), { recursive: true });
  await writeFile(dest, html);
  console.error(`oj prerender: ${url} -> ${file}`);
}
"#;

const SSR_PROD_SERVER: &str = r#"// Generated by `oj build --ssr`: streaming production SSR server.
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { dirname, join, normalize } from "node:path";
import * as entry from "./entry-server.mjs";
import { dispatch as __ojDispatch } from "./_oj_server_fns.mjs";

const root = dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || 5180;
const CLIENT_JS = "__CLIENT_JS__";
const CLIENT_CSS = "__CLIENT_CSS__";
const TAIL = "</div></body></html>";
const TYPES = { ".js": "text/javascript", ".css": "text/css", ".map": "application/json" };
const serialize = (data) => JSON.stringify(data ?? null).replace(/</g, "\\u003c");
const readBody = (req) =>
  new Promise((resolve) => {
    let b = "";
    req.on("data", (c) => (b += c));
    req.on("end", () => resolve(b));
  });

createServer(async (req, res) => {
  const url = req.url.split("?")[0];
  // Server functions: run the requested export server-side and return JSON.
  if (req.method === "POST" && url === "/__oj_fn") {
    try {
      const { module, name, args } = JSON.parse(await readBody(req));
      const result = await __ojDispatch(module, name, args);
      res.writeHead(200, { "content-type": "application/json" });
      return void res.end(JSON.stringify(result ?? null));
    } catch (e) {
      res.writeHead(500, { "content-type": "text/plain" });
      return void res.end(String((e && e.stack) || e));
    }
  }
  if (url.startsWith("/assets/")) {
    const file = normalize(join(root, url));
    if (!file.startsWith(root)) return void res.writeHead(403).end();
    try {
      const buf = await readFile(file);
      res.writeHead(200, { "content-type": TYPES[file.slice(file.lastIndexOf("."))] || "application/octet-stream" });
      return void res.end(buf);
    } catch {
      return void res.writeHead(404).end();
    }
  }
  try {
    const wantsData = Boolean(req.headers["oj-loader"]);
    const load = () => (typeof entry.load === "function" ? entry.load(url) : null);
    // Action (mutation): run it server-side, then revalidate. Compute before
    // writing headers so a throwing loader/action falls to the catch cleanly.
    if (req.method === "POST") {
      if (typeof entry.action === "function") await entry.action(url, await readBody(req));
      if (wantsData) {
        const body = serialize(await load());
        res.writeHead(200, { "content-type": "application/json" });
        return void res.end(body);
      }
      // No-JS form: redirect so the browser re-GETs the updated document.
      return void res.writeHead(303, { location: url }).end();
    }
    // Client data fetch for a navigation.
    if (wantsData) {
      const body = serialize(await load());
      res.writeHead(200, { "content-type": "application/json" });
      return void res.end(body);
    }
    const data = await load();
    const json = serialize(data);
    const routeHead = typeof entry.head === "function" ? String(await entry.head(url, data)) : "";
    const HEAD =
      '<!doctype html><html><head><meta charset="utf-8">' +
      routeHead +
      `<script>window.__OJ_DATA__=${json}</script>` +
      (CLIENT_CSS ? `<link rel="stylesheet" href="${CLIENT_CSS}">` : "") +
      `<script type="module" src="${CLIENT_JS}"></script></head><body><div id="app">`;
    const stream = await entry.renderStream(url, data);
    res.writeHead(200, { "content-type": "text/html; charset=utf-8", "transfer-encoding": "chunked" });
    res.write(HEAD);
    const reader = stream.getReader();
    const dec = new TextDecoder();
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;
      res.write(dec.decode(value, { stream: true }));
    }
    res.write(TAIL);
    res.end();
  } catch (e) {
    res.writeHead(500, { "content-type": "text/html" }).end(`<pre>${String((e && e.stack) || e)}</pre>`);
  }
}).listen(PORT, () => console.log(`oj ssr server on http://localhost:${PORT}`));
"#;

/// Generated by `oj build --ssr`: an edge/worker SSR entry, a Web-standard
/// `fetch` handler (Request/Response/ReadableStream, no `node:*`) for a
/// Cloudflare-Workers / `workerd`-style runtime. Static assets are served by
/// the platform; this handles SSR, loaders/actions, and server functions.
/// `__CLIENT_JS__` / `__CLIENT_CSS__` are filled at build time.
const SSR_WORKER_ENTRY: &str = r#"import * as entry from "./entry-server.mjs";
import { dispatch as __ojDispatch } from "./_oj_server_fns.mjs";

const CLIENT_JS = "__CLIENT_JS__";
const CLIENT_CSS = "__CLIENT_CSS__";
const serialize = (d) => JSON.stringify(d ?? null).replace(/</g, "\\u003c");
const enc = new TextEncoder();

export default {
  async fetch(request) {
    const url = new URL(request.url).pathname;
    // Server functions.
    if (request.method === "POST" && url === "/__oj_fn") {
      try {
        const { module, name, args } = await request.json();
        return Response.json(await __ojDispatch(module, name, args));
      } catch (e) {
        return new Response(String((e && e.stack) || e), { status: 500 });
      }
    }
    const wantsData = Boolean(request.headers.get("oj-loader"));
    const load = () => (typeof entry.load === "function" ? entry.load(url) : null);
    if (request.method === "POST") {
      if (typeof entry.action === "function") await entry.action(url, await request.text());
      if (wantsData) return Response.json(await load());
      return new Response(null, { status: 303, headers: { location: url } });
    }
    if (wantsData) return Response.json(await load());
    // Document: stream the shell + render + tail.
    const data = await load();
    const routeHead = typeof entry.head === "function" ? String(await entry.head(url, data)) : "";
    const HEAD =
      '<!doctype html><html><head><meta charset="utf-8">' +
      routeHead +
      `<script>window.__OJ_DATA__=${serialize(data)}</script>` +
      (CLIENT_CSS ? `<link rel="stylesheet" href="${CLIENT_CSS}">` : "") +
      `<script type="module" src="${CLIENT_JS}"></script></head><body><div id="app">`;
    const stream = await entry.renderStream(url, data);
    const body = new ReadableStream({
      async start(controller) {
        controller.enqueue(enc.encode(HEAD));
        const reader = stream.getReader();
        for (;;) {
          const { done, value } = await reader.read();
          if (done) break;
          controller.enqueue(value);
        }
        controller.enqueue(enc.encode("</div></body></html>"));
        controller.close();
      },
    });
    return new Response(body, { headers: { "content-type": "text/html; charset=utf-8" } });
  },
};
"#;

/// Derive the client hydration entry from the SSR entry by convention: swap
/// "server" for "client" in the filename (`entry-server.tsx` becomes
/// `entry-client.tsx`), if that sibling file exists.
pub(crate) fn derive_client_entry(root: &Path, server_entry: &str) -> Option<String> {
    let file = Path::new(server_entry).file_name()?.to_str()?;
    if !file.contains("server") {
        return None;
    }
    let client_file = file.replace("server", "client");
    let client_rel = match Path::new(server_entry).parent() {
        Some(dir) if !dir.as_os_str().is_empty() => format!("{}/{}", dir.to_string_lossy(), client_file),
        _ => client_file,
    };
    root.join(&client_rel).is_file().then_some(client_rel)
}

/// Full production SSR build: the Node server bundle, a browser client bundle
/// for hydration (from the sibling `*-client.*` entry), and a streaming
/// `server.mjs` that ties them together. Without a client entry, only the
/// server bundle is emitted (no runnable server, nothing to hydrate).
pub(crate) async fn build_ssr_app(
    root: &Path,
    out_dir: &Path,
    entry: &str,
    minify: bool,
    sourcemap: bool,
    prerender: Option<Vec<String>>,
) -> anyhow::Result<()> {
    let _ = fs::remove_dir_all(out_dir);
    fs::create_dir_all(out_dir)?;

    build_ssr(root, out_dir, entry, sourcemap).await?;

    let Some(client_entry) = derive_client_entry(root, entry) else {
        println!("oj build (ssr): server bundle only (no *-client sibling to hydrate)");
        return Ok(());
    };
    let (js, css) = build_client_entry(root, out_dir, &client_entry, minify, sourcemap).await?;

    // Server functions: the client bundle above stubbed `*.server.*` modules;
    // this bundles their real implementations into a dispatch the server runs.
    // Always built so server.mjs's import resolves (an empty dispatch is inert).
    build_server_fns(root, out_dir).await?;
    if has_server_modules(root) {
        println!("  {:>9}  _oj_server_fns.mjs", human_bytes(OJ_SERVER_FNS_JS.len()));
    }

    let server = SSR_PROD_SERVER
        .replace("__CLIENT_JS__", &js)
        .replace("__CLIENT_CSS__", css.as_deref().unwrap_or(""));
    fs::write(out_dir.join("server.mjs"), server)?;
    println!("  {:>9}  server.mjs", human_bytes(SSR_PROD_SERVER.len()));

    // Edge/worker entry alongside the Node server: a Web `fetch` handler for a
    // Workers-style runtime (assets served by the platform).
    let worker = SSR_WORKER_ENTRY
        .replace("__CLIENT_JS__", &js)
        .replace("__CLIENT_CSS__", css.as_deref().unwrap_or(""));
    fs::write(out_dir.join("worker.mjs"), worker)?;
    println!("  {:>9}  worker.mjs (edge)", human_bytes(SSR_WORKER_ENTRY.len()));

    // Prerender (SSG): render each configured path to static HTML, hydrated by
    // the same client bundle. A one-shot node run over the server bundle.
    if let Some(paths) = prerender.filter(|p| !p.is_empty()) {
        let script = PRERENDER_JS
            .replace("__CLIENT_JS__", &js)
            .replace("__CLIENT_CSS__", css.as_deref().unwrap_or(""));
        let script_path = out_dir.join("_oj_prerender.mjs");
        fs::write(&script_path, script)?;
        let out = std::process::Command::new("node")
            .arg(&script_path)
            .arg(serde_json::to_string(&paths)?)
            .current_dir(out_dir)
            .output()
            .context("node not found for prerender")?;
        let _ = fs::remove_file(&script_path);
        if !out.status.success() {
            bail!("prerender failed: {}", String::from_utf8_lossy(&out.stderr));
        }
        for line in String::from_utf8_lossy(&out.stderr).lines() {
            println!("  {line}");
        }
    }
    println!("  run: node {}", out_dir.join("server.mjs").display());
    Ok(())
}

/// Bundle one browser entry (prod, hashed, minified) into `<out>/assets`,
/// returning the entry's `/assets/<name>-<hash>.js` url and an optional
/// `/assets/style-<hash>.css` url for the collected CSS. Used to build the
/// client hydration bundle for a production SSR app.
async fn build_client_entry(
    root: &Path,
    out_dir: &Path,
    entry: &str,
    minify: bool,
    sourcemap: bool,
) -> anyhow::Result<(String, Option<String>)> {
    let entry_import = if entry.starts_with('.') { entry.to_string() } else { format!("./{entry}") };
    let stem = Path::new(entry).file_stem().and_then(|s| s.to_str()).unwrap_or("client").to_string();
    let collected_css: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));

    // User plugins run in the client hydration bundle as the "client"
    // environment (matching the dev client pipeline), so a shared module can
    // use plugin resolveId/load/transform on both the server and client sides.
    let mut config = oj_config::load(root).map_err(|e| anyhow::anyhow!("{e}"))?;
    oj_server::plugins::adopt_vite_config_values(&mut config, root);
    let client_base = config.base.clone().unwrap_or_else(|| "/".into());
    let plugin_host = user_plugin_host(
        root,
        &client_base,
        &serde_json::json!(config.define),
        &serde_json::json!(config.environments),
        "client",
    )
    .await;
    let mut oj_plugins: Vec<SharedPluginable> = Vec::new();
    if let Some(host) = &plugin_host {
        if let Err(e) = host.build_start().await {
            eprintln!("oj build (client): plugin buildStart failed: {e}");
        }
        oj_plugins.push(Arc::new(OjUserPlugin::new(Arc::clone(host))));
    }
    oj_plugins.push(Arc::new(OjCssPlugin { collected: Arc::clone(&collected_css), root: root.to_path_buf(), has_postcss: oj_server::has_postcss_config(root), client: true }));

    let mut bundler = BundlerBuilder::default()
        .with_plugins(oj_plugins)
        .with_options(BundlerOptions {
            input: Some(vec![InputItem { name: Some(stem), import: entry_import, ..Default::default() }]),
            cwd: Some(root.to_path_buf()),
            dir: Some(out_dir.display().to_string()),
            resolve: rolldown_resolve(root, &config, "client"),
            entry_filenames: Some("assets/[name]-[hash].js".to_string().into()),
            chunk_filenames: Some("assets/[name]-[hash].js".to_string().into()),
            // Per-environment build output for the "client" hydration bundle.
            minify: Some(RawMinifyOptions::Bool(
                oj_config::environment_build_bool(&config, "client", "minify").unwrap_or(minify),
            )),
            sourcemap: oj_config::environment_build_bool(&config, "client", "sourcemap")
                .unwrap_or(sourcemap)
                .then_some(SourceMapType::File),
            define: Some({
                let env = oj_env::load(root, "production");
                let mut pairs =
                    vec![("process.env.NODE_ENV".to_string(), "'production'".to_string())];
                pairs.extend(oj_env::import_meta_env_defines(&env, "production", false, "/", "VITE_"));
                // client hydration bundle: config + "client" environment define.
                pairs.extend(oj_config::config_defines(&config));
                pairs.extend(oj_config::environment_defines(&config, "client"));
                pairs.into_iter().collect()
            }),
            ..Default::default()
        })
        .build()
        .map_err(|errs| anyhow::anyhow!("rolldown init failed: {errs:?}"))?;

    let output = bundler
        .write()
        .await
        .map_err(|errs| anyhow::anyhow!("client build failed:\n{errs:?}"))?;
    bundler.close().await.map_err(|errs| anyhow::anyhow!("client close failed:\n{errs:?}"))?;

    if let Some(host) = &plugin_host {
        if let Err(e) = host.build_end().await {
            eprintln!("oj build (client): plugin buildEnd failed: {e}");
        }
    }

    let mut js = None;
    for asset in &output.assets {
        if let rolldown_common::Output::Chunk(c) = asset {
            if c.is_entry {
                js = Some(format!("/{}", c.filename));
            }
        }
    }
    let js = js.ok_or_else(|| anyhow::anyhow!("client build produced no entry chunk"))?;

    // Emit collected CSS (incl. CSS Modules) as one hashed stylesheet.
    let mut css_entries = collected_css.lock().unwrap().clone();
    let css = if css_entries.is_empty() {
        None
    } else {
        css_entries.sort();
        let combined: String =
            css_entries.into_iter().map(|(_, css)| css).collect::<Vec<_>>().join("\n");
        let hash = format!("{:016x}", {
            use std::hash::{Hash, Hasher};
            let mut h = std::collections::hash_map::DefaultHasher::new();
            combined.hash(&mut h);
            h.finish()
        });
        let name = format!("assets/style-{}.css", &hash[..8]);
        fs::write(out_dir.join(&name), combined)?;
        Some(format!("/{name}"))
    };
    Ok((js, css))
}

/// Build a library (`build.lib`): one Rolldown pass per output format,
/// emitting `<fileName>.<ext>` files plus a single stylesheet for any
/// imported CSS. No HTML, no manifest.
async fn build_library(
    root: &Path,
    out_dir: &Path,
    lib: oj_config::LibConfig,
    minify: bool,
    sourcemap: bool,
) -> anyhow::Result<()> {
    let entry_import = if lib.entry.starts_with('.') {
        lib.entry.clone()
    } else {
        format!("./{}", lib.entry)
    };
    let file_name = lib.file_name.clone().unwrap_or_else(|| {
        Path::new(&lib.entry)
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("index")
            .to_string()
    });
    let formats = lib.formats.clone().unwrap_or_else(|| vec!["es".into()]);

    let _ = fs::remove_dir_all(out_dir);
    fs::create_dir_all(out_dir)?;
    let started = Instant::now();
    let collected_css: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
    let mut emitted: Vec<(String, usize)> = Vec::new();

    for fmt in &formats {
        let (ext, needs_name) = lib_format(fmt)
            .ok_or_else(|| anyhow::anyhow!("unknown lib format: {fmt} (es, cjs, umd, iife)"))?;
        let format = match fmt.as_str() {
            "es" | "esm" => OutputFormat::Esm,
            "cjs" => OutputFormat::Cjs,
            "umd" => OutputFormat::Umd,
            _ => OutputFormat::Iife,
        };
        if needs_name && lib.name.is_none() {
            bail!("build.lib.name is required for the '{fmt}' format");
        }

        let mut bundler = BundlerBuilder::default()
            .with_plugins(vec![Arc::new(OjCssPlugin { collected: Arc::clone(&collected_css), root: root.to_path_buf(), has_postcss: oj_server::has_postcss_config(root), client: true })])
            .with_options(BundlerOptions {
                input: Some(vec![InputItem {
                    name: Some(file_name.clone()),
                    import: entry_import.clone(),
                    ..Default::default()
                }]),
                cwd: Some(root.to_path_buf()),
                dir: Some(out_dir.display().to_string()),
                format: Some(format),
                name: lib.name.clone(),
                entry_filenames: Some(format!("{file_name}.{ext}").into()),
                chunk_filenames: Some(format!("{file_name}-[hash].{ext}").into()),
                minify: Some(RawMinifyOptions::Bool(minify)),
                sourcemap: sourcemap.then_some(SourceMapType::File),
                define: Some(
                    std::iter::once(("process.env.NODE_ENV".to_string(), "'production'".to_string()))
                        .collect(),
                ),
                ..Default::default()
            })
            .build()
            .map_err(|errs| anyhow::anyhow!("rolldown init failed: {errs:?}"))?;

        let output = bundler
            .write()
            .await
            .map_err(|errs| anyhow::anyhow!("lib build ({fmt}) failed:\n{errs:?}"))?;
        for asset in &output.assets {
            if let rolldown_common::Output::Chunk(c) = asset {
                emitted.push((c.filename.to_string(), c.code.len()));
            }
        }
    }

    // One stylesheet for any CSS the library imported.
    let css_entries = collected_css.lock().unwrap().clone();
    if !css_entries.is_empty() {
        let combined: String =
            css_entries.into_iter().map(|(_, css)| css).collect::<Vec<_>>().join("\n");
        let css_name = format!("{file_name}.css");
        fs::write(out_dir.join(&css_name), &combined)?;
        emitted.push((css_name, combined.len()));
    }

    println!("oj build (library): {} in {:?}", out_dir.display(), started.elapsed());
    emitted.sort_by(|a, b| b.1.cmp(&a.1));
    emitted.dedup();
    for (name, bytes) in &emitted {
        println!("  {:>9}  {}", human_bytes(*bytes), name);
    }
    Ok(())
}

/// Map a lib format name to its (file extension, needs-a-global-name) pair.
fn lib_format(fmt: &str) -> Option<(&'static str, bool)> {
    match fmt {
        "es" | "esm" => Some(("js", false)),
        "cjs" => Some(("cjs", false)),
        "umd" => Some(("umd.js", true)),
        "iife" => Some(("iife.js", true)),
        _ => None,
    }
}

/// Normalize a public base path to a leading+trailing-slash form
/// (`"/"`, `"/app/"`). Empty/relative bases fall back to `"/"`.
fn normalize_base(base: &str) -> String {
    if base.is_empty() || base == "./" {
        return "/".to_string();
    }
    let mut b = base.to_string();
    if !b.starts_with('/') {
        b.insert(0, '/');
    }
    if !b.ends_with('/') {
        b.push('/');
    }
    b
}

/// Prefix an emitted asset filename (e.g. `assets/x-hash.js`) with the base.
fn with_base(filename: &str, base: &str) -> String {
    format!("{base}{}", filename.trim_start_matches('/'))
}

/// One entry in the Vite-compatible build manifest.
struct ManifestEntry {
    name: String,
    file: String,
    src: String,
    is_entry: bool,
    imports: Vec<String>,
    css: Vec<String>,
}

/// Build a Vite-compatible `manifest.json` value: keyed by root-relative
/// source path, each row carrying the emitted file plus name/isEntry/imports/
/// css. The shape Laravel/Rails/Django Vite plugins consume.
fn build_manifest(entries: &[ManifestEntry]) -> serde_json::Value {
    let mut map = serde_json::Map::new();
    for e in entries {
        let mut row = serde_json::Map::new();
        row.insert("file".into(), e.file.clone().into());
        row.insert("name".into(), e.name.clone().into());
        row.insert("src".into(), e.src.clone().into());
        if e.is_entry {
            row.insert("isEntry".into(), true.into());
        }
        if !e.imports.is_empty() {
            row.insert("imports".into(), e.imports.clone().into());
        }
        if !e.css.is_empty() {
            row.insert("css".into(), e.css.clone().into());
        }
        map.insert(e.src.clone(), serde_json::Value::Object(row));
    }
    serde_json::Value::Object(map)
}

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

    #[test]
    fn manifest_matches_vite_shape() {
        let m = build_manifest(&[ManifestEntry {
            name: "main".into(),
            file: "assets/main-abc123.js".into(),
            src: "src/main.tsx".into(),
            is_entry: true,
            imports: vec!["assets/vendor-def456.js".into()],
            css: vec!["assets/style-99.css".into()],
        }]);
        let row = &m["src/main.tsx"];
        assert_eq!(row["file"], "assets/main-abc123.js");
        assert_eq!(row["name"], "main");
        assert_eq!(row["src"], "src/main.tsx");
        assert_eq!(row["isEntry"], true);
        assert_eq!(row["imports"][0], "assets/vendor-def456.js");
        assert_eq!(row["css"][0], "assets/style-99.css");
    }

    #[test]
    fn non_entry_omits_isentry_and_empty_fields() {
        let m = build_manifest(&[ManifestEntry {
            name: "chunk".into(),
            file: "assets/chunk-1.js".into(),
            src: "chunk".into(),
            is_entry: false,
            imports: vec![],
            css: vec![],
        }]);
        let row = m["chunk"].as_object().unwrap();
        assert!(!row.contains_key("isEntry"));
        assert!(!row.contains_key("imports"));
        assert!(!row.contains_key("css"));
    }

    #[test]
    fn lib_format_mapping() {
        assert_eq!(lib_format("es"), Some(("js", false)));
        assert_eq!(lib_format("esm"), Some(("js", false)));
        assert_eq!(lib_format("cjs"), Some(("cjs", false)));
        assert_eq!(lib_format("umd"), Some(("umd.js", true)));
        assert_eq!(lib_format("iife"), Some(("iife.js", true)));
        assert_eq!(lib_format("amd"), None);
    }

    #[test]
    fn base_normalization_and_application() {
        assert_eq!(normalize_base("/"), "/");
        assert_eq!(normalize_base(""), "/");
        assert_eq!(normalize_base("./"), "/");
        assert_eq!(normalize_base("app"), "/app/");
        assert_eq!(normalize_base("/app"), "/app/");
        assert_eq!(normalize_base("/app/"), "/app/");
        assert_eq!(with_base("assets/x-h.js", "/"), "/assets/x-h.js");
        assert_eq!(with_base("assets/x-h.js", "/app/"), "/app/assets/x-h.js");
    }

    #[test]
    fn module_script_srcs_only_module_type_absolute() {
        let html = r#"<script type="module" src="/src/main.tsx"></script>
                      <script src="/legacy.js"></script>
                      <script type="module" src="https://cdn/x.js"></script>"#;
        let srcs = module_script_srcs(html);
        assert_eq!(srcs, vec!["/src/main.tsx"]);
    }

    #[test]
    fn is_server_module_path_matches_server_suffixes() {
        for yes in ["api.server.ts", "a/b/auth.server.tsx", "x.server.js", "y.server.jsx"] {
            assert!(is_server_module_path(yes), "{yes} should be a server module");
        }
        for no in ["api.ts", "server.ts", "api.server.css", "a.serverx.ts", "note.server.md"] {
            assert!(!is_server_module_path(no), "{no} should not be a server module");
        }
    }

    #[test]
    fn server_fn_prod_stub_emits_an_rpc_per_export() {
        let out = server_fn_prod_stub(&["getUser".into(), "default".into()], "/api.server.ts");
        assert!(out.contains("const __ojCall ="), "the fetch helper is inlined: {out}");
        assert!(
            out.contains(r#"export const getUser = (...a) => __ojCall("/api.server.ts", "getUser", a);"#),
            "named export stub: {out}"
        );
        assert!(
            out.contains(r#"export default (...a) => __ojCall("/api.server.ts", "default", a);"#),
            "default export stub: {out}"
        );
        // with no exports, only the helper is emitted (no export statements)
        let empty = server_fn_prod_stub(&[], "/x.server.ts");
        assert!(empty.contains("__ojCall"));
        assert!(!empty.contains("export "), "no exports means no stubs: {empty}");
    }

    #[test]
    fn human_bytes_scales_by_threshold() {
        assert_eq!(human_bytes(0), "0B");
        assert_eq!(human_bytes(512), "512B");
        assert_eq!(human_bytes(1023), "1023B");
        assert_eq!(human_bytes(1024), "1.0kB");
        assert_eq!(human_bytes(1536), "1.5kB");
        assert_eq!(human_bytes(1_048_575), "1024.0kB"); // just below the MB threshold
        assert_eq!(human_bytes(1_048_576), "1.0MB");
        assert_eq!(human_bytes(3_145_728), "3.0MB");
    }

    #[test]
    fn link_hrefs_collects_only_absolute_hrefs() {
        let html = r#"<html><head>
          <link rel="stylesheet" href="/assets/app.css">
          <link rel="icon" href="favicon.ico">
          <link rel="modulepreload" href="/assets/chunk.js">
        </head></html>"#;
        let hrefs = link_hrefs(html);
        assert!(hrefs.contains(&"/assets/app.css".to_string()), "{hrefs:?}");
        assert!(hrefs.contains(&"/assets/chunk.js".to_string()), "{hrefs:?}");
        assert!(!hrefs.iter().any(|h| h.contains("favicon")), "relative href filtered: {hrefs:?}");
    }
}