diff --git a/Cargo.lock b/Cargo.lock index 879e940a32a..a8252003541 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1180,6 +1180,7 @@ dependencies = [ "duct", "spacetimedb-guard", "tempfile", + "which 8.0.0", ] [[package]] diff --git a/crates/bindings-typescript/src/svelte/SpacetimeDBProvider.ts b/crates/bindings-typescript/src/svelte/SpacetimeDBProvider.ts index 20480c500ef..740af1030b9 100644 --- a/crates/bindings-typescript/src/svelte/SpacetimeDBProvider.ts +++ b/crates/bindings-typescript/src/svelte/SpacetimeDBProvider.ts @@ -1,5 +1,5 @@ import { setContext, onDestroy } from 'svelte'; -import { writable, type Writable } from 'svelte/store'; +import { readonly, writable, type Readable } from 'svelte/store'; import { DbConnectionBuilder, type DbConnectionImpl, @@ -32,7 +32,7 @@ export function createSpacetimeDBProvider< DbConnection extends DbConnectionImpl, >( connectionBuilder: DbConnectionBuilder -): Writable { +): Readable { const key = ConnectionManager.getKey( connectionBuilder.getUri(), connectionBuilder.getModuleName() @@ -72,6 +72,9 @@ export function createSpacetimeDBProvider< ConnectionManager.release(key); }); - setContext(SPACETIMEDB_CONTEXT_KEY, store); - return store; + // Hand out a read-only view: the state is owned by the ConnectionManager, so + // writes from components would only be overwritten (or worse, believed). + const readable = readonly(store); + setContext(SPACETIMEDB_CONTEXT_KEY, readable); + return readable; } diff --git a/crates/bindings-typescript/src/svelte/index.ts b/crates/bindings-typescript/src/svelte/index.ts index b32fbdf4b80..3b3e64aba48 100644 --- a/crates/bindings-typescript/src/svelte/index.ts +++ b/crates/bindings-typescript/src/svelte/index.ts @@ -2,3 +2,4 @@ export * from './SpacetimeDBProvider.ts'; export { useSpacetimeDB } from './useSpacetimeDB.ts'; export { useTable } from './useTable.ts'; export { useReducer } from './useReducer.ts'; +export { useProcedure } from './useProcedure.ts'; diff --git a/crates/bindings-typescript/src/svelte/useProcedure.ts b/crates/bindings-typescript/src/svelte/useProcedure.ts new file mode 100644 index 00000000000..001dfc0a8de --- /dev/null +++ b/crates/bindings-typescript/src/svelte/useProcedure.ts @@ -0,0 +1,57 @@ +import { getByAccessorPath } from '../lib/accessor_path.ts'; +import { onDestroy } from 'svelte'; +import { get } from 'svelte/store'; +import type { UntypedProcedureDef } from '../sdk/procedures.ts'; +import { useSpacetimeDB } from './useSpacetimeDB.ts'; +import type { + ProcedureParamsType, + ProcedureReturnType, +} from '../sdk/type_utils.ts'; + +export function useProcedure( + procedureDef: ProcedureDef +): ( + ...params: ProcedureParamsType +) => Promise> { + const connectionStore = useSpacetimeDB(); + const procedureName = procedureDef.accessorName; + + // Holds calls made before the connection exists + const queue: { + params: ProcedureParamsType; + resolve: (val: ProcedureReturnType) => void; + reject: (err: unknown) => void; + }[] = []; + + // Flush when we finally have a connection + const unsubscribe = connectionStore.subscribe(state => { + const conn = state.getConnection(); + if (!conn || !queue.length) return; + + const fn = getByAccessorPath(conn.procedures, procedureName) as ( + ...p: ProcedureParamsType + ) => Promise>; + for (const item of queue.splice(0)) { + fn(...item.params).then(item.resolve, item.reject); + } + }); + + onDestroy(() => { + unsubscribe(); + }); + + return (...params: ProcedureParamsType) => { + const conn = get(connectionStore).getConnection(); + if (!conn) { + return new Promise>( + (resolve, reject) => { + queue.push({ params, resolve, reject }); + } + ); + } + const fn = getByAccessorPath(conn.procedures, procedureName) as ( + ...p: ProcedureParamsType + ) => Promise>; + return fn(...params); + }; +} diff --git a/crates/bindings-typescript/src/svelte/useReducer.ts b/crates/bindings-typescript/src/svelte/useReducer.ts index f574932674a..8bdff9d8852 100644 --- a/crates/bindings-typescript/src/svelte/useReducer.ts +++ b/crates/bindings-typescript/src/svelte/useReducer.ts @@ -1,17 +1,9 @@ import { getByAccessorPath } from '../lib/accessor_path.ts'; import { onDestroy } from 'svelte'; import { get } from 'svelte/store'; -import type { InferTypeOfParams } from '../lib/type_builders.ts'; import type { UntypedReducerDef } from '../sdk/reducers.ts'; +import type { ParamsType } from '../sdk/type_utils.ts'; import { useSpacetimeDB } from './useSpacetimeDB.ts'; -import type { Prettify } from '../lib/type_util.ts'; - -type IsEmptyObject = [keyof T] extends [never] ? true : false; -type MaybeParams = IsEmptyObject extends true ? [] : [params: T]; - -type ParamsType = MaybeParams< - Prettify> ->; export function useReducer( reducerDef: ReducerDef diff --git a/crates/bindings-typescript/src/svelte/useSpacetimeDB.ts b/crates/bindings-typescript/src/svelte/useSpacetimeDB.ts index af74990e85c..7f525e1d6db 100644 --- a/crates/bindings-typescript/src/svelte/useSpacetimeDB.ts +++ b/crates/bindings-typescript/src/svelte/useSpacetimeDB.ts @@ -1,13 +1,13 @@ import { getContext } from 'svelte'; -import type { Writable } from 'svelte/store'; +import type { Readable } from 'svelte/store'; import { SPACETIMEDB_CONTEXT_KEY, type ConnectionState, } from './connection_state.ts'; // Throws an error if used outside of a SpacetimeDBProvider -export function useSpacetimeDB(): Writable { - const context = getContext | undefined>( +export function useSpacetimeDB(): Readable { + const context = getContext | undefined>( SPACETIMEDB_CONTEXT_KEY ); diff --git a/crates/bindings-typescript/src/svelte/useTable.ts b/crates/bindings-typescript/src/svelte/useTable.ts index 24fb55d9350..742cf4c4665 100644 --- a/crates/bindings-typescript/src/svelte/useTable.ts +++ b/crates/bindings-typescript/src/svelte/useTable.ts @@ -1,7 +1,7 @@ import type { UntypedClientTable } from '../sdk/client_table.ts'; import { getByAccessorPath } from '../lib/accessor_path.ts'; import { onDestroy } from 'svelte'; -import { writable, get, type Readable } from 'svelte/store'; +import { writable, type Readable } from 'svelte/store'; import { useSpacetimeDB } from './useSpacetimeDB.ts'; import type { ConnectionState } from './connection_state.ts'; import type { EventContextInterface } from '../sdk/db_connection_impl.ts'; @@ -75,13 +75,17 @@ export function useTable( let appliedConnectionId: string | null = null; let subscribedConnection: ReturnType = null; - let latestTransactionEvent: any = null; + // The latest connection state, kept current by the store subscription below. + // Reading it here instead of calling `get(connectionStore)` avoids a + // subscribe/unsubscribe round trip on every transaction. + let currentState: ConnectionState | undefined; + + let latestTransactionEventId: string | null = null; let unsubscribeFromTable: (() => void) | null = null; let subscriptionHandle: { unsubscribe: () => void } | null = null; const computeFilteredRows = (): readonly Prettify[] => { - const state = get(connectionStore); - const connection = state.getConnection(); + const connection = currentState?.getConnection(); if (!connection) return []; const table = getByAccessorPath( @@ -100,8 +104,7 @@ export function useTable( }; const setupTableListeners = () => { - const state = get(connectionStore); - const connection = state.getConnection(); + const connection = currentState?.getConnection(); if (!connection) return; const table = getByAccessorPath( @@ -117,11 +120,8 @@ export function useTable( if (whereExpr && !evaluateBooleanExpr(whereExpr, row)) return; callbacks?.onInsert?.(row); - if ( - eventCtx.event !== latestTransactionEvent || - !latestTransactionEvent - ) { - latestTransactionEvent = eventCtx.event; + if (eventCtx.event.id !== latestTransactionEventId) { + latestTransactionEventId = eventCtx.event.id; rows.set(computeFilteredRows()); } }; @@ -133,11 +133,8 @@ export function useTable( if (whereExpr && !evaluateBooleanExpr(whereExpr, row)) return; callbacks?.onDelete?.(row); - if ( - eventCtx.event !== latestTransactionEvent || - !latestTransactionEvent - ) { - latestTransactionEvent = eventCtx.event; + if (eventCtx.event.id !== latestTransactionEventId) { + latestTransactionEventId = eventCtx.event.id; rows.set(computeFilteredRows()); } }; @@ -163,11 +160,8 @@ export function useTable( return; } - if ( - eventCtx.event !== latestTransactionEvent || - !latestTransactionEvent - ) { - latestTransactionEvent = eventCtx.event; + if (eventCtx.event.id !== latestTransactionEventId) { + latestTransactionEventId = eventCtx.event.id; rows.set(computeFilteredRows()); } }; @@ -184,8 +178,7 @@ export function useTable( }; const setupSubscription = () => { - const state = get(connectionStore); - const connection = state.getConnection(); + const connection = currentState?.getConnection(); if (!connection) return; subscriptionHandle = connection @@ -203,6 +196,7 @@ export function useTable( }; const unsubscribeConnection = connectionStore.subscribe(state => { + currentState = state; const connection = state.getConnection(); isReady.set( state.isActive && appliedConnectionId === state.connectionId.toHexString() @@ -235,7 +229,7 @@ export function useTable( unsubscribeConnection(); unsubscribeFromTable?.(); subscriptionHandle?.unsubscribe(); - latestTransactionEvent = null; + latestTransactionEventId = null; }); return [{ subscribe: rows.subscribe }, { subscribe: isReady.subscribe }]; diff --git a/crates/bindings-typescript/tests/svelte_bindings.test.ts b/crates/bindings-typescript/tests/svelte_bindings.test.ts new file mode 100644 index 00000000000..13a4d70c28f --- /dev/null +++ b/crates/bindings-typescript/tests/svelte_bindings.test.ts @@ -0,0 +1,477 @@ +// Tests for the Svelte bindings (`spacetimedb/svelte`). Reconnect behaviour of +// `useTable` is covered for every framework in framework_table_reconnect.test.ts; +// this file covers the rest of the Svelte surface. +// +// `svelte` is mocked with a minimal component lifecycle: `setContext` and +// `getContext` share one map per test (one provider and its children), and +// `onDestroy` callbacks registered while `component()` runs its body are +// returned as that component's `destroy`. +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { get, writable, type Readable } from 'svelte/store'; +import { + createSpacetimeDBProvider, + useProcedure, + useReducer, + useSpacetimeDB, + useTable, +} from '../src/svelte'; +import { + SPACETIMEDB_CONTEXT_KEY, + type ConnectionState, +} from '../src/svelte/connection_state'; +import { ConnectionManager } from '../src/sdk/connection_manager'; +import { ConnectionId } from '../src'; +import { ServerMessage } from '../src/sdk/client_api/types'; +import { WebsocketTestAdapterFactory } from '../src/sdk/websocket_test_adapter'; +import { DbConnection, tables } from '../test-app/src/module_bindings'; +import type { UntypedProcedureDef } from '../src/sdk/procedures'; +import type { UntypedReducerDef } from '../src/sdk/reducers'; +import { + anIdentity, + bobIdentity, + encodeUser, + makeQueryRows, + makeQuerySetUpdate, + sallyIdentity, +} from './utils'; + +const lifecycle = vi.hoisted(() => ({ + contexts: new Map(), + destroyers: [] as (() => void)[], +})); +vi.mock('svelte', () => ({ + setContext: (key: unknown, value: unknown) => { + lifecycle.contexts.set(key, value); + return value; + }, + getContext: (key: unknown) => lifecycle.contexts.get(key), + onDestroy: (fn: () => void) => { + lifecycle.destroyers.push(fn); + }, +})); + +/** Run `body` as a component's initialisation; returns its result and a destroy function. */ +function component(body: () => T): { value: T; destroy: () => void } { + lifecycle.destroyers = []; + const value = body(); + const destroyers = lifecycle.destroyers; + lifecycle.destroyers = []; + return { value, destroy: () => destroyers.forEach(fn => fn()) }; +} + +/** Let queued promise callbacks run. */ +async function settle() { + for (let i = 0; i < 5; i++) await Promise.resolve(); +} + +let factory: WebsocketTestAdapterFactory; +let databaseCounter = 0; + +function builder() { + return DbConnection.builder() + .withUri('ws://localhost:1234') + .withDatabaseName(`svelte-bindings-${databaseCounter}`) + .withWSFn(factory.openWebSocket); +} + +/** Complete the handshake for the connection currently opening. */ +async function establish(connection: DbConnection) { + await connection['wsPromise']; + factory.current.acceptConnection(); + factory.current.sendToClient( + ServerMessage.InitialConnection({ + identity: anIdentity, + connectionId: ConnectionId.random(), + token: 'token', + }) + ); + await settle(); +} + +beforeEach(() => { + vi.useFakeTimers(); + lifecycle.contexts.clear(); + lifecycle.destroyers = []; + factory = new WebsocketTestAdapterFactory(); + databaseCounter += 1; +}); +afterEach(() => { + vi.useRealTimers(); +}); + +describe('useSpacetimeDB', () => { + test('throws a helpful error outside a provider', () => { + expect(() => useSpacetimeDB()).toThrow(/createSpacetimeDBProvider/); + }); + + test('useTable also explains a missing provider', () => { + expect(() => useTable(tables.user)).toThrow( + /Did you forget to call `createSpacetimeDBProvider`/ + ); + }); +}); + +describe('createSpacetimeDBProvider', () => { + test('shares a read-only connection store with its children', () => { + const provider = component(() => createSpacetimeDBProvider(builder())); + try { + const store = provider.value; + expect(useSpacetimeDB()).toBe(store); + expect('set' in store).toBe(false); + expect('update' in store).toBe(false); + expect(get(store).isActive).toBe(false); + } finally { + provider.destroy(); + } + }); + + test('reflects the connection becoming active', async () => { + const provider = component(() => createSpacetimeDBProvider(builder())); + try { + const store = provider.value; + const connection = get(store).getConnection() as DbConnection; + expect(connection).toBeInstanceOf(DbConnection); + + await establish(connection); + + const state = get(store); + expect(state.isActive).toBe(true); + expect(state.identity?.isEqual(anIdentity)).toBe(true); + expect(state.token).toBe('token'); + } finally { + provider.destroy(); + } + }); + + test('reconnect(builder) replaces the connection', async () => { + const provider = component(() => createSpacetimeDBProvider(builder())); + try { + const store = provider.value; + const first = get(store).getConnection() as DbConnection; + await establish(first); + + get(store).reconnect(builder().withToken('new-token')); + + const second = get(store).getConnection() as DbConnection; + expect(second).toBeInstanceOf(DbConnection); + expect(second).not.toBe(first); + expect(first.isActive).toBe(false); + } finally { + provider.destroy(); + } + }); + + test('releases the connection when destroyed', async () => { + const b = builder(); + const key = ConnectionManager.getKey(b.getUri(), b.getModuleName()); + const provider = component(() => createSpacetimeDBProvider(b)); + const connection = get(provider.value).getConnection() as DbConnection; + await establish(connection); + + provider.destroy(); + // Release is deferred so a quick remount (HMR, {#key}) can reuse it. + expect(ConnectionManager.getConnection(key)).toBe(connection); + await vi.runOnlyPendingTimersAsync(); + + expect(ConnectionManager.getConnection(key)).toBeNull(); + expect(connection.isActive).toBe(false); + }); +}); + +/** A connection store driven by hand, for testing the call hooks in isolation. */ +function fakeConnectionStore() { + const calls: [string, unknown][] = []; + const connection = { + reducers: { + createPlayer: (args: unknown) => { + calls.push(['createPlayer', args]); + return Promise.resolve(); + }, + failingReducer: () => Promise.reject(new Error('reducer failed')), + }, + procedures: { + getScore: (args: { name: string }) => { + calls.push(['getScore', args]); + return Promise.resolve(`score for ${args.name}`); + }, + failingProcedure: () => Promise.reject(new Error('procedure failed')), + }, + }; + const state = (live: boolean): ConnectionState => ({ + isActive: live, + identity: undefined, + token: undefined, + connectionId: ConnectionId.random(), + connectionError: undefined, + getConnection: () => (live ? (connection as never) : null), + reconnect: () => {}, + }); + const store = writable(state(false)); + lifecycle.contexts.set( + SPACETIMEDB_CONTEXT_KEY, + store satisfies Readable + ); + return { + calls, + connect: () => store.set(state(true)), + disconnect: () => store.set(state(false)), + }; +} + +const createPlayer = { accessorName: 'createPlayer' } as UntypedReducerDef; +const failingReducer = { accessorName: 'failingReducer' } as UntypedReducerDef; +const getScore = { accessorName: 'getScore' } as UntypedProcedureDef; +const failingProcedure = { + accessorName: 'failingProcedure', +} as UntypedProcedureDef; + +describe('useReducer', () => { + test('queues calls made before connecting and sends them once connected', async () => { + const conn = fakeConnectionStore(); + const hook = component(() => useReducer(createPlayer)); + const call = hook.value as (args: unknown) => Promise; + + const pending = call({ name: 'Alice' }); + await settle(); + expect(conn.calls).toEqual([]); + + conn.connect(); + await expect(pending).resolves.toBeUndefined(); + expect(conn.calls).toEqual([['createPlayer', { name: 'Alice' }]]); + hook.destroy(); + }); + + test('calls straight through when connected', async () => { + const conn = fakeConnectionStore(); + conn.connect(); + const hook = component(() => useReducer(createPlayer)); + const call = hook.value as (args: unknown) => Promise; + + await call({ name: 'Bob' }); + expect(conn.calls).toEqual([['createPlayer', { name: 'Bob' }]]); + hook.destroy(); + }); + + test('rejects a queued call when the reducer fails', async () => { + const conn = fakeConnectionStore(); + const hook = component(() => useReducer(failingReducer)); + const pending = (hook.value as () => Promise)(); + conn.connect(); + await expect(pending).rejects.toThrow('reducer failed'); + hook.destroy(); + }); + + test('stops sending queued calls once destroyed', async () => { + const conn = fakeConnectionStore(); + const hook = component(() => useReducer(createPlayer)); + void (hook.value as (args: unknown) => Promise)({ name: 'Ghost' }); + + hook.destroy(); + conn.connect(); + await settle(); + expect(conn.calls).toEqual([]); + }); +}); + +describe('useProcedure', () => { + test('queues calls made before connecting and resolves with the return value', async () => { + const conn = fakeConnectionStore(); + const hook = component(() => useProcedure(getScore)); + const call = hook.value as (args: { name: string }) => Promise; + + const pending = call({ name: 'Alice' }); + await settle(); + expect(conn.calls).toEqual([]); + + conn.connect(); + await expect(pending).resolves.toBe('score for Alice'); + hook.destroy(); + }); + + test('calls straight through when connected', async () => { + const conn = fakeConnectionStore(); + conn.connect(); + const hook = component(() => useProcedure(getScore)); + const call = hook.value as (args: { name: string }) => Promise; + + await expect(call({ name: 'Bob' })).resolves.toBe('score for Bob'); + hook.destroy(); + }); + + test('rejects a queued call when the procedure fails', async () => { + const conn = fakeConnectionStore(); + const hook = component(() => useProcedure(failingProcedure)); + const pending = (hook.value as () => Promise)(); + conn.connect(); + await expect(pending).rejects.toThrow('procedure failed'); + hook.destroy(); + }); + + test('stops sending queued calls once destroyed', async () => { + const conn = fakeConnectionStore(); + const hook = component(() => useProcedure(getScore)); + void (hook.value as (args: { name: string }) => Promise)({ + name: 'Ghost', + }); + + hook.destroy(); + conn.connect(); + await settle(); + expect(conn.calls).toEqual([]); + }); +}); + +describe('useTable', () => { + const alice = { identity: anIdentity, username: 'Alice' }; + const bob = { identity: bobIdentity, username: 'Bob' }; + const sally = { identity: sallyIdentity, username: 'Sally' }; + + /** Mount a provider with a live connection, then a component calling useTable. */ + async function mountTable( + query: Parameters[0], + initialRows: (typeof alice)[] + ) { + const events: string[] = []; + const provider = component(() => createSpacetimeDBProvider(builder())); + const connection = get(provider.value).getConnection() as DbConnection; + await establish(connection); + + const hook = component(() => + useTable(query, { + onInsert: row => events.push(`insert ${row.username}`), + onDelete: row => events.push(`delete ${row.username}`), + onUpdate: (oldRow, newRow) => + events.push(`update ${oldRow.username} -> ${newRow.username}`), + }) + ); + const [rows, ready] = hook.value; + await settle(); + + const subscribe = factory.current.outgoingMessages.at(-1); + if (subscribe?.tag !== 'Subscribe') { + throw new Error('Expected useTable to subscribe'); + } + const querySetId = subscribe.value.querySetId.id; + factory.current.sendToClient( + ServerMessage.SubscribeApplied({ + requestId: subscribe.value.requestId, + querySetId: subscribe.value.querySetId, + rows: makeQueryRows('user', initialRows.map(encodeUser)), + }) + ); + await settle(); + + const emissions: string[][] = []; + const stopWatching = rows.subscribe(value => + emissions.push(value.map(row => row.username as string)) + ); + emissions.length = 0; // drop the immediate emission from subscribing + + const transaction = async ( + inserts: (typeof alice)[], + deletes: (typeof alice)[] = [] + ) => { + factory.current.sendToClient( + ServerMessage.TransactionUpdate({ + querySets: [ + makeQuerySetUpdate( + querySetId, + 'user', + inserts.map(encodeUser), + deletes.map(encodeUser) + ), + ], + }) + ); + await settle(); + }; + const names = () => get(rows).map(row => row.username); + const destroy = () => { + stopWatching(); + hook.destroy(); + provider.destroy(); + }; + return { rows, ready, names, events, emissions, transaction, destroy }; + } + + test('becomes ready with the subscribed rows', async () => { + const t = await mountTable(tables.user, [alice, bob]); + try { + expect(get(t.ready)).toBe(true); + expect(t.names()).toEqual(['Alice', 'Bob']); + } finally { + t.destroy(); + } + }); + + test('updates rows once per transaction, firing callbacks per row', async () => { + const t = await mountTable(tables.user, [alice]); + try { + t.events.length = 0; + await t.transaction([bob, sally]); + + expect(t.names()).toEqual(['Alice', 'Bob', 'Sally']); + expect(t.events).toEqual(['insert Bob', 'insert Sally']); + expect(t.emissions).toEqual([['Alice', 'Bob', 'Sally']]); + } finally { + t.destroy(); + } + }); + + test('filters rows and callbacks by the where clause', async () => { + const t = await mountTable( + tables.user.where(row => row.username.eq('Alice')), + [alice, bob] + ); + try { + expect(t.names()).toEqual(['Alice']); + t.events.length = 0; + + // Bob is renamed to Alice: he enters the filtered set, so onInsert. + await t.transaction([{ ...bob, username: 'Alice' }], [bob]); + expect(t.events).toEqual(['insert Alice']); + expect(t.names()).toEqual(['Alice', 'Alice']); + + // Alice is renamed: she leaves the filtered set, so onDelete. + t.events.length = 0; + await t.transaction([{ ...alice, username: 'Alicia' }], [alice]); + expect(t.events).toEqual(['delete Alice']); + expect(t.names()).toEqual(['Alice']); + + // A change entirely outside the filter fires nothing. + t.events.length = 0; + t.emissions.length = 0; + await t.transaction([sally]); + expect(t.events).toEqual([]); + expect(t.emissions).toEqual([]); + } finally { + t.destroy(); + } + }); + + test('reports an in-filter change as an update', async () => { + const t = await mountTable(tables.user, [alice]); + try { + t.events.length = 0; + await t.transaction([{ ...alice, username: 'Alicia' }], [alice]); + expect(t.events).toEqual(['update Alice -> Alicia']); + expect(t.names()).toEqual(['Alicia']); + } finally { + t.destroy(); + } + }); + + test('unsubscribes and stops listening when destroyed', async () => { + const t = await mountTable(tables.user, [alice]); + t.destroy(); + await settle(); + expect(factory.current.outgoingMessages.at(-1)?.tag).toBe('Unsubscribe'); + + // Later transactions no longer reach the destroyed hook. + t.events.length = 0; + t.emissions.length = 0; + await t.transaction([bob]); + expect(t.events).toEqual([]); + expect(t.emissions).toEqual([]); + }); +}); diff --git a/crates/cli/src/subcommands/init.rs b/crates/cli/src/subcommands/init.rs index 0411393788f..0d9643a409d 100644 --- a/crates/cli/src/subcommands/init.rs +++ b/crates/cli/src/subcommands/init.rs @@ -1093,6 +1093,23 @@ fn to_major_minor_patch_wildcard(version: &str) -> String { } } +/// Templates keep a `generate` script that regenerates their checked-in +/// bindings with `cargo run -p gen-bindings`. That tool only exists inside the +/// SpacetimeDB repository, so in a user's project the script can only fail. +/// Users regenerate bindings with `spacetime generate` (or the template's +/// `spacetime:generate` script) instead. +const MONOREPO_ONLY_SCRIPT_MARKER: &str = "gen-bindings"; + +fn remove_monorepo_only_scripts(package: &mut serde_json::Value) { + if let Some(scripts) = package.get_mut("scripts").and_then(|s| s.as_object_mut()) { + scripts.retain(|_, command| { + !command + .as_str() + .is_some_and(|command| command.contains(MONOREPO_ONLY_SCRIPT_MARKER)) + }); + } +} + fn update_package_json(dir: &Path, package_name: &str) -> anyhow::Result<()> { let package_path = dir.join("package.json"); if !package_path.exists() { @@ -1111,6 +1128,8 @@ fn update_package_json(dir: &Path, package_name: &str) -> anyhow::Result<()> { deps["spacetimedb"] = json!(to_major_minor_patch_wildcard(get_spacetimedb_typescript_version())); } + remove_monorepo_only_scripts(&mut package); + let updated_content = serde_json::to_string_pretty(&package)?; fs::write(package_path, updated_content)?; @@ -2471,6 +2490,66 @@ mod tests { ); } + #[test] + fn test_update_package_json_removes_monorepo_only_scripts_from_every_template() { + let mut templates_with_monorepo_scripts = 0; + for (source, files) in embedded::get_template_files() { + let Some(original) = files.get("package.json") else { + continue; + }; + let original: serde_json::Value = serde_json::from_str(original).unwrap(); + let original_scripts = original["scripts"].as_object().cloned().unwrap_or_default(); + if original_scripts + .values() + .any(|command| command.as_str().unwrap_or("").contains("gen-bindings")) + { + templates_with_monorepo_scripts += 1; + } + + let temp = tempfile::TempDir::new().unwrap(); + let package_json = temp.path().join("package.json"); + std::fs::write(&package_json, serde_json::to_string(&original).unwrap()).unwrap(); + update_package_json(temp.path(), "my-app").unwrap(); + let updated: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&package_json).unwrap()).unwrap(); + let updated_scripts = updated["scripts"].as_object().cloned().unwrap_or_default(); + + for (name, command) in &original_scripts { + let command = command.as_str().unwrap_or(""); + if command.contains("gen-bindings") { + assert!( + !updated_scripts.contains_key(name), + "{source}: script `{name}` needs the SpacetimeDB repo but was kept" + ); + } else { + assert_eq!( + updated_scripts.get(name).and_then(|c| c.as_str()), + Some(command), + "{source}: script `{name}` should be kept unchanged" + ); + } + } + } + // Guard against the marker going stale: if no template uses it any + // more, this test no longer checks anything. + assert!( + templates_with_monorepo_scripts > 0, + "no embedded template has a gen-bindings script; update MONOREPO_ONLY_SCRIPT_MARKER" + ); + } + + #[test] + fn test_update_package_json_keeps_package_without_scripts() { + let temp = tempfile::TempDir::new().unwrap(); + let package_json = temp.path().join("package.json"); + std::fs::write(&package_json, r#"{ "name": "old-name" }"#).unwrap(); + + update_package_json(temp.path(), "new-name").unwrap(); + + let parsed: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(package_json).unwrap()).unwrap(); + assert_eq!(parsed, serde_json::json!({ "name": "new-name" })); + } + #[test] fn test_update_cargo_toml_rewrites_spacetimedb_deps_to_patch_wildcards() { let temp = tempfile::TempDir::new().unwrap(); diff --git a/crates/smoketests/src/lib.rs b/crates/smoketests/src/lib.rs index 2b9285dcab7..cb56a6513d3 100644 --- a/crates/smoketests/src/lib.rs +++ b/crates/smoketests/src/lib.rs @@ -410,8 +410,25 @@ pub fn pnpm(args: &[&str], cwd: &Path) -> Result { Ok(String::from_utf8_lossy(&output.stdout).to_string()) } -/// Builds the local TypeScript bindings package. +/// Set by the smoketest runner once it has built the TypeScript SDK, so that +/// tests skip rebuilding it. +pub const TYPESCRIPT_SDK_PREBUILT_ENV: &str = "SPACETIME_SMOKETEST_TS_SDK_PREBUILT"; + +/// Builds the local TypeScript bindings package, unless the runner has already +/// built it. +/// +/// Tests run in parallel and share one copy of the SDK. Rebuilding it clears +/// `dist/` while other tests may be copying it into their projects, so the +/// runner builds it once up front, and tests only build it when run directly. pub fn build_typescript_sdk() -> Result<()> { + if std::env::var_os(TYPESCRIPT_SDK_PREBUILT_ENV).is_some() { + return Ok(()); + } + prebuild_typescript_sdk() +} + +/// Builds the local TypeScript bindings package unconditionally. +pub fn prebuild_typescript_sdk() -> Result<()> { let workspace = workspace_root(); let ts_bindings = workspace.join("crates/bindings-typescript"); pnpm(&["--filter", "spacetimedb", "install"], &ts_bindings)?; diff --git a/crates/smoketests/tests/cluster/templates.rs b/crates/smoketests/tests/cluster/templates.rs index 8bc30631734..f2f9c8522d9 100644 --- a/crates/smoketests/tests/cluster/templates.rs +++ b/crates/smoketests/tests/cluster/templates.rs @@ -12,7 +12,7 @@ use anyhow::{bail, Context, Result}; use regex::Regex; use serde_json::Value; -use spacetimedb_smoketests::{pnpm, random_string, workspace_root, Smoketest}; +use spacetimedb_smoketests::{build_typescript_sdk, pnpm, random_string, workspace_root, Smoketest}; use std::env; use std::fs; use std::path::{Path, PathBuf}; @@ -590,22 +590,12 @@ fn pin_csharp_client_sdk_package_version(project_path: &Path) -> Result<()> { Ok(()) } -/// Builds the TypeScript SDK (`crates/bindings-typescript`). -/// -/// Should be called once before testing any TypeScript templates. -fn build_typescript_sdk() -> Result<()> { - let sdk_path = workspace_root().join("crates/bindings-typescript"); - eprintln!("[TEMPLATES] Building TypeScript SDK at {:?}", sdk_path); - run_pnpm(&["--filter", "spacetimedb", "install"], &sdk_path)?; - run_pnpm(&["build"], &sdk_path)?; - Ok(()) -} - /// Points the `spacetimedb` entry in `package.json` at the local TypeScript /// SDK and removes the template's lockfile so pnpm re-resolves dependencies. fn setup_typescript_sdk_in_package_json(package_json_path: &Path) -> Result<()> { let sdk_path = workspace_root().join("crates/bindings-typescript"); update_package_json_dependency(package_json_path, "spacetimedb", &sdk_path)?; + inject_package_json_dependency(package_json_path, "spacetimedb")?; // Remove the template's lockfile; the dependency changed. let lockfile = package_json_path.parent().unwrap().join("pnpm-lock.yaml"); @@ -615,6 +605,44 @@ fn setup_typescript_sdk_in_package_json(package_json_path: &Path) -> Result<()> Ok(()) } +/// Marks a local-path dependency as injected (`dependenciesMeta..injected`). +/// +/// By default pnpm symlinks a local directory dependency, so the SDK resolves +/// its own imports, including the type declarations of its optional framework +/// peers (vue, react, svelte, ...), from the monorepo's `node_modules` rather +/// than the project's. The project then sees two copies of, for example, Vue's +/// types, and Vue brands `Ref` with a `unique symbol`, so a `Ref` from one copy +/// isn't recognised by the other. Injecting copies the SDK into the project and +/// resolves its peers there, as installing the published package would. +fn inject_package_json_dependency(package_json_path: &Path, package_name: &str) -> Result<()> { + let content = + fs::read_to_string(package_json_path).with_context(|| format!("Failed to read {:?}", package_json_path))?; + let mut data: Value = + serde_json::from_str(&content).with_context(|| format!("Failed to parse {:?}", package_json_path))?; + + let has_dependency = data + .get("dependencies") + .is_some_and(|deps| deps.get(package_name).is_some()); + if !has_dependency { + return Ok(()); + } + let Some(package) = data.as_object_mut() else { + bail!("{:?} is not a JSON object", package_json_path); + }; + let meta = package + .entry("dependenciesMeta") + .or_insert_with(|| Value::Object(Default::default())); + let Some(meta) = meta.as_object_mut() else { + bail!("dependenciesMeta in {:?} is not a JSON object", package_json_path); + }; + meta.insert(package_name.to_string(), serde_json::json!({ "injected": true })); + + let new_content = + serde_json::to_string_pretty(&data).with_context(|| format!("Failed to serialize {:?}", package_json_path))?; + fs::write(package_json_path, new_content).with_context(|| format!("Failed to write {:?}", package_json_path))?; + Ok(()) +} + /// Rewires the Rust server module's `spacetimedb` dependency to the local /// `crates/bindings` path. /// @@ -815,7 +843,7 @@ fn test_rust_template(test: &Smoketest, template: &Template, project_path: &Path Ok(()) } -/// Publishes a TypeScript server module and verifies the TypeScript client type-checks. +/// Publishes a TypeScript server module and verifies the TypeScript client builds. fn test_typescript_template(test: &Smoketest, template: &Template, project_path: &Path) -> Result<()> { // Server let server_path = project_path.join("spacetimedb"); @@ -840,18 +868,56 @@ fn test_typescript_template(test: &Smoketest, template: &Template, project_path: })?; let _ = test.spacetime(&["delete", "--server", &test.server_url, "--yes", &domain]); - // Client type-check (only if there's a client package.json in the project root) + // Client build (only if there's a client package.json in the project root) let client_package_json = project_path.join("package.json"); if client_package_json.exists() { setup_typescript_sdk_in_package_json(&client_package_json)?; run_pnpm(&["install"], project_path)?; - // TODO: some templates don't pass tsc yet, re-enable once they're fixed. - // run_pnpm(&["exec", "tsc", "--noEmit"], project_path)?; + if let Some(reason) = typescript_client_build_known_failure(&template.id) { + eprintln!( + "[TEMPLATES] Skipping client build for {}: known failure: {reason}", + template.id + ); + } else { + // Each template's own `build` script, which type-checks where the + // framework's tooling does (tsc, vue-tsc, svelte-check, ...). + run_pnpm(&["run", "--if-present", "build"], project_path) + .with_context(|| format!("Client build failed for template {}", template.id))?; + } } Ok(()) } +/// TypeScript templates whose client `build` script currently fails, and why. +/// Remove an entry as soon as its template is fixed, so the build is checked again. +const TYPESCRIPT_CLIENT_BUILD_KNOWN_FAILURES: &[(&str, &str)] = &[( + "bun-ts", + "pnpm doesn't run the `bun` package's postinstall, so `bun build` can't start", +)]; + +fn typescript_client_build_known_failure(template_id: &str) -> Option<&'static str> { + TYPESCRIPT_CLIENT_BUILD_KNOWN_FAILURES + .iter() + .find(|(id, _)| *id == template_id) + .map(|(_, reason)| *reason) +} + +#[test] +fn test_typescript_client_build_known_failures_name_real_templates() { + let typescript_templates: Vec = get_templates() + .into_iter() + .filter(|template| template.server_lang.as_deref() == Some("typescript")) + .map(|template| template.id) + .collect(); + for (id, _) in TYPESCRIPT_CLIENT_BUILD_KNOWN_FAILURES { + assert!( + typescript_templates.iter().any(|template| template == id), + "known-failure entry {id} is not a TypeScript template; remove it" + ); + } +} + /// Publishes a C# server module and verifies the C# client builds. fn test_csharp_template(test: &Smoketest, template: &Template) -> Result<()> { for dotnet_version in ["8", "10"] { diff --git a/docs/docs/00100-intro/00200-quickstarts/00160-svelte.md b/docs/docs/00100-intro/00200-quickstarts/00160-svelte.md index 80f19aebb26..b3e179082ae 100644 --- a/docs/docs/00100-intro/00200-quickstarts/00160-svelte.md +++ b/docs/docs/00100-intro/00200-quickstarts/00160-svelte.md @@ -46,17 +46,19 @@ spacetime dev --template svelte-ts Your project contains both server and client code. - Edit `spacetimedb/src/index.ts` to add tables and reducers. Edit `src/App.svelte` to build your UI. + Edit `spacetimedb/src/index.ts` to add tables and reducers. Edit `src/App.svelte` to build your UI. The connection to SpacetimeDB is configured in `src/Root.svelte`. ``` my-spacetime-app/ -├── spacetimedb/ # Your SpacetimeDB module +├── spacetimedb/ # Your SpacetimeDB module │ └── src/ -│ └── index.ts # Server-side logic -├── src/ # Svelte frontend -│ ├── App.svelte -│ └── module_bindings/ # Auto-generated types +│ └── index.ts # Server-side logic +├── src/ # Svelte frontend +│ ├── main.ts # Mounts Root.svelte +│ ├── Root.svelte # Connects to SpacetimeDB +│ ├── App.svelte # Your UI +│ └── module_bindings/ # Auto-generated types └── package.json ``` @@ -99,6 +101,30 @@ export const sayHello = spacetimedb.reducer(ctx => { + + + `src/Root.svelte` calls `createSpacetimeDBProvider`, which shares the connection with every component below it. It has to run inside a component, because it uses Svelte context, so it can't move to `main.ts`. + + `src/App.svelte` then reads that connection with the hooks from `spacetimedb/svelte`. `useSpacetimeDB` and `useTable` return Svelte stores, so read them with a `$` prefix. `useTable` subscribes to the table and keeps its rows up to date. `useReducer` returns a function that calls the reducer. + + +```svelte + + +

{$conn.isActive ? 'Connected' : 'Disconnected'}

+

{$people.length} people

+ +``` +
+
+ Open a new terminal and navigate to your project directory. Then use the SpacetimeDB CLI to call reducers and query your data directly. @@ -130,4 +156,5 @@ spacetime logs ## Next steps -- Read the [TypeScript SDK Reference](../../00200-core-concepts/00600-clients/00700-typescript-reference.md) for detailed API docs +- Read the [Svelte section of the TypeScript SDK Reference](../../00200-core-concepts/00600-clients/00700-typescript-reference.md#svelte) for the full Svelte API +- Work through the [Chat App Tutorial](../00300-tutorials/00100-chat-app.md) to build a bigger module. Its client is written in React, but the module and the SDK calls carry over to Svelte. diff --git a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md index ecc993e4eed..b03333a2091 100644 --- a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md +++ b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md @@ -1495,10 +1495,53 @@ const [onlineUsers] = useTable( ### Svelte ```typescript -import { SpacetimeDBProvider, useSpacetimeDB, useTable, useReducer } from 'spacetimedb/svelte'; +import { createSpacetimeDBProvider, useSpacetimeDB, useTable, useReducer, useProcedure } from 'spacetimedb/svelte'; ``` -The Svelte integration provides the same hooks as React. `useTable` returns `[Readable, Readable]` using Svelte stores: +The Svelte integration provides the same hooks as React, built on Svelte stores. Read them with the `$` prefix in markup and ` + + +``` + +#### `useSpacetimeDB()` + +Returns a readable store of the current connection state. Besides `getConnection()`, the state includes `reconnect(builder)`, which tears down the connection and reconnects with a new builder, for example to apply a new token after sign-in. Table hooks re-subscribe automatically. + +```svelte + + +

{$conn.isActive ? 'Connected' : 'Disconnected'}

+``` + +#### `useTable(query, callbacks?)` + +Returns `[Readable, Readable]`. It accepts the same queries and `onInsert`, `onDelete` and `onUpdate` callbacks as React. The query is read once when the component initializes, so to change it, re-create the component (for example with `{#key}`): ```svelte {#if $isReady} - {#each $users as user} + {#each $users as user (user.identity.toHexString())}
{user.name}
{/each} {/if} ``` + +#### `useReducer(reducer)` and `useProcedure(procedure)` + +Return functions that call a reducer or procedure. Calls made before the connection is ready are queued and sent once connected: + +```svelte + + + +``` diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a724ddce8e2..2b98d82a7fc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -145,7 +145,7 @@ importers: version: 8.40.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) '@vitest/coverage-v8': specifier: ^3.2.6 - version: 3.2.7(vitest@3.2.7(@types/debug@4.1.13)(@types/node@24.3.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1)) + version: 3.2.7(vitest@3.2.7(@types/debug@4.1.13)(@types/node@22.18.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1)) brotli-size-cli: specifier: ^1.0.0 version: 1.0.0 @@ -175,7 +175,7 @@ importers: version: 5.43.1 ts-node: specifier: ^10.9.2 - version: 10.9.2(@types/node@24.3.0)(typescript@5.9.3) + version: 10.9.2(@types/node@22.18.0)(typescript@5.9.3) tsup: specifier: ^8.1.0 version: 8.5.1(jiti@2.7.0)(postcss@8.5.33)(tsx@4.23.15)(typescript@5.9.3)(yaml@2.9.1) @@ -187,10 +187,10 @@ importers: version: 8.40.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) vite: specifier: ^7.3.8 - version: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) + version: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) vitest: specifier: ^3.2.7 - version: 3.2.7(@types/debug@4.1.13)(@types/node@24.3.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) + version: 3.2.7(@types/debug@4.1.13)(@types/node@22.18.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) crates/bindings-typescript/case-conversion-test-client: dependencies: @@ -1787,20 +1787,20 @@ importers: version: link:../../crates/bindings-typescript devDependencies: '@sveltejs/vite-plugin-svelte': - specifier: ^5.1.1 - version: 5.1.1(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) + specifier: ^6.2.4 + version: 6.2.4(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) svelte: - specifier: ^5.0.0 + specifier: ^5.46.4 version: 5.59.1(@typescript-eslint/types@8.50.0) svelte-check: - specifier: ^4.0.0 + specifier: ^4.7.8 version: 4.7.8(picomatch@4.0.7)(svelte@5.59.1(@typescript-eslint/types@8.50.0))(typescript@5.6.3) typescript: specifier: ~5.6.2 version: 5.6.3 vite: - specifier: ^6.4.6 - version: 6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) + specifier: ^7.3.8 + version: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) templates/tanstack-ts: dependencies: @@ -7112,20 +7112,20 @@ packages: resolution: {integrity: sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==} engines: {node: '>= 18.0.0'} - '@sveltejs/vite-plugin-svelte-inspector@4.0.1': - resolution: {integrity: sha512-J/Nmb2Q2y7mck2hyCX4ckVHcR5tu2J+MtBEQqpDrrgELZ2uvraQcK/ioCV61AqkdXFgriksOKIceDcQmqnGhVw==} - engines: {node: ^18.0.0 || ^20.0.0 || >=22} + '@sveltejs/vite-plugin-svelte-inspector@5.0.2': + resolution: {integrity: sha512-TZzRTcEtZffICSAoZGkPSl6Etsj2torOVrx6Uw0KpXxrec9Gg6jFWQ60Q3+LmNGfZSxHRCZL7vXVZIWmuV50Ig==} + engines: {node: ^20.19 || ^22.12 || >=24} peerDependencies: - '@sveltejs/vite-plugin-svelte': ^5.0.0 + '@sveltejs/vite-plugin-svelte': ^6.0.0-next.0 svelte: ^5.0.0 - vite: ^6.0.0 + vite: ^6.3.0 || ^7.0.0 - '@sveltejs/vite-plugin-svelte@5.1.1': - resolution: {integrity: sha512-Y1Cs7hhTc+a5E9Va/xwKlAJoariQyHY+5zBgCZg4PFWNYQ1nMN9sjK1zhw1gK69DuqVP++sht/1GZg1aRwmAXQ==} - engines: {node: ^18.0.0 || ^20.0.0 || >=22} + '@sveltejs/vite-plugin-svelte@6.2.4': + resolution: {integrity: sha512-ou/d51QSdTyN26D7h6dSpusAKaZkAiGM55/AKYi+9AGZw7q85hElbjK3kEyzXHhLSnRISHOYzVge6x0jRZ7DXA==} + engines: {node: ^20.19 || ^22.12 || >=24} peerDependencies: svelte: ^5.0.0 - vite: ^6.0.0 + vite: ^6.3.0 || ^7.0.0 '@svgr/babel-plugin-add-jsx-attribute@8.0.0': resolution: {integrity: sha512-b9MIk7yhdS1pMCZM8VeNfUlSKVRhsHZNMl5O9SfaX0l0t5wjdgu4IDzGB8bpnGBBOjGST3rRFVsaaEtI4W6f7g==} @@ -22264,27 +22264,22 @@ snapshots: '@sveltejs/load-config@0.2.3': {} - '@sveltejs/vite-plugin-svelte-inspector@4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)))(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1))': + '@sveltejs/vite-plugin-svelte-inspector@5.0.2(@sveltejs/vite-plugin-svelte@6.2.4(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)))(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1))': dependencies: - '@sveltejs/vite-plugin-svelte': 5.1.1(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) - debug: 4.4.3 + '@sveltejs/vite-plugin-svelte': 6.2.4(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) + obug: 2.2.1 svelte: 5.59.1(@typescript-eslint/types@8.50.0) - vite: 6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) - transitivePeerDependencies: - - supports-color + vite: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) - '@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1))': + '@sveltejs/vite-plugin-svelte@6.2.4(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1))': dependencies: - '@sveltejs/vite-plugin-svelte-inspector': 4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)))(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) - debug: 4.4.3 + '@sveltejs/vite-plugin-svelte-inspector': 5.0.2(@sveltejs/vite-plugin-svelte@6.2.4(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)))(svelte@5.59.1(@typescript-eslint/types@8.50.0))(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) deepmerge: 4.3.1 - kleur: 4.1.5 magic-string: 0.30.21 + obug: 2.2.1 svelte: 5.59.1(@typescript-eslint/types@8.50.0) - vite: 6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) - vitefu: 1.1.4(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) - transitivePeerDependencies: - - supports-color + vite: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) + vitefu: 1.1.4(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) '@svgr/babel-plugin-add-jsx-attribute@8.0.0(@babel/core@7.29.13)': dependencies: @@ -23010,6 +23005,7 @@ snapshots: '@types/node@24.3.0': dependencies: undici-types: 7.10.0 + optional: true '@types/object-inspect@1.13.0': {} @@ -23429,7 +23425,7 @@ snapshots: vite: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) vue: 3.5.46(typescript@5.6.3) - '@vitest/coverage-v8@3.2.7(vitest@3.2.7(@types/debug@4.1.13)(@types/node@24.3.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1))': + '@vitest/coverage-v8@3.2.7(vitest@3.2.7(@types/debug@4.1.13)(@types/node@22.18.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@ampproject/remapping': 2.3.0 '@bcoe/v8-coverage': 1.0.2 @@ -23444,7 +23440,7 @@ snapshots: std-env: 3.10.0 test-exclude: 7.0.2 tinyrainbow: 2.0.0 - vitest: 3.2.7(@types/debug@4.1.13)(@types/node@24.3.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) + vitest: 3.2.7(@types/debug@4.1.13)(@types/node@22.18.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) transitivePeerDependencies: - supports-color @@ -23472,21 +23468,21 @@ snapshots: optionalDependencies: vite: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) - '@vitest/mocker@3.2.7(vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1))': + '@vitest/mocker@3.2.7(vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@vitest/spy': 3.2.7 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) + vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) - '@vitest/mocker@3.2.7(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1))': + '@vitest/mocker@3.2.7(vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@vitest/spy': 3.2.7 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) + vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) '@vitest/mocker@3.2.7(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1))': dependencies: @@ -31809,26 +31805,25 @@ snapshots: ts-interface-checker@0.1.13: {} - ts-node@10.9.2(@types/node@24.3.0)(typescript@5.6.3): + ts-node@10.9.2(@types/node@22.18.0)(typescript@5.9.3): dependencies: '@cspotcode/source-map-support': 0.8.1 '@tsconfig/node10': 1.0.11 '@tsconfig/node12': 1.0.11 '@tsconfig/node14': 1.0.3 '@tsconfig/node16': 1.0.4 - '@types/node': 24.3.0 + '@types/node': 22.18.0 acorn: 8.19.0 acorn-walk: 8.3.4 arg: 4.1.3 create-require: 1.1.1 diff: 4.0.4 make-error: 1.3.6 - typescript: 5.6.3 + typescript: 5.9.3 v8-compile-cache-lib: 3.0.1 yn: 3.1.1 - optional: true - ts-node@10.9.2(@types/node@24.3.0)(typescript@5.9.3): + ts-node@10.9.2(@types/node@24.3.0)(typescript@5.6.3): dependencies: '@cspotcode/source-map-support': 0.8.1 '@tsconfig/node10': 1.0.11 @@ -31842,9 +31837,10 @@ snapshots: create-require: 1.1.1 diff: 4.0.4 make-error: 1.3.6 - typescript: 5.9.3 + typescript: 5.6.3 v8-compile-cache-lib: 3.0.1 yn: 3.1.1 + optional: true tsconfck@3.1.6(typescript@5.9.3): optionalDependencies: @@ -32503,13 +32499,13 @@ snapshots: - tsx - yaml - vite-node@3.2.4(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1): + vite-node@3.2.4(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1): dependencies: cac: 6.7.14 debug: 4.4.3 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) + vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) transitivePeerDependencies: - '@types/node' - jiti @@ -32524,13 +32520,13 @@ snapshots: - tsx - yaml - vite-node@3.2.4(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1): + vite-node@3.2.4(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1): dependencies: cac: 6.7.14 debug: 4.4.3 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) + vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) transitivePeerDependencies: - '@types/node' - jiti @@ -32686,7 +32682,7 @@ snapshots: tsx: 4.23.15 yaml: 2.9.1 - vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1): + vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1): dependencies: esbuild: 0.28.2 fdir: 6.5.0(picomatch@4.0.7) @@ -32700,11 +32696,11 @@ snapshots: jiti: 2.7.0 lightningcss: 1.33.0 sass: 1.97.3 - terser: 5.51.4 + terser: 5.43.1 tsx: 4.23.15 yaml: 2.9.1 - vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1): + vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1): dependencies: esbuild: 0.28.2 fdir: 6.5.0(picomatch@4.0.7) @@ -32713,12 +32709,12 @@ snapshots: rollup: 4.68.8 tinyglobby: 0.2.17 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 22.18.0 fsevents: 2.3.3 jiti: 2.7.0 lightningcss: 1.33.0 sass: 1.97.3 - terser: 5.43.1 + terser: 5.51.4 tsx: 4.23.15 yaml: 2.9.1 @@ -32774,10 +32770,6 @@ snapshots: tsx: 4.23.15 yaml: 2.9.1 - vitefu@1.1.4(vite@6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)): - optionalDependencies: - vite: 6.4.6(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) - vitefu@1.1.4(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)): optionalDependencies: vite: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) @@ -32829,11 +32821,11 @@ snapshots: - tsx - yaml - vitest@3.2.7(@types/debug@4.1.13)(@types/node@22.18.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1): + vitest@3.2.7(@types/debug@4.1.13)(@types/node@22.18.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1): dependencies: '@types/chai': 5.2.3 '@vitest/expect': 3.2.7 - '@vitest/mocker': 3.2.7(vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) + '@vitest/mocker': 3.2.7(vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1)) '@vitest/pretty-format': 3.2.7 '@vitest/runner': 3.2.7 '@vitest/snapshot': 3.2.7 @@ -32851,8 +32843,8 @@ snapshots: tinyglobby: 0.2.17 tinypool: 2.2.0 tinyrainbow: 2.0.0 - vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) - vite-node: 3.2.4(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) + vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) + vite-node: 3.2.4(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.13 @@ -32872,11 +32864,11 @@ snapshots: - tsx - yaml - vitest@3.2.7(@types/debug@4.1.13)(@types/node@24.3.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1): + vitest@3.2.7(@types/debug@4.1.13)(@types/node@22.18.0)(jiti@2.7.0)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1): dependencies: '@types/chai': 5.2.3 '@vitest/expect': 3.2.7 - '@vitest/mocker': 3.2.7(vite@7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1)) + '@vitest/mocker': 3.2.7(vite@7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1)) '@vitest/pretty-format': 3.2.7 '@vitest/runner': 3.2.7 '@vitest/snapshot': 3.2.7 @@ -32894,12 +32886,12 @@ snapshots: tinyglobby: 0.2.17 tinypool: 2.2.0 tinyrainbow: 2.0.0 - vite: 7.3.8(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) - vite-node: 3.2.4(@types/node@24.3.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.15)(yaml@2.9.1) + vite: 7.3.8(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) + vite-node: 3.2.4(@types/node@22.18.0)(jiti@2.7.0)(lightningcss@1.33.0)(sass@1.97.3)(terser@5.51.4)(tsx@4.23.15)(yaml@2.9.1) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.13 - '@types/node': 24.3.0 + '@types/node': 22.18.0 jsdom: 26.1.0 transitivePeerDependencies: - jiti diff --git a/templates/svelte-ts/.gitignore b/templates/svelte-ts/.gitignore index ab8ad35a188..63a103aa772 100644 --- a/templates/svelte-ts/.gitignore +++ b/templates/svelte-ts/.gitignore @@ -1,6 +1,5 @@ node_modules dist -.svelte-kit *.log .DS_Store diff --git a/templates/svelte-ts/README.md b/templates/svelte-ts/README.md index 2833e9dd72a..c6770436591 100644 --- a/templates/svelte-ts/README.md +++ b/templates/svelte-ts/README.md @@ -33,16 +33,18 @@ The template includes a basic Svelte app connected to SpacetimeDB. Your project contains both server and client code. -Edit `spacetimedb/src/index.ts` to add tables and reducers. Edit `src/App.svelte` to build your UI. +Edit `spacetimedb/src/index.ts` to add tables and reducers. Edit `src/App.svelte` to build your UI. The connection to SpacetimeDB is configured in `src/Root.svelte`. ``` my-spacetime-app/ -├── spacetimedb/ # Your SpacetimeDB module +├── spacetimedb/ # Your SpacetimeDB module │ └── src/ -│ └── index.ts # Server-side logic -├── src/ # Svelte frontend -│ ├── App.svelte -│ └── module_bindings/ # Auto-generated types +│ └── index.ts # Server-side logic +├── src/ # Svelte frontend +│ ├── main.ts # Mounts Root.svelte +│ ├── Root.svelte # Connects to SpacetimeDB +│ ├── App.svelte # Your UI +│ └── module_bindings/ # Auto-generated types └── package.json ``` @@ -84,6 +86,29 @@ export const sayHello = spacetimedb.reducer(ctx => { +## Use your data in Svelte + +`src/Root.svelte` calls `createSpacetimeDBProvider`, which shares the connection with every component below it. It has to run inside a component, because it uses Svelte context, so it can't move to `main.ts`. + +`src/App.svelte` then reads that connection with the hooks from `spacetimedb/svelte`. `useSpacetimeDB` and `useTable` return Svelte stores, so read them with a `$` prefix. `useTable` subscribes to the table and keeps its rows up to date. `useReducer` returns a function that calls the reducer. + +```svelte + + +

{$conn.isActive ? 'Connected' : 'Disconnected'}

+

{$people.length} people

+ +``` + + + ## Test with the CLI Open a new terminal and navigate to your project directory. Then use the SpacetimeDB CLI to call reducers and query your data directly. @@ -111,4 +136,5 @@ spacetime logs ## Next steps -- Read the [TypeScript SDK Reference](https://spacetimedb.com/docs/clients/typescript) for detailed API docs +- Read the [Svelte section of the TypeScript SDK Reference](https://spacetimedb.com/docs/clients/typescript#svelte) for the full Svelte API +- Work through the [Chat App Tutorial](https://spacetimedb.com/docs/tutorials/chat-app) to build a bigger module. Its client is written in React, but the module and the SDK calls carry over to Svelte. diff --git a/templates/svelte-ts/package.json b/templates/svelte-ts/package.json index dff1b7bc8ef..ef1229ae685 100644 --- a/templates/svelte-ts/package.json +++ b/templates/svelte-ts/package.json @@ -5,7 +5,8 @@ "type": "module", "scripts": { "dev": "vite", - "build": "vite build", + "build": "svelte-check --tsconfig ./tsconfig.json && vite build", + "check": "svelte-check --tsconfig ./tsconfig.json", "preview": "vite preview", "generate": "pnpm --dir spacetimedb install && cargo run -p gen-bindings -- --out-dir src/module_bindings --module-path spacetimedb && prettier --write src/module_bindings", "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings --module-path spacetimedb", @@ -16,11 +17,11 @@ "spacetimedb": "workspace:*" }, "devDependencies": { - "@sveltejs/vite-plugin-svelte": "^5.1.1", - "svelte": "^5.0.0", - "svelte-check": "^4.0.0", + "@sveltejs/vite-plugin-svelte": "^6.2.4", + "svelte": "^5.46.4", + "svelte-check": "^4.7.8", "typescript": "~5.6.2", - "vite": "^6.4.6" + "vite": "^7.3.8" }, "engines": { "node": "^22.23.4 || ^24.22.1 || >=26.12.1" diff --git a/templates/svelte-ts/src/App.svelte b/templates/svelte-ts/src/App.svelte index 9e3f0d37e2c..4dc80191f2c 100644 --- a/templates/svelte-ts/src/App.svelte +++ b/templates/svelte-ts/src/App.svelte @@ -5,19 +5,30 @@ import { tables, reducers } from './module_bindings'; const conn = useSpacetimeDB(); // Subscribe to all people in the database -const [people] = useTable(tables.person); +const [people, peopleReady] = useTable(tables.person); + +// Until the subscription's first results arrive, an empty list means +// "not loaded yet", not "no people". +const loading = $derived(!$peopleReady && $people.length === 0); const addReducer = useReducer(reducers.add); let name = $state(''); +let error = $state(null); -function addPerson(e: SubmitEvent) { +async function addPerson(e: SubmitEvent) { e.preventDefault(); if (!name.trim() || !$conn.isActive) return; - // Call the add reducer - addReducer({ name: name }); + const newName = name; name = ''; + error = null; + try { + // Call the add reducer. It rejects if the reducer fails on the server. + await addReducer({ name: newName }); + } catch (err) { + error = `Couldn't add ${newName}: ${err instanceof Error ? err.message : err}`; + } } @@ -48,13 +59,21 @@ function addPerson(e: SubmitEvent) { + {#if error} +

{error}

+ {/if} +
-

People ({$people.length})

- {#if $people.length === 0} +

People{loading ? '' : ` (${$people.length})`}

+ {#if loading} +

Loading…

+ {:else if $people.length === 0}

No people yet. Add someone above!

{:else}
    - {#each $people as person} + + {#each $people as person (person)}
  • {person.name}
  • {/each}
diff --git a/templates/svelte-ts/src/Root.svelte b/templates/svelte-ts/src/Root.svelte index 65cfbf6bcb3..afea6ef02d2 100644 --- a/templates/svelte-ts/src/Root.svelte +++ b/templates/svelte-ts/src/Root.svelte @@ -32,6 +32,8 @@ const connectionBuilder = DbConnection.builder() .onDisconnect(onDisconnect) .onConnectError(onConnectError); +// Shares the connection with every component below this one. It uses Svelte +// context, so it has to be called in a component, not in main.ts. createSpacetimeDBProvider(connectionBuilder); diff --git a/templates/svelte-ts/svelte.config.js b/templates/svelte-ts/svelte.config.js index 4c6b24b1073..43b3b42313e 100644 --- a/templates/svelte-ts/svelte.config.js +++ b/templates/svelte-ts/svelte.config.js @@ -1,5 +1,12 @@ -import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; - +/** @type {import("@sveltejs/vite-plugin-svelte").SvelteConfig} */ export default { - preprocess: vitePreprocess(), + vitePlugin: { + // Compile this app's components in runes mode, so a component can't + // silently fall back to legacy mode. Components from dependencies keep + // whichever mode they were written in. + dynamicCompileOptions: ({ filename }) => + filename.split(/[/\\]/).includes('node_modules') + ? undefined + : { runes: true }, + }, }; diff --git a/templates/svelte-ts/tsconfig.json b/templates/svelte-ts/tsconfig.json index 6406a7d1573..859fbbd2730 100644 --- a/templates/svelte-ts/tsconfig.json +++ b/templates/svelte-ts/tsconfig.json @@ -3,13 +3,14 @@ "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], - "types": ["vite/client"], + "types": ["svelte", "vite/client"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "isolatedModules": true, + "verbatimModuleSyntax": true, "moduleDetection": "force", "noEmit": true, diff --git a/tools/ci/commands/smoketests/Cargo.toml b/tools/ci/commands/smoketests/Cargo.toml index f161fe64586..7f0b5c2d1a2 100644 --- a/tools/ci/commands/smoketests/Cargo.toml +++ b/tools/ci/commands/smoketests/Cargo.toml @@ -9,4 +9,5 @@ duct.workspace = true clap.workspace = true tempfile.workspace = true spacetimedb-guard.workspace = true +which = "8.0.0" ci-common = { path = "../../common" } diff --git a/tools/ci/commands/smoketests/src/main.rs b/tools/ci/commands/smoketests/src/main.rs index 869a75532d2..a6f42e9e5dd 100644 --- a/tools/ci/commands/smoketests/src/main.rs +++ b/tools/ci/commands/smoketests/src/main.rs @@ -193,6 +193,37 @@ fn build_precompiled_modules() -> Result<()> { Ok(()) } +/// Tells test processes the TypeScript SDK is already built. Must match +/// `spacetimedb_smoketests::TYPESCRIPT_SDK_PREBUILT_ENV`. +const TYPESCRIPT_SDK_PREBUILT_ENV: &str = "SPACETIME_SMOKETEST_TS_SDK_PREBUILT"; + +/// Builds the TypeScript SDK (`crates/bindings-typescript`) that the TypeScript +/// smoketests install into their projects. +/// +/// Tests run in parallel and share this one copy of the SDK. If each test built +/// it, one test's build would clear `dist/` while another was copying it into +/// its project. Returns whether the SDK was built; without pnpm the TypeScript +/// tests skip themselves, so there is nothing to build. +fn build_typescript_sdk(workspace_root: &Path) -> Result { + let Ok(pnpm) = which::which("pnpm") else { + eprintln!("Skipping TypeScript SDK build (pnpm not found).\n"); + return Ok(false); + }; + let sdk_dir = workspace_root.join("crates/bindings-typescript"); + + eprintln!("Building TypeScript SDK..."); + for args in [&["--filter", "spacetimedb", "install"][..], &["build"]] { + let status = Command::new(&pnpm).args(args).current_dir(&sdk_dir).status()?; + ensure!( + status.success(), + "Failed to build TypeScript SDK: pnpm {}", + args.join(" ") + ); + } + eprintln!("TypeScript SDK built.\n"); + Ok(true) +} + fn archive_smoketests(archive_file: &Path, suite: SmoketestSuite) -> Result<()> { build_precompiled_modules()?; @@ -220,9 +251,10 @@ fn run_smoketest_archive(archive_file: &Path, args: Vec) -> Result<()> { let cli_path = ensure_binaries_built(); let base_config_dir = prepare_base_config(&cli_path, None, None)?; let base_config_path = base_config_dir.path().join("config.toml"); + let typescript_sdk_prebuilt = build_typescript_sdk(&workspace_root)?; let mut cmd = Command::new("cargo"); - set_env(&mut cmd, None, true, false, &base_config_path); + set_env(&mut cmd, None, true, false, &base_config_path, typescript_sdk_prebuilt); cmd.args(["nextest", "run", "--archive-file"]) .arg(archive_file) .args(["--workspace-remap"]) @@ -266,6 +298,9 @@ fn run_smoketest( // 2. Build pre-compiled modules (this also warms the WASM dependency cache) build_precompiled_modules()?; + // 3. Build the TypeScript SDK once, rather than in every test that uses it + let typescript_sdk_prebuilt = build_typescript_sdk(&env::current_dir()?)?; + let cli_path = ensure_binaries_built(); let base_config_dir = prepare_base_config(&cli_path, server.as_deref(), auth_host)?; let base_config_path = base_config_dir.path().join("config.toml"); @@ -287,7 +322,14 @@ fn run_smoketest( let mut cmd = if use_nextest { eprintln!("Running smoketests with cargo nextest...\n"); let mut cmd = Command::new("cargo"); - set_env(&mut cmd, server, dotnet, auth_host.is_some(), &base_config_path); + set_env( + &mut cmd, + server, + dotnet, + auth_host.is_some(), + &base_config_path, + typescript_sdk_prebuilt, + ); cmd.args(["nextest", "run", "--release", "-p", "spacetimedb-smoketests"]) .args(suite.cargo_args()) .arg("--no-fail-fast"); @@ -304,7 +346,14 @@ fn run_smoketest( } else { eprintln!("Running smoketests with cargo test...\n"); let mut cmd = Command::new("cargo"); - set_env(&mut cmd, server, dotnet, auth_host.is_some(), &base_config_path); + set_env( + &mut cmd, + server, + dotnet, + auth_host.is_some(), + &base_config_path, + typescript_sdk_prebuilt, + ); cmd.args(["test", "--release", "-p", "spacetimedb-smoketests"]) .args(suite.cargo_args()); cmd @@ -385,7 +434,17 @@ fn prepare_base_config(cli_path: &Path, server: Option<&str>, auth_host: Option< Ok(temp_dir) } -fn set_env(cmd: &mut Command, server: Option, dotnet: bool, auth_host: bool, base_config_path: &Path) { +fn set_env( + cmd: &mut Command, + server: Option, + dotnet: bool, + auth_host: bool, + base_config_path: &Path, + typescript_sdk_prebuilt: bool, +) { + if typescript_sdk_prebuilt { + cmd.env(TYPESCRIPT_SDK_PREBUILT_ENV, "1"); + } if let Some(ref server_url) = server { cmd.env("SPACETIME_REMOTE_SERVER", server_url); }