node-app-build 7.7.66

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
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
use assert_cmd::Command;
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};

fn fixture_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/client-node-stage")
}

fn copy_tree(src: &Path, dst: &Path) {
    fs::create_dir_all(dst).unwrap();
    for entry in fs::read_dir(src).unwrap() {
        let entry = entry.unwrap();
        let source = entry.path();
        let dest = dst.join(entry.file_name());
        if entry.file_type().unwrap().is_dir() {
            copy_tree(&source, &dest);
        } else {
            fs::copy(&source, &dest).unwrap();
        }
    }
}

fn sha256_hex(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    format!("{:x}", hasher.finalize())
}

fn collect_relative_files(root: &Path) -> Vec<String> {
    fn walk(root: &Path, cursor: &Path, out: &mut Vec<String>) {
        for entry in fs::read_dir(cursor).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();
            if entry.file_type().unwrap().is_dir() {
                walk(root, &path, out);
            } else {
                let rel = path
                    .strip_prefix(root)
                    .unwrap()
                    .to_string_lossy()
                    .replace('\\', "/");
                out.push(rel);
            }
        }
    }

    let mut files = Vec::new();
    walk(root, root, &mut files);
    files.sort();
    files
}

fn balanced_braced_segment(text: &str, open_index: usize) -> (&str, usize) {
    let mut depth = 0_u32;
    for (offset, character) in text[open_index..].char_indices() {
        match character {
            '{' => depth += 1,
            '}' => {
                depth = depth
                    .checked_sub(1)
                    .expect("closing brace must follow an opening brace");
                if depth == 0 {
                    let end = open_index + offset + character.len_utf8();
                    return (&text[open_index..end], end);
                }
            }
            _ => {}
        }
    }
    panic!("unclosed type expression starting at byte {open_index}");
}

fn jsdoc_type_expression(path: &Path, type_name: &str) -> String {
    let text = fs::read_to_string(path).unwrap();
    for (marker_index, _) in text.match_indices("@typedef {") {
        let open_index = marker_index + "@typedef ".len();
        let (expression, end) = balanced_braced_segment(&text, open_index);
        let declared_name = text[end..]
            .trim_start_matches(|character: char| {
                character.is_whitespace() || character == '*' || character == '/'
            })
            .split_whitespace()
            .next();
        if declared_name == Some(type_name) {
            let mut uncommented = String::new();
            for line in expression[1..expression.len() - 1].lines() {
                let trimmed = line.trim_start();
                uncommented.push_str(trimmed.strip_prefix('*').unwrap_or(trimmed));
            }
            return canonical_type_expression(&uncommented);
        }
    }
    panic!(
        "missing JSDoc typedef {type_name} in {}",
        path.to_string_lossy()
    );
}

fn declaration_type_expression(path: &Path, type_name: &str) -> String {
    let text = fs::read_to_string(path).unwrap();
    let interface_marker = format!("export interface {type_name}");
    if let Some((marker_index, _)) = text
        .match_indices(&interface_marker)
        .find(|(marker_index, _)| {
            matches!(
                text[marker_index + interface_marker.len()..].chars().next(),
                Some(character) if character.is_whitespace() || character == '{'
            )
        })
    {
        let open_index = text[marker_index + interface_marker.len()..]
            .find('{')
            .map(|offset| marker_index + interface_marker.len() + offset)
            .unwrap_or_else(|| panic!("missing body for {interface_marker}"));
        let (expression, _) = balanced_braced_segment(&text, open_index);
        return canonical_type_expression(expression);
    }

    let type_marker = format!("export type {type_name} =");
    if let Some(marker_index) = text.find(&type_marker) {
        let expression_start = marker_index + type_marker.len();
        let mut braces = 0_u32;
        let mut brackets = 0_u32;
        let mut parentheses = 0_u32;
        for (offset, character) in text[expression_start..].char_indices() {
            match character {
                '{' => braces += 1,
                '}' => braces = braces.checked_sub(1).expect("balanced type braces"),
                '[' => brackets += 1,
                ']' => brackets = brackets.checked_sub(1).expect("balanced type brackets"),
                '(' => parentheses += 1,
                ')' => {
                    parentheses = parentheses
                        .checked_sub(1)
                        .expect("balanced type parentheses")
                }
                ';' if braces == 0 && brackets == 0 && parentheses == 0 => {
                    let end = expression_start + offset;
                    return canonical_type_expression(&text[expression_start..end]);
                }
                _ => {}
            }
        }
        panic!("unterminated declaration for {type_marker}");
    }

    panic!(
        "missing exported declaration {type_name} in {}",
        path.to_string_lossy()
    );
}

