1#![cfg(feature = "cli")]
2
3use std::env;
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use anyhow::{Context, Result, anyhow, bail};
9use clap::Args;
10use serde_json::Value as JsonValue;
11use wasmtime::component::{Component, Linker, Val};
12use wasmtime::{Engine, Store};
13use wasmtime_wasi::{ResourceTable, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
14
15use crate::abi::{self, AbiError};
16use crate::cmd::component_world::{canonical_component_world, is_fallback_world};
17use crate::cmd::flow::{
18 FlowUpdateResult, manifest_component_id, resolve_operation, update_with_manifest,
19};
20use crate::cmd::i18n;
21use crate::config::{
22 ConfigInferenceOptions, ConfigSchemaSource, load_manifest_with_schema, resolve_manifest_path,
23};
24use crate::describe::{DescribePayload, from_wit_world};
25use crate::embedded_descriptor::embed_and_verify_wasm;
26use crate::parse_manifest;
27use crate::path_safety::normalize_under_root;
28use crate::schema_quality::{SchemaQualityMode, validate_operation_schemas};
29use greentic_types::cbor::canonical;
30use greentic_types::schemas::component::v0_6_0::ComponentDescribe;
31
32const DEFAULT_MANIFEST: &str = "component.manifest.json";
33
34#[derive(Args, Debug, Clone)]
35pub struct BuildArgs {
36 #[arg(long = "manifest", value_name = "PATH", default_value = DEFAULT_MANIFEST)]
38 pub manifest: PathBuf,
39 #[arg(long = "cargo", value_name = "PATH")]
41 pub cargo_bin: Option<PathBuf>,
42 #[arg(long = "no-flow")]
44 pub no_flow: bool,
45 #[arg(long = "no-infer-config")]
47 pub no_infer_config: bool,
48 #[arg(long = "no-write-schema")]
50 pub no_write_schema: bool,
51 #[arg(long = "force-write-schema")]
53 pub force_write_schema: bool,
54 #[arg(long = "no-validate")]
56 pub no_validate: bool,
57 #[arg(long = "json")]
59 pub json: bool,
60 #[arg(long)]
62 pub permissive: bool,
63}
64
65#[derive(Debug, serde::Serialize)]
66struct BuildSummary {
67 manifest: PathBuf,
68 wasm_path: PathBuf,
69 wasm_hash: String,
70 config_source: ConfigSchemaSource,
71 schema_written: bool,
72 #[serde(skip_serializing_if = "Option::is_none")]
73 flows: Option<FlowUpdateResult>,
74}
75
76pub fn run(args: BuildArgs) -> Result<()> {
77 let manifest_path = resolve_manifest_path(&args.manifest);
78 let cwd = env::current_dir().context("failed to read current directory")?;
79 let manifest_path = if manifest_path.is_absolute() {
80 manifest_path
81 } else {
82 cwd.join(manifest_path)
83 };
84 if !manifest_path.exists() {
85 bail!(
86 "{}",
87 i18n::tr_lit("manifest not found at {}").replacen(
88 "{}",
89 &manifest_path.display().to_string(),
90 1
91 )
92 );
93 }
94 let cargo_bin = args
95 .cargo_bin
96 .clone()
97 .or_else(|| env::var_os("CARGO").map(PathBuf::from))
98 .unwrap_or_else(|| PathBuf::from("cargo"));
99 let inference_opts = ConfigInferenceOptions {
100 allow_infer: !args.no_infer_config,
101 write_schema: !args.no_write_schema,
102 force_write_schema: args.force_write_schema,
103 validate: !args.no_validate,
104 };
105 println!(
106 "Using manifest at {} (cargo: {})",
107 manifest_path.display(),
108 cargo_bin.display()
109 );
110
111 let config = load_manifest_with_schema(&manifest_path, &inference_opts)?;
112 let mode = if args.permissive {
113 SchemaQualityMode::Permissive
114 } else {
115 SchemaQualityMode::Strict
116 };
117 let manifest_component = parse_manifest(
118 &serde_json::to_string(&config.manifest)
119 .context("failed to serialize manifest for schema validation")?,
120 )
121 .context("failed to parse manifest for schema validation")?;
122 let schema_warnings = validate_operation_schemas(&manifest_component, mode)?;
123 for warning in schema_warnings {
124 eprintln!("warning[W_OP_SCHEMA_EMPTY]: {}", warning.message);
125 }
126 let component_id = manifest_component_id(&config.manifest)?;
127 let _operation = resolve_operation(&config.manifest, component_id)?;
128 let flow_outcome = if args.no_flow {
129 None
130 } else {
131 Some(update_with_manifest(&config)?)
132 };
133
134 let mut manifest_to_write = flow_outcome
135 .as_ref()
136 .map(|outcome| outcome.manifest.clone())
137 .unwrap_or_else(|| config.manifest.clone());
138 let canonical_manifest = parse_manifest(
139 &serde_json::to_string(&manifest_to_write)
140 .context("failed to serialize manifest for embedded descriptor")?,
141 )
142 .context("failed to parse canonical manifest for embedded descriptor")?;
143
144 let manifest_dir = manifest_path.parent().unwrap_or_else(|| Path::new("."));
145 build_wasm(manifest_dir, &cargo_bin, &manifest_to_write)?;
146 check_canonical_world_export(manifest_dir, &manifest_to_write)?;
147 let wasm_path_for_embedding = resolve_wasm_path(manifest_dir, &manifest_to_write)?;
148 embed_and_verify_wasm(&wasm_path_for_embedding, &canonical_manifest)
149 .context("failed to embed canonical manifest into built wasm")?;
150
151 if !config.persist_schema {
152 manifest_to_write
153 .as_object_mut()
154 .map(|obj| obj.remove("config_schema"));
155 }
156 let (wasm_path, wasm_hash) = update_manifest_hashes(manifest_dir, &mut manifest_to_write)?;
157 emit_describe_artifacts(manifest_dir, &manifest_to_write, &wasm_path)?;
158 write_manifest(&manifest_path, &manifest_to_write)?;
159
160 if args.json {
161 let payload = BuildSummary {
162 manifest: manifest_path.clone(),
163 wasm_path,
164 wasm_hash,
165 config_source: config.source,
166 schema_written: config.schema_written && config.persist_schema,
167 flows: flow_outcome.as_ref().map(|outcome| outcome.result),
168 };
169 serde_json::to_writer_pretty(std::io::stdout(), &payload)?;
170 println!();
171 } else {
172 println!("Built wasm artifact at {}", wasm_path.display());
173 println!("Updated {} hashes (blake3)", manifest_path.display());
174 if config.schema_written && config.persist_schema {
175 println!(
176 "Updated {} with inferred config_schema ({:?})",
177 manifest_path.display(),
178 config.source
179 );
180 }
181 if let Some(outcome) = flow_outcome {
182 let flows = outcome.result;
183 println!(
184 "Flows updated (default: {}, custom: {})",
185 flows.default_updated, flows.custom_updated
186 );
187 } else {
188 println!("Flow regeneration skipped (--no-flow)");
189 }
190 }
191
192 Ok(())
193}
194
195fn build_wasm(manifest_dir: &Path, cargo_bin: &Path, manifest: &JsonValue) -> Result<()> {
196 let resolved_world = manifest.get("world").and_then(|v| v.as_str()).unwrap_or("");
197 if resolved_world.is_empty() {
198 println!("Resolved manifest world: <missing>");
199 } else {
200 println!("Resolved manifest world: {resolved_world}");
201 }
202 let require_component = resolved_world.contains("component@0.6.0");
203
204 if require_component {
205 if cargo_component_available(cargo_bin) {
206 println!(
207 "Running cargo component build via {} in {}",
208 cargo_bin.display(),
209 manifest_dir.display()
210 );
211 let mut cmd = Command::new(cargo_bin);
212 if let Some(flags) = resolved_wasm_rustflags() {
213 cmd.env("RUSTFLAGS", sanitize_wasm_rustflags(&flags));
214 }
215 cmd.arg("component").arg("build");
216 maybe_add_offline_flag(&mut cmd);
217 let status = cmd
218 .arg("--target")
219 .arg("wasm32-wasip2")
220 .arg("--release")
221 .current_dir(manifest_dir)
222 .status()
223 .with_context(|| {
224 format!(
225 "failed to run cargo component build via {}",
226 cargo_bin.display()
227 )
228 })?;
229 if !status.success() {
230 bail!(
231 "cargo component build --target wasm32-wasip2 --release failed with status {}",
232 status
233 );
234 }
235 return Ok(());
236 }
237 bail!(
238 "component@0.6.0 manifests require cargo-component; install it with `cargo install cargo-component --locked`"
239 );
240 }
241
242 println!(
243 "Running cargo build via {} in {}",
244 cargo_bin.display(),
245 manifest_dir.display()
246 );
247 let mut cmd = Command::new(cargo_bin);
248 if let Some(flags) = resolved_wasm_rustflags() {
249 cmd.env("RUSTFLAGS", sanitize_wasm_rustflags(&flags));
250 }
251 cmd.arg("build");
252 maybe_add_offline_flag(&mut cmd);
253 let status = cmd
254 .arg("--target")
255 .arg("wasm32-wasip2")
256 .arg("--release")
257 .current_dir(manifest_dir)
258 .status()
259 .with_context(|| format!("failed to run cargo build via {}", cargo_bin.display()))?;
260
261 if !status.success() {
262 bail!(
263 "cargo build --target wasm32-wasip2 --release failed with status {}",
264 status
265 );
266 }
267 Ok(())
268}
269
270fn cargo_component_available(cargo_bin: &Path) -> bool {
271 Command::new(cargo_bin)
272 .arg("component")
273 .arg("--version")
274 .status()
275 .map(|status| status.success())
276 .unwrap_or(false)
277}
278
279fn maybe_add_offline_flag(cmd: &mut Command) {
280 if cargo_offline_requested() {
281 cmd.arg("--offline");
282 }
283}
284
285fn cargo_offline_requested() -> bool {
286 env_truthy(env::var_os("CARGO_NET_OFFLINE").as_deref())
287}
288
289fn env_truthy(value: Option<&std::ffi::OsStr>) -> bool {
290 value
291 .and_then(|raw| raw.to_str())
292 .map(|raw| {
293 matches!(
294 raw.trim().to_ascii_lowercase().as_str(),
295 "1" | "true" | "yes" | "on"
296 )
297 })
298 .unwrap_or(false)
299}
300
301fn resolved_wasm_rustflags() -> Option<String> {
303 env::var("WASM_RUSTFLAGS")
304 .ok()
305 .or_else(|| env::var("RUSTFLAGS").ok())
306}
307
308fn sanitize_wasm_rustflags(flags: &str) -> String {
310 flags
311 .replace("-Wl,", "")
312 .replace("-C link-arg=--no-keep-memory", "")
313 .replace("-C link-arg=--threads=1", "")
314 .split_whitespace()
315 .collect::<Vec<_>>()
316 .join(" ")
317}
318
319fn check_canonical_world_export(manifest_dir: &Path, manifest: &JsonValue) -> Result<()> {
320 if env::var_os("GREENTIC_SKIP_NODE_EXPORT_CHECK").is_some() {
321 println!("World export check skipped (GREENTIC_SKIP_NODE_EXPORT_CHECK=1)");
322 return Ok(());
323 }
324 let wasm_path = resolve_wasm_path(manifest_dir, manifest)?;
325 let canonical_world = canonical_component_world();
326 match abi::check_world_base(&wasm_path, canonical_world) {
327 Ok(exported) => println!("Exported world: {exported}"),
328 Err(err) => match err {
329 AbiError::WorldMismatch { expected, found } if is_fallback_world(&found) => {
330 println!("Exported world: {expected} (compatible fallback export: {found})");
331 }
332 err => {
333 return Err(err)
334 .with_context(|| format!("component must export world {canonical_world}"));
335 }
336 },
337 }
338 Ok(())
339}
340
341fn update_manifest_hashes(
342 manifest_dir: &Path,
343 manifest: &mut JsonValue,
344) -> Result<(PathBuf, String)> {
345 let artifact_path = resolve_wasm_path(manifest_dir, manifest)?;
346 let wasm_bytes = fs::read(&artifact_path)
347 .with_context(|| format!("failed to read wasm at {}", artifact_path.display()))?;
348 let digest = blake3::hash(&wasm_bytes).to_hex().to_string();
349
350 manifest["artifacts"]["component_wasm"] =
351 JsonValue::String(path_string_relative(manifest_dir, &artifact_path)?);
352 manifest["hashes"]["component_wasm"] = JsonValue::String(format!("blake3:{digest}"));
353
354 Ok((artifact_path, format!("blake3:{digest}")))
355}
356
357fn path_string_relative(base: &Path, target: &Path) -> Result<String> {
358 let rel = pathdiff::diff_paths(target, base).unwrap_or_else(|| target.to_path_buf());
359 rel.to_str()
360 .map(|s| s.to_string())
361 .ok_or_else(|| anyhow!("failed to stringify path {}", target.display()))
362}
363
364fn resolve_wasm_path(manifest_dir: &Path, manifest: &JsonValue) -> Result<PathBuf> {
365 let manifest_root = manifest_dir
366 .canonicalize()
367 .with_context(|| format!("failed to canonicalize {}", manifest_dir.display()))?;
368 let candidate = manifest
369 .get("artifacts")
370 .and_then(|a| a.get("component_wasm"))
371 .and_then(|v| v.as_str())
372 .map(PathBuf::from)
373 .unwrap_or_else(|| {
374 let raw_name = manifest
375 .get("name")
376 .and_then(|v| v.as_str())
377 .or_else(|| manifest.get("id").and_then(|v| v.as_str()))
378 .unwrap_or("component");
379 let sanitized = raw_name.replace(['-', '.'], "_");
380 manifest_dir.join(format!("target/wasm32-wasip2/release/{sanitized}.wasm"))
381 });
382 if candidate.exists() {
383 let normalized = normalize_under_root(&manifest_root, &candidate).or_else(|_| {
384 if candidate.is_absolute() {
385 candidate
386 .canonicalize()
387 .with_context(|| format!("failed to canonicalize {}", candidate.display()))
388 } else {
389 normalize_under_root(&manifest_root, &candidate)
390 }
391 })?;
392 return Ok(normalized);
393 }
394
395 if let Some(cargo_target_dir) = env::var_os("CARGO_TARGET_DIR") {
396 let relative = candidate
397 .strip_prefix(manifest_dir)
398 .unwrap_or(&candidate)
399 .to_path_buf();
400 if relative.starts_with("target") {
401 let alt =
402 PathBuf::from(cargo_target_dir).join(relative.strip_prefix("target").unwrap());
403 if alt.exists() {
404 return alt
405 .canonicalize()
406 .with_context(|| format!("failed to canonicalize {}", alt.display()));
407 }
408 }
409 }
410
411 let normalized = normalize_under_root(&manifest_root, &candidate).or_else(|_| {
412 if candidate.is_absolute() {
413 candidate
414 .canonicalize()
415 .with_context(|| format!("failed to canonicalize {}", candidate.display()))
416 } else {
417 normalize_under_root(&manifest_root, &candidate)
418 }
419 })?;
420 Ok(normalized)
421}
422
423fn write_manifest(manifest_path: &Path, manifest: &JsonValue) -> Result<()> {
424 let formatted = serde_json::to_string_pretty(manifest)?;
425 fs::write(manifest_path, formatted + "\n")
426 .with_context(|| format!("failed to write {}", manifest_path.display()))
427}
428
429fn emit_describe_artifacts(
430 manifest_dir: &Path,
431 manifest: &JsonValue,
432 wasm_path: &Path,
433) -> Result<()> {
434 let abi_version = read_abi_version(manifest_dir);
435 let require_describe = abi_version.as_deref() == Some("0.6.0");
436 let manifest_model = parse_manifest(
437 &serde_json::to_string(manifest).context("failed to serialize manifest for describe")?,
438 )
439 .context("failed to parse manifest for describe")?;
440
441 let describe_bytes = match call_describe(wasm_path) {
442 Ok(bytes) => bytes,
443 Err(err) => {
444 if require_describe {
445 match from_wit_world(wasm_path, manifest_model.world.as_str()) {
446 Ok(payload) => {
447 write_wit_describe_artifacts(
448 manifest_dir,
449 manifest,
450 wasm_path,
451 abi_version.as_deref(),
452 &payload,
453 )?;
454 eprintln!(
455 "warning: describe export unavailable, emitted WIT-derived describe.json instead ({err})"
456 );
457 return Ok(());
458 }
459 Err(wit_err) => {
460 return Err(anyhow!(
461 "describe failed: {err}; WIT fallback failed: {wit_err}"
462 ));
463 }
464 }
465 }
466 eprintln!("warning: skipping describe artifacts ({err})");
467 return Ok(());
468 }
469 };
470
471 let payload = strip_self_describe_tag(&describe_bytes);
472 let canonical_bytes = canonical::canonicalize_allow_floats(payload)
473 .map_err(|err| anyhow!("describe canonicalization failed: {err}"))?;
474 let describe: ComponentDescribe = canonical::from_cbor(&canonical_bytes)
475 .map_err(|err| anyhow!("describe decode failed: {err}"))?;
476
477 let dist_dir = manifest_dir.join("dist");
478 fs::create_dir_all(&dist_dir)
479 .with_context(|| format!("failed to create {}", dist_dir.display()))?;
480
481 let (name, abi_underscore) = artifact_basename(manifest, wasm_path, abi_version.as_deref());
482 let base = format!("{name}__{abi_underscore}");
483 let describe_cbor_path = dist_dir.join(format!("{base}.describe.cbor"));
484 fs::write(&describe_cbor_path, &canonical_bytes)
485 .with_context(|| format!("failed to write {}", describe_cbor_path.display()))?;
486
487 let describe_json_path = dist_dir.join(format!("{base}.describe.json"));
488 let json = serde_json::to_string_pretty(&describe)?;
489 fs::write(&describe_json_path, json + "\n")
490 .with_context(|| format!("failed to write {}", describe_json_path.display()))?;
491
492 let wasm_out = dist_dir.join(format!("{base}.wasm"));
493 if wasm_out != wasm_path {
494 let _ = fs::copy(wasm_path, &wasm_out);
495 }
496
497 Ok(())
498}
499
500fn write_wit_describe_artifacts(
501 manifest_dir: &Path,
502 manifest: &JsonValue,
503 wasm_path: &Path,
504 abi_version: Option<&str>,
505 payload: &DescribePayload,
506) -> Result<()> {
507 let dist_dir = manifest_dir.join("dist");
508 fs::create_dir_all(&dist_dir)
509 .with_context(|| format!("failed to create {}", dist_dir.display()))?;
510
511 let (name, abi_underscore) = artifact_basename(manifest, wasm_path, abi_version);
512 let base = format!("{name}__{abi_underscore}");
513 let describe_cbor_path = dist_dir.join(format!("{base}.describe.cbor"));
514 let cbor = canonical::to_canonical_cbor_allow_floats(payload)
515 .map_err(|err| anyhow!("describe fallback canonicalization failed: {err}"))?;
516 fs::write(&describe_cbor_path, cbor)
517 .with_context(|| format!("failed to write {}", describe_cbor_path.display()))?;
518
519 let describe_json_path = dist_dir.join(format!("{base}.describe.json"));
520 let json = serde_json::to_string_pretty(payload)?;
521 fs::write(&describe_json_path, json + "\n")
522 .with_context(|| format!("failed to write {}", describe_json_path.display()))?;
523
524 let wasm_out = dist_dir.join(format!("{base}.wasm"));
525 if wasm_out != wasm_path {
526 let _ = fs::copy(wasm_path, &wasm_out);
527 }
528
529 Ok(())
530}
531
532fn read_abi_version(manifest_dir: &Path) -> Option<String> {
533 let cargo_path = manifest_dir.join("Cargo.toml");
534 let contents = fs::read_to_string(cargo_path).ok()?;
535 let doc: toml::Value = toml::from_str(&contents).ok()?;
536 doc.get("package")
537 .and_then(|pkg| pkg.get("metadata"))
538 .and_then(|meta| meta.get("greentic"))
539 .and_then(|g| g.get("abi_version"))
540 .and_then(|v| v.as_str())
541 .map(|s| s.to_string())
542}
543
544fn artifact_basename(
545 manifest: &JsonValue,
546 wasm_path: &Path,
547 abi_version: Option<&str>,
548) -> (String, String) {
549 let name = manifest
550 .get("name")
551 .and_then(|v| v.as_str())
552 .or_else(|| manifest.get("id").and_then(|v| v.as_str()))
553 .map(sanitize_name)
554 .unwrap_or_else(|| {
555 wasm_path
556 .file_stem()
557 .and_then(|s| s.to_str())
558 .map(sanitize_name)
559 .unwrap_or_else(|| "component".to_string())
560 });
561 let abi = abi_version.unwrap_or("0.6.0").replace('.', "_");
562 (name, abi)
563}
564
565fn sanitize_name(raw: &str) -> String {
566 raw.chars()
567 .map(|ch| {
568 if ch.is_ascii_alphanumeric() || ch == '-' {
569 ch
570 } else {
571 '_'
572 }
573 })
574 .collect::<String>()
575 .trim_matches('_')
576 .to_string()
577}
578
579fn call_describe(wasm_path: &Path) -> Result<Vec<u8>> {
580 let mut config = wasmtime::Config::new();
581 config.wasm_component_model(true);
582 let engine = Engine::new(&config).map_err(|err| anyhow!("failed to create engine: {err}"))?;
583 let component = Component::from_file(&engine, wasm_path)
584 .map_err(|err| anyhow!("failed to load component {}: {err}", wasm_path.display()))?;
585 let mut linker = Linker::new(&engine);
586 wasmtime_wasi::p2::add_to_linker_sync(&mut linker)
587 .map_err(|err| anyhow!("failed to add wasi: {err}"))?;
588 let mut store = Store::new(&engine, BuildWasi::new()?);
589 let instance = linker
590 .instantiate(&mut store, &component)
591 .map_err(|err| anyhow!("failed to instantiate component: {err}"))?;
592 let instance_index = resolve_interface_index(&instance, &mut store, "component-descriptor")
593 .ok_or_else(|| anyhow!("missing export interface component-descriptor"))?;
594 let func_index = instance
595 .get_export_index(&mut store, Some(&instance_index), "describe")
596 .ok_or_else(|| anyhow!("missing export component-descriptor.describe"))?;
597 let func = instance
598 .get_func(&mut store, func_index)
599 .ok_or_else(|| anyhow!("describe export is not callable"))?;
600 let mut results = vec![Val::Bool(false); func.ty(&mut store).results().len()];
601 func.call(&mut store, &[], &mut results)
602 .map_err(|err| anyhow!("describe call failed: {err}"))?;
603 let val = results
604 .first()
605 .ok_or_else(|| anyhow!("describe returned no value"))?;
606 val_to_bytes(val).map_err(|err| anyhow!(err))
607}
608
609fn resolve_interface_index(
610 instance: &wasmtime::component::Instance,
611 store: &mut Store<BuildWasi>,
612 interface: &str,
613) -> Option<wasmtime::component::ComponentExportIndex> {
614 for candidate in interface_candidates(interface) {
615 if let Some(index) = instance.get_export_index(&mut *store, None, &candidate) {
616 return Some(index);
617 }
618 }
619 None
620}
621
622fn interface_candidates(interface: &str) -> [String; 3] {
623 [
624 interface.to_string(),
625 format!("greentic:component/{interface}@0.6.0"),
626 format!("greentic:component/{interface}"),
627 ]
628}
629
630fn val_to_bytes(val: &Val) -> Result<Vec<u8>, String> {
631 match val {
632 Val::List(items) => {
633 let mut out = Vec::with_capacity(items.len());
634 for item in items {
635 match item {
636 Val::U8(byte) => out.push(*byte),
637 _ => return Err("expected list<u8>".to_string()),
638 }
639 }
640 Ok(out)
641 }
642 _ => Err("expected list<u8>".to_string()),
643 }
644}
645
646fn strip_self_describe_tag(bytes: &[u8]) -> &[u8] {
647 const SELF_DESCRIBE_TAG: [u8; 3] = [0xd9, 0xd9, 0xf7];
648 if bytes.starts_with(&SELF_DESCRIBE_TAG) {
649 &bytes[SELF_DESCRIBE_TAG.len()..]
650 } else {
651 bytes
652 }
653}
654
655struct BuildWasi {
656 ctx: WasiCtx,
657 table: ResourceTable,
658}
659
660impl BuildWasi {
661 fn new() -> Result<Self> {
662 let ctx = WasiCtxBuilder::new().build();
663 Ok(Self {
664 ctx,
665 table: ResourceTable::new(),
666 })
667 }
668}
669
670impl WasiView for BuildWasi {
671 fn ctx(&mut self) -> WasiCtxView<'_> {
672 WasiCtxView {
673 ctx: &mut self.ctx,
674 table: &mut self.table,
675 }
676 }
677}
678
679#[cfg(test)]
680mod tests {
681 use std::ffi::OsStr;
682 use std::path::Path;
683
684 use serde_json::json;
685 use wasmtime::component::Val;
686
687 use super::{
688 env_truthy, path_string_relative, resolve_wasm_path, sanitize_name,
689 sanitize_wasm_rustflags, strip_self_describe_tag, val_to_bytes,
690 };
691
692 #[test]
693 fn sanitize_name_preserves_hyphens_for_dist_artifacts() {
694 assert_eq!(
695 sanitize_name("wizard-smoke-advanced"),
696 "wizard-smoke-advanced"
697 );
698 assert_eq!(
699 sanitize_name("wizard_smoke_advanced"),
700 "wizard_smoke_advanced"
701 );
702 }
703
704 #[test]
705 fn env_truthy_accepts_common_true_spellings() {
706 for value in ["1", "true", "TRUE", " yes ", "on"] {
707 assert!(
708 env_truthy(Some(OsStr::new(value))),
709 "{value} should be truthy"
710 );
711 }
712 }
713
714 #[test]
715 fn env_truthy_rejects_falsey_and_missing_values() {
716 for value in [
717 None,
718 Some(OsStr::new("0")),
719 Some(OsStr::new("false")),
720 Some(OsStr::new("")),
721 ] {
722 assert!(!env_truthy(value));
723 }
724 }
725
726 #[test]
727 fn sanitize_wasm_rustflags_drops_unsupported_linker_args() {
728 let sanitized = sanitize_wasm_rustflags(
729 "-C opt-level=z -Wl,--export-table -C link-arg=--no-keep-memory -C link-arg=--threads=1",
730 );
731
732 assert_eq!(sanitized, "-C opt-level=z --export-table");
733 }
734
735 #[test]
736 fn path_string_relative_prefers_relative_path() {
737 let base = Path::new("/tmp/project");
738 let target = Path::new("/tmp/project/dist/component.wasm");
739
740 let relative = path_string_relative(base, target).expect("relative path");
741
742 assert_eq!(relative, "dist/component.wasm");
743 }
744
745 #[test]
746 fn resolve_wasm_path_uses_default_target_location_when_manifest_omits_artifact() {
747 let dir = tempfile::tempdir().expect("tempdir");
748 let target = dir
749 .path()
750 .join("target/wasm32-wasip2/release/com_greentic_demo.wasm");
751 std::fs::create_dir_all(target.parent().expect("target parent"))
752 .expect("create target dir");
753 std::fs::write(&target, b"wasm").expect("write wasm");
754
755 let manifest = json!({
756 "id": "com.greentic.demo"
757 });
758
759 let resolved = resolve_wasm_path(dir.path(), &manifest).expect("resolve default wasm path");
760 assert_eq!(resolved, target.canonicalize().expect("canonical target"));
761 }
762
763 #[test]
764 fn val_to_bytes_rejects_non_byte_lists() {
765 let err = val_to_bytes(&Val::List(vec![Val::String("oops".to_string())]))
766 .expect_err("non-u8 list should fail");
767 assert_eq!(err, "expected list<u8>");
768 }
769
770 #[test]
771 fn strip_self_describe_tag_removes_only_known_prefix() {
772 let tagged = [0xd9, 0xd9, 0xf7, 0x01, 0x02];
773 assert_eq!(strip_self_describe_tag(&tagged), &[0x01, 0x02]);
774 assert_eq!(strip_self_describe_tag(&[0x01, 0x02]), &[0x01, 0x02]);
775 }
776}