event-sourced-collection 0.0.5 → 0.0.6

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 CHANGED
@@ -278,35 +278,85 @@ After setup you get `db.collections.users`, `db.collections.todos`, `db.collecti
278
278
 
279
279
  #### Collection indexes
280
280
 
281
- Add one or more indexes per collection via the optional `indexes` array on each collection definition. Each entry becomes a `collection.createIndex(select, { name?, indexType? })` call during DB init no post-`ensureDb` setup required.
281
+ TanStack DB indexes are **opt-in**. Declare them on each collection in the `collections` registry the package calls `collection.createIndex(select, { name?, indexType })` for you and keeps them registered across the collection lifecycle (including after SQLite hydration when the collection becomes `ready` again).
282
282
 
283
- `indexType` comes from `@tanstack/db` (e.g. `BasicIndex`). Use `name` when a collection has multiple indexes so they are easy to tell apart.
283
+ **Requirements**
284
+
285
+ - Import `BasicIndex` from `@tanstack/db` and pass it as `indexType` on every index entry.
286
+ - The `select` callback must return the **same field** you filter, join, or `orderBy` on in `useLiveQuery`.
287
+ - Use `name` when a collection has more than one index.
288
+
289
+ **Shape**
284
290
 
285
291
  ```typescript
286
292
  import { BasicIndex } from "@tanstack/db";
293
+ import type { CollectionDef } from "event-sourced-collection";
287
294
 
288
- // Multiple indexes: add more objects to the array
289
- todos: {
290
- getKey: (todo: Todo) => todo.id,
291
- indexes: [
292
- { select: (todo: Todo) => todo.id, indexType: BasicIndex, name: "by-id" },
293
- { select: (todo: Todo) => todo.userId, indexType: BasicIndex, name: "by-user" },
294
- { select: (todo: Todo) => todo.status, indexType: BasicIndex, name: "by-status" },
295
- { select: (todo: Todo) => todo.title, indexType: BasicIndex, name: "by-title" },
296
- ],
297
- },
295
+ type SavedMovieRef = { movieId: number; title: string; addedAt: number };
298
296
 
