diff --git a/.github/workflows/typescript-test.yml b/.github/workflows/typescript-test.yml index 9affa726f47..fbd3816a8fd 100644 --- a/.github/workflows/typescript-test.yml +++ b/.github/workflows/typescript-test.yml @@ -115,12 +115,12 @@ jobs: fi - name: Generate client bindings - working-directory: templates/quickstart-chat-typescript + working-directory: templates/chat-react-ts run: | pnpm generate - name: Check for changes - working-directory: templates/quickstart-chat-typescript + working-directory: templates/chat-react-ts run: | "${GITHUB_WORKSPACE}"/tools/check-diff.sh src/module_bindings || { echo "Error: Bindings are dirty. Please generate bindings again and commit them to this branch." @@ -144,7 +144,7 @@ jobs: # spacetime logs quickstart-chat - name: Check that quickstart-chat builds - working-directory: templates/quickstart-chat-typescript + working-directory: templates/chat-react-ts run: pnpm build - name: Check that templates build diff --git a/Cargo.lock b/Cargo.lock index 168fffc3df7..1bdfae40079 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -444,6 +444,14 @@ dependencies = [ "vsimd", ] +[[package]] +name = "basic-rust-module" +version = "0.1.0" +dependencies = [ + "log", + "spacetimedb 1.11.2", +] + [[package]] name = "benchmarks-module" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index a63949f1fcd..e99a9e30206 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,8 @@ members = [ "modules/keynote-benchmarks", "modules/perf-test", "modules/module-test", - "templates/quickstart-chat-rust/spacetimedb", + "templates/chat-console-rs/spacetimedb", + "templates/basic-rs/spacetimedb", "modules/sdk-test", "modules/sdk-test-connect-disconnect", "modules/sdk-test-procedure", @@ -168,10 +169,16 @@ colored = "2.0.0" console = { version = "0.15.6" } convert_case = "0.6.0" crc32c = "0.6.4" -criterion = { version = "0.5.1", features = ["async", "async_tokio", "html_reports"] } +criterion = { version = "0.5.1", features = [ + "async", + "async_tokio", + "html_reports", +] } crossbeam-channel = "0.5" crossbeam-queue = "0.3.12" -cursive = { version = "0.20", default-features = false, features = ["crossterm-backend"] } +cursive = { version = "0.20", default-features = false, features = [ + "crossterm-backend", +] } decorum = { version = "0.3.1", default-features = false, features = ["std"] } derive_more = "0.99" dialoguer = { version = "0.11", default-features = false } @@ -195,14 +202,19 @@ futures-util = "0.3" getrandom02 = { package = "getrandom", version = "0.2" } git2 = "0.19" glob = "0.3.1" -hashbrown = { version = "0.16.1", default-features = false, features = ["equivalent", "inline-more", "rayon", "serde"] } +hashbrown = { version = "0.16.1", default-features = false, features = [ + "equivalent", + "inline-more", + "rayon", + "serde", +] } headers = "0.4" heck = "0.4" hex = "0.4.3" home = "0.5" hostname = "^0.3" http = "1.0" -http-body-util= "0.1.3" +http-body-util = "0.1.3" humantime = "2.1.0" hyper = "1.0" hyper-util = { version = "0.1", features = ["tokio"] } @@ -232,7 +244,10 @@ paste = "1.0" percent-encoding = "2.3" petgraph = { version = "0.6.5", default-features = false } pin-project-lite = "0.2.9" -pgwire = { version = "0.34.2", default-features = false, features = ["server-api", "pg-ext-types"] } +pgwire = { version = "0.34.2", default-features = false, features = [ + "server-api", + "pg-ext-types", +] } postgres-types = "0.2.5" pretty_assertions = { version = "1.4", features = ["unstable"] } proc-macro2 = "1.0" @@ -262,7 +277,10 @@ second-stack = "0.3" self-replace = "1.5" semver = "1" serde = { version = "1.0.136", features = ["derive"] } -serde_json = { version = "1.0.128", features = ["raw_value", "arbitrary_precision"] } +serde_json = { version = "1.0.128", features = [ + "raw_value", + "arbitrary_precision", +] } serde_path_to_error = "0.1.9" serde_with = { version = "3.3.0", features = ["base64", "hex"] } serial_test = "2.0.0" @@ -279,7 +297,9 @@ sqllogictest-engines = "0.17" sqlparser = "0.38.0" strum = { version = "0.25.0", features = ["derive"] } syn = { version = "2", features = ["full", "extra-traits"] } -syntect = { version = "5.0.0", default-features = false, features = ["default-fancy"] } +syntect = { version = "5.0.0", default-features = false, features = [ + "default-fancy", +] } tabled = "0.14.0" tar = "0.4" tempdir = "0.3.7" diff --git a/crates/bindings-typescript/package.json b/crates/bindings-typescript/package.json index 7b83e8e1c4f..4b30509038e 100644 --- a/crates/bindings-typescript/package.json +++ b/crates/bindings-typescript/package.json @@ -36,10 +36,10 @@ "generate:moduledef": "cargo run -p spacetimedb-codegen --example regen-typescript-moduledef && prettier --write src/lib/autogen", "generate:client-api": "cargo run -p generate-client-api && prettier --write src/sdk/client_api", "generate:test-app": "pnpm --filter @clockworklabs/test-app generate", - "generate:examples:quickstart-chat": "pnpm --filter @clockworklabs/quickstart-chat generate", - "generate:examples:basic-react": "pnpm --filter @clockworklabs/basic-react generate", + "generate:examples:chat-react-ts": "pnpm --filter @clockworklabs/chat-react-ts generate", + "generate:examples:react-ts": "pnpm --filter @clockworklabs/react-ts generate", "generate:examples:empty": "pnpm --filter @clockworklabs/empty-client generate", - "generate": "pnpm generate:moduledef && pnpm generate:client-api && pnpm generate:test-app && pnpm generate:examples:quickstart-chat && pnpm generate:examples:basic-react && pnpm generate:examples:empty", + "generate": "pnpm generate:moduledef && pnpm generate:client-api && pnpm generate:test-app && pnpm generate:examples:chat-react-ts && pnpm generate:examples:react-ts && pnpm generate:examples:empty", "prepublishOnly": "pnpm run build && pnpm run test && pnpm run size" }, "main": "dist/index.cjs", diff --git a/crates/cli/build.rs b/crates/cli/build.rs index e49f1e0cbad..00f97dfa3f7 100644 --- a/crates/cli/build.rs +++ b/crates/cli/build.rs @@ -314,8 +314,8 @@ fn generate_template_entry(code: &mut String, template_path: &Path, source: &str // Example: crates/cli let manifest_rel = manifest_canonical.strip_prefix(&repo_root_canonical).unwrap(); - // Example for inside crate: /Users/user/SpacetimeDB/crates/cli/templates/basic-rust/server - // Example for outside crate: /Users/user/SpacetimeDB/modules/quickstart-chat + // Example for inside crate: /Users/user/SpacetimeDB/crates/cli/templates/basic-rs/server + // Example for outside crate: /Users/user/SpacetimeDB/modules/chat-console-rs let resolved_canonical = repo_root.join(&resolved_base).canonicalize().unwrap(); // If the files are outside of the cli crate we need to copy them to the crate directory, @@ -337,8 +337,8 @@ fn generate_template_entry(code: &mut String, template_path: &Path, source: &str code.push_str(" let mut files = HashMap::new();\n"); for file_path in git_files { - // Example file_path: modules/quickstart-chat/src/lib.rs (relative to repo root) - // Example resolved_base: modules/quickstart-chat + // Example file_path: modules/chat-console-rs/src/lib.rs (relative to repo root) + // Example resolved_base: modules/chat-console-rs // Example relative_path: src/lib.rs let relative_path = match file_path.strip_prefix(&resolved_base) { Ok(p) => p, @@ -360,33 +360,33 @@ fn generate_template_entry(code: &mut String, template_path: &Path, source: &str if full_path.exists() && full_path.is_file() { let include_path = if let Some(ref copy_dir) = local_copy_dir { // Outside crate: copy to .templates - // Example dest_file: /Users/user/SpacetimeDB/crates/cli/.templates/parent_parent_modules_quickstart-chat/src/lib.rs + // Example dest_file: /Users/user/SpacetimeDB/crates/cli/.templates/parent_parent_modules_chat-console-rs/src/lib.rs let dest_file = copy_dir.join(relative_path); fs::create_dir_all(dest_file.parent().unwrap()).expect("Failed to create parent directory"); copy_if_changed(&full_path, &dest_file) .unwrap_or_else(|_| panic!("Failed to copy file {:?} to {:?}", full_path, dest_file)); - // Example relative_to_manifest: .templates/parent_parent_modules_quickstart-chat/src/lib.rs + // Example relative_to_manifest: .templates/parent_parent_modules_chat-console-rs/src/lib.rs let relative_to_manifest = dest_file.strip_prefix(manifest_dir).unwrap(); let path_str = relative_to_manifest.to_str().unwrap().replace("\\", "/"); // Watch the original file for changes - // Example: modules/quickstart-chat/src/lib.rs + // Example: modules/chat-console-rs/src/lib.rs println!("cargo:rerun-if-changed={}", full_path.display()); path_str } else { // Inside crate: use path relative to CARGO_MANIFEST_DIR - // Example file_path: crates/cli/templates/basic-rust/server/src/lib.rs + // Example file_path: crates/cli/templates/basic-rs/server/src/lib.rs // Example manifest_rel: crates/cli - // Result: templates/basic-rust/server/src/lib.rs + // Result: templates/basic-rs/server/src/lib.rs let relative_to_manifest = file_path.strip_prefix(manifest_rel).unwrap(); let path_str = relative_to_manifest.to_str().unwrap().replace("\\", "/"); - // Example: crates/cli/templates/basic-rust/server/src/lib.rs + // Example: crates/cli/templates/basic-rs/server/src/lib.rs println!("cargo:rerun-if-changed={}", full_path.display()); path_str }; - // Example include_path (inside crate): "templates/basic-rust/server/src/lib.rs" - // Example include_path (outside crate): ".templates/parent_parent_modules_quickstart-chat/src/lib.rs" + // Example include_path (inside crate): "templates/basic-rs/server/src/lib.rs" + // Example include_path (outside crate): ".templates/parent_parent_modules_chat-console-rs/src/lib.rs" // Example relative_str: "src/lib.rs" code.push_str(&format!( " files.insert(\"{}\", include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/{}\")));\n", diff --git a/crates/cli/src/subcommands/init.rs b/crates/cli/src/subcommands/init.rs index 8530bde2933..0d313afc545 100644 --- a/crates/cli/src/subcommands/init.rs +++ b/crates/cli/src/subcommands/init.rs @@ -1484,11 +1484,11 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> anyhow::Result anyhow::Result<()> { let export_files = vec![ ( - include_str!("../../../../templates/basic-rust/spacetimedb/Cargo.toml"), + include_str!("../../../../templates/basic-rs/spacetimedb/Cargo.toml"), "Cargo.toml", ), ( - include_str!("../../../../templates/basic-rust/spacetimedb/src/lib.rs"), + include_str!("../../../../templates/basic-rs/spacetimedb/src/lib.rs"), "src/lib.rs", ), ]; @@ -1508,15 +1508,15 @@ pub fn init_rust_project(project_path: &Path) -> anyhow::Result<()> { pub fn init_csharp_project(project_path: &Path) -> anyhow::Result<()> { let export_files = vec![ ( - include_str!("../../../../templates/basic-c-sharp/spacetimedb/StdbModule.csproj"), + include_str!("../../../../templates/basic-cs/spacetimedb/StdbModule.csproj"), "StdbModule.csproj", ), ( - include_str!("../../../../templates/basic-c-sharp/spacetimedb/Lib.cs"), + include_str!("../../../../templates/basic-cs/spacetimedb/Lib.cs"), "Lib.cs", ), ( - include_str!("../../../../templates/basic-c-sharp/spacetimedb/global.json"), + include_str!("../../../../templates/basic-cs/spacetimedb/global.json"), "global.json", ), ]; @@ -1536,15 +1536,15 @@ pub fn init_csharp_project(project_path: &Path) -> anyhow::Result<()> { pub fn init_typescript_project(project_path: &Path) -> anyhow::Result<()> { let export_files = vec![ ( - include_str!("../../../../templates/basic-typescript/spacetimedb/package.json"), + include_str!("../../../../templates/basic-ts/spacetimedb/package.json"), "package.json", ), ( - include_str!("../../../../templates/basic-typescript/spacetimedb/tsconfig.json"), + include_str!("../../../../templates/basic-ts/spacetimedb/tsconfig.json"), "tsconfig.json", ), ( - include_str!("../../../../templates/basic-typescript/spacetimedb/src/index.ts"), + include_str!("../../../../templates/basic-ts/spacetimedb/src/index.ts"), "src/index.ts", ), ]; diff --git a/crates/cli/tests/dev.rs b/crates/cli/tests/dev.rs index 0bb0c913557..477546c533f 100644 --- a/crates/cli/tests/dev.rs +++ b/crates/cli/tests/dev.rs @@ -54,7 +54,7 @@ fn cli_init_with_template_creates_project() { .args([ "init", "--template", - "basic-rust", + "basic-rs", "--local", "--non-interactive", "test-project", diff --git a/crates/cli/tests/publish.rs b/crates/cli/tests/publish.rs index 3ef8eab4a36..9e048047e07 100644 --- a/crates/cli/tests/publish.rs +++ b/crates/cli/tests/publish.rs @@ -10,7 +10,7 @@ fn cli_can_publish_spacetimedb_on_disk() { // dir = /modules/quickstart-chat let dir = workspace_dir .join("templates") - .join("quickstart-chat-rust") + .join("chat-console-rs") .join("spacetimedb"); let mut cmd = cargo_bin_cmd!("spacetimedb-cli"); diff --git a/docs/STYLE.md b/docs/STYLE.md index 5e11c5389bb..b5983a759f1 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -411,4 +411,4 @@ If the tutorial involved writing code, add a link to the complete code. This sho At the end of the tutorial that builds the `quickstart-chat` module in Rust, you might write: -> You can find the full code for this module in [the SpacetimeDB module examples](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/quickstart-chat-rust/spacetimedb). +> You can find the full code for this module in [the SpacetimeDB module examples](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/chat-console-rs/spacetimedb). diff --git a/docs/docs/00100-intro/00200-quickstarts/00100-react.md b/docs/docs/00100-intro/00200-quickstarts/00100-react.md index c254e9ca2de..129140e5281 100644 --- a/docs/docs/00100-intro/00200-quickstarts/00100-react.md +++ b/docs/docs/00100-intro/00200-quickstarts/00100-react.md @@ -29,7 +29,7 @@ Get a SpacetimeDB React app running in under 5 minutes. ```bash -spacetime dev --template basic-react my-spacetime-app +spacetime dev --template react-ts my-spacetime-app ``` diff --git a/docs/docs/00100-intro/00200-quickstarts/00400-typescript.md b/docs/docs/00100-intro/00200-quickstarts/00400-typescript.md index 4510c2e57ca..374aa83fd43 100644 --- a/docs/docs/00100-intro/00200-quickstarts/00400-typescript.md +++ b/docs/docs/00100-intro/00200-quickstarts/00400-typescript.md @@ -29,7 +29,7 @@ Get a SpacetimeDB TypeScript app running in under 5 minutes. ```bash -spacetime dev --template basic-typescript my-spacetime-app +spacetime dev --template basic-ts my-spacetime-app ``` diff --git a/docs/docs/00100-intro/00200-quickstarts/00500-rust.md b/docs/docs/00100-intro/00200-quickstarts/00500-rust.md index ec33acbc918..4bc561fa092 100644 --- a/docs/docs/00100-intro/00200-quickstarts/00500-rust.md +++ b/docs/docs/00100-intro/00200-quickstarts/00500-rust.md @@ -29,7 +29,7 @@ Get a SpacetimeDB Rust app running in under 5 minutes. ```bash -spacetime dev --template basic-rust my-spacetime-app +spacetime dev --template basic-rs my-spacetime-app ``` diff --git a/docs/docs/00100-intro/00200-quickstarts/00600-c-sharp.md b/docs/docs/00100-intro/00200-quickstarts/00600-c-sharp.md index eb6ddb5e2fa..86635b257e6 100644 --- a/docs/docs/00100-intro/00200-quickstarts/00600-c-sharp.md +++ b/docs/docs/00100-intro/00200-quickstarts/00600-c-sharp.md @@ -40,7 +40,7 @@ dotnet workload install wasi-experimental ```bash -spacetime dev --template basic-c-sharp my-spacetime-app +spacetime dev --template basic-cs my-spacetime-app ``` diff --git a/docs/docs/00100-intro/00300-tutorials/00100-chat-app.md b/docs/docs/00100-intro/00300-tutorials/00100-chat-app.md index 14064ef614d..3f9b5f72239 100644 --- a/docs/docs/00100-intro/00300-tutorials/00100-chat-app.md +++ b/docs/docs/00100-intro/00300-tutorials/00100-chat-app.md @@ -661,9 +661,9 @@ Output will resemble: ``` You've just set up your first SpacetimeDB module! You can find the full code for this module: -- [TypeScript server module](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/quickstart-chat-typescript) -- [C# server module](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/quickstart-chat-c-sharp/spacetimedb) -- [Rust server module](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/quickstart-chat-rust/spacetimedb) +- [TypeScript server module](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/chat-react-ts) +- [C# server module](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/chat-console-cs/spacetimedb) +- [Rust server module](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/chat-console-rs/spacetimedb) --- @@ -1429,7 +1429,7 @@ You've just experienced the core features of SpacetimeDB: real-time synchronizat ### Conclusion -Congratulations! You've built a simple chat app with SpacetimeDB. You can find the full source code for the client we've created in this quickstart tutorial [here](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/quickstart-chat-typescript). +Congratulations! You've built a simple chat app with SpacetimeDB. You can find the full source code for the client we've created in this quickstart tutorial [here](https://github.com/clockworklabs/SpacetimeDB/tree/master/templates/chat-react-ts). At this point you've learned how to create a basic TypeScript client for your SpacetimeDB `quickstart-chat` module. You've learned how to connect to SpacetimeDB and call reducers to update data. You've learned how to subscribe to table data, and hook it up so that it updates reactively in a React application. diff --git a/docs/docs/00200-core-concepts/00100-databases/00200-spacetime-dev.md b/docs/docs/00200-core-concepts/00100-databases/00200-spacetime-dev.md index 4a3eb6ffa21..864d28bf4e2 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00200-spacetime-dev.md +++ b/docs/docs/00200-core-concepts/00100-databases/00200-spacetime-dev.md @@ -64,13 +64,13 @@ Creates a full-stack React web application with: #### Use Template Choose from several built-in templates: -- `basic-typescript` - Basic TypeScript client and server stubs -- `basic-c-sharp` - Basic C# client and server stubs -- `basic-rust` - Basic Rust client and server stubs -- `basic-react` - React web app with TypeScript server -- `quickstart-chat-rust` - Complete Rust chat implementation -- `quickstart-chat-c-sharp` - Complete C# chat implementation -- `quickstart-chat-typescript` - Complete TypeScript chat implementation +- `basic-ts` - Basic TypeScript client and server stubs +- `basic-cs` - Basic C# client and server stubs +- `basic-rs` - Basic Rust client and server stubs +- `react-ts` - React web app with TypeScript server +- `chat-console-rs` - Complete Rust chat implementation +- `chat-console-cs` - Complete C# chat implementation +- `chat-react-ts` - Complete TypeScript chat implementation You can also clone an existing project by entering a GitHub repository (`owner/repo`) or git URL. diff --git a/eslint.config.js b/eslint.config.js index 4f96b16ab8e..ed23aceef3c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -38,9 +38,6 @@ export default tseslint.config( './tsconfig.json', './crates/bindings-typescript/tsconfig.json', './crates/bindings-typescript/test-app/tsconfig.json', - './crates/bindings-typescript/examples/basic-react/tsconfig.json', - './crates/bindings-typescript/examples/empty/tsconfig.json', - './crates/bindings-typescript/examples/quickstart-chat/tsconfig.json', './docs/tsconfig.json', ], projectService: true, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e9de64e1c10..d3628700fb1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -258,35 +258,7 @@ importers: specifier: workspace:^ version: link:../../crates/bindings-typescript - templates/basic-react: - dependencies: - react: - specifier: ^18.3.1 - version: 18.3.1 - react-dom: - specifier: ^18.3.1 - version: 18.3.1(react@18.3.1) - spacetimedb: - specifier: workspace:* - version: link:../../crates/bindings-typescript - devDependencies: - '@types/react': - specifier: ^18.3.18 - version: 18.3.23 - '@types/react-dom': - specifier: ^18.3.5 - version: 18.3.7(@types/react@18.3.23) - '@vitejs/plugin-react': - specifier: ^5.0.2 - version: 5.0.2(vite@7.1.5(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)) - typescript: - specifier: ~5.6.2 - version: 5.6.3 - vite: - specifier: ^7.1.5 - version: 7.1.5(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) - - templates/basic-typescript: + templates/basic-ts: dependencies: spacetimedb: specifier: workspace:* @@ -299,7 +271,7 @@ importers: specifier: ^7.1.5 version: 7.1.5(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) - templates/quickstart-chat-typescript: + templates/chat-react-ts: dependencies: react: specifier: ^18.3.1 @@ -363,12 +335,40 @@ importers: specifier: 3.2.4 version: 3.2.4(@types/debug@4.1.12)(@types/node@24.3.0)(jiti@2.5.1)(jsdom@26.1.0)(terser@5.43.1)(tsx@4.20.4) - templates/quickstart-chat-typescript/spacetimedb: + templates/chat-react-ts/spacetimedb: dependencies: spacetimedb: specifier: workspace:^ version: link:../../../crates/bindings-typescript + templates/react-ts: + dependencies: + react: + specifier: ^18.3.1 + version: 18.3.1 + react-dom: + specifier: ^18.3.1 + version: 18.3.1(react@18.3.1) + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/react': + specifier: ^18.3.18 + version: 18.3.23 + '@types/react-dom': + specifier: ^18.3.5 + version: 18.3.7(@types/react@18.3.23) + '@vitejs/plugin-react': + specifier: ^5.0.2 + version: 5.0.2(vite@7.1.5(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)) + typescript: + specifier: ~5.6.2 + version: 5.6.3 + vite: + specifier: ^7.1.5 + version: 7.1.5(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) + packages: '@adobe/css-tools@4.4.4': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 0b6b411ea9e..4dbfe8479b4 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,12 +1,12 @@ packages: - 'crates/bindings-typescript' - 'crates/bindings-typescript/test-app' - - 'templates/quickstart-chat-typescript' - - 'templates/basic-react' - - 'templates/basic-typescript' + - 'templates/chat-react-ts' + - 'templates/react-ts' + - 'templates/basic-ts' - 'modules/benchmarks-ts' - 'modules/module-test-ts' - - 'templates/quickstart-chat-typescript/spacetimedb' + - 'templates/chat-react-ts/spacetimedb' - 'modules/sdk-test-connect-disconnect-ts' - 'modules/sdk-test-procedure-ts' - 'modules/sdk-test-ts' diff --git a/sdks/csharp/DEVELOP.md b/sdks/csharp/DEVELOP.md index 9f02025de65..ff56a1baf82 100644 --- a/sdks/csharp/DEVELOP.md +++ b/sdks/csharp/DEVELOP.md @@ -29,11 +29,11 @@ The SDK uses multiple layers of code generation: The code created by `spacetime generate` imports the SpacetimeDB SDK and extends its various classes to create a SpacetimeDB client. It also imports `SpacetimeDB.BSATN.Codegen` for its serialization needs. -See [`../../templates/quickstart-chat-c-sharp/module_bindings`](../../templates/quickstart-chat-c-sharp/module_bindings/) for an example of what `spacetime generate`d code looks like. +See [`../../templates/chat-console-cs/module_bindings`](../../templates/chat-console-cs/module_bindings/) for an example of what `spacetime generate`d code looks like. If you need to debug `SpacetimeDB.BSATN.Codegen`, you can set `true` in the `` in the SDK code, which lives in [`src/SpacetimeDBClient.cs`](./src/SpacetimeDBClient.cs). This is a general pattern. Similar inheritance patterns are used for tables and indexes: the generated code defines a class that inherits most of its behavior from a class in the SDK. diff --git a/sdks/csharp/SpacetimeDB.ClientSDK.sln b/sdks/csharp/SpacetimeDB.ClientSDK.sln index 0c5f2d3d978..aa629fb0411 100644 --- a/sdks/csharp/SpacetimeDB.ClientSDK.sln +++ b/sdks/csharp/SpacetimeDB.ClientSDK.sln @@ -7,7 +7,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpacetimeDB.ClientSDK", "Sp EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "tests", "tests~\tests.csproj", "{5CD31104-4719-4CE3-8D39-8BAE0B75C085}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "client", "..\..\templates\quickstart-chat-c-sharp\client.csproj", "{FE261832-1594-DE21-C8C8-2D525680CBD7}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "client", "..\..\templates\chat-console-cs\client.csproj", "{FE261832-1594-DE21-C8C8-2D525680CBD7}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples~", "examples~", "{E0CADA48-79A1-4490-ACEC-698EC7D2AB43}" EndProject diff --git a/sdks/csharp/tests~/tests.csproj b/sdks/csharp/tests~/tests.csproj index 02fb3372328..bcb4e59fef0 100644 --- a/sdks/csharp/tests~/tests.csproj +++ b/sdks/csharp/tests~/tests.csproj @@ -24,7 +24,7 @@ - + diff --git a/sdks/csharp/tools~/gen-quickstart.sh b/sdks/csharp/tools~/gen-quickstart.sh index 340c06b6e2f..25a1abf2213 100755 --- a/sdks/csharp/tools~/gen-quickstart.sh +++ b/sdks/csharp/tools~/gen-quickstart.sh @@ -7,4 +7,4 @@ SDK_PATH="$(realpath "$SDK_PATH")" STDB_PATH="$SDK_PATH/../.." cargo build --manifest-path "$STDB_PATH/crates/standalone/Cargo.toml" -cargo run --manifest-path "$STDB_PATH/crates/cli/Cargo.toml" -- generate -y -l csharp -o "$STDB_PATH/templates/quickstart-chat-c-sharp/module_bindings" --project-path "$STDB_PATH/templates/quickstart-chat-c-sharp/spacetimedb" +cargo run --manifest-path "$STDB_PATH/crates/cli/Cargo.toml" -- generate -y -l csharp -o "$STDB_PATH/templates/chat-console-cs/module_bindings" --project-path "$STDB_PATH/templates/chat-console-cs/spacetimedb" diff --git a/smoketests/__init__.py b/smoketests/__init__.py index 657b7740361..effb7781065 100644 --- a/smoketests/__init__.py +++ b/smoketests/__init__.py @@ -25,8 +25,8 @@ BASE_STDB_CONFIG_PATH = TEST_DIR / "config.toml" # the contents of files for the base smoketest project template -TEMPLATE_LIB_RS = open(STDB_DIR / "templates/basic-rust/spacetimedb/src/lib.rs").read() -TEMPLATE_CARGO_TOML = open(STDB_DIR / "templates/basic-rust/spacetimedb/Cargo.toml").read() +TEMPLATE_LIB_RS = open(STDB_DIR / "templates/basic-rs/spacetimedb/src/lib.rs").read() +TEMPLATE_CARGO_TOML = open(STDB_DIR / "templates/basic-rs/spacetimedb/Cargo.toml").read() bindings_path = (STDB_DIR / "crates/bindings").absolute() escaped_bindings_path = str(bindings_path).replace('\\', '\\\\\\\\') # double escape for re.sub + toml TYPESCRIPT_BINDINGS_PATH = (STDB_DIR / "crates/bindings-typescript").absolute() diff --git a/smoketests/tests/spacetimedb_init.py b/smoketests/tests/spacetimedb_init.py new file mode 100644 index 00000000000..c2408e89632 --- /dev/null +++ b/smoketests/tests/spacetimedb_init.py @@ -0,0 +1,233 @@ +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +import toml + +from .. import STDB_DIR, spacetime, pnpm, requires_dotnet, run_cmd + + +class TestSpacetimeInit(unittest.TestCase): + def get_templates(self): + templates_dir = STDB_DIR / "templates" + templates = [] + + for entry in templates_dir.iterdir(): + if not entry.is_dir(): + continue + + template_json = entry / ".template.json" + if not template_json.exists(): + continue + + with open(template_json) as f: + metadata = json.load(f) + + templates.append({ + "id": entry.name, + "server_lang": metadata["server_lang"], + "client_lang": metadata.get("client_lang"), + }) + + return templates + + def test_init_and_publish_all_templates(self): + templates = self.get_templates() + self.assertGreater(len(templates), 0, "No templates found") + + print(f"\nTesting {len(templates)} template(s)...") + print("="*60) + + results = {} + passed_count = 0 + failed_count = 0 + + for i, template in enumerate(templates, 1): + print(f"\n[{i}/{len(templates)}] Testing template: {template['id']}") + print("-" * 60) + with self.subTest(template=template["id"]): + try: + self._test_template(template) + results[template["id"]] = "[PASS]" + passed_count += 1 + print(f"[PASS] {template['id']}") + except Exception as e: + results[template["id"]] = f"[FAIL]: {str(e)}" + failed_count += 1 + print(f"[FAIL] {template['id']}: {str(e)}") + raise + + print("\n" + "="*60) + print("TEMPLATE TEST SUMMARY") + print("="*60) + for template_id, result in sorted(results.items()): + print(f"{template_id:30} {result}") + print("="*60) + + total = len(results) + print(f"TOTAL: {passed_count}/{total} passed\n") + + def _test_template(self, template): + with tempfile.TemporaryDirectory() as tmpdir: + project_name = f"test-{template['id']}" + project_path = Path(tmpdir) / project_name + + print(f" > Initializing project from template...") + spacetime( + "init", + "--template", template["id"], + "--project-path", str(project_path), + "--non-interactive", + project_name + ) + + self.assertTrue(project_path.exists(), f"Project directory not created for {template['id']}") + + if template.get("server_lang"): + server_path = project_path / "spacetimedb" + self.assertTrue(server_path.exists(), f"Server directory not found for {template['id']}") + + print(f" > Publishing server...") + self._publish_server(template, server_path) + + if template.get("client_lang"): + print(f" > Testing client...") + self._test_client(template, project_path) + + def _publish_server(self, template, server_path): + server_lang = template["server_lang"] + template_id = template["id"] + + if server_lang == "typescript": + self._setup_typescript_local_sdk(server_path) + pnpm("install", cwd=server_path) + + if server_lang == "rust": + self._setup_rust_local_sdk(server_path) + + if server_lang == "csharp": + self._setup_csharp_nuget(server_path) + + domain = f"test-{server_lang}-{os.urandom(8).hex()}" + print(f" > Building and publishing template '{template_id}' (language: {server_lang}) at {server_path}") + spacetime("publish", "-s", "local", "--yes", "--project-path", str(server_path), domain) + + spacetime("delete", "-s", "local", "--yes", domain) + + def _update_cargo_toml_dependency(self, cargo_toml_path, package_name, local_path): + """Replace crates.io dependency with local path dependency.""" + if not cargo_toml_path.exists(): + return + + cargo_data = toml.load(cargo_toml_path) + + if package_name in cargo_data.get("dependencies", {}): + cargo_data["dependencies"][package_name] = {"path": str(local_path)} + + with open(cargo_toml_path, 'w') as f: + toml.dump(cargo_data, f) + + def _setup_rust_local_sdk(self, server_path): + """Replace crates.io spacetimedb dependency with local path dependency.""" + print(f" > Setting up local Rust SDK...") + cargo_toml_path = server_path / "Cargo.toml" + rust_sdk_path = STDB_DIR / "crates/bindings" + self._update_cargo_toml_dependency(cargo_toml_path, "spacetimedb", rust_sdk_path) + + def _update_package_json_dependency(self, package_json_path, package_name, local_path): + """Replace npm package dependency with local path reference.""" + with open(package_json_path, 'r') as f: + package_data = json.load(f) + + # Convert to absolute path and format as URI for npm/pnpm file: protocol + abs_path = Path(local_path).absolute() + # Use as_uri() to get proper file:// URL format (works on both Windows and Unix) + file_url = abs_path.as_uri() + package_data["dependencies"][package_name] = file_url + + with open(package_json_path, 'w') as f: + json.dump(package_data, f, indent=2) + + def _setup_typescript_local_sdk(self, server_path): + """Replace npm registry spacetimedb dependency with local SDK path reference.""" + print(f" > Setting up local TypeScript SDK...") + typescript_sdk_path = STDB_DIR / "crates/bindings-typescript" + print(f" > Building TypeScript SDK...") + pnpm("install", cwd=typescript_sdk_path) + pnpm("build", cwd=typescript_sdk_path) + + # Create a global link from the SDK + print(f" > Linking TypeScript SDK globally...") + pnpm("link", "--global", cwd=typescript_sdk_path) + + # Link it in the server project + print(f" > Linking spacetimedb package in server...") + pnpm("link", "--global", "spacetimedb", cwd=server_path) + + # Remove lockfile since the linked version may differ from lockfile spec + lockfile = server_path / "pnpm-lock.yaml" + if lockfile.exists(): + lockfile.unlink() + + def _setup_csharp_nuget(self, server_path): + """Create a local nuget.config file to avoid polluting global NuGet sources""" + print(f" > Setting up C# NuGet sources...") + nuget_config = server_path / "nuget.config" + if not nuget_config.exists(): + nuget_config.write_text(""" + + + + + + +""") + + bindings = STDB_DIR / "crates/bindings-csharp" + packed_projects = ["BSATN.Runtime", "Runtime", "BSATN.Codegen", "Codegen"] + + for project in packed_projects: + run_cmd("dotnet", "pack", "-c", "Release", cwd=bindings / project) + path = bindings / project / "bin" / "Release" + project_name = f"SpacetimeDB.{project}" + run_cmd("dotnet", "nuget", "add", "source", str(path), "-n", project_name, "--configfile", str(nuget_config), cwd=server_path) + + # Pack ClientSDK for client projects + client_sdk = STDB_DIR / "sdks/csharp" + client_sdk_proj = client_sdk / "SpacetimeDB.ClientSDK.csproj" + run_cmd("dotnet", "pack", str(client_sdk_proj), "-c", "Release") + client_sdk_path = client_sdk / "bin~" / "Release" + run_cmd("dotnet", "nuget", "add", "source", str(client_sdk_path), "-n", "SpacetimeDB.ClientSDK", "--configfile", str(nuget_config), cwd=server_path) + + def _test_client(self, template, project_path): + """Test the client code based on the client language.""" + client_lang = template.get("client_lang") + + if client_lang == "rust": + print(f" - Building Rust client...") + # Setup local SDK for client + client_cargo_toml = project_path / "Cargo.toml" + rust_sdk_path = STDB_DIR / "sdks/rust" + self._update_cargo_toml_dependency(client_cargo_toml, "spacetimedb-sdk", rust_sdk_path) + run_cmd("cargo", "build", cwd=project_path) + + elif client_lang == "typescript": + print(f" - Type-checking TypeScript client...") + # Link the globally linked spacetimedb package + pnpm("link", "--global", "spacetimedb", cwd=project_path) + # Remove lockfile since the linked version may differ from lockfile spec + lockfile = project_path / "pnpm-lock.yaml" + if lockfile.exists(): + lockfile.unlink() + # Install other dependencies + pnpm("install", cwd=project_path) + # Run TypeScript compiler in check mode + pnpm("exec", "tsc", "--noEmit", cwd=project_path) + + elif client_lang == "csharp": + print(f" - Building C# client...") + # Setup nuget for client if needed + self._setup_csharp_nuget(project_path) + run_cmd("dotnet", "build", cwd=project_path) diff --git a/templates/basic-c-sharp/module_bindings/Reducers/Add.g.cs b/templates/basic-c-sharp/module_bindings/Reducers/Add.g.cs new file mode 100644 index 00000000000..d64911a70ad --- /dev/null +++ b/templates/basic-c-sharp/module_bindings/Reducers/Add.g.cs @@ -0,0 +1,80 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void AddHandler(ReducerEventContext ctx, string name, int age); + public event AddHandler? OnAdd; + + public void Add(string name, int age) + { + conn.InternalCallReducer(new Reducer.Add(name, age), this.SetCallReducerFlags.AddFlags); + } + + public bool InvokeAdd(ReducerEventContext ctx, Reducer.Add args) + { + if (OnAdd == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnAdd( + ctx, + args.Name, + args.Age + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Add : Reducer, IReducerArgs + { + [DataMember(Name = "name")] + public string Name; + [DataMember(Name = "age")] + public int Age; + + public Add( + string Name, + int Age + ) + { + this.Name = Name; + this.Age = Age; + } + + public Add() + { + this.Name = ""; + } + + string IReducerArgs.ReducerName => "Add"; + } + } + + public sealed partial class SetReducerFlags + { + internal CallReducerFlags AddFlags; + public void Add(CallReducerFlags flags) => AddFlags = flags; + } +} diff --git a/templates/basic-c-sharp/module_bindings/Reducers/SayHello.g.cs b/templates/basic-c-sharp/module_bindings/Reducers/SayHello.g.cs new file mode 100644 index 00000000000..90af68404f9 --- /dev/null +++ b/templates/basic-c-sharp/module_bindings/Reducers/SayHello.g.cs @@ -0,0 +1,59 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteReducers : RemoteBase + { + public delegate void SayHelloHandler(ReducerEventContext ctx); + public event SayHelloHandler? OnSayHello; + + public void SayHello() + { + conn.InternalCallReducer(new Reducer.SayHello(), this.SetCallReducerFlags.SayHelloFlags); + } + + public bool InvokeSayHello(ReducerEventContext ctx, Reducer.SayHello args) + { + if (OnSayHello == null) + { + if (InternalOnUnhandledReducerError != null) + { + switch (ctx.Event.Status) + { + case Status.Failed(var reason): InternalOnUnhandledReducerError(ctx, new Exception(reason)); break; + case Status.OutOfEnergy(var _): InternalOnUnhandledReducerError(ctx, new Exception("out of energy")); break; + } + } + return false; + } + OnSayHello( + ctx + ); + return true; + } + } + + public abstract partial class Reducer + { + [SpacetimeDB.Type] + [DataContract] + public sealed partial class SayHello : Reducer, IReducerArgs + { + string IReducerArgs.ReducerName => "SayHello"; + } + } + + public sealed partial class SetReducerFlags + { + internal CallReducerFlags SayHelloFlags; + public void SayHello(CallReducerFlags flags) => SayHelloFlags = flags; + } +} diff --git a/templates/basic-c-sharp/module_bindings/SpacetimeDBClient.g.cs b/templates/basic-c-sharp/module_bindings/SpacetimeDBClient.g.cs new file mode 100644 index 00000000000..2f18d6eb2ca --- /dev/null +++ b/templates/basic-c-sharp/module_bindings/SpacetimeDBClient.g.cs @@ -0,0 +1,632 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 1.11.2 (commit 3c8836b1a3aa2f1a7176a37838212c432960ce83). + +#nullable enable + +using System; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteReducers : RemoteBase + { + internal RemoteReducers(DbConnection conn, SetReducerFlags flags) : base(conn) => SetCallReducerFlags = flags; + internal readonly SetReducerFlags SetCallReducerFlags; + internal event Action? InternalOnUnhandledReducerError; + } + + public sealed partial class RemoteProcedures : RemoteBase + { + internal RemoteProcedures(DbConnection conn) : base(conn) { } + } + + public sealed partial class RemoteTables : RemoteTablesBase + { + public RemoteTables(DbConnection conn) + { + AddTable(Person = new(conn)); + } + } + + public sealed partial class SetReducerFlags { } + + public interface IRemoteDbContext : IDbContext + { + public event Action? OnUnhandledReducerError; + } + + public sealed class EventContext : IEventContext, IRemoteDbContext + { + private readonly DbConnection conn; + + /// + /// The event that caused this callback to run. + /// + public readonly Event Event; + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to setters for per-reducer flags. + /// + /// The returned SetReducerFlags will have a method to invoke, + /// for each reducer defined by the module, + /// which call-flags for the reducer can be set. + /// + public SetReducerFlags SetReducerFlags => conn.SetReducerFlags; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal EventContext(DbConnection conn, Event Event) + { + this.conn = conn; + this.Event = Event; + } + } + + public sealed class ReducerEventContext : IReducerEventContext, IRemoteDbContext + { + private readonly DbConnection conn; + /// + /// The reducer event that caused this callback to run. + /// + public readonly ReducerEvent Event; + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to setters for per-reducer flags. + /// + /// The returned SetReducerFlags will have a method to invoke, + /// for each reducer defined by the module, + /// which call-flags for the reducer can be set. + /// + public SetReducerFlags SetReducerFlags => conn.SetReducerFlags; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal ReducerEventContext(DbConnection conn, ReducerEvent reducerEvent) + { + this.conn = conn; + Event = reducerEvent; + } + } + + public sealed class ErrorContext : IErrorContext, IRemoteDbContext + { + private readonly DbConnection conn; + /// + /// The Exception that caused this error callback to be run. + /// + public readonly Exception Event; + Exception IErrorContext.Event + { + get + { + return Event; + } + } + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to setters for per-reducer flags. + /// + /// The returned SetReducerFlags will have a method to invoke, + /// for each reducer defined by the module, + /// which call-flags for the reducer can be set. + /// + public SetReducerFlags SetReducerFlags => conn.SetReducerFlags; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal ErrorContext(DbConnection conn, Exception error) + { + this.conn = conn; + Event = error; + } + } + + public sealed class SubscriptionEventContext : ISubscriptionEventContext, IRemoteDbContext + { + private readonly DbConnection conn; + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to setters for per-reducer flags. + /// + /// The returned SetReducerFlags will have a method to invoke, + /// for each reducer defined by the module, + /// which call-flags for the reducer can be set. + /// + public SetReducerFlags SetReducerFlags => conn.SetReducerFlags; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal SubscriptionEventContext(DbConnection conn) + { + this.conn = conn; + } + } + + public sealed class ProcedureEventContext : IProcedureEventContext, IRemoteDbContext + { + private readonly DbConnection conn; + /// + /// The procedure event that caused this callback to run. + /// + public readonly ProcedureEvent Event; + + /// + /// Access to tables in the client cache, which stores a read-only replica of the remote database state. + /// + /// The returned DbView will have a method to access each table defined by the module. + /// + public RemoteTables Db => conn.Db; + /// + /// Access to reducers defined by the module. + /// + /// The returned RemoteReducers will have a method to invoke each reducer defined by the module, + /// plus methods for adding and removing callbacks on each of those reducers. + /// + public RemoteReducers Reducers => conn.Reducers; + /// + /// Access to setters for per-reducer flags. + /// + /// The returned SetReducerFlags will have a method to invoke, + /// for each reducer defined by the module, + /// which call-flags for the reducer can be set. + /// + public SetReducerFlags SetReducerFlags => conn.SetReducerFlags; + /// + /// Access to procedures defined by the module. + /// + /// The returned RemoteProcedures will have a method to invoke each procedure defined by the module, + /// with a callback for when the procedure completes and returns a value. + /// + public RemoteProcedures Procedures => conn.Procedures; + /// + /// Returns true if the connection is active, i.e. has not yet disconnected. + /// + public bool IsActive => conn.IsActive; + /// + /// Close the connection. + /// + /// Throws an error if the connection is already closed. + /// + public void Disconnect() + { + conn.Disconnect(); + } + /// + /// Start building a subscription. + /// + /// A builder-pattern constructor for subscribing to queries, + /// causing matching rows to be replicated into the client cache. + public SubscriptionBuilder SubscriptionBuilder() => conn.SubscriptionBuilder(); + /// + /// Get the Identity of this connection. + /// + /// This method returns null if the connection was constructed anonymously + /// and we have not yet received our newly-generated Identity from the host. + /// + public Identity? Identity => conn.Identity; + /// + /// Get this connection's ConnectionId. + /// + public ConnectionId ConnectionId => conn.ConnectionId; + /// + /// Register a callback to be called when a reducer with no handler returns an error. + /// + public event Action? OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + + internal ProcedureEventContext(DbConnection conn, ProcedureEvent Event) + { + this.conn = conn; + this.Event = Event; + } + } + + /// + /// Builder-pattern constructor for subscription queries. + /// + public sealed class SubscriptionBuilder + { + private readonly IDbConnection conn; + + private event Action? Applied; + private event Action? Error; + + /// + /// Private API, use conn.SubscriptionBuilder() instead. + /// + public SubscriptionBuilder(IDbConnection conn) + { + this.conn = conn; + } + + /// + /// Register a callback to run when the subscription is applied. + /// + public SubscriptionBuilder OnApplied( + Action callback + ) + { + Applied += callback; + return this; + } + + /// + /// Register a callback to run when the subscription fails. + /// + /// Note that this callback may run either when attempting to apply the subscription, + /// in which case Self::on_applied will never run, + /// or later during the subscription's lifetime if the module's interface changes, + /// in which case Self::on_applied may have already run. + /// + public SubscriptionBuilder OnError( + Action callback + ) + { + Error += callback; + return this; + } + + /// + /// Subscribe to the following SQL queries. + /// + /// This method returns immediately, with the data not yet added to the DbConnection. + /// The provided callbacks will be invoked once the data is returned from the remote server. + /// Data from all the provided queries will be returned at the same time. + /// + /// See the SpacetimeDB SQL docs for more information on SQL syntax: + /// https://spacetimedb.com/docs/sql + /// + public SubscriptionHandle Subscribe( + string[] querySqls + ) => new(conn, Applied, Error, querySqls); + + /// + /// Subscribe to all rows from all tables. + /// + /// This method is intended as a convenience + /// for applications where client-side memory use and network bandwidth are not concerns. + /// Applications where these resources are a constraint + /// should register more precise queries via Self.Subscribe + /// in order to replicate only the subset of data which the client needs to function. + /// + /// This method should not be combined with Self.Subscribe on the same DbConnection. + /// A connection may either Self.Subscribe to particular queries, + /// or Self.SubscribeToAllTables, but not both. + /// Attempting to call Self.Subscribe + /// on a DbConnection that has previously used Self.SubscribeToAllTables, + /// or vice versa, may misbehave in any number of ways, + /// including dropping subscriptions, corrupting the client cache, or panicking. + /// + public void SubscribeToAllTables() + { + // Make sure we use the legacy handle constructor here, even though there's only 1 query. + // We drop the error handler, since it can't be called for legacy subscriptions. + new SubscriptionHandle( + conn, + Applied, + new string[] { "SELECT * FROM *" } + ); + } + } + + public sealed class SubscriptionHandle : SubscriptionHandleBase + { + /// + /// Internal API. Construct SubscriptionHandles using conn.SubscriptionBuilder. + /// + public SubscriptionHandle(IDbConnection conn, Action? onApplied, string[] querySqls) : base(conn, onApplied, querySqls) + { } + + /// + /// Internal API. Construct SubscriptionHandles using conn.SubscriptionBuilder. + /// + public SubscriptionHandle( + IDbConnection conn, + Action? onApplied, + Action? onError, + string[] querySqls + ) : base(conn, onApplied, onError, querySqls) + { } + } + + public abstract partial class Reducer + { + private Reducer() { } + } + + public abstract partial class Procedure + { + private Procedure() { } + } + + public sealed class DbConnection : DbConnectionBase + { + public override RemoteTables Db { get; } + public readonly RemoteReducers Reducers; + public readonly SetReducerFlags SetReducerFlags = new(); + public readonly RemoteProcedures Procedures; + + public DbConnection() + { + Db = new(this); + Reducers = new(this, SetReducerFlags); + Procedures = new(this); + } + + protected override Reducer ToReducer(TransactionUpdate update) + { + var encodedArgs = update.ReducerCall.Args; + return update.ReducerCall.ReducerName switch + { + "Add" => BSATNHelpers.Decode(encodedArgs), + "SayHello" => BSATNHelpers.Decode(encodedArgs), + "" => throw new SpacetimeDBEmptyReducerNameException("Reducer name is empty"), + var reducer => throw new ArgumentOutOfRangeException("Reducer", $"Unknown reducer {reducer}") + }; + } + + protected override IEventContext ToEventContext(Event Event) => + new EventContext(this, Event); + + protected override IReducerEventContext ToReducerEventContext(ReducerEvent reducerEvent) => + new ReducerEventContext(this, reducerEvent); + + protected override ISubscriptionEventContext MakeSubscriptionEventContext() => + new SubscriptionEventContext(this); + + protected override IErrorContext ToErrorContext(Exception exception) => + new ErrorContext(this, exception); + + protected override IProcedureEventContext ToProcedureEventContext(ProcedureEvent procedureEvent) => + new ProcedureEventContext(this, procedureEvent); + + protected override bool Dispatch(IReducerEventContext context, Reducer reducer) + { + var eventContext = (ReducerEventContext)context; + return reducer switch + { + Reducer.Add args => Reducers.InvokeAdd(eventContext, args), + Reducer.SayHello args => Reducers.InvokeSayHello(eventContext, args), + _ => throw new ArgumentOutOfRangeException("Reducer", $"Unknown reducer {reducer}") + }; + } + + public SubscriptionBuilder SubscriptionBuilder() => new(this); + public event Action OnUnhandledReducerError + { + add => Reducers.InternalOnUnhandledReducerError += value; + remove => Reducers.InternalOnUnhandledReducerError -= value; + } + } +} diff --git a/templates/basic-c-sharp/module_bindings/Tables/Person.g.cs b/templates/basic-c-sharp/module_bindings/Tables/Person.g.cs new file mode 100644 index 00000000000..411147c5d1d --- /dev/null +++ b/templates/basic-c-sharp/module_bindings/Tables/Person.g.cs @@ -0,0 +1,39 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using SpacetimeDB.BSATN; +using SpacetimeDB.ClientApi; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + public sealed partial class RemoteTables + { + public sealed class PersonHandle : RemoteTableHandle + { + protected override string RemoteTableName => "Person"; + + public sealed class IdUniqueIndex : UniqueIndexBase + { + protected override int GetKey(Person row) => row.Id; + + public IdUniqueIndex(PersonHandle table) : base(table) { } + } + + public readonly IdUniqueIndex Id; + + internal PersonHandle(DbConnection conn) : base(conn) + { + Id = new(this); + } + + protected override object GetPrimaryKey(Person row) => row.Id; + } + + public readonly PersonHandle Person; + } +} diff --git a/templates/basic-c-sharp/module_bindings/Types/Person.g.cs b/templates/basic-c-sharp/module_bindings/Types/Person.g.cs new file mode 100644 index 00000000000..b40c83cbefb --- /dev/null +++ b/templates/basic-c-sharp/module_bindings/Types/Person.g.cs @@ -0,0 +1,39 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace SpacetimeDB.Types +{ + [SpacetimeDB.Type] + [DataContract] + public sealed partial class Person + { + [DataMember(Name = "Id")] + public int Id; + [DataMember(Name = "Name")] + public string Name; + [DataMember(Name = "Age")] + public int Age; + + public Person( + int Id, + string Name, + int Age + ) + { + this.Id = Id; + this.Name = Name; + this.Age = Age; + } + + public Person() + { + this.Name = ""; + } + } +} diff --git a/templates/basic-c-sharp/.template.json b/templates/basic-cs/.template.json similarity index 100% rename from templates/basic-c-sharp/.template.json rename to templates/basic-cs/.template.json diff --git a/templates/basic-c-sharp/LICENSE b/templates/basic-cs/LICENSE similarity index 100% rename from templates/basic-c-sharp/LICENSE rename to templates/basic-cs/LICENSE diff --git a/templates/basic-c-sharp/Program.cs b/templates/basic-cs/Program.cs similarity index 100% rename from templates/basic-c-sharp/Program.cs rename to templates/basic-cs/Program.cs diff --git a/templates/basic-c-sharp/client.csproj b/templates/basic-cs/client.csproj similarity index 100% rename from templates/basic-c-sharp/client.csproj rename to templates/basic-cs/client.csproj diff --git a/templates/basic-c-sharp/spacetimedb/Lib.cs b/templates/basic-cs/spacetimedb/Lib.cs similarity index 100% rename from templates/basic-c-sharp/spacetimedb/Lib.cs rename to templates/basic-cs/spacetimedb/Lib.cs diff --git a/templates/basic-c-sharp/spacetimedb/StdbModule.csproj b/templates/basic-cs/spacetimedb/StdbModule.csproj similarity index 100% rename from templates/basic-c-sharp/spacetimedb/StdbModule.csproj rename to templates/basic-cs/spacetimedb/StdbModule.csproj diff --git a/templates/basic-c-sharp/spacetimedb/global.json b/templates/basic-cs/spacetimedb/global.json similarity index 100% rename from templates/basic-c-sharp/spacetimedb/global.json rename to templates/basic-cs/spacetimedb/global.json diff --git a/templates/basic-react/src/module_bindings/add_type.ts b/templates/basic-react/src/module_bindings/add_type.ts index 638f62cea39..c97ca72351c 100644 --- a/templates/basic-react/src/module_bindings/add_type.ts +++ b/templates/basic-react/src/module_bindings/add_type.ts @@ -8,8 +8,10 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; -export default __t.object('Add', { +export default __t.object("Add", { name: __t.string(), }); + + diff --git a/templates/basic-react/src/module_bindings/init_type.ts b/templates/basic-react/src/module_bindings/init_type.ts index 52ed691ed94..847f94de0ec 100644 --- a/templates/basic-react/src/module_bindings/init_type.ts +++ b/templates/basic-react/src/module_bindings/init_type.ts @@ -8,6 +8,8 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; + +export default __t.object("Init", {}); + -export default __t.object('Init', {}); diff --git a/templates/basic-react/src/module_bindings/on_connect_type.ts b/templates/basic-react/src/module_bindings/on_connect_type.ts index d36362515de..d95ba1fa6e2 100644 --- a/templates/basic-react/src/module_bindings/on_connect_type.ts +++ b/templates/basic-react/src/module_bindings/on_connect_type.ts @@ -8,6 +8,8 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; + +export default __t.object("OnConnect", {}); + -export default __t.object('OnConnect', {}); diff --git a/templates/basic-react/src/module_bindings/on_disconnect_type.ts b/templates/basic-react/src/module_bindings/on_disconnect_type.ts index efda71ebcfd..3d29234b70e 100644 --- a/templates/basic-react/src/module_bindings/on_disconnect_type.ts +++ b/templates/basic-react/src/module_bindings/on_disconnect_type.ts @@ -8,6 +8,8 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; + +export default __t.object("OnDisconnect", {}); + -export default __t.object('OnDisconnect', {}); diff --git a/templates/basic-react/src/module_bindings/say_hello_type.ts b/templates/basic-react/src/module_bindings/say_hello_type.ts index 6293ca6bd09..76564f6b314 100644 --- a/templates/basic-react/src/module_bindings/say_hello_type.ts +++ b/templates/basic-react/src/module_bindings/say_hello_type.ts @@ -8,6 +8,8 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; + +export default __t.object("SayHello", {}); + -export default __t.object('SayHello', {}); diff --git a/templates/basic-rust/.template.json b/templates/basic-rs/.template.json similarity index 100% rename from templates/basic-rust/.template.json rename to templates/basic-rs/.template.json diff --git a/templates/basic-rust/Cargo.toml b/templates/basic-rs/Cargo.toml similarity index 100% rename from templates/basic-rust/Cargo.toml rename to templates/basic-rs/Cargo.toml diff --git a/templates/basic-react/LICENSE b/templates/basic-rs/LICENSE similarity index 100% rename from templates/basic-react/LICENSE rename to templates/basic-rs/LICENSE diff --git a/templates/basic-rust/README.md b/templates/basic-rs/README.md similarity index 100% rename from templates/basic-rust/README.md rename to templates/basic-rs/README.md diff --git a/templates/basic-rust/spacetimedb/Cargo.toml b/templates/basic-rs/spacetimedb/Cargo.toml similarity index 71% rename from templates/basic-rust/spacetimedb/Cargo.toml rename to templates/basic-rs/spacetimedb/Cargo.toml index 271b883365e..2a2fa523efd 100644 --- a/templates/basic-rust/spacetimedb/Cargo.toml +++ b/templates/basic-rs/spacetimedb/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "spacetime-module" +name = "basic-rust-module" version = "0.1.0" edition = "2021" @@ -9,5 +9,5 @@ edition = "2021" crate-type = ["cdylib"] [dependencies] -spacetimedb = "1.11.*" +spacetimedb = { path = "../../../crates/bindings" } log = "0.4" diff --git a/templates/basic-rust/spacetimedb/src/lib.rs b/templates/basic-rs/spacetimedb/src/lib.rs similarity index 100% rename from templates/basic-rust/spacetimedb/src/lib.rs rename to templates/basic-rs/spacetimedb/src/lib.rs diff --git a/templates/basic-rust/src/main.rs b/templates/basic-rs/src/main.rs similarity index 100% rename from templates/basic-rust/src/main.rs rename to templates/basic-rs/src/main.rs diff --git a/templates/basic-rust/src/module_bindings/add_reducer.rs b/templates/basic-rust/src/module_bindings/add_reducer.rs new file mode 100644 index 00000000000..5dcce528d76 --- /dev/null +++ b/templates/basic-rust/src/module_bindings/add_reducer.rs @@ -0,0 +1,96 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct AddArgs { + pub name: String, +} + +impl From for super::Reducer { + fn from(args: AddArgs) -> Self { + Self::Add { name: args.name } + } +} + +impl __sdk::InModule for AddArgs { + type Module = super::RemoteModule; +} + +pub struct AddCallbackId(__sdk::CallbackId); + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `add`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait add { + /// Request that the remote module invoke the reducer `add` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed by listening for [`Self::on_add`] callbacks. + fn add(&self, name: String) -> __sdk::Result<()>; + /// Register a callback to run whenever we are notified of an invocation of the reducer `add`. + /// + /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] + /// to determine the reducer's status. + /// + /// The returned [`AddCallbackId`] can be passed to [`Self::remove_on_add`] + /// to cancel the callback. + fn on_add(&self, callback: impl FnMut(&super::ReducerEventContext, &String) + Send + 'static) -> AddCallbackId; + /// Cancel a callback previously registered by [`Self::on_add`], + /// causing it not to run in the future. + fn remove_on_add(&self, callback: AddCallbackId); +} + +impl add for super::RemoteReducers { + fn add(&self, name: String) -> __sdk::Result<()> { + self.imp.call_reducer("add", AddArgs { name }) + } + fn on_add(&self, mut callback: impl FnMut(&super::ReducerEventContext, &String) + Send + 'static) -> AddCallbackId { + AddCallbackId(self.imp.on_reducer( + "add", + Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] + let super::ReducerEventContext { + event: + __sdk::ReducerEvent { + reducer: super::Reducer::Add { name }, + .. + }, + .. + } = ctx + else { + unreachable!() + }; + callback(ctx, name) + }), + )) + } + fn remove_on_add(&self, callback: AddCallbackId) { + self.imp.remove_on_reducer("add", callback.0) + } +} + +#[allow(non_camel_case_types)] +#[doc(hidden)] +/// Extension trait for setting the call-flags for the reducer `add`. +/// +/// Implemented for [`super::SetReducerFlags`]. +/// +/// This type is currently unstable and may be removed without a major version bump. +pub trait set_flags_for_add { + /// Set the call-reducer flags for the reducer `add` to `flags`. + /// + /// This type is currently unstable and may be removed without a major version bump. + fn add(&self, flags: __ws::CallReducerFlags); +} + +impl set_flags_for_add for super::SetReducerFlags { + fn add(&self, flags: __ws::CallReducerFlags) { + self.imp.set_call_reducer_flags("add", flags); + } +} diff --git a/templates/quickstart-chat-rust/src/module_bindings/identity_connected_reducer.rs b/templates/basic-rust/src/module_bindings/identity_connected_reducer.rs similarity index 97% rename from templates/quickstart-chat-rust/src/module_bindings/identity_connected_reducer.rs rename to templates/basic-rust/src/module_bindings/identity_connected_reducer.rs index 0696aa16ccc..5c2d5e0df4e 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/identity_connected_reducer.rs +++ b/templates/basic-rust/src/module_bindings/identity_connected_reducer.rs @@ -1,8 +1,6 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). - #![allow(unused, clippy::all)] use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; @@ -60,6 +58,7 @@ impl identity_connected for super::RemoteReducers { IdentityConnectedCallbackId(self.imp.on_reducer( "identity_connected", Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] let super::ReducerEventContext { event: __sdk::ReducerEvent { diff --git a/templates/quickstart-chat-rust/src/module_bindings/identity_disconnected_reducer.rs b/templates/basic-rust/src/module_bindings/identity_disconnected_reducer.rs similarity index 97% rename from templates/quickstart-chat-rust/src/module_bindings/identity_disconnected_reducer.rs rename to templates/basic-rust/src/module_bindings/identity_disconnected_reducer.rs index 23831f6473f..ae4679d09aa 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/identity_disconnected_reducer.rs +++ b/templates/basic-rust/src/module_bindings/identity_disconnected_reducer.rs @@ -1,8 +1,6 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). - #![allow(unused, clippy::all)] use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; @@ -61,6 +59,7 @@ impl identity_disconnected for super::RemoteReducers { IdentityDisconnectedCallbackId(self.imp.on_reducer( "identity_disconnected", Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] let super::ReducerEventContext { event: __sdk::ReducerEvent { diff --git a/templates/basic-rust/src/module_bindings/mod.rs b/templates/basic-rust/src/module_bindings/mod.rs new file mode 100644 index 00000000000..893882f5d5a --- /dev/null +++ b/templates/basic-rust/src/module_bindings/mod.rs @@ -0,0 +1,854 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 1.11.2 (commit 3c8836b1a3aa2f1a7176a37838212c432960ce83). + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +pub mod add_reducer; +pub mod identity_connected_reducer; +pub mod identity_disconnected_reducer; +pub mod person_table; +pub mod person_type; +pub mod say_hello_reducer; + +pub use add_reducer::{add, set_flags_for_add, AddCallbackId}; +pub use identity_connected_reducer::{ + identity_connected, set_flags_for_identity_connected, IdentityConnectedCallbackId, +}; +pub use identity_disconnected_reducer::{ + identity_disconnected, set_flags_for_identity_disconnected, IdentityDisconnectedCallbackId, +}; +pub use person_table::*; +pub use person_type::Person; +pub use say_hello_reducer::{say_hello, set_flags_for_say_hello, SayHelloCallbackId}; + +#[derive(Clone, PartialEq, Debug)] + +/// One of the reducers defined by this module. +/// +/// Contained within a [`__sdk::ReducerEvent`] in [`EventContext`]s for reducer events +/// to indicate which reducer caused the event. + +pub enum Reducer { + Add { name: String }, + IdentityConnected, + IdentityDisconnected, + SayHello, +} + +impl __sdk::InModule for Reducer { + type Module = RemoteModule; +} + +impl __sdk::Reducer for Reducer { + fn reducer_name(&self) -> &'static str { + match self { + Reducer::Add { .. } => "add", + Reducer::IdentityConnected => "identity_connected", + Reducer::IdentityDisconnected => "identity_disconnected", + Reducer::SayHello => "say_hello", + _ => unreachable!(), + } + } +} +impl TryFrom<__ws::ReducerCallInfo<__ws::BsatnFormat>> for Reducer { + type Error = __sdk::Error; + fn try_from(value: __ws::ReducerCallInfo<__ws::BsatnFormat>) -> __sdk::Result { + match &value.reducer_name[..] { + "add" => Ok(__sdk::parse_reducer_args::("add", &value.args)?.into()), + "identity_connected" => Ok( + __sdk::parse_reducer_args::( + "identity_connected", + &value.args, + )? + .into(), + ), + "identity_disconnected" => Ok(__sdk::parse_reducer_args::< + identity_disconnected_reducer::IdentityDisconnectedArgs, + >("identity_disconnected", &value.args)? + .into()), + "say_hello" => { + Ok(__sdk::parse_reducer_args::("say_hello", &value.args)?.into()) + } + unknown => Err(__sdk::InternalError::unknown_name("reducer", unknown, "ReducerCallInfo").into()), + } + } +} + +#[derive(Default)] +#[allow(non_snake_case)] +#[doc(hidden)] +pub struct DbUpdate { + person: __sdk::TableUpdate, +} + +impl TryFrom<__ws::DatabaseUpdate<__ws::BsatnFormat>> for DbUpdate { + type Error = __sdk::Error; + fn try_from(raw: __ws::DatabaseUpdate<__ws::BsatnFormat>) -> Result { + let mut db_update = DbUpdate::default(); + for table_update in raw.tables { + match &table_update.table_name[..] { + "person" => db_update.person.append(person_table::parse_table_update(table_update)?), + + unknown => { + return Err(__sdk::InternalError::unknown_name("table", unknown, "DatabaseUpdate").into()); + } + } + } + Ok(db_update) + } +} + +impl __sdk::InModule for DbUpdate { + type Module = RemoteModule; +} + +impl __sdk::DbUpdate for DbUpdate { + fn apply_to_client_cache(&self, cache: &mut __sdk::ClientCache) -> AppliedDiff<'_> { + let mut diff = AppliedDiff::default(); + + diff.person = cache.apply_diff_to_table::("person", &self.person); + + diff + } +} + +#[derive(Default)] +#[allow(non_snake_case)] +#[doc(hidden)] +pub struct AppliedDiff<'r> { + person: __sdk::TableAppliedDiff<'r, Person>, + __unused: std::marker::PhantomData<&'r ()>, +} + +impl __sdk::InModule for AppliedDiff<'_> { + type Module = RemoteModule; +} + +impl<'r> __sdk::AppliedDiff<'r> for AppliedDiff<'r> { + fn invoke_row_callbacks(&self, event: &EventContext, callbacks: &mut __sdk::DbCallbacks) { + callbacks.invoke_table_row_callbacks::("person", &self.person, event); + } +} + +#[doc(hidden)] +pub struct RemoteModule; + +impl __sdk::InModule for RemoteModule { + type Module = Self; +} + +/// The `reducers` field of [`EventContext`] and [`DbConnection`], +/// with methods provided by extension traits for each reducer defined by the module. +pub struct RemoteReducers { + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for RemoteReducers { + type Module = RemoteModule; +} + +/// The `procedures` field of [`DbConnection`] and other [`DbContext`] types, +/// with methods provided by extension traits for each procedure defined by the module. +pub struct RemoteProcedures { + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for RemoteProcedures { + type Module = RemoteModule; +} + +#[doc(hidden)] +/// The `set_reducer_flags` field of [`DbConnection`], +/// with methods provided by extension traits for each reducer defined by the module. +/// Each method sets the flags for the reducer with the same name. +/// +/// This type is currently unstable and may be removed without a major version bump. +pub struct SetReducerFlags { + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for SetReducerFlags { + type Module = RemoteModule; +} + +/// The `db` field of [`EventContext`] and [`DbConnection`], +/// with methods provided by extension traits for each table defined by the module. +pub struct RemoteTables { + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for RemoteTables { + type Module = RemoteModule; +} + +/// A connection to a remote module, including a materialized view of a subset of the database. +/// +/// Connect to a remote module by calling [`DbConnection::builder`] +/// and using the [`__sdk::DbConnectionBuilder`] builder-pattern constructor. +/// +/// You must explicitly advance the connection by calling any one of: +/// +/// - [`DbConnection::frame_tick`]. +/// - [`DbConnection::run_threaded`]. +/// - [`DbConnection::run_async`]. +/// - [`DbConnection::advance_one_message`]. +/// - [`DbConnection::advance_one_message_blocking`]. +/// - [`DbConnection::advance_one_message_async`]. +/// +/// Which of these methods you should call depends on the specific needs of your application, +/// but you must call one of them, or else the connection will never progress. +pub struct DbConnection { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + #[doc(hidden)] + /// Access to setting the call-flags of each reducer defined for each reducer defined by the module + /// via extension traits implemented for [`SetReducerFlags`]. + /// + /// This type is currently unstable and may be removed without a major version bump. + pub set_reducer_flags: SetReducerFlags, + + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for DbConnection { + type Module = RemoteModule; +} + +impl __sdk::DbContext for DbConnection { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + type SetReducerFlags = SetReducerFlags; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + fn set_reducer_flags(&self) -> &Self::SetReducerFlags { + &self.set_reducer_flags + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl DbConnection { + /// Builder-pattern constructor for a connection to a remote module. + /// + /// See [`__sdk::DbConnectionBuilder`] for required and optional configuration for the new connection. + pub fn builder() -> __sdk::DbConnectionBuilder { + __sdk::DbConnectionBuilder::new() + } + + /// If any WebSocket messages are waiting, process one of them. + /// + /// Returns `true` if a message was processed, or `false` if the queue is empty. + /// Callers should invoke this message in a loop until it returns `false` + /// or for as much time is available to process messages. + /// + /// Returns an error if the connection is disconnected. + /// If the disconnection in question was normal, + /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], + /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. + /// + /// This is a low-level primitive exposed for power users who need significant control over scheduling. + /// Most applications should call [`Self::frame_tick`] each frame + /// to fully exhaust the queue whenever time is available. + pub fn advance_one_message(&self) -> __sdk::Result { + self.imp.advance_one_message() + } + + /// Process one WebSocket message, potentially blocking the current thread until one is received. + /// + /// Returns an error if the connection is disconnected. + /// If the disconnection in question was normal, + /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], + /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. + /// + /// This is a low-level primitive exposed for power users who need significant control over scheduling. + /// Most applications should call [`Self::run_threaded`] to spawn a thread + /// which advances the connection automatically. + pub fn advance_one_message_blocking(&self) -> __sdk::Result<()> { + self.imp.advance_one_message_blocking() + } + + /// Process one WebSocket message, `await`ing until one is received. + /// + /// Returns an error if the connection is disconnected. + /// If the disconnection in question was normal, + /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], + /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. + /// + /// This is a low-level primitive exposed for power users who need significant control over scheduling. + /// Most applications should call [`Self::run_async`] to run an `async` loop + /// which advances the connection when polled. + pub async fn advance_one_message_async(&self) -> __sdk::Result<()> { + self.imp.advance_one_message_async().await + } + + /// Process all WebSocket messages waiting in the queue, + /// then return without `await`ing or blocking the current thread. + pub fn frame_tick(&self) -> __sdk::Result<()> { + self.imp.frame_tick() + } + + /// Spawn a thread which processes WebSocket messages as they are received. + pub fn run_threaded(&self) -> std::thread::JoinHandle<()> { + self.imp.run_threaded() + } + + /// Run an `async` loop which processes WebSocket messages when polled. + pub async fn run_async(&self) -> __sdk::Result<()> { + self.imp.run_async().await + } +} + +impl __sdk::DbConnection for DbConnection { + fn new(imp: __sdk::DbContextImpl) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + imp, + } + } +} + +/// A handle on a subscribed query. +// TODO: Document this better after implementing the new subscription API. +#[derive(Clone)] +pub struct SubscriptionHandle { + imp: __sdk::SubscriptionHandleImpl, +} + +impl __sdk::InModule for SubscriptionHandle { + type Module = RemoteModule; +} + +impl __sdk::SubscriptionHandle for SubscriptionHandle { + fn new(imp: __sdk::SubscriptionHandleImpl) -> Self { + Self { imp } + } + + /// Returns true if this subscription has been terminated due to an unsubscribe call or an error. + fn is_ended(&self) -> bool { + self.imp.is_ended() + } + + /// Returns true if this subscription has been applied and has not yet been unsubscribed. + fn is_active(&self) -> bool { + self.imp.is_active() + } + + /// Unsubscribe from the query controlled by this `SubscriptionHandle`, + /// then run `on_end` when its rows are removed from the client cache. + fn unsubscribe_then(self, on_end: __sdk::OnEndedCallback) -> __sdk::Result<()> { + self.imp.unsubscribe_then(Some(on_end)) + } + + fn unsubscribe(self) -> __sdk::Result<()> { + self.imp.unsubscribe_then(None) + } +} + +/// Alias trait for a [`__sdk::DbContext`] connected to this module, +/// with that trait's associated types bounded to this module's concrete types. +/// +/// Users can use this trait as a boundary on definitions which should accept +/// either a [`DbConnection`] or an [`EventContext`] and operate on either. +pub trait RemoteDbContext: + __sdk::DbContext< + DbView = RemoteTables, + Reducers = RemoteReducers, + SetReducerFlags = SetReducerFlags, + SubscriptionBuilder = __sdk::SubscriptionBuilder, +> +{ +} +impl< + Ctx: __sdk::DbContext< + DbView = RemoteTables, + Reducers = RemoteReducers, + SetReducerFlags = SetReducerFlags, + SubscriptionBuilder = __sdk::SubscriptionBuilder, + >, + > RemoteDbContext for Ctx +{ +} + +/// An [`__sdk::DbContext`] augmented with a [`__sdk::Event`], +/// passed to [`__sdk::Table::on_insert`], [`__sdk::Table::on_delete`] and [`__sdk::TableWithPrimaryKey::on_update`] callbacks. +pub struct EventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to setting the call-flags of each reducer defined for each reducer defined by the module + /// via extension traits implemented for [`SetReducerFlags`]. + /// + /// This type is currently unstable and may be removed without a major version bump. + pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + /// The event which caused these callbacks to run. + pub event: __sdk::Event, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for EventContext { + type Event = __sdk::Event; + fn event(&self) -> &Self::Event { + &self.event + } + fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + event, + imp, + } + } +} + +impl __sdk::InModule for EventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for EventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + type SetReducerFlags = SetReducerFlags; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + fn set_reducer_flags(&self) -> &Self::SetReducerFlags { + &self.set_reducer_flags + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::EventContext for EventContext {} + +/// An [`__sdk::DbContext`] augmented with a [`__sdk::ReducerEvent`], +/// passed to on-reducer callbacks. +pub struct ReducerEventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to setting the call-flags of each reducer defined for each reducer defined by the module + /// via extension traits implemented for [`SetReducerFlags`]. + /// + /// This type is currently unstable and may be removed without a major version bump. + pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + /// The event which caused these callbacks to run. + pub event: __sdk::ReducerEvent, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for ReducerEventContext { + type Event = __sdk::ReducerEvent; + fn event(&self) -> &Self::Event { + &self.event + } + fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + event, + imp, + } + } +} + +impl __sdk::InModule for ReducerEventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for ReducerEventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + type SetReducerFlags = SetReducerFlags; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + fn set_reducer_flags(&self) -> &Self::SetReducerFlags { + &self.set_reducer_flags + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::ReducerEventContext for ReducerEventContext {} + +/// An [`__sdk::DbContext`] passed to procedure callbacks. +pub struct ProcedureEventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to setting the call-flags of each reducer defined for each reducer defined by the module + /// via extension traits implemented for [`SetReducerFlags`]. + /// + /// This type is currently unstable and may be removed without a major version bump. + pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for ProcedureEventContext { + type Event = (); + fn event(&self) -> &Self::Event { + &() + } + fn new(imp: __sdk::DbContextImpl, _event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + imp, + } + } +} + +impl __sdk::InModule for ProcedureEventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for ProcedureEventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + type SetReducerFlags = SetReducerFlags; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + fn set_reducer_flags(&self) -> &Self::SetReducerFlags { + &self.set_reducer_flags + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::ProcedureEventContext for ProcedureEventContext {} + +/// An [`__sdk::DbContext`] passed to [`__sdk::SubscriptionBuilder::on_applied`] and [`SubscriptionHandle::unsubscribe_then`] callbacks. +pub struct SubscriptionEventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to setting the call-flags of each reducer defined for each reducer defined by the module + /// via extension traits implemented for [`SetReducerFlags`]. + /// + /// This type is currently unstable and may be removed without a major version bump. + pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for SubscriptionEventContext { + type Event = (); + fn event(&self) -> &Self::Event { + &() + } + fn new(imp: __sdk::DbContextImpl, _event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + imp, + } + } +} + +impl __sdk::InModule for SubscriptionEventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for SubscriptionEventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + type SetReducerFlags = SetReducerFlags; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + fn set_reducer_flags(&self) -> &Self::SetReducerFlags { + &self.set_reducer_flags + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::SubscriptionEventContext for SubscriptionEventContext {} + +/// An [`__sdk::DbContext`] augmented with a [`__sdk::Error`], +/// passed to [`__sdk::DbConnectionBuilder::on_disconnect`], [`__sdk::DbConnectionBuilder::on_connect_error`] and [`__sdk::SubscriptionBuilder::on_error`] callbacks. +pub struct ErrorContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to setting the call-flags of each reducer defined for each reducer defined by the module + /// via extension traits implemented for [`SetReducerFlags`]. + /// + /// This type is currently unstable and may be removed without a major version bump. + pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + /// The event which caused these callbacks to run. + pub event: Option<__sdk::Error>, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for ErrorContext { + type Event = Option<__sdk::Error>; + fn event(&self) -> &Self::Event { + &self.event + } + fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + event, + imp, + } + } +} + +impl __sdk::InModule for ErrorContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for ErrorContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + type SetReducerFlags = SetReducerFlags; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + fn set_reducer_flags(&self) -> &Self::SetReducerFlags { + &self.set_reducer_flags + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::ErrorContext for ErrorContext {} + +impl __sdk::SpacetimeModule for RemoteModule { + type DbConnection = DbConnection; + type EventContext = EventContext; + type ReducerEventContext = ReducerEventContext; + type ProcedureEventContext = ProcedureEventContext; + type SubscriptionEventContext = SubscriptionEventContext; + type ErrorContext = ErrorContext; + type Reducer = Reducer; + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type SetReducerFlags = SetReducerFlags; + type DbUpdate = DbUpdate; + type AppliedDiff<'r> = AppliedDiff<'r>; + type SubscriptionHandle = SubscriptionHandle; + + fn register_tables(client_cache: &mut __sdk::ClientCache) { + person_table::register_table(client_cache); + } +} diff --git a/templates/basic-rust/src/module_bindings/person_table.rs b/templates/basic-rust/src/module_bindings/person_table.rs new file mode 100644 index 00000000000..da3f64bd255 --- /dev/null +++ b/templates/basic-rust/src/module_bindings/person_table.rs @@ -0,0 +1,95 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::person_type::Person; +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +/// Table handle for the table `person`. +/// +/// Obtain a handle from the [`PersonTableAccess::person`] method on [`super::RemoteTables`], +/// like `ctx.db.person()`. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.person().on_insert(...)`. +pub struct PersonTableHandle<'ctx> { + imp: __sdk::TableHandle, + ctx: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the table `person`. +/// +/// Implemented for [`super::RemoteTables`]. +pub trait PersonTableAccess { + #[allow(non_snake_case)] + /// Obtain a [`PersonTableHandle`], which mediates access to the table `person`. + fn person(&self) -> PersonTableHandle<'_>; +} + +impl PersonTableAccess for super::RemoteTables { + fn person(&self) -> PersonTableHandle<'_> { + PersonTableHandle { + imp: self.imp.get_table::("person"), + ctx: std::marker::PhantomData, + } + } +} + +pub struct PersonInsertCallbackId(__sdk::CallbackId); +pub struct PersonDeleteCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::Table for PersonTableHandle<'ctx> { + type Row = Person; + type EventContext = super::EventContext; + + fn count(&self) -> u64 { + self.imp.count() + } + fn iter(&self) -> impl Iterator + '_ { + self.imp.iter() + } + + type InsertCallbackId = PersonInsertCallbackId; + + fn on_insert( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> PersonInsertCallbackId { + PersonInsertCallbackId(self.imp.on_insert(Box::new(callback))) + } + + fn remove_on_insert(&self, callback: PersonInsertCallbackId) { + self.imp.remove_on_insert(callback.0) + } + + type DeleteCallbackId = PersonDeleteCallbackId; + + fn on_delete( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> PersonDeleteCallbackId { + PersonDeleteCallbackId(self.imp.on_delete(Box::new(callback))) + } + + fn remove_on_delete(&self, callback: PersonDeleteCallbackId) { + self.imp.remove_on_delete(callback.0) + } +} + +#[doc(hidden)] +pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { + let _table = client_cache.get_or_make_table::("person"); +} + +#[doc(hidden)] +pub(super) fn parse_table_update( + raw_updates: __ws::TableUpdate<__ws::BsatnFormat>, +) -> __sdk::Result<__sdk::TableUpdate> { + __sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| { + __sdk::InternalError::failed_parse("TableUpdate", "TableUpdate") + .with_cause(e) + .into() + }) +} diff --git a/templates/basic-rust/src/module_bindings/person_type.rs b/templates/basic-rust/src/module_bindings/person_type.rs new file mode 100644 index 00000000000..56436ae601a --- /dev/null +++ b/templates/basic-rust/src/module_bindings/person_type.rs @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct Person { + pub name: String, +} + +impl __sdk::InModule for Person { + type Module = super::RemoteModule; +} diff --git a/templates/basic-rust/src/module_bindings/say_hello_reducer.rs b/templates/basic-rust/src/module_bindings/say_hello_reducer.rs new file mode 100644 index 00000000000..c3b8c277050 --- /dev/null +++ b/templates/basic-rust/src/module_bindings/say_hello_reducer.rs @@ -0,0 +1,97 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct SayHelloArgs {} + +impl From for super::Reducer { + fn from(args: SayHelloArgs) -> Self { + Self::SayHello + } +} + +impl __sdk::InModule for SayHelloArgs { + type Module = super::RemoteModule; +} + +pub struct SayHelloCallbackId(__sdk::CallbackId); + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `say_hello`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait say_hello { + /// Request that the remote module invoke the reducer `say_hello` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed by listening for [`Self::on_say_hello`] callbacks. + fn say_hello(&self) -> __sdk::Result<()>; + /// Register a callback to run whenever we are notified of an invocation of the reducer `say_hello`. + /// + /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] + /// to determine the reducer's status. + /// + /// The returned [`SayHelloCallbackId`] can be passed to [`Self::remove_on_say_hello`] + /// to cancel the callback. + fn on_say_hello(&self, callback: impl FnMut(&super::ReducerEventContext) + Send + 'static) -> SayHelloCallbackId; + /// Cancel a callback previously registered by [`Self::on_say_hello`], + /// causing it not to run in the future. + fn remove_on_say_hello(&self, callback: SayHelloCallbackId); +} + +impl say_hello for super::RemoteReducers { + fn say_hello(&self) -> __sdk::Result<()> { + self.imp.call_reducer("say_hello", SayHelloArgs {}) + } + fn on_say_hello( + &self, + mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, + ) -> SayHelloCallbackId { + SayHelloCallbackId(self.imp.on_reducer( + "say_hello", + Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] + let super::ReducerEventContext { + event: + __sdk::ReducerEvent { + reducer: super::Reducer::SayHello {}, + .. + }, + .. + } = ctx + else { + unreachable!() + }; + callback(ctx) + }), + )) + } + fn remove_on_say_hello(&self, callback: SayHelloCallbackId) { + self.imp.remove_on_reducer("say_hello", callback.0) + } +} + +#[allow(non_camel_case_types)] +#[doc(hidden)] +/// Extension trait for setting the call-flags for the reducer `say_hello`. +/// +/// Implemented for [`super::SetReducerFlags`]. +/// +/// This type is currently unstable and may be removed without a major version bump. +pub trait set_flags_for_say_hello { + /// Set the call-reducer flags for the reducer `say_hello` to `flags`. + /// + /// This type is currently unstable and may be removed without a major version bump. + fn say_hello(&self, flags: __ws::CallReducerFlags); +} + +impl set_flags_for_say_hello for super::SetReducerFlags { + fn say_hello(&self, flags: __ws::CallReducerFlags) { + self.imp.set_call_reducer_flags("say_hello", flags); + } +} diff --git a/templates/basic-typescript/.template.json b/templates/basic-ts/.template.json similarity index 100% rename from templates/basic-typescript/.template.json rename to templates/basic-ts/.template.json diff --git a/templates/basic-rust/LICENSE b/templates/basic-ts/LICENSE similarity index 100% rename from templates/basic-rust/LICENSE rename to templates/basic-ts/LICENSE diff --git a/templates/basic-typescript/index.html b/templates/basic-ts/index.html similarity index 100% rename from templates/basic-typescript/index.html rename to templates/basic-ts/index.html diff --git a/templates/basic-typescript/package.json b/templates/basic-ts/package.json similarity index 100% rename from templates/basic-typescript/package.json rename to templates/basic-ts/package.json diff --git a/templates/basic-react/spacetimedb/package.json b/templates/basic-ts/spacetimedb/package.json similarity index 100% rename from templates/basic-react/spacetimedb/package.json rename to templates/basic-ts/spacetimedb/package.json diff --git a/templates/basic-react/spacetimedb/pnpm-lock.yaml b/templates/basic-ts/spacetimedb/pnpm-lock.yaml similarity index 100% rename from templates/basic-react/spacetimedb/pnpm-lock.yaml rename to templates/basic-ts/spacetimedb/pnpm-lock.yaml diff --git a/templates/basic-typescript/spacetimedb/src/index.ts b/templates/basic-ts/spacetimedb/src/index.ts similarity index 100% rename from templates/basic-typescript/spacetimedb/src/index.ts rename to templates/basic-ts/spacetimedb/src/index.ts diff --git a/templates/basic-react/spacetimedb/tsconfig.json b/templates/basic-ts/spacetimedb/tsconfig.json similarity index 100% rename from templates/basic-react/spacetimedb/tsconfig.json rename to templates/basic-ts/spacetimedb/tsconfig.json diff --git a/templates/basic-typescript/src/main.ts b/templates/basic-ts/src/main.ts similarity index 100% rename from templates/basic-typescript/src/main.ts rename to templates/basic-ts/src/main.ts diff --git a/templates/basic-react/src/module_bindings/add_reducer.ts b/templates/basic-ts/src/module_bindings/add_reducer.ts similarity index 100% rename from templates/basic-react/src/module_bindings/add_reducer.ts rename to templates/basic-ts/src/module_bindings/add_reducer.ts diff --git a/templates/basic-ts/src/module_bindings/add_type.ts b/templates/basic-ts/src/module_bindings/add_type.ts new file mode 100644 index 00000000000..638f62cea39 --- /dev/null +++ b/templates/basic-ts/src/module_bindings/add_type.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('Add', { + name: __t.string(), +}); diff --git a/templates/basic-react/src/module_bindings/index.ts b/templates/basic-ts/src/module_bindings/index.ts similarity index 100% rename from templates/basic-react/src/module_bindings/index.ts rename to templates/basic-ts/src/module_bindings/index.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/init_type.ts b/templates/basic-ts/src/module_bindings/init_type.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/init_type.ts rename to templates/basic-ts/src/module_bindings/init_type.ts diff --git a/templates/basic-react/src/module_bindings/on_connect_reducer.ts b/templates/basic-ts/src/module_bindings/on_connect_reducer.ts similarity index 100% rename from templates/basic-react/src/module_bindings/on_connect_reducer.ts rename to templates/basic-ts/src/module_bindings/on_connect_reducer.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/on_connect_type.ts b/templates/basic-ts/src/module_bindings/on_connect_type.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/on_connect_type.ts rename to templates/basic-ts/src/module_bindings/on_connect_type.ts diff --git a/templates/basic-react/src/module_bindings/on_disconnect_reducer.ts b/templates/basic-ts/src/module_bindings/on_disconnect_reducer.ts similarity index 100% rename from templates/basic-react/src/module_bindings/on_disconnect_reducer.ts rename to templates/basic-ts/src/module_bindings/on_disconnect_reducer.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/on_disconnect_type.ts b/templates/basic-ts/src/module_bindings/on_disconnect_type.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/on_disconnect_type.ts rename to templates/basic-ts/src/module_bindings/on_disconnect_type.ts diff --git a/templates/basic-react/src/module_bindings/person_table.ts b/templates/basic-ts/src/module_bindings/person_table.ts similarity index 100% rename from templates/basic-react/src/module_bindings/person_table.ts rename to templates/basic-ts/src/module_bindings/person_table.ts diff --git a/templates/basic-react/src/module_bindings/person_type.ts b/templates/basic-ts/src/module_bindings/person_type.ts similarity index 100% rename from templates/basic-react/src/module_bindings/person_type.ts rename to templates/basic-ts/src/module_bindings/person_type.ts diff --git a/templates/basic-react/src/module_bindings/say_hello_reducer.ts b/templates/basic-ts/src/module_bindings/say_hello_reducer.ts similarity index 100% rename from templates/basic-react/src/module_bindings/say_hello_reducer.ts rename to templates/basic-ts/src/module_bindings/say_hello_reducer.ts diff --git a/templates/basic-ts/src/module_bindings/say_hello_type.ts b/templates/basic-ts/src/module_bindings/say_hello_type.ts new file mode 100644 index 00000000000..6293ca6bd09 --- /dev/null +++ b/templates/basic-ts/src/module_bindings/say_hello_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('SayHello', {}); diff --git a/templates/basic-typescript/tsconfig.json b/templates/basic-ts/tsconfig.json similarity index 100% rename from templates/basic-typescript/tsconfig.json rename to templates/basic-ts/tsconfig.json diff --git a/templates/basic-typescript/vite.config.ts b/templates/basic-ts/vite.config.ts similarity index 100% rename from templates/basic-typescript/vite.config.ts rename to templates/basic-ts/vite.config.ts diff --git a/templates/basic-typescript/src/module_bindings/add_type.ts b/templates/basic-typescript/src/module_bindings/add_type.ts index 638f62cea39..c97ca72351c 100644 --- a/templates/basic-typescript/src/module_bindings/add_type.ts +++ b/templates/basic-typescript/src/module_bindings/add_type.ts @@ -8,8 +8,10 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; -export default __t.object('Add', { +export default __t.object("Add", { name: __t.string(), }); + + diff --git a/templates/basic-typescript/src/module_bindings/init_type.ts b/templates/basic-typescript/src/module_bindings/init_type.ts index 52ed691ed94..847f94de0ec 100644 --- a/templates/basic-typescript/src/module_bindings/init_type.ts +++ b/templates/basic-typescript/src/module_bindings/init_type.ts @@ -8,6 +8,8 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; + +export default __t.object("Init", {}); + -export default __t.object('Init', {}); diff --git a/templates/basic-typescript/src/module_bindings/on_connect_type.ts b/templates/basic-typescript/src/module_bindings/on_connect_type.ts index d36362515de..d95ba1fa6e2 100644 --- a/templates/basic-typescript/src/module_bindings/on_connect_type.ts +++ b/templates/basic-typescript/src/module_bindings/on_connect_type.ts @@ -8,6 +8,8 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; + +export default __t.object("OnConnect", {}); + -export default __t.object('OnConnect', {}); diff --git a/templates/basic-typescript/src/module_bindings/on_disconnect_type.ts b/templates/basic-typescript/src/module_bindings/on_disconnect_type.ts index efda71ebcfd..3d29234b70e 100644 --- a/templates/basic-typescript/src/module_bindings/on_disconnect_type.ts +++ b/templates/basic-typescript/src/module_bindings/on_disconnect_type.ts @@ -8,6 +8,8 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; + +export default __t.object("OnDisconnect", {}); + -export default __t.object('OnDisconnect', {}); diff --git a/templates/basic-typescript/src/module_bindings/say_hello_type.ts b/templates/basic-typescript/src/module_bindings/say_hello_type.ts index 6293ca6bd09..76564f6b314 100644 --- a/templates/basic-typescript/src/module_bindings/say_hello_type.ts +++ b/templates/basic-typescript/src/module_bindings/say_hello_type.ts @@ -8,6 +8,8 @@ import { t as __t, type AlgebraicTypeType as __AlgebraicTypeType, type Infer as __Infer, -} from 'spacetimedb'; +} from "spacetimedb"; + +export default __t.object("SayHello", {}); + -export default __t.object('SayHello', {}); diff --git a/templates/quickstart-chat-c-sharp/.template.json b/templates/chat-console-cs/.template.json similarity index 100% rename from templates/quickstart-chat-c-sharp/.template.json rename to templates/chat-console-cs/.template.json diff --git a/templates/basic-typescript/LICENSE b/templates/chat-console-cs/LICENSE similarity index 100% rename from templates/basic-typescript/LICENSE rename to templates/chat-console-cs/LICENSE diff --git a/templates/quickstart-chat-c-sharp/Program.cs b/templates/chat-console-cs/Program.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/Program.cs rename to templates/chat-console-cs/Program.cs diff --git a/templates/quickstart-chat-c-sharp/README.md b/templates/chat-console-cs/README.md similarity index 100% rename from templates/quickstart-chat-c-sharp/README.md rename to templates/chat-console-cs/README.md diff --git a/templates/quickstart-chat-c-sharp/client.csproj b/templates/chat-console-cs/client.csproj similarity index 100% rename from templates/quickstart-chat-c-sharp/client.csproj rename to templates/chat-console-cs/client.csproj diff --git a/templates/quickstart-chat-c-sharp/module_bindings/Reducers/ClientConnected.g.cs b/templates/chat-console-cs/module_bindings/Reducers/ClientConnected.g.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/module_bindings/Reducers/ClientConnected.g.cs rename to templates/chat-console-cs/module_bindings/Reducers/ClientConnected.g.cs diff --git a/templates/quickstart-chat-c-sharp/module_bindings/Reducers/ClientDisconnected.g.cs b/templates/chat-console-cs/module_bindings/Reducers/ClientDisconnected.g.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/module_bindings/Reducers/ClientDisconnected.g.cs rename to templates/chat-console-cs/module_bindings/Reducers/ClientDisconnected.g.cs diff --git a/templates/quickstart-chat-c-sharp/module_bindings/Reducers/SendMessage.g.cs b/templates/chat-console-cs/module_bindings/Reducers/SendMessage.g.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/module_bindings/Reducers/SendMessage.g.cs rename to templates/chat-console-cs/module_bindings/Reducers/SendMessage.g.cs diff --git a/templates/quickstart-chat-c-sharp/module_bindings/Reducers/SetName.g.cs b/templates/chat-console-cs/module_bindings/Reducers/SetName.g.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/module_bindings/Reducers/SetName.g.cs rename to templates/chat-console-cs/module_bindings/Reducers/SetName.g.cs diff --git a/templates/quickstart-chat-c-sharp/module_bindings/SpacetimeDBClient.g.cs b/templates/chat-console-cs/module_bindings/SpacetimeDBClient.g.cs similarity index 99% rename from templates/quickstart-chat-c-sharp/module_bindings/SpacetimeDBClient.g.cs rename to templates/chat-console-cs/module_bindings/SpacetimeDBClient.g.cs index 1e25d609f69..b8fc91e0bae 100644 --- a/templates/quickstart-chat-c-sharp/module_bindings/SpacetimeDBClient.g.cs +++ b/templates/chat-console-cs/module_bindings/SpacetimeDBClient.g.cs @@ -1,7 +1,7 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.8.0 (commit 6cbedef7ca453ea48801d9192779fcee7a465a10). +// This was generated using spacetimedb cli version 1.11.2 (commit 3c8836b1a3aa2f1a7176a37838212c432960ce83). #nullable enable diff --git a/templates/quickstart-chat-c-sharp/module_bindings/Tables/Message.g.cs b/templates/chat-console-cs/module_bindings/Tables/Message.g.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/module_bindings/Tables/Message.g.cs rename to templates/chat-console-cs/module_bindings/Tables/Message.g.cs diff --git a/templates/quickstart-chat-c-sharp/module_bindings/Tables/User.g.cs b/templates/chat-console-cs/module_bindings/Tables/User.g.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/module_bindings/Tables/User.g.cs rename to templates/chat-console-cs/module_bindings/Tables/User.g.cs diff --git a/templates/quickstart-chat-c-sharp/module_bindings/Types/Message.g.cs b/templates/chat-console-cs/module_bindings/Types/Message.g.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/module_bindings/Types/Message.g.cs rename to templates/chat-console-cs/module_bindings/Types/Message.g.cs diff --git a/templates/quickstart-chat-c-sharp/module_bindings/Types/User.g.cs b/templates/chat-console-cs/module_bindings/Types/User.g.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/module_bindings/Types/User.g.cs rename to templates/chat-console-cs/module_bindings/Types/User.g.cs diff --git a/templates/quickstart-chat-c-sharp/spacetimedb/Lib.cs b/templates/chat-console-cs/spacetimedb/Lib.cs similarity index 100% rename from templates/quickstart-chat-c-sharp/spacetimedb/Lib.cs rename to templates/chat-console-cs/spacetimedb/Lib.cs diff --git a/templates/quickstart-chat-c-sharp/spacetimedb/StdbModule.csproj b/templates/chat-console-cs/spacetimedb/StdbModule.csproj similarity index 100% rename from templates/quickstart-chat-c-sharp/spacetimedb/StdbModule.csproj rename to templates/chat-console-cs/spacetimedb/StdbModule.csproj diff --git a/templates/quickstart-chat-c-sharp/spacetimedb/global.json b/templates/chat-console-cs/spacetimedb/global.json similarity index 100% rename from templates/quickstart-chat-c-sharp/spacetimedb/global.json rename to templates/chat-console-cs/spacetimedb/global.json diff --git a/templates/quickstart-chat-rust/.template.json b/templates/chat-console-rs/.template.json similarity index 100% rename from templates/quickstart-chat-rust/.template.json rename to templates/chat-console-rs/.template.json diff --git a/templates/quickstart-chat-rust/Cargo.toml b/templates/chat-console-rs/Cargo.toml similarity index 100% rename from templates/quickstart-chat-rust/Cargo.toml rename to templates/chat-console-rs/Cargo.toml diff --git a/templates/quickstart-chat-c-sharp/LICENSE b/templates/chat-console-rs/LICENSE similarity index 100% rename from templates/quickstart-chat-c-sharp/LICENSE rename to templates/chat-console-rs/LICENSE diff --git a/templates/quickstart-chat-rust/README.md b/templates/chat-console-rs/README.md similarity index 100% rename from templates/quickstart-chat-rust/README.md rename to templates/chat-console-rs/README.md diff --git a/templates/quickstart-chat-rust/spacetimedb/Cargo.toml b/templates/chat-console-rs/spacetimedb/Cargo.toml similarity index 100% rename from templates/quickstart-chat-rust/spacetimedb/Cargo.toml rename to templates/chat-console-rs/spacetimedb/Cargo.toml diff --git a/templates/quickstart-chat-rust/spacetimedb/README.md b/templates/chat-console-rs/spacetimedb/README.md similarity index 100% rename from templates/quickstart-chat-rust/spacetimedb/README.md rename to templates/chat-console-rs/spacetimedb/README.md diff --git a/templates/quickstart-chat-rust/spacetimedb/src/lib.rs b/templates/chat-console-rs/spacetimedb/src/lib.rs similarity index 100% rename from templates/quickstart-chat-rust/spacetimedb/src/lib.rs rename to templates/chat-console-rs/spacetimedb/src/lib.rs diff --git a/templates/quickstart-chat-rust/src/main.rs b/templates/chat-console-rs/src/main.rs similarity index 100% rename from templates/quickstart-chat-rust/src/main.rs rename to templates/chat-console-rs/src/main.rs diff --git a/templates/chat-console-rs/src/module_bindings/identity_connected_reducer.rs b/templates/chat-console-rs/src/module_bindings/identity_connected_reducer.rs new file mode 100644 index 00000000000..5c2d5e0df4e --- /dev/null +++ b/templates/chat-console-rs/src/module_bindings/identity_connected_reducer.rs @@ -0,0 +1,100 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct IdentityConnectedArgs {} + +impl From for super::Reducer { + fn from(args: IdentityConnectedArgs) -> Self { + Self::IdentityConnected + } +} + +impl __sdk::InModule for IdentityConnectedArgs { + type Module = super::RemoteModule; +} + +pub struct IdentityConnectedCallbackId(__sdk::CallbackId); + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `identity_connected`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait identity_connected { + /// Request that the remote module invoke the reducer `identity_connected` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed by listening for [`Self::on_identity_connected`] callbacks. + fn identity_connected(&self) -> __sdk::Result<()>; + /// Register a callback to run whenever we are notified of an invocation of the reducer `identity_connected`. + /// + /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] + /// to determine the reducer's status. + /// + /// The returned [`IdentityConnectedCallbackId`] can be passed to [`Self::remove_on_identity_connected`] + /// to cancel the callback. + fn on_identity_connected( + &self, + callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, + ) -> IdentityConnectedCallbackId; + /// Cancel a callback previously registered by [`Self::on_identity_connected`], + /// causing it not to run in the future. + fn remove_on_identity_connected(&self, callback: IdentityConnectedCallbackId); +} + +impl identity_connected for super::RemoteReducers { + fn identity_connected(&self) -> __sdk::Result<()> { + self.imp.call_reducer("identity_connected", IdentityConnectedArgs {}) + } + fn on_identity_connected( + &self, + mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, + ) -> IdentityConnectedCallbackId { + IdentityConnectedCallbackId(self.imp.on_reducer( + "identity_connected", + Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] + let super::ReducerEventContext { + event: + __sdk::ReducerEvent { + reducer: super::Reducer::IdentityConnected {}, + .. + }, + .. + } = ctx + else { + unreachable!() + }; + callback(ctx) + }), + )) + } + fn remove_on_identity_connected(&self, callback: IdentityConnectedCallbackId) { + self.imp.remove_on_reducer("identity_connected", callback.0) + } +} + +#[allow(non_camel_case_types)] +#[doc(hidden)] +/// Extension trait for setting the call-flags for the reducer `identity_connected`. +/// +/// Implemented for [`super::SetReducerFlags`]. +/// +/// This type is currently unstable and may be removed without a major version bump. +pub trait set_flags_for_identity_connected { + /// Set the call-reducer flags for the reducer `identity_connected` to `flags`. + /// + /// This type is currently unstable and may be removed without a major version bump. + fn identity_connected(&self, flags: __ws::CallReducerFlags); +} + +impl set_flags_for_identity_connected for super::SetReducerFlags { + fn identity_connected(&self, flags: __ws::CallReducerFlags) { + self.imp.set_call_reducer_flags("identity_connected", flags); + } +} diff --git a/templates/chat-console-rs/src/module_bindings/identity_disconnected_reducer.rs b/templates/chat-console-rs/src/module_bindings/identity_disconnected_reducer.rs new file mode 100644 index 00000000000..ae4679d09aa --- /dev/null +++ b/templates/chat-console-rs/src/module_bindings/identity_disconnected_reducer.rs @@ -0,0 +1,101 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct IdentityDisconnectedArgs {} + +impl From for super::Reducer { + fn from(args: IdentityDisconnectedArgs) -> Self { + Self::IdentityDisconnected + } +} + +impl __sdk::InModule for IdentityDisconnectedArgs { + type Module = super::RemoteModule; +} + +pub struct IdentityDisconnectedCallbackId(__sdk::CallbackId); + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `identity_disconnected`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait identity_disconnected { + /// Request that the remote module invoke the reducer `identity_disconnected` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed by listening for [`Self::on_identity_disconnected`] callbacks. + fn identity_disconnected(&self) -> __sdk::Result<()>; + /// Register a callback to run whenever we are notified of an invocation of the reducer `identity_disconnected`. + /// + /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] + /// to determine the reducer's status. + /// + /// The returned [`IdentityDisconnectedCallbackId`] can be passed to [`Self::remove_on_identity_disconnected`] + /// to cancel the callback. + fn on_identity_disconnected( + &self, + callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, + ) -> IdentityDisconnectedCallbackId; + /// Cancel a callback previously registered by [`Self::on_identity_disconnected`], + /// causing it not to run in the future. + fn remove_on_identity_disconnected(&self, callback: IdentityDisconnectedCallbackId); +} + +impl identity_disconnected for super::RemoteReducers { + fn identity_disconnected(&self) -> __sdk::Result<()> { + self.imp + .call_reducer("identity_disconnected", IdentityDisconnectedArgs {}) + } + fn on_identity_disconnected( + &self, + mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, + ) -> IdentityDisconnectedCallbackId { + IdentityDisconnectedCallbackId(self.imp.on_reducer( + "identity_disconnected", + Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] + let super::ReducerEventContext { + event: + __sdk::ReducerEvent { + reducer: super::Reducer::IdentityDisconnected {}, + .. + }, + .. + } = ctx + else { + unreachable!() + }; + callback(ctx) + }), + )) + } + fn remove_on_identity_disconnected(&self, callback: IdentityDisconnectedCallbackId) { + self.imp.remove_on_reducer("identity_disconnected", callback.0) + } +} + +#[allow(non_camel_case_types)] +#[doc(hidden)] +/// Extension trait for setting the call-flags for the reducer `identity_disconnected`. +/// +/// Implemented for [`super::SetReducerFlags`]. +/// +/// This type is currently unstable and may be removed without a major version bump. +pub trait set_flags_for_identity_disconnected { + /// Set the call-reducer flags for the reducer `identity_disconnected` to `flags`. + /// + /// This type is currently unstable and may be removed without a major version bump. + fn identity_disconnected(&self, flags: __ws::CallReducerFlags); +} + +impl set_flags_for_identity_disconnected for super::SetReducerFlags { + fn identity_disconnected(&self, flags: __ws::CallReducerFlags) { + self.imp.set_call_reducer_flags("identity_disconnected", flags); + } +} diff --git a/templates/quickstart-chat-rust/src/module_bindings/message_table.rs b/templates/chat-console-rs/src/module_bindings/message_table.rs similarity index 96% rename from templates/quickstart-chat-rust/src/module_bindings/message_table.rs rename to templates/chat-console-rs/src/module_bindings/message_table.rs index fcd4908abb3..4c7757a9a5e 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/message_table.rs +++ b/templates/chat-console-rs/src/module_bindings/message_table.rs @@ -1,8 +1,6 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). - #![allow(unused, clippy::all)] use super::message_type::Message; use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; diff --git a/templates/quickstart-chat-rust/src/module_bindings/message_type.rs b/templates/chat-console-rs/src/module_bindings/message_type.rs similarity index 83% rename from templates/quickstart-chat-rust/src/module_bindings/message_type.rs rename to templates/chat-console-rs/src/module_bindings/message_type.rs index 184c9520f6f..16f2e194ac4 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/message_type.rs +++ b/templates/chat-console-rs/src/module_bindings/message_type.rs @@ -1,8 +1,6 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). - #![allow(unused, clippy::all)] use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; diff --git a/templates/quickstart-chat-rust/src/module_bindings/mod.rs b/templates/chat-console-rs/src/module_bindings/mod.rs similarity index 83% rename from templates/quickstart-chat-rust/src/module_bindings/mod.rs rename to templates/chat-console-rs/src/module_bindings/mod.rs index 3497ccdc4e1..27a9463c215 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/mod.rs +++ b/templates/chat-console-rs/src/module_bindings/mod.rs @@ -1,7 +1,7 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). +// This was generated using spacetimedb cli version 1.11.2 (commit 3c8836b1a3aa2f1a7176a37838212c432960ce83). #![allow(unused, clippy::all)] use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; @@ -53,6 +53,7 @@ impl __sdk::Reducer for Reducer { Reducer::IdentityDisconnected => "identity_disconnected", Reducer::SendMessage { .. } => "send_message", Reducer::SetName { .. } => "set_name", + _ => unreachable!(), } } } @@ -135,6 +136,7 @@ impl __sdk::DbUpdate for DbUpdate { pub struct AppliedDiff<'r> { message: __sdk::TableAppliedDiff<'r, Message>, user: __sdk::TableAppliedDiff<'r, User>, + __unused: std::marker::PhantomData<&'r ()>, } impl __sdk::InModule for AppliedDiff<'_> { @@ -165,6 +167,16 @@ impl __sdk::InModule for RemoteReducers { type Module = RemoteModule; } +/// The `procedures` field of [`DbConnection`] and other [`DbContext`] types, +/// with methods provided by extension traits for each procedure defined by the module. +pub struct RemoteProcedures { + imp: __sdk::DbContextImpl, +} + +impl __sdk::InModule for RemoteProcedures { + type Module = RemoteModule; +} + #[doc(hidden)] /// The `set_reducer_flags` field of [`DbConnection`], /// with methods provided by extension traits for each reducer defined by the module. @@ -217,6 +229,9 @@ pub struct DbConnection { /// This type is currently unstable and may be removed without a major version bump. pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + imp: __sdk::DbContextImpl, } @@ -227,6 +242,7 @@ impl __sdk::InModule for DbConnection { impl __sdk::DbContext for DbConnection { type DbView = RemoteTables; type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; type SetReducerFlags = SetReducerFlags; fn db(&self) -> &Self::DbView { @@ -235,6 +251,9 @@ impl __sdk::DbContext for DbConnection { fn reducers(&self) -> &Self::Reducers { &self.reducers } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } fn set_reducer_flags(&self) -> &Self::SetReducerFlags { &self.set_reducer_flags } @@ -340,6 +359,7 @@ impl __sdk::DbConnection for DbConnection { Self { db: RemoteTables { imp: imp.clone() }, reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, set_reducer_flags: SetReducerFlags { imp: imp.clone() }, imp, } @@ -420,6 +440,8 @@ pub struct EventContext { /// /// This type is currently unstable and may be removed without a major version bump. pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, /// The event which caused these callbacks to run. pub event: __sdk::Event, imp: __sdk::DbContextImpl, @@ -435,6 +457,7 @@ impl __sdk::AbstractEventContext for EventContext { db: RemoteTables { imp: imp.clone() }, reducers: RemoteReducers { imp: imp.clone() }, set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, event, imp, } @@ -448,6 +471,7 @@ impl __sdk::InModule for EventContext { impl __sdk::DbContext for EventContext { type DbView = RemoteTables; type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; type SetReducerFlags = SetReducerFlags; fn db(&self) -> &Self::DbView { @@ -456,6 +480,9 @@ impl __sdk::DbContext for EventContext { fn reducers(&self) -> &Self::Reducers { &self.reducers } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } fn set_reducer_flags(&self) -> &Self::SetReducerFlags { &self.set_reducer_flags } @@ -499,6 +526,8 @@ pub struct ReducerEventContext { /// /// This type is currently unstable and may be removed without a major version bump. pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, /// The event which caused these callbacks to run. pub event: __sdk::ReducerEvent, imp: __sdk::DbContextImpl, @@ -514,6 +543,7 @@ impl __sdk::AbstractEventContext for ReducerEventContext { db: RemoteTables { imp: imp.clone() }, reducers: RemoteReducers { imp: imp.clone() }, set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, event, imp, } @@ -527,6 +557,7 @@ impl __sdk::InModule for ReducerEventContext { impl __sdk::DbContext for ReducerEventContext { type DbView = RemoteTables; type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; type SetReducerFlags = SetReducerFlags; fn db(&self) -> &Self::DbView { @@ -535,6 +566,9 @@ impl __sdk::DbContext for ReducerEventContext { fn reducers(&self) -> &Self::Reducers { &self.reducers } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } fn set_reducer_flags(&self) -> &Self::SetReducerFlags { &self.set_reducer_flags } @@ -566,6 +600,88 @@ impl __sdk::DbContext for ReducerEventContext { impl __sdk::ReducerEventContext for ReducerEventContext {} +/// An [`__sdk::DbContext`] passed to procedure callbacks. +pub struct ProcedureEventContext { + /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. + pub db: RemoteTables, + /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. + pub reducers: RemoteReducers, + /// Access to setting the call-flags of each reducer defined for each reducer defined by the module + /// via extension traits implemented for [`SetReducerFlags`]. + /// + /// This type is currently unstable and may be removed without a major version bump. + pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, + imp: __sdk::DbContextImpl, +} + +impl __sdk::AbstractEventContext for ProcedureEventContext { + type Event = (); + fn event(&self) -> &Self::Event { + &() + } + fn new(imp: __sdk::DbContextImpl, _event: Self::Event) -> Self { + Self { + db: RemoteTables { imp: imp.clone() }, + reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, + set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + imp, + } + } +} + +impl __sdk::InModule for ProcedureEventContext { + type Module = RemoteModule; +} + +impl __sdk::DbContext for ProcedureEventContext { + type DbView = RemoteTables; + type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; + type SetReducerFlags = SetReducerFlags; + + fn db(&self) -> &Self::DbView { + &self.db + } + fn reducers(&self) -> &Self::Reducers { + &self.reducers + } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } + fn set_reducer_flags(&self) -> &Self::SetReducerFlags { + &self.set_reducer_flags + } + + fn is_active(&self) -> bool { + self.imp.is_active() + } + + fn disconnect(&self) -> __sdk::Result<()> { + self.imp.disconnect() + } + + type SubscriptionBuilder = __sdk::SubscriptionBuilder; + + fn subscription_builder(&self) -> Self::SubscriptionBuilder { + __sdk::SubscriptionBuilder::new(&self.imp) + } + + fn try_identity(&self) -> Option<__sdk::Identity> { + self.imp.try_identity() + } + fn connection_id(&self) -> __sdk::ConnectionId { + self.imp.connection_id() + } + fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { + self.imp.try_connection_id() + } +} + +impl __sdk::ProcedureEventContext for ProcedureEventContext {} + /// An [`__sdk::DbContext`] passed to [`__sdk::SubscriptionBuilder::on_applied`] and [`SubscriptionHandle::unsubscribe_then`] callbacks. pub struct SubscriptionEventContext { /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. @@ -577,6 +693,8 @@ pub struct SubscriptionEventContext { /// /// This type is currently unstable and may be removed without a major version bump. pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, imp: __sdk::DbContextImpl, } @@ -589,6 +707,7 @@ impl __sdk::AbstractEventContext for SubscriptionEventContext { Self { db: RemoteTables { imp: imp.clone() }, reducers: RemoteReducers { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, set_reducer_flags: SetReducerFlags { imp: imp.clone() }, imp, } @@ -602,6 +721,7 @@ impl __sdk::InModule for SubscriptionEventContext { impl __sdk::DbContext for SubscriptionEventContext { type DbView = RemoteTables; type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; type SetReducerFlags = SetReducerFlags; fn db(&self) -> &Self::DbView { @@ -610,6 +730,9 @@ impl __sdk::DbContext for SubscriptionEventContext { fn reducers(&self) -> &Self::Reducers { &self.reducers } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } fn set_reducer_flags(&self) -> &Self::SetReducerFlags { &self.set_reducer_flags } @@ -653,6 +776,8 @@ pub struct ErrorContext { /// /// This type is currently unstable and may be removed without a major version bump. pub set_reducer_flags: SetReducerFlags, + /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. + pub procedures: RemoteProcedures, /// The event which caused these callbacks to run. pub event: Option<__sdk::Error>, imp: __sdk::DbContextImpl, @@ -668,6 +793,7 @@ impl __sdk::AbstractEventContext for ErrorContext { db: RemoteTables { imp: imp.clone() }, reducers: RemoteReducers { imp: imp.clone() }, set_reducer_flags: SetReducerFlags { imp: imp.clone() }, + procedures: RemoteProcedures { imp: imp.clone() }, event, imp, } @@ -681,6 +807,7 @@ impl __sdk::InModule for ErrorContext { impl __sdk::DbContext for ErrorContext { type DbView = RemoteTables; type Reducers = RemoteReducers; + type Procedures = RemoteProcedures; type SetReducerFlags = SetReducerFlags; fn db(&self) -> &Self::DbView { @@ -689,6 +816,9 @@ impl __sdk::DbContext for ErrorContext { fn reducers(&self) -> &Self::Reducers { &self.reducers } + fn procedures(&self) -> &Self::Procedures { + &self.procedures + } fn set_reducer_flags(&self) -> &Self::SetReducerFlags { &self.set_reducer_flags } @@ -724,6 +854,7 @@ impl __sdk::SpacetimeModule for RemoteModule { type DbConnection = DbConnection; type EventContext = EventContext; type ReducerEventContext = ReducerEventContext; + type ProcedureEventContext = ProcedureEventContext; type SubscriptionEventContext = SubscriptionEventContext; type ErrorContext = ErrorContext; type Reducer = Reducer; diff --git a/templates/quickstart-chat-rust/src/module_bindings/send_message_reducer.rs b/templates/chat-console-rs/src/module_bindings/send_message_reducer.rs similarity index 97% rename from templates/quickstart-chat-rust/src/module_bindings/send_message_reducer.rs rename to templates/chat-console-rs/src/module_bindings/send_message_reducer.rs index f71342e3b78..e1e701b9e03 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/send_message_reducer.rs +++ b/templates/chat-console-rs/src/module_bindings/send_message_reducer.rs @@ -1,8 +1,6 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). - #![allow(unused, clippy::all)] use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; @@ -62,6 +60,7 @@ impl send_message for super::RemoteReducers { SendMessageCallbackId(self.imp.on_reducer( "send_message", Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] let super::ReducerEventContext { event: __sdk::ReducerEvent { diff --git a/templates/quickstart-chat-rust/src/module_bindings/set_name_reducer.rs b/templates/chat-console-rs/src/module_bindings/set_name_reducer.rs similarity index 97% rename from templates/quickstart-chat-rust/src/module_bindings/set_name_reducer.rs rename to templates/chat-console-rs/src/module_bindings/set_name_reducer.rs index 21cd2e1c094..cc9905d3dc1 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/set_name_reducer.rs +++ b/templates/chat-console-rs/src/module_bindings/set_name_reducer.rs @@ -1,8 +1,6 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). - #![allow(unused, clippy::all)] use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; @@ -62,6 +60,7 @@ impl set_name for super::RemoteReducers { SetNameCallbackId(self.imp.on_reducer( "set_name", Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] let super::ReducerEventContext { event: __sdk::ReducerEvent { diff --git a/templates/quickstart-chat-rust/src/module_bindings/user_table.rs b/templates/chat-console-rs/src/module_bindings/user_table.rs similarity index 97% rename from templates/quickstart-chat-rust/src/module_bindings/user_table.rs rename to templates/chat-console-rs/src/module_bindings/user_table.rs index 130e605272e..a77137d5e04 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/user_table.rs +++ b/templates/chat-console-rs/src/module_bindings/user_table.rs @@ -1,8 +1,6 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). - #![allow(unused, clippy::all)] use super::user_type::User; use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; diff --git a/templates/quickstart-chat-rust/src/module_bindings/user_type.rs b/templates/chat-console-rs/src/module_bindings/user_type.rs similarity index 82% rename from templates/quickstart-chat-rust/src/module_bindings/user_type.rs rename to templates/chat-console-rs/src/module_bindings/user_type.rs index 0f453ae68f6..ad82fbca031 100644 --- a/templates/quickstart-chat-rust/src/module_bindings/user_type.rs +++ b/templates/chat-console-rs/src/module_bindings/user_type.rs @@ -1,8 +1,6 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using spacetimedb cli version 1.2.0 (commit 88dc3695d8bc55c081db4a5646a4968da7587405). - #![allow(unused, clippy::all)] use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; diff --git a/templates/quickstart-chat-typescript/.template.json b/templates/chat-react-ts/.template.json similarity index 100% rename from templates/quickstart-chat-typescript/.template.json rename to templates/chat-react-ts/.template.json diff --git a/templates/quickstart-chat-typescript/CHANGELOG.md b/templates/chat-react-ts/CHANGELOG.md similarity index 100% rename from templates/quickstart-chat-typescript/CHANGELOG.md rename to templates/chat-react-ts/CHANGELOG.md diff --git a/templates/quickstart-chat-rust/LICENSE b/templates/chat-react-ts/LICENSE similarity index 100% rename from templates/quickstart-chat-rust/LICENSE rename to templates/chat-react-ts/LICENSE diff --git a/templates/quickstart-chat-typescript/README.md b/templates/chat-react-ts/README.md similarity index 100% rename from templates/quickstart-chat-typescript/README.md rename to templates/chat-react-ts/README.md diff --git a/templates/quickstart-chat-typescript/index.html b/templates/chat-react-ts/index.html similarity index 100% rename from templates/quickstart-chat-typescript/index.html rename to templates/chat-react-ts/index.html diff --git a/templates/quickstart-chat-typescript/package.json b/templates/chat-react-ts/package.json similarity index 100% rename from templates/quickstart-chat-typescript/package.json rename to templates/chat-react-ts/package.json diff --git a/templates/quickstart-chat-typescript/public/vite.svg b/templates/chat-react-ts/public/vite.svg similarity index 100% rename from templates/quickstart-chat-typescript/public/vite.svg rename to templates/chat-react-ts/public/vite.svg diff --git a/templates/quickstart-chat-typescript/spacetimedb/package-lock.json b/templates/chat-react-ts/spacetimedb/package-lock.json similarity index 100% rename from templates/quickstart-chat-typescript/spacetimedb/package-lock.json rename to templates/chat-react-ts/spacetimedb/package-lock.json diff --git a/templates/quickstart-chat-typescript/spacetimedb/package.json b/templates/chat-react-ts/spacetimedb/package.json similarity index 100% rename from templates/quickstart-chat-typescript/spacetimedb/package.json rename to templates/chat-react-ts/spacetimedb/package.json diff --git a/templates/quickstart-chat-typescript/spacetimedb/src/index.ts b/templates/chat-react-ts/spacetimedb/src/index.ts similarity index 100% rename from templates/quickstart-chat-typescript/spacetimedb/src/index.ts rename to templates/chat-react-ts/spacetimedb/src/index.ts diff --git a/templates/quickstart-chat-typescript/spacetimedb/tsconfig.json b/templates/chat-react-ts/spacetimedb/tsconfig.json similarity index 100% rename from templates/quickstart-chat-typescript/spacetimedb/tsconfig.json rename to templates/chat-react-ts/spacetimedb/tsconfig.json diff --git a/templates/quickstart-chat-typescript/src/.gitattributes b/templates/chat-react-ts/src/.gitattributes similarity index 100% rename from templates/quickstart-chat-typescript/src/.gitattributes rename to templates/chat-react-ts/src/.gitattributes diff --git a/templates/quickstart-chat-typescript/src/App.css b/templates/chat-react-ts/src/App.css similarity index 100% rename from templates/quickstart-chat-typescript/src/App.css rename to templates/chat-react-ts/src/App.css diff --git a/templates/quickstart-chat-typescript/src/App.integration.test.tsx b/templates/chat-react-ts/src/App.integration.test.tsx similarity index 100% rename from templates/quickstart-chat-typescript/src/App.integration.test.tsx rename to templates/chat-react-ts/src/App.integration.test.tsx diff --git a/templates/quickstart-chat-typescript/src/App.tsx b/templates/chat-react-ts/src/App.tsx similarity index 100% rename from templates/quickstart-chat-typescript/src/App.tsx rename to templates/chat-react-ts/src/App.tsx diff --git a/templates/quickstart-chat-typescript/src/assets/react.svg b/templates/chat-react-ts/src/assets/react.svg similarity index 100% rename from templates/quickstart-chat-typescript/src/assets/react.svg rename to templates/chat-react-ts/src/assets/react.svg diff --git a/templates/quickstart-chat-typescript/src/index.css b/templates/chat-react-ts/src/index.css similarity index 100% rename from templates/quickstart-chat-typescript/src/index.css rename to templates/chat-react-ts/src/index.css diff --git a/templates/quickstart-chat-typescript/src/main.tsx b/templates/chat-react-ts/src/main.tsx similarity index 100% rename from templates/quickstart-chat-typescript/src/main.tsx rename to templates/chat-react-ts/src/main.tsx diff --git a/templates/quickstart-chat-typescript/src/module_bindings/index.ts b/templates/chat-react-ts/src/module_bindings/index.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/index.ts rename to templates/chat-react-ts/src/module_bindings/index.ts diff --git a/templates/chat-react-ts/src/module_bindings/init_type.ts b/templates/chat-react-ts/src/module_bindings/init_type.ts new file mode 100644 index 00000000000..52ed691ed94 --- /dev/null +++ b/templates/chat-react-ts/src/module_bindings/init_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('Init', {}); diff --git a/templates/quickstart-chat-typescript/src/module_bindings/message_table.ts b/templates/chat-react-ts/src/module_bindings/message_table.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/message_table.ts rename to templates/chat-react-ts/src/module_bindings/message_table.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/message_type.ts b/templates/chat-react-ts/src/module_bindings/message_type.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/message_type.ts rename to templates/chat-react-ts/src/module_bindings/message_type.ts diff --git a/templates/basic-typescript/src/module_bindings/on_connect_reducer.ts b/templates/chat-react-ts/src/module_bindings/on_connect_reducer.ts similarity index 100% rename from templates/basic-typescript/src/module_bindings/on_connect_reducer.ts rename to templates/chat-react-ts/src/module_bindings/on_connect_reducer.ts diff --git a/templates/chat-react-ts/src/module_bindings/on_connect_type.ts b/templates/chat-react-ts/src/module_bindings/on_connect_type.ts new file mode 100644 index 00000000000..d36362515de --- /dev/null +++ b/templates/chat-react-ts/src/module_bindings/on_connect_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('OnConnect', {}); diff --git a/templates/basic-typescript/src/module_bindings/on_disconnect_reducer.ts b/templates/chat-react-ts/src/module_bindings/on_disconnect_reducer.ts similarity index 100% rename from templates/basic-typescript/src/module_bindings/on_disconnect_reducer.ts rename to templates/chat-react-ts/src/module_bindings/on_disconnect_reducer.ts diff --git a/templates/chat-react-ts/src/module_bindings/on_disconnect_type.ts b/templates/chat-react-ts/src/module_bindings/on_disconnect_type.ts new file mode 100644 index 00000000000..efda71ebcfd --- /dev/null +++ b/templates/chat-react-ts/src/module_bindings/on_disconnect_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('OnDisconnect', {}); diff --git a/templates/quickstart-chat-typescript/src/module_bindings/send_message_reducer.ts b/templates/chat-react-ts/src/module_bindings/send_message_reducer.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/send_message_reducer.ts rename to templates/chat-react-ts/src/module_bindings/send_message_reducer.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/send_message_type.ts b/templates/chat-react-ts/src/module_bindings/send_message_type.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/send_message_type.ts rename to templates/chat-react-ts/src/module_bindings/send_message_type.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/set_name_reducer.ts b/templates/chat-react-ts/src/module_bindings/set_name_reducer.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/set_name_reducer.ts rename to templates/chat-react-ts/src/module_bindings/set_name_reducer.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/set_name_type.ts b/templates/chat-react-ts/src/module_bindings/set_name_type.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/set_name_type.ts rename to templates/chat-react-ts/src/module_bindings/set_name_type.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/user_table.ts b/templates/chat-react-ts/src/module_bindings/user_table.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/user_table.ts rename to templates/chat-react-ts/src/module_bindings/user_table.ts diff --git a/templates/quickstart-chat-typescript/src/module_bindings/user_type.ts b/templates/chat-react-ts/src/module_bindings/user_type.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/user_type.ts rename to templates/chat-react-ts/src/module_bindings/user_type.ts diff --git a/templates/quickstart-chat-typescript/src/setupTests.ts b/templates/chat-react-ts/src/setupTests.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/setupTests.ts rename to templates/chat-react-ts/src/setupTests.ts diff --git a/templates/quickstart-chat-typescript/tsconfig.app.json b/templates/chat-react-ts/tsconfig.app.json similarity index 100% rename from templates/quickstart-chat-typescript/tsconfig.app.json rename to templates/chat-react-ts/tsconfig.app.json diff --git a/templates/quickstart-chat-typescript/tsconfig.json b/templates/chat-react-ts/tsconfig.json similarity index 100% rename from templates/quickstart-chat-typescript/tsconfig.json rename to templates/chat-react-ts/tsconfig.json diff --git a/templates/quickstart-chat-typescript/tsconfig.node.json b/templates/chat-react-ts/tsconfig.node.json similarity index 100% rename from templates/quickstart-chat-typescript/tsconfig.node.json rename to templates/chat-react-ts/tsconfig.node.json diff --git a/templates/quickstart-chat-typescript/vite.config.ts b/templates/chat-react-ts/vite.config.ts similarity index 100% rename from templates/quickstart-chat-typescript/vite.config.ts rename to templates/chat-react-ts/vite.config.ts diff --git a/templates/quickstart-chat-typescript/vitest.config.ts b/templates/chat-react-ts/vitest.config.ts similarity index 100% rename from templates/quickstart-chat-typescript/vitest.config.ts rename to templates/chat-react-ts/vitest.config.ts diff --git a/templates/basic-react/.template.json b/templates/react-ts/.template.json similarity index 100% rename from templates/basic-react/.template.json rename to templates/react-ts/.template.json diff --git a/templates/quickstart-chat-typescript/LICENSE b/templates/react-ts/LICENSE similarity index 100% rename from templates/quickstart-chat-typescript/LICENSE rename to templates/react-ts/LICENSE diff --git a/templates/basic-react/index.html b/templates/react-ts/index.html similarity index 100% rename from templates/basic-react/index.html rename to templates/react-ts/index.html diff --git a/templates/basic-react/package.json b/templates/react-ts/package.json similarity index 95% rename from templates/basic-react/package.json rename to templates/react-ts/package.json index 1f4a68402ec..a49c2f23238 100644 --- a/templates/basic-react/package.json +++ b/templates/react-ts/package.json @@ -1,5 +1,5 @@ { - "name": "@clockworklabs/basic-react", + "name": "@clockworklabs/react-ts", "private": true, "version": "0.0.1", "type": "module", diff --git a/templates/basic-typescript/spacetimedb/package.json b/templates/react-ts/spacetimedb/package.json similarity index 100% rename from templates/basic-typescript/spacetimedb/package.json rename to templates/react-ts/spacetimedb/package.json diff --git a/templates/basic-typescript/spacetimedb/pnpm-lock.yaml b/templates/react-ts/spacetimedb/pnpm-lock.yaml similarity index 100% rename from templates/basic-typescript/spacetimedb/pnpm-lock.yaml rename to templates/react-ts/spacetimedb/pnpm-lock.yaml diff --git a/templates/basic-react/spacetimedb/src/index.ts b/templates/react-ts/spacetimedb/src/index.ts similarity index 100% rename from templates/basic-react/spacetimedb/src/index.ts rename to templates/react-ts/spacetimedb/src/index.ts diff --git a/templates/basic-typescript/spacetimedb/tsconfig.json b/templates/react-ts/spacetimedb/tsconfig.json similarity index 100% rename from templates/basic-typescript/spacetimedb/tsconfig.json rename to templates/react-ts/spacetimedb/tsconfig.json diff --git a/templates/basic-react/src/App.tsx b/templates/react-ts/src/App.tsx similarity index 100% rename from templates/basic-react/src/App.tsx rename to templates/react-ts/src/App.tsx diff --git a/templates/basic-react/src/main.tsx b/templates/react-ts/src/main.tsx similarity index 94% rename from templates/basic-react/src/main.tsx rename to templates/react-ts/src/main.tsx index 2d43ef4495a..9d5844aebe0 100644 --- a/templates/basic-react/src/main.tsx +++ b/templates/react-ts/src/main.tsx @@ -6,7 +6,7 @@ import { SpacetimeDBProvider } from 'spacetimedb/react'; import { DbConnection, ErrorContext } from './module_bindings/index.ts'; const HOST = import.meta.env.VITE_SPACETIMEDB_HOST ?? 'ws://localhost:3000'; -const DB_NAME = import.meta.env.VITE_SPACETIMEDB_DB_NAME ?? 'basic-react'; +const DB_NAME = import.meta.env.VITE_SPACETIMEDB_DB_NAME ?? 'react-ts'; const onConnect = (_conn: DbConnection, identity: Identity, token: string) => { localStorage.setItem('auth_token', token); diff --git a/templates/basic-typescript/src/module_bindings/add_reducer.ts b/templates/react-ts/src/module_bindings/add_reducer.ts similarity index 100% rename from templates/basic-typescript/src/module_bindings/add_reducer.ts rename to templates/react-ts/src/module_bindings/add_reducer.ts diff --git a/templates/react-ts/src/module_bindings/add_type.ts b/templates/react-ts/src/module_bindings/add_type.ts new file mode 100644 index 00000000000..638f62cea39 --- /dev/null +++ b/templates/react-ts/src/module_bindings/add_type.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('Add', { + name: __t.string(), +}); diff --git a/templates/basic-typescript/src/module_bindings/index.ts b/templates/react-ts/src/module_bindings/index.ts similarity index 100% rename from templates/basic-typescript/src/module_bindings/index.ts rename to templates/react-ts/src/module_bindings/index.ts diff --git a/templates/react-ts/src/module_bindings/init_type.ts b/templates/react-ts/src/module_bindings/init_type.ts new file mode 100644 index 00000000000..52ed691ed94 --- /dev/null +++ b/templates/react-ts/src/module_bindings/init_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('Init', {}); diff --git a/templates/quickstart-chat-typescript/src/module_bindings/on_connect_reducer.ts b/templates/react-ts/src/module_bindings/on_connect_reducer.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/on_connect_reducer.ts rename to templates/react-ts/src/module_bindings/on_connect_reducer.ts diff --git a/templates/react-ts/src/module_bindings/on_connect_type.ts b/templates/react-ts/src/module_bindings/on_connect_type.ts new file mode 100644 index 00000000000..d36362515de --- /dev/null +++ b/templates/react-ts/src/module_bindings/on_connect_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('OnConnect', {}); diff --git a/templates/quickstart-chat-typescript/src/module_bindings/on_disconnect_reducer.ts b/templates/react-ts/src/module_bindings/on_disconnect_reducer.ts similarity index 100% rename from templates/quickstart-chat-typescript/src/module_bindings/on_disconnect_reducer.ts rename to templates/react-ts/src/module_bindings/on_disconnect_reducer.ts diff --git a/templates/react-ts/src/module_bindings/on_disconnect_type.ts b/templates/react-ts/src/module_bindings/on_disconnect_type.ts new file mode 100644 index 00000000000..efda71ebcfd --- /dev/null +++ b/templates/react-ts/src/module_bindings/on_disconnect_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('OnDisconnect', {}); diff --git a/templates/basic-typescript/src/module_bindings/person_table.ts b/templates/react-ts/src/module_bindings/person_table.ts similarity index 100% rename from templates/basic-typescript/src/module_bindings/person_table.ts rename to templates/react-ts/src/module_bindings/person_table.ts diff --git a/templates/basic-typescript/src/module_bindings/person_type.ts b/templates/react-ts/src/module_bindings/person_type.ts similarity index 100% rename from templates/basic-typescript/src/module_bindings/person_type.ts rename to templates/react-ts/src/module_bindings/person_type.ts diff --git a/templates/basic-typescript/src/module_bindings/say_hello_reducer.ts b/templates/react-ts/src/module_bindings/say_hello_reducer.ts similarity index 100% rename from templates/basic-typescript/src/module_bindings/say_hello_reducer.ts rename to templates/react-ts/src/module_bindings/say_hello_reducer.ts diff --git a/templates/react-ts/src/module_bindings/say_hello_type.ts b/templates/react-ts/src/module_bindings/say_hello_type.ts new file mode 100644 index 00000000000..6293ca6bd09 --- /dev/null +++ b/templates/react-ts/src/module_bindings/say_hello_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('SayHello', {}); diff --git a/templates/basic-react/tsconfig.json b/templates/react-ts/tsconfig.json similarity index 100% rename from templates/basic-react/tsconfig.json rename to templates/react-ts/tsconfig.json diff --git a/templates/basic-react/vite.config.ts b/templates/react-ts/vite.config.ts similarity index 100% rename from templates/basic-react/vite.config.ts rename to templates/react-ts/vite.config.ts diff --git a/templates/templates-list.json b/templates/templates-list.json deleted file mode 100644 index 05f8c035e5c..00000000000 --- a/templates/templates-list.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "highlights": [ - { "name": "React", "template_id": "basic-react" } - ], - "templates": [ - { - "id": "basic-typescript", - "description": "A basic TypeScript client and server template with only stubs for code", - "server_source": "basic-ts/spacetimedb", - "client_source": "basic-ts", - "server_lang": "typescript", - "client_lang": "typescript" - }, - { - "id": "basic-c-sharp", - "description": "A basic C# client and server template with only stubs for code", - "server_source": "basic-cs/spacetimedb", - "client_source": "basic-cs", - "server_lang": "csharp", - "client_lang": "csharp" - }, - { - "id": "basic-rust", - "description": "A basic Rust client and server template with only stubs for code", - "server_source": "basic-rs/spacetimedb", - "client_source": "basic-rs", - "server_lang": "rust", - "client_lang": "rust" - }, - { - "id": "basic-react", - "description": "React web app with TypeScript server", - "server_source": "basic-react/spacetimedb", - "client_source": "basic-react", - "server_lang": "typescript", - "client_lang": "typescript" - }, - { - "id": "quickstart-chat-rust", - "description": "Rust server/client implementing quickstart chat", - "server_source": "quickstart-chat-rs/spacetimedb", - "client_source": "quickstart-chat-rs", - "server_lang": "rust", - "client_lang": "rust" - }, - { - "id": "quickstart-chat-c-sharp", - "description": "C# server/client implementing quickstart chat", - "server_source": "quickstart-chat-cs/spacetimedb", - "client_source": "quickstart-chat-cs", - "server_lang": "csharp", - "client_lang": "csharp" - }, - { - "id": "quickstart-chat-typescript", - "description": "TypeScript server/client implementing quickstart chat", - "server_source": "quickstart-chat-ts/spacetimedb", - "client_source": "quickstart-chat-ts", - "server_lang": "typescript", - "client_lang": "typescript" - } - ] -} diff --git a/tools/ci/src/main.rs b/tools/ci/src/main.rs index 036e8993033..d7cf7e269c7 100644 --- a/tools/ci/src/main.rs +++ b/tools/ci/src/main.rs @@ -218,7 +218,8 @@ fn main() -> Result<()> { ["-m", "smoketests"] .into_iter() .map(|s| s.to_string()) - .chain(smoketest_args), + .chain(smoketest_args) + .chain(vec!["spacetimedb_init".to_string()]), ) .run()?; } diff --git a/tools/upgrade-version/src/main.rs b/tools/upgrade-version/src/main.rs index 212f82e9fc4..cead3e53883 100644 --- a/tools/upgrade-version/src/main.rs +++ b/tools/upgrade-version/src/main.rs @@ -169,7 +169,7 @@ fn main() -> anyhow::Result<()> { } })?; - edit_toml("templates/basic-rust/spacetimedb/Cargo.toml", |doc| { + edit_toml("templates/basic-rs/spacetimedb/Cargo.toml", |doc| { // Only set major.minor.* for the spacetimedb dependency. // See https://github.com/clockworklabs/SpacetimeDB/issues/2724. // @@ -178,7 +178,7 @@ fn main() -> anyhow::Result<()> { doc["dependencies"]["spacetimedb"] = toml_edit::value(wildcard_patch.clone()); })?; - edit_toml("templates/basic-rust/Cargo.toml", |doc| { + edit_toml("templates/basic-rs/Cargo.toml", |doc| { doc["dependencies"]["spacetimedb-sdk"] = toml_edit::value(wildcard_patch.clone()); })?; @@ -256,7 +256,7 @@ fn main() -> anyhow::Result<()> { // 2) StdbModule.csproj files: SpacetimeDB.Runtime dependency -> major.minor let stdb_modules: &[&str] = &[ "demo/Blackholio/server-csharp/StdbModule.csproj", - "templates/quickstart-chat-c-sharp/spacetimedb/StdbModule.csproj", + "templates/chat-console-cs/spacetimedb/StdbModule.csproj", "sdks/csharp/examples~/regression-tests/server/StdbModule.csproj", ]; for path in stdb_modules { @@ -287,7 +287,7 @@ fn main() -> anyhow::Result<()> { // 4) Template StdbModule.csproj: SpacetimeDB.Runtime dependency -> major.minor.* rewrite_csproj_package_ref_version( - "templates/basic-c-sharp/spacetimedb/StdbModule.csproj", + "templates/basic-cs/spacetimedb/StdbModule.csproj", "SpacetimeDB.Runtime", &wildcard_patch, )?;