fn canonical_type_expression(expression: &str) -> String {
    expression
        .replace("import(\"@econ-v1/domain\").", "")
        .replace("import(\"./client.js\").", "")
        .chars()
        .filter(|character| !character.is_whitespace() && *character != ',' && *character != ';')
        .collect()
}

#[test]
fn stage_scaffold_preserves_the_last_valid_manifest_when_an_asset_is_missing() {
    let temp = tempfile::tempdir().unwrap();
    let project = temp.path().join("demo");
    Command::cargo_bin("node-app")
        .unwrap()
        .args(["new", "demo", "--profile", "stage", "--out"])
        .arg(&project)
        .assert()
        .success();

    let manifest_path = project.join("manifest.json");
    let mut manifest: Value = serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap();
    manifest["ui"]["deferred"] = serde_json::json!(["ui/dist/lazy.js"]);
    fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();
    let ui = project.join("ui");
    let dist = ui.join("dist");
    fs::create_dir(&dist).unwrap();
    let assets = ["main.js", "icon.svg", "lazy.js"];
    for asset in assets {
        fs::write(dist.join(asset), asset).unwrap();
    }

    let stamp = || {
        let mut cmd = Command::new("bun");
        cmd.current_dir(&ui).arg("scripts/stamp-integrity.mjs");
        cmd
    };
    stamp().assert().success();
    let last_valid = fs::read(&manifest_path).unwrap();
    let stamped: Value = serde_json::from_slice(&last_valid).unwrap();
    for asset in assets {
        assert_eq!(
            stamped["ui"]["integrity"][format!("ui/dist/{asset}")],
            sha256_hex(asset.as_bytes())
        );
        fs::remove_file(dist.join(asset)).unwrap();
        stamp().assert().failure();
        assert_eq!(
            fs::read(&manifest_path).unwrap(),
            last_valid,
            "missing {asset}"
        );
        fs::write(dist.join(asset), asset).unwrap();
    }
}

