@convex-dev/table-history 0.1.3

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 (49) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +231 -0
  3. package/dist/esm/client/index.d.ts +116 -0
  4. package/dist/esm/client/index.d.ts.map +1 -0
  5. package/dist/esm/client/index.js +93 -0
  6. package/dist/esm/client/index.js.map +1 -0
  7. package/dist/esm/component/_generated/api.d.ts +34 -0
  8. package/dist/esm/component/_generated/api.d.ts.map +1 -0
  9. package/dist/esm/component/_generated/api.js +31 -0
  10. package/dist/esm/component/_generated/api.js.map +1 -0
  11. package/dist/esm/component/_generated/component.d.ts +105 -0
  12. package/dist/esm/component/_generated/component.d.ts.map +1 -0
  13. package/dist/esm/component/_generated/component.js +11 -0
  14. package/dist/esm/component/_generated/component.js.map +1 -0
  15. package/dist/esm/component/_generated/dataModel.d.ts +46 -0
  16. package/dist/esm/component/_generated/dataModel.d.ts.map +1 -0
  17. package/dist/esm/component/_generated/dataModel.js +11 -0
  18. package/dist/esm/component/_generated/dataModel.js.map +1 -0
  19. package/dist/esm/component/_generated/server.d.ts +121 -0
  20. package/dist/esm/component/_generated/server.d.ts.map +1 -0
  21. package/dist/esm/component/_generated/server.js +78 -0
  22. package/dist/esm/component/_generated/server.js.map +1 -0
  23. package/dist/esm/component/convex.config.d.ts +3 -0
  24. package/dist/esm/component/convex.config.d.ts.map +1 -0
  25. package/dist/esm/component/convex.config.js +3 -0
  26. package/dist/esm/component/convex.config.js.map +1 -0
  27. package/dist/esm/component/lib.d.ts +137 -0
  28. package/dist/esm/component/lib.d.ts.map +1 -0
  29. package/dist/esm/component/lib.js +316 -0
  30. package/dist/esm/component/lib.js.map +1 -0
  31. package/dist/esm/component/schema.d.ts +25 -0
  32. package/dist/esm/component/schema.d.ts.map +1 -0
  33. package/dist/esm/component/schema.js +17 -0
  34. package/dist/esm/component/schema.js.map +1 -0
  35. package/dist/esm/react/index.d.ts +2 -0
  36. package/dist/esm/react/index.d.ts.map +1 -0
  37. package/dist/esm/react/index.js +8 -0
  38. package/dist/esm/react/index.js.map +1 -0
  39. package/package.json +84 -0
  40. package/src/client/index.ts +174 -0
  41. package/src/component/_generated/api.ts +50 -0
  42. package/src/component/_generated/component.ts +136 -0
  43. package/src/component/_generated/dataModel.ts +60 -0
  44. package/src/component/_generated/server.ts +161 -0
  45. package/src/component/convex.config.ts +3 -0
  46. package/src/component/lib.test.ts +285 -0
  47. package/src/component/lib.ts +337 -0
  48. package/src/component/schema.ts +17 -0
  49. package/src/react/index.ts +8 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,231 @@
