@livestore/livestore 0.5.0-dev.0 → 0.5.0-dev.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.
Files changed (82) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/QueryCache.d.ts.map +1 -1
  3. package/dist/SqliteDbWrapper.d.ts +1 -1
  4. package/dist/SqliteDbWrapper.d.ts.map +1 -1
  5. package/dist/SqliteDbWrapper.js +2 -2
  6. package/dist/SqliteDbWrapper.js.map +1 -1
  7. package/dist/SqliteDbWrapper.test.js +2 -2
  8. package/dist/effect/LiveStore.d.ts +54 -2
  9. package/dist/effect/LiveStore.d.ts.map +1 -1
  10. package/dist/effect/LiveStore.js +5 -3
  11. package/dist/effect/LiveStore.js.map +1 -1
  12. package/dist/effect/LiveStore.test.js +2 -2
  13. package/dist/effect/mod.js +2 -2
  14. package/dist/internal/mod.js +2 -2
  15. package/dist/live-queries/base-class.d.ts +1 -1
  16. package/dist/live-queries/base-class.d.ts.map +1 -1
  17. package/dist/live-queries/base-class.js +2 -2
  18. package/dist/live-queries/base-class.js.map +1 -1
  19. package/dist/live-queries/client-document-get-query.d.ts.map +1 -1
  20. package/dist/live-queries/client-document-get-query.js +1 -1
  21. package/dist/live-queries/computed.d.ts +1 -1
  22. package/dist/live-queries/computed.d.ts.map +1 -1
  23. package/dist/live-queries/computed.js +2 -2
  24. package/dist/live-queries/db-query.d.ts +1 -1
  25. package/dist/live-queries/db-query.d.ts.map +1 -1
  26. package/dist/live-queries/db-query.js +5 -5
  27. package/dist/live-queries/db-query.test.js +6 -6
  28. package/dist/live-queries/mod.js +4 -4
  29. package/dist/live-queries/signal.d.ts +1 -1
  30. package/dist/live-queries/signal.d.ts.map +1 -1
  31. package/dist/live-queries/signal.js +1 -1
  32. package/dist/live-queries/signal.test.js +3 -3
  33. package/dist/mod.js +8 -8
  34. package/dist/reactive.d.ts.map +1 -1
  35. package/dist/reactive.test.js +1 -1
  36. package/dist/store/StoreRegistry.d.ts.map +1 -1
  37. package/dist/store/StoreRegistry.js +1 -1
  38. package/dist/store/StoreRegistry.js.map +1 -1
  39. package/dist/store/StoreRegistry.test.js +3 -3
  40. package/dist/store/StoreRegistry.test.js.map +1 -1
  41. package/dist/store/create-store.d.ts +15 -1
  42. package/dist/store/create-store.d.ts.map +1 -1
  43. package/dist/store/create-store.js +14 -5
  44. package/dist/store/create-store.js.map +1 -1
  45. package/dist/store/create-store.test.d.ts +2 -0
  46. package/dist/store/create-store.test.d.ts.map +1 -0
  47. package/dist/store/create-store.test.js +28 -0
  48. package/dist/store/create-store.test.js.map +1 -0
  49. package/dist/store/devtools.js +3 -3
  50. package/dist/store/devtools.js.map +1 -1
  51. package/dist/store/store-commit.test.d.ts +2 -0
  52. package/dist/store/store-commit.test.d.ts.map +1 -0
  53. package/dist/store/store-commit.test.js +85 -0
  54. package/dist/store/store-commit.test.js.map +1 -0
  55. package/dist/store/store-eventstream.test.js +1 -1
  56. package/dist/store/store-types.d.ts.map +1 -1
  57. package/dist/store/store-types.js +1 -1
  58. package/dist/store/store-types.test.js +3 -3
  59. package/dist/store/store.d.ts +13 -14
  60. package/dist/store/store.d.ts.map +1 -1
  61. package/dist/store/store.js +35 -35
  62. package/dist/store/store.js.map +1 -1
  63. package/dist/utils/data-structures.d.ts.map +1 -1
  64. package/dist/utils/dev.d.ts.map +1 -1
  65. package/dist/utils/function-string.d.ts +3 -3
  66. package/dist/utils/function-string.d.ts.map +1 -1
  67. package/dist/utils/stack-info.d.ts.map +1 -1
  68. package/dist/utils/stack-info.test.js +1 -1
  69. package/dist/utils/tests/fixture.d.ts.map +1 -1
  70. package/dist/utils/tests/fixture.js.map +1 -1
  71. package/dist/utils/tests/mod.js +3 -3
  72. package/dist/utils/tests/otel.d.ts +6 -6
  73. package/dist/utils/tests/otel.d.ts.map +1 -1
  74. package/package.json +40 -40
  75. package/src/SqliteDbWrapper.ts +1 -1
  76. package/src/effect/LiveStore.ts +4 -1
  77. package/src/live-queries/__snapshots__/db-query.test.ts.snap +108 -126
  78. package/src/live-queries/base-class.ts +1 -1
  79. package/src/store/create-store.test.ts +35 -0
  80. package/src/store/create-store.ts +32 -11
  81. package/src/store/store-commit.test.ts +137 -0
  82. package/src/store/store.ts +37 -40