#[test]
fn package_stages_stage_ui_with_generated_integrity_and_no_typescript() {
    let fixture = fixture_root();
    let temp = tempfile::tempdir().unwrap();
    let project = temp.path().join("client-node-stage");
    copy_tree(&fixture, &project);

    let source_manifest_before = fs::read(project.join("manifest.json")).unwrap();
    let source_manifest_json: Value = serde_json::from_slice(&source_manifest_before).unwrap();
    let source_integrity = source_manifest_json["ui"].get("integrity");
    assert!(
        source_integrity.is_none()
            || source_integrity
                .and_then(|value| value.as_object())
                .map(|map| map.is_empty())
                .unwrap_or(false),
        "source manifest must not ship generated integrity: {source_manifest_json:#}"
    );

    Command::cargo_bin("node-app")
        .unwrap()
        .current_dir(temp.path())
        .args(["build", "--path"])
        .arg("client-node-stage")
        .assert()
        .success();

    let out_dir = temp.path().join("out");
    Command::cargo_bin("node-app")
        .unwrap()
        .current_dir(temp.path())
        .env("NODE_APP_PACKAGE_STAGE_ONLY", "1")
        .args(["package", "--path"])
        .arg("client-node-stage")
        .args(["--out"])
        .arg(&out_dir)
        .assert()
        .success();

    assert_eq!(
        source_manifest_before,
        fs::read(project.join("manifest.json")).unwrap()
    );

    let app_root = out_dir.join("staging/usr/lib/node/apps/client-node-stage");
    let triggers = fs::read_to_string(out_dir.join("staging/DEBIAN/triggers")).unwrap();
    assert_eq!(triggers, "activate-noawait /usr/share/node/triggers/apps\n");
    assert!(!triggers.contains("interest-noawait"));
    assert!(!out_dir.join("staging/DEBIAN/triggered").exists());
    Command::cargo_bin("node-app")
        .unwrap()
        .args(["validate", "--path"])
        .arg(&app_root)
        .assert()
        .success();
    let staged_manifest: Value =
        serde_json::from_slice(&fs::read(app_root.join("manifest.json")).unwrap()).unwrap();
    let integrity: BTreeMap<String, String> =
        serde_json::from_value(staged_manifest["ui"]["integrity"].clone()).unwrap();

    let staged_files = collect_relative_files(&app_root);
    assert!(
        staged_files.iter().all(|path| !path.ends_with(".ts")),
        "staged files should not contain TypeScript sources: {staged_files:?}"
    );
    assert!(
        integrity.len() >= 2,
        "expected entry/icon integrity plus any emitted assets, got {integrity:?}"
    );

    for (relative_path, expected_digest) in &integrity {
        let bytes = fs::read(app_root.join(relative_path)).unwrap();
        assert_eq!(
            sha256_hex(&bytes),
            *expected_digest,
            "digest mismatch for {relative_path}"
        );
    }

    let entry_path = staged_manifest["ui"]["entry"].as_str().unwrap();
    let mut mutated = fs::read(app_root.join(entry_path)).unwrap();
    mutated[0] ^= 0b0000_0001;
    assert_ne!(
        sha256_hex(&mutated),
        integrity.get(entry_path).unwrap().as_str(),
        "mutating one byte should invalidate the published digest"
    );
}

#[test]
fn package_stores_a_gzip_sibling_for_the_stage_entry() {
    let fixture = fixture_root();
    let temp = tempfile::tempdir().unwrap();
    let project = temp.path().join("client-node-stage");
    copy_tree(&fixture, &project);

    Command::cargo_bin("node-app")
        .unwrap()
        .current_dir(temp.path())
        .args(["build", "--path"])
        .arg("client-node-stage")
        .assert()
        .success();

    let out_dir = temp.path().join("out");
    Command::cargo_bin("node-app")
        .unwrap()
        .current_dir(temp.path())
        .env("NODE_APP_PACKAGE_STAGE_ONLY", "1")
        .args(["package", "--path"])
        .arg("client-node-stage")
        .args(["--out"])
        .arg(&out_dir)
        .assert()
        .success();

    let app_root = out_dir.join("staging/usr/lib/node/apps/client-node-stage");
    Command::cargo_bin("node-app")
        .unwrap()
        .args(["validate", "--path"])
        .arg(&app_root)
        .assert()
        .success();
    let staged_manifest: Value =
        serde_json::from_slice(&fs::read(app_root.join("manifest.json")).unwrap()).unwrap();
    let entry = staged_manifest["ui"]["entry"].as_str().unwrap();
    let raw = fs::read(app_root.join(entry)).unwrap();
    let sibling = fs::read(app_root.join(format!("{entry}.gz"))).unwrap();
    assert!(sibling.len() < raw.len(), "the sibling must be smaller");
    let mut decoded = Vec::new();
    flate2::read::GzDecoder::new(sibling.as_slice())
        .read_to_end(&mut decoded)
        .unwrap();
    assert_eq!(decoded, raw);

    let integrity = staged_manifest["ui"]["integrity"].as_object().unwrap();
    assert!(integrity.contains_key(entry));
    assert!(
        integrity.keys().all(|path| !path.ends_with(".gz")),
        "siblings must stay out of ui.integrity: {integrity:?}"
    );
}