299
- // Single index: a one-element array works the same way
300
- favorites: {
301
- getKey: (item) => item.movieId,
302
- indexes: [{ select: (item) => item.movieId, indexType: BasicIndex }],
297
+ // In your AppCollectionDefs / collections registry:
298
+ favorites: CollectionDef<SavedMovieRef, number>;
299
+ ```
300
+
301
+ ```typescript
302
+ collections: {
303
+ todos: {
304
+ getKey: (todo: Todo) => todo.id,
305
+ indexes: [
306
+ { select: (todo: Todo) => todo.id, indexType: BasicIndex, name: "by-id" },
307
+ { select: (todo: Todo) => todo.userId, indexType: BasicIndex, name: "by-user" },
308
+ { select: (todo: Todo) => todo.status, indexType: BasicIndex, name: "by-status" },
309
+ ],
310
+ },
311
+
312
+ favorites: {
313
+ getKey: (item: SavedMovieRef) => item.movieId,
314
+ indexes: [{ select: (item) => item.movieId, indexType: BasicIndex, name: "by-movie-id" }],
315
+ },
316
+
317
+ settings: { getKey: (settings: AppSettings) => settings.id },
303
318
  },
319
+ ```
304
320
 
305
- // No indexes: omit the field entirely
306
- settings: { getKey: (settings: AppSettings) => settings.id },
321
+ **Joins** index the field on the **joined** collection (the right-hand side), not the driving collection:
322
+
323
+ ```typescript
324
+ import { eq, useLiveQuery } from "@tanstack/react-db";
325
+ import { db } from "./collections";
326
+ import { moviesCollection } from "./movies-collection";
327
+
328
+ // favorites needs an index on movieId because the join is eq(movie.id, favorite.movieId)
329
+ const { data } = useLiveQuery((q) =>
330
+ q
331
+ .from({ movie: moviesCollection })
332
+ .leftJoin({ favorite: db.collections.favorites }, ({ movie, favorite }) =>
333
+ eq(movie.id, favorite.movieId),
334
+ )
335
+ .select(({ movie, favorite }) => ({ movie, isFavorite: favorite !== undefined })),
336
+ );
307
337
  ```
308
338
 
309
- Indexes speed up `useLiveQuery` filters, joins, and `orderBy` on those fields. Match indexes to how you query — e.g. `by-user` for `where(({ todo }) => eq(todo.userId, userId))`, `by-title` for title search.
339
+ Without that index, TanStack DB logs a warning and falls back to loading the entire `favorites` collection for each join.
340
+
341
+ **Filters and sort** — match indexes to your queries:
342
+
343
+ | Query pattern | Index `select` |
344
+ | ------------- | -------------- |
345
+ | `eq(todo.userId, userId)` | `(todo) => todo.userId` |
346
+ | `eq(todo.status, "pending")` | `(todo) => todo.status` |
347
+ | `orderBy(({ todo }) => todo.title)` | `(todo) => todo.title` |
348
+
349
+ **What you do not need**
350
+
351
+ - Do not call `collection.createIndex()` yourself after `ensureDb()` when using this package — declare indexes in `collections` instead.
352
+ - Do not enable `autoIndex: 'eager'` for collections created here; explicit `indexes` + `BasicIndex` is the supported pattern.
353
+
354
+ **Debugging** — after `await ensureDb()`, check that indexes exist:
355
+
356
+ ```typescript
357
+ db.collections.favorites.getIndexMetadata();
358
+ // non-empty array means indexes are registered
359
+ ```
310
360
 
311
361
  ### 5. App settings (`app-settings.ts`)
312
362
 
package/dist/browser.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as createEventSourcedDB, t as createLazySingleton } from "./lazy-singleton-BG02GHLj.mjs";
1
+ import { n as createEventSourcedDB, t as createLazySingleton } from "./lazy-singleton-CB50yOVo.mjs";
2
2
  //#region src/platforms/browser-wa-sqlite-driver.ts
3
3
  function assertTransactionCallbackHasDriverArg(fn) {
4
4
  if (fn.length > 0) return;
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as SyncPullError, i as createEventSourcedLogger, n as createEventSourcedDB, o as SyncPushError, r as generateEventId, s as createHttpTransport, t as createLazySingleton } from "./lazy-singleton-BG02GHLj.mjs";
1
+ import { a as SyncPullError, i as createEventSourcedLogger, n as createEventSourcedDB, o as SyncPushError, r as generateEventId, s as createHttpTransport, t as createLazySingleton } from "./lazy-singleton-CB50yOVo.mjs";
2
2
  export { SyncPullError, SyncPushError, createEventSourcedDB, createEventSourcedLogger, createHttpTransport, createLazySingleton, generateEventId };
@@ -174,6 +174,7 @@ async function createEventSourcedDB(config) {
174
174
  getKey,
175
175
  persistence: config.persistence,
176
176
  schemaVersion: def.schemaVersion ?? defaultSchemaVersion,
177
+ gcTime: Number.POSITIVE_INFINITY,
177
178
  onInsert: createMutationHook(outbox, collectionId, "insert", seq, log),
178
179
  onUpdate: createMutationHook(outbox, collectionId, "update", seq, log),
179
180
  onDelete: createMutationHook(outbox, collectionId, "delete", seq, log)
@@ -332,16 +333,21 @@ function createMetaCollection(config, id, getKey, schemaVersion) {
332
333
  function applyCollectionIndexes(collection, collectionId, indexes, log) {
333
334
  if (!indexes?.length) return;
334
335
  const indexable = collection;
335
- for (const indexDef of indexes) {
336
- indexable.createIndex(indexDef.select, {
337
- name: indexDef.name,
338
- indexType: indexDef.indexType
339
- });
340
- log.debug("registered collection index", {
341
- collectionId,
342
- name: indexDef.name
343
- });
344
- }
336
+ const register = () => {
337
+ if ((indexable.getIndexMetadata?.().length ?? 0) > 0) return;
338
+ for (const indexDef of indexes) {
339
+ indexable.createIndex(indexDef.select, {
340
+ name: indexDef.name,
341
+ indexType: indexDef.indexType
342
+ });
343
+ log.debug("registered collection index", {
344
+ collectionId,
345
+ name: indexDef.name
346
+ });
347
+ }
348
+ };
349
+ register();
350
+ indexable.on?.("status:ready", register);
345
351
  }
346
352
  function createMutationHook(outbox, collectionId, type, seq, log) {
347
353
  return async (params) => {
@@ -661,4 +667,4 @@ function createLazySingleton(factory, options = {}) {
661
667
  //#endregion
662
668
  export { SyncPullError as a, createEventSourcedLogger as i, createEventSourcedDB as n, SyncPushError as o, generateEventId as r, createHttpTransport as s, createLazySingleton as t };
663
669
 
664
- //# sourceMappingURL=lazy-singleton-BG02GHLj.mjs.map
670
+ //# sourceMappingURL=lazy-singleton-CB50yOVo.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lazy-singleton-CB50yOVo.mjs","names":[],"sources":["../src/sync.ts","../src/utils/logger.ts","../src/create-event-sourced-db.ts","../src/lazy-singleton.ts"],"sourcesContent":["import type {\n OutboundEvent,\n PullEventsFn,\n PullResponse,\n PushConfirmation,\n PushEventsFn,\n PushResponse,\n SyncHandlersConfig,\n SyncTransport,\n SyncUrlConfig,\n} from \"./types\";\n\nexport type NormalizedSyncTransport = {\n push?: PushEventsFn;\n pull?: (since: number) => Promise<PullResponse>;\n};\n\ntype HeaderConfig = SyncHandlersConfig[\"headers\"];\n\nexport function createHttpTransport(config: SyncUrlConfig): SyncTransport {\n return {\n push: createHttpPushEvents(config.push, config.headers),\n pull: createHttpPullEvents(config.pull, config.headers),\n };\n}\n\nexport function createSyncTransport(\n config?: SyncHandlersConfig | SyncUrlConfig | SyncTransport,\n): NormalizedSyncTransport | null {\n if (!config) {\n return null;\n }\n\n if (isTransport(config)) {\n return {\n push: config.push,\n pull: config.pull,\n };\n }\n\n const pushUrl = getPushUrl(config);\n const pullUrl = getPullUrl(config);\n\n const push = \"pushEvents\" in config && config.pushEvents\n ? config.pushEvents\n : pushUrl\n ? createHttpPushEvents(pushUrl, config.headers)\n : undefined;\n\n const pullEvents = \"pullEvents\" in config ? config.pullEvents : undefined;\n const pull = pullEvents\n ? createPullFromHandler(pullEvents)\n : pullUrl\n ? createHttpPullEvents(pullUrl, config.headers)\n : undefined;\n\n if (!push && !pull) {\n return null;\n }\n\n return { push, pull };\n}\n\nexport function normalizePushResponse(\n response: PushResponse | ReadonlyArray<PushConfirmation>,\n): PushResponse {\n if (isConfirmationArray(response)) {\n return { confirmed: response };\n }\n\n return {\n confirmed: response.confirmed,\n failed: response.failed,\n };\n}\n\nfunction isConfirmationArray(\n response: PushResponse | ReadonlyArray<PushConfirmation>,\n): response is ReadonlyArray<PushConfirmation> {\n return Array.isArray(response);\n}\n\nfunction createHttpPushEvents(url: string, headers: HeaderConfig): PushEventsFn {\n return async (events: ReadonlyArray<OutboundEvent>): Promise<PushResponse> => {\n if (events.length === 0) return { confirmed: [] };\n\n const resolvedHeaders = await resolveHeaders(headers);\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", ...resolvedHeaders },\n body: JSON.stringify(events),\n });\n\n if (!response.ok) {\n throw new SyncPushError(response.status, await response.text());\n }\n\n return response.json() as Promise<PushResponse>;\n };\n}\n\nfunction createPullFromHandler(pullEvents: PullEventsFn): (since: number) => Promise<PullResponse> {\n return (since: number) => pullEvents({ since });\n}\n\nfunction createHttpPullEvents(\n url: string,\n headers: HeaderConfig,\n): (since: number) => Promise<PullResponse> {\n return async (since: number): Promise<PullResponse> => {\n const resolvedHeaders = await resolveHeaders(headers);\n const pullUrl = appendSince(url, since);\n\n const response = await fetch(pullUrl, {\n headers: { Accept: \"application/json\", ...resolvedHeaders },\n });\n\n if (!response.ok) {\n throw new SyncPullError(response.status, await response.text());\n }\n\n return response.json() as Promise<PullResponse>;\n };\n}\n\nasync function resolveHeaders(headers: HeaderConfig): Promise<Record<string, string>> {\n if (!headers) return {};\n if (typeof headers === \"function\") return headers();\n return headers;\n}\n\nfunction appendSince(url: string, since: number): string {\n const separator = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${separator}since=${encodeURIComponent(String(since))}`;\n}\n\nfunction getPushUrl(config: SyncHandlersConfig | SyncUrlConfig): string | undefined {\n if (\"pushUrl\" in config && config.pushUrl) {\n return config.pushUrl;\n }\n\n if (\"push\" in config && typeof config.push === \"string\") {\n return config.push;\n }\n\n return undefined;\n}\n\nfunction getPullUrl(config: SyncHandlersConfig | SyncUrlConfig): string | undefined {\n if (\"pullUrl\" in config && config.pullUrl) {\n return config.pullUrl;\n }\n\n if (\"pull\" in config && typeof config.pull === \"string\") {\n return config.pull;\n }\n\n return undefined;\n}\n\nexport class SyncPushError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n ) {\n super(`Event push failed: HTTP ${status}`);\n this.name = \"SyncPushError\";\n }\n}\n\nexport class SyncPullError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n ) {\n super(`Event pull failed: HTTP ${status}`);\n this.name = \"SyncPullError\";\n }\n}\n\nexport function isTransport(\n value: SyncHandlersConfig | SyncUrlConfig | SyncTransport,\n): value is SyncTransport {\n return \"push\" in value && typeof value.push === \"function\";\n}\n","export type EventSourcedLogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type EventSourcedLogger = {\n debug: (message: string, data?: Record<string, unknown>) => void;\n info: (message: string, data?: Record<string, unknown>) => void;\n warn: (message: string, data?: Record<string, unknown>) => void;\n error: (message: string, data?: Record<string, unknown>) => void;\n};\n\nconst noopLogger: EventSourcedLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\nconst LOG_PREFIX = \"[event-sourced]\";\n\nexport function createEventSourcedLogger(\n debug?: boolean | EventSourcedLogger,\n): EventSourcedLogger {\n if (debug === undefined || debug === false) {\n return noopLogger;\n }\n\n if (typeof debug === \"object\") {\n return debug;\n }\n\n return {\n debug: (message, data) => {\n if (data === undefined) {\n console.debug(LOG_PREFIX, message);\n return;\n }\n console.debug(LOG_PREFIX, message, data);\n },\n info: (message, data) => {\n if (data === undefined) {\n console.info(LOG_PREFIX, message);\n return;\n }\n console.info(LOG_PREFIX, message, data);\n },\n warn: (message, data) => {\n if (data === undefined) {\n console.warn(LOG_PREFIX, message);\n return;\n }\n console.warn(LOG_PREFIX, message, data);\n },\n error: (message, data) => {\n if (data === undefined) {\n console.error(LOG_PREFIX, message);\n return;\n }\n console.error(LOG_PREFIX, message, data);\n },\n };\n}\n","import type { Collection, IndexConstructor } from \"@tanstack/db\";\nimport { createSyncTransport, normalizePushResponse } from \"./sync\";\nimport type { NormalizedSyncTransport } from \"./sync\";\nimport type { EventSourcedLogger } from \"./utils/logger\";\nimport { createEventSourcedLogger } from \"./utils/logger\";\nimport { generateEventId } from \"./utils/uuid\";\nimport type {\n CollectionMap,\n EventSourcedDB,\n EventSourcedDBConfig,\n InboxEntry,\n MutationType,\n OutboundEvent,\n OutboxEntry,\n ServerEvent,\n SyncResult,\n ManualSyncResult,\n} from \"./types\";\n\nconst OUTBOX_ID = \"outbox\";\nconst INBOX_ID = \"inbox\";\nconst RESERVED_IDS = new Set<string>([OUTBOX_ID, INBOX_ID]);\n\ntype CollectionDefConstraint = {\n getKey: (state: never) => string | number;\n schemaVersion?: number;\n indexes?: ReadonlyArray<{\n select: (row: never) => unknown;\n name?: string;\n indexType?: IndexConstructor<string | number>;\n }>;\n};\n\ntype ReplayMutation = {\n mutationId: string;\n type: MutationType;\n key: string | number;\n modified: Record<string, unknown>;\n original: Record<string, unknown>;\n changes: Record<string, unknown>;\n collection: AcceptMutationsCollection;\n};\n\ntype AcceptMutationsCollection = {\n id?: string;\n utils: {\n acceptMutations?: (transaction: { mutations: Array<ReplayMutation> }) => Promise<void> | void;\n };\n};\n\ntype MutationHookParams = {\n transaction: {\n mutations: ReadonlyArray<{\n mutationId: string;\n key: string | number;\n modified: Record<string, unknown>;\n original: Record<string, unknown>;\n }>;\n };\n};\n\ntype SeqCounter = { value: number };\n\ntype MetaCollectionFactory = Pick<\n EventSourcedDBConfig<Record<string, CollectionDefConstraint>>,\n \"createCollection\" | \"persistedCollectionOptions\" | \"persistence\"\n>;\n\nexport async function createEventSourcedDB<\n const TDefs extends Record<string, CollectionDefConstraint>,\n>(config: EventSourcedDBConfig<TDefs>): Promise<EventSourcedDB<TDefs>> {\n assertReservedNamesAvailable(config.collections);\n\n const log = createEventSourcedLogger(config.debug);\n\n const transport = createSyncTransport(config.sync);\n let syncEnabled = config.syncEnabled ?? true;\n\n log.info(\"creating event-sourced db\", {\n collectionIds: Object.keys(config.collections),\n hasTransport: transport !== null,\n syncEnabled,\n });\n\n const defaultSchemaVersion = config.schemaVersion ?? 1;\n const seq: SeqCounter = { value: 0 };\n\n const outbox = createMetaCollection<OutboxEntry>(\n config,\n OUTBOX_ID,\n (entry) => entry.eventId,\n defaultSchemaVersion,\n );\n\n const inbox = createMetaCollection<InboxEntry>(\n config,\n INBOX_ID,\n (entry) => entry.eventId,\n defaultSchemaVersion,\n );\n\n const userCollections = {} as CollectionMap<TDefs>;\n\n for (const collectionId of Object.keys(config.collections)) {\n const def = config.collections[collectionId]!;\n const getKey = def.getKey as (item: Record<string, unknown>) => string | number;\n\n const options = config.persistedCollectionOptions<Record<string, unknown>, string | number>({\n id: collectionId,\n getKey,\n persistence: config.persistence,\n schemaVersion: def.schemaVersion ?? defaultSchemaVersion,\n gcTime: Number.POSITIVE_INFINITY,\n onInsert: createMutationHook(outbox, collectionId, \"insert\", seq, log),\n onUpdate: createMutationHook(outbox, collectionId, \"update\", seq, log),\n onDelete: createMutationHook(outbox, collectionId, \"delete\", seq, log),\n });\n\n const collection = config.createCollection(options);\n applyCollectionIndexes(collection, collectionId, def.indexes, log);\n const hasAcceptMutations = Boolean(\n (collection as AcceptMutationsCollection).utils?.acceptMutations,\n );\n\n log.debug(\"registered collection\", {\n collectionId,\n hasAcceptMutations,\n });\n\n (userCollections as Record<string, unknown>)[collectionId] = collection;\n }\n\n const collections = {\n ...(userCollections as CollectionMap<TDefs>),\n outbox,\n inbox,\n } as EventSourcedDB<TDefs>[\"collections\"];\n\n const replayTargets = collections as unknown as Record<string, AcceptMutationsCollection>;\n\n const subscriptions = [\n outbox.subscribeChanges(() => {}),\n inbox.subscribeChanges(() => {}),\n ];\n\n await outbox.preload();\n await inbox.preload();\n\n seq.value = nextLocalSeq(outbox);\n\n log.info(\"preloaded meta collections\", {\n outboxCount: outbox.state.size,\n inboxCount: inbox.state.size,\n nextLocalSeq: seq.value,\n });\n\n await replayInbox(inbox, replayTargets, log);\n\n async function sync(): Promise<SyncResult> {\n if (!syncEnabled) {\n log.debug(\"sync skipped: sync disabled\");\n return { pushed: 0, pulled: 0, errors: [] };\n }\n\n if (!transport) {\n log.warn(\"sync skipped: no transport configured\");\n return { pushed: 0, pulled: 0, errors: [] };\n }\n\n log.info(\"sync started\");\n\n await outbox.preload();\n await inbox.preload();\n\n const errors: Error[] = [];\n let pushed = 0;\n let pulled = 0;\n\n try {\n if (transport.push) {\n pushed = await pushOutbox(outbox, transport.push, log);\n } else {\n log.debug(\"push skipped: no push transport configured\");\n }\n } catch (err) {\n const error = toError(err);\n log.error(\"push outbox failed\", { message: error.message });\n errors.push(error);\n }\n\n try {\n if (transport.pull) {\n pulled = await pullInbox(outbox, inbox, transport.pull, replayTargets, log);\n } else {\n log.debug(\"pull skipped: no pull transport configured\");\n }\n } catch (err) {\n const error = toError(err);\n log.error(\"pull inbox failed\", { message: error.message });\n errors.push(error);\n }\n\n log.info(\"sync finished\", { pushed, pulled, errorCount: errors.length });\n\n return { pushed, pulled, errors };\n }\n\n async function manualSync(): Promise<ManualSyncResult> {\n log.info(\"manual sync started\");\n\n await outbox.preload();\n await inbox.preload();\n\n const errors: Error[] = [];\n let pushed = 0;\n let pulled = 0;\n let replayed = 0;\n\n if (syncEnabled && transport) {\n try {\n if (transport.push) {\n pushed = await pushOutbox(outbox, transport.push, log);\n } else {\n log.debug(\"manual sync push skipped: no push transport configured\");\n }\n } catch (err) {\n const error = toError(err);\n log.error(\"manual sync push failed\", { message: error.message });\n errors.push(error);\n }\n\n try {\n if (transport.pull) {\n pulled = await pullInbox(outbox, inbox, transport.pull, replayTargets, log);\n } else {\n log.debug(\"manual sync pull skipped: no pull transport configured\");\n }\n } catch (err) {\n const error = toError(err);\n log.error(\"manual sync pull failed\", { message: error.message });\n errors.push(error);\n }\n } else if (!syncEnabled) {\n log.debug(\"manual sync push/pull skipped: sync disabled\");\n } else {\n log.warn(\"manual sync: no transport configured, skipping push/pull\");\n }\n\n try {\n replayed = await replayInbox(inbox, replayTargets, log);\n } catch (err) {\n const error = toError(err);\n log.error(\"manual sync replay failed\", { message: error.message });\n errors.push(error);\n }\n\n log.info(\"manual sync finished\", { pushed, pulled, replayed, errorCount: errors.length });\n\n return { pushed, pulled, replayed, errors };\n }\n\n function getSyncEnabled(): boolean {\n return syncEnabled;\n }\n\n function setSyncEnabled(enabled: boolean): void {\n syncEnabled = enabled;\n log.debug(\"sync enabled updated\", { syncEnabled: enabled });\n }\n\n function dispose(): void {\n log.debug(\"disposing event-sourced db\");\n for (const subscription of subscriptions) {\n subscription.unsubscribe();\n }\n }\n\n return { collections, sync, manualSync, getSyncEnabled, setSyncEnabled, dispose };\n}\n\nfunction createMetaCollection<TEntry extends object>(\n config: MetaCollectionFactory,\n id: string,\n getKey: (entry: TEntry) => string,\n schemaVersion: number,\n): Collection<TEntry, string> {\n const options = config.persistedCollectionOptions<TEntry, string>({\n id,\n getKey,\n persistence: config.persistence,\n schemaVersion,\n });\n\n return config.createCollection(options);\n}\n\ntype IndexableCollection = {\n createIndex: (\n indexCallback: (row: Record<string, unknown>) => unknown,\n config?: {\n name?: string;\n indexType?: IndexConstructor<string | number>;\n },\n ) => unknown;\n getIndexMetadata?: () => ReadonlyArray<unknown>;\n on?: (event: \"status:ready\", callback: () => void) => () => void;\n};\n\nfunction applyCollectionIndexes(\n collection: Collection<Record<string, unknown>, string | number>,\n collectionId: string,\n indexes: CollectionDefConstraint[\"indexes\"],\n log: EventSourcedLogger,\n): void {\n if (!indexes?.length) {\n return;\n }\n\n const indexable = collection as IndexableCollection;\n\n const register = (): void => {\n if ((indexable.getIndexMetadata?.().length ?? 0) > 0) {\n return;\n }\n\n for (const indexDef of indexes) {\n indexable.createIndex(indexDef.select as (row: Record<string, unknown>) => unknown, {\n name: indexDef.name,\n indexType: indexDef.indexType,\n });\n\n log.debug(\"registered collection index\", {\n collectionId,\n name: indexDef.name,\n });\n }\n };\n\n register();\n\n indexable.on?.(\"status:ready\", register);\n}\n\nfunction createMutationHook(\n outbox: Collection<OutboxEntry, string>,\n collectionId: string,\n type: MutationType,\n seq: SeqCounter,\n log: EventSourcedLogger,\n) {\n return async (params: MutationHookParams): Promise<Record<string, unknown>> => {\n for (const mutation of params.transaction.mutations) {\n const payload = type === \"delete\" ? mutation.original : mutation.modified;\n\n const entry: OutboxEntry = {\n eventId: generateEventId(),\n collectionId,\n type,\n key: mutation.key,\n payload,\n timestamp: Date.now(),\n localSeq: seq.value++,\n globalSeq: null,\n sync: false,\n syncStatus: \"pending\",\n attemptCount: 0,\n lastAttemptAt: null,\n lastError: null,\n lastErrorCode: null,\n retryable: null,\n };\n\n await outbox.insert(entry).isPersisted.promise;\n\n log.debug(\"outbox entry created\", {\n eventId: entry.eventId,\n collectionId,\n type,\n key: entry.key,\n localSeq: entry.localSeq,\n });\n }\n\n return {};\n };\n}\n\nasync function pushOutbox(\n outbox: Collection<OutboxEntry, string>,\n push: NonNullable<NormalizedSyncTransport[\"push\"]>,\n log: EventSourcedLogger,\n): Promise<number> {\n const pending = [...outbox.state.values()]\n .filter((entry) => !entry.sync && entry.syncStatus !== \"failed\")\n .sort((a, b) => a.localSeq - b.localSeq);\n\n log.debug(\"push outbox\", { pendingCount: pending.length });\n\n if (pending.length === 0) return 0;\n\n const attemptAt = Date.now();\n\n for (const entry of pending) {\n await outbox\n .update(entry.eventId, (draft) => {\n draft.syncStatus = \"pending\";\n draft.attemptCount = (draft.attemptCount ?? 0) + 1;\n draft.lastAttemptAt = attemptAt;\n draft.lastError = null;\n draft.lastErrorCode = null;\n draft.retryable = null;\n })\n .isPersisted.promise;\n }\n\n const outbound: OutboundEvent[] = pending.map((entry) => ({\n eventId: entry.eventId,\n collectionId: entry.collectionId,\n type: entry.type,\n key: entry.key,\n payload: entry.payload,\n timestamp: entry.timestamp,\n }));\n\n const response = normalizePushResponse(await push(outbound));\n\n log.info(\"push outbox confirmed\", {\n sent: outbound.length,\n confirmed: response.confirmed.length,\n failed: response.failed?.length ?? 0,\n });\n\n for (const confirmation of response.confirmed) {\n await outbox\n .update(confirmation.eventId, (draft) => {\n draft.sync = true;\n draft.syncStatus = \"synced\";\n draft.globalSeq = confirmation.globalSeq;\n draft.lastError = null;\n draft.lastErrorCode = null;\n draft.retryable = null;\n })\n .isPersisted.promise;\n\n log.debug(\"outbox entry marked pushed\", {\n eventId: confirmation.eventId,\n globalSeq: confirmation.globalSeq,\n });\n }\n\n for (const failure of response.failed ?? []) {\n await outbox\n .update(failure.eventId, (draft) => {\n draft.sync = false;\n draft.syncStatus = \"failed\";\n draft.lastError = failure.message;\n draft.lastErrorCode = failure.code ?? null;\n draft.retryable = failure.retryable ?? null;\n })\n .isPersisted.promise;\n\n log.warn(\"outbox entry marked failed\", {\n eventId: failure.eventId,\n message: failure.message,\n code: failure.code,\n retryable: failure.retryable,\n });\n }\n\n return response.confirmed.length;\n}\n\nasync function pullInbox(\n outbox: Collection<OutboxEntry, string>,\n inbox: Collection<InboxEntry, string>,\n pull: NonNullable<NormalizedSyncTransport[\"pull\"]>,\n targets: Record<string, AcceptMutationsCollection>,\n log: EventSourcedLogger,\n): Promise<number> {\n let pulled = 0;\n let hasMore = true;\n\n while (hasMore) {\n const since = currentSince(inbox);\n log.debug(\"pull inbox page\", { since });\n\n const response = await pull(since);\n\n log.debug(\"pull inbox response\", {\n since,\n eventCount: response.events.length,\n hasMore: response.hasMore,\n cursor: response.cursor,\n });\n\n if (response.events.length === 0) break;\n\n const sorted = [...response.events].sort((a, b) => a.globalSeq - b.globalSeq);\n\n for (const event of sorted) {\n if (outbox.has(event.eventId)) {\n await markInboxEventSynced(inbox, event);\n\n log.debug(\"pull skipped: event originated locally\", {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n });\n continue;\n }\n\n const existing = inbox.get(event.eventId);\n if (existing?.sync) {\n log.debug(\"pull skipped: inbox already applied\", {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n });\n continue;\n }\n\n if (!existing) {\n await inbox.insert(toInboxEntry(event, false)).isPersisted.promise;\n log.debug(\"inbox entry inserted\", {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n collectionId: event.collectionId,\n });\n }\n\n const applied = await replayEvent(\n targets,\n event.collectionId,\n event.eventId,\n event.type,\n event.key,\n event.payload,\n log,\n );\n\n if (!applied) {\n return pulled;\n }\n\n await inbox\n .update(event.eventId, (draft) => {\n draft.sync = true;\n })\n .isPersisted.promise;\n\n log.info(\"pull replay applied\", {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n collectionId: event.collectionId,\n type: event.type,\n key: event.key,\n });\n\n pulled++;\n }\n\n hasMore = response.hasMore;\n }\n\n log.info(\"pull inbox finished\", { pulled });\n\n return pulled;\n}\n\nasync function replayInbox(\n inbox: Collection<InboxEntry, string>,\n targets: Record<string, AcceptMutationsCollection>,\n log: EventSourcedLogger,\n): Promise<number> {\n const pending = [...inbox.state.values()]\n .filter((entry) => !entry.sync)\n .sort((a, b) => a.globalSeq - b.globalSeq);\n\n log.info(\"pending inbox replay started\", { pendingCount: pending.length });\n\n let replayed = 0;\n\n for (const entry of pending) {\n const applied = await replayEvent(\n targets,\n entry.collectionId,\n entry.eventId,\n entry.type,\n entry.key,\n entry.payload,\n log,\n );\n\n if (!applied) {\n break;\n }\n\n await inbox\n .update(entry.eventId, (draft) => {\n draft.sync = true;\n })\n .isPersisted.promise;\n\n replayed++;\n\n log.info(\"pending inbox replay applied\", {\n eventId: entry.eventId,\n globalSeq: entry.globalSeq,\n collectionId: entry.collectionId,\n });\n }\n\n log.info(\"pending inbox replay finished\", { replayed });\n\n return replayed;\n}\n\nasync function replayEvent(\n targets: Record<string, AcceptMutationsCollection>,\n collectionId: string,\n eventId: string,\n type: MutationType,\n key: string | number,\n payload: Record<string, unknown>,\n log: EventSourcedLogger,\n): Promise<boolean> {\n if (RESERVED_IDS.has(collectionId)) {\n log.warn(\"replay skipped: reserved collection\", { eventId, collectionId, type, key });\n return false;\n }\n\n const target = targets[collectionId];\n if (!target) {\n log.warn(\"replay skipped: unknown collection\", {\n eventId,\n collectionId,\n type,\n key,\n knownCollections: Object.keys(targets).filter((id) => !RESERVED_IDS.has(id)),\n });\n return false;\n }\n\n if (!target.utils.acceptMutations) {\n log.warn(\"replay skipped: collection missing acceptMutations\", {\n eventId,\n collectionId,\n type,\n key,\n targetId: target.id,\n });\n return false;\n }\n\n log.debug(\"replay applying mutation\", { eventId, collectionId, type, key });\n\n try {\n await target.utils.acceptMutations({\n mutations: [\n {\n mutationId: eventId,\n type,\n key,\n modified: payload,\n original: payload,\n changes: payload,\n collection: target,\n },\n ],\n });\n\n log.info(\"replay mutation accepted\", { eventId, collectionId, type, key });\n } catch (err) {\n const error = toError(err);\n log.error(\"replay mutation failed\", {\n eventId,\n collectionId,\n type,\n key,\n message: error.message,\n });\n throw error;\n }\n\n return true;\n}\n\nfunction currentSince(inbox: Collection<InboxEntry, string>): number {\n let max = 0;\n\n for (const entry of inbox.state.values()) {\n if (entry.sync && entry.globalSeq > max) max = entry.globalSeq;\n }\n\n return max;\n}\n\nfunction nextLocalSeq(outbox: Collection<OutboxEntry, string>): number {\n let max = -1;\n\n for (const entry of outbox.state.values()) {\n if (entry.localSeq > max) max = entry.localSeq;\n }\n\n return max + 1;\n}\n\nasync function markInboxEventSynced(\n inbox: Collection<InboxEntry, string>,\n event: ServerEvent,\n): Promise<void> {\n const existing = inbox.get(event.eventId);\n\n if (!existing) {\n await inbox.insert(toInboxEntry(event, true)).isPersisted.promise;\n return;\n }\n\n if (!existing.sync || existing.globalSeq !== event.globalSeq) {\n await inbox\n .update(event.eventId, (draft) => {\n draft.globalSeq = event.globalSeq;\n draft.sync = true;\n })\n .isPersisted.promise;\n }\n}\n\nfunction toInboxEntry(event: ServerEvent, sync: boolean): InboxEntry {\n return {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n collectionId: event.collectionId,\n type: event.type,\n key: event.key,\n payload: event.payload,\n timestamp: event.timestamp,\n sync,\n };\n}\n\nfunction assertReservedNamesAvailable(collections: Record<string, unknown>): void {\n for (const id of Object.keys(collections)) {\n if (RESERVED_IDS.has(id)) {\n throw new Error(\n `Collection id \"${id}\" is reserved. \"outbox\" and \"inbox\" are built-in collections.`,\n );\n }\n }\n}\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n","export type LazySingletonOptions = {\n guard?: () => void;\n notInitializedMessage?: string;\n};\n\nexport type LazySingleton<T extends object> = {\n ensure: () => Promise<T>;\n proxy: T;\n reset: () => void;\n};\n\nexport function createLazySingleton<T extends object>(\n factory: () => Promise<T>,\n options: LazySingletonOptions = {},\n): LazySingleton<T> {\n let instance: T | null = null;\n let initPromise: Promise<T> | null = null;\n\n const ensure = async (): Promise<T> => {\n options.guard?.();\n\n if (instance) {\n return instance;\n }\n\n if (!initPromise) {\n initPromise = factory()\n .then((resolved) => {\n instance = resolved;\n return resolved;\n })\n .catch((error: unknown) => {\n initPromise = null;\n throw error;\n });\n }\n\n return initPromise;\n };\n\n const message =\n options.notInitializedMessage ?? \"Instance is not initialized. Call ensure() first.\";\n\n const proxy = new Proxy({} as T, {\n get(_target, prop, receiver) {\n if (!instance) {\n throw new Error(message);\n }\n return Reflect.get(instance, prop, receiver);\n },\n has(_target, prop) {\n if (!instance) {\n throw new Error(message);\n }\n return Reflect.has(instance, prop);\n },\n getPrototypeOf() {\n if (!instance) {\n throw new Error(message);\n }\n return Reflect.getPrototypeOf(instance);\n },\n });\n\n const reset = (): void => {\n instance = null;\n initPromise = null;\n };\n\n return { ensure, proxy, reset };\n}\n"],"mappings":";;AAmBA,SAAgB,oBAAoB,QAAsC;CACxE,OAAO;EACL,MAAM,qBAAqB,OAAO,MAAM,OAAO,OAAO;EACtD,MAAM,qBAAqB,OAAO,MAAM,OAAO,OAAO;CACxD;AACF;AAEA,SAAgB,oBACd,QACgC;CAChC,IAAI,CAAC,QACH,OAAO;CAGT,IAAI,YAAY,MAAM,GACpB,OAAO;EACL,MAAM,OAAO;EACb,MAAM,OAAO;CACf;CAGF,MAAM,UAAU,WAAW,MAAM;CACjC,MAAM,UAAU,WAAW,MAAM;CAEjC,MAAM,OAAO,gBAAgB,UAAU,OAAO,aAC1C,OAAO,aACP,UACE,qBAAqB,SAAS,OAAO,OAAO,IAC5C,KAAA;CAEN,MAAM,aAAa,gBAAgB,SAAS,OAAO,aAAa,KAAA;CAChE,MAAM,OAAO,aACT,sBAAsB,UAAU,IAChC,UACE,qBAAqB,SAAS,OAAO,OAAO,IAC5C,KAAA;CAEN,IAAI,CAAC,QAAQ,CAAC,MACZ,OAAO;CAGT,OAAO;EAAE;EAAM;CAAK;AACtB;AAEA,SAAgB,sBACd,UACc;CACd,IAAI,oBAAoB,QAAQ,GAC9B,OAAO,EAAE,WAAW,SAAS;CAG/B,OAAO;EACL,WAAW,SAAS;EACpB,QAAQ,SAAS;CACnB;AACF;AAEA,SAAS,oBACP,UAC6C;CAC7C,OAAO,MAAM,QAAQ,QAAQ;AAC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OAAO,UAAmB;GACzB,cAAc;GACd,MAAM;EACR,CAAC;EAGL,OAAO;CACT;CAEA,MAAM,UACJ,QAAQ,yBAAyB;CAEnC,MAAM,QAAQ,IAAI,MAAM,CAAC,GAAQ;EAC/B,IAAI,SAAS,MAAM,UAAU;GAC3B,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,OAAO;GAEzB,OAAO,QAAQ,IAAI,UAAU,MAAM,QAAQ;EAC7C;EACA,IAAI,SAAS,MAAM;GACjB,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,OAAO;GAEzB,OAAO,QAAQ,IAAI,UAAU,IAAI;EACnC;EACA,iBAAiB;GACf,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,OAAO;GAEzB,OAAO,QAAQ,eAAe,QAAQ;EACxC;CACF,CAAC;CAED,MAAM,cAAoB;EACxB,WAAW;EACX,cAAc;CAChB;CAEA,OAAO;EAAE;EAAQ;EAAO;CAAM;AAChC"}
@@ -1,4 +1,4 @@
1
- import { n as createEventSourcedDB, t as createLazySingleton } from "./lazy-singleton-BG02GHLj.mjs";
1
+ import { n as createEventSourcedDB, t as createLazySingleton } from "./lazy-singleton-CB50yOVo.mjs";
2
2
  //#region src/platforms/react-native.ts