@@ -0,0 +1,35 @@
1
+ import { expect } from 'vitest'
2
+
3
+ import { type Adapter, OtelLiveDummy, UnknownError } from '@livestore/common'
4
+ import { Vitest } from '@livestore/utils-dev/node-vitest'
5
+ import { Effect } from '@livestore/utils/effect'
6
+
7
+ import { schema } from '../utils/tests/fixture.ts'
8
+ import { createStore } from './create-store.ts'
9
+
10
+ Vitest.live('validates stateRebuildBatchSize before invoking the adapter', () =>
11
+ Effect.gen(function* () {
12
+ const observedBatchSizes: number[] = []
13
+ const adapter: Adapter = ({ params }) => {
14
+ observedBatchSizes.push(params.stateRebuildBatchSize)
15
+ return Effect.fail(UnknownError.make({ cause: 'adapter sentinel' }))
16
+ }
17
+ const run = (stateRebuildBatchSize?: number) =>
18
+ createStore({
19
+ schema,
20
+ adapter,
21
+ storeId: 'batch-size-test',
22
+ ...(stateRebuildBatchSize === undefined ? {} : { params: { stateRebuildBatchSize } }),
23
+ }).pipe(Effect.scoped, Effect.exit)
24
+
25
+ for (const invalid of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
26
+ expect((yield* run(invalid))._tag).toBe('Failure')
27
+ }
28
+ expect(observedBatchSizes).toEqual([])
29
+
30
+ yield* run()
31
+ yield* run(1)
32
+ yield* run(100_000)
33
+ expect(observedBatchSizes).toEqual([100, 1, 100_000])
34
+ }).pipe(Effect.provide(OtelLiveDummy)),
35
+ )
@@ -14,6 +14,7 @@ import {
14
14
  UnknownError,
15
15
  type LogConfig,
16
16
  } from '@livestore/common'
17
+ import { STATE_REBUILD_BATCH_SIZE_DEFAULT, StateRebuildBatchSizeSchema } from '@livestore/common/leader-thread'
17
18
  import type { LiveStoreSchema } from '@livestore/common/schema'
18
19
  import { isDevEnv, LS_DEV, omitUndefineds } from '@livestore/utils'
19
20
  import {
@@ -137,6 +138,11 @@ export type LiveStoreContextProps<
137
138
  * useStore({ ..., syncPayloadSchema: SyncPayload, syncPayload: { authToken: '...' } })
138
139
  */
139
140
  syncPayload?: TSyncPayloadSchema['Type']
141
+ /** Advanced runtime tuning parameters. */
142
+ params?: {
143
+ /** Number of events read and committed per SQLite state-rebuild batch. Defaults to 100. */
144
+ stateRebuildBatchSize?: number
145
+ }
140
146
  }
141
147
 
142
148
  export interface CreateStoreOptions<
@@ -214,12 +220,21 @@ export interface CreateStoreOptions<
214
220
  * @default undefined
215
221
  */
216
222
  syncPayload?: TSyncPayloadSchema['Type']
