@hyper-fetch/db 0.0.0-stage → 1.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 (141) hide show
  1. package/README.md +180 -2
  2. package/__tests__/e2e/db.e2e.spec.ts +269 -0
  3. package/__tests__/features/connection/connection.spec.ts +23 -0
  4. package/__tests__/features/model/live-query.model.spec.ts +320 -0
  5. package/__tests__/features/operators/operators.spec.ts +113 -0
  6. package/__tests__/features/runtime/runtime.spec.ts +185 -0
  7. package/__tests__/features/serializer/serializer.spec.ts +73 -0
  8. package/__tests__/features/store/store.spec.ts +147 -0
  9. package/__tests__/features/types/db.types.spec.ts +337 -0
  10. package/__tests__/integration/audit.spec.ts +639 -0
  11. package/__tests__/integration/competitors.spec.ts +393 -0
  12. package/__tests__/integration/convergence.model.spec.ts +162 -0
  13. package/__tests__/integration/edge-cases.spec.ts +465 -0
  14. package/__tests__/integration/errors.spec.ts +178 -0
  15. package/__tests__/integration/infinite.model.spec.ts +142 -0
  16. package/__tests__/integration/infinite.spec.ts +290 -0
  17. package/__tests__/integration/inspect.spec.ts +103 -0
  18. package/__tests__/integration/joins-many.spec.ts +177 -0
  19. package/__tests__/integration/joins.spec.ts +179 -0
  20. package/__tests__/integration/key-loaders.spec.ts +196 -0
  21. package/__tests__/integration/links.spec.ts +105 -0
  22. package/__tests__/integration/mutations.spec.ts +337 -0
  23. package/__tests__/integration/normalize.spec.ts +80 -0
  24. package/__tests__/integration/offline.spec.ts +479 -0
  25. package/__tests__/integration/queries.spec.ts +513 -0
  26. package/__tests__/integration/races.spec.ts +127 -0
  27. package/__tests__/integration/server-operators.spec.ts +123 -0
  28. package/__tests__/integration/ssr.spec.ts +111 -0
  29. package/__tests__/integration/syncs.spec.ts +564 -0
  30. package/__tests__/integration/transactions.spec.ts +344 -0
  31. package/__tests__/integration/windows.spec.ts +192 -0
  32. package/__tests__/tsconfig.json +11 -0
  33. package/__tests__/type-budget/budget.fixture.ts +2476 -0
  34. package/__tests__/type-budget/tsconfig.json +4 -0
  35. package/__tests__/utils/fixtures.ts +225 -0
  36. package/__tests__/utils/random.ts +19 -0
  37. package/__tests__/vitest.setup.ts +11 -0
  38. package/dist/collection/collection.d.ts +111 -0
  39. package/dist/collection/collection.d.ts.map +1 -0
  40. package/dist/collection/collection.types.d.ts +316 -0
  41. package/dist/collection/collection.types.d.ts.map +1 -0
  42. package/dist/collection/resource.types.d.ts +77 -0
  43. package/dist/collection/resource.types.d.ts.map +1 -0
  44. package/dist/db/collection.runtime.d.ts +98 -0
  45. package/dist/db/collection.runtime.d.ts.map +1 -0
  46. package/dist/db/db.d.ts +154 -0
  47. package/dist/db/db.d.ts.map +1 -0
  48. package/dist/db/db.runtime.d.ts +114 -0
  49. package/dist/db/db.runtime.d.ts.map +1 -0
  50. package/dist/db/db.types.d.ts +162 -0
  51. package/dist/db/db.types.d.ts.map +1 -0
  52. package/dist/graphql/connection.d.ts +25 -0
  53. package/dist/graphql/connection.d.ts.map +1 -0
  54. package/dist/index.d.ts +17 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.mjs +4220 -0
  57. package/dist/index.mjs.map +1 -0
  58. package/dist/mutation/mutation.d.ts +136 -0
  59. package/dist/mutation/mutation.d.ts.map +1 -0
  60. package/dist/mutation/mutation.errors.d.ts +6 -0
  61. package/dist/mutation/mutation.errors.d.ts.map +1 -0
  62. package/dist/mutation/mutation.utils.d.ts +35 -0
  63. package/dist/mutation/mutation.utils.d.ts.map +1 -0
  64. package/dist/operators/operators.d.ts +33 -0
  65. package/dist/operators/operators.d.ts.map +1 -0
  66. package/dist/operators/operators.types.d.ts +68 -0
  67. package/dist/operators/operators.types.d.ts.map +1 -0
  68. package/dist/operators/operators.utils.d.ts +19 -0
  69. package/dist/operators/operators.utils.d.ts.map +1 -0
  70. package/dist/persistence/persistence.d.ts +42 -0
  71. package/dist/persistence/persistence.d.ts.map +1 -0
  72. package/dist/persistence/serializer.d.ts +23 -0
  73. package/dist/persistence/serializer.d.ts.map +1 -0
  74. package/dist/persistence/snapshot.d.ts +29 -0
  75. package/dist/persistence/snapshot.d.ts.map +1 -0
  76. package/dist/persistence/tabs.d.ts +53 -0
  77. package/dist/persistence/tabs.d.ts.map +1 -0
  78. package/dist/query/infinite-query.d.ts +59 -0
  79. package/dist/query/infinite-query.d.ts.map +1 -0
  80. package/dist/query/live-query.d.ts +85 -0
  81. package/dist/query/live-query.d.ts.map +1 -0
  82. package/dist/query/planner.d.ts +57 -0
  83. package/dist/query/planner.d.ts.map +1 -0
  84. package/dist/query/query.d.ts +155 -0
  85. package/dist/query/query.d.ts.map +1 -0
  86. package/dist/query/query.types.d.ts +71 -0
  87. package/dist/query/query.types.d.ts.map +1 -0
  88. package/dist/schema/schema.types.d.ts +33 -0
  89. package/dist/schema/schema.types.d.ts.map +1 -0
  90. package/dist/store/store.d.ts +76 -0
  91. package/dist/store/store.d.ts.map +1 -0
  92. package/dist/store/store.types.d.ts +27 -0
  93. package/dist/store/store.types.d.ts.map +1 -0
  94. package/dist/subset/base-subset.d.ts +66 -0
  95. package/dist/subset/base-subset.d.ts.map +1 -0
  96. package/dist/subset/key-subset.d.ts +23 -0
  97. package/dist/subset/key-subset.d.ts.map +1 -0
  98. package/dist/subset/list-subset.d.ts +63 -0
  99. package/dist/subset/list-subset.d.ts.map +1 -0
  100. package/dist/sync/sync.d.ts +42 -0
  101. package/dist/sync/sync.d.ts.map +1 -0
  102. package/dist/utils/request.utils.d.ts +11 -0
  103. package/dist/utils/request.utils.d.ts.map +1 -0
  104. package/package.json +71 -4
  105. package/project.json +4 -0
  106. package/scripts/docs-typescript.mjs +24 -0
  107. package/scripts/type-budget.mjs +37 -0
  108. package/src/collection/collection.ts +330 -0
  109. package/src/collection/collection.types.ts +383 -0
  110. package/src/collection/resource.types.ts +114 -0
  111. package/src/db/collection.runtime.ts +572 -0
  112. package/src/db/db.runtime.ts +537 -0
  113. package/src/db/db.ts +451 -0
  114. package/src/db/db.types.ts +157 -0
  115. package/src/graphql/connection.ts +23 -0
  116. package/src/index.ts +16 -0
  117. package/src/mutation/mutation.errors.ts +7 -0
  118. package/src/mutation/mutation.ts +776 -0
  119. package/src/mutation/mutation.utils.ts +58 -0
  120. package/src/operators/operators.ts +90 -0
  121. package/src/operators/operators.types.ts +67 -0
  122. package/src/operators/operators.utils.ts +169 -0
  123. package/src/persistence/persistence.ts +168 -0
  124. package/src/persistence/serializer.ts +123 -0
  125. package/src/persistence/snapshot.ts +76 -0
  126. package/src/persistence/tabs.ts +86 -0
  127. package/src/query/infinite-query.ts +206 -0
  128. package/src/query/live-query.ts +552 -0
  129. package/src/query/planner.ts +199 -0
  130. package/src/query/query.ts +319 -0
  131. package/src/query/query.types.ts +90 -0
  132. package/src/schema/schema.types.ts +29 -0
  133. package/src/store/store.ts +300 -0
  134. package/src/store/store.types.ts +17 -0
  135. package/src/subset/base-subset.ts +169 -0
  136. package/src/subset/key-subset.ts +44 -0
  137. package/src/subset/list-subset.ts +328 -0
  138. package/src/sync/sync.ts +99 -0
  139. package/src/utils/request.utils.ts +67 -0
  140. package/tsconfig.json +12 -0
  141. package/vite.config.ts +71 -0
