@sidekickdb/solidjs 0.0.0 → 2.0.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 (51) 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/.turbo/turbo-build.log +50 -0
  5. package/LICENSE.md +202 -0
  6. package/NOTICE +27 -0
  7. package/README.md +41 -2
  8. package/dist/commonjs/InstantSolidDatabase.d.ts +185 -0
  9. package/dist/commonjs/InstantSolidDatabase.d.ts.map +1 -0
  10. package/dist/commonjs/InstantSolidDatabase.js +329 -0
  11. package/dist/commonjs/InstantSolidDatabase.js.map +1 -0
  12. package/dist/commonjs/InstantSolidRoom.d.ts +97 -0
  13. package/dist/commonjs/InstantSolidRoom.d.ts.map +1 -0
  14. package/dist/commonjs/InstantSolidRoom.js +209 -0
  15. package/dist/commonjs/InstantSolidRoom.js.map +1 -0
  16. package/dist/commonjs/index.d.ts +6 -0
  17. package/dist/commonjs/index.d.ts.map +1 -0
  18. package/dist/commonjs/index.js +23 -0
  19. package/dist/commonjs/index.js.map +1 -0
  20. package/dist/commonjs/package.json +3 -0
  21. package/dist/commonjs/version.d.ts +3 -0
  22. package/dist/commonjs/version.d.ts.map +1 -0
  23. package/dist/commonjs/version.js +5 -0
  24. package/dist/commonjs/version.js.map +1 -0
  25. package/dist/esm/InstantSolidDatabase.d.ts +185 -0
  26. package/dist/esm/InstantSolidDatabase.d.ts.map +1 -0
  27. package/dist/esm/InstantSolidDatabase.js +321 -0
  28. package/dist/esm/InstantSolidDatabase.js.map +1 -0
  29. package/dist/esm/InstantSolidRoom.d.ts +97 -0
  30. package/dist/esm/InstantSolidRoom.d.ts.map +1 -0
  31. package/dist/esm/InstantSolidRoom.js +200 -0
  32. package/dist/esm/InstantSolidRoom.js.map +1 -0
  33. package/dist/esm/index.d.ts +6 -0
  34. package/dist/esm/index.d.ts.map +1 -0
  35. package/dist/esm/index.js +18 -0
  36. package/dist/esm/index.js.map +1 -0
  37. package/dist/esm/package.json +3 -0
  38. package/dist/esm/version.d.ts +3 -0
  39. package/dist/esm/version.d.ts.map +1 -0
  40. package/dist/esm/version.js +3 -0
  41. package/dist/esm/version.js.map +1 -0
  42. package/dist/standalone/index.js +8511 -0
  43. package/dist/standalone/index.umd.cjs +7 -0
  44. package/package.json +60 -3
  45. package/src/InstantSolidDatabase.ts +463 -0
  46. package/src/InstantSolidRoom.ts +330 -0
  47. package/src/index.ts +204 -0
  48. package/src/version.ts +2 -0
  49. package/tsconfig.dev.json +14 -0
  50. package/tsconfig.json +45 -0
  51. package/vite.config.ts +20 -0