217
- /** Options provided to the Store constructor. */
223
+ /** Advanced runtime tuning parameters. */
218
224
  params?: {
219
225
  /** Max events pushed to the leader per write batch. */
220
226
  leaderPushBatchSize?: number
221
227
  /** Chunk size used when the stream replays confirmed events. */
222
228
  eventQueryBatchSize?: number
229
+ /**
230
+ * Number of events read and committed per batch when rebuilding SQLite state from the event log.
231
+ * Lower values reduce per-batch resource usage but perform more queries and savepoints.
232
+ * This is a per-client runtime setting and changing it does not trigger a rebuild.
233
+ *
234
+ * @default 100
235
+ * @minimum 1
236
+ */
237
+ stateRebuildBatchSize?: number
223
238
  }
224
239
  debug?: {
225
240
  instanceId?: string
@@ -297,6 +312,10 @@ export const createStore = <
297
312
  Scope.Scope | OtelTracer.OtelTracer
298
313
  > =>
299
314
  Effect.gen(function* () {
315
+ const stateRebuildBatchSize = yield* Schema.decodeEffect(StateRebuildBatchSizeSchema)(
316
+ params?.stateRebuildBatchSize ?? STATE_REBUILD_BATCH_SIZE_DEFAULT,
317
+ ).pipe(UnknownError.mapToUnknownError)
318
+
300
319
  const lifetimeScope = yield* Scope.make()
301
320
 
302
321
  yield* validateStoreId(storeId)
@@ -346,12 +365,13 @@ export const createStore = <
346
365
  // Drain up to the bound, then force-close the scope regardless. The bound exceeds the
347
366
  // caller-side wait below so an in-flight (but progressing) push is not cut short.
348
367
  const closeFiber = yield* (shutdownSyncProcessor?.(exit) ?? Effect.void).pipe(
349
- Effect.timeout(SHUTDOWN_DRAIN_HARD_TIMEOUT_MS),
350
- Effect.catchTag('TimeoutError', () =>
351
- Effect.logError(
352
- `@livestore/livestore:shutdown: drain exceeded hard bound of ${SHUTDOWN_DRAIN_HARD_TIMEOUT_MS}ms; forcing scope close`,
353
- ),
354
- ),
368
+ Effect.timeoutOrElse({
369
+ duration: SHUTDOWN_DRAIN_HARD_TIMEOUT_MS,
370
+ orElse: () =>
371
+ Effect.logError(
372
+ `@livestore/livestore:shutdown: drain exceeded hard bound of ${SHUTDOWN_DRAIN_HARD_TIMEOUT_MS}ms; forcing scope close`,
373
+ ),
374
+ }),
355
375
  Effect.ensuring(Scope.close(lifetimeScope, exit)),
356
376
  Effect.forkDetach,
357
377
  )
@@ -359,10 +379,10 @@ export const createStore = <
359
379
  // the detached teardown above (which remains bounded by SHUTDOWN_DRAIN_HARD_TIMEOUT_MS).
360
380
  yield* Fiber.join(closeFiber).pipe(
361
381
  Effect.logWarnIfTakesLongerThan({ label: '@livestore/livestore:shutdown', duration: 500 }),
362
- Effect.timeout(1000),
363
- Effect.catchTag('TimeoutError', () =>
364
- Effect.logError('@livestore/livestore:shutdown: Timed out after 1 second'),
365
- ),
382
+ Effect.timeoutOrElse({
383
+ duration: 1000,
384
+ orElse: () => Effect.logError('@livestore/livestore:shutdown: Timed out after 1 second'),
385
+ }),
366
386
  )
367
387
 
368
388
  if (shutdownDeferred !== undefined) {
@@ -388,6 +408,7 @@ export const createStore = <
388
408
  const clientSession: ClientSession = yield* adapter({
389
409
  schema,
390
410
  storeId,
411
+ params: { stateRebuildBatchSize },
391
412
  devtoolsEnabled: getDevtoolsEnabled(disableDevtools),
392
413
  bootStatusQueue,
393
414
  shutdown,
@@ -0,0 +1,137 @@
1
+ import { expect } from 'vitest'
2
+
3
+ import { Vitest } from '@livestore/utils-dev/node-vitest'
4
+ import { Effect } from '@livestore/utils/effect'
5
+
6
+ import { events, makeTodoMvc, tables } from '../utils/tests/fixture.ts'
7
+
8
+ Vitest.describe('Store commit API', () => {
9
+ Vitest.live('should materialize events returned by the commit callback', () =>
10
+ Effect.gen(function* () {
11
+ const store = yield* makeTodoMvc()
12
+ const firstTodo = { id: '1', text: 'Make coffee', completed: false }
13
+ const secondTodo = { id: '2', text: 'Buy groceries', completed: false }
14
+
15
+ // Regression for https://github.com/livestorejs/livestore/issues/1611.
16
+ store.commit(() => {
17
+ expect(store.query(tables.todos)).toEqual([])
18
+ return [events.todoCreated(firstTodo), events.todoCreated(secondTodo)]
19
+ })
20
+
21
+ expect(store.query(tables.todos.orderBy('id', 'asc'))).toEqual([firstTodo, secondTodo])
22
+ }).pipe(Effect.scoped),
23
+ )
24
+
25
+ Vitest.live('should materialize a single callback event', () =>
26
+ Effect.gen(function* () {
27
+ const store = yield* makeTodoMvc()
28
+ const todo = { id: '1', text: 'Make coffee', completed: false }
29
+ const batch = [events.todoCreated(todo)] as const
30
+
31
+ store.commit(() => batch)
32
+
33
+ expect(store.query(tables.todos)).toEqual([todo])
34
+ }).pipe(Effect.scoped),
35
+ )
36
+
37
+ Vitest.live('should accept an empty callback', () =>
38
+ Effect.gen(function* () {
39
+ const store = yield* makeTodoMvc()
40
+
41
+ store.commit(() => [])
42
+
43
+ expect(store.query(tables.todos)).toEqual([])
44
+ }).pipe(Effect.scoped),
45
+ )
46
+
47
+ Vitest.live('should apply no events when the callback throws', () =>
48
+ Effect.gen(function* () {
49
+ const store = yield* makeTodoMvc()
50
+ const todo = { id: '1', text: 'Make coffee', completed: false }
51
+ const error = new Error('Callback failed')
52
+
53
+ expect(() =>
54
+ store.commit(() => {
55
+ throw error
56
+ }),
57
+ ).toThrow(error)
58
+
59
+ expect(store.query(tables.todos)).toEqual([])
60
+ store.commit(events.todoCreated(todo))
61
+ expect(store.query(tables.todos)).toEqual([todo])
62
+ }).pipe(Effect.scoped),
63
+ )
64
+
65
+ Vitest.live('should commit multiple returned event types in order', () =>
66
+ Effect.gen(function* () {
67
+ const store = yield* makeTodoMvc()
68
+ const todo = { id: '1', text: 'Make coffee', completed: false }
69
+
70
+ store.commit(() => [events.todoCreated(todo), events.todoCompleted({ id: todo.id })])
71
+
72
+ expect(store.query(tables.todos)).toEqual([{ ...todo, completed: true }])
73
+ }).pipe(Effect.scoped),
74
+ )
75
+
76
+ for (const options of [{}, { label: 'Create todo' }]) {
77
+ Vitest.live(`should accept callback options ${JSON.stringify(options)}`, () =>
78
+ Effect.gen(function* () {
79
+ const store = yield* makeTodoMvc()
80
+ const todo = { id: '1', text: 'Make coffee', completed: false }
81
+
82
+ store.commit(options, () => [events.todoCreated(todo)])
83
+
84
+ expect(store.query(tables.todos)).toEqual([todo])
85
+ }).pipe(Effect.scoped),
86
+ )
87
+ }
88
+
89
+ Vitest.live('should reject callback values that are not event arrays', () =>
90
+ Effect.gen(function* () {
91
+ const store = yield* makeTodoMvc()
92
+
93
+ expect(() => Reflect.apply(store.commit, store, [() => undefined])).toThrow(
94
+ 'store.commit callback must synchronously return an array of events',
95
+ )
96
+ expect(() => Reflect.apply(store.commit, store, [() => Promise.resolve([])])).toThrow(
97
+ 'store.commit callback must synchronously return an array of events',
98
+ )
99
+
100
+ expect(store.query(tables.todos)).toEqual([])
101
+ }).pipe(Effect.scoped),
102
+ )
103
+
104
+ Vitest.live('should reject non-array and asynchronous callbacks at the type level', () =>
105
+ Effect.gen(function* () {
106
+ const store = yield* makeTodoMvc()
107
+
108
+ // Keep invalid calls uninvoked so TypeScript checks the public overloads without executing them.
109
+ const assertRejectedCallbackTypes = () => {
110
+ // @ts-expect-error Commit callbacks must return an event array.
111
+ store.commit(() => {})
112
+ // @ts-expect-error Commit callbacks do not receive an event emitter.
113
+ store.commit((emit: () => void) => {
114
+ emit()
115
+ return []
116
+ })
117
+ // @ts-expect-error Commit callbacks must be synchronous.
118
+ store.commit(async () => [])
119
+ }
120
+
121
+ expect(assertRejectedCallbackTypes).toBeTypeOf('function')
122
+ }).pipe(Effect.scoped),
123
+ )
124
+
125
+ Vitest.live('should still accept direct events with options and no events', () =>
126
+ Effect.gen(function* () {
127
+ const store = yield* makeTodoMvc()
128
+ const todo = { id: '1', text: 'Make coffee', completed: false }
129
+
130
+ store.commit()
131
+ store.commit({ label: 'Empty commit' })
132
+ store.commit({ label: 'Create and complete' }, events.todoCreated(todo), events.todoCompleted({ id: todo.id }))
133
+
134
+ expect(store.query(tables.todos)).toEqual([{ ...todo, completed: true }])
135
+ }).pipe(Effect.scoped),
136
+ )
137
+ })
@@ -821,19 +821,16 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
821
821
  * events.todoCompleted({ id: todoId }))
822
822
  * ```
823
823
  *
824
- * For more advanced transaction scenarios, you can pass a synchronous function to `commit` which will receive a callback
825
- * to which you can pass multiple events to be committed in the same database transaction.
826
- * Under the hood this will simply collect all events and apply them in a single database transaction.
824
+ * For conditional batches, you can pass a synchronous function to `commit` which returns an array of events.
825
+ * LiveStore evaluates the function before applying the returned events in a single database transaction.
827
826
  *
828
827
  * @example
829
828
  * ```ts
830
- * store.commit((commit) => {
829
+ * store.commit(() => {
831
830
  * const todoId = nanoid()
832
- * if (Math.random() > 0.5) {
833
- * commit(events.todoCreated({ id: todoId, text: 'Make coffee' }))
834
- * } else {
835
- * commit(events.todoCompleted({ id: todoId }))
836
- * }
831
+ * return Math.random() > 0.5
832
+ * ? [events.todoCreated({ id: todoId, text: 'Make coffee' })]
833
+ * : [events.todoCompleted({ id: todoId })]
837
834
  * })
838
835
  * ```
839
836
  *
@@ -855,25 +852,16 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
855
852
  */
856
853
  commit: {
857
854
  <const TCommitArg extends ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>>(...list: TCommitArg): void
858
- (
859
- txn: <const TCommitArg extends ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>>(
860
- ...list: TCommitArg
861
- ) => void,
862
- ): void
855
+ (buildEvents: CommitBatchBuilder<TSchema>): void
863
856
  <const TCommitArg extends ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>>(
864
857
  options: StoreCommitOptions,
865
858
  ...list: TCommitArg
866
859
  ): void
867
- (
868
- options: StoreCommitOptions,
869
- txn: <const TCommitArg extends ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>>(
870
- ...list: TCommitArg
871
- ) => void,
872
- ): void
873
- } = (firstEventOrTxnFnOrOptions: any, ...restEvents: any[]) => {
860
+ (options: StoreCommitOptions, buildEvents: CommitBatchBuilder<TSchema>): void
861
+ } = (firstEventOrBatchBuilderOrOptions: any, ...restEvents: any[]) => {
874
862
  this.checkShutdown('commit')
875
863
 
876
- const { events, options } = this.getCommitArgs(firstEventOrTxnFnOrOptions, restEvents)
864
+ const { events, options } = this.getCommitArgs(firstEventOrBatchBuilderOrOptions, restEvents)
877
865
 
878
866
  Effect.gen({ self: this }, function* () {
879
867
  const commitsSpan = otel.trace.getSpan(this[StoreInternalsSymbol].otel.commitsSpanContext)
@@ -1271,33 +1259,42 @@ export class Store<TSchema extends LiveStoreSchema = LiveStoreSchema.Any, TConte
1271
1259
  effect.pipe(Effect.tapCauseLogPretty, Effect.runPromiseWith(this[StoreInternalsSymbol].effectContext.services))
1272
1260
 
1273
1261
  private getCommitArgs = (
1274
- firstEventOrTxnFnOrOptions: any,
1262
+ firstEventOrBatchBuilderOrOptions: any,
1275
1263
  restEvents: any[],
1276
1264
  ): {
1277
1265
  events: LiveStoreEvent.Input.ForSchema<TSchema>[]
1278
1266
  options: StoreCommitOptions | undefined
1279
1267
  } => {
1280
- let events: LiveStoreEvent.Input.ForSchema<TSchema>[]
1268
+ let events: LiveStoreEvent.Input.ForSchema<TSchema>[] = []
1281
1269
  let options: StoreCommitOptions | undefined
1282
-
1283
- if (typeof firstEventOrTxnFnOrOptions === 'function') {
1284
- // TODO ensure that function is synchronous and isn't called in a async way (also write tests for this)
1285
- events = firstEventOrTxnFnOrOptions((arg: any) => events.push(arg))
1286
- } else if (
1287
- firstEventOrTxnFnOrOptions?.label !== undefined ||
1288
- firstEventOrTxnFnOrOptions?.skipRefresh !== undefined ||
1289
- firstEventOrTxnFnOrOptions?.otelContext !== undefined ||
1290
- firstEventOrTxnFnOrOptions?.spanLinks !== undefined
1270
+ let commitArgs = [firstEventOrBatchBuilderOrOptions, ...restEvents]
1271
+
1272
+ if (
1273
+ firstEventOrBatchBuilderOrOptions?.label !== undefined ||
1274
+ firstEventOrBatchBuilderOrOptions?.skipRefresh !== undefined ||
1275
+ firstEventOrBatchBuilderOrOptions?.otelContext !== undefined ||
1276
+ firstEventOrBatchBuilderOrOptions?.spanLinks !== undefined ||
1277
+ typeof restEvents[0] === 'function'
1291
1278
  ) {
1292
- options = firstEventOrTxnFnOrOptions
1293
- events = restEvents
1294
- } else if (firstEventOrTxnFnOrOptions === undefined) {
1295
- // When `commit` is called with no arguments (which sometimes happens when dynamically filtering events)
1296
- events = []
1297
- } else {
1298
- events = [firstEventOrTxnFnOrOptions, ...restEvents]
1279
+ options = firstEventOrBatchBuilderOrOptions
1280
+ commitArgs = restEvents
1281
+ }
1282
+
1283
+ const firstEventOrBatchBuilder = commitArgs[0]
1284
+ if (typeof firstEventOrBatchBuilder === 'function') {
1285
+ const builtEvents: unknown = firstEventOrBatchBuilder()
1286
+ if (Array.isArray(builtEvents) === false) {
1287
+ throw new TypeError('store.commit callback must synchronously return an array of events')
1288
+ }
1289
+
1290
+ // Copy the completed batch so callers cannot mutate the array while it enters the commit pipeline.
1291
+ events = [...builtEvents]
1292
+ } else if (firstEventOrBatchBuilder !== undefined) {
1293
+ events = commitArgs
1299
1294
  }
1300
1295
 
1301
1296
  return { events, options }
1302
1297
  }
1303
1298
  }
1299
+
1300
+ type CommitBatchBuilder<TSchema extends LiveStoreSchema> = () => ReadonlyArray<LiveStoreEvent.Input.ForSchema<TSchema>>