@fidscript/instant-solidjs 0.1.0

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.
Files changed (43) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +16 -0
  3. package/.tshy/esm.json +15 -0
  4. package/dist/commonjs/InstantSolidDatabase.d.ts +185 -0
  5. package/dist/commonjs/InstantSolidDatabase.d.ts.map +1 -0
  6. package/dist/commonjs/InstantSolidDatabase.js +329 -0
  7. package/dist/commonjs/InstantSolidDatabase.js.map +1 -0
  8. package/dist/commonjs/InstantSolidRoom.d.ts +97 -0
  9. package/dist/commonjs/InstantSolidRoom.d.ts.map +1 -0
  10. package/dist/commonjs/InstantSolidRoom.js +209 -0
  11. package/dist/commonjs/InstantSolidRoom.js.map +1 -0
  12. package/dist/commonjs/index.d.ts +6 -0
  13. package/dist/commonjs/index.d.ts.map +1 -0
  14. package/dist/commonjs/index.js +23 -0
  15. package/dist/commonjs/index.js.map +1 -0
  16. package/dist/commonjs/package.json +3 -0
  17. package/dist/commonjs/version.d.ts +3 -0
  18. package/dist/commonjs/version.d.ts.map +1 -0
  19. package/dist/commonjs/version.js +5 -0
  20. package/dist/commonjs/version.js.map +1 -0
  21. package/dist/esm/InstantSolidDatabase.d.ts +185 -0
  22. package/dist/esm/InstantSolidDatabase.d.ts.map +1 -0
  23. package/dist/esm/InstantSolidDatabase.js +321 -0
  24. package/dist/esm/InstantSolidDatabase.js.map +1 -0
  25. package/dist/esm/InstantSolidRoom.d.ts +97 -0
  26. package/dist/esm/InstantSolidRoom.d.ts.map +1 -0
  27. package/dist/esm/InstantSolidRoom.js +200 -0
  28. package/dist/esm/InstantSolidRoom.js.map +1 -0
  29. package/dist/esm/index.d.ts +6 -0
  30. package/dist/esm/index.d.ts.map +1 -0
  31. package/dist/esm/index.js +18 -0
  32. package/dist/esm/index.js.map +1 -0
  33. package/dist/esm/package.json +3 -0
  34. package/dist/esm/version.d.ts +3 -0
  35. package/dist/esm/version.d.ts.map +1 -0
  36. package/dist/esm/version.js +3 -0
  37. package/dist/esm/version.js.map +1 -0
  38. package/package.json +47 -0
  39. package/src/InstantSolidDatabase.ts +463 -0
  40. package/src/InstantSolidRoom.ts +330 -0
  41. package/src/index.ts +204 -0
  42. package/src/version.ts +2 -0
  43. package/tsconfig.json +45 -0