3
3
  function createReactNativePlatform(deps, config) {
4
4
  const persistence = deps.createReactNativeSQLitePersistence({ database: config.database });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "event-sourced-collection",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "Event-sourced local-first database built on TanStack DB persistence",
5
5
  "keywords": [
6
6
  "event-sourcing",
@@ -1 +0,0 @@
1
- {"version":3,"file":"lazy-singleton-BG02GHLj.mjs","names":[],"sources":["../src/sync.ts","../src/utils/logger.ts","../src/create-event-sourced-db.ts","../src/lazy-singleton.ts"],"sourcesContent":["import type {\n OutboundEvent,\n PullEventsFn,\n PullResponse,\n PushConfirmation,\n PushEventsFn,\n PushResponse,\n SyncHandlersConfig,\n SyncTransport,\n SyncUrlConfig,\n} from \"./types\";\n\nexport type NormalizedSyncTransport = {\n push?: PushEventsFn;\n pull?: (since: number) => Promise<PullResponse>;\n};\n\ntype HeaderConfig = SyncHandlersConfig[\"headers\"];\n\nexport function createHttpTransport(config: SyncUrlConfig): SyncTransport {\n return {\n push: createHttpPushEvents(config.push, config.headers),\n pull: createHttpPullEvents(config.pull, config.headers),\n };\n}\n\nexport function createSyncTransport(\n config?: SyncHandlersConfig | SyncUrlConfig | SyncTransport,\n): NormalizedSyncTransport | null {\n if (!config) {\n return null;\n }\n\n if (isTransport(config)) {\n return {\n push: config.push,\n pull: config.pull,\n };\n }\n\n const pushUrl = getPushUrl(config);\n const pullUrl = getPullUrl(config);\n\n const push = \"pushEvents\" in config && config.pushEvents\n ? config.pushEvents\n : pushUrl\n ? createHttpPushEvents(pushUrl, config.headers)\n : undefined;\n\n const pullEvents = \"pullEvents\" in config ? config.pullEvents : undefined;\n const pull = pullEvents\n ? createPullFromHandler(pullEvents)\n : pullUrl\n ? createHttpPullEvents(pullUrl, config.headers)\n : undefined;\n\n if (!push && !pull) {\n return null;\n }\n\n return { push, pull };\n}\n\nexport function normalizePushResponse(\n response: PushResponse | ReadonlyArray<PushConfirmation>,\n): PushResponse {\n if (isConfirmationArray(response)) {\n return { confirmed: response };\n }\n\n return {\n confirmed: response.confirmed,\n failed: response.failed,\n };\n}\n\nfunction isConfirmationArray(\n response: PushResponse | ReadonlyArray<PushConfirmation>,\n): response is ReadonlyArray<PushConfirmation> {\n return Array.isArray(response);\n}\n\nfunction createHttpPushEvents(url: string, headers: HeaderConfig): PushEventsFn {\n return async (events: ReadonlyArray<OutboundEvent>): Promise<PushResponse> => {\n if (events.length === 0) return { confirmed: [] };\n\n const resolvedHeaders = await resolveHeaders(headers);\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", ...resolvedHeaders },\n body: JSON.stringify(events),\n });\n\n if (!response.ok) {\n throw new SyncPushError(response.status, await response.text());\n }\n\n return response.json() as Promise<PushResponse>;\n };\n}\n\nfunction createPullFromHandler(pullEvents: PullEventsFn): (since: number) => Promise<PullResponse> {\n return (since: number) => pullEvents({ since });\n}\n\nfunction createHttpPullEvents(\n url: string,\n headers: HeaderConfig,\n): (since: number) => Promise<PullResponse> {\n return async (since: number): Promise<PullResponse> => {\n const resolvedHeaders = await resolveHeaders(headers);\n const pullUrl = appendSince(url, since);\n\n const response = await fetch(pullUrl, {\n headers: { Accept: \"application/json\", ...resolvedHeaders },\n });\n\n if (!response.ok) {\n throw new SyncPullError(response.status, await response.text());\n }\n\n return response.json() as Promise<PullResponse>;\n };\n}\n\nasync function resolveHeaders(headers: HeaderConfig): Promise<Record<string, string>> {\n if (!headers) return {};\n if (typeof headers === \"function\") return headers();\n return headers;\n}\n\nfunction appendSince(url: string, since: number): string {\n const separator = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${separator}since=${encodeURIComponent(String(since))}`;\n}\n\nfunction getPushUrl(config: SyncHandlersConfig | SyncUrlConfig): string | undefined {\n if (\"pushUrl\" in config && config.pushUrl) {\n return config.pushUrl;\n }\n\n if (\"push\" in config && typeof config.push === \"string\") {\n return config.push;\n }\n\n return undefined;\n}\n\nfunction getPullUrl(config: SyncHandlersConfig | SyncUrlConfig): string | undefined {\n if (\"pullUrl\" in config && config.pullUrl) {\n return config.pullUrl;\n }\n\n if (\"pull\" in config && typeof config.pull === \"string\") {\n return config.pull;\n }\n\n return undefined;\n}\n\nexport class SyncPushError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n ) {\n super(`Event push failed: HTTP ${status}`);\n this.name = \"SyncPushError\";\n }\n}\n\nexport class SyncPullError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n ) {\n super(`Event pull failed: HTTP ${status}`);\n this.name = \"SyncPullError\";\n }\n}\n\nexport function isTransport(\n value: SyncHandlersConfig | SyncUrlConfig | SyncTransport,\n): value is SyncTransport {\n return \"push\" in value && typeof value.push === \"function\";\n}\n","export type EventSourcedLogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type EventSourcedLogger = {\n debug: (message: string, data?: Record<string, unknown>) => void;\n info: (message: string, data?: Record<string, unknown>) => void;\n warn: (message: string, data?: Record<string, unknown>) => void;\n error: (message: string, data?: Record<string, unknown>) => void;\n};\n\nconst noopLogger: EventSourcedLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\nconst LOG_PREFIX = \"[event-sourced]\";\n\nexport function createEventSourcedLogger(\n debug?: boolean | EventSourcedLogger,\n): EventSourcedLogger {\n if (debug === undefined || debug === false) {\n return noopLogger;\n }\n\n if (typeof debug === \"object\") {\n return debug;\n }\n\n return {\n debug: (message, data) => {\n if (data === undefined) {\n console.debug(LOG_PREFIX, message);\n return;\n }\n console.debug(LOG_PREFIX, message, data);\n },\n info: (message, data) => {\n if (data === undefined) {\n console.info(LOG_PREFIX, message);\n return;\n }\n console.info(LOG_PREFIX, message, data);\n },\n warn: (message, data) => {\n if (data === undefined) {\n console.warn(LOG_PREFIX, message);\n return;\n }\n console.warn(LOG_PREFIX, message, data);\n },\n error: (message, data) => {\n if (data === undefined) {\n console.error(LOG_PREFIX, message);\n return;\n }\n console.error(LOG_PREFIX, message, data);\n },\n };\n}\n","import type { Collection, IndexConstructor } from \"@tanstack/db\";\nimport { createSyncTransport, normalizePushResponse } from \"./sync\";\nimport type { NormalizedSyncTransport } from \"./sync\";\nimport type { EventSourcedLogger } from \"./utils/logger\";\nimport { createEventSourcedLogger } from \"./utils/logger\";\nimport { generateEventId } from \"./utils/uuid\";\nimport type {\n CollectionMap,\n EventSourcedDB,\n EventSourcedDBConfig,\n InboxEntry,\n MutationType,\n OutboundEvent,\n OutboxEntry,\n ServerEvent,\n SyncResult,\n ManualSyncResult,\n} from \"./types\";\n\nconst OUTBOX_ID = \"outbox\";\nconst INBOX_ID = \"inbox\";\nconst RESERVED_IDS = new Set<string>([OUTBOX_ID, INBOX_ID]);\n\ntype CollectionDefConstraint = {\n getKey: (state: never) => string | number;\n schemaVersion?: number;\n indexes?: ReadonlyArray<{\n select: (row: never) => unknown;\n name?: string;\n indexType?: IndexConstructor<string | number>;\n }>;\n};\n\ntype ReplayMutation = {\n mutationId: string;\n type: MutationType;\n key: string | number;\n modified: Record<string, unknown>;\n original: Record<string, unknown>;\n changes: Record<string, unknown>;\n collection: AcceptMutationsCollection;\n};\n\ntype AcceptMutationsCollection = {\n id?: string;\n utils: {\n acceptMutations?: (transaction: { mutations: Array<ReplayMutation> }) => Promise<void> | void;\n };\n};\n\ntype MutationHookParams = {\n transaction: {\n mutations: ReadonlyArray<{\n mutationId: string;\n key: string | number;\n modified: Record<string, unknown>;\n original: Record<string, unknown>;\n }>;\n };\n};\n\ntype SeqCounter = { value: number };\n\ntype MetaCollectionFactory = Pick<\n EventSourcedDBConfig<Record<string, CollectionDefConstraint>>,\n \"createCollection\" | \"persistedCollectionOptions\" | \"persistence\"\n>;\n\nexport async function createEventSourcedDB<\n const TDefs extends Record<string, CollectionDefConstraint>,\n>(config: EventSourcedDBConfig<TDefs>): Promise<EventSourcedDB<TDefs>> {\n assertReservedNamesAvailable(config.collections);\n\n const log = createEventSourcedLogger(config.debug);\n\n const transport = createSyncTransport(config.sync);\n let syncEnabled = config.syncEnabled ?? true;\n\n log.info(\"creating event-sourced db\", {\n collectionIds: Object.keys(config.collections),\n hasTransport: transport !== null,\n syncEnabled,\n });\n\n const defaultSchemaVersion = config.schemaVersion ?? 1;\n const seq: SeqCounter = { value: 0 };\n\n const outbox = createMetaCollection<OutboxEntry>(\n config,\n OUTBOX_ID,\n (entry) => entry.eventId,\n defaultSchemaVersion,\n );\n\n const inbox = createMetaCollection<InboxEntry>(\n config,\n INBOX_ID,\n (entry) => entry.eventId,\n defaultSchemaVersion,\n );\n\n const userCollections = {} as CollectionMap<TDefs>;\n\n for (const collectionId of Object.keys(config.collections)) {\n const def = config.collections[collectionId]!;\n const getKey = def.getKey as (item: Record<string, unknown>) => string | number;\n\n const options = config.persistedCollectionOptions<Record<string, unknown>, string | number>({\n id: collectionId,\n getKey,\n persistence: config.persistence,\n schemaVersion: def.schemaVersion ?? defaultSchemaVersion,\n onInsert: createMutationHook(outbox, collectionId, \"insert\", seq, log),\n onUpdate: createMutationHook(outbox, collectionId, \"update\", seq, log),\n onDelete: createMutationHook(outbox, collectionId, \"delete\", seq, log),\n });\n\n const collection = config.createCollection(options);\n applyCollectionIndexes(collection, collectionId, def.indexes, log);\n const hasAcceptMutations = Boolean(\n (collection as AcceptMutationsCollection).utils?.acceptMutations,\n );\n\n log.debug(\"registered collection\", {\n collectionId,\n hasAcceptMutations,\n });\n\n (userCollections as Record<string, unknown>)[collectionId] = collection;\n }\n\n const collections = {\n ...(userCollections as CollectionMap<TDefs>),\n outbox,\n inbox,\n } as EventSourcedDB<TDefs>[\"collections\"];\n\n const replayTargets = collections as unknown as Record<string, AcceptMutationsCollection>;\n\n const subscriptions = [\n outbox.subscribeChanges(() => {}),\n inbox.subscribeChanges(() => {}),\n ];\n\n await outbox.preload();\n await inbox.preload();\n\n seq.value = nextLocalSeq(outbox);\n\n log.info(\"preloaded meta collections\", {\n outboxCount: outbox.state.size,\n inboxCount: inbox.state.size,\n nextLocalSeq: seq.value,\n });\n\n await replayInbox(inbox, replayTargets, log);\n\n async function sync(): Promise<SyncResult> {\n if (!syncEnabled) {\n log.debug(\"sync skipped: sync disabled\");\n return { pushed: 0, pulled: 0, errors: [] };\n }\n\n if (!transport) {\n log.warn(\"sync skipped: no transport configured\");\n return { pushed: 0, pulled: 0, errors: [] };\n }\n\n log.info(\"sync started\");\n\n await outbox.preload();\n await inbox.preload();\n\n const errors: Error[] = [];\n let pushed = 0;\n let pulled = 0;\n\n try {\n if (transport.push) {\n pushed = await pushOutbox(outbox, transport.push, log);\n } else {\n log.debug(\"push skipped: no push transport configured\");\n }\n } catch (err) {\n const error = toError(err);\n log.error(\"push outbox failed\", { message: error.message });\n errors.push(error);\n }\n\n try {\n if (transport.pull) {\n pulled = await pullInbox(outbox, inbox, transport.pull, replayTargets, log);\n } else {\n log.debug(\"pull skipped: no pull transport configured\");\n }\n } catch (err) {\n const error = toError(err);\n log.error(\"pull inbox failed\", { message: error.message });\n errors.push(error);\n }\n\n log.info(\"sync finished\", { pushed, pulled, errorCount: errors.length });\n\n return { pushed, pulled, errors };\n }\n\n async function manualSync(): Promise<ManualSyncResult> {\n log.info(\"manual sync started\");\n\n await outbox.preload();\n await inbox.preload();\n\n const errors: Error[] = [];\n let pushed = 0;\n let pulled = 0;\n let replayed = 0;\n\n if (syncEnabled && transport) {\n try {\n if (transport.push) {\n pushed = await pushOutbox(outbox, transport.push, log);\n } else {\n log.debug(\"manual sync push skipped: no push transport configured\");\n }\n } catch (err) {\n const error = toError(err);\n log.error(\"manual sync push failed\", { message: error.message });\n errors.push(error);\n }\n\n try {\n if (transport.pull) {\n pulled = await pullInbox(outbox, inbox, transport.pull, replayTargets, log);\n } else {\n log.debug(\"manual sync pull skipped: no pull transport configured\");\n }\n } catch (err) {\n const error = toError(err);\n log.error(\"manual sync pull failed\", { message: error.message });\n errors.push(error);\n }\n } else if (!syncEnabled) {\n log.debug(\"manual sync push/pull skipped: sync disabled\");\n } else {\n log.warn(\"manual sync: no transport configured, skipping push/pull\");\n }\n\n try {\n replayed = await replayInbox(inbox, replayTargets, log);\n } catch (err) {\n const error = toError(err);\n log.error(\"manual sync replay failed\", { message: error.message });\n errors.push(error);\n }\n\n log.info(\"manual sync finished\", { pushed, pulled, replayed, errorCount: errors.length });\n\n return { pushed, pulled, replayed, errors };\n }\n\n function getSyncEnabled(): boolean {\n return syncEnabled;\n }\n\n function setSyncEnabled(enabled: boolean): void {\n syncEnabled = enabled;\n log.debug(\"sync enabled updated\", { syncEnabled: enabled });\n }\n\n function dispose(): void {\n log.debug(\"disposing event-sourced db\");\n for (const subscription of subscriptions) {\n subscription.unsubscribe();\n }\n }\n\n return { collections, sync, manualSync, getSyncEnabled, setSyncEnabled, dispose };\n}\n\nfunction createMetaCollection<TEntry extends object>(\n config: MetaCollectionFactory,\n id: string,\n getKey: (entry: TEntry) => string,\n schemaVersion: number,\n): Collection<TEntry, string> {\n const options = config.persistedCollectionOptions<TEntry, string>({\n id,\n getKey,\n persistence: config.persistence,\n schemaVersion,\n });\n\n return config.createCollection(options);\n}\n\ntype IndexableCollection = {\n createIndex: (\n indexCallback: (row: Record<string, unknown>) => unknown,\n config?: {\n name?: string;\n indexType?: IndexConstructor<string | number>;\n },\n ) => unknown;\n};\n\nfunction applyCollectionIndexes(\n collection: Collection<Record<string, unknown>, string | number>,\n collectionId: string,\n indexes: CollectionDefConstraint[\"indexes\"],\n log: EventSourcedLogger,\n): void {\n if (!indexes?.length) {\n return;\n }\n\n const indexable = collection as IndexableCollection;\n\n for (const indexDef of indexes) {\n indexable.createIndex(indexDef.select as (row: Record<string, unknown>) => unknown, {\n name: indexDef.name,\n indexType: indexDef.indexType,\n });\n\n log.debug(\"registered collection index\", {\n collectionId,\n name: indexDef.name,\n });\n }\n}\n\nfunction createMutationHook(\n outbox: Collection<OutboxEntry, string>,\n collectionId: string,\n type: MutationType,\n seq: SeqCounter,\n log: EventSourcedLogger,\n) {\n return async (params: MutationHookParams): Promise<Record<string, unknown>> => {\n for (const mutation of params.transaction.mutations) {\n const payload = type === \"delete\" ? mutation.original : mutation.modified;\n\n const entry: OutboxEntry = {\n eventId: generateEventId(),\n collectionId,\n type,\n key: mutation.key,\n payload,\n timestamp: Date.now(),\n localSeq: seq.value++,\n globalSeq: null,\n sync: false,\n syncStatus: \"pending\",\n attemptCount: 0,\n lastAttemptAt: null,\n lastError: null,\n lastErrorCode: null,\n retryable: null,\n };\n\n await outbox.insert(entry).isPersisted.promise;\n\n log.debug(\"outbox entry created\", {\n eventId: entry.eventId,\n collectionId,\n type,\n key: entry.key,\n localSeq: entry.localSeq,\n });\n }\n\n return {};\n };\n}\n\nasync function pushOutbox(\n outbox: Collection<OutboxEntry, string>,\n push: NonNullable<NormalizedSyncTransport[\"push\"]>,\n log: EventSourcedLogger,\n): Promise<number> {\n const pending = [...outbox.state.values()]\n .filter((entry) => !entry.sync && entry.syncStatus !== \"failed\")\n .sort((a, b) => a.localSeq - b.localSeq);\n\n log.debug(\"push outbox\", { pendingCount: pending.length });\n\n if (pending.length === 0) return 0;\n\n const attemptAt = Date.now();\n\n for (const entry of pending) {\n await outbox\n .update(entry.eventId, (draft) => {\n draft.syncStatus = \"pending\";\n draft.attemptCount = (draft.attemptCount ?? 0) + 1;\n draft.lastAttemptAt = attemptAt;\n draft.lastError = null;\n draft.lastErrorCode = null;\n draft.retryable = null;\n })\n .isPersisted.promise;\n }\n\n const outbound: OutboundEvent[] = pending.map((entry) => ({\n eventId: entry.eventId,\n collectionId: entry.collectionId,\n type: entry.type,\n key: entry.key,\n payload: entry.payload,\n timestamp: entry.timestamp,\n }));\n\n const response = normalizePushResponse(await push(outbound));\n\n log.info(\"push outbox confirmed\", {\n sent: outbound.length,\n confirmed: response.confirmed.length,\n failed: response.failed?.length ?? 0,\n });\n\n for (const confirmation of response.confirmed) {\n await outbox\n .update(confirmation.eventId, (draft) => {\n draft.sync = true;\n draft.syncStatus = \"synced\";\n draft.globalSeq = confirmation.globalSeq;\n draft.lastError = null;\n draft.lastErrorCode = null;\n draft.retryable = null;\n })\n .isPersisted.promise;\n\n log.debug(\"outbox entry marked pushed\", {\n eventId: confirmation.eventId,\n globalSeq: confirmation.globalSeq,\n });\n }\n\n for (const failure of response.failed ?? []) {\n await outbox\n .update(failure.eventId, (draft) => {\n draft.sync = false;\n draft.syncStatus = \"failed\";\n draft.lastError = failure.message;\n draft.lastErrorCode = failure.code ?? null;\n draft.retryable = failure.retryable ?? null;\n })\n .isPersisted.promise;\n\n log.warn(\"outbox entry marked failed\", {\n eventId: failure.eventId,\n message: failure.message,\n code: failure.code,\n retryable: failure.retryable,\n });\n }\n\n return response.confirmed.length;\n}\n\nasync function pullInbox(\n outbox: Collection<OutboxEntry, string>,\n inbox: Collection<InboxEntry, string>,\n pull: NonNullable<NormalizedSyncTransport[\"pull\"]>,\n targets: Record<string, AcceptMutationsCollection>,\n log: EventSourcedLogger,\n): Promise<number> {\n let pulled = 0;\n let hasMore = true;\n\n while (hasMore) {\n const since = currentSince(inbox);\n log.debug(\"pull inbox page\", { since });\n\n const response = await pull(since);\n\n log.debug(\"pull inbox response\", {\n since,\n eventCount: response.events.length,\n hasMore: response.hasMore,\n cursor: response.cursor,\n });\n\n if (response.events.length === 0) break;\n\n const sorted = [...response.events].sort((a, b) => a.globalSeq - b.globalSeq);\n\n for (const event of sorted) {\n if (outbox.has(event.eventId)) {\n await markInboxEventSynced(inbox, event);\n\n log.debug(\"pull skipped: event originated locally\", {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n });\n continue;\n }\n\n const existing = inbox.get(event.eventId);\n if (existing?.sync) {\n log.debug(\"pull skipped: inbox already applied\", {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n });\n continue;\n }\n\n if (!existing) {\n await inbox.insert(toInboxEntry(event, false)).isPersisted.promise;\n log.debug(\"inbox entry inserted\", {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n collectionId: event.collectionId,\n });\n }\n\n const applied = await replayEvent(\n targets,\n event.collectionId,\n event.eventId,\n event.type,\n event.key,\n event.payload,\n log,\n );\n\n if (!applied) {\n return pulled;\n }\n\n await inbox\n .update(event.eventId, (draft) => {\n draft.sync = true;\n })\n .isPersisted.promise;\n\n log.info(\"pull replay applied\", {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n collectionId: event.collectionId,\n type: event.type,\n key: event.key,\n });\n\n pulled++;\n }\n\n hasMore = response.hasMore;\n }\n\n log.info(\"pull inbox finished\", { pulled });\n\n return pulled;\n}\n\nasync function replayInbox(\n inbox: Collection<InboxEntry, string>,\n targets: Record<string, AcceptMutationsCollection>,\n log: EventSourcedLogger,\n): Promise<number> {\n const pending = [...inbox.state.values()]\n .filter((entry) => !entry.sync)\n .sort((a, b) => a.globalSeq - b.globalSeq);\n\n log.info(\"pending inbox replay started\", { pendingCount: pending.length });\n\n let replayed = 0;\n\n for (const entry of pending) {\n const applied = await replayEvent(\n targets,\n entry.collectionId,\n entry.eventId,\n entry.type,\n entry.key,\n entry.payload,\n log,\n );\n\n if (!applied) {\n break;\n }\n\n await inbox\n .update(entry.eventId, (draft) => {\n draft.sync = true;\n })\n .isPersisted.promise;\n\n replayed++;\n\n log.info(\"pending inbox replay applied\", {\n eventId: entry.eventId,\n globalSeq: entry.globalSeq,\n collectionId: entry.collectionId,\n });\n }\n\n log.info(\"pending inbox replay finished\", { replayed });\n\n return replayed;\n}\n\nasync function replayEvent(\n targets: Record<string, AcceptMutationsCollection>,\n collectionId: string,\n eventId: string,\n type: MutationType,\n key: string | number,\n payload: Record<string, unknown>,\n log: EventSourcedLogger,\n): Promise<boolean> {\n if (RESERVED_IDS.has(collectionId)) {\n log.warn(\"replay skipped: reserved collection\", { eventId, collectionId, type, key });\n return false;\n }\n\n const target = targets[collectionId];\n if (!target) {\n log.warn(\"replay skipped: unknown collection\", {\n eventId,\n collectionId,\n type,\n key,\n knownCollections: Object.keys(targets).filter((id) => !RESERVED_IDS.has(id)),\n });\n return false;\n }\n\n if (!target.utils.acceptMutations) {\n log.warn(\"replay skipped: collection missing acceptMutations\", {\n eventId,\n collectionId,\n type,\n key,\n targetId: target.id,\n });\n return false;\n }\n\n log.debug(\"replay applying mutation\", { eventId, collectionId, type, key });\n\n try {\n await target.utils.acceptMutations({\n mutations: [\n {\n mutationId: eventId,\n type,\n key,\n modified: payload,\n original: payload,\n changes: payload,\n collection: target,\n },\n ],\n });\n\n log.info(\"replay mutation accepted\", { eventId, collectionId, type, key });\n } catch (err) {\n const error = toError(err);\n log.error(\"replay mutation failed\", {\n eventId,\n collectionId,\n type,\n key,\n message: error.message,\n });\n throw error;\n }\n\n return true;\n}\n\nfunction currentSince(inbox: Collection<InboxEntry, string>): number {\n let max = 0;\n\n for (const entry of inbox.state.values()) {\n if (entry.sync && entry.globalSeq > max) max = entry.globalSeq;\n }\n\n return max;\n}\n\nfunction nextLocalSeq(outbox: Collection<OutboxEntry, string>): number {\n let max = -1;\n\n for (const entry of outbox.state.values()) {\n if (entry.localSeq > max) max = entry.localSeq;\n }\n\n return max + 1;\n}\n\nasync function markInboxEventSynced(\n inbox: Collection<InboxEntry, string>,\n event: ServerEvent,\n): Promise<void> {\n const existing = inbox.get(event.eventId);\n\n if (!existing) {\n await inbox.insert(toInboxEntry(event, true)).isPersisted.promise;\n return;\n }\n\n if (!existing.sync || existing.globalSeq !== event.globalSeq) {\n await inbox\n .update(event.eventId, (draft) => {\n draft.globalSeq = event.globalSeq;\n draft.sync = true;\n })\n .isPersisted.promise;\n }\n}\n\nfunction toInboxEntry(event: ServerEvent, sync: boolean): InboxEntry {\n return {\n eventId: event.eventId,\n globalSeq: event.globalSeq,\n collectionId: event.collectionId,\n type: event.type,\n key: event.key,\n payload: event.payload,\n timestamp: event.timestamp,\n sync,\n };\n}\n\nfunction assertReservedNamesAvailable(collections: Record<string, unknown>): void {\n for (const id of Object.keys(collections)) {\n if (RESERVED_IDS.has(id)) {\n throw new Error(\n `Collection id \"${id}\" is reserved. \"outbox\" and \"inbox\" are built-in collections.`,\n );\n }\n }\n}\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n","export type LazySingletonOptions = {\n guard?: () => void;\n notInitializedMessage?: string;\n};\n\nexport type LazySingleton<T extends object> = {\n ensure: () => Promise<T>;\n proxy: T;\n reset: () => void;\n};\n\nexport function createLazySingleton<T extends object>(\n factory: () => Promise<T>,\n options: LazySingletonOptions = {},\n): LazySingleton<T> {\n let instance: T | null = null;\n let initPromise: Promise<T> | null = null;\n\n const ensure = async (): Promise<T> => {\n options.guard?.();\n\n if (instance) {\n return instance;\n }\n\n if (!initPromise) {\n initPromise = factory()\n .then((resolved) => {\n instance = resolved;\n return resolved;\n })\n .catch((error: unknown) => {\n initPromise = null;\n throw error;\n });\n }\n\n return initPromise;\n };\n\n const message =\n options.notInitializedMessage ?? \"Instance is not initialized. Call ensure() first.\";\n\n const proxy = new Proxy({} as T, {\n get(_target, prop, receiver) {\n if (!instance) {\n throw new Error(message);\n }\n return Reflect.get(instance, prop, receiver);\n },\n has(_target, prop) {\n if (!instance) {\n throw new Error(message);\n }\n return Reflect.has(instance, prop);\n },\n getPrototypeOf() {\n if (!instance) {\n throw new Error(message);\n }\n return Reflect.getPrototypeOf(instance);\n },\n });\n\n const reset = (): void => {\n instance = null;\n initPromise = null;\n };\n\n return { ensure, proxy, reset };\n}\n"],"mappings":";;AAmBA,SAAgB,oBAAoB,QAAsC;CACxE,OAAO;EACL,MAAM,qBAAqB,OAAO,MAAM,OAAO,OAAO;EACtD,MAAM,qBAAqB,OAAO,MAAM,OAAO,OAAO;CACxD;AACF;AAEA,SAAgB,oBACd,QACgC;CAChC,IAAI,CAAC,QACH,OAAO;CAGT,IAAI,YAAY,MAAM,GACpB,OAAO;EACL,MAAM,OAAO;EACb,MAAM,OAAO;CACf;CAGF,MAAM,UAAU,WAAW,MAAM;CACjC,MAAM,UAAU,WAAW,MAAM;CAEjC,MAAM,OAAO,gBAAgB,UAAU,OAAO,aAC1C,OAAO,aACP,UACE,qBAAqB,SAAS,OAAO,OAAO,IAC5C,KAAA;CAEN,MAAM,aAAa,gBAAgB,SAAS,OAAO,aAAa,KAAA;CAChE,MAAM,OAAO,aACT,sBAAsB,UAAU,IAChC,UACE,qBAAqB,SAAS,OAAO,OAAO,IAC5C,KAAA;CAEN,IAAI,CAAC,QAAQ,CAAC,MACZ,OAAO;CAGT,OAAO;EAAE;EAAM;CAAK;AACtB;AAEA,SAAgB,sBACd,UACc;CACd,IAAI,oBAAoB,QAAQ,GAC9B,OAAO,EAAE,WAAW,SAAS;CAG/B,OAAO;EACL,WAAW,SAAS;EACpB,QAAQ,SAAS;CACnB;AACF;AAEA,SAAS,oBACP,UAC6C;CAC7C,OAAO,MAAM,QAAQ,QAAQ;AAC/B;AAEA,SAAS,qBAAqB,KAAa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