@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,199 @@
1
+ import type {
2
+ AnyRequestPatch,
3
+ CollectionConfig,
4
+ LoaderConfig,
5
+ RowKey,
6
+ SortDirection,
7
+ } from "../collection/collection.types";
8
+ import type { DbNotation } from "../db/db.types";
9
+ import type { ComparisonNode, ExpressionNode, SendableNode } from "../operators/operators.types";
10
+ import { getExpressionFields, splitAnd, stableStringify } from "../operators/operators.utils";
11
+ import type { QueryDefinition } from "./query.types";
12
+
13
+ export type ListPlan = {
14
+ kind: "list";
15
+ loaderIndex: number;
16
+ /** Conditions sent to the backend */
17
+ sent: SendableNode[];
18
+ /** Conditions evaluated on the rows the db holds */
19
+ local: ExpressionNode[];
20
+ /** Whether the query's order is sent to the backend */
21
+ sendOrder: boolean;
22
+ /** Whether the query's limit is sent to the backend */
23
+ sendLimit: boolean;
24
+ paginated: boolean;
25
+ /** Whether the query filters or sorts by a field the backend compares differently, so it is never answered locally */
26
+ serverOnly: boolean;
27
+ subsetId: string;
28
+ };
29
+
30
+ export type OnePlan = { kind: "one"; key: RowKey; loaderIndex: number | undefined };
31
+
32
+ export type LocalPlan = { kind: "local" };
33
+
34
+ export type ErrorPlan = { kind: "error"; error: Error };
35
+
36
+ export type QueryPlan = ListPlan | OnePlan | LocalPlan | ErrorPlan;
37
+
38
+ export const isPaginatedLoader = (loader: LoaderConfig) => Boolean(loader.cursor || loader.limit);
39
+
40
+ /**
41
+ * How a loader sends a comparison: its own mapping, the db-wide notation for one declared with `true`, or the loader's
42
+ * adapter notation for any field. `undefined` when it cannot send it.
43
+ */
44
+ export const getWhereMapping = (
45
+ loader: LoaderConfig,
46
+ node: SendableNode,
47
+ notation: DbNotation | undefined,
48
+ ): ((value: unknown) => AnyRequestPatch) | undefined => {
49
+ if (node.op === "server") {
50
+ // Server-only operators have no notation, so the loader maps them itself
51
+ const declaration = (loader.where?.[node.field] as Record<string, unknown> | undefined)?.[node.name];
52
+ return typeof declaration === "function" ? (declaration as (value: unknown) => AnyRequestPatch) : undefined;
53
+ }
54
+ const declaration = loader.where?.[node.field]?.[node.op];
55
+ if (typeof declaration === "function") {
56
+ return declaration as (value: unknown) => AnyRequestPatch;
57
+ }
58
+ const shared = declaration === true ? notation?.where?.[node.op] : loader.notation?.where?.[node.op];
59
+ return shared && ((value) => shared(node.field, value));
60
+ };
61
+
62
+ /** How a loader sends an order, resolved like `getWhereMapping` */
63
+ export const getOrderMapping = (
64
+ loader: LoaderConfig,
65
+ field: string,
66
+ notation: DbNotation | undefined,
67
+ ): ((direction: SortDirection) => AnyRequestPatch) | undefined => {
68
+ const declaration = loader.orderBy?.[field];
69
+ if (typeof declaration === "function") {
70
+ return declaration as (direction: SortDirection) => AnyRequestPatch;
71
+ }
72
+ const shared = declaration === true ? notation?.orderBy : loader.notation?.orderBy;
73
+ return shared && ((direction) => shared(field, direction));
74
+ };
75
+
76
+ /** Whether an expression uses a server-only operator anywhere */
77
+ const containsServerNode = (node: ExpressionNode): boolean => {
78
+ if (node.op === "and" || node.op === "or") {
79
+ return node.items.some(containsServerNode);
80
+ }
81
+ if (node.op === "not") {
82
+ return containsServerNode(node.item);
83
+ }
84
+ return node.op === "server";
85
+ };
86
+
87
+ /** Whether a loader can send a condition. `and`, `or` and `not` run on the client. */
88
+ export const canSend = (loader: LoaderConfig, node: ExpressionNode, notation: DbNotation | undefined): boolean => {
89
+ if (node.op === "and" || node.op === "or" || node.op === "not") {
90
+ return false;
91
+ }
92
+ return Boolean(getWhereMapping(loader, node, notation));
93
+ };
94
+
95
+ const canSendOrder = (loader: LoaderConfig, field: string, notation: DbNotation | undefined) =>
96
+ Boolean(getOrderMapping(loader, field, notation));
97
+
98
+ /** Builds the id of the loaded subset that serves a plan, shared by every query with the same backend request */
99
+ export const getSubsetId = (
100
+ collectionName: string,
101
+ plan: Omit<ListPlan, "subsetId">,
102
+ definition: QueryDefinition,
103
+ ): string => {
104
+ const sent = plan.sent.map((node) => stableStringify(node)).toSorted();
105
+ return stableStringify([
106
+ collectionName,
107
+ plan.loaderIndex,
108
+ sent,
109
+ plan.sendOrder ? definition.orderBy : null,
110
+ plan.sendLimit ? definition.limit : null,
111
+ ]);
112
+ };
113
+
114
+ /**
115
+ * Picks how the db serves a query. Among the list loaders whose required filters the query sets, it picks the one that
116
+ * can send the most of the query's top-level conditions; ties go to the loader declared first. A paginated loader is a
117
+ * candidate only when it can send every condition and order, because filtering one page on the client is wrong.
118
+ */
119
+ export const planQuery = ({
120
+ collectionName,
121
+ config,
122
+ definition,
123
+ notation,
124
+ }: {
125
+ collectionName: string;
126
+ config: CollectionConfig;
127
+ definition: QueryDefinition;
128
+ notation: DbNotation | undefined;
129
+ }): QueryPlan => {
130
+ if (definition.one) {
131
+ const index = config.loaders.findIndex((loader) => loader.kind === "byKeys");
132
+ const byKey = config.loaders.findIndex((loader) => loader.kind === "byKey");
133
+ const loaderIndex = index === -1 ? byKey : index;
134
+ const usable = !definition.local && loaderIndex !== -1;
135
+ return { kind: "one", key: definition.one.key, loaderIndex: usable ? loaderIndex : undefined };
136
+ }
137
+
138
+ if (definition.local) {
139
+ if (definition.where && containsServerNode(definition.where)) {
140
+ return { kind: "error", error: new Error("A local query cannot use a server-only operator") };
141
+ }
142
+ return { kind: "local" };
143
+ }
144
+
145
+ const conditions = splitAnd(definition.where);
146
+ const eqFields = new Set(
147
+ conditions.filter((node): node is ComparisonNode => node.op === "eq").map((node) => node.field),
148
+ );
149
+
150
+ let best: Omit<ListPlan, "subsetId"> | undefined;
151
+
152
+ config.loaders.forEach((loader, loaderIndex) => {
153
+ if (loader.kind !== "list") {
154
+ return;
155
+ }
156
+ const required = Object.keys(loader.where ?? {}).filter((field) => loader.where?.[field]?.required);
157
+ if (!required.every((field) => eqFields.has(field))) {
158
+ return;
159
+ }
160
+ const sent = conditions.filter((node): node is SendableNode => canSend(loader, node, notation));
161
+ const local = conditions.filter((node) => !canSend(loader, node, notation));
162
+ const ordersSendable = definition.orderBy.every((order) => canSendOrder(loader, order.field, notation));
163
+ const paginated = isPaginatedLoader(loader);
164
+ if (paginated && (local.length > 0 || !ordersSendable)) {
165
+ return;
166
+ }
167
+ // The client cannot evaluate a server-only operator, so a loader that cannot send it cannot serve the query
168
+ if (local.some((node) => containsServerNode(node))) {
169
+ return;
170
+ }
171
+ if (best && best.sent.length >= sent.length) {
172
+ return;
173
+ }
174
+ const serverOnly = new Set(loader.serverOnly);
175
+ const readFields = [
176
+ ...conditions.flatMap((node) => getExpressionFields(node)),
177
+ ...definition.orderBy.map((order) => order.field),
178
+ ];
179
+ best = {
180
+ kind: "list",
181
+ loaderIndex,
182
+ sent,
183
+ local,
184
+ sendOrder: ordersSendable && definition.orderBy.length > 0,
185
+ sendLimit: Boolean(loader.limit && definition.limit !== undefined),
186
+ paginated,
187
+ serverOnly: readFields.some((field) => serverOnly.has(field)) || sent.some((node) => node.op === "server"),
188
+ };
189
+ });
190
+
191
+ if (!best) {
192
+ return {
193
+ kind: "error",
194
+ error: new Error(`No loader of "${collectionName}" can serve this query. Set its required filters.`),
195
+ };
196
+ }
197
+
198
+ return { ...best, subsetId: getSubsetId(collectionName, best, definition) };
199
+ };
@@ -0,0 +1,319 @@
1
+ import type { SortDirection } from "../collection/collection.types";
2
+ import type { DbRuntime } from "../db/db.runtime";
3
+ import type {
4
+ Condition,
5
+ ExtractConditionEq,
6
+ ExtractConditionTokens,
7
+ FieldRef,
8
+ RowRefs,
9
+ } from "../operators/operators.types";
10
+ import { stableStringify } from "../operators/operators.utils";
11
+ import type { InfiniteQueryOptions } from "./infinite-query";
12
+ import { InfiniteQuery } from "./infinite-query";
13
+ import type { IsServable, QueryDefinition, QueryExplanation, QueryState } from "./query.types";
14
+
15
+ const createRefs = <Row>(): RowRefs<Row> => {
16
+ return new Proxy(
17
+ {},
18
+ {
19
+ get: (_target, field) => ({ kind: "field", field }),
20
+ },
21
+ ) as RowRefs<Row>;
22
+ };
23
+
24
+ /** What a query's `data` holds: a list of results, or one result for `findOne` */
25
+ export type QueryData<Result, Mode extends "list" | "one"> = Mode extends "one" ? Result : Result[];
26
+
27
+ /** A collection a query can join: a handle of the db, with its name, row and key field */
28
+ export type JoinTarget = { readonly collectionName: string; readonly __types?: { row: unknown; key: string } };
29
+
30
+ /** The row of a joined collection */
31
+ export type JoinedRowOf<Target extends JoinTarget> = NonNullable<Target["__types"]>["row"];
32
+
33
+ /** The key type of a joined collection, which the foreign key must hold */
34
+ export type JoinedKeyOf<Target extends JoinTarget> = JoinedRowOf<Target>[NonNullable<Target["__types"]>["key"] &
35
+ keyof JoinedRowOf<Target>];
36
+
37
+ /** What a join adds to each result: one row, one row or `undefined`, or an array of rows with `on` */
38
+ export type JoinedValue<JoinedRow, On, Type> = unknown extends On
39
+ ? [Type] extends ["inner"]
40
+ ? JoinedRow
41
+ : JoinedRow | undefined
42
+ : JoinedRow[];
43
+
44
+ /** The value the foreign key must hold: the joined collection's key, or its `on` field */
45
+ export type JoinedMatchOf<Target extends JoinTarget, On> = unknown extends On
46
+ ? JoinedKeyOf<Target>
47
+ : On extends keyof JoinedRowOf<Target>
48
+ ? JoinedRowOf<Target>[On]
49
+ : never;
50
+
51
+ /** The field that holds the joined key, alone or with join options */
52
+ export type JoinSpec<Row, Field extends keyof Row & string, Match, On, Type> =
53
+ | JoinBy<Row, Field, Match>
54
+ | { by: JoinBy<Row, Field, Match>; on?: On; type?: Type & ("left" | "inner") };
55
+
56
+ /** Picks the field of a row that holds the joined key or value */
57
+ export type JoinBy<Row, Field extends keyof Row & string, Match> = (
58
+ row: RowRefs<Row>,
59
+ ) => FieldRef<Field, Row[Field] & (Match | null | undefined)>;
60
+
61
+ /** The result of a query with one more joined value */
62
+ type Joined<Result, Name extends string, Value> = {
63
+ [Field in keyof Result | Name]: Field extends Name ? Value : Field extends keyof Result ? Result[Field] : never;
64
+ };
65
+
66
+ type Selected<Selection> = {
67
+ [Output in keyof Selection]: Selection[Output] extends FieldRef<string, infer Value> ? Value : never;
68
+ };
69
+
70
+ /**
71
+ * An immutable description of a query over one collection. Each method returns a new query, and two queries with the
72
+ * same structure are the same query, so a component can rebuild its query on every render.
73
+ *
74
+ * The type parameters record what the query asks a backend for, so the types can check that a loader serves it.
75
+ */
76
+ export class Query<
77
+ Row,
78
+ Loaders,
79
+ Result,
80
+ Tokens extends string = never,
81
+ Eq extends string = never,
82
+ Order extends string = never,
83
+ Mode extends "list" | "one" = "list",
84
+ Local extends boolean = false,
85
+ > {
86
+ /** Type-only carrier of the query's generics, never set at runtime */
87
+ declare readonly __types?: {
88
+ row: Row;
89
+ loaders: Loaders;
90
+ result: Result;
91
+ tokens: Tokens;
92
+ eq: Eq;
93
+ order: Order;
94
+ mode: Mode;
95
+ local: Local;
96
+ };
97
+
98
+ /** Identifies the query by its structure */
99
+ readonly key: string;
100
+
101
+ constructor(
102
+ private readonly runtime: DbRuntime,
103
+ readonly definition: QueryDefinition,
104
+ ) {
105
+ this.key = stableStringify(definition);
106
+ }
107
+
108
+ /**
109
+ * Filters rows. The db splits the condition at its top-level `and`: conditions the loader declares are sent to the
110
+ * backend, and the rest run on the rows the db holds. Calling it again adds conditions.
111
+ */
112
+ where<C extends Condition<string, string>>(
113
+ this: Query<Row, Loaders, Result, Tokens, Eq, Order, "list", Local>,
114
+ callback: (row: RowRefs<Row>) => C,
115
+ ): Query<Row, Loaders, Result, Tokens | ExtractConditionTokens<C>, Eq | ExtractConditionEq<C>, Order, Mode, Local> {
116
+ const { node } = callback(createRefs<Row>());
117
+ const where = this.definition.where ? { op: "and" as const, items: [this.definition.where, node] } : node;
118
+ return new Query(this.runtime, { ...this.definition, where });
119
+ }
120
+
121
+ /** Sorts rows by a field. Calling it again adds a sort that breaks ties of the previous ones. */
122
+ orderBy<Name extends keyof Row & string>(
123
+ this: Query<Row, Loaders, Result, Tokens, Eq, Order, "list", Local>,
124
+ callback: (row: RowRefs<Row>) => FieldRef<Name, Row[Name]>,
125
+ direction: SortDirection = "asc",
126
+ ): Query<Row, Loaders, Result, Tokens, Eq, Order | Name, Mode, Local> {
127
+ const { field } = callback(createRefs<Row>());
128
+ return new Query(this.runtime, { ...this.definition, orderBy: [...this.definition.orderBy, { field, direction }] });
129
+ }
130
+
131
+ /** Picks and renames the fields each result holds */
132
+ select<Selection extends Record<string, FieldRef<string, unknown>>>(
133
+ callback: (row: RowRefs<Row>) => Selection,
134
+ ): Query<Row, Loaders, Selected<Selection>, Tokens, Eq, Order, Mode, Local> {
135
+ const selection = callback(createRefs<Row>());
136
+ const select = Object.fromEntries(Object.entries(selection).map(([output, ref]) => [output, ref.field]));
137
+ return new Query(this.runtime, { ...this.definition, select });
138
+ }
139
+
140
+ /**
141
+ * Adds the row of another collection whose key is the given field, as a left join: each result holds it under `name`,
142
+ * or `undefined` while it is not loaded or when there is none. With `{ type: "inner" }`, results without a joined row
143
+ * are left out. With `{ on: "postId" }`, the join matches that field of the joined collection instead of its key and
144
+ * holds an array of every matching row, loaded through a list loader that can send `inArray` on it. Options go in an
145
+ * object with the field as `by`, as in `join("comments", db.comment, { by: (post) => post.id, on: "postId" })`. The db loads joined rows in batches through the joined
146
+ * collection's key loader, and a result updates whenever its joined row changes. Joined rows are loaded by key, so
147
+ * only syncs without `where` reach them.
148
+ */
149
+ join<Name extends string, Target extends JoinTarget, Field extends keyof Row & string, const On, const Type>(
150
+ name: Name,
151
+ collection: Target,
152
+ by: JoinSpec<Row, Field, JoinedMatchOf<Target, On>, On, Type>,
153
+ ): Query<
154
+ Row,
155
+ Loaders,
156
+ Joined<Result, Name, JoinedValue<JoinedRowOf<Target>, On, Type>>,
157
+ Tokens,
158
+ Eq,
159
+ Order,
160
+ Mode,
161
+ Local
162
+ > {
163
+ const options: { type?: string; on?: unknown } = typeof by === "function" ? {} : by;
164
+ const callback = typeof by === "function" ? by : by.by;
165
+ const { field } = callback(createRefs<Row>());
166
+ const join = {
167
+ name,
168
+ collection: collection.collectionName,
169
+ field,
170
+ ...(options.type === "inner" ? { type: "inner" as const } : {}),
171
+ ...(options.on ? { on: options.on as string } : {}),
172
+ };
173
+ return new Query(this.runtime, { ...this.definition, joins: [...(this.definition.joins ?? []), join] });
174
+ }
175
+
176
+ /** Limits the number of results. A paginated loader that declares `limit` receives it as its page size. */
177
+ limit(
178
+ this: Query<Row, Loaders, Result, Tokens, Eq, Order, "list", Local>,
179
+ limit: number,
180
+ ): Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, Local> {
181
+ return new Query(this.runtime, { ...this.definition, limit });
182
+ }
183
+
184
+ /** Reads only the rows the db holds and never sends a request */
185
+ local(): Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, true> {
186
+ return new Query(this.runtime, { ...this.definition, local: true });
187
+ }
188
+
189
+ /**
190
+ * Subscribes to the query's state. The first subscriber attaches the query to the subset that serves it, which loads
191
+ * when it is stale. Returns a function that unsubscribes.
192
+ */
193
+ subscribe(
194
+ this: Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, Local> &
195
+ ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local>,
196
+ listener: () => void,
197
+ ): () => void {
198
+ return this.runtime.getLiveQuery(this.definition).subscribe(listener);
199
+ }
200
+
201
+ /** The current state. It keeps its identity until something changes, as `useSyncExternalStore` expects. */
202
+ getSnapshot(): QueryState<QueryData<Result, Mode>> {
203
+ return this.runtime.getLiveQuery(this.definition).getState() as QueryState<QueryData<Result, Mode>>;
204
+ }
205
+
206
+ /** Reads the query once: resolves with the first state that is not loading */
207
+ get(
208
+ this: Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, Local> &
209
+ ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local>,
210
+ ): Promise<QueryState<QueryData<Result, Mode>>> {
211
+ const live = this.runtime.getLiveQuery(this.definition);
212
+ return new Promise((resolve) => {
213
+ let settled = false;
214
+ const settle = () => {
215
+ const state = live.getState();
216
+ if (settled || state.status === "loading") {
217
+ return;
218
+ }
219
+ settled = true;
220
+ resolve(state as QueryState<QueryData<Result, Mode>>);
221
+ // The first state can arrive while subscribing, before `unsubscribe` exists
222
+ queueMicrotask(() => unsubscribe());
223
+ };
224
+ const unsubscribe = live.subscribe(settle);
225
+ settle();
226
+ });
227
+ }
228
+
229
+ /**
230
+ * A window over the query's ordered result, widened one page at a time with `fetchNextPage`. Rows the db holds show
231
+ * at once, and the loader loads more only when the window runs past them. The query must have `orderBy`, so a page
232
+ * never shifts between renders.
233
+ *
234
+ * @example
235
+ * const feed = db.post.orderBy((post) => post.createdAt, "desc").infinite({ pageSize: 20 });
236
+ * feed.subscribe(() => render(feed.getSnapshot().pages));
237
+ */
238
+ infinite(
239
+ this: Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, Local> &
240
+ ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local> &
241
+ InfiniteCheck<Order, Mode>,
242
+ options: InfiniteQueryOptions,
243
+ ): InfiniteQuery<Result> {
244
+ return new InfiniteQuery<Result>(this.runtime, this.definition, options);
245
+ }
246
+
247
+ /** Loads the query's subset again */
248
+ refetch(): Promise<void> {
249
+ return this.runtime.getLiveQuery(this.definition).refetch();
250
+ }
251
+
252
+ /** Loads the next page of a paginated query */
253
+ fetchNextPage(): Promise<void> {
254
+ return this.runtime.getLiveQuery(this.definition).fetchNextPage();
255
+ }
256
+
257
+ /** How the db serves the query: the loader, what is sent, what runs locally and which syncs keep it live */
258
+ explain(): QueryExplanation {
259
+ return this.runtime.getLiveQuery(this.definition).explain();
260
+ }
261
+ }
262
+
263
+ /** Fails to compile when no loader can serve the query */
264
+ export type ServableCheck<
265
+ Loaders,
266
+ Tokens extends string,
267
+ Eq extends string,
268
+ Order extends string,
269
+ Mode extends "list" | "one",
270
+ Local extends boolean,
271
+ > = IsServable<Loaders, Tokens, Eq, Order, Mode, Local> extends true ? unknown : { servable: never };
272
+
273
+ /** Fails to compile for a query without `orderBy` or one that reads one row */
274
+ export type InfiniteCheck<Order extends string, Mode extends "list" | "one"> = [Order] extends [never]
275
+ ? { orderBy: never }
276
+ : Mode extends "one"
277
+ ? { list: never }
278
+ : unknown;
279
+
280
+ /** The type arguments a query instance records, read directly so that `never` stays `never` */
281
+ type QueryTypes<Q> = Q extends { __types?: infer Types } ? NonNullable<Types> : never;
282
+
283
+ /** Fails to compile when a query cannot be read as an infinite query */
284
+ export type InfiniteQueryCheck<Q> =
285
+ QueryTypes<Q> extends {
286
+ loaders: infer Loaders;
287
+ tokens: infer Tokens extends string;
288
+ eq: infer Eq extends string;
289
+ order: infer Order extends string;
290
+ mode: infer Mode extends "list" | "one";
291
+ local: infer Local extends boolean;
292
+ }
293
+ ? ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local> & InfiniteCheck<Order, Mode>
294
+ : never;
295
+
296
+ /** The item type of a query instance's results */
297
+ export type ExtractQueryResult<Q> = QueryTypes<Q> extends { result: infer Result } ? Result : never;
298
+
299
+ /** Any query, whatever its collection and result */
300
+ export type QueryInstance = Query<any, any, any, any, any, any, any, any>;
301
+
302
+ /** Fails to compile when no loader can serve the query */
303
+ export type ServableQuery<Q> =
304
+ QueryTypes<Q> extends {
305
+ loaders: infer Loaders;
306
+ tokens: infer Tokens extends string;
307
+ eq: infer Eq extends string;
308
+ order: infer Order extends string;
309
+ mode: infer Mode extends "list" | "one";
310
+ local: infer Local extends boolean;
311
+ }
312
+ ? ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local>
313
+ : never;
314
+
315
+ /** The data of a query instance */
316
+ export type ExtractQueryData<Q> =
317
+ QueryTypes<Q> extends { result: infer Result; mode: infer Mode extends "list" | "one" }
318
+ ? QueryData<Result, Mode>
319
+ : never;
@@ -0,0 +1,90 @@
1
+ import type { ListLoaderDescriptor, RowKey, SortDirection } from "../collection/collection.types";
2
+ import type { ComparisonOperator, ExpressionNode, LocalToken, SendableNode } from "../operators/operators.types";
3
+
4
+ /** A query as data. Two queries with the same definition are the same query. */
5
+ export type QueryDefinition = {
6
+ collection: string;
7
+ where?: ExpressionNode;
8
+ orderBy: { field: string; direction: SortDirection }[];
9
+ /** Output name to row field */
10
+ select?: Record<string, string>;
11
+ limit?: number;
12
+ one?: { key: RowKey };
13
+ local: boolean;
14
+ /** Left joins on another collection's key: each result carries the joined row under `name` */
15
+ joins?: { name: string; collection: string; field: string; type?: "inner"; on?: string }[];
16
+ };
17
+
18
+ export type QueryStatus = "loading" | "ready" | "error";
19
+
20
+ export type QueryState<Data> = {
21
+ /** `undefined` until the query has loaded, then the selected fields of every row */
22
+ data: Data | undefined;
23
+ /** `error` only when a first load failed and there is nothing to show */
24
+ status: QueryStatus;
25
+ /** The last failure, also when a refresh failed and the rows stay */
26
+ error: unknown;
27
+ /** Whether the rows may be out of date: their subset is stale or its syncs are disconnected */
28
+ stale: boolean;
29
+ /** Whether a request for the query is in flight */
30
+ isFetching: boolean;
31
+ /** Whether a paginated query has another page */
32
+ hasNextPage: boolean;
33
+ };
34
+
35
+ /** How the db serves a query, from `query.explain()` */
36
+ export type QueryExplanation = {
37
+ kind: "list" | "one" | "local" | "error";
38
+ /** Index of the loader in the collection's chain */
39
+ loader?: number;
40
+ /** Conditions sent to the backend */
41
+ sent: SendableNode[];
42
+ /** Conditions evaluated on the rows the db holds */
43
+ local: ExpressionNode[];
44
+ /** Whether rows the db already holds answer the query, with no request */
45
+ answeredLocally: boolean;
46
+ /** The syncs that keep the result live */
47
+ syncs: { type: "insert" | "update" | "delete" | "changes"; topic: string }[];
48
+ error?: Error;
49
+ };
50
+
51
+ /**
52
+ * Whether some loader can serve a query: the query sets its required filters, and a paginated loader can send every
53
+ * condition and order.
54
+ */
55
+ export type IsServable<
56
+ Loaders,
57
+ Tokens extends string,
58
+ Eq extends string,
59
+ Order extends string,
60
+ Mode extends "list" | "one",
61
+ Local extends boolean,
62
+ > = Local extends true
63
+ ? true
64
+ : Mode extends "one"
65
+ ? [Extract<Loaders, { kind: "key" }>] extends [never]
66
+ ? false
67
+ : true
68
+ : true extends ServableBy<Loaders, Tokens, Eq, Order>
69
+ ? true
70
+ : false;
71
+
72
+ /** Tokens of server-only operators, which the loader must send because the client cannot evaluate them */
73
+ type ServerTokens<Tokens extends string> = Tokens extends `${string}:${ComparisonOperator}` | LocalToken
74
+ ? never
75
+ : Tokens;
76
+
77
+ type ServableBy<Loaders, Tokens extends string, Eq extends string, Order extends string> =
78
+ Loaders extends ListLoaderDescriptor<infer Required, infer LoaderTokens, infer LoaderOrder, infer Paginated>
79
+ ? [Required] extends [Eq]
80
+ ? [ServerTokens<Tokens>] extends [LoaderTokens]
81
+ ? Paginated extends true
82
+ ? [Tokens] extends [LoaderTokens]
83
+ ? [Order] extends [LoaderOrder]
84
+ ? true
85
+ : false
86
+ : false
87
+ : true
88
+ : false
89
+ : false
90
+ : false;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The [Standard Schema](https://standardschema.dev) interface. Zod, Valibot, ArkType and other libraries implement it,
3
+ * so a collection accepts any of them without an adapter.
4
+ */
5
+ export type StandardSchemaV1<Input = unknown, Output = Input> = {
6
+ readonly "~standard": StandardSchemaV1Props<Input, Output>;
7
+ };
8
+
9
+ export type StandardSchemaV1Props<Input = unknown, Output = Input> = {
10
+ readonly version: 1;
11
+ readonly vendor: string;
12
+ readonly validate: (value: unknown) => StandardSchemaV1Result<Output> | Promise<StandardSchemaV1Result<Output>>;
13
+ readonly types?: { readonly input: Input; readonly output: Output } | undefined;
14
+ };
15
+
16
+ export type StandardSchemaV1Result<Output> =
17
+ | { readonly value: Output; readonly issues?: undefined }
18
+ | { readonly issues: readonly StandardSchemaV1Issue[] };
19
+
20
+ export type StandardSchemaV1Issue = {
21
+ readonly message: string;
22
+ readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[] | undefined;
23
+ };
24
+
25
+ /** The type a schema accepts */
26
+ export type InferSchemaInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
27
+
28
+ /** The type a schema produces */
29
+ export type InferSchemaOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];