1
+ # Convex TableHistory Component
2
+
3
+ [![npm version](https://badge.fury.io/js/%40convex-dev%2Ftable-history.svg)](https://badge.fury.io/js/%40convex-dev%2Ftable-history)
4
+
5
+ <!-- START: Include on https://convex.dev/components -->
6
+
7
+ Note: this Component is currently BETA. It was previously published under `convex-table-history`.
8
+
9
+ ## History on a Convex table
10
+
11
+ Attach a history component to your Convex table to keep track of changes.
12
+
13
+ - View an audit log of all table changes in the Convex Dashboard or in a custom React component.
14
+ - Answer questions like "was document A updated before document B?"
15
+ - View an audit log of changes to a single document
16
+ - Answer questions like "what was the user's email address before they changed it?"
17
+ - Look at a snapshot of the table at any point in time.
18
+
19
+ ```ts
20
+ // Paginate through all history on the "documents" table, from newest to oldest.
21
+ documentAuditLog.listHistory(ctx, args.maxTs, args.paginationOpts);
22
+
23
+ // Paginate through all history for a specific document, from newest to oldest.
24
+ documentAuditLog.listDocumentHistory(ctx, args.documentId, args.maxTs, args.paginationOpts);
25
+
26
+ // Paginate through all documents in the "documents" table at a specific timestamp.
27
+ documentAuditLog.listSnapshot(ctx, args.snapshotTs, args.currentTs, args.paginationOpts);
28
+ ```
29
+
30
+ Found a bug? Feature request? [File it here](https://github.com/ldanilek/table-history/issues).
31
+
32
+ ## Pre-requisite: Convex
33
+
34
+ You'll need an existing Convex project to use the component.
35
+ Convex is a hosted backend platform, including a database, serverless functions,
36
+ and a ton more you can learn about [here](https://docs.convex.dev/get-started).
37
+
38
+ Run `npm create convex` or follow any of the [quickstarts](https://docs.convex.dev/home) to set one up.
39
+
40
+ ## Installation
41
+
42
+ Install the component package:
43
+
44
+ ```ts
45
+ npm install @convex-dev/table-history
46
+ ```
47
+
48
+ Create a `convex.config.ts` file in your app's `convex/` folder and install the component by calling `use`:
49
+
50
+ ```ts
51
+ // convex/convex.config.ts
52
+ import { defineApp } from "convex/server";
53
+ import tableHistory from "@convex-dev/table-history/convex.config";
54
+
55
+ const app = defineApp();
56
+ app.use(tableHistory, { name: "documentAuditLog" });
57
+
58
+ export default app;
59
+ ```
60
+
61
+ To add history to multiple tables, you can call `app.use` multiple times with
62
+ different names. They will be available in your app as
63
+ `new TableHistory(components.<name>, ...)`.
64
+
65
+ ## Usage
66
+
67
+ ```ts
68
+ import { components } from "./_generated/api";
69
+ import { TableHistory } from "@convex-dev/table-history";
70
+
71
+ const documentAuditLog = new TableHistory<DataModel, "documents">(components.documentAuditLog);
72
+ ```
73
+
74
+ Add an item to the history table when a document changes:
75
+
76
+ ```ts
77
+ async function patchDocument(ctx: MutationCtx, documentId: Id<"documents">, patch: Partial<Doc<"documents">>) {
78
+ await ctx.db.patch(documentId, patch);
79
+ const document = await ctx.db.get(documentId);
80
+ await documentAuditLog.update(ctx, documentId, document);
81
+ }
82
+
83
+ async function insertDocument(ctx: MutationCtx, documentId: Id<"documents">, newDoc: WithoutSystemFields<Doc<"documents">>) {
84
+ const documentId = await ctx.db.insert("documents", newDoc);
85
+ const document = await ctx.db.get(documentId);
86
+ await documentAuditLog.update(ctx, documentId, document);
87
+ }
88
+
89
+ async function deleteDocument(ctx: MutationCtx, documentId: Id<"documents">) {
90
+ await ctx.db.delete(documentId);
91
+ await documentAuditLog.update(ctx, documentId, null);
92
+ }
93
+ ```
94
+
95
+ Or attach a [trigger](https://www.npmjs.com/package/convex-helpers#triggers) to automatically write to the history table when a mutation changes a document:
96
+
97
+ ```ts
98
+ const triggers = new Triggers<DataModel>();
99
+ triggers.register("documents", documentAuditLog.trigger());
100
+ export const mutation = customMutation(rawMutation, customCtx(triggers.wrapDB));
101
+ ```
102
+
103
+ Now that you're writing to the history table, you can use the `listHistory`, `listDocumentHistory`, and `listSnapshot` functions to query the history.
104
+
105
+ These functions are paginated, so you can use them with `usePaginatedQuery` to get all of the entries incrementally.
106
+ The pages consist of `HistoryEntry` objects, which have the following fields:
107
+
108
+ - `id`: the id of the document that was changed
109
+ - `doc`: the new version of the document that was changed, or null if the document was deleted
110
+ - `ts`: the timestamp of the change. See [serializability](#serializability).
111
+ - `isDeleted`: whether the document was deleted
112
+ - `attribution`: an optional arbitrary object that will be stored with the history entry
113
+
114
+ See more example usage in [example.ts](./example/convex/example.ts).
115
+
116
+ ## Details of usage
117
+
118
+ ### Serializability
119
+
120
+ Convex mutations are serializable transactions, which is great for maintaining
121
+ consistency in your tables.
122
+
123
+ However, if you need the guarantee that history timestamps match the mutations'
124
+ serializable order, that would require serializing all changes to your whole
125
+ database, and your database would slow to a crawl and get OCC errors.
126
+
127
+ You can configure the serializability of the history table by setting the
128
+ `serializability` option. The three options are:
129
+
130
+ - `"table"` -- i.e. the latest ts for the table, plus one
131
+ - history entries are serializable with other updates on the same table
132
+ - `"document"` -- i.e. the latest ts for the document, plus one
133
+ - history entries are serializable with other updates on the same document.
134
+ - `"wallclock"` -- i.e. Date.now()
135
+ - history entry timestamps don't have guarantees, but they also take no extra
136
+ dependencies and are usually sufficient.
137
+
138
+ The default serializability is `"wallclock"`.
139
+
140
+ ### `currentTs` and `maxTs` are required
141
+
142
+ ```ts
143
+ const [currentTs] = useState(Date.now()); // stable and recent
144
+ const [yesterday] = useState(Date.now() - 24 * 60 * 60 * 1000); // stable
145
+ const snapshotOfUsersYesterday = usePaginatedQuery(
146
+ api.documents.listSnapshot,
147
+ {
148
+ currentTs,
149
+ snapshotTs: yesterday,
150
+ },
151
+ { initialNumItems: 100 },
152
+ );
153
+ const auditLogBeforeYesterday = usePaginatedQuery(
154
+ api.documents.listHistory,
155
+ {
156
+ maxTs: yesterday,
157
+ },
158
+ { initialNumItems: 100 },
159
+ );
160
+ ```
161
+
162
+ - For `listSnapshot`, `currentTs` should be a stable recent timestamp.
163
+ - "Stable" means it should have the same value for all pages.
164
+ - To keep a stable timestamp for all pages, pick a value on the client and
165
+ pass it as an arg of `usePaginatedQuery`.
166
+ - "Recent" is relative to how often the table gets new inserts. The amount of
167
+ extra work performed by the query is proportional to the number of
168
+ `ctx.db.insert(tableName, doc)` calls since the `currentTs`.
169
+ - If the timestamp isn't recent, the queries might read too much data in
170
+ a single page and throw an error.
171
+ - Don't pick a timestamp in the future, or gaps will appear between pages
172
+ as new documents are inserted. The timestamp should be `Date.now()` or
173
+ slightly in the past.
174
+ - For `listHistory` and `listDocumentHistory`, `maxTs` should be stable but
175
+ doesn't need to be recent.
176
+
177
+ **Why is this necessary?**
178
+
179
+ The TableHistory component supports paginated queries with
180
+ [`usePaginatedQuery`](https://docs.convex.dev/database/pagination#paginating-within-react-components)
181
+ and [manual pagination](https://docs.convex.dev/database/pagination#paginating-manually).
182
+ But it needs a little help from you to make everything work seamlessly.
183
+
184
+ You want
185
+ [fully reactive pagination](https://stack.convex.dev/fully-reactive-pagination).
186
+ Concretely, `usePaginatedQuery` results should not have gaps or duplicates.
187
+
188
+ In order to implement this feature without the built-in `.paginate` method,
189
+ the TableHistory component assumes its own data model is append-only (which is
190
+ true, except when vacuuming), and takes in a stable recent timestamp. Then it
191
+ ignores history entries created after that timestamp.
192
+
193
+ ### Attribution
194
+
195
+ Store an update's `attribution` to track information like which user made the
196
+ change, or what mutation made the change.
197
+
198
+ ```ts
199
+ await documentAuditLog.update(ctx, documentId, document, {
200
+ attribution: {
201
+ actorIdentity: await ctx.auth.getUserIdentity(),
202
+ mutationName: "patchDocument",
203
+ source: "web",
204
+ },
205
+ });
206
+ ```
207
+
208
+ The default attribution when using `TableHistory.update` is `null`.
209
+
210
+ The default attribution when using `TableHistory.trigger` is the mutation's
211
+ `ctx.auth.getUserIdentity()`.
212
+
213
+ ### Vacuuming
214
+
215
+ The history table can grow large, so you can use the `vacuumHistory` function
216
+ to remove old history entries. This function will
217
+ schedule background jobs to delete old history entries.
218
+ The entries which will be deleted are those which are not visible
219
+ at snapshots `>=minTsToKeep`.
220
+
221
+ After vacuuming up to `minTsToKeep`, you can no longer call `listSnapshot`
222
+ with a snapshot timestamp less than `minTsToKeep`.
223
+
224
+ ### Limitations
225
+
226
+ - No indexes: you can't use an index to change the sort order or get a subset of results.
227
+ - Workaround: you can paginate until `isDone` returns true, and sort or filter
228
+ the results yourself, either on the client or in an action.
229
+ Consider [manual pagination](https://docs.convex.dev/database/pagination#paginating-manually).
230
+
231
+ <!-- END: Include on https://convex.dev/components -->
@@ -0,0 +1,116 @@
1
+ import { DocumentByName, GenericDataModel, GenericMutationCtx, GenericQueryCtx, PaginationOptions, TableNamesInDataModel } from "convex/server";
2
+ import { GenericId } from "convex/values";
3
+ import type { Serializability } from "../component/lib.js";
4
+ import type { ComponentApi } from "../component/_generated/component.js";
5
+ export declare class TableHistory<DataModel extends GenericDataModel, TableName extends TableNamesInDataModel<DataModel>> {
6
+ component: ComponentApi;
7
+ options: {
8
+ serializability: Serializability;
9
+ };
10
+ constructor(component: ComponentApi, options?: {
11
+ serializability?: Serializability;
12
+ });
13
+ /**
14
+ * Write a new history entry.
15
+ *
16
+ * @argument attribution an arbitrary object that will be stored with the
17
+ * history entry. Attribution can include actor/user identity, reason for
18
+ * change, etc.
19
+ */
20
+ update(ctx: RunMutationCtx, id: GenericId<TableName>, doc: DocumentByName<DataModel, TableName> | null, attribution?: unknown): Promise<number>;
21
+ /**
22
+ * Paginate the history of the table, from newest to oldest.
23
+ *
24
+ * @argument maxTs To keep pages contiguous, set `maxTs` to a fixed timestamp
25
+ * (milliseconds since epoch, like Date.now()) and keep
26
+ * it the same for subsequent pages.
27
+ */
28
+ listHistory(ctx: RunQueryCtx, maxTs: number, paginationOpts: PaginationOptions): Promise<{
29
+ continueCursor: string;
30
+ isDone: boolean;
31
+ page: Array<{
32
+ attribution: any;
33
+ doc: any;
34
+ id: string;
35
+ isDeleted: boolean;
36
+ ts: number;
37
+ }>;
38
+ pageStatus?: null | "SplitRequired" | "SplitRecommended";
39
+ splitCursor?: null | string;
40
+ }>;
41
+ /**
42
+ * Paginate the history of a single document, from newest to oldest.
43
+ *
44
+ * @argument maxTs To keep pages contiguous, set `maxTs` to a fixed timestamp
45
+ * (milliseconds since epoch, like Date.now()) and keep
46
+ * it the same for subsequent pages.
47
+ */
48
+ listDocumentHistory(ctx: RunQueryCtx, id: GenericId<TableName>, maxTs: number, paginationOpts: PaginationOptions): Promise<{
49
+ continueCursor: string;
50
+ isDone: boolean;
51
+ page: Array<{
52
+ attribution: any;
53
+ doc: any;
54
+ id: string;
55
+ isDeleted: boolean;
56
+ ts: number;
57
+ }>;
58
+ pageStatus?: null | "SplitRequired" | "SplitRecommended";
59
+ splitCursor?: null | string;
60
+ }>;
61
+ /**
62
+ * Paginate a snapshot of the table at a fixed timestamp.
63
+ *
64
+ * @argument ts the snapshot at which you want to list the table (milliseconds since epoch)
65
+ * @argument currentTs a fixed recent timestamp (milliseconds since epoch, like Date.now())
66
+ * which should be the same for subsequent pages.
67
+ */
68
+ listSnapshot(ctx: RunQueryCtx, snapshotTs: number, currentTs: number, paginationOpts: PaginationOptions): Promise<{
69
+ continueCursor: string;
70
+ isDone: boolean;
71
+ page: Array<{
72
+ attribution: any;
73
+ doc: any;
74
+ id: string;
75
+ isDeleted: boolean;
76
+ ts: number;
77
+ }>;
78
+ pageStatus?: null | "SplitRequired" | "SplitRecommended";
79
+ splitCursor?: null | string;
80
+ }>;
81
+ /**
82
+ * Delete old history entries.
83
+ *
84
+ * @argument minTsToKeep the timestamp (milliseconds since epoch) of the oldest
85
+ * snapshot of history that should be kept.
86
+ */
87
+ vacuumHistory(ctx: RunMutationCtx, minTsToKeep: number): Promise<any>;
88
+ /**
89
+ * For use with `Triggers` from "convex-helpers/server/triggers".
90
+ */
91
+ trigger<Ctx extends RunMutationCtx>(): Trigger<Ctx, DataModel, TableName>;
92
+ }
93
+ export type Trigger<Ctx, DataModel extends GenericDataModel, TableName extends TableNamesInDataModel<DataModel>> = (ctx: Ctx, change: Change<DataModel, TableName>) => Promise<void>;
94
+ export type Change<DataModel extends GenericDataModel, TableName extends TableNamesInDataModel<DataModel>> = {
95
+ id: GenericId<TableName>;
96
+ } & ({
97
+ operation: "insert";
98
+ oldDoc: null;
99
+ newDoc: DocumentByName<DataModel, TableName>;
100
+ } | {
101
+ operation: "update";
102
+ oldDoc: DocumentByName<DataModel, TableName>;
103
+ newDoc: DocumentByName<DataModel, TableName>;
104
+ } | {
105
+ operation: "delete";
106
+ oldDoc: DocumentByName<DataModel, TableName>;
107
+ newDoc: null;
108
+ });
109
+ type RunQueryCtx = {
110
+ runQuery: GenericQueryCtx<GenericDataModel>["runQuery"];
111
+ };
112
+ type RunMutationCtx = {
113
+ runMutation: GenericMutationCtx<GenericDataModel>["runMutation"];
114
+ };
115
+ export {};
116
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,iBAAiB,EACjB,qBAAqB,EACtB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AAEzE,qBAAa,YAAY,CACvB,SAAS,SAAS,gBAAgB,EAClC,SAAS,SAAS,qBAAqB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,MAAM,CAChB,SAAS,SAAS,gBAAgB,EAClC,SAAS,SAAS,qBAAqB,CAAC,SAAS,CAAC,IAChD;IACF,EAAE,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;CAC1B,GAAG,CACA;IACE,SAAS,EAAE,QAAQ,CAAC;IACpB,MAAM,EAAE,IAAI,CAAC;IACb,MAAM,EAAE,cAAc,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;CAC9C,GACD;IACE,SAAS,EAAE,QAAQ,CAAC;IACpB,MAAM,EAAE,cAAc,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IAC7C,MAAM,EAAE,cAAc,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;CAC9C,GACD;IACE,SAAS,EAAE,QAAQ,CAAC;IACpB,MAAM,EAAE,cAAc,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IAC7C,MAAM,EAAE,IAAI,CAAC;CACd,CACJ,CAAC;AAEF,KAAK,WAAW,GAAG;IACjB,QAAQ,EAAE,eAAe,CAAC,gBAAgB,CAAC,CAAC,UAAU,CAAC,CAAC;CACzD,CAAC;AACF,KAAK,cAAc,GAAG;IACpB,WAAW,EAAE,kBAAkB,CAAC,gBAAgB,CAAC,CAAC,aAAa,CAAC,CAAC;CAClE,CAAC"}
@@ -0,0 +1,93 @@
1
+ export class TableHistory {
2
+ component;
3
+ options;
4
+ constructor(component, options) {
5
+ this.component = component;
6
+ this.options = {
7
+ serializability: options?.serializability ?? "wallclock",
8
+ };
9
+ }
10
+ /**
11
+ * Write a new history entry.
12
+ *
13
+ * @argument attribution an arbitrary object that will be stored with the
14
+ * history entry. Attribution can include actor/user identity, reason for
15
+ * change, etc.
16
+ */
17
+ async update(ctx, id, doc, attribution = null) {
18
+ return ctx.runMutation(this.component.lib.update, {
19
+ id,
20
+ doc,
21
+ serializability: this.options.serializability,
22
+ attribution,
23
+ });
24
+ }
25
+ /**
26
+ * Paginate the history of the table, from newest to oldest.
27
+ *
28
+ * @argument maxTs To keep pages contiguous, set `maxTs` to a fixed timestamp
29
+ * (milliseconds since epoch, like Date.now()) and keep
30
+ * it the same for subsequent pages.
31
+ */
32
+ async listHistory(ctx, maxTs, paginationOpts) {
33
+ return ctx.runQuery(this.component.lib.listHistory, {
34
+ maxTs,
35
+ paginationOpts,
36
+ });
37
+ }
38
+ /**
39
+ * Paginate the history of a single document, from newest to oldest.
40
+ *
41
+ * @argument maxTs To keep pages contiguous, set `maxTs` to a fixed timestamp
42
+ * (milliseconds since epoch, like Date.now()) and keep
43
+ * it the same for subsequent pages.
44
+ */
45
+ async listDocumentHistory(ctx, id, maxTs, paginationOpts) {
46
+ return ctx.runQuery(this.component.lib.listDocumentHistory, {
47
+ id,
48
+ maxTs,
49
+ paginationOpts,
50
+ });
51
+ }
52
+ /**
53
+ * Paginate a snapshot of the table at a fixed timestamp.
54
+ *
55
+ * @argument ts the snapshot at which you want to list the table (milliseconds since epoch)
56
+ * @argument currentTs a fixed recent timestamp (milliseconds since epoch, like Date.now())
57
+ * which should be the same for subsequent pages.
58
+ */
59
+ async listSnapshot(ctx, snapshotTs, currentTs, paginationOpts) {
60
+ return ctx.runQuery(this.component.lib.listSnapshot, {
61
+ snapshotTs,
62
+ currentTs,
63
+ paginationOpts,
64
+ });
65
+ }
66
+ /**
67
+ * Delete old history entries.
68
+ *
69
+ * @argument minTsToKeep the timestamp (milliseconds since epoch) of the oldest
70
+ * snapshot of history that should be kept.
71
+ */
72
+ async vacuumHistory(ctx, minTsToKeep) {
73
+ return ctx.runMutation(this.component.lib.vacuumHistory, { minTsToKeep });
74
+ }
75
+ /**
76
+ * For use with `Triggers` from "convex-helpers/server/triggers".
77
+ */
78
+ trigger() {
79
+ return async (ctx, change) => {
80
+ let attribution = null;
81
+ if (
82
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
+ ctx.auth &&
84
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
85
+ typeof ctx.auth.getUserIdentity === "function") {
86
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
+ attribution = await ctx.auth.getUserIdentity();
88
+ }
89
+ await this.update(ctx, change.id, change.newDoc, attribution);
90
+ };
91
+ }
92
+ }
93
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAYA,MAAM,OAAO,YAAY;IAQd;IAJF,OAAO,CAEZ;IACF,YACS,SAAuB,EAC9B,OAEC;QAHM,cAAS,GAAT,SAAS,CAAc;QAK9B,IAAI,CAAC,OAAO,GAAG;YACb,eAAe,EAAE,OAAO,EAAE,eAAe,IAAI,WAAW;SACzD,CAAC;IACJ,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,MAAM,CACV,GAAmB,EACnB,EAAwB,EACxB,GAAgD,EAChD,cAAuB,IAAI;QAE3B,OAAO,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE;YAChD,EAAE;YACF,GAAG;YACH,eAAe,EAAE,IAAI,CAAC,OAAO,CAAC,eAAe;YAC7C,WAAW;SACZ,CAAC,CAAC;IACL,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,WAAW,CACf,GAAgB,EAChB,KAAa,EACb,cAAiC;QAEjC,OAAO,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,WAAW,EAAE;YAClD,KAAK;YACL,cAAc;SACf,CAAC,CAAC;IACL,CAAC;IACD;;;;;;OAMG;IACH,KAAK,CAAC,mBAAmB,CACvB,GAAgB,EAChB,EAAwB,EACxB,KAAa,EACb,cAAiC;QAEjC,OAAO,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,mBAAmB,EAAE;YAC1D,EAAE;YACF,KAAK;YACL,cAAc;SACf,CAAC,CAAC;IACL,CAAC;IACD;;;;;;OAMG;IACH,KAAK,CAAC,YAAY,CAChB,GAA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