@hyper-fetch/db 0.0.0-stage → 10.2.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,4 @@
1
+ {
2
+ "extends": "../tsconfig.json",
3
+ "include": ["budget.fixture.ts", "../../../../global.d.ts"]
4
+ }
@@ -0,0 +1,225 @@
1
+ import { Client } from "@hyper-fetch/core";
2
+ import { Socket } from "@hyper-fetch/sockets";
3
+ import { HttpResponse, http } from "msw";
4
+ import { z } from "zod";
5
+
6
+ export const BASE_URL = "http://localhost:5000";
7
+ export const SOCKET_URL = "ws://localhost:1234";
8
+
9
+ export const PostSchema = z.object({
10
+ id: z.number(),
11
+ teamId: z.number(),
12
+ title: z.string().min(1),
13
+ body: z.string(),
14
+ likes: z.number(),
15
+ archived: z.boolean(),
16
+ createdAt: z.string(),
17
+ updatedAt: z.number(),
18
+ });
19
+
20
+ export const PostSummarySchema = PostSchema.omit({ body: true });
21
+
22
+ export type Post = z.infer<typeof PostSchema>;
23
+ export type PostSummary = z.infer<typeof PostSummarySchema>;
24
+
25
+ export const createPost = (id: number, overrides: Partial<Post> = {}): Post => ({
26
+ id,
27
+ teamId: 1,
28
+ title: `Post ${id}`,
29
+ body: `Body of post ${id}`,
30
+ likes: id,
31
+ archived: false,
32
+ createdAt: `2026-01-${String(id).padStart(2, "0")}`,
33
+ updatedAt: 1,
34
+ ...overrides,
35
+ });
36
+
37
+ export const toSummary = ({ body: _body, ...summary }: Post): PostSummary => summary;
38
+
39
+ export const createHttpClient = (url = BASE_URL) => new Client({ url });
40
+
41
+ export type HttpClient = ReturnType<typeof createHttpClient>;
42
+
43
+ export const createRequests = (client: HttpClient) => ({
44
+ getTeamPosts: client.createRequest<{
45
+ response: PostSummary[];
46
+ queryParams?: { likes_gt?: number; sort?: string; limit?: number; title?: string };
47
+ }>()({ endpoint: "/teams/:teamId/posts" }),
48
+ getTeamFullPosts: client.createRequest<{
49
+ response: { items: Post[] };
50
+ queryParams?: { likes_gt?: number; sort?: string; limit?: number };
51
+ }>()({ endpoint: "/teams/:teamId/full-posts" }),
52
+ getAllPosts: client.createRequest<{
53
+ response: { items: Post[]; next: string | null };
54
+ queryParams?: { cursor?: string; sort?: string; limit?: number };
55
+ }>()({ endpoint: "/all-posts" }),
56
+ getPost: client.createRequest<{ response: Post }>()({ endpoint: "/posts/:postId" }),
57
+ getPostsByIds: client.createRequest<{ response: Post[]; queryParams?: { ids?: number[] } }>()({
58
+ endpoint: "/posts-by-ids",
59
+ }),
60
+ searchPosts: client.createRequest<{ response: { results: Post[] }; queryParams?: { q?: string } }>()({
61
+ endpoint: "/search",
62
+ }),
63
+ createPostRequest: client.createRequest<{ response: Post; payload: Omit<Post, "id"> & { id?: number } }>()({
64
+ endpoint: "/posts",
65
+ method: "POST",
66
+ }),
67
+ updatePostRequest: client.createRequest<{ response: Post; payload: Partial<Post> }>()({
68
+ endpoint: "/posts/:postId",
69
+ method: "PATCH",
70
+ }),
71
+ deletePostRequest: client.createRequest<{ response: null }>()({ endpoint: "/posts/:postId", method: "DELETE" }),
72
+ });
73
+
74
+ export const createSocket = (url = SOCKET_URL) => new Socket({ url, reconnectTime: 10 });
75
+
76
+ export type TestSocket = ReturnType<typeof createSocket>;
77
+
78
+ export const createListeners = (socket: TestSocket) => ({
79
+ onPostCreated: socket.createListener<Post>()({ topic: "teams/:teamId/posts/created" }),
80
+ onPostChanged: socket.createListener<Partial<Post> & { id: number }>()({ topic: "teams/:teamId/posts/changed" }),
81
+ onPostDeleted: socket.createListener<{ id: number }>()({ topic: "teams/:teamId/posts/deleted" }),
82
+ onAnyPostCreated: socket.createListener<Post>()({ topic: "posts/created" }),
83
+ onAnyPostChanged: socket.createListener<Partial<Post> & { id: number }>()({ topic: "posts/changed" }),
84
+ onAnyPostDeleted: socket.createListener<{ postId: number }>()({ topic: "posts/deleted" }),
85
+ onTeamChanges: socket.createListener<{ upsert: Post[]; delete: number[]; refetch?: number[] }>()({
86
+ topic: "teams/:teamId/changes",
87
+ }),
88
+ onPostChanges: socket.createListener<{ upsert: Post[]; delete: number[] }>()({ topic: "posts/:postId/changes" }),
89
+ });
90
+
91
+ type RouteContext = { params: Record<string, string>; url: URL; body: unknown };
92
+ type RouteResult = { status?: number; data?: unknown; networkError?: boolean };
93
+ export type RouteResolver = (context: RouteContext) => RouteResult | Promise<RouteResult>;
94
+
95
+ /** Answers requests at the network level with msw and records every call */
96
+ export const createApi = (server: { use: (...handlers: ReturnType<typeof http.get>[]) => void }) => {
97
+ const calls: { method: string; path: string; url: URL; body: unknown }[] = [];
98
+ const route = (method: "get" | "post" | "patch" | "put" | "delete", path: string, resolver: RouteResolver) => {
99
+ server.use(
100
+ http[method](`${BASE_URL}${path}`, async ({ params, request }) => {
101
+ const url = new URL(request.url);
102
+ const text = method === "get" ? "" : await request.text();
103
+ const body = text ? JSON.parse(text) : undefined;
104
+ calls.push({ method, path: url.pathname, url, body });
105
+ const result = await resolver({ params: params as Record<string, string>, url, body });
106
+ if (result.networkError) {
107
+ return HttpResponse.error();
108
+ }
109
+ return HttpResponse.json((result.data ?? null) as never, { status: result.status ?? 200 });
110
+ }),
111
+ );
112
+ };
113
+ return {
114
+ calls,
115
+ callsTo: (path: string, method = "get") => calls.filter((call) => call.path === path && call.method === method),
116
+ get: (path: string, resolver: RouteResolver) => route("get", path, resolver),
117
+ post: (path: string, resolver: RouteResolver) => route("post", path, resolver),
118
+ patch: (path: string, resolver: RouteResolver) => route("patch", path, resolver),
119
+ put: (path: string, resolver: RouteResolver) => route("put", path, resolver),
120
+ delete: (path: string, resolver: RouteResolver) => route("delete", path, resolver),
121
+ };
122
+ };
123
+
124
+ type E2EServer = {
125
+ route: (
126
+ method: string,
127
+ path: string,
128
+ // oxlint-disable-next-line max-params -- the e2e server's handler signature
129
+ handler: (
130
+ req: { url?: string },
131
+ res: { writeHead: (status: number, headers: Record<string, string>) => void; end: (body: string) => void },
132
+ body: Buffer,
133
+ params: Record<string, string>,
134
+ ) => void | Promise<void>,
135
+ ) => void;
136
+ getUrl: () => string;
137
+ };
138
+
139
+ /** The same interface as `createApi`, answered by a real HTTP server */
140
+ export const createE2EApi = (server: E2EServer) => {
141
+ const calls: { method: string; path: string; url: URL; body: unknown }[] = [];
142
+ const resolvers = new Map<string, RouteResolver>();
143
+ const registered = new Set<string>();
144
+ const route = (method: string, path: string, resolver: RouteResolver) => {
145
+ const id = `${method} ${path}`;
146
+ resolvers.set(id, resolver);
147
+ if (registered.has(id)) {
148
+ return;
149
+ }
150
+ registered.add(id);
151
+ // oxlint-disable-next-line max-params -- the e2e server's handler signature
152
+ server.route(method, path, async (req, res, raw, params) => {
153
+ const url = new URL(req.url ?? "/", server.getUrl());
154
+ const text = raw.toString();
155
+ const body = text ? JSON.parse(text) : undefined;
156
+ calls.push({ method, path: url.pathname, url, body });
157
+ const result = await resolvers.get(id)!({ params, url, body });
158
+ res.writeHead(result.status ?? 200, { "Content-Type": "application/json" });
159
+ res.end(JSON.stringify(result.data ?? null));
160
+ });
161
+ };
162
+ return {
163
+ calls,
164
+ reset: () => {
165
+ calls.length = 0;
166
+ },
167
+ callsTo: (path: string, method = "get") => calls.filter((call) => call.path === path && call.method === method),
168
+ get: (path: string, resolver: RouteResolver) => route("get", path, resolver),
169
+ post: (path: string, resolver: RouteResolver) => route("post", path, resolver),
170
+ patch: (path: string, resolver: RouteResolver) => route("patch", path, resolver),
171
+ put: (path: string, resolver: RouteResolver) => route("put", path, resolver),
172
+ delete: (path: string, resolver: RouteResolver) => route("delete", path, resolver),
173
+ };
174
+ };
175
+
176
+ export const deferred = <T = void>() => {
177
+ let resolve!: (value: T) => void;
178
+ const promise = new Promise<T>((resolvePromise) => {
179
+ resolve = resolvePromise;
180
+ });
181
+ return { promise, resolve };
182
+ };
183
+
184
+ /** A storage backed by a map, which behaves like `localStorage` */
185
+ export const createMemoryStorage = (initial: Record<string, string> = {}) => {
186
+ const items = new Map(Object.entries(initial));
187
+ return {
188
+ items,
189
+ getItem: (key: string) => items.get(key) ?? null,
190
+ setItem: (key: string, value: string) => {
191
+ items.set(key, value);
192
+ },
193
+ removeItem: (key: string) => {
194
+ items.delete(key);
195
+ },
196
+ };
197
+ };
198
+
199
+ /** Resolves after pending timers of zero delay, promises and microtasks have run */
200
+ export const flush = async (times = 5) => {
201
+ for (let index = 0; index < times; index += 1) {
202
+ // oxlint-disable-next-line no-await-in-loop
203
+ await new Promise((resolve) => {
204
+ setTimeout(resolve, 0);
205
+ });
206
+ }
207
+ };
208
+
209
+ /** Subscribes to a query and resolves once its state matches */
210
+ export const waitForState = async <State>(
211
+ query: { subscribe: (listener: () => void) => () => void; getSnapshot: () => State },
212
+ predicate: (state: State) => boolean,
213
+ ) => {
214
+ if (predicate(query.getSnapshot())) {
215
+ return query.getSnapshot();
216
+ }
217
+ return new Promise<State>((resolve) => {
218
+ const unsubscribe = query.subscribe(() => {
219
+ if (predicate(query.getSnapshot())) {
220
+ unsubscribe();
221
+ resolve(query.getSnapshot());
222
+ }
223
+ });
224
+ });
225
+ };
@@ -0,0 +1,19 @@
1
+ /* oxlint-disable unicorn/prefer-math-trunc -- `>>> 0` keeps the state an unsigned 32-bit integer, which trunc does not */
2
+ /** A small deterministic PRNG (mulberry32), so every seed of a model test replays the same steps */
3
+ export const createRandom = (seed: number) => {
4
+ let state = seed >>> 0;
5
+ const next = () => {
6
+ // 0x6D2B79F5, written in decimal so the formatter and the linter agree
7
+ state = (state + 1_831_565_813) >>> 0;
8
+ let value = state;
9
+ value = Math.imul(value ^ (value >>> 15), value | 1);
10
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
11
+ return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
12
+ };
13
+ const int = (min: number, max: number) => min + Math.floor(next() * (max - min + 1));
14
+ const pick = <T>(items: readonly T[]): T => items[int(0, items.length - 1)];
15
+ const chance = (probability: number) => next() < probability;
16
+ return { int, pick, chance };
17
+ };
18
+
19
+ export type Random = ReturnType<typeof createRandom>;
@@ -0,0 +1,11 @@
1
+ /// <reference types="vitest/globals" />
2
+ import * as matchers from "jest-extended";
3
+ import { expect } from "vitest";
4
+
5
+ expect.extend(matchers);
6
+
7
+ if (typeof window === "undefined") {
8
+ // E2E specs run in node, where sockets need a real WebSocket implementation
9
+ const { WebSocket: NodeWebSocket } = await import("ws");
10
+ (globalThis as unknown as { WebSocket: unknown }).WebSocket = NodeWebSocket;
11
+ }
@@ -0,0 +1,111 @@
1
+ import { ExtractResponseType, RequestInstance } from '@hyper-fetch/core';
2
+ import { ListenerInstance } from '@hyper-fetch/sockets';
3
+ import { InferSchemaInput, InferSchemaOutput, StandardSchemaV1 } from '../schema/schema.types';
4
+ import { CollectionConfig, CollectionOptions, DefaultRows, DeleteMutation, DescribeLoader, DescribeMutations, Inferred, IngestOptions, IngestType, InsertMutation, IsExactRow, IsIngestRow, IsPartialRow, IsSyncRow, IsWriteHandled, KeyFieldOf, LoaderDescriptor, LoaderOptions, MutationDescriptor, RowMismatch, SyncChangesOptions, SyncMessage, SyncOptions, SyncType, UpdateMutation } from './collection.types';
5
+ import { IsResourceValid, ResourceLoaders, ResourceMutations, ResourceOptions } from './resource.types';
6
+ /**
7
+ * A typed set of complete rows, defined by a schema and a key. It declares how its backend loads rows (`load`), keeps
8
+ * them live (`sync`), feeds them from other responses (`ingest`) and changes them (`mutate`). A collection is
9
+ * immutable: every method returns a new collection, so it is defined in one chain and passed to `createDb`.
10
+ *
11
+ * When rows a method reads do not match the row type, it returns a `RowMismatch` instead of a collection, so the chain
12
+ * and `createDb` do not compile.
13
+ */
14
+ export declare class Collection<Row, Input = Row, KeyField extends KeyFieldOf<Row> = KeyFieldOf<Row>, Loaders extends LoaderDescriptor = never, Mutations extends MutationDescriptor = {}> {
15
+ readonly config: CollectionConfig;
16
+ /** Type-only carrier of the collection's generics, never set at runtime */
17
+ readonly __types?: {
18
+ row: Row;
19
+ input: Input;
20
+ key: KeyField;
21
+ loaders: Loaders;
22
+ mutations: Mutations;
23
+ };
24
+ constructor(config: CollectionConfig);
25
+ /**
26
+ * Adds a loader: a request plus the way to read complete rows from its response. A list loader declares the filters
27
+ * and orders it can send and whether it is paginated. A loader with `byKey` or `byKeys` reads rows by key.
28
+ */
29
+ load<Req extends RequestInstance, Mapped, Where, Order, Cursor, Limit, ByKey, ByKeys, LoaderNotation>(request: Req, options?: LoaderOptions<Row, NonNullable<Row[KeyField]>, Req, Mapped, Where, Order, Cursor, Limit, ByKey, ByKeys, LoaderNotation>): IsExactRow<Inferred<Mapped, DefaultRows<Req>>, Row> extends true ? Collection<Row, Input, KeyField, Loaders | DescribeLoader<Row, Where, Order, Cursor, Limit, ByKey, ByKeys, LoaderNotation>, Mutations> : RowMismatch<Inferred<Mapped, DefaultRows<Req>>, Row>;
30
+ /**
31
+ * Derives loaders and mutations from an SDK resource that follows REST conventions: `$get` lists, `item.$get` reads
32
+ * by key, `$post` inserts, `item.$patch` or `item.$put` updates and `item.$delete` deletes. Path params of the list
33
+ * endpoint become required `eq` filters, and the query params listed in `list.where` become `eq` filters.
34
+ *
35
+ * @example
36
+ * collection(PostSchema, { key: "id" }).resource(sdk.posts, { item: "$postId" });
37
+ */
38
+ resource<Node, Item, Mapped, Filters, Cursor, InsertSuccess, UpdateSuccess, ListOption>(node: Node, options: ResourceOptions<Row, Node, Item, Mapped, Filters, Cursor, InsertSuccess, UpdateSuccess> & {
39
+ list?: ListOption;
40
+ }): IsResourceValid<Row, KeyField, Node, Item, Mapped, ListOption extends false ? false : true, InsertSuccess, UpdateSuccess> extends true ? Collection<Row, Input, KeyField, Loaders | ResourceLoaders<Row, Node, Item, Filters, Cursor, ListOption extends false ? false : true>, Mutations & ResourceMutations<Input, Row, Node, Item>> : RowMismatch<unknown, Row>;
41
+ /**
42
+ * Keeps rows current from a listener. `insert` messages carry complete rows, `update` messages the key and some
43
+ * fields, and `delete` messages the key. One listener can sync several collections.
44
+ */
45
+ sync<Listener extends ListenerInstance, Type extends SyncType, Mapped>(listener: Listener, options: SyncOptions<Row, KeyField, Listener, Type, Mapped>): IsSyncRow<Row, KeyField, Type, Inferred<Mapped, SyncMessage<Listener>>> extends true ? Collection<Row, Input, KeyField, Loaders, Mutations> : RowMismatch<Inferred<Mapped, SyncMessage<Listener>>, Row>;
46
+ /**
47
+ * Writes the rows nested in this collection's rows into another collection, for example the author of a post into
48
+ * the `user` collection. It runs on every complete write from the server: loads, inserts, ingested responses and
49
+ * mutation responses. The target is the collection itself, so renaming or removing it breaks the build.
50
+ *
51
+ * @example
52
+ * collection(PostSchema, { key: "id" }).normalize(User, (post) => (post.author ? [post.author] : []));
53
+ */
54
+ normalize<TargetRow, Mapped>(target: {
55
+ readonly config: CollectionConfig;
56
+ readonly __types?: {
57
+ row: TargetRow;
58
+ };
59
+ }, extract: (row: Row) => readonly Mapped[]): ([Mapped] extends [never] ? true : IsExactRow<Mapped, TargetRow>) extends true ? Collection<Row, Input, KeyField, Loaders, Mutations> : RowMismatch<Mapped, TargetRow>;
60
+ /**
61
+ * Keeps rows current from a listener whose events carry several changes at once, such as a Firestore snapshot.
62
+ * `changes` reads the complete rows to write and the keys to delete. With `notation`, the sync covers every subset
63
+ * by sending its conditions to the listener. Adapter presets such as `firestoreCollection` use it.
64
+ */
65
+ syncChanges<Listener extends ListenerInstance, Mapped>(listener: Listener, options: SyncChangesOptions<Row, KeyField, Listener, Mapped>): ([Mapped] extends [never] ? true : IsExactRow<Mapped, Row>) extends true ? Collection<Row, Input, KeyField, Loaders, Mutations> : RowMismatch<Mapped, Row>;
66
+ /**
67
+ * Writes the rows of another request's responses into the collection, for example a search endpoint or a
68
+ * `useSubmit` whose response is the changed row. The request does not become a loader.
69
+ */
70
+ ingest<Req extends RequestInstance, Mapped, Type>(request: Req, options?: IngestOptions<Req, Mapped, Type>): IsIngestRow<Row, KeyField, Inferred<Type, "insert"> & IngestType, Inferred<Mapped, DefaultRows<Req>>> extends true ? Collection<Row, Input, KeyField, Loaders, Mutations> : RowMismatch<Inferred<Mapped, DefaultRows<Req>>, Row>;
71
+ /**
72
+ * Declares how inserts, updates and deletes reach the backend. Each `map` turns the write into the request's params,
73
+ * query params and payload. A response that is not the row needs `onSuccess`.
74
+ */
75
+ mutate<InsertReq, UpdateReq, DeleteReq, InsertMapped, UpdateMapped, InsertSuccess, UpdateSuccess>(mutations: {
76
+ insert?: InsertMutation<Row, InsertReq, InsertMapped, InsertSuccess>;
77
+ update?: UpdateMutation<Row, KeyField, UpdateReq, UpdateMapped, UpdateSuccess>;
78
+ delete?: DeleteMutation<Row, KeyField, DeleteReq>;
79
+ }): [
80
+ IsWriteHandled<InsertReq, IsExactRow<Inferred<InsertMapped, ExtractResponseType<InsertReq>>, Row>, InsertSuccess>,
81
+ IsWriteHandled<UpdateReq, IsPartialRow<Inferred<UpdateMapped, ExtractResponseType<UpdateReq>>, Row, KeyField>, UpdateSuccess>
82
+ ] extends [true, true] ? Collection<Row, Input, KeyField, Loaders, Mutations & DescribeMutations<Input, Row, InsertReq, UpdateReq, DeleteReq>> : RowMismatch<ExtractResponseType<InsertReq> | ExtractResponseType<UpdateReq>, Row>;
83
+ }
84
+ /** Any collection, whatever its row type */
85
+ export type CollectionInstance = {
86
+ readonly config: CollectionConfig;
87
+ readonly __types?: {
88
+ row: any;
89
+ input: any;
90
+ key: any;
91
+ loaders: any;
92
+ mutations: any;
93
+ };
94
+ };
95
+ /** A row type without a schema, for `collection(rowType<Post>(), { key: "id" })`. Rows are not validated. */
96
+ export type RowType<Row> = {
97
+ readonly kind: "row-type";
98
+ readonly __row?: Row;
99
+ };
100
+ /** Declares a collection's row type without a schema, so writes are not validated */
101
+ export declare const rowType: <Row>() => RowType<Row>;
102
+ /**
103
+ * Creates a collection from a Standard Schema, such as a Zod, Valibot or ArkType schema, or from `rowType<Row>()`.
104
+ *
105
+ * @example
106
+ * const Post = collection(PostSchema, { key: "id", version: "updatedAt" });
107
+ * const Draft = collection(rowType<Draft>(), { key: "id" });
108
+ */
109
+ export declare function collection<Schema extends StandardSchemaV1, KeyField extends KeyFieldOf<InferSchemaOutput<Schema>>>(schema: Schema, options: CollectionOptions<InferSchemaOutput<Schema>, KeyField>): Collection<InferSchemaOutput<Schema>, InferSchemaInput<Schema>, KeyField>;
110
+ export declare function collection<Row, KeyField extends KeyFieldOf<Row>>(type: RowType<Row>, options: CollectionOptions<Row, KeyField>): Collection<Row, Row, KeyField>;
111
+ //# sourceMappingURL=collection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collection.d.ts","sourceRoot":"","sources":["../../src/collection/collection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACpG,OAAO,KAAK,EAEV,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,cAAc,EACd,cAAc,EACd,iBA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