#[test]
fn package_prints_the_stage_entry_set() {
    let fixture = fixture_root();
    let temp = tempfile::tempdir().unwrap();
    let project = temp.path().join("client-node-stage");
    copy_tree(&fixture, &project);

    Command::cargo_bin("node-app")
        .unwrap()
        .current_dir(temp.path())
        .args(["build", "--path"])
        .arg("client-node-stage")
        .assert()
        .success();

    let out_dir = temp.path().join("out");
    let output = Command::cargo_bin("node-app")
        .unwrap()
        .current_dir(temp.path())
        .env("NODE_APP_PACKAGE_STAGE_ONLY", "1")
        .args(["package", "--path"])
        .arg("client-node-stage")
        .args(["--out"])
        .arg(&out_dir)
        .output()
        .unwrap();
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("stage entry set"), "{stdout}");
    assert!(stdout.contains("ui/dist/main.js"), "{stdout}");
}

#[test]
fn package_warns_and_still_succeeds_for_a_stage_over_the_ceiling() {
    let fixture = fixture_root();
    let temp = tempfile::tempdir().unwrap();
    let project = temp.path().join("client-node-stage");
    copy_tree(&fixture, &project);

    Command::cargo_bin("node-app")
        .unwrap()
        .current_dir(temp.path())
        .args(["build", "--path"])
        .arg("client-node-stage")
        .assert()
        .success();

    // Random bytes do not compress, so the gzip size stays over the ceiling.
    let noise: Vec<u8> = (0..400 * 1024).map(|_| rand::random::<u8>()).collect();
    fs::write(project.join("ui/dist/noise.js"), noise).unwrap();

    let out_dir = temp.path().join("out");
    let output = Command::cargo_bin("node-app")
        .unwrap()
        .current_dir(temp.path())
        .env("NODE_APP_PACKAGE_STAGE_ONLY", "1")
        .args(["package", "--path"])
        .arg("client-node-stage")
        .args(["--out"])
        .arg(&out_dir)
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("warning:"), "{stderr}");
    assert!(stderr.contains("ui.deferred"), "{stderr}");
    // The stage-only shortcut stops before `.deb` finalization; the staged
    // tree is what the `.deb` is built from.
    let staged = out_dir.join("staging/usr/lib/node/apps/client-node-stage/ui/dist/noise.js");
    assert!(staged.exists(), "{}", staged.display());
}

#[test]
fn local_stage_context_shims_match_the_rpc_stage_contract_surface() {
    let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
    let rpc_contract = repo_root.join("client/rpc/src/stage-context.js");
    let declaration_shims = [
        repo_root.join(
            "examples/client-node-stage/ui/src/vendor-node-client-rpc-stage-context.d.ts",
        ),
        repo_root.join(
            "system/node-app-build/profiles/stage/ui/src/vendor-node-client-rpc-stage-context.d.ts",
        ),
        repo_root.join(
            "system/node-app-build/profiles/bun-stage/ui/src/vendor-node-client-rpc-stage-context.d.ts",
        ),
    ];

    let page_contract = repo_root.join("client/rpc/src/page-understanding-contract.js");
    for declaration_shim in &declaration_shims {
        assert_eq!(
            declaration_type_expression(declaration_shim, "PageUnderstandingV1"),
            jsdoc_type_expression(&page_contract, "PageUnderstandingV1"),
            "PageUnderstandingV1 must match the versioned RPC contract"
        );
    }

    for type_name in [
        "StageComposition",
        "StageLoadOptions",
        "MountedStage",
        "StageLoadHandler",
        "StageContext",
        "StageModule",
    ] {
        let expected = jsdoc_type_expression(&rpc_contract, type_name);
        for declaration_shim in &declaration_shims {
            assert_eq!(
                declaration_type_expression(declaration_shim, type_name),
                expected,
                "{type_name} in {} must match the RPC JSDoc contract",
                declaration_shim.to_string_lossy()
            );
        }
    }
}