@@ -0,0 +1,463 @@
1
+ import {
2
+ // types
3
+ type AuthState,
4
+ type User,
5
+ type ConnectionStatus,
6
+ type TransactionChunk,
7
+ type RoomSchemaShape,
8
+ type InstaQLOptions,
9
+ type InstantConfig,
10
+ type PageInfoResponse,
11
+ type InstaQLLifecycleState,
12
+ type InstaQLResponse,
13
+ type InfiniteQuerySubscription,
14
+ type ValidQuery,
15
+ // classes
16
+ Auth,
17
+ Storage,
18
+ Streams,
19
+ txInit,
20
+ InstantCoreDatabase,
21
+ init as core_init,
22
+ coerceQuery,
23
+ getInfiniteQueryInitialSnapshot,
24
+ InstantSchemaDef,
25
+ RoomsOf,
26
+ InstantError,
27
+ IInstantDatabase,
28
+ } from '@sidekickdb/core';
29
+
30
+ import { createSignal, createEffect, onCleanup, createMemo } from 'solid-js';
31
+ import type { Accessor } from 'solid-js';
32
+
33
+ import { InstantSolidRoom, rooms } from './InstantSolidRoom.js';
34
+ import version from './version.js';
35
+
36
+ const defaultState = {
37
+ isLoading: true,
38
+ data: undefined,
39
+ pageInfo: undefined,
40
+ error: undefined,
41
+ } as const;
42
+
43
+ export type InfiniteQueryState<
44
+ Schema extends InstantSchemaDef<any, any, any>,
45
+ Q extends ValidQuery<Q, Schema>,
46
+ UseDates extends boolean,
47
+ > = {
48
+ isLoading: boolean;
49
+ error: { message: string } | undefined;
50
+ data: InstaQLResponse<Schema, Q, UseDates> | undefined;
51
+ canLoadNextPage: boolean;
52
+ loadNextPage: () => void;
53
+ };
54
+
55
+ const defaultAuthState: AuthState = {
56
+ isLoading: true,
57
+ user: undefined,
58
+ error: undefined,
59
+ };
60
+
61
+ function stateForResult(result: any) {
62
+ return {
63
+ isLoading: !Boolean(result),
64
+ data: undefined,
65
+ pageInfo: undefined,
66
+ error: undefined,
67
+ ...(result ? result : {}),
68
+ };
69
+ }
70
+
71
+ export class InstantSolidDatabase<
72
+ Schema extends InstantSchemaDef<any, any, any>,
73
+ UseDates extends boolean = false,
74
+ Rooms extends RoomSchemaShape = RoomsOf<Schema>,
75
+ > implements IInstantDatabase<Schema>
76
+ {
77
+ public tx = txInit<Schema>();
78
+
79
+ public auth: Auth;
80
+ public storage: Storage;
81
+ public streams: Streams;
82
+ public core: InstantCoreDatabase<Schema, UseDates>;
83
+
84
+ constructor(core: InstantCoreDatabase<Schema, UseDates>) {
85
+ this.core = core;
86
+ this.auth = this.core.auth;
87
+ this.storage = this.core.storage;
88
+ this.streams = this.core.streams;
89
+ }
90
+
91
+ /**
92
+ * Returns a unique ID for a given `name`. It's stored in local storage,
93
+ * so you will get the same ID across sessions.
94
+ *
95
+ * @example
96
+ * const deviceId = await db.getLocalId('device');
97
+ */
98
+ getLocalId = (name: string): Promise<string> => {
99
+ return this.core.getLocalId(name);
100
+ };
101
+
102
+ /**
103
+ * Use this to write data! You can create, update, delete, and link objects
104
+ *
105
+ * @see https://sidekickdb.co/docs/instaml
106
+ *
107
+ * @example
108
+ * const goalId = id();
109
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
110
+ */
111
+ transact = (
112
+ chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],
113
+ ) => {
114
+ return this.core.transact(chunks);
115
+ };
116
+
117
+ /**
118
+ * One time query for the logged in state.
119
+ *
120
+ * @see https://sidekickdb.co/docs/auth
121
+ * @example
122
+ * const user = await db.getAuth();
123
+ * console.log('logged in as', user.email)
124
+ */
125
+ getAuth(): Promise<User | null> {
126
+ return this.core.getAuth();
127
+ }
128
+
129
+ /**
130
+ * Use this for one-off queries.
131
+ * Returns local data if available, otherwise fetches from the server.
132
+ *
133
+ * @see https://sidekickdb.co/docs/instaql
134
+ *
135
+ * @example
136
+ * const resp = await db.queryOnce({ goals: {} });
137
+ * console.log(resp.data.goals)
138
+ */
139
+ queryOnce = <Q extends ValidQuery<Q, Schema>>(
140
+ query: Q,
141
+ opts?: InstaQLOptions,
142
+ ): Promise<{
143
+ data: InstaQLResponse<Schema, Q, UseDates>;
144
+ pageInfo: PageInfoResponse<Q>;
145
+ }> => {
146
+ return this.core.queryOnce(query, opts);
147
+ };
148
+
149
+ // -----------
150
+ // Solid reactive hooks
151
+
152
+ /**
153
+ * Use this to query your data!
154
+ *
155
+ * @see https://sidekickdb.co/docs/instaql
156
+ *
157
+ * @example
158
+ * const state = db.useQuery({ goals: {} });
159
+ * // state().isLoading, state().error, state().data
160
+ */
161
+ useQuery = <Q extends ValidQuery<Q, Schema>>(
162
+ query: (() => null | Q) | null | Q,
163
+ opts?: InstaQLOptions,
164
+ ): Accessor<InstaQLLifecycleState<Schema, Q, UseDates>> => {
165
+ const [state, setState] = createSignal<
166
+ InstaQLLifecycleState<Schema, Q, UseDates>
167
+ >(defaultState as InstaQLLifecycleState<Schema, Q, UseDates>);
168
+
169
+ createEffect(() => {
170
+ const resolvedQuery = typeof query === 'function' ? query() : query;
171
+
172
+ if (!resolvedQuery) {
173
+ setState(
174
+ () => defaultState as InstaQLLifecycleState<Schema, Q, UseDates>,
175
+ );
176
+ return;
177
+ }
178
+
179
+ let q = resolvedQuery;
180
+ if (opts && 'ruleParams' in opts) {
181
+ q = { $$ruleParams: (opts as any)['ruleParams'], ...q };
182
+ }
183
+
184
+ const coerced = coerceQuery(q);
185
+ const prev = this.core._reactor.getPreviousResult(coerced);
186
+ if (prev) {
187
+ setState(
188
+ () =>
189
+ stateForResult(prev) as InstaQLLifecycleState<Schema, Q, UseDates>,
190
+ );
191
+ }
192
+
193
+ const unsub = this.core.subscribeQuery<Q, UseDates>(coerced, (result) => {
194
+ setState(
195
+ () =>
196
+ Object.assign(
197
+ {
198
+ isLoading: false,
199
+ data: undefined,
200
+ pageInfo: undefined,
201
+ error: undefined,
202
+ },
203
+ result,
204
+ ) as InstaQLLifecycleState<Schema, Q, UseDates>,
205
+ );
206
+ });
207
+
208
+ onCleanup(unsub);
209
+ });
210
+
211
+ return state;
212
+ };
213
+
214
+ /**
215
+ * Subscribe to a query and incrementally load more items.
216
+ *
217
+ * Only one top level namespace in the query is allowed.
218
+ *
219
+ * @see https://sidekickdb.co/docs/instaql
220
+ *
221
+ * @example
222
+ * const state = db.useInfiniteQuery({
223
+ * posts: {
224
+ * $: {
225
+ * limit: 20,
226
+ * order: { createdAt: 'desc' },
227
+ * },
228
+ * },
229
+ * });
230
+ * // state().data, state().isLoading, state().error,
231
+ * // state().canLoadNextPage, state().loadNextPage()
232
+ */
233
+ useInfiniteQuery = <Q extends ValidQuery<Q, Schema>>(
234
+ query: (() => null | Q) | null | Q,
235
+ opts?: InstaQLOptions,
236
+ ): Accessor<InfiniteQueryState<Schema, Q, UseDates>> => {
237
+ let sub: InfiniteQuerySubscription | null = null;
238
+ const loadNextPage = () => sub?.loadNextPage();
239
+
240
+ const [state, setState] = createSignal<
241
+ InfiniteQueryState<Schema, Q, UseDates>
242
+ >({
243
+ isLoading: true,
244
+ error: undefined,
245
+ data: undefined,
246
+ canLoadNextPage: false,
247
+ loadNextPage,
248
+ });
249
+
250
+ createEffect(() => {
251
+ const resolvedQuery = typeof query === 'function' ? query() : query;
252
+
253
+ if (!resolvedQuery) {
254
+ sub = null;
255
+ setState(() => ({
256
+ isLoading: true,
257
+ error: undefined,
258
+ data: undefined,
259
+ canLoadNextPage: false,
260
+ loadNextPage,
261
+ }));
262
+ return;
263
+ }
264
+
265
+ const snapshot = getInfiniteQueryInitialSnapshot<Schema, Q, UseDates>(
266
+ this.core,
267
+ resolvedQuery,
268
+ opts,
269
+ );
270
+ setState(() => ({
271
+ ...snapshot,
272
+ isLoading: !snapshot.data && !snapshot.error,
273
+ loadNextPage,
274
+ }));
275
+
276
+ sub = this.core.subscribeInfiniteQuery<Q>(
277
+ resolvedQuery,
278
+ (resp) => {
279
+ setState(() => ({
280
+ ...resp,
281
+ isLoading: false,
282
+ loadNextPage,
283
+ }));
284
+ },
285
+ opts,
286
+ );
287
+
288
+ onCleanup(() => {
289
+ sub?.unsubscribe();
290
+ sub = null;
291
+ });
292
+ });
293
+
294
+ return state;
295
+ };
296
+
297
+ /**
298
+ * Listen for the logged in state. This is useful
299
+ * for deciding when to show a login screen.
300
+ *
301
+ * @see https://sidekickdb.co/docs/auth
302
+ * @example
303
+ * function App() {
304
+ * const auth = db.useAuth();
305
+ * // auth().isLoading, auth().user, auth().error
306
+ * }
307
+ */
308
+ useAuth = (): Accessor<AuthState> => {
309
+ const [state, setState] = createSignal<AuthState>(
310
+ this.core._reactor._currentUserCached ?? defaultAuthState,
311
+ );
312
+
313
+ createEffect(() => {
314
+ const unsub = this.core.subscribeAuth((auth) => {
315
+ setState({ isLoading: false, ...auth });
316
+ });
317
+
318
+ onCleanup(unsub);
319
+ });
320
+
321
+ return state;
322
+ };
323
+
324
+ /**
325
+ * Subscribe to the currently logged in user.
326
+ * If the user is not logged in, this will throw an Error.
327
+ *
328
+ * @see https://sidekickdb.co/docs/auth
329
+ * @example
330
+ * function UserDisplay() {
331
+ * const user = db.useUser();
332
+ * return <div>Logged in as: {user().email}</div>
333
+ * }
334
+ */
335
+ useUser = (): Accessor<User> => {
336
+ const auth = this.useAuth();
337
+ return createMemo(() => {
338
+ const { user } = auth();
339
+ if (!user) {
340
+ throw new InstantError(
341
+ 'useUser must be used within an auth-protected route',
342
+ );
343
+ }
344
+ return user;
345
+ });
346
+ };
347
+
348
+ /**
349
+ * Listen for connection status changes to Instant.
350
+ *
351
+ * @see https://sidekickdb.co/docs/patterns#connection-status
352
+ * @example
353
+ * function App() {
354
+ * const status = db.useConnectionStatus();
355
+ * return <div>Connection state: {status()}</div>
356
+ * }
357
+ */
358
+ useConnectionStatus = (): Accessor<ConnectionStatus> => {
359
+ const [status, setStatus] = createSignal<ConnectionStatus>(
360
+ this.core._reactor.status as ConnectionStatus,
361
+ );
362
+
363
+ createEffect(() => {
364
+ const unsub = this.core.subscribeConnectionStatus((newStatus) => {
365
+ setStatus(() => newStatus);
366
+ });
367
+
368
+ onCleanup(unsub);
369
+ });
370
+
371
+ return status;
372
+ };
373
+
374
+ /**
375
+ * A hook that returns a unique ID for a given `name`. localIds are
376
+ * stored in local storage, so you will get the same ID across sessions.
377
+ *
378
+ * Initially returns `null`, and then loads the localId.
379
+ *
380
+ * @example
381
+ * const deviceId = db.useLocalId('device');
382
+ * // deviceId() is null initially, then the ID string
383
+ */
384
+ useLocalId = (name: string): Accessor<string | null> => {
385
+ const [localId, setLocalId] = createSignal<string | null>(null);
386
+
387
+ createEffect(() => {
388
+ let mounted = true;
389
+ this.getLocalId(name).then((id) => {
390
+ if (mounted) {
391
+ setLocalId(() => id);
392
+ }
393
+ });
394
+ onCleanup(() => {
395
+ mounted = false;
396
+ });
397
+ });
398
+
399
+ return localId;
400
+ };
401
+
402
+ /**
403
+ * Obtain a handle to a room, which allows you to listen to topics and presence data
404
+ *
405
+ * @see https://sidekickdb.co/docs/presence-and-topics
406
+ *
407
+ * @example
408
+ * const room = db.room('chat', roomId);
409
+ * const presence = db.rooms.usePresence(room);
410
+ */
411
+ room<RoomType extends keyof Rooms>(
412
+ type: RoomType = '_defaultRoomType' as RoomType,
413
+ id: string = '_defaultRoomId',
414
+ ) {
415
+ return new InstantSolidRoom<Schema, Rooms, RoomType>(this.core, type, id);
416
+ }
417
+
418
+ /**
419
+ * Hooks for working with rooms
420
+ *
421
+ * @see https://sidekickdb.co/docs/presence-and-topics
422
+ *
423
+ * @example
424
+ * const room = db.room('chat', roomId);
425
+ * const presence = db.rooms.usePresence(room);
426
+ * const publish = db.rooms.usePublishTopic(room, 'emoji');
427
+ */
428
+ rooms = rooms;
429
+ }
430
+
431
+ // -----------
432
+ // init
433
+
434
+ /**
435
+ * The first step: init your application!
436
+ *
437
+ * Find your `appId` in your SidekickDB dashboard.
438
+ *
439
+ * @example
440
+ * import { init } from "@sidekickdb/solidjs"
441
+ *
442
+ * const db = init({ appId: "my-app-id", apiURI: "https://sidekick.example.com" })
443
+ *
444
+ * // You can also provide a schema for type safety and editor autocomplete!
445
+ *
446
+ * import { init } from "@sidekickdb/solidjs"
447
+ * import schema from "../instant.schema.ts";
448
+ *
449
+ * const db = init({ appId: "my-app-id", apiURI: "https://sidekick.example.com", schema })
450
+ */
451
+ export function init<
452
+ Schema extends InstantSchemaDef<any, any, any>,
453
+ UseDates extends boolean = false,
454
+ >(
455
+ config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {
456
+ useDateObjects?: UseDates;
457
+ },
458
+ ): InstantSolidDatabase<Schema, UseDates> {
459
+ const coreDb = core_init<Schema, UseDates>(config, undefined, undefined, {
460
+ '@instantdb/solidjs': version,
461
+ });
462
+ return new InstantSolidDatabase<Schema, UseDates>(coreDb);
463
+ }