@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,23 @@
1
+ import { LoaderConfig, RowKey } from '../collection/collection.types';
2
+ import { CollectionRuntime } from '../db/collection.runtime';
3
+ import { Stamp } from '../store/store.types';
4
+ import { LoadOptions, BaseSubset } from './base-subset';
5
+ /** One row read by key, for `findOne`. Keys read in the same tick are batched when the loader has `byKeys`. */
6
+ export declare class KeySubset extends BaseSubset {
7
+ readonly key: RowKey;
8
+ constructor(collection: CollectionRuntime, loader: LoaderConfig, key: RowKey);
9
+ holds: (key: RowKey) => boolean;
10
+ /** The fields of the row the server sent, so syncs scoped by those fields keep it live */
11
+ getEqValues: () => Record<string, unknown>;
12
+ /** Called by the collection when the batched request for this key settled */
13
+ complete: (result: {
14
+ success: true;
15
+ found: boolean;
16
+ stamp: Stamp;
17
+ } | {
18
+ success: false;
19
+ error: unknown;
20
+ }) => void;
21
+ protected run: (options: LoadOptions) => Promise<void>;
22
+ }
23
+ //# sourceMappingURL=key-subset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key-subset.d.ts","sourceRoot":"","sources":["../../src/subset/key-subset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,+GAA+G;AAC/G,qBAAa,SAAU,SAAQ,UAAU;IAIrC,QAAQ,CAAC,GAAG,EAAE,MAAM;gBAFpB,UAAU,EAAE,iBAAiB,EAC7B,MAAM,EAAE,YAAY,EACX,GAAG,EAAE,MAAM;IAKtB,KAAK,GAAI,KAAK,MAAM,aAAsB;IAE1C,0FAA0F;IAC1F,WAAW,QAAO,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAuD;IAEhG,6EAA6E;IAC7E,QAAQ,GAAI,QAAQ;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,KAAK,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,UAetG;IAEF,SAAS,CAAC,GAAG,GAAU,SAAS,WAAW,mBAGzC;CACH"}
@@ -0,0 +1,63 @@
1
+ import { LoaderConfig, RowKey } from '../collection/collection.types';
2
+ import { CollectionRuntime } from '../db/collection.runtime';
3
+ import { ListPlan } from '../query/planner';
4
+ import { QueryDefinition } from '../query/query.types';
5
+ import { Row } from '../store/store.types';
6
+ import { LoadOptions, BaseSubset } from './base-subset';
7
+ /**
8
+ * The rows one list loader returned for one set of sent conditions, order and range. It owns those rows until it is
9
+ * released, and records which rows a refetch no longer returned.
10
+ */
11
+ export declare class ListSubset extends BaseSubset {
12
+ owned: Set<RowKey>;
13
+ /** Rows that inserts added inside a paginated subset's range */
14
+ inserted: Set<RowKey>;
15
+ /** Rows a refetch no longer returned, which another subset still holds */
16
+ excluded: Set<RowKey>;
17
+ orderIndex: Map<RowKey, number>;
18
+ cursor: unknown;
19
+ hasMore: boolean;
20
+ /** How many pages a paginated subset has loaded, so a refetch reloads all of them */
21
+ pages: number;
22
+ readonly listLoader: LoaderConfig;
23
+ readonly plan: ListPlan;
24
+ readonly definition: Pick<QueryDefinition, "orderBy" | "limit">;
25
+ constructor(collection: CollectionRuntime, options: {
26
+ loader: LoaderConfig;
27
+ plan: ListPlan;
28
+ definition: Pick<QueryDefinition, "orderBy" | "limit">;
29
+ });
30
+ get id(): string;
31
+ /** The values of the subset's sent `eq` conditions, which syncs use to pick their subscription */
32
+ getEqValues: () => Record<string, unknown>;
33
+ /** Whether a row matches what the backend was asked for, including the loader's fixed filters */
34
+ matchesSent: (row: Row) => boolean;
35
+ /** Whether the backend decides membership alone: pages, or a server-only operator the client cannot evaluate */
36
+ get ownsOnly(): boolean;
37
+ holds: (key: RowKey) => boolean;
38
+ /** Adds an inserted row to a paginated subset when it sorts inside the loaded range */
39
+ noteInsert: (key: RowKey) => void;
40
+ /** Loads the page after the last loaded one */
41
+ loadNext: () => Promise<void>;
42
+ protected run: (options: LoadOptions) => Promise<void>;
43
+ private buildRequest;
44
+ /**
45
+ * Loads from the first page, or the page after the last loaded one. A paginated subset is a prefix of its result, so
46
+ * loading from the first page reloads every page loaded so far, in order, and then releases the rows none of them
47
+ * returned. The rows stay until the last page is back, so the list does not jump while it reloads.
48
+ */
49
+ private loadPages;
50
+ /** Loads pages one after another, each with the cursor the previous one returned, until `remaining` are loaded */
51
+ private fetchPages;
52
+ /** Sends one page's request and writes its rows, adding their keys to `returned` in order */
53
+ private fetchPage;
54
+ /**
55
+ * Releases rows a complete reload no longer returned: rows it owned, rows inserts had added to its pages, and rows
56
+ * nothing else holds that match what it sent, such as a confirmed insert someone else deleted since. The server
57
+ * answered for its conditions, so such a row is not in them.
58
+ */
59
+ private release;
60
+ /** With persistence, a subset that restored no rows shows an empty result once the network took too long */
61
+ private startNetworkTimeout;
62
+ }
63
+ //# sourceMappingURL=list-subset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list-subset.d.ts","sourceRoot":"","sources":["../../src/subset/list-subset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmB,YAAY,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AAC5F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAEhD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C;;;GAGG;AACH,qBAAa,UAAW,SAAQ,UAAU;IACxC,KAAK,cAAqB;IAC1B,gEAAgE;IAChE,QAAQ,cAAqB;IAC7B,0EAA0E;IAC1E,QAAQ,cAAqB;IAC7B,UAAU,sBAA6B;IACvC,MAAM,EAAE,OAAO,CAAa;IAC5B,OAAO,UAAS;IAChB,qFAAqF;IACrF,KAAK,SAAK;IAEV,QAAQ,CAAC,UAAU,EAAE,YAAY,CAAC;IAClC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,IAAI,CAAC,eAAe,EAAE,SAAS,GAAG,OAAO,CAAC,CAAC;gBAG9D,UAAU,EAAE,iBAAiB,EAC7B,OAAO,EAAE;QAAE,MAAM,EAAE,YAAY,CAAC;QAAC,IAAI,EAAE,QAAQ,CAAC;QAAC,UAAU,EAAE,IAAI,CAAC,eAAe,EAAE,SAAS,GAAG,OAAO,CAAC,CAAA;KAAE;IAQ3G,IAAI,EAAE,WAEL;IAED,kGAAkG;IAClG,WAAW,QAAO,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAIvC;IAEF,iGAAiG;IACjG,WAAW,GAAI,KAAK,GAAG,aAIrB;IAEF,gHAAgH;IAChH,IAAI,QAAQ,YAEX;IAED,KAAK,GAAI,KAAK,MAAM,aASlB;IAEF,uFAAuF;IACvF,UAAU,GAAI,KAAK,MAAM,UAsBvB;IAEF,+CAA+C;IAC/C,QAAQ,QAAO,OAAO,CAAC,IAAI,CAAC,CAY1B;IAEF,SAAS,CAAC,GAAG,GAAI,SAAS,WAAW,mBAA2D;IAEhG,OAAO,CAAC,YAAY,CAmBlB;IAEF;;;;OAIG;IACH,OAAO,CAAC,SAAS,CA+Df;IAEF,kHAAkH;IAClH,OAAO,CAAC,UAAU,CAsBhB;IAEF,6FAA6F;IAC7F,OAAO,CAAC,SAAS,CAoCf;IAEF;;;;OAIG;IACH,OAAO,CAAC,OAAO,CAgCb;IAEF,4GAA4G;IAC5G,OAAO,CAAC,mBAAmB,CAczB;CACH"}
@@ -0,0 +1,42 @@
1
+ import { ListenerInstance } from '@hyper-fetch/sockets';
2
+ import { SyncConfig } from '../collection/collection.types';
3
+ import { Stamp } from '../store/store.types';
4
+ export type SyncHost = {
5
+ tick: () => number;
6
+ applySyncMessage: (sync: SyncConfig, message: unknown, stamp: Stamp) => void;
7
+ onLiveChange: () => void;
8
+ onRemove: (subscription: SyncSubscription) => void;
9
+ };
10
+ /**
11
+ * One server-side subscription of a sync, for one set of filter values. Subsets that need the same subscription
12
+ * share it, and it stops when the last one releases it.
13
+ *
14
+ * While a subset that uses it is loading, events are buffered and applied after the response, so an `update` for a row
15
+ * that only the response brings is not lost.
16
+ */
17
+ export declare class SyncSubscription {
18
+ started: boolean;
19
+ private users;
20
+ private loading;
21
+ private buffer;
22
+ private unsubscribe;
23
+ readonly id: string;
24
+ readonly sync: SyncConfig;
25
+ readonly listener: ListenerInstance;
26
+ private readonly host;
27
+ constructor(options: {
28
+ id: string;
29
+ sync: SyncConfig;
30
+ listener: ListenerInstance;
31
+ host: SyncHost;
32
+ });
33
+ /** Whether the server has started the subscription and the socket is connected */
34
+ isLive: () => boolean;
35
+ addUser: (user: object) => void;
36
+ removeUser: (user: object) => void;
37
+ getUsers: () => object[];
38
+ beginLoad: (user: object) => void;
39
+ endLoad: (user: object) => void;
40
+ private receive;
41
+ }
42
+ //# sourceMappingURL=sync.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../../src/sync/sync.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAElD,MAAM,MAAM,QAAQ,GAAG;IACrB,IAAI,EAAE,MAAM,MAAM,CAAC;IACnB,gBAAgB,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAC7E,YAAY,EAAE,MAAM,IAAI,CAAC;IACzB,QAAQ,EAAE,CAAC,YAAY,EAAE,gBAAgB,KAAK,IAAI,CAAC;CACpD,CAAC;AAEF;;;;;;GAMG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,UAAS;IAChB,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,MAAM,CAA4C;IAC1D,OAAO,CAAC,WAAW,CAA2B;IAE9C,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,CAAC;IACpC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAW;gBAEpB,OAAO,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,UAAU,CAAC;QAAC,QAAQ,EAAE,gBAAgB,CAAC;QAAC,IAAI,EAAE,QAAQ,CAAA;KAAE;IAOjG,kFAAkF;IAClF,MAAM,gBAAgE;IAEtE,OAAO,GAAI,MAAM,MAAM,UAkBrB;IAEF,UAAU,GAAI,MAAM,MAAM,UAUxB;IAEF,QAAQ,iBAAyB;IAEjC,SAAS,GAAI,MAAM,MAAM,UAEvB;IAEF,OAAO,GAAI,MAAM,MAAM,UAQrB;IAEF,OAAO,CAAC,OAAO,CAQb;CACH"}
@@ -0,0 +1,11 @@
1
+ import { RequestInstance } from '@hyper-fetch/core';
2
+ import { ListenerInstance } from '@hyper-fetch/sockets';
3
+ import { AnyRequestPatch, ListenerPatch } from '../collection/collection.types';
4
+ export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
5
+ /** Applies patches to a request, merging params, query params and object payloads into what it already has */
6
+ export declare const applyRequestPatches: <Req extends RequestInstance>(request: Req, patches: readonly AnyRequestPatch[]) => Req;
7
+ /** Applies patches to a listener, merging topic params, payloads and query params into what it already has */
8
+ export declare const applyListenerPatches: (listener: ListenerInstance, patches: readonly ListenerPatch[]) => ListenerInstance;
9
+ /** A unique id for transactions and temporary keys */
10
+ export declare const createId: () => string;
11
+ //# sourceMappingURL=request.utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.utils.d.ts","sourceRoot":"","sources":["../../src/utils/request.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAErF,eAAO,MAAM,aAAa,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAE7E,CAAC;AAaF,8GAA8G;AAC9G,eAAO,MAAM,mBAAmB,GAAI,GAAG,SAAS,eAAe,EAC7D,SAAS,GAAG,EACZ,SAAS,SAAS,eAAe,EAAE,KAClC,GAcF,CAAC;AAEF,8GAA8G;AAC9G,eAAO,MAAM,oBAAoB,GAAI,UAAU,gBAAgB,EAAE,SAAS,SAAS,aAAa,EAAE,qBAcjG,CAAC;AAIF,sDAAsD;AACtD,eAAO,MAAM,QAAQ,QAAO,MAM3B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@hyper-fetch/db",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Collections and live queries for Hyper Fetch: one source of truth for data from requests and sockets",
5
+ "author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
6
+ "homepage": "https://hyperfetch.bettertyped.com/",
7
+ "license": "Apache-2.0",
8
+ "main": "dist/index.mjs",
9
+ "module": "dist/index.mjs",
10
+ "types": "dist/index.d.ts",
11
+ "source": "src/index.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": {
15
+ "import": "./dist/index.d.ts"
16
+ },
17
+ "default": {
18
+ "require": "./dist/index.mjs",
19
+ "import": "./dist/index.mjs"
20
+ }
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "scripts": {
25
+ "test": "vitest run",
26
+ "start": "pnpm build && npx run-when-changed --watch 'src/**/*.ts' --exec 'pnpm build'",
27
+ "build": "vite build",
28
+ "lint": "oxlint .",
29
+ "format": "oxfmt --write .",
30
+ "typecheck": "tsgo --noEmit --emitDeclarationOnly false && tsgo --noEmit -p __tests__/tsconfig.json && node scripts/type-budget.mjs && node scripts/docs-typescript.mjs",
31
+ "tests": "pnpm lint-staged"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public",
35
+ "registry": "https://registry.npmjs.org/"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/BetterTyped/hyper-fetch.git",
40
+ "directory": "packages/db"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/BetterTyped/hyper-fetch/issues"
44
+ },
45
+ "peerDependencies": {
46
+ "@hyper-fetch/core": "*",
47
+ "@hyper-fetch/sockets": "*"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "@hyper-fetch/sockets": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "devDependencies": {
55
+ "ws": "^8.18.0",
56
+ "zod": "^4.4.1"
57
+ },
58
+ "lint-staged": {
59
+ "*.{js,jsx,ts,tsx}": [
60
+ "vitest related --run --passWithNoTests"
61
+ ]
62
+ },
63
+ "keywords": [
64
+ "database",
65
+ "collections",
66
+ "live queries",
67
+ "normalized cache",
68
+ "optimistic updates",
69
+ "offline",
70
+ "sync",
71
+ "typescript"
72
+ ]
73
+ }
package/project.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "name": "db",
3
+ "$schema": "../../node_modules/nx/schemas/project-schema.json"
4
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The API docs parse `src` with the TypeScript the documentation pins, which is older than the repo's. Code that
3
+ * only newer compilers accept, such as the built-in `NoInfer`, makes the docs build fail on main after merge.
4
+ * Compile `src` with that version here, so the failure shows in this package's typecheck instead.
5
+ */
6
+ import { execFileSync } from "node:child_process";
7
+ import { createRequire } from "node:module";
8
+ import path from "node:path";
9
+
10
+ const root = path.dirname(import.meta.dirname);
11
+ const require = createRequire(path.join(root, "../../documentation/package.json"));
12
+ const tsc = require.resolve("typescript/bin/tsc");
13
+ const { version } = require("typescript/package.json");
14
+
15
+ try {
16
+ execFileSync(process.execPath, [tsc, "--noEmit", "--emitDeclarationOnly", "false", "-p", "tsconfig.json"], {
17
+ cwd: root,
18
+ stdio: "inherit",
19
+ });
20
+ } catch {
21
+ console.error(`\nsrc does not compile with TypeScript ${version}, the version the API docs use.\n`);
22
+ process.exit(1);
23
+ }
24
+ process.stdout.write(`src compiles with TypeScript ${version}, the version the API docs use.\n`);
@@ -0,0 +1,37 @@
1
+ // Type-checks a db of 50 collections that uses every typed feature, and fails when it no longer compiles or when its
2
+ // instantiations grow past the budget. Instantiations are deterministic, unlike check time, so the budget holds on CI.
3
+ import { execFileSync } from "node:child_process";
4
+ import { createRequire } from "node:module";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ /** About 25% above the measured 257,186, so ordinary changes pass and a type that explodes does not */
8
+ const BUDGET = 320_000;
9
+
10
+ const require = createRequire(import.meta.url);
11
+ const tsc = require.resolve("typescript/bin/tsc");
12
+ const project = fileURLToPath(new URL("../__tests__/type-budget/tsconfig.json", import.meta.url));
13
+
14
+ let output;
15
+ try {
16
+ output = execFileSync(process.execPath, [tsc, "--noEmit", "-p", project, "--extendedDiagnostics"], {
17
+ encoding: "utf8",
18
+ });
19
+ } catch (error) {
20
+ console.error(error.stdout || error.message);
21
+ console.error("The type budget fixture does not compile.");
22
+ process.exit(1);
23
+ }
24
+
25
+ const instantiations = Number(/Instantiations:\s+(\d+)/.exec(output)?.[1]);
26
+ const checkTime = /Check time:\s+([\d.]+s)/.exec(output)?.[1];
27
+ if (!Number.isFinite(instantiations)) {
28
+ console.error(output);
29
+ console.error("Could not read the instantiation count.");
30
+ process.exit(1);
31
+ }
32
+ const summary = `${instantiations.toLocaleString("en")} instantiations (budget ${BUDGET.toLocaleString("en")}), check time ${checkTime}`;
33
+ if (instantiations > BUDGET) {
34
+ console.error(`Type budget exceeded: ${summary}`);
35
+ process.exit(1);
36
+ }
37
+ process.stdout.write(`Type budget: ${summary}\n`);
@@ -0,0 +1,330 @@
1
+ import type { ExtractResponseType, RequestInstance } from "@hyper-fetch/core";
2
+ import type { ListenerInstance } from "@hyper-fetch/sockets";
3
+
4
+ import type { InferSchemaInput, InferSchemaOutput, StandardSchemaV1 } from "../schema/schema.types";
5
+ import type {
6
+ AnyRequestPatch,
7
+ CollectionConfig,
8
+ CollectionOptions,
9
+ DefaultRows,
10
+ DeleteMutation,
11
+ DescribeLoader,
12
+ DescribeMutations,
13
+ Inferred,
14
+ IngestConfig,
15
+ IngestOptions,
16
+ IngestType,
17
+ InsertMutation,
18
+ IsExactRow,
19
+ IsIngestRow,
20
+ IsPartialRow,
21
+ IsSyncRow,
22
+ IsWriteHandled,
23
+ KeyFieldOf,
24
+ LoaderConfig,
25
+ LoaderDescriptor,
26
+ LoaderOptions,
27
+ MutationConfig,
28
+ MutationDescriptor,
29
+ RowMismatch,
30
+ SyncChangesOptions,
31
+ SyncConfig,
32
+ SyncMessage,
33
+ SyncOptions,
34
+ SyncType,
35
+ UpdateMutation,
36
+ } from "./collection.types";
37
+ import type {
38
+ IsResourceValid,
39
+ ResourceListOptions,
40
+ ResourceLoaders,
41
+ ResourceMutations,
42
+ ResourceOptions,
43
+ } from "./resource.types";
44
+
45
+ /**
46
+ * A typed set of complete rows, defined by a schema and a key. It declares how its backend loads rows (`load`), keeps
47
+ * them live (`sync`), feeds them from other responses (`ingest`) and changes them (`mutate`). A collection is
48
+ * immutable: every method returns a new collection, so it is defined in one chain and passed to `createDb`.
49
+ *
50
+ * When rows a method reads do not match the row type, it returns a `RowMismatch` instead of a collection, so the chain
51
+ * and `createDb` do not compile.
52
+ */
53
+ export class Collection<
54
+ Row,
55
+ Input = Row,
56
+ KeyField extends KeyFieldOf<Row> = KeyFieldOf<Row>,
57
+ Loaders extends LoaderDescriptor = never,
58
+ Mutations extends MutationDescriptor = {},
59
+ > {
60
+ /** Type-only carrier of the collection's generics, never set at runtime */
61
+ declare readonly __types?: { row: Row; input: Input; key: KeyField; loaders: Loaders; mutations: Mutations };
62
+
63
+ constructor(readonly config: CollectionConfig) {}
64
+
65
+ /**
66
+ * Adds a loader: a request plus the way to read complete rows from its response. A list loader declares the filters
67
+ * and orders it can send and whether it is paginated. A loader with `byKey` or `byKeys` reads rows by key.
68
+ */
69
+ load<Req extends RequestInstance, Mapped, Where, Order, Cursor, Limit, ByKey, ByKeys, LoaderNotation>(
70
+ request: Req,
71
+ options?: LoaderOptions<
72
+ Row,
73
+ NonNullable<Row[KeyField]>,
74
+ Req,
75
+ Mapped,
76
+ Where,
77
+ Order,
78
+ Cursor,
79
+ Limit,
80
+ ByKey,
81
+ ByKeys,
82
+ LoaderNotation
83
+ >,
84
+ ): IsExactRow<Inferred<Mapped, DefaultRows<Req>>, Row> extends true
85
+ ? Collection<
86
+ Row,
87
+ Input,
88
+ KeyField,
89
+ Loaders | DescribeLoader<Row, Where, Order, Cursor, Limit, ByKey, ByKeys, LoaderNotation>,
90
+ Mutations
91
+ >
92
+ : RowMismatch<Inferred<Mapped, DefaultRows<Req>>, Row> {
93
+ const loaderOptions = (options ?? {}) as Omit<LoaderConfig, "kind" | "request">;
94
+ let kind: LoaderConfig["kind"] = "list";
95
+ if (loaderOptions.byKey) {
96
+ kind = "byKey";
97
+ } else if (loaderOptions.byKeys) {
98
+ kind = "byKeys";
99
+ }
100
+ const loader: LoaderConfig = { ...loaderOptions, kind, request };
101
+ return new Collection({ ...this.config, loaders: [...this.config.loaders, loader] }) as never;
102
+ }
103
+
104
+ /**
105
+ * Derives loaders and mutations from an SDK resource that follows REST conventions: `$get` lists, `item.$get` reads
106
+ * by key, `$post` inserts, `item.$patch` or `item.$put` updates and `item.$delete` deletes. Path params of the list
107
+ * endpoint become required `eq` filters, and the query params listed in `list.where` become `eq` filters.
108
+ *
109
+ * @example
110
+ * collection(PostSchema, { key: "id" }).resource(sdk.posts, { item: "$postId" });
111
+ */
112
+ resource<Node, Item, Mapped, Filters, Cursor, InsertSuccess, UpdateSuccess, ListOption>(
113
+ node: Node,
114
+ options: ResourceOptions<Row, Node, Item, Mapped, Filters, Cursor, InsertSuccess, UpdateSuccess> & {
115
+ list?: ListOption;
116
+ },
117
+ ): IsResourceValid<
118
+ Row,
119
+ KeyField,
120
+ Node,
121
+ Item,
122
+ Mapped,
123
+ ListOption extends false ? false : true,
124
+ InsertSuccess,
125
+ UpdateSuccess
126
+ > extends true
127
+ ? Collection<
128
+ Row,
129
+ Input,
130
+ KeyField,
131
+ Loaders | ResourceLoaders<Row, Node, Item, Filters, Cursor, ListOption extends false ? false : true>,
132
+ Mutations & ResourceMutations<Input, Row, Node, Item>
133
+ >
134
+ : RowMismatch<unknown, Row> {
135
+ type Endpoint = Record<string, RequestInstance & Record<string, unknown>>;
136
+ const resourceNode = node as unknown as Endpoint;
137
+ const itemKey = options.item as string;
138
+ const itemParam = itemKey.slice(1);
139
+ const itemNode = resourceNode[itemKey] as unknown as Endpoint;
140
+ const toKeyPatch = (key: unknown): AnyRequestPatch => ({ params: { [itemParam]: key } });
141
+ const loaders: LoaderConfig[] = [];
142
+ const list =
143
+ options.list === false
144
+ ? undefined
145
+ : ((options.list as ResourceListOptions<Row, Node, Mapped, Filters, Cursor> | undefined) ?? {});
146
+ if (list) {
147
+ const listRequest = resourceNode.$get;
148
+ const endpoint = String(listRequest.requestOptions.endpoint);
149
+ const pathParams = [...endpoint.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]);
150
+ const where: NonNullable<LoaderConfig["where"]> = {};
151
+ pathParams.forEach((param) => {
152
+ where[param] = { eq: (value: unknown) => ({ params: { [param]: value } }), required: true };
153
+ });
154
+ (list.where ?? []).forEach((field) => {
155
+ where[field as string] = { eq: (value: unknown) => ({ queryParams: { [field as string]: value } }) };
156
+ });
157
+ loaders.push({
158
+ kind: "list",
159
+ request: listRequest,
160
+ rows: list.rows as LoaderConfig["rows"],
161
+ where,
162
+ cursor: list.cursor as LoaderConfig["cursor"],
163
+ page: list.page as LoaderConfig["page"],
164
+ });
165
+ }
166
+ loaders.push({ kind: "byKey", request: itemNode.$get, byKey: toKeyPatch });
167
+ return new Collection({
168
+ ...this.config,
169
+ loaders: [...this.config.loaders, ...loaders],
170
+ mutations: {
171
+ ...this.config.mutations,
172
+ insert: {
173
+ request: resourceNode.$post,
174
+ map: (row: unknown) => ({ payload: row }),
175
+ onSuccess: options.insert?.onSuccess,
176
+ },
177
+ update: {
178
+ request: itemNode[options.update?.method ?? "$patch"],
179
+ map: (key: unknown, changes: unknown) => ({ ...toKeyPatch(key), payload: changes }),
180
+ onSuccess: options.update?.onSuccess,
181
+ },
182
+ delete: { request: itemNode.$delete, map: (key: unknown) => toKeyPatch(key), onSuccess: "keep" },
183
+ },
184
+ }) as never;
185
+ }
186
+
187
+ /**
188
+ * Keeps rows current from a listener. `insert` messages carry complete rows, `update` messages the key and some
189
+ * fields, and `delete` messages the key. One listener can sync several collections.
190
+ */
191
+ sync<Listener extends ListenerInstance, Type extends SyncType, Mapped>(
192
+ listener: Listener,
193
+ options: SyncOptions<Row, KeyField, Listener, Type, Mapped>,
194
+ ): IsSyncRow<Row, KeyField, Type, Inferred<Mapped, SyncMessage<Listener>>> extends true
195
+ ? Collection<Row, Input, KeyField, Loaders, Mutations>
196
+ : RowMismatch<Inferred<Mapped, SyncMessage<Listener>>, Row> {
197
+ const sync = { ...options, listener } as SyncConfig;
198
+ return new Collection({ ...this.config, syncs: [...this.config.syncs, sync] }) as never;
199
+ }
200
+
201
+ /**
202
+ * Writes the rows nested in this collection's rows into another collection, for example the author of a post into
203
+ * the `user` collection. It runs on every complete write from the server: loads, inserts, ingested responses and
204
+ * mutation responses. The target is the collection itself, so renaming or removing it breaks the build.
205
+ *
206
+ * @example
207
+ * collection(PostSchema, { key: "id" }).normalize(User, (post) => (post.author ? [post.author] : []));
208
+ */
209
+ normalize<TargetRow, Mapped>(
210
+ target: { readonly config: CollectionConfig; readonly __types?: { row: TargetRow } },
211
+ extract: (row: Row) => readonly Mapped[],
212
+ ): ([Mapped] extends [never] ? true : IsExactRow<Mapped, TargetRow>) extends true
213
+ ? Collection<Row, Input, KeyField, Loaders, Mutations>
214
+ : RowMismatch<Mapped, TargetRow> {
215
+ const normalize = [...(this.config.normalize ?? []), { target: target.config, extract: extract as never }];
216
+ return new Collection({ ...this.config, normalize }) as never;
217
+ }
218
+
219
+ /**
220
+ * Keeps rows current from a listener whose events carry several changes at once, such as a Firestore snapshot.
221
+ * `changes` reads the complete rows to write and the keys to delete. With `notation`, the sync covers every subset
222
+ * by sending its conditions to the listener. Adapter presets such as `firestoreCollection` use it.
223
+ */
224
+ syncChanges<Listener extends ListenerInstance, Mapped>(
225
+ listener: Listener,
226
+ options: SyncChangesOptions<Row, KeyField, Listener, Mapped>,
227
+ ): ([Mapped] extends [never] ? true : IsExactRow<Mapped, Row>) extends true
228
+ ? Collection<Row, Input, KeyField, Loaders, Mutations>
229
+ : RowMismatch<Mapped, Row> {
230
+ const sync = { ...options, type: "changes", listener } as SyncConfig;
231
+ return new Collection({ ...this.config, syncs: [...this.config.syncs, sync] }) as never;
232
+ }
233
+
234
+ /**
235
+ * Writes the rows of another request's responses into the collection, for example a search endpoint or a
236
+ * `useSubmit` whose response is the changed row. The request does not become a loader.
237
+ */
238
+ ingest<Req extends RequestInstance, Mapped, Type>(
239
+ request: Req,
240
+ options?: IngestOptions<Req, Mapped, Type>,
241
+ ): IsIngestRow<Row, KeyField, Inferred<Type, "insert"> & IngestType, Inferred<Mapped, DefaultRows<Req>>> extends true
242
+ ? Collection<Row, Input, KeyField, Loaders, Mutations>
243
+ : RowMismatch<Inferred<Mapped, DefaultRows<Req>>, Row> {
244
+ const ingestOptions = (options ?? {}) as Partial<IngestConfig>;
245
+ const ingest: IngestConfig = { ...ingestOptions, request, type: ingestOptions.type ?? "insert" };
246
+ return new Collection({ ...this.config, ingests: [...this.config.ingests, ingest] }) as never;
247
+ }
248
+
249
+ /**
250
+ * Declares how inserts, updates and deletes reach the backend. Each `map` turns the write into the request's params,
251
+ * query params and payload. A response that is not the row needs `onSuccess`.
252
+ */
253
+ mutate<InsertReq, UpdateReq, DeleteReq, InsertMapped, UpdateMapped, InsertSuccess, UpdateSuccess>(mutations: {
254
+ insert?: InsertMutation<Row, InsertReq, InsertMapped, InsertSuccess>;
255
+ update?: UpdateMutation<Row, KeyField, UpdateReq, UpdateMapped, UpdateSuccess>;
256
+ delete?: DeleteMutation<Row, KeyField, DeleteReq>;
257
+ }): [
258
+ IsWriteHandled<InsertReq, IsExactRow<Inferred<InsertMapped, ExtractResponseType<InsertReq>>, Row>, InsertSuccess>,
259
+ IsWriteHandled<
260
+ UpdateReq,
261
+ IsPartialRow<Inferred<UpdateMapped, ExtractResponseType<UpdateReq>>, Row, KeyField>,
262
+ UpdateSuccess
263
+ >,
264
+ ] extends [true, true]
265
+ ? Collection<
266
+ Row,
267
+ Input,
268
+ KeyField,
269
+ Loaders,
270
+ Mutations & DescribeMutations<Input, Row, InsertReq, UpdateReq, DeleteReq>
271
+ >
272
+ : RowMismatch<ExtractResponseType<InsertReq> | ExtractResponseType<UpdateReq>, Row> {
273
+ const config = mutations as Record<"insert" | "update" | "delete", MutationConfig | undefined>;
274
+ return new Collection({
275
+ ...this.config,
276
+ mutations: {
277
+ ...this.config.mutations,
278
+ ...(config.insert ? { insert: config.insert } : {}),
279
+ ...(config.update ? { update: config.update } : {}),
280
+ ...(config.delete ? { delete: config.delete } : {}),
281
+ },
282
+ }) as never;
283
+ }
284
+ }
285
+
286
+ /** Any collection, whatever its row type */
287
+ export type CollectionInstance = {
288
+ readonly config: CollectionConfig;
289
+ readonly __types?: { row: any; input: any; key: any; loaders: any; mutations: any };
290
+ };
291
+
292
+ const emptyConfig = (options: CollectionOptions<any, string>, schema?: StandardSchemaV1): CollectionConfig => ({
293
+ schema,
294
+ key: options.key,
295
+ version: options.version,
296
+ validate: options.validate ?? "client",
297
+ loaders: [],
298
+ syncs: [],
299
+ ingests: [],
300
+ mutations: {},
301
+ });
302
+
303
+ /** A row type without a schema, for `collection(rowType<Post>(), { key: "id" })`. Rows are not validated. */
304
+ export type RowType<Row> = { readonly kind: "row-type"; readonly __row?: Row };
305
+
306
+ /** Declares a collection's row type without a schema, so writes are not validated */
307
+ export const rowType = <Row>(): RowType<Row> => ({ kind: "row-type" });
308
+
309
+ /**
310
+ * Creates a collection from a Standard Schema, such as a Zod, Valibot or ArkType schema, or from `rowType<Row>()`.
311
+ *
312
+ * @example
313
+ * const Post = collection(PostSchema, { key: "id", version: "updatedAt" });
314
+ * const Draft = collection(rowType<Draft>(), { key: "id" });
315
+ */
316
+ export function collection<Schema extends StandardSchemaV1, KeyField extends KeyFieldOf<InferSchemaOutput<Schema>>>(
317
+ schema: Schema,
318
+ options: CollectionOptions<InferSchemaOutput<Schema>, KeyField>,
319
+ ): Collection<InferSchemaOutput<Schema>, InferSchemaInput<Schema>, KeyField>;
320
+ export function collection<Row, KeyField extends KeyFieldOf<Row>>(
321
+ type: RowType<Row>,
322
+ options: CollectionOptions<Row, KeyField>,
323
+ ): Collection<Row, Row, KeyField>;
324
+ export function collection(
325
+ schemaOrType: StandardSchemaV1 | RowType<unknown>,
326
+ options: CollectionOptions<any, string>,
327
+ ): CollectionInstance {
328
+ const schema = "~standard" in schemaOrType ? schemaOrType : undefined;
329
+ return new Collection(emptyConfig(options, schema));
330
+ }