diff --git a/Cargo.lock b/Cargo.lock index 879e940a32a..a8252003541 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1180,6 +1180,7 @@ dependencies = [ "duct", "spacetimedb-guard", "tempfile", + "which 8.0.0", ] [[package]] diff --git a/crates/smoketests/src/lib.rs b/crates/smoketests/src/lib.rs index 2b9285dcab7..cb56a6513d3 100644 --- a/crates/smoketests/src/lib.rs +++ b/crates/smoketests/src/lib.rs @@ -410,8 +410,25 @@ pub fn pnpm(args: &[&str], cwd: &Path) -> Result { Ok(String::from_utf8_lossy(&output.stdout).to_string()) } -/// Builds the local TypeScript bindings package. +/// Set by the smoketest runner once it has built the TypeScript SDK, so that +/// tests skip rebuilding it. +pub const TYPESCRIPT_SDK_PREBUILT_ENV: &str = "SPACETIME_SMOKETEST_TS_SDK_PREBUILT"; + +/// Builds the local TypeScript bindings package, unless the runner has already +/// built it. +/// +/// Tests run in parallel and share one copy of the SDK. Rebuilding it clears +/// `dist/` while other tests may be copying it into their projects, so the +/// runner builds it once up front, and tests only build it when run directly. pub fn build_typescript_sdk() -> Result<()> { + if std::env::var_os(TYPESCRIPT_SDK_PREBUILT_ENV).is_some() { + return Ok(()); + } + prebuild_typescript_sdk() +} + +/// Builds the local TypeScript bindings package unconditionally. +pub fn prebuild_typescript_sdk() -> Result<()> { let workspace = workspace_root(); let ts_bindings = workspace.join("crates/bindings-typescript"); pnpm(&["--filter", "spacetimedb", "install"], &ts_bindings)?; diff --git a/crates/smoketests/tests/cluster/templates.rs b/crates/smoketests/tests/cluster/templates.rs index 8bc30631734..f2f9c8522d9 100644 --- a/crates/smoketests/tests/cluster/templates.rs +++ b/crates/smoketests/tests/cluster/templates.rs @@ -12,7 +12,7 @@ use anyhow::{bail, Context, Result}; use regex::Regex; use serde_json::Value; -use spacetimedb_smoketests::{pnpm, random_string, workspace_root, Smoketest}; +use spacetimedb_smoketests::{build_typescript_sdk, pnpm, random_string, workspace_root, Smoketest}; use std::env; use std::fs; use std::path::{Path, PathBuf}; @@ -590,22 +590,12 @@ fn pin_csharp_client_sdk_package_version(project_path: &Path) -> Result<()> { Ok(()) } -/// Builds the TypeScript SDK (`crates/bindings-typescript`). -/// -/// Should be called once before testing any TypeScript templates. -fn build_typescript_sdk() -> Result<()> { - let sdk_path = workspace_root().join("crates/bindings-typescript"); - eprintln!("[TEMPLATES] Building TypeScript SDK at {:?}", sdk_path); - run_pnpm(&["--filter", "spacetimedb", "install"], &sdk_path)?; - run_pnpm(&["build"], &sdk_path)?; - Ok(()) -} - /// Points the `spacetimedb` entry in `package.json` at the local TypeScript /// SDK and removes the template's lockfile so pnpm re-resolves dependencies. fn setup_typescript_sdk_in_package_json(package_json_path: &Path) -> Result<()> { let sdk_path = workspace_root().join("crates/bindings-typescript"); update_package_json_dependency(package_json_path, "spacetimedb", &sdk_path)?; + inject_package_json_dependency(package_json_path, "spacetimedb")?; // Remove the template's lockfile; the dependency changed. let lockfile = package_json_path.parent().unwrap().join("pnpm-lock.yaml"); @@ -615,6 +605,44 @@ fn setup_typescript_sdk_in_package_json(package_json_path: &Path) -> Result<()> Ok(()) } +/// Marks a local-path dependency as injected (`dependenciesMeta..injected`). +/// +/// By default pnpm symlinks a local directory dependency, so the SDK resolves +/// its own imports, including the type declarations of its optional framework +/// peers (vue, react, svelte, ...), from the monorepo's `node_modules` rather +/// than the project's. The project then sees two copies of, for example, Vue's +/// types, and Vue brands `Ref` with a `unique symbol`, so a `Ref` from one copy +/// isn't recognised by the other. Injecting copies the SDK into the project and +/// resolves its peers there, as installing the published package would. +fn inject_package_json_dependency(package_json_path: &Path, package_name: &str) -> Result<()> { + let content = + fs::read_to_string(package_json_path).with_context(|| format!("Failed to read {:?}", package_json_path))?; + let mut data: Value = + serde_json::from_str(&content).with_context(|| format!("Failed to parse {:?}", package_json_path))?; + + let has_dependency = data + .get("dependencies") + .is_some_and(|deps| deps.get(package_name).is_some()); + if !has_dependency { + return Ok(()); + } + let Some(package) = data.as_object_mut() else { + bail!("{:?} is not a JSON object", package_json_path); + }; + let meta = package + .entry("dependenciesMeta") + .or_insert_with(|| Value::Object(Default::default())); + let Some(meta) = meta.as_object_mut() else { + bail!("dependenciesMeta in {:?} is not a JSON object", package_json_path); + }; + meta.insert(package_name.to_string(), serde_json::json!({ "injected": true })); + + let new_content = + serde_json::to_string_pretty(&data).with_context(|| format!("Failed to serialize {:?}", package_json_path))?; + fs::write(package_json_path, new_content).with_context(|| format!("Failed to write {:?}", package_json_path))?; + Ok(()) +} + /// Rewires the Rust server module's `spacetimedb` dependency to the local /// `crates/bindings` path. /// @@ -815,7 +843,7 @@ fn test_rust_template(test: &Smoketest, template: &Template, project_path: &Path Ok(()) } -/// Publishes a TypeScript server module and verifies the TypeScript client type-checks. +/// Publishes a TypeScript server module and verifies the TypeScript client builds. fn test_typescript_template(test: &Smoketest, template: &Template, project_path: &Path) -> Result<()> { // Server let server_path = project_path.join("spacetimedb"); @@ -840,18 +868,56 @@ fn test_typescript_template(test: &Smoketest, template: &Template, project_path: })?; let _ = test.spacetime(&["delete", "--server", &test.server_url, "--yes", &domain]); - // Client type-check (only if there's a client package.json in the project root) + // Client build (only if there's a client package.json in the project root) let client_package_json = project_path.join("package.json"); if client_package_json.exists() { setup_typescript_sdk_in_package_json(&client_package_json)?; run_pnpm(&["install"], project_path)?; - // TODO: some templates don't pass tsc yet, re-enable once they're fixed. - // run_pnpm(&["exec", "tsc", "--noEmit"], project_path)?; + if let Some(reason) = typescript_client_build_known_failure(&template.id) { + eprintln!( + "[TEMPLATES] Skipping client build for {}: known failure: {reason}", + template.id + ); + } else { + // Each template's own `build` script, which type-checks where the + // framework's tooling does (tsc, vue-tsc, svelte-check, ...). + run_pnpm(&["run", "--if-present", "build"], project_path) + .with_context(|| format!("Client build failed for template {}", template.id))?; + } } Ok(()) } +/// TypeScript templates whose client `build` script currently fails, and why. +/// Remove an entry as soon as its template is fixed, so the build is checked again. +const TYPESCRIPT_CLIENT_BUILD_KNOWN_FAILURES: &[(&str, &str)] = &[( + "bun-ts", + "pnpm doesn't run the `bun` package's postinstall, so `bun build` can't start", +)]; + +fn typescript_client_build_known_failure(template_id: &str) -> Option<&'static str> { + TYPESCRIPT_CLIENT_BUILD_KNOWN_FAILURES + .iter() + .find(|(id, _)| *id == template_id) + .map(|(_, reason)| *reason) +} + +#[test] +fn test_typescript_client_build_known_failures_name_real_templates() { + let typescript_templates: Vec = get_templates() + .into_iter() + .filter(|template| template.server_lang.as_deref() == Some("typescript")) + .map(|template| template.id) + .collect(); + for (id, _) in TYPESCRIPT_CLIENT_BUILD_KNOWN_FAILURES { + assert!( + typescript_templates.iter().any(|template| template == id), + "known-failure entry {id} is not a TypeScript template; remove it" + ); + } +} + /// Publishes a C# server module and verifies the C# client builds. fn test_csharp_template(test: &Smoketest, template: &Template) -> Result<()> { for dotnet_version in ["8", "10"] { diff --git a/tools/ci/commands/smoketests/Cargo.toml b/tools/ci/commands/smoketests/Cargo.toml index f161fe64586..7f0b5c2d1a2 100644 --- a/tools/ci/commands/smoketests/Cargo.toml +++ b/tools/ci/commands/smoketests/Cargo.toml @@ -9,4 +9,5 @@ duct.workspace = true clap.workspace = true tempfile.workspace = true spacetimedb-guard.workspace = true +which = "8.0.0" ci-common = { path = "../../common" } diff --git a/tools/ci/commands/smoketests/src/main.rs b/tools/ci/commands/smoketests/src/main.rs index 869a75532d2..a6f42e9e5dd 100644 --- a/tools/ci/commands/smoketests/src/main.rs +++ b/tools/ci/commands/smoketests/src/main.rs @@ -193,6 +193,37 @@ fn build_precompiled_modules() -> Result<()> { Ok(()) } +/// Tells test processes the TypeScript SDK is already built. Must match +/// `spacetimedb_smoketests::TYPESCRIPT_SDK_PREBUILT_ENV`. +const TYPESCRIPT_SDK_PREBUILT_ENV: &str = "SPACETIME_SMOKETEST_TS_SDK_PREBUILT"; + +/// Builds the TypeScript SDK (`crates/bindings-typescript`) that the TypeScript +/// smoketests install into their projects. +/// +/// Tests run in parallel and share this one copy of the SDK. If each test built +/// it, one test's build would clear `dist/` while another was copying it into +/// its project. Returns whether the SDK was built; without pnpm the TypeScript +/// tests skip themselves, so there is nothing to build. +fn build_typescript_sdk(workspace_root: &Path) -> Result { + let Ok(pnpm) = which::which("pnpm") else { + eprintln!("Skipping TypeScript SDK build (pnpm not found).\n"); + return Ok(false); + }; + let sdk_dir = workspace_root.join("crates/bindings-typescript"); + + eprintln!("Building TypeScript SDK..."); + for args in [&["--filter", "spacetimedb", "install"][..], &["build"]] { + let status = Command::new(&pnpm).args(args).current_dir(&sdk_dir).status()?; + ensure!( + status.success(), + "Failed to build TypeScript SDK: pnpm {}", + args.join(" ") + ); + } + eprintln!("TypeScript SDK built.\n"); + Ok(true) +} + fn archive_smoketests(archive_file: &Path, suite: SmoketestSuite) -> Result<()> { build_precompiled_modules()?; @@ -220,9 +251,10 @@ fn run_smoketest_archive(archive_file: &Path, args: Vec) -> Result<()> { let cli_path = ensure_binaries_built(); let base_config_dir = prepare_base_config(&cli_path, None, None)?; let base_config_path = base_config_dir.path().join("config.toml"); + let typescript_sdk_prebuilt = build_typescript_sdk(&workspace_root)?; let mut cmd = Command::new("cargo"); - set_env(&mut cmd, None, true, false, &base_config_path); + set_env(&mut cmd, None, true, false, &base_config_path, typescript_sdk_prebuilt); cmd.args(["nextest", "run", "--archive-file"]) .arg(archive_file) .args(["--workspace-remap"]) @@ -266,6 +298,9 @@ fn run_smoketest( // 2. Build pre-compiled modules (this also warms the WASM dependency cache) build_precompiled_modules()?; + // 3. Build the TypeScript SDK once, rather than in every test that uses it + let typescript_sdk_prebuilt = build_typescript_sdk(&env::current_dir()?)?; + let cli_path = ensure_binaries_built(); let base_config_dir = prepare_base_config(&cli_path, server.as_deref(), auth_host)?; let base_config_path = base_config_dir.path().join("config.toml"); @@ -287,7 +322,14 @@ fn run_smoketest( let mut cmd = if use_nextest { eprintln!("Running smoketests with cargo nextest...\n"); let mut cmd = Command::new("cargo"); - set_env(&mut cmd, server, dotnet, auth_host.is_some(), &base_config_path); + set_env( + &mut cmd, + server, + dotnet, + auth_host.is_some(), + &base_config_path, + typescript_sdk_prebuilt, + ); cmd.args(["nextest", "run", "--release", "-p", "spacetimedb-smoketests"]) .args(suite.cargo_args()) .arg("--no-fail-fast"); @@ -304,7 +346,14 @@ fn run_smoketest( } else { eprintln!("Running smoketests with cargo test...\n"); let mut cmd = Command::new("cargo"); - set_env(&mut cmd, server, dotnet, auth_host.is_some(), &base_config_path); + set_env( + &mut cmd, + server, + dotnet, + auth_host.is_some(), + &base_config_path, + typescript_sdk_prebuilt, + ); cmd.args(["test", "--release", "-p", "spacetimedb-smoketests"]) .args(suite.cargo_args()); cmd @@ -385,7 +434,17 @@ fn prepare_base_config(cli_path: &Path, server: Option<&str>, auth_host: Option< Ok(temp_dir) } -fn set_env(cmd: &mut Command, server: Option, dotnet: bool, auth_host: bool, base_config_path: &Path) { +fn set_env( + cmd: &mut Command, + server: Option, + dotnet: bool, + auth_host: bool, + base_config_path: &Path, + typescript_sdk_prebuilt: bool, +) { + if typescript_sdk_prebuilt { + cmd.env(TYPESCRIPT_SDK_PREBUILT_ENV, "1"); + } if let Some(ref server_url) = server { cmd.env("SPACETIME_REMOTE_SERVER", server_url); }