@@ -0,0 +1,154 @@
1
+ import { CollectionInstance } from '../collection/collection';
2
+ import { KeyFieldOf, LoaderDescriptor, MutationDescriptor, SortDirection } from '../collection/collection.types';
3
+ import { Transaction } from '../mutation/mutation';
4
+ import { Condition, ExtractConditionEq, ExtractConditionTokens, FieldRef, RowRefs } from '../operators/operators.types';
5
+ import { Query, JoinSpec, JoinTarget, JoinedMatchOf } from '../query/query';
6
+ import { DbRuntime } from './db.runtime';
7
+ import { DbErrorEvent, DbInspection, DbOptions, DehydratedDb, TransactionConfig } from './db.types';
8
+ export type WriteOptions = {
9
+ /** Writes this one is built on. When one of them is rejected, this write is dropped too. */
10
+ dependsOn?: readonly (Transaction | string)[];
11
+ };
12
+ type InsertMethod<Mutations> = Mutations extends {
13
+ insert: infer Input;
14
+ } ? (row: Input, options?: WriteOptions) => Transaction : never;
15
+ type UpdateMethod<Key, Mutations> = Mutations extends {
16
+ update: infer Changes;
17
+ } ? (key: Key, changes: Changes, options?: WriteOptions) => Transaction : never;
18
+ type DeleteMethod<Key, Mutations> = Mutations extends {
19
+ delete: true;
20
+ } ? (key: Key, options?: WriteOptions) => Transaction : never;
21
+ /** A collection inside a db: queries start here, and writes go through it */
22
+ export declare class CollectionHandle<Row, Input, KeyField extends KeyFieldOf<Row>, Loaders extends LoaderDescriptor, Mutations extends MutationDescriptor> {
23
+ private readonly runtime;
24
+ private readonly name;
25
+ /** Type-only carrier of the handle's generics, never set at runtime */
26
+ readonly __types?: {
27
+ row: Row;
28
+ input: Input;
29
+ key: KeyField;
30
+ loaders: Loaders;
31
+ mutations: Mutations;
32
+ };
33
+ /** The collection's name in `createDb` */
34
+ readonly collectionName: string;
35
+ /** Adds an optimistic insert and sends it. A row without a key gets a temporary one until the server assigns it. */
36
+ readonly insert: InsertMethod<Mutations>;
37
+ /** Adds an optimistic update and sends it */
38
+ readonly update: UpdateMethod<NonNullable<Row[KeyField]>, Mutations>;
39
+ /** Adds an optimistic delete and sends it */
40
+ readonly delete: DeleteMethod<NonNullable<Row[KeyField]>, Mutations>;
41
+ constructor(runtime: DbRuntime, name: string);
42
+ where<C extends Condition<string, string>>(callback: (row: RowRefs<Row>) => C): Query<Row, Loaders, Row, ExtractConditionTokens<C>, ExtractConditionEq<C>>;
43
+ orderBy<Name extends keyof Row & string>(callback: (row: RowRefs<Row>) => FieldRef<Name, Row[Name]>, direction?: SortDirection): Query<Row, Loaders, Row, never, never, Name, "list", false>;
44
+ select<Selection extends Record<string, FieldRef<string, unknown>>>(callback: (row: RowRefs<Row>) => Selection): Query<Row, Loaders, { [Output in keyof Selection]: Selection[Output] extends FieldRef<string, infer Value> ? Value : never; }, never, never, never, "list", false>;
45
+ limit(limit: number): Query<Row, Loaders, Row, never, never, never, "list", false>;
46
+ /** Adds the row of another collection whose key is the given field. See `Query.join`. */
47
+ join<Name extends string, Target extends JoinTarget, Field extends keyof Row & string, const On, const Type>(name: Name, collection: Target, by: JoinSpec<Row, Field, JoinedMatchOf<Target, On>, On, Type>): Query<Row, Loaders, { [Field_1 in keyof Row | Name]: Field_1 extends Name ? import('..').JoinedValue<import('..').JoinedRowOf<Target>, On, Type> : Field_1 extends keyof Row ? Row[Field_1] : never; }, never, never, never, "list", false>;
48
+ /** Reads only the rows the db holds and never sends a request */
49
+ local(): Query<Row, Loaders, Row, never, never, never, "list", true>;
50
+ /** Reads one row by key */
51
+ findOne(key: NonNullable<Row[KeyField]>): Query<Row, Loaders, Row, never, never, never, "one">;
52
+ /** The key to render a row with. It stays the same when a temporary key is swapped for the server's. */
53
+ renderKey(key: NonNullable<Row[KeyField]>): string;
54
+ private start;
55
+ private getRuntime;
56
+ private write;
57
+ }
58
+ type HandleOf<C> = C extends {
59
+ __types?: {
60
+ row: infer Row;
61
+ input: infer Input;
62
+ key: infer KeyField;
63
+ loaders: infer Loaders;
64
+ mutations: infer Mutations;
65
+ };
66
+ } ? [KeyField, Loaders, Mutations] extends [KeyFieldOf<Row>, LoaderDescriptor, MutationDescriptor] ? CollectionHandle<Row, Input, KeyField & KeyFieldOf<Row>, Loaders & LoaderDescriptor, Mutations & MutationDescriptor> : never : never;
67
+ /** The writes a transaction can make to one collection. Named transactions can write any collection. */
68
+ type TransactionHandleOf<C, Named extends boolean> = C extends {
69
+ __types?: {
70
+ row: infer Row;
71
+ input: infer Input;
72
+ key: infer KeyField;
73
+ mutations: infer Mutations;
74
+ };
75
+ } ? KeyField extends keyof Row ? Named extends true ? {
76
+ /** Needs its key, because one request cannot tell which key the server gave which row */
77
+ insert: (row: Input & {
78
+ [Field in KeyField]: NonNullable<Row[KeyField]>;
79
+ }) => void;
80
+ update: (key: NonNullable<Row[KeyField]>, changes: Partial<Row>) => void;
81
+ delete: (key: NonNullable<Row[KeyField]>) => void;
82
+ } : {
83
+ insert: Mutations extends {
84
+ insert: infer Inserted;
85
+ } ? (row: Inserted & {
86
+ [Field in KeyField]: NonNullable<Row[KeyField]>;
87
+ }) => void : never;
88
+ update: Mutations extends {
89
+ update: infer Changes;
90
+ } ? (key: NonNullable<Row[KeyField]>, changes: Changes) => void : never;
91
+ delete: Mutations extends {
92
+ delete: true;
93
+ } ? (key: NonNullable<Row[KeyField]>) => void : never;
94
+ } : never : never;
95
+ /** What a transaction callback receives: one handle per collection, which records writes instead of sending them */
96
+ export type TransactionHandles<Collections, Named extends boolean> = {
97
+ [Name in keyof Collections]: TransactionHandleOf<Collections[Name], Named>;
98
+ };
99
+ type TransactionMethod<Collections, Transactions> = {
100
+ /**
101
+ * Groups writes into one optimistic layer, kept or dropped as a whole. Each write goes through its collection's
102
+ * `mutate`, in order; when one fails, the writes after it are dropped and the subsets holding rows already written
103
+ * refetch.
104
+ */
105
+ (callback: (tx: TransactionHandles<Collections, false>) => void): Transaction;
106
+ /**
107
+ * Groups writes into one optimistic layer and sends them as one request, through the `mutationFn` of the named
108
+ * transaction in `createDb`. The name is stored in the outbox, so the transaction can be replayed after a restart.
109
+ */
110
+ <Name extends keyof Transactions & string>(name: Name, callback: (tx: TransactionHandles<Collections, true>) => void): Transaction;
111
+ };
112
+ type ReservedName = "clear" | "destroy" | "ready" | "onError" | "transaction" | "dehydrate" | "inspect" | "onChange";
113
+ export type DbMethods = {
114
+ /** Resolves once persisted rows and the outbox are restored */
115
+ ready: Promise<void>;
116
+ /** Removes every row, loaded subset and pending write, and the persisted data of the scope, for example on sign-out */
117
+ clear: () => Promise<void>;
118
+ /** Stops every sync, timer and tab channel */
119
+ destroy: () => void;
120
+ /** Listens to failed writes, rejected validation, outbox and persistence errors */
121
+ onError: (listener: (event: DbErrorEvent) => void) => () => void;
122
+ /**
123
+ * The server rows and loaded subsets, as type-tagged JSON, for server rendering. Optimistic layers, the outbox and
124
+ * syncs are never included. Pass it to `createDb(collections, { state })` on the client.
125
+ */
126
+ dehydrate: () => DehydratedDb;
127
+ /** What the db holds right now: collections with their layers and subsets, live queries and the outbox */
128
+ inspect: () => DbInspection;
129
+ /** Listens to every change the db makes, once per batch of writes, load or outbox change */
130
+ onChange: (listener: () => void) => () => void;
131
+ };
132
+ export type Db<Collections extends Record<string, CollectionInstance>, Transactions = unknown> = {
133
+ [Name in keyof Collections]: HandleOf<Collections[Name]>;
134
+ } & DbMethods & {
135
+ transaction: TransactionMethod<Collections, Transactions>;
136
+ };
137
+ /**
138
+ * Creates the db that queries and writes go through. The names given to it are the names on the db, as in `db.post`.
139
+ * Requests carry their Client and listeners carry their Socket, so it needs neither.
140
+ *
141
+ * @example
142
+ * const db = createDb({ post: Post, user: User });
143
+ */
144
+ export declare const createDb: <Collections extends Record<string, CollectionInstance>, Transactions>(collections: Collections & { [Name in Extract<keyof Collections, ReservedName>]: never; }, options?: DbOptions & {
145
+ /**
146
+ * Collections that hold the same records in different shapes, such as `["post", "postSummary"]`. A write, delete
147
+ * or optimistic change to one changes the fields the other has, for the same key.
148
+ */
149
+ links?: readonly (readonly [keyof Collections & string, keyof Collections & string])[];
150
+ /** Named transactions: each sends the writes of `db.transaction(name, ...)` as one request */
151
+ transactions?: Transactions & Record<string, TransactionConfig>;
152
+ }) => Db<Collections, Transactions>;
153
+ export {};
154
+ //# sourceMappingURL=db.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/db/db.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,KAAK,EACV,UAAU,EACV,gBAAgB,EAChB,kBAAkB,EAElB,aAAa,EACd,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAExD,OAAO,KAAK,EACV,SAAS,EACT,kBAAkB,EAClB,sBAAsB,EACtB,QAAQ,EACR,OAAO,EACR,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,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AM,IAAI,CAAC;IACjE;;;OAGG;IACH,SAAS,EAAE,MAAM,YAAY,CAAC;IAC9B,0GAA0G;IAC1G,OAAO,EAAE,MAAM,YAAY,CAAC;IAC5B,4FAA4F;IAC5F,QAAQ,EAAE,CAAC,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,IAAI,CAAC;CAChD,CAAC;AAEF,MAAM,MAAM,EAAE,CAAC,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,EAAE,YAAY,GAAG,OAAO,IAAI;KAC9F,IAAI,IAAI,MAAM,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;CACzD,GAAG,SAAS,GAAG;IAAE,WAAW,EAAE,iBAAiB,CAAC,WAAW,EAAE,YAAY,CAAC,CAAA;CAAE,CAAC;AA4D9E;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,GAAI,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,EAAE,YAAY,EAC3F,aAAa,WAAW,GAAG,GAAG,IAAI,IAAI,OAAO,CAAC,MAAM,WAAW,EAAE,YAAY,CAAC,GAAG,KAAK,GAAE,EACxF,UAAU,SAAS,GAAG;IACpB;;;OAGG;IACH,KAAK,CAAC,EAAE,SAAS,CAAC,SAAS,CAAC,MAAM,WAAW,GAAG,MAAM,EAAE,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC;IACvF,8FAA8F;IAC9F,YAAY,CAAC,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;CACjE,KACA,EAAE,CAAC,WAAW,EAAE,YAAY,CAmB9B,CAAC"}
@@ -0,0 +1,114 @@
1
+ import { SocketInstance } from '@hyper-fetch/sockets';
2
+ import { CollectionInstance } from '../collection/collection';
3
+ import { CollectionConfig, RowKey } from '../collection/collection.types';
4
+ import { MutationEngine } from '../mutation/mutation';
5
+ import { Persistence } from '../persistence/persistence';
6
+ import { Tabs } from '../persistence/tabs';
7
+ import { LiveQuery } from '../query/live-query';
8
+ import { QueryDefinition } from '../query/query.types';
9
+ import { CollectionRuntime } from './collection.runtime';
10
+ import { DbErrorEvent, DbInspection, DbNotation, DbOptions, DehydratedDb, TransactionConfig } from './db.types';
11
+ /**
12
+ * The running db. It owns the collections, batches writes into transactions so every query updates once, revalidates
13
+ * stale subsets on focus and reconnect, and connects persistence, the outbox and other tabs.
14
+ */
15
+ export declare class DbRuntime {
16
+ readonly collections: Map<string, CollectionRuntime>;
17
+ readonly gcTime: number;
18
+ readonly syncTimeout: number;
19
+ readonly notation: DbNotation;
20
+ readonly mutations: MutationEngine;
21
+ readonly persistence: Persistence | undefined;
22
+ private readonly serializer;
23
+ private changeListeners;
24
+ /** Timers of sync waits, cleared on `destroy` */
25
+ private timers;
26
+ private queryTimers;
27
+ readonly tabs: Tabs | undefined;
28
+ readonly ready: Promise<void>;
29
+ /** Changes on `clear`, so responses to requests sent before are never written */
30
+ generation: number;
31
+ isReady: boolean;
32
+ isDestroyed: boolean;
33
+ private seq;
34
+ private batchDepth;
35
+ private changedRows;
36
+ private dirtyQueries;
37
+ private liveQueries;
38
+ private inflight;
39
+ private errorListeners;
40
+ private syncWaiters;
41
+ private lastSyncWrite;
42
+ private sockets;
43
+ private cleanups;
44
+ constructor(collections: Record<string, CollectionInstance>, options?: DbOptions & {
45
+ links?: readonly (readonly [string, string])[];
46
+ transactions?: Record<string, TransactionConfig>;
47
+ });
48
+ /** Listens to every change the db makes, once per batch of writes, load or outbox change. Returns the unsubscribe. */
49
+ onChange: (listener: () => void) => () => void;
50
+ notifyChange: () => void;
51
+ /** What the db holds right now: collections with their layers and subsets, live queries and the outbox */
52
+ inspect: () => DbInspection;
53
+ /** The server rows and loaded subsets of every collection that holds any, as type-tagged JSON */
54
+ dehydrate: () => DehydratedDb;
55
+ /** Writes a server's rows and subsets, before anything renders, so the first render matches the server's */
56
+ private hydrate;
57
+ /** Whether this tab replays the outbox and writes persisted rows */
58
+ get isLeader(): boolean;
59
+ /** The collection a config belongs to, for references between collections such as `normalize` */
60
+ getCollectionByConfig: (config: CollectionConfig) => CollectionRuntime | undefined;
61
+ tick: () => number;
62
+ /** Runs writes as one transaction: every query updates once, after the last write */
63
+ batch: <T>(callback: () => T) => T;
64
+ /** Records a changed row. Every store write runs inside `batch`, which flushes the changes once it ends. */
65
+ markRowChanged: (collection: CollectionRuntime, key: RowKey) => void;
66
+ markQueryDirty: (query: LiveQuery) => void;
67
+ /** The live query for a definition, shared by every query with the same structure */
68
+ getLiveQuery: (definition: QueryDefinition) => LiveQuery;
69
+ /**
70
+ * Forgets a live query nobody subscribes to after `gcTime`, so queries made once, such as each search, do not pile
71
+ * up and slow every write. A query read again later is made again.
72
+ */
73
+ releaseLater: (query: LiveQuery) => void;
74
+ trackRequest: (seq: number) => void;
75
+ /** A request the db sent settled, so deletes made after every pending request no longer need remembering */
76
+ settleRequest: (seq: number) => void;
77
+ onError: (listener: (event: DbErrorEvent) => void) => () => void;
78
+ emitError: (event: DbErrorEvent) => void;
79
+ /** A sync event touched a row, which writes with `onSuccess: "sync"` wait for */
80
+ notifySyncWrite: (collection: string, key: RowKey) => void;
81
+ /**
82
+ * Resolves with `true` when a sync event touched the row after `since`, also while the write was in flight, or with
83
+ * `false` after the timeout
84
+ */
85
+ waitForSync: ({ collection, key, since, timeout, }: {
86
+ collection: string;
87
+ key: RowKey;
88
+ since: number;
89
+ timeout: number;
90
+ }) => Promise<boolean>;
91
+ /** Marks the subsets a socket's syncs covered stale after a reconnect, unless their subscriptions resume */
92
+ watchSocket: (socket: SocketInstance) => void;
93
+ /** Removes every row, loaded subset and pending write, and the persisted data of the scope */
94
+ clear: () => Promise<void>;
95
+ /** Refetches the stale subsets of every mounted query */
96
+ private revalidateActive;
97
+ /**
98
+ * Drops rows, subsets and pending writes in this tab. Responses to requests sent before belong to the previous user,
99
+ * so the generation changes and they are never written.
100
+ */
101
+ private clearLocal;
102
+ /** This tab became the leader: it adopts the persisted outbox, so the previous leader's writes are replayed */
103
+ private takeLead;
104
+ destroy: () => void;
105
+ private watchClients;
106
+ private watchClient;
107
+ private flush;
108
+ private flushPending;
109
+ /** Tabs that do not persist send their server rows to the tab that does */
110
+ private forwardRows;
111
+ private onTabsMessage;
112
+ private restore;
113
+ }
114
+ //# sourceMappingURL=db.runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db.runtime.d.ts","sourceRoot":"","sources":["../../src/db/db.runtime.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAMzD,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,KAAK,EACV,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,SAAS,EACT,YAAY,EACZ,iBAAiB,EAElB,MAAM,YAAY,CAAC;AAKpB;;;GAGG;AACH,qBAAa,SAAS;IACpB,QAAQ,CAAC,WAAW,iCAAwC;IAC5D,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC;IACnC,QAAQ,CAAC,WAAW,EAAE,WAAW,GAAG,SAAS,CAAC;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A2E;IAC3E,OAAO,CAAC,WAAW,CAYjB;IAEF,OAAO,CAAC,aAAa,CAgCnB;IAEF,OAAO,CAAC,OAAO,CAWb;CACH"}
@@ -0,0 +1,162 @@
1
+ import { RequestInstance, ResponseType } from '@hyper-fetch/core';
2
+ import { Notation, RowKey } from '../collection/collection.types';
3
+ import { DbCodec } from '../persistence/serializer';
4
+ import { QueryExplanation } from '../query/query.types';
5
+ /** The db-wide notation that loaders use for operators and orders they declare with `true` */
6
+ export type DbNotation = Notation;
7
+ /** Storage for persisted rows and the outbox, such as `localStorage` or an async key-value store */
8
+ export type DbStorage = {
9
+ getItem: (key: string) => string | null | Promise<string | null>;
10
+ setItem: (key: string, value: string) => unknown;
11
+ removeItem: (key: string) => unknown;
12
+ };
13
+ /** The part of the Web Locks API the db uses to elect the tab that replays the outbox */
14
+ export type DbLockManager = {
15
+ request: (name: string, callback: () => Promise<unknown>) => Promise<unknown>;
16
+ };
17
+ /** The part of `BroadcastChannel` the db uses to talk to other tabs */
18
+ export type DbChannel = {
19
+ postMessage: (message: unknown) => void;
20
+ addEventListener: (type: "message", listener: (event: {
21
+ data: unknown;
22
+ }) => void) => void;
23
+ removeEventListener: (type: "message", listener: (event: {
24
+ data: unknown;
25
+ }) => void) => void;
26
+ close: () => void;
27
+ };
28
+ export type DbPersistenceOptions = {
29
+ storage: DbStorage;
30
+ /** Keeps one user's or tenant's data apart from another's, such as the user id */
31
+ scope?: string;
32
+ /** Persisted rows of another version are cleared. The outbox is kept, because it holds the only copy of writes. */
33
+ version?: string | number;
34
+ /** How long a query whose restore found no rows waits for the network before it shows an empty result */
35
+ networkTimeout?: number;
36
+ };
37
+ export type DbOfflineOptions = {
38
+ /**
39
+ * Whether a failed replay is temporary and retried, or permanent and dropped. By default a 4xx response other than
40
+ * 408 and 429 is permanent.
41
+ */
42
+ retryable?: (response: ResponseType<unknown, unknown, any>) => boolean;
43
+ /** Delay before retrying a temporary failure */
44
+ retryDelay?: (attempt: number) => number;
45
+ };
46
+ /** What the db holds right now, for devtools such as HyperFlow */
47
+ export type DbInspection = {
48
+ collections: {
49
+ name: string;
50
+ /** Rows with their optimistic layers applied */
51
+ rows: number;
52
+ layers: {
53
+ id: string;
54
+ key: RowKey;
55
+ type: MutationOperation;
56
+ }[];
57
+ subsets: {
58
+ id: string;
59
+ kind: "list" | "key";
60
+ /** Index of the loader in the collection's chain */
61
+ loader: number;
62
+ rows: number;
63
+ fresh: boolean;
64
+ live: boolean;
65
+ loading: boolean;
66
+ error: unknown;
67
+ loadedAt: number;
68
+ /** Queries reading the subset */
69
+ observers: number;
70
+ }[];
71
+ }[];
72
+ queries: {
73
+ key: string;
74
+ collection: string;
75
+ subscribers: number;
76
+ status: "loading" | "ready" | "error";
77
+ rows: number | undefined;
78
+ plan: QueryExplanation;
79
+ }[];
80
+ outbox: TransactionRecord[];
81
+ };
82
+ /** What `db.dehydrate()` returns: the server rows and loaded subsets, as type-tagged JSON */
83
+ export type DehydratedDb = {
84
+ readonly __dehydrated: true;
85
+ readonly collections: unknown;
86
+ };
87
+ export type DbOptions = DbNotation & {
88
+ /**
89
+ * Value types to persist and dehydrate beyond `Date`, `bigint`, `Map`, `Set`, `undefined`, `NaN` and the
90
+ * infinities, which the db stores as type-tagged JSON on its own
91
+ */
92
+ codecs?: readonly DbCodec[];
93
+ /** Rows and loaded subsets a server rendered with, from `db.dehydrate()`. They show at once and refetch when used. */
94
+ state?: DehydratedDb;
95
+ /** How long a loaded subset no query uses is kept. Defaults to five minutes, like the core `cacheTime`. */
96
+ gcTime?: number;
97
+ /** How long a write with `onSuccess: "sync"` waits for a sync event before it refetches */
98
+ syncTimeout?: number;
99
+ /** Persists rows, loaded subsets and the outbox */
100
+ persistence?: DbPersistenceOptions;
101
+ /** Sends every write through the outbox, so writes made offline are replayed when the connection returns */
102
+ offline?: boolean | DbOfflineOptions;
103
+ /** How tabs agree on which one replays the outbox. Defaults to Web Locks and `BroadcastChannel`. */
104
+ tabs?: false | {
105
+ locks?: DbLockManager;
106
+ channel?: DbChannel;
107
+ };
108
+ };
109
+ export type MutationOperation = "insert" | "update" | "delete";
110
+ /** One write of a transaction, as a transaction's `mutationFn` receives it and the outbox keeps it */
111
+ export type TransactionWrite = {
112
+ collection: string;
113
+ op: MutationOperation;
114
+ key: RowKey;
115
+ /** The complete row of an insert, or the changed fields of an update. Empty for a delete. */
116
+ values: Record<string, unknown>;
117
+ };
118
+ /** A named transaction declared in `createDb`: one request sends all of its writes */
119
+ export type TransactionConfig = {
120
+ /** Returns the request that sends the writes. The transaction id is an idempotency key. */
121
+ mutationFn: (context: {
122
+ id: string;
123
+ mutations: TransactionWrite[];
124
+ }) => RequestInstance;
125
+ /**
126
+ * What happens to the changes once the request succeeds: `keep` makes them the server state, which is the default,
127
+ * and `refetch` reloads the loaded subsets that hold the changed rows
128
+ */
129
+ onSuccess?: "keep" | "refetch";
130
+ };
131
+ /** A write as the outbox keeps it */
132
+ export type TransactionRecord = {
133
+ id: string;
134
+ collection: string;
135
+ op: MutationOperation;
136
+ key: RowKey;
137
+ values: Record<string, unknown>;
138
+ dependsOn: string[];
139
+ /** Set before the request goes out, so a restart sends it again with the same id */
140
+ sent: boolean;
141
+ /** The key is temporary until the server assigns one, so it is not sent */
142
+ temporaryKey?: boolean;
143
+ createdAt: number;
144
+ /** A named transaction: its writes go out through the transaction's `mutationFn`, as one request */
145
+ transaction?: {
146
+ name: string;
147
+ writes: TransactionWrite[];
148
+ };
149
+ };
150
+ /** What a write resolves with. Like `send()`, a write never rejects. */
151
+ export type MutationResult = {
152
+ success: boolean;
153
+ data: unknown;
154
+ error: unknown;
155
+ };
156
+ export type DbErrorEvent = {
157
+ type: "mutation" | "outbox" | "validation" | "persistence" | "load" | "sync" | "subscriber";
158
+ error: unknown;
159
+ collection?: string;
160
+ transaction?: TransactionRecord;
161
+ };
162
+ //# sourceMappingURL=db.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db.types.d.ts","sourceRoot":"","sources":["../../src/db/db.types.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shape many GraphQL APIs use for paginated lists */
2
+ export type RelayConnection<Node> = {
3
+ edges?: readonly ({
4
+ node: Node;
5
+ } | null)[] | null;
6
+ pageInfo: {
7
+ hasNextPage: boolean;
8
+ endCursor?: string | null;
9
+ };
10
+ };
11
+ /**
12
+ * Reads the rows and the next cursor of a Relay connection (`edges` / `node`), for a paginated GraphQL loader. Spread it
13
+ * into the loader options and add `page` to send the cursor.
14
+ *
15
+ * @example
16
+ * collection(PostSchema, { key: "id" }).load(getPosts, {
17
+ * ...relayConnection((response: PostsResponse) => response.posts),
18
+ * page: (after) => ({ payload: { after } }),
19
+ * });
20
+ */
21
+ export declare const relayConnection: <Response, Node>(select: (response: Response) => RelayConnection<Node>) => {
22
+ rows: (response: Response) => Node[];
23
+ cursor: (response: Response) => string | null;
24
+ };
25
+ //# sourceMappingURL=connection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/graphql/connection.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,MAAM,MAAM,eAAe,CAAC,IAAI,IAAI;IAClC,KAAK,CAAC,EAAE,SAAS,CAAC;QAAE,IAAI,EAAE,IAAI,CAAA;KAAE,GAAG,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC;IAClD,QAAQ,EAAE;QAAE,WAAW,EAAE,OAAO,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;CAC/D,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,EAAE,IAAI,EAAE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,KAAK,eAAe,CAAC,IAAI,CAAC;qBAClF,QAAQ,KAAG,IAAI,EAAE;uBACf,QAAQ,KAAG,MAAM,GAAG,IAAI;CAI3C,CAAC"}
@@ -0,0 +1,17 @@
1
+ export * from './collection/collection';
2
+ export * from './collection/collection.types';
3
+ export * from './collection/resource.types';
4
+ export * from './db/db';
5
+ export * from './db/db.types';
6
+ export * from './graphql/connection';
7
+ export * from './mutation/mutation';
8
+ export * from './mutation/mutation.errors';
9
+ export * from './operators/operators';
10
+ export * from './operators/operators.types';
11
+ export * from './query/infinite-query';
12
+ export * from './query/query';
13
+ export * from './persistence/serializer';
14
+ export type { CollectionSnapshot, SubsetSnapshot } from './persistence/snapshot';
15
+ export * from './query/query.types';
16
+ export * from './schema/schema.types';
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,SAAS,CAAC;AACxB,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,wBAAwB,CAAC;AACvC,cAAc,eAAe,CAAC;AAC9B,cAAc,0BAA0B,CAAC;AACzC,YAAY,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACjF,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC"}