@blujosi/rivetkit-svelte 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,342 @@
1
+ # RivetKit Svelte
2
+
3
+ A Svelte 5 integration for [RivetKit](https://rivetkit.com) that provides reactive actor connections using Svelte's new runes system.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ pnpm add @rivetkit/svelte
9
+
10
+ # or
11
+
12
+ npm i @rivetkit/svelte
13
+ ```
14
+
15
+ ## Overview
16
+
17
+ RivetKit Svelte provides seamless integration between RivetKit's actor system and Svelte 5's reactive runes. It allows you to connect to RivetKit actors from your Svelte components with automatic reactivity, real-time event handling, and type safety.
18
+
19
+ ## Features
20
+
21
+ - **Svelte 5 Runes Integration** - Built specifically for Svelte 5's new reactivity system
22
+ - **Real-time Actor Connections** - Connect to RivetKit actors with automatic state synchronization
23
+ - **Event Handling** - Listen to actor events with automatic cleanup
24
+ - **Type Safety** - Full TypeScript support with proper type inference
25
+ - **SSR Compatible** - Works with SvelteKit's server-side rendering
26
+ - **Automatic Reconnection** - Handles connection states and errors gracefully
27
+
28
+ ## Quick Start
29
+
30
+ ### Step 1: Set Up Your RivetKit Backend
31
+
32
+ First, create your RivetKit actors and registry. Here's a simple counter example:
33
+
34
+ ```typescript
35
+ // backend/registry.ts
36
+ import { actor, setup } from "@rivetkit/actor";
37
+
38
+ export const counter = actor({
39
+ onAuth: () => {
40
+ // Configure auth here if needed
41
+ },
42
+ state: { count: 0 },
43
+ actions: {
44
+ increment: (c, x: number) => {
45
+ console.log("incrementing by", x);
46
+ c.state.count += x;
47
+ c.broadcast("newCount", c.state.count);
48
+ return c.state.count;
49
+ },
50
+ reset: (c) => {
51
+ c.state.count = 0;
52
+ c.broadcast("newCount", c.state.count);
53
+ return c.state.count;
54
+ },
55
+ },
56
+ });
57
+
58
+ export const registry = setup({
59
+ use: { counter },
60
+ });
61
+ ```
62
+
63
+ ### Step 2: Start Your RivetKit Server
64
+
65
+ ```typescript
66
+ // backend/index.ts
67
+ import { registry } from "./registry";
68
+
69
+ export type Registry = typeof registry;
70
+
71
+ registry.runServer({
72
+ cors: {
73
+ origin: "http://localhost:5173", // Your Svelte app URL
74
+ },
75
+ });
76
+ ```
77
+
78
+ ### Step 3: Create the Client Connection
79
+
80
+ In your Svelte app, create a client connection to your RivetKit server:
81
+
82
+ ```typescript
83
+ // src/lib/actor-client.ts
84
+ import { createClient, createRivetKit } from "@rivetkit/svelte";
85
+ import type { Registry } from "../../backend";
86
+
87
+ const client = createClient<Registry>(`http://localhost:8080`);
88
+ export const { useActor } = createRivetKit(client);
89
+ ```
90
+
91
+ ### Step 4: Use Actors in Your Svelte Components
92
+
93
+ Now you can use the `useActor` function in your Svelte 5 components:
94
+
95
+ ```svelte
96
+ <!-- src/routes/+page.svelte -->
97
+ <script lang="ts">
98
+ import { useActor } from "../lib/actor-client";
99
+
100
+ let count = $state(0);
101
+ const counter = useActor({ name: 'counter', key: ['test-counter'] });
102
+
103
+ $effect(() => {
104
+ console.log('status', counter?.isConnected);
105
+ counter?.useEvent('newCount', (x: number) => {
106
+ console.log('new count event', x);
107
+ count = x;
108
+ });
109
+ });
110
+
111
+ const increment = () => {
112
+ counter?.connection?.increment(1);
113
+ };
114
+
115
+ const reset = () => {
116
+ counter?.connection?.reset();
117
+ };
118
+
119
+ // Debug the connection status
120
+ $inspect('useActor is connected', counter?.isConnected);
121
+ </script>
122
+
123
+ <div>
124
+ <h1>Counter: {count}</h1>
125
+ <button onclick={increment}>Increment</button>
126
+ <button onclick={reset}>Reset</button>
127
+ </div>
128
+ ```
129
+
130
+ ## Core Concepts
131
+
132
+ ### useActor Hook
133
+
134
+ The `useActor` function is the main way to connect to RivetKit actors from your Svelte components. It returns a reactive object with the following properties:
135
+
136
+ - **`connection`** - The actor connection object for calling actions
137
+ - **`handle`** - The actor handle for advanced operations
138
+ - **`isConnected`** - Boolean indicating if the actor is connected
139
+ - **`isConnecting`** - Boolean indicating if the actor is currently connecting
140
+ - **`isError`** - Boolean indicating if there's an error
141
+ - **`error`** - The error object if one exists
142
+ - **`useEvent`** - Function to listen for actor events
143
+
144
+ ### Actor Options
145
+
146
+ When calling `useActor`, you need to provide:
147
+
148
+ ```typescript
149
+ const actor = useActor({
150
+ name: 'counter', // The actor name from your registry
151
+ key: ['test-counter'], // Unique key for this actor instance
152
+ params: { /* ... */ }, // Optional parameters
153
+ enabled: true // Optional, defaults to true
154
+ });
155
+ ```
156
+
157
+ ## Event Handling
158
+
159
+ ### Using useEvent
160
+
161
+ The `useEvent` function allows you to listen for events broadcast by actors:
162
+
163
+ ```svelte
164
+ <script lang="ts">
165
+ import { useActor } from "../lib/actor-client";
166
+
167
+ const chatActor = useActor({ name: 'chat', key: ['room-1'] });
168
+
169
+ $effect(() => {
170
+ // Listen for new messages
171
+ chatActor?.useEvent('newMessage', (message) => {
172
+ console.log('New message:', message);
173
+ // Update your component state
174
+ });
175
+
176
+ // Listen for user joined events
177
+ chatActor?.useEvent('userJoined', (user) => {
178
+ console.log('User joined:', user);
179
+ });
180
+ });
181
+ </script>
182
+ ```
183
+
184
+ ### Alternative Event Listening
185
+
186
+ You can also listen to events directly on the connection:
187
+
188
+ ```svelte
189
+ <script lang="ts">
190
+ const actor = useActor({ name: 'counter', key: ['test'] });
191
+
192
+ $effect(() => {
193
+ const unsubscribe = actor.connection?.on('newCount', (count) => {
194
+ console.log('Count updated:', count);
195
+ });
196
+
197
+ // Cleanup is handled automatically by $effect
198
+ return unsubscribe;
199
+ });
200
+ </script>
201
+ ```
202
+
203
+ ## Advanced Usage
204
+
205
+ ### Conditional Actor Connections
206
+
207
+ You can conditionally enable/disable actor connections:
208
+
209
+ ```svelte
210
+ <script lang="ts">
211
+ let userId = $state<string | null>(null);
212
+
213
+ const userActor = useActor({
214
+ name: 'user',
215
+ key: [userId || 'anonymous'],
216
+ enabled: userId !== null
217
+ });
218
+ </script>
219
+ ```
220
+
221
+ ### Multiple Actor Instances
222
+
223
+ You can connect to multiple instances of the same actor:
224
+
225
+ ```svelte
226
+ <script lang="ts">
227
+ const chatRoom1 = useActor({ name: 'chat', key: ['room-1'] });
228
+ const chatRoom2 = useActor({ name: 'chat', key: ['room-2'] });
229
+ const privateChat = useActor({ name: 'chat', key: ['private', userId] });
230
+ </script>
231
+ ```
232
+
233
+ ### Error Handling
234
+
235
+ Handle connection errors gracefully:
236
+
237
+ ```svelte
238
+ <script lang="ts">
239
+ const actor = useActor({ name: 'counter', key: ['test'] });
240
+
241
+ $effect(() => {
242
+ if (actor?.isError && actor?.error) {
243
+ console.error('Actor connection error:', actor.error);
244
+ // Show error message to user
245
+ }
246
+ });
247
+ </script>
248
+
249
+ {#if actor?.isError}
250
+ <div class="error">
251
+ Connection failed: {actor.error?.message}
252
+ </div>
253
+ {:else if actor?.isConnecting}
254
+ <div class="loading">Connecting...</div>
255
+ {:else if actor?.isConnected}
256
+ <div class="success">Connected!</div>
257
+ {/if}
258
+ ```
259
+
260
+ ## API Reference
261
+
262
+ ### createClient(url: string)
263
+
264
+ Creates a client connection to your RivetKit server.
265
+
266
+ ```typescript
267
+ import { createClient } from "@rivetkit/svelte";
268
+
269
+ const client = createClient<Registry>("http://localhost:8080");
270
+ ```
271
+
272
+ ### createRivetKit(client: Client)
273
+
274
+ Creates the RivetKit integration with your client.
275
+
276
+ ```typescript
277
+ import { createRivetKit } from "@rivetkit/svelte";
278
+
279
+ const { useActor } = createRivetKit(client);
280
+ ```
281
+
282
+ ### useActor(options: ActorOptions)
283
+
284
+ Connects to a RivetKit actor and returns reactive state.
285
+
286
+ **Parameters:**
287
+ - `name: string` - The actor name from your registry
288
+ - `key: string | string[]` - Unique identifier for the actor instance
289
+ - `params?: Record<string, string>` - Optional parameters to pass to the actor
290
+ - `enabled?: boolean` - Whether the connection is enabled (default: true)
291
+
292
+ **Returns:**
293
+ - `connection` - Actor connection for calling actions
294
+ - `handle` - Actor handle for advanced operations
295
+ - `isConnected` - Connection status
296
+ - `isConnecting` - Loading state
297
+ - `isError` - Error state
298
+ - `error` - Error object
299
+ - `useEvent` - Function to listen for events
300
+
301
+ ## TypeScript Support
302
+
303
+ RivetKit Svelte provides full TypeScript support. Make sure to type your registry:
304
+
305
+ ```typescript
306
+ // backend/index.ts
307
+ export type Registry = typeof registry;
308
+
309
+ // frontend/actor-client.ts
310
+ import type { Registry } from "../../backend";
311
+ const client = createClient<Registry>("http://localhost:8080");
312
+ ```
313
+
314
+ ## SvelteKit Integration
315
+
316
+ RivetKit Svelte works seamlessly with SvelteKit. The library automatically detects browser environment and handles SSR appropriately.
317
+
318
+ ```svelte
319
+ <!-- +layout.svelte -->
320
+ <script lang="ts">
321
+ import { useActor } from "$lib/actor-client";
322
+
323
+ // This will only connect in the browser
324
+ const globalActor = useActor({ name: 'global', key: ['app'] });
325
+ </script>
326
+ ```
327
+
328
+ ## Examples
329
+
330
+ Check out the `examples` folder in this repository for a complete working example with:
331
+ - Backend RivetKit server setup
332
+ - Frontend Svelte integration
333
+ - Real-time counter with events
334
+ - TypeScript configuration
335
+
336
+ ## Contributing
337
+
338
+ Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
339
+
340
+ ## License
341
+
342
+ MIT License - see LICENSE file for details.
@@ -0,0 +1 @@
1
+ export * from "./rivet.svelte.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./rivet.svelte.js";
@@ -0,0 +1,22 @@
1
+ import type * as _rivetkit_core_client from "@rivetkit/core/client";
2
+ import type { Client, ExtractActorsFromRegistry } from "@rivetkit/core/client";
3
+ import { type ActorOptions, type AnyActorRegistry, type CreateRivetKitOptions } from "@rivetkit/framework-base";
4
+ export { createClient } from "@rivetkit/core/client";
5
+ export declare function createRivetKit<Registry extends AnyActorRegistry>(client: Client<Registry>, opts?: CreateRivetKitOptions<Registry>): {
6
+ useActor: <ActorName extends keyof ExtractActorsFromRegistry<Registry>>(opts: ActorOptions<Registry, ActorName>) => {
7
+ connection: _rivetkit_core_client.ActorConn<ExtractActorsFromRegistry<Registry>[ActorName]> | null;
8
+ handle: _rivetkit_core_client.ActorHandle<ExtractActorsFromRegistry<Registry>[ActorName]> | null;
9
+ isConnected: boolean | undefined;
10
+ isConnecting: boolean | undefined;
11
+ actorOpts: {
12
+ name: keyof ExtractActorsFromRegistry<Registry>;
13
+ key: string | string[];
14
+ params?: Record<string, string>;
15
+ enabled?: boolean;
16
+ };
17
+ isError: boolean | undefined;
18
+ error: Error | null;
19
+ hash: string;
20
+ useEvent: (eventName: string, handler: (...args: any[]) => void) => void;
21
+ };
22
+ };
@@ -0,0 +1,103 @@
1
+ import { createRivetKit as createVanillaRivetKit, } from "@rivetkit/framework-base";
2
+ import { BROWSER } from "esm-env";
3
+ export { createClient } from "@rivetkit/core/client";
4
+ export function createRivetKit(client, opts = {}) {
5
+ const { getOrCreateActor } = createVanillaRivetKit(client, opts);
6
+ /**
7
+ * Svelte 5 rune-based function to connect to an actor and retrieve its state.
8
+ * Using this function with the same options will return the same actor instance.
9
+ * This simplifies passing around the actor state in your components.
10
+ * It also provides a method to listen for events emitted by the actor.
11
+ * @param opts - Options for the actor, including its name, key, and parameters.
12
+ * @returns An object containing reactive state and event listener function.
13
+ */
14
+ function useActor(opts) {
15
+ const { mount, setState, state } = getOrCreateActor(opts);
16
+ let connection = $state(null);
17
+ let handle = $state(null);
18
+ let isConnected = $state(false);
19
+ let isConnecting = $state(false);
20
+ let actorOpts = $state({});
21
+ let isError = $state(undefined);
22
+ let error = $state(null);
23
+ let hash = $state("");
24
+ // Only run in browser to avoid SSR issues
25
+ if (BROWSER) {
26
+ state.subscribe((newData) => {
27
+ connection = newData.currentVal.connection;
28
+ handle = newData.currentVal.handle;
29
+ isConnected = newData.currentVal.isConnected;
30
+ isConnecting = newData.currentVal.isConnecting;
31
+ actorOpts = newData.currentVal.opts;
32
+ isError = newData.currentVal.isError;
33
+ error = newData.currentVal.error;
34
+ hash = newData.currentVal.hash;
35
+ });
36
+ // Update options reactively
37
+ $effect.root(() => {
38
+ setState((prev) => {
39
+ prev.opts = {
40
+ ...opts,
41
+ enabled: opts.enabled ?? true,
42
+ };
43
+ return prev;
44
+ });
45
+ });
46
+ // Mount and subscribe to state changes
47
+ $effect.root(() => {
48
+ mount();
49
+ });
50
+ }
51
+ /**
52
+ * Function to listen for events emitted by the actor.
53
+ * This function allows you to subscribe to specific events emitted by the actor
54
+ * and execute a handler function when the event occurs.
55
+ * It automatically manages the event listener lifecycle.
56
+ * @param eventName The name of the event to listen for.
57
+ * @param handler The function to call when the event is emitted.
58
+ */
59
+ function useEvent(eventName,
60
+ // biome-ignore lint/suspicious/noExplicitAny: strong typing of handler is not supported yet
61
+ handler) {
62
+ const connection = $derived(state.state.connection);
63
+ let connSubs;
64
+ $effect.root(() => {
65
+ connSubs = connection?.on(eventName, handler);
66
+ // Cleanup function
67
+ return () => {
68
+ connSubs?.();
69
+ };
70
+ });
71
+ }
72
+ return {
73
+ get connection() {
74
+ return connection;
75
+ },
76
+ get handle() {
77
+ return handle;
78
+ },
79
+ get isConnected() {
80
+ return isConnected;
81
+ },
82
+ get isConnecting() {
83
+ return isConnecting;
84
+ },
85
+ get actorOpts() {
86
+ return actorOpts;
87
+ },
88
+ get isError() {
89
+ return isError;
90
+ },
91
+ get error() {
92
+ return error;
93
+ },
94
+ get hash() {
95
+ return hash;
96
+ },
97
+ useEvent,
98
+ };
99
+ }
100
+ return {
101
+ useActor,
102
+ };
103
+ }
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@blujosi/rivetkit-svelte",
3
+ "version": "0.0.1",
4
+ "scripts": {
5
+ "dev": "vite dev",
6
+ "build": "vite build && npm run prepack",
7
+ "preview": "vite preview",
8
+ "prepare": "svelte-kit sync || echo ''",
9
+ "prepack": "svelte-kit sync && svelte-package && publint",
10
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
11
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "!dist/**/*.test.*",
16
+ "!dist/**/*.spec.*"
17
+ ],
18
+ "sideEffects": [
19
+ "**/*.css"
20
+ ],
21
+ "svelte": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "svelte": "./dist/index.js"
28
+ }
29
+ },
30
+ "peerDependencies": {
31
+ "svelte": "^5.0.0"
32
+ },
33
+ "devDependencies": {
34
+ "@sveltejs/adapter-auto": "^6.0.0",
35
+ "@sveltejs/kit": "^2.22.0",
36
+ "@sveltejs/package": "^2.0.0",
37
+ "@sveltejs/vite-plugin-svelte": "^6.0.0",
38
+ "publint": "^0.3.2",
39
+ "svelte": "^5.38.1",
40
+ "svelte-check": "^4.0.0",
41
+ "typescript": "^5.0.0",
42
+ "vite": "^7.0.4"
43
+ },
44
+ "keywords": [
45
+ "svelte"
46
+ ],
47
+ "dependencies": {
48
+ "@rivetkit/actor": "^0.9.9",
49
+ "@rivetkit/core": "^0.9.9",
50
+ "@rivetkit/framework-base": "^0.9.9",
51
+ "esm-env": "^1.2.2"
52
+ }
53
+ }