@vllnt/convex-helpers 0.2.0-canary.487d828 → 0.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.
- package/CHANGELOG.md +12 -1
- package/NOTICE +214 -0
- package/README.md +66 -9
- package/dist/builders.d.ts +104 -0
- package/dist/builders.d.ts.map +1 -0
- package/dist/builders.js +151 -0
- package/dist/builders.js.map +1 -0
- package/dist/validators.d.ts +89 -0
- package/dist/validators.d.ts.map +1 -0
- package/dist/validators.js +294 -0
- package/dist/validators.js.map +1 -0
- package/docs/API.md +63 -19
- package/llms.txt +5 -4
- package/package.json +22 -9
- package/src/builders.ts +475 -0
- package/src/validators.ts +446 -0
package/CHANGELOG.md
CHANGED
|
@@ -8,7 +8,7 @@ and this project adheres to
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
-
## [0.2.0] -
|
|
11
|
+
## [0.2.0] - 2026-11-26
|
|
12
12
|
|
|
13
13
|
### Fixed
|
|
14
14
|
|
|
@@ -61,6 +61,17 @@ and this project adheres to
|
|
|
61
61
|
sessions (anonymous plugin and email/password) issue JWTs whose issuer,
|
|
62
62
|
subject and anonymous claims `./identity` accepts on a real Convex backend,
|
|
63
63
|
and that tampered, foreign-issuer and expired tokens are rejected.
|
|
64
|
+
- `./builders` — `customQuery` / `customMutation` / `customAction` / `customCtx`
|
|
65
|
+
with the signatures and runtime behaviour of
|
|
66
|
+
`convex-helpers/server/customFunctions` 0.1.124, held by a convex-test parity
|
|
67
|
+
test against that package.
|
|
68
|
+
- `./validators` — `validate` (`throw`, `allowUnknownFields`), `parse` and
|
|
69
|
+
`doc`, matching `convex-helpers/validators` 0.1.124 (parity-tested). Two
|
|
70
|
+
fail-closed differences: object fields are own properties only (inherited
|
|
71
|
+
names such as `constructor` are unknown fields), and the `db` id-table option
|
|
72
|
+
is refused.
|
|
73
|
+
- `NOTICE` — attribution for the convex-helpers (Apache-2.0) behaviour and types
|
|
74
|
+
these entries follow.
|
|
64
75
|
- `./better-auth` — fail-closed trusted-origin parser + HTTPS cookie settings
|
|
65
76
|
for `@convex-dev/better-auth` (does not import better-auth).
|
|
66
77
|
- `./identity` — `getOrCreateFromAuth` / `requireFromAuth` / `retargetRows`
|
package/NOTICE
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
@vllnt/convex-helpers
|
|
2
|
+
Copyright (c) 2026 bntvllnt. Licensed under the MIT License (see LICENSE).
|
|
3
|
+
|
|
4
|
+
The ./builders and ./validators entry points follow the public API, runtime
|
|
5
|
+
behaviour and type signatures of convex-helpers 0.1.124
|
|
6
|
+
(https://github.com/get-convex/convex-helpers), Copyright Convex, Inc.,
|
|
7
|
+
licensed under the Apache License, Version 2.0, reproduced below. The
|
|
8
|
+
implementation in src/builders.ts and src/validators.ts was written for this
|
|
9
|
+
package; the CustomBuilder, Customization and AddFieldsToValidator types are
|
|
10
|
+
adapted from convex-helpers.
|
|
11
|
+
|
|
12
|
+
--------------------------------------------------------------------------------
|
|
13
|
+
|
|
14
|
+
Apache License
|
|
15
|
+
Version 2.0, January 2004
|
|
16
|
+
http://www.apache.org/licenses/
|
|
17
|
+
|
|
18
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
19
|
+
|
|
20
|
+
1. Definitions.
|
|
21
|
+
|
|
22
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
23
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
24
|
+
|
|
25
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
26
|
+
the copyright owner that is granting the License.
|
|
27
|
+
|
|
28
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
29
|
+
other entities that control, are controlled by, or are under common
|
|
30
|
+
control with that entity. For the purposes of this definition,
|
|
31
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
32
|
+
direction or management of such entity, whether by contract or
|
|
33
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
34
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
35
|
+
|
|
36
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
37
|
+
exercising permissions granted by this License.
|
|
38
|
+
|
|
39
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
40
|
+
including but not limited to software source code, documentation
|
|
41
|
+
source, and configuration files.
|
|
42
|
+
|
|
43
|
+
"Object" form shall mean any form resulting from mechanical
|
|
44
|
+
transformation or translation of a Source form, including but
|
|
45
|
+
not limited to compiled object code, generated documentation,
|
|
46
|
+
and conversions to other media types.
|
|
47
|
+
|
|
48
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
49
|
+
Object form, made available under the License, as indicated by a
|
|
50
|
+
copyright notice that is included in or attached to the work
|
|
51
|
+
(an example is provided in the Appendix below).
|
|
52
|
+
|
|
53
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
54
|
+
form, that is based on (or derived from) the Work and for which the
|
|
55
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
56
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
57
|
+
of this License, Derivative Works shall not include works that remain
|
|
58
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
59
|
+
the Work and Derivative Works thereof.
|
|
60
|
+
|
|
61
|
+
"Contribution" shall mean any work of authorship, including
|
|
62
|
+
the original version of the Work and any modifications or additions
|
|
63
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
64
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
65
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
66
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
67
|
+
means any form of electronic, verbal, or written communication sent
|
|
68
|
+
to the Licensor or its representatives, including but not limited to
|
|
69
|
+
communication on electronic mailing lists, source code control systems,
|
|
70
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
71
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
72
|
+
excluding communication that is conspicuously marked or otherwise
|
|
73
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
74
|
+
|
|
75
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
76
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
77
|
+
subsequently incorporated within the Work.
|
|
78
|
+
|
|
79
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
80
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
81
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
82
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
83
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
84
|
+
Work and such Derivative Works in Source or Object form.
|
|
85
|
+
|
|
86
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
87
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
88
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
89
|
+
(except as stated in this section) patent license to make, have made,
|
|
90
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
91
|
+
where such license applies only to those patent claims licensable
|
|
92
|
+
by such Contributor that are necessarily infringed by their
|
|
93
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
94
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
95
|
+
institute patent litigation against any entity (including a
|
|
96
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
97
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
98
|
+
or contributory patent infringement, then any patent licenses
|
|
99
|
+
granted to You under this License for that Work shall terminate
|
|
100
|
+
as of the date such litigation is filed.
|
|
101
|
+
|
|
102
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
103
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
104
|
+
modifications, and in Source or Object form, provided that You
|
|
105
|
+
meet the following conditions:
|
|
106
|
+
|
|
107
|
+
(a) You must give any other recipients of the Work or
|
|
108
|
+
Derivative Works a copy of this License; and
|
|
109
|
+
|
|
110
|
+
(b) You must cause any modified files to carry prominent notices
|
|
111
|
+
stating that You changed the files; and
|
|
112
|
+
|
|
113
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
114
|
+
that You distribute, all copyright, patent, trademark, and
|
|
115
|
+
attribution notices from the Source form of the Work,
|
|
116
|
+
excluding those notices that do not pertain to any part of
|
|
117
|
+
the Derivative Works; and
|
|
118
|
+
|
|
119
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
120
|
+
distribution, then any Derivative Works that You distribute must
|
|
121
|
+
include a readable copy of the attribution notices contained
|
|
122
|
+
within such NOTICE file, excluding those notices that do not
|
|
123
|
+
pertain to any part of the Derivative Works, in at least one
|
|
124
|
+
of the following places: within a NOTICE text file distributed
|
|
125
|
+
as part of the Derivative Works; within the Source form or
|
|
126
|
+
documentation, if provided along with the Derivative Works; or,
|
|
127
|
+
within a display generated by the Derivative Works, if and
|
|
128
|
+
wherever such third-party notices normally appear. The contents
|
|
129
|
+
of the NOTICE file are for informational purposes only and
|
|
130
|
+
do not modify the License. You may add Your own attribution
|
|
131
|
+
notices within Derivative Works that You distribute, alongside
|
|
132
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
133
|
+
that such additional attribution notices cannot be construed
|
|
134
|
+
as modifying the License.
|
|
135
|
+
|
|
136
|
+
You may add Your own copyright statement to Your modifications and
|
|
137
|
+
may provide additional or different license terms and conditions
|
|
138
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
139
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
140
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
141
|
+
the conditions stated in this License.
|
|
142
|
+
|
|
143
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
144
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
145
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
146
|
+
this License, without any additional terms or conditions.
|
|
147
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
148
|
+
the terms of any separate license agreement you may have executed
|
|
149
|
+
with Licensor regarding such Contributions.
|
|
150
|
+
|
|
151
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
152
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
153
|
+
except as required for reasonable and customary use in describing the
|
|
154
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
155
|
+
|
|
156
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
157
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
158
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
159
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
160
|
+
implied, including, without limitation, any warranties or conditions
|
|
161
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
162
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
163
|
+
appropriateness of using or redistributing the Work and assume any
|
|
164
|
+
risks associated with Your exercise of permissions under this License.
|
|
165
|
+
|
|
166
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
167
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
168
|
+
unless required by applicable law (such as deliberate and grossly
|
|
169
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
170
|
+
liable to You for damages, including any direct, indirect, special,
|
|
171
|
+
incidental, or consequential damages of any character arising as a
|
|
172
|
+
result of this License or out of the use or inability to use the
|
|
173
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
174
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
175
|
+
other commercial damages or losses), even if such Contributor
|
|
176
|
+
has been advised of the possibility of such damages.
|
|
177
|
+
|
|
178
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
179
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
180
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
181
|
+
or other liability obligations and/or rights consistent with this
|
|
182
|
+
License. However, in accepting such obligations, You may act only
|
|
183
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
184
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
185
|
+
defend, and hold each Contributor harmless for any liability
|
|
186
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
187
|
+
of your accepting any such warranty or additional liability.
|
|
188
|
+
|
|
189
|
+
END OF TERMS AND CONDITIONS
|
|
190
|
+
|
|
191
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
192
|
+
|
|
193
|
+
To apply the Apache License to your work, attach the following
|
|
194
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
195
|
+
replaced with your own identifying information. (Don't include
|
|
196
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
197
|
+
comment syntax for the file format. We also recommend that a
|
|
198
|
+
file or class name and description of purpose be included on the
|
|
199
|
+
same "printed page" as the copyright notice for easier
|
|
200
|
+
identification within third-party archives.
|
|
201
|
+
|
|
202
|
+
Copyright [yyyy] [name of copyright owner]
|
|
203
|
+
|
|
204
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
205
|
+
you may not use this file except in compliance with the License.
|
|
206
|
+
You may obtain a copy of the License at
|
|
207
|
+
|
|
208
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
209
|
+
|
|
210
|
+
Unless required by applicable law or agreed to in writing, software
|
|
211
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
212
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
213
|
+
See the License for the specific language governing permissions and
|
|
214
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -33,15 +33,17 @@ See [ROADMAP.md](./ROADMAP.md) for the planned module surface.
|
|
|
33
33
|
- `./mcp` — expose Convex functions as MCP tools (`createMCPServer` +
|
|
34
34
|
`query`/`mutation`/`action`/`resource`), default-deny auth, optional cursor
|
|
35
35
|
pagination
|
|
36
|
-
-
|
|
37
|
-
`
|
|
36
|
+
- `./builders` — `customQuery`/`customMutation`/`customAction`/`customCtx` (same
|
|
37
|
+
signatures and behaviour as `convex-helpers/server/customFunctions`)
|
|
38
|
+
- `./validators` — runtime `validate`/`parse` and the `doc(schema, table)`
|
|
39
|
+
document validator (same behaviour as `convex-helpers/validators`)
|
|
38
40
|
- [planned] `./errors` — typed `AppError` + HTTP-status map
|
|
39
41
|
- [planned] `./env` — `defineEnv(zodSchema)` cold-start validation
|
|
40
42
|
- [planned] `./tracing` — span emit + `traceparent` propagation via
|
|
41
43
|
`@vllnt/logger`
|
|
42
44
|
- [planned] `./testing` — fixture factories + `withIdentity`
|
|
43
|
-
- [planned] `./relationships`, `./validators
|
|
44
|
-
`./triggers`, `./http`
|
|
45
|
+
- [planned] `./relationships`, more `./validators` (`partial`/`typedV`/zod
|
|
46
|
+
bridge), `./pagination`, `./rls`, `./triggers`, `./http`
|
|
45
47
|
- [planned] `./react` — optional tree-shakeable front-end hooks layer
|
|
46
48
|
|
|
47
49
|
## Installation
|
|
@@ -50,11 +52,11 @@ See [ROADMAP.md](./ROADMAP.md) for the planned module surface.
|
|
|
50
52
|
pnpm add @vllnt/convex-helpers
|
|
51
53
|
```
|
|
52
54
|
|
|
53
|
-
This README describes current `main`. `./better-auth
|
|
54
|
-
ship in `0.2.0`; `0.1.0` has only the root
|
|
55
|
-
`main` are published to the `canary` dist-tag;
|
|
56
|
-
resolved version and test before production use.
|
|
57
|
-
not exported yet.
|
|
55
|
+
This README describes current `main`. `./better-auth`, `./identity`,
|
|
56
|
+
`./builders` and `./validators` first ship in `0.2.0`; `0.1.0` has only the root
|
|
57
|
+
utilities and `./mcp`. Builds of `main` are published to the `canary` dist-tag;
|
|
58
|
+
canary tags move, so pin the resolved version and test before production use.
|
|
59
|
+
Modules marked **planned** are not exported yet.
|
|
58
60
|
|
|
59
61
|
`convex@^1.45.0` is a peer dependency:
|
|
60
62
|
|
|
@@ -168,6 +170,61 @@ returns secure, HttpOnly, SameSite=None attributes for a valid HTTPS origin
|
|
|
168
170
|
only; it does not replace CSRF/origin protection and is for hosts requiring
|
|
169
171
|
cross-site cookies.
|
|
170
172
|
|
|
173
|
+
### Custom functions — `./builders`
|
|
174
|
+
|
|
175
|
+
Resolve shared context once for every function made with a builder. The
|
|
176
|
+
signatures match `convex-helpers/server/customFunctions` (0.1.124), so switching
|
|
177
|
+
is an import-path change.
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
import {
|
|
181
|
+
customCtx,
|
|
182
|
+
customMutation,
|
|
183
|
+
customQuery,
|
|
184
|
+
} from "@vllnt/convex-helpers/builders";
|
|
185
|
+
import { mutation, query } from "./_generated/server";
|
|
186
|
+
|
|
187
|
+
// customCtx(...) form: add ctx fields.
|
|
188
|
+
export const authQuery = customQuery(
|
|
189
|
+
query,
|
|
190
|
+
customCtx(async (ctx) => ({ user: await requireUser(ctx) })),
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
// { args, input } form: `args` are taken out of the handler's args and passed
|
|
194
|
+
// to `input`, which returns ctx fields, args to add and an optional onSuccess.
|
|
195
|
+
export const userMutation = customMutation(mutation, {
|
|
196
|
+
args: {},
|
|
197
|
+
input: async (ctx) => ({ args: {}, ctx: { user: await requireUser(ctx) } }),
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
export const rename = userMutation({
|
|
201
|
+
args: { name: v.string() },
|
|
202
|
+
handler: async (ctx, { name }) => ctx.db.patch(ctx.user._id, { name }),
|
|
203
|
+
});
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
`customCtx`'s callback also receives the definition's extra keys (everything but
|
|
207
|
+
`args`, `handler` and `returns`). Builders add no auth of their own: the `input`
|
|
208
|
+
you write decides who may call.
|
|
209
|
+
|
|
210
|
+
### Runtime validation — `./validators`
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
import { doc, parse, validate } from "@vllnt/convex-helpers/validators";
|
|
214
|
+
|
|
215
|
+
validate(v.object({ a: v.string() }), value); // boolean, narrows `value`
|
|
216
|
+
validate(validator, value, { throw: true }); // throws ValidationError
|
|
217
|
+
validate(validator, value, { allowUnknownFields: true, throw: true });
|
|
218
|
+
const clean = parse(validator, JSON.parse(raw)); // validates, drops unknown fields
|
|
219
|
+
const userDoc = doc(schema, "users"); // table validator + _id + _creationTime
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
The `db` option of `convex-helpers` (checking which table a `v.id` belongs to)
|
|
223
|
+
is refused; `v.id` checks that the value is a string. Object fields are matched
|
|
224
|
+
as own properties, so inherited names such as `constructor` count as unknown
|
|
225
|
+
fields (upstream accepts them). See
|
|
226
|
+
[docs/API.md](docs/API.md#validators-shipped).
|
|
227
|
+
|
|
171
228
|
### Identity — `./identity`
|
|
172
229
|
|
|
173
230
|
Map `ctx.auth.getUserIdentity()` to a host row. The host must configure a
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module @vllnt/convex-helpers/builders
|
|
3
|
+
* Wrap Convex `query` / `mutation` / `action` builders so every function made
|
|
4
|
+
* with them gets extra `ctx` fields (and optionally consumes extra args), e.g.
|
|
5
|
+
* an authenticated user resolved once in a shared `input`.
|
|
6
|
+
*
|
|
7
|
+
* Adapted, with changes, from `convex-helpers/server/customFunctions` 0.1.124
|
|
8
|
+
* (Apache-2.0, see NOTICE): same signatures and runtime behaviour for
|
|
9
|
+
* `customQuery`, `customMutation`, `customAction` and `customCtx`; the
|
|
10
|
+
* `CustomBuilder`, `Customization` and `Registration` types follow upstream's.
|
|
11
|
+
* Unlike upstream, a customization must supply both `args` and `input` (the
|
|
12
|
+
* types already require them). `tests/builders-parity.test.ts`
|
|
13
|
+
* runs both side by side.
|
|
14
|
+
*/
|
|
15
|
+
import type { ActionBuilder, ArgsArrayForOptionalValidator, ArgsArrayToObject, DefaultArgsForOptionalValidator, DefaultFunctionArgs, FunctionVisibility, GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx, MutationBuilder, QueryBuilder, RegisteredAction, RegisteredMutation, RegisteredQuery, ReturnValueForOptionalValidator } from "convex/server";
|
|
16
|
+
import type { GenericValidator, ObjectType, PropertyValidators, Validator } from "convex/values";
|
|
17
|
+
type AnyRecord = Record<string, any>;
|
|
18
|
+
/** What a customization's `input` returns. */
|
|
19
|
+
export type CustomInput<TCtx, TCustomCtx, TCustomMadeArguments> = {
|
|
20
|
+
args: TCustomMadeArguments;
|
|
21
|
+
ctx: TCustomCtx;
|
|
22
|
+
/** Runs after the handler succeeds, with the original ctx and args. */
|
|
23
|
+
onSuccess?: (outcome: {
|
|
24
|
+
args: Record<string, unknown>;
|
|
25
|
+
ctx: TCtx;
|
|
26
|
+
result: unknown;
|
|
27
|
+
}) => Promise<void> | void;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* How a custom builder changes each function: the `args` it consumes (taken
|
|
31
|
+
* out of the handler's args) and an `input` that returns ctx fields and args
|
|
32
|
+
* to add.
|
|
33
|
+
*/
|
|
34
|
+
export type Customization<TCtx extends AnyRecord, TCustomArgumentsValidator extends PropertyValidators, TCustomCtx extends AnyRecord, TCustomMadeArguments extends AnyRecord, TExtraArguments extends AnyRecord = AnyRecord> = {
|
|
35
|
+
args: TCustomArgumentsValidator;
|
|
36
|
+
input: (ctx: TCtx, arguments_: ObjectType<TCustomArgumentsValidator>, extra: TExtraArguments) => CustomInput<TCtx, TCustomCtx, TCustomMadeArguments> | Promise<CustomInput<TCtx, TCustomCtx, TCustomMadeArguments>>;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Builds a customization that adds ctx fields and leaves args alone.
|
|
40
|
+
* `modifyCtx` receives the original ctx and the definition's extra properties
|
|
41
|
+
* (all keys but `args`, `handler` and `returns`).
|
|
42
|
+
*
|
|
43
|
+
* @param modifyCtx - Returns the ctx fields to add (may be async)
|
|
44
|
+
* @returns A customization for {@link customQuery}, {@link customMutation} or {@link customAction}
|
|
45
|
+
* @example
|
|
46
|
+
* const authQuery = customQuery(query, customCtx(async (ctx) => ({ user: await requireUser(ctx) })));
|
|
47
|
+
*/
|
|
48
|
+
export declare function customCtx<TInCtx extends AnyRecord, TOutCtx extends AnyRecord, TExtraArguments extends AnyRecord = AnyRecord>(modifyCtx: (original: TInCtx, extra: TExtraArguments) => Promise<TOutCtx> | TOutCtx): Customization<TInCtx, Record<string, never>, TOutCtx, Record<string, never>, TExtraArguments>;
|
|
49
|
+
type Expand<TObject extends AnyRecord> = {
|
|
50
|
+
[Key in keyof TObject]: TObject[Key];
|
|
51
|
+
};
|
|
52
|
+
type Overwrite<TBase, TPatch> = keyof TPatch extends never ? TBase : Omit<TBase, keyof TPatch> & TPatch;
|
|
53
|
+
type ArgumentsForHandlerType<TOneOrZeroArguments extends [] | [AnyRecord], TCustomMadeArguments extends AnyRecord> = TCustomMadeArguments extends Record<string, never> ? TOneOrZeroArguments : TOneOrZeroArguments extends [infer TArguments extends AnyRecord] ? [Expand<TArguments & TCustomMadeArguments>] : [TCustomMadeArguments];
|
|
54
|
+
/** The registered function type a custom builder returns. */
|
|
55
|
+
export type Registration<TFunctionType extends "action" | "mutation" | "query", TVisibility extends FunctionVisibility, TArguments extends DefaultFunctionArgs, TOutput> = {
|
|
56
|
+
action: RegisteredAction<TVisibility, TArguments, TOutput>;
|
|
57
|
+
mutation: RegisteredMutation<TVisibility, TArguments, TOutput>;
|
|
58
|
+
query: RegisteredQuery<TVisibility, TArguments, TOutput>;
|
|
59
|
+
}[TFunctionType];
|
|
60
|
+
/** A function builder made by {@link customQuery}, {@link customMutation} or {@link customAction}. */
|
|
61
|
+
export type CustomBuilder<TFunctionType extends "action" | "mutation" | "query", TCustomArgumentsValidator extends PropertyValidators, TCustomCtx extends AnyRecord, TCustomMadeArguments extends AnyRecord, TInputCtx, TVisibility extends FunctionVisibility, TExtraArguments extends AnyRecord> = <TArgumentsValidator extends PropertyValidators | Validator<any, any, any> | void, TReturnsValidator extends GenericValidator | PropertyValidators | void, TReturnValue extends ReturnValueForOptionalValidator<TReturnsValidator> = any, TOneOrZeroArguments extends ArgsArrayForOptionalValidator<TArgumentsValidator> = DefaultArgsForOptionalValidator<TArgumentsValidator>>(function_: ((ctx: Overwrite<TInputCtx, TCustomCtx>, ...arguments_: ArgumentsForHandlerType<TOneOrZeroArguments, TCustomMadeArguments>) => TReturnValue) | ({
|
|
62
|
+
args?: TArgumentsValidator;
|
|
63
|
+
handler: (ctx: Overwrite<TInputCtx, TCustomCtx>, ...arguments_: ArgumentsForHandlerType<TOneOrZeroArguments, TCustomMadeArguments>) => TReturnValue;
|
|
64
|
+
returns?: TReturnsValidator;
|
|
65
|
+
} & {
|
|
66
|
+
[Key in keyof TExtraArguments as Key extends "args" | "handler" | "returns" ? never : Key]: TExtraArguments[Key];
|
|
67
|
+
})) => Registration<TFunctionType, TVisibility, ArgsArrayToObject<TCustomArgumentsValidator extends Record<string, never> ? TOneOrZeroArguments : TOneOrZeroArguments extends [infer TArguments extends AnyRecord] ? [Expand<ObjectType<TCustomArgumentsValidator> & TArguments>] : [ObjectType<TCustomArgumentsValidator>]>, TReturnValue>;
|
|
68
|
+
/** The ctx type a custom builder's handlers receive. */
|
|
69
|
+
export type CustomCtx<TBuilder> = TBuilder extends CustomBuilder<any, any, infer TCustom, any, infer TInputCtx, any, any> ? Overwrite<TInputCtx, TCustom> : never;
|
|
70
|
+
/**
|
|
71
|
+
* Wraps a query builder (`query`, `internalQuery`, `queryGeneric`) with a
|
|
72
|
+
* customization.
|
|
73
|
+
*
|
|
74
|
+
* @param query - The Convex query builder to wrap
|
|
75
|
+
* @param customization - `{ args, input }`, or `customCtx(...)`
|
|
76
|
+
* @returns A builder used like `query({ args, returns, handler })`
|
|
77
|
+
* @example
|
|
78
|
+
* export const userQuery = customQuery(query, customCtx(async (ctx) => ({ user: await requireUser(ctx) })));
|
|
79
|
+
*/
|
|
80
|
+
export declare function customQuery<TCustomArgumentsValidator extends PropertyValidators, TCustomCtx extends AnyRecord, TCustomMadeArguments extends AnyRecord, TVisibility extends FunctionVisibility, TDataModel extends GenericDataModel, TExtraArguments extends AnyRecord = object>(query: QueryBuilder<TDataModel, TVisibility>, customization: Customization<GenericQueryCtx<TDataModel>, TCustomArgumentsValidator, TCustomCtx, TCustomMadeArguments, TExtraArguments>): CustomBuilder<"query", TCustomArgumentsValidator, TCustomCtx, TCustomMadeArguments, GenericQueryCtx<TDataModel>, TVisibility, TExtraArguments>;
|
|
81
|
+
/**
|
|
82
|
+
* Wraps a mutation builder (`mutation`, `internalMutation`, `mutationGeneric`)
|
|
83
|
+
* with a customization.
|
|
84
|
+
*
|
|
85
|
+
* @param mutation - The Convex mutation builder to wrap
|
|
86
|
+
* @param customization - `{ args, input }`, or `customCtx(...)`
|
|
87
|
+
* @returns A builder used like `mutation({ args, returns, handler })`
|
|
88
|
+
* @example
|
|
89
|
+
* export const userMutation = customMutation(mutation, { args: {}, input: async (ctx) => ({ args: {}, ctx: { user: await requireUser(ctx) } }) });
|
|
90
|
+
*/
|
|
91
|
+
export declare function customMutation<TCustomArgumentsValidator extends PropertyValidators, TCustomCtx extends AnyRecord, TCustomMadeArguments extends AnyRecord, TVisibility extends FunctionVisibility, TDataModel extends GenericDataModel, TExtraArguments extends AnyRecord = object>(mutation: MutationBuilder<TDataModel, TVisibility>, customization: Customization<GenericMutationCtx<TDataModel>, TCustomArgumentsValidator, TCustomCtx, TCustomMadeArguments, TExtraArguments>): CustomBuilder<"mutation", TCustomArgumentsValidator, TCustomCtx, TCustomMadeArguments, GenericMutationCtx<TDataModel>, TVisibility, TExtraArguments>;
|
|
92
|
+
/**
|
|
93
|
+
* Wraps an action builder (`action`, `internalAction`, `actionGeneric`) with a
|
|
94
|
+
* customization.
|
|
95
|
+
*
|
|
96
|
+
* @param action - The Convex action builder to wrap
|
|
97
|
+
* @param customization - `{ args, input }`, or `customCtx(...)`
|
|
98
|
+
* @returns A builder used like `action({ args, returns, handler })`
|
|
99
|
+
* @example
|
|
100
|
+
* export const keyedAction = customAction(action, { args: { key: v.string() }, input: async (_ctx, { key }) => ({ args: {}, ctx: { key } }) });
|
|
101
|
+
*/
|
|
102
|
+
export declare function customAction<TCustomArgumentsValidator extends PropertyValidators, TCustomCtx extends AnyRecord, TCustomMadeArguments extends AnyRecord, TVisibility extends FunctionVisibility, TDataModel extends GenericDataModel, TExtraArguments extends AnyRecord = object>(action: ActionBuilder<TDataModel, TVisibility>, customization: Customization<GenericActionCtx<TDataModel>, TCustomArgumentsValidator, TCustomCtx, TCustomMadeArguments, TExtraArguments>): CustomBuilder<"action", TCustomArgumentsValidator, TCustomCtx, TCustomMadeArguments, GenericActionCtx<TDataModel>, TVisibility, TExtraArguments>;
|
|
103
|
+
export {};
|
|
104
|
+
//# sourceMappingURL=builders.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"builders.d.ts","sourceRoot":"","sources":["../src/builders.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EACV,aAAa,EACb,6BAA6B,EAC7B,iBAAiB,EACjB,+BAA+B,EAC/B,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,+BAA+B,EAChC,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EACV,gBAAgB,EAChB,UAAU,EACV,kBAAkB,EAClB,SAAS,EACV,MAAM,eAAe,CAAC;AAIvB,KAAK,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAGrC,8CAA8C;AAC9C,MAAM,MAAM,WAAW,CAAC,IAAI,EAAE,UAAU,EAAE,oBAAoB,IAAI;IAChE,IAAI,EAAE,oBAAoB,CAAC;IAC3B,GAAG,EAAE,UAAU,CAAC;IAChB,uEAAuE;IACvE,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE;QACpB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC9B,GAAG,EAAE,IAAI,CAAC;QACV,MAAM,EAAE,OAAO,CAAC;KACjB,KAAK,OAAO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AAU,EACV,oBAAoB,EACpB,eAAe,CAChB,GACA,aAAa,CACd,QAAQ,EACR,yBAAyB,EACzB,UAAU,EACV,oBAAoB,EACpB,gBAAgB,CAAC,UAAU,CAAC,EAC5B,WAAW,EACX,eAAe,CAChB,CAKA"}
|
package/dist/builders.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module @vllnt/convex-helpers/builders
|
|
3
|
+
* Wrap Convex `query` / `mutation` / `action` builders so every function made
|
|
4
|
+
* with them gets extra `ctx` fields (and optionally consumes extra args), e.g.
|
|
5
|
+
* an authenticated user resolved once in a shared `input`.
|
|
6
|
+
*
|
|
7
|
+
* Adapted, with changes, from `convex-helpers/server/customFunctions` 0.1.124
|
|
8
|
+
* (Apache-2.0, see NOTICE): same signatures and runtime behaviour for
|
|
9
|
+
* `customQuery`, `customMutation`, `customAction` and `customCtx`; the
|
|
10
|
+
* `CustomBuilder`, `Customization` and `Registration` types follow upstream's.
|
|
11
|
+
* Unlike upstream, a customization must supply both `args` and `input` (the
|
|
12
|
+
* types already require them). `tests/builders-parity.test.ts`
|
|
13
|
+
* runs both side by side.
|
|
14
|
+
*/
|
|
15
|
+
import { asObjectValidator, v } from "convex/values";
|
|
16
|
+
/**
|
|
17
|
+
* Builds a customization that adds ctx fields and leaves args alone.
|
|
18
|
+
* `modifyCtx` receives the original ctx and the definition's extra properties
|
|
19
|
+
* (all keys but `args`, `handler` and `returns`).
|
|
20
|
+
*
|
|
21
|
+
* @param modifyCtx - Returns the ctx fields to add (may be async)
|
|
22
|
+
* @returns A customization for {@link customQuery}, {@link customMutation} or {@link customAction}
|
|
23
|
+
* @example
|
|
24
|
+
* const authQuery = customQuery(query, customCtx(async (ctx) => ({ user: await requireUser(ctx) })));
|
|
25
|
+
*/
|
|
26
|
+
export function customCtx(modifyCtx) {
|
|
27
|
+
return {
|
|
28
|
+
args: {},
|
|
29
|
+
input: async (ctx, _ignored, extra) => ({
|
|
30
|
+
args: {},
|
|
31
|
+
ctx: await modifyCtx(ctx, extra),
|
|
32
|
+
}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function mergeFields(fields, added) {
|
|
36
|
+
return Object.entries(added).reduce((merged, [key, validator]) => {
|
|
37
|
+
const existing = merged[key];
|
|
38
|
+
if (existing === undefined)
|
|
39
|
+
return { ...merged, [key]: validator };
|
|
40
|
+
if (existing.kind !== validator.kind) {
|
|
41
|
+
throw new Error(`Cannot intersect validators with different kinds: ${existing.kind} and ${validator.kind}`);
|
|
42
|
+
}
|
|
43
|
+
// Keep the required side when one side is optional; else keep the function's.
|
|
44
|
+
return existing.isOptional === "optional" &&
|
|
45
|
+
validator.isOptional !== "optional"
|
|
46
|
+
? { ...merged, [key]: validator }
|
|
47
|
+
: merged;
|
|
48
|
+
}, { ...fields });
|
|
49
|
+
}
|
|
50
|
+
function addInputArguments(functionArguments, inputArguments) {
|
|
51
|
+
const validator = asObjectValidator(functionArguments);
|
|
52
|
+
if (Object.keys(inputArguments).length === 0)
|
|
53
|
+
return validator;
|
|
54
|
+
if (validator.kind === "object") {
|
|
55
|
+
return v.object(mergeFields(validator.fields, inputArguments));
|
|
56
|
+
}
|
|
57
|
+
if (validator.kind === "union") {
|
|
58
|
+
return v.union(...validator.members.map((member) => addInputArguments(member, inputArguments)));
|
|
59
|
+
}
|
|
60
|
+
throw new Error("Cannot add arguments to a validator that is not an object or union.");
|
|
61
|
+
}
|
|
62
|
+
function splitKeys(source, keys) {
|
|
63
|
+
const entries = Object.entries(source);
|
|
64
|
+
return {
|
|
65
|
+
picked: Object.fromEntries(entries.filter(([key]) => keys.includes(key))),
|
|
66
|
+
rest: Object.fromEntries(entries.filter(([key]) => !keys.includes(key))),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function wrapHandler(options) {
|
|
70
|
+
const { customization, extra, handler, splitArgs } = options;
|
|
71
|
+
const inputKeys = Object.keys(customization.args);
|
|
72
|
+
return async (ctx, allArguments) => {
|
|
73
|
+
const { picked, rest } = splitArgs
|
|
74
|
+
? splitKeys(allArguments, inputKeys)
|
|
75
|
+
: { picked: allArguments, rest: allArguments };
|
|
76
|
+
const added = await customization.input(ctx, picked, extra);
|
|
77
|
+
const result = await handler({ ...ctx, ...added.ctx }, { ...rest, ...added.args });
|
|
78
|
+
if (added.onSuccess)
|
|
79
|
+
await added.onSuccess({ args: rest, ctx, result });
|
|
80
|
+
return result;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function assertNoInputArguments(customization) {
|
|
84
|
+
if (Object.keys(customization.args).length > 0) {
|
|
85
|
+
throw new Error("If you're using a custom function with arguments for the input " +
|
|
86
|
+
"customization, you must declare the arguments for the function too.");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function customFunctionBuilder(builder, customization) {
|
|
90
|
+
return (definition) => {
|
|
91
|
+
// A bare function is its own handler, with no args validator or extras.
|
|
92
|
+
const { args, handler = definition, returns, ...extra } = definition;
|
|
93
|
+
if (args) {
|
|
94
|
+
return builder({
|
|
95
|
+
args: addInputArguments(args, customization.args),
|
|
96
|
+
handler: wrapHandler({
|
|
97
|
+
customization,
|
|
98
|
+
extra,
|
|
99
|
+
handler,
|
|
100
|
+
splitArgs: true,
|
|
101
|
+
}),
|
|
102
|
+
returns,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
assertNoInputArguments(customization);
|
|
106
|
+
return builder({
|
|
107
|
+
handler: wrapHandler({ customization, extra, handler, splitArgs: false }),
|
|
108
|
+
returns,
|
|
109
|
+
});
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Wraps a query builder (`query`, `internalQuery`, `queryGeneric`) with a
|
|
114
|
+
* customization.
|
|
115
|
+
*
|
|
116
|
+
* @param query - The Convex query builder to wrap
|
|
117
|
+
* @param customization - `{ args, input }`, or `customCtx(...)`
|
|
118
|
+
* @returns A builder used like `query({ args, returns, handler })`
|
|
119
|
+
* @example
|
|
120
|
+
* export const userQuery = customQuery(query, customCtx(async (ctx) => ({ user: await requireUser(ctx) })));
|
|
121
|
+
*/
|
|
122
|
+
export function customQuery(query, customization) {
|
|
123
|
+
return customFunctionBuilder(query, customization);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Wraps a mutation builder (`mutation`, `internalMutation`, `mutationGeneric`)
|
|
127
|
+
* with a customization.
|
|
128
|
+
*
|
|
129
|
+
* @param mutation - The Convex mutation builder to wrap
|
|
130
|
+
* @param customization - `{ args, input }`, or `customCtx(...)`
|
|
131
|
+
* @returns A builder used like `mutation({ args, returns, handler })`
|
|
132
|
+
* @example
|
|
133
|
+
* export const userMutation = customMutation(mutation, { args: {}, input: async (ctx) => ({ args: {}, ctx: { user: await requireUser(ctx) } }) });
|
|
134
|
+
*/
|
|
135
|
+
export function customMutation(mutation, customization) {
|
|
136
|
+
return customFunctionBuilder(mutation, customization);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Wraps an action builder (`action`, `internalAction`, `actionGeneric`) with a
|
|
140
|
+
* customization.
|
|
141
|
+
*
|
|
142
|
+
* @param action - The Convex action builder to wrap
|
|
143
|
+
* @param customization - `{ args, input }`, or `customCtx(...)`
|
|
144
|
+
* @returns A builder used like `action({ args, returns, handler })`
|
|
145
|
+
* @example
|
|
146
|
+
* export const keyedAction = customAction(action, { args: { key: v.string() }, input: async (_ctx, { key }) => ({ args: {}, ctx: { key } }) });
|
|
147
|
+
*/
|
|
148
|
+
export function customAction(action, customization) {
|
|
149
|
+
return customFunctionBuilder(action, customization);
|
|
150
|
+
}
|
|
151
|
+
//# sourceMappingURL=builders.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"builders.js","sourceRoot":"","sources":["../src/builders.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AA0BH,OAAO,EAAE,iBAAiB,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAwCrD;;;;;;;;;GASG;AACH,MAAM,UA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