@@ -0,0 +1,330 @@
1
+ import {
2
+ type PresenceOpts,
3
+ type PresenceResponse,
4
+ type RoomSchemaShape,
5
+ InstantCoreDatabase,
6
+ InstantSchemaDef,
7
+ } from '@fidscript/instant-sdk';
8
+
9
+ import { createSignal, createEffect, onCleanup, createMemo } from 'solid-js';
10
+ import type { Accessor } from 'solid-js';
11
+
12
+ // ------
13
+ // Types
14
+
15
+ export type PresenceHandle<
16
+ PresenceShape,
17
+ Keys extends keyof PresenceShape,
18
+ > = PresenceResponse<PresenceShape, Keys> & {
19
+ publishPresence: (data: Partial<PresenceShape>) => void;
20
+ };
21
+
22
+ export type TypingIndicatorOpts = {
23
+ timeout?: number | null;
24
+ stopOnEnter?: boolean;
25
+ // Perf opt - `active` will always be an empty array
26
+ writeOnly?: boolean;
27
+ };
28
+
29
+ export type TypingIndicatorHandle<PresenceShape> = {
30
+ active: Accessor<PresenceShape[]>;
31
+ setActive(active: boolean): void;
32
+ inputProps: {
33
+ onKeyDown: (e: KeyboardEvent) => void;
34
+ onBlur: () => void;
35
+ };
36
+ };
37
+
38
+ export const defaultActivityStopTimeout = 1_000;
39
+
40
+ // ------
41
+ // Topics
42
+
43
+ /**
44
+ * Listen for broadcasted events given a room and topic.
45
+ *
46
+ * @see https://instantdb.com/docs/presence-and-topics
47
+ * @example
48
+ * function App({ roomId }) {
49
+ * const room = db.room('chats', roomId);
50
+ * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => {
51
+ * console.log(peer.name, 'sent', message);
52
+ * });
53
+ * // ...
54
+ * }
55
+ */
56
+ export function useTopicEffect<
57
+ RoomSchema extends RoomSchemaShape,
58
+ RoomType extends keyof RoomSchema,
59
+ TopicType extends keyof RoomSchema[RoomType]['topics'],
60
+ >(
61
+ room: InstantSolidRoom<any, RoomSchema, RoomType>,
62
+ topic: TopicType,
63
+ onEvent: (
64
+ event: RoomSchema[RoomType]['topics'][TopicType],
65
+ peer: RoomSchema[RoomType]['presence'],
66
+ ) => any,
67
+ ): void {
68
+ createEffect(() => {
69
+ const unsub = room.core._reactor.subscribeTopic(
70
+ room.type,
71
+ room.id,
72
+ topic,
73
+ (event: any, peer: any) => {
74
+ onEvent(event, peer);
75
+ },
76
+ );
77
+
78
+ onCleanup(unsub);
79
+ });
80
+ }
81
+
82
+ /**
83
+ * Broadcast an event to a room.
84
+ *
85
+ * @see https://instantdb.com/docs/presence-and-topics
86
+ * @example
87
+ * function App({ roomId }) {
88
+ * const room = db.room('chat', roomId);
89
+ * const publishTopic = db.rooms.usePublishTopic(room, "emoji");
90
+ *
91
+ * return (
92
+ * <button onClick={() => publishTopic({ emoji: "🔥" })}>Send emoji</button>
93
+ * );
94
+ * }
95
+ *
96
+ */
97
+ export function usePublishTopic<
98
+ RoomSchema extends RoomSchemaShape,
99
+ RoomType extends keyof RoomSchema,
100
+ TopicType extends keyof RoomSchema[RoomType]['topics'],
101
+ >(
102
+ room: InstantSolidRoom<any, RoomSchema, RoomType>,
103
+ topic: TopicType,
104
+ ): (data: RoomSchema[RoomType]['topics'][TopicType]) => void {
105
+ createEffect(() => {
106
+ const unsub = room.core._reactor.joinRoom(room.type as string, room.id);
107
+ onCleanup(unsub);
108
+ });
109
+
110
+ return (data: RoomSchema[RoomType]['topics'][TopicType]) => {
111
+ room.core._reactor.publishTopic({
112
+ roomType: room.type,
113
+ roomId: room.id,
114
+ topic,
115
+ data,
116
+ });
117
+ };
118
+ }
119
+
120
+ // ---------
121
+ // Presence
122
+
123
+ /**
124
+ * Listen for peer's presence data in a room, and publish the current user's presence.
125
+ *
126
+ * @see https://instantdb.com/docs/presence-and-topics
127
+ * @example
128
+ * function App({ roomId }) {
129
+ * const presence = db.rooms.usePresence(room, { keys: ["name", "avatar"] });
130
+ * // presence().peers, presence().isLoading, presence().publishPresence
131
+ * }
132
+ */
133
+ export function usePresence<
134
+ RoomSchema extends RoomSchemaShape,
135
+ RoomType extends keyof RoomSchema,
136
+ Keys extends keyof RoomSchema[RoomType]['presence'],
137
+ >(
138
+ room: InstantSolidRoom<any, RoomSchema, RoomType>,
139
+ opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},
140
+ ): Accessor<PresenceHandle<RoomSchema[RoomType]['presence'], Keys>> {
141
+ const [state, setState] = createSignal<
142
+ PresenceResponse<RoomSchema[RoomType]['presence'], Keys>
143
+ >(
144
+ (room.core._reactor.getPresence(room.type, room.id, opts) ?? {
145
+ peers: {},
146
+ isLoading: true,
147
+ }) as PresenceResponse<RoomSchema[RoomType]['presence'], Keys>,
148
+ );
149
+
150
+ createEffect(() => {
151
+ const unsub = room.core._reactor.subscribePresence(
152
+ room.type,
153
+ room.id,
154
+ opts,
155
+ (data: any) => {
156
+ setState(data);
157
+ },
158
+ );
159
+
160
+ onCleanup(unsub);
161
+ });
162
+
163
+ const publishPresence = (data: Partial<RoomSchema[RoomType]['presence']>) => {
164
+ room.core._reactor.publishPresence(room.type, room.id, data);
165
+ };
166
+
167
+ return createMemo(() => ({
168
+ ...state(),
169
+ publishPresence,
170
+ }));
171
+ }
172
+
173
+ /**
174
+ * Publishes presence data to a room
175
+ *
176
+ * @see https://instantdb.com/docs/presence-and-topics
177
+ * @example
178
+ * function App({ roomId, nickname }) {
179
+ * const room = db.room('chat', roomId);
180
+ * db.rooms.useSyncPresence(room, { nickname });
181
+ * }
182
+ */
183
+ export function useSyncPresence<
184
+ RoomSchema extends RoomSchemaShape,
185
+ RoomType extends keyof RoomSchema,
186
+ >(
187
+ room: InstantSolidRoom<any, RoomSchema, RoomType>,
188
+ data: Partial<RoomSchema[RoomType]['presence']>,
189
+ deps?: any[],
190
+ ): void {
191
+ createEffect(() => {
192
+ const unsub = room.core._reactor.joinRoom(
193
+ room.type as string,
194
+ room.id,
195
+ data,
196
+ );
197
+ onCleanup(unsub);
198
+ });
199
+
200
+ createEffect(() => {
201
+ // Track deps if provided, otherwise track serialized data
202
+ if (deps) {
203
+ deps.forEach((d) => (typeof d === 'function' ? d() : d));
204
+ } else {
205
+ JSON.stringify(data);
206
+ }
207
+ room.core._reactor.publishPresence(room.type, room.id, data);
208
+ });
209
+ }
210
+
211
+ // -----------------
212
+ // Typing Indicator
213
+
214
+ /**
215
+ * Manage typing indicator state
216
+ *
217
+ * @see https://instantdb.com/docs/presence-and-topics
218
+ * @example
219
+ * function App({ roomId }) {
220
+ * const room = db.room('chat', roomId);
221
+ * const typing = db.rooms.useTypingIndicator(room, "chat-input");
222
+ * // typing.active(), typing.setActive(bool), typing.inputProps
223
+ * }
224
+ */
225
+ export function useTypingIndicator<
226
+ RoomSchema extends RoomSchemaShape,
227
+ RoomType extends keyof RoomSchema,
228
+ >(
229
+ room: InstantSolidRoom<any, RoomSchema, RoomType>,
230
+ inputName: string,
231
+ opts: TypingIndicatorOpts = {},
232
+ ): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> {
233
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
234
+
235
+ const presence = rooms.usePresence(room, {
236
+ keys: [inputName] as (keyof RoomSchema[RoomType]['presence'])[],
237
+ });
238
+
239
+ const active = createMemo(() => {
240
+ if (opts?.writeOnly) return [];
241
+ // Access presence to track it
242
+ presence();
243
+ const presenceSnapshot = room.core._reactor.getPresence(room.type, room.id);
244
+ return Object.values(presenceSnapshot?.peers ?? {}).filter(
245
+ (p: any) => p[inputName] === true,
246
+ );
247
+ });
248
+
249
+ const setActive = (isActive: boolean) => {
250
+ room.core._reactor.publishPresence(room.type, room.id, {
251
+ [inputName]: isActive ? true : null,
252
+ } as Partial<RoomSchema[RoomType]['presence']>);
253
+
254
+ if (timeoutId) {
255
+ clearTimeout(timeoutId);
256
+ timeoutId = null;
257
+ }
258
+
259
+ if (!isActive) return;
260
+
261
+ if (opts?.timeout === null || opts?.timeout === 0) return;
262
+
263
+ timeoutId = setTimeout(() => {
264
+ room.core._reactor.publishPresence(room.type, room.id, {
265
+ [inputName]: null,
266
+ } as Partial<RoomSchema[RoomType]['presence']>);
267
+ }, opts?.timeout ?? defaultActivityStopTimeout);
268
+ };
269
+
270
+ onCleanup(() => {
271
+ if (timeoutId) {
272
+ clearTimeout(timeoutId);
273
+ timeoutId = null;
274
+ }
275
+
276
+ // Ensure we don't leave a sticky typing state behind on unmount,
277
+ // even when opts.timeout is null/0 (i.e. no auto-timeout).
278
+ setActive(false);
279
+ });
280
+
281
+ const onKeyDown = (e: KeyboardEvent) => {
282
+ const isEnter = opts?.stopOnEnter && e.key === 'Enter';
283
+ const isActive = !isEnter;
284
+ setActive(isActive);
285
+ };
286
+
287
+ const onBlur = () => {
288
+ setActive(false);
289
+ };
290
+
291
+ return {
292
+ active,
293
+ setActive,
294
+ inputProps: { onKeyDown, onBlur },
295
+ };
296
+ }
297
+
298
+ // --------------
299
+ // Hooks namespace
300
+
301
+ export const rooms = {
302
+ useTopicEffect,
303
+ usePublishTopic,
304
+ usePresence,
305
+ useSyncPresence,
306
+ useTypingIndicator,
307
+ };
308
+
309
+ // ------------
310
+ // Class
311
+
312
+ export class InstantSolidRoom<
313
+ Schema extends InstantSchemaDef<any, any, any>,
314
+ RoomSchema extends RoomSchemaShape,
315
+ RoomType extends keyof RoomSchema,
316
+ > {
317
+ core: InstantCoreDatabase<Schema, boolean>;
318
+ type: RoomType;
319
+ id: string;
320
+
321
+ constructor(
322
+ core: InstantCoreDatabase<Schema, boolean>,
323
+ type: RoomType,
324
+ id: string,
325
+ ) {
326
+ this.core = core;
327
+ this.type = type;
328
+ this.id = id;
329
+ }
330
+ }
package/src/index.ts ADDED
@@ -0,0 +1,204 @@
1
+ import {
2
+ id,
3
+ tx,
4
+ lookup,
5
+ i,
6
+
7
+ // error
8
+ InstantAPIError,
9
+
10
+ // sync table enums
11
+ SyncTableCallbackEventType,
12
+
13
+ // types
14
+ type QueryResponse,
15
+ type InstantQuery,
16
+ type InstantQueryResult,
17
+ type InstantSchema,
18
+ type InstantObject,
19
+ type InstantEntity,
20
+ type InstantSchemaDatabase,
21
+ type InstantUnknownSchemaDef,
22
+ type IInstantDatabase,
23
+ type User,
24
+ type AuthState,
25
+ type Query,
26
+ type Config,
27
+ type InstaQLParams,
28
+ type ConnectionStatus,
29
+ type ValidQuery,
30
+
31
+ // presence types
32
+ type PresencePeer,
33
+
34
+ // schema types
35
+ type AttrsDefs,
36
+ type CardinalityKind,
37
+ type DataAttrDef,
38
+ type EntitiesDef,
39
+ type EntitiesWithLinks,
40
+ type EntityDef,
41
+ type InstantGraph,
42
+ type InstantConfig,
43
+ type LinkAttrDef,
44
+ type LinkDef,
45
+ type LinksDef,
46
+ type ResolveAttrs,
47
+ type ValueTypes,
48
+ type InstaQLEntity,
49
+ type InstaQLFields,
50
+ type InstaQLResult,
51
+ type InstaQLEntitySubquery,
52
+ type RoomsOf,
53
+ type RoomsDef,
54
+ type PresenceOf,
55
+ type TopicsOf,
56
+ type TopicOf,
57
+ type RoomHandle,
58
+ type TransactionChunk,
59
+ type InstantUnknownSchema,
60
+ type InstantSchemaDef,
61
+ type BackwardsCompatibleSchema,
62
+ type InstantRules,
63
+ type UpdateParams,
64
+ type LinkParams,
65
+ type CreateParams,
66
+ type CheckMagicCodeParams,
67
+ type CheckMagicCodeResponse,
68
+ type ExchangeCodeForTokenParams,
69
+ type SendMagicCodeParams,
70
+ type SendMagicCodeResponse,
71
+ type SignInWithIdTokenParams,
72
+ type VerifyMagicCodeParams,
73
+ type VerifyResponse,
74
+
75
+ // storage types
76
+ type FileOpts,
77
+ type UploadFileResponse,
78
+ type DeleteFileResponse,
79
+
80
+ // sync table types
81
+ type SyncTableCallback,
82
+ type SyncTableCallbackEvent,
83
+ type SyncTableInitialSyncBatch,
84
+ type SyncTableInitialSyncComplete,
85
+ type SyncTableSyncTransaction,
86
+ type SyncTableLoadFromStorage,
87
+ type SyncTableSetupError,
88
+ StoreInterface,
89
+ createInstantRouteHandler,
90
+ type InstantRouteHandlerPayloadByType,
91
+ type InstantRouteHandlerType,
92
+ type InstantRouteHandlerBody,
93
+ type StoreInterfaceStoreName,
94
+ type Logger,
95
+ } from '@fidscript/instant-sdk';
96
+
97
+ import { InstantSolidDatabase } from './InstantSolidDatabase.js';
98
+ import { init } from './InstantSolidDatabase.js';
99
+ import { InstantSolidRoom } from './InstantSolidRoom.js';
100
+
101
+ export {
102
+ id,
103
+ tx,
104
+ lookup,
105
+ init,
106
+ InstantSolidDatabase,
107
+ InstantSolidRoom,
108
+ i,
109
+
110
+ // error
111
+ InstantAPIError,
112
+
113
+ // sync table enums
114
+ SyncTableCallbackEventType,
115
+
116
+ // types
117
+ type Config,
118
+ type InstantConfig,
119
+ type InstantUnknownSchemaDef,
120
+ type Query,
121
+ type QueryResponse,
122
+ type InstantObject,
123
+ type User,
124
+ type AuthState,
125
+ type ConnectionStatus,
126
+ type InstantQuery,
127
+ type InstantQueryResult,
128
+ type InstantSchema,
129
+ type InstantEntity,
130
+ type InstantSchemaDatabase,
131
+ type IInstantDatabase,
132
+ type InstaQLParams,
133
+ type ValidQuery,
134
+ type InstaQLFields,
135
+
136
+ // presence types
137
+ type PresencePeer,
138
+
139
+ // schema types
140
+ type AttrsDefs,
141
+ type CardinalityKind,
142
+ type DataAttrDef,
143
+ type EntitiesDef,
144
+ type EntitiesWithLinks,
145
+ type EntityDef,
146
+ type InstantGraph,
147
+ type LinkAttrDef,
148
+ type LinkDef,
149
+ type LinksDef,
150
+ type ResolveAttrs,
151
+ type ValueTypes,
152
+ type InstaQLEntity,
153
+ type InstaQLResult,
154
+ type InstaQLEntitySubquery,
155
+ type RoomsOf,
156
+ type RoomsDef,
157
+ type TransactionChunk,
158
+ type PresenceOf,
159
+ type TopicsOf,
160
+ type TopicOf,
161
+ type RoomHandle,
162
+ type InstantUnknownSchema,
163
+ type InstantSchemaDef,
164
+ type BackwardsCompatibleSchema,
165
+ type InstantRules,
166
+ type UpdateParams,
167
+ type LinkParams,
168
+ type CreateParams,
169
+ type CheckMagicCodeParams,
170
+ type CheckMagicCodeResponse,
171
+ type ExchangeCodeForTokenParams,
172
+ type SendMagicCodeParams,
173
+ type SendMagicCodeResponse,
174
+ type SignInWithIdTokenParams,
175
+ type VerifyMagicCodeParams,
176
+ type VerifyResponse,
177
+
178
+ // storage types
179
+ type FileOpts,
180
+ type UploadFileResponse,
181
+ type DeleteFileResponse,
182
+
183
+ // custom store
184
+ StoreInterface,
185
+ type StoreInterfaceStoreName,
186
+
187
+ // sync table types
188
+ type SyncTableCallback,
189
+ type SyncTableCallbackEvent,
190
+ type SyncTableInitialSyncBatch,
191
+ type SyncTableInitialSyncComplete,
192
+ type SyncTableSyncTransaction,
193
+ type SyncTableLoadFromStorage,
194
+ type SyncTableSetupError,
195
+
196
+ // Server helper
197
+ createInstantRouteHandler,
198
+ type InstantRouteHandlerPayloadByType,
199
+ type InstantRouteHandlerType,
200
+ type InstantRouteHandlerBody,
201
+
202
+ // logger
203
+ type Logger,
204
+ };
package/src/version.ts ADDED
@@ -0,0 +1,2 @@
1
+ const version = '0.1.0';
2
+ export default version;
package/tsconfig.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ // Visit https://aka.ms/tsconfig to read more about this file
4
+ "compilerOptions": {
5
+ // File Layout
6
+ "rootDir": "./src",
7
+ "outDir": "./dist",
8
+
9
+ // Environment Settings
10
+ // See also https://aka.ms/tsconfig/module
11
+ "module": "nodenext",
12
+ "target": "esnext",
13
+ "types": [],
14
+ // For nodejs:
15
+ // "lib": ["esnext"],
16
+ // "types": ["node"],
17
+ // and npm install -D @types/node
18
+
19
+ // Other Outputs
20
+ "sourceMap": true,
21
+ "declaration": true,
22
+ "declarationMap": true,
23
+
24
+ // Stricter Typechecking Options
25
+ "noUncheckedIndexedAccess": true,
26
+ "exactOptionalPropertyTypes": true,
27
+
28
+ // Style Options
29
+ // "noImplicitReturns": true,
30
+ // "noImplicitOverride": true,
31
+ // "noUnusedLocals": true,
32
+ // "noUnusedParameters": true,
33
+ // "noFallthroughCasesInSwitch": true,
34
+ // "noPropertyAccessFromIndexSignature": true,
35
+
36
+ // Recommended Options
37
+ "strict": true,
38
+ "jsx": "preserve",
39
+ "isolatedModules": true,
40
+ "noUncheckedSideEffectImports": true,
41
+ "moduleDetection": "force",
42
+ "skipLibCheck": true
43
+ },
44
+ "include": ["src"]
45
+ }