@rowstile/vitest 0.0.0-stage → 0.1.0-alpha.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.
- package/LICENSE +202 -0
- package/README.md +80 -2
- package/dist/index.d.ts +46 -0
- package/dist/index.js +103 -0
- package/package.json +33 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
#
|
|
1
|
+
# rowstile for TypeScript
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The SDK for TypeScript apps on a rowstile policy: every transaction signs in as whoever the request
|
|
4
|
+
or the job acts for, refused writes become a 403 with the database's reason, rows the user can't see a 404,
|
|
5
|
+
signed-in reads stay out of Next.js's caches, and the app refuses to start on a connection that skips
|
|
6
|
+
row-level security. It holds no rowstile logic: it calls the `authz.*` functions the policy made, and
|
|
7
|
+
translates their answers.
|
|
8
|
+
|
|
9
|
+
Next.js with Prisma:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
// src/db.ts
|
|
13
|
+
import { PrismaPg } from "@prisma/adapter-pg";
|
|
14
|
+
import { authz, signedIn } from "@rowstile/prisma";
|
|
15
|
+
import "@rowstile/next"; // signed-in reads never land in a cache
|
|
16
|
+
import "./authz.gen"; // the policy's names (rowstile client)
|
|
17
|
+
|
|
18
|
+
const adapter = signedIn(new PrismaPg({ connectionString: process.env.DATABASE_URL }),
|
|
19
|
+
{ user: async () => (await auth())?.user.id });
|
|
20
|
+
export const db = new PrismaClient({ adapter }).$extends(authz());
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// app/api/folders/[id]/route.ts: no checks; a hidden folder is 404, one the user may not rename 403
|
|
25
|
+
export const PATCH = route(async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
|
|
26
|
+
await db.folder.update({ where: { id: Number((await params).id) }, data: await req.json() });
|
|
27
|
+
return Response.json({ ok: true });
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
| package | what |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `@rowstile/client` | `actingAs(who, fn)`, `job(who, fn)`, `current()`, `Refused`, `NotFound`, `NotSignedIn`, `translate(e)` and `problemResponse(e)` for any driver's error, `errorCode(e)` (rowstile's code: `AZ709`), `calls(queryable)` (the runtime's functions), the `Register` the generated names fill in |
|
|
34
|
+
| `@rowstile/prisma` | `signedIn(adapter, { user })`: every transaction Prisma begins signs in; `authz()`: P2025 as `NotFound` or `Refused` with the reason, refused creates naming the rule, `db.$authz` (`can`, `ids`, `permsOf`, `share`, `check`, ...) |
|
|
35
|
+
| `@rowstile/pg` | `authz(pool, { user })`: `transaction(fn)`, `query()`, the runtime's functions; `changes(pool)` for live updates |
|
|
36
|
+
| `@rowstile/postgres` | `authz(sql, { user })`: `begin(fn)`, the runtime's functions |
|
|
37
|
+
| `@rowstile/drizzle` | `withAuthz(db, { user })`: `transaction(fn)`; `inIds(column, type, perm)` and `ids()` for `where`; `expect(tx, result, ...)` for updates and deletes that changed nothing |
|
|
38
|
+
| `@rowstile/next` | `route(handler)` (403 and 404 problem bodies), `action(fn)` (`{ ok, value }` or `{ ok: false, problem }`), `authzRoutes()` (what the React kit calls), `checkAtStart()` for `instrumentation.ts`; importing it keeps signed-in reads out of caches |
|
|
39
|
+
| `@rowstile/react` | `<AuthzProvider>`, `usePerms(type, ids)` (one call for a list), `<Can>`, `useShares` and a headless `<ShareDialog>`, `useAccessRequest`; kept current over server-sent events |
|
|
40
|
+
| `@rowstile/vitest` | `expect.extend(matchers)`: `toBeRefused(command, reason)`, `toBeNotFound()`; `asUser(who, fn)`; `databasePerWorker(url)`. Vitest 4 or 5 |
|
|
41
|
+
|
|
42
|
+
Who a transaction acts for: `42` or `"42"` (a user), `["service", 3]` (another principal type of the policy),
|
|
43
|
+
or `null` (nobody: only what `anyone` may see). A plain id is always a user's, whatever it holds: `"service:3"`
|
|
44
|
+
is the user with that id, so an id from outside (a username, an identity provider's subject) can't name a
|
|
45
|
+
service. `parsePrincipal("service:3")` reads back what `describe()` wrote, for text your own code wrote. Whoever the code acts for (`actingAs`, a `job`)
|
|
46
|
+
comes first, else the `user` function, else nobody; a `who` given to one call (`transaction(fn, who)`) comes
|
|
47
|
+
before all, and `null` there is nobody. Every transaction signs in, even as nobody, and nothing uses a
|
|
48
|
+
session-level `SET`, so pools and poolers in transaction mode are safe; the change feed needs its own connection
|
|
49
|
+
to Postgres ([Behind a pooler](../../docs/operations.md#behind-a-pooler)).
|
|
50
|
+
|
|
51
|
+
Traps it handles:
|
|
52
|
+
|
|
53
|
+
- **Next.js caching.** Before a transaction signs in as someone, `@rowstile/next` calls Next's `connection()`:
|
|
54
|
+
the render is dynamic, and a signed-in read inside `"use cache"` or `unstable_cache` fails instead of being
|
|
55
|
+
cached for the next user. Reads as nobody may be cached.
|
|
56
|
+
- **Prisma answers some calls together.** It dispatches the `findUnique` calls of one tick, and array
|
|
57
|
+
transactions, from the first caller's context. `authz()` runs each `findUnique` in a transaction of its own,
|
|
58
|
+
and refuses `$transaction([...])` (use `$transaction(async (tx) => ...)`), so no query runs as someone else.
|
|
59
|
+
Use the client `$extends(authz())` returns, and only that one: the client it was made from is refused
|
|
60
|
+
whenever it is used.
|
|
61
|
+
- **Inserts that read the row back** (`RETURNING`, Prisma's `create`) also need the select rule: Postgres's own
|
|
62
|
+
message comes back as `Refused` naming the select rule.
|
|
63
|
+
- **Prisma's promises are lazy**: `actingAs` and `job` await what they return inside their scope.
|
|
64
|
+
- **A connection that drops.** node-postgres stops the process when a client that is checked out loses its
|
|
65
|
+
connection and nobody listens: `@rowstile/pg` listens while it holds one, so the transaction fails instead.
|
|
66
|
+
`changes(pool)` listens again after its connection drops, and tells its subscribers once.
|
|
67
|
+
- **An update that changed nothing** is `NotFound` when the user can't see the row, `Refused` when the database
|
|
68
|
+
says no, and `NotFound` again when the rule allows it and the statement matched nothing for another reason
|
|
69
|
+
(a `where` with more than the key).
|
|
70
|
+
- **The answers in the browser are one user's.** Give `<AuthzProvider user={id}>` if the user can change
|
|
71
|
+
without a page load: the hooks forget what they had and ask again.
|
|
72
|
+
|
|
73
|
+
The types and permissions of the policy are generated names: with a `@rowstile/*` dependency in
|
|
74
|
+
`package.json`, `rowstile client` writes only the names (`[clients] ts = "src/authz.gen.ts"`), registered with
|
|
75
|
+
the SDK, so `db.$authz.can("note", 1, "edt")` doesn't type-check. Policy changes ship as migrations for your
|
|
76
|
+
tool (`rowstile migrate`, with `tool = "prisma"` or `"drizzle"` in `rowstile.toml`).
|
|
77
|
+
|
|
78
|
+
The packages are an npm workspace at the repository root (`npm ci`, then `npx tsc -b sdk/typescript`).
|
|
79
|
+
`integrations/nextjs/` is the conformance suite: a small Next.js app on Prisma 7 and Prisma Migrate, and the
|
|
80
|
+
checks every supported stack passes, with pg, postgres.js, Drizzle and the React kit
|
|
81
|
+
(`integrations/nextjs/test.sh`).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rowstile with Vitest (and Jest: the matchers are plain functions).
|
|
3
|
+
*
|
|
4
|
+
* // vitest.setup.ts
|
|
5
|
+
* import { expect } from "vitest";
|
|
6
|
+
* import { matchers } from "@rowstile/vitest";
|
|
7
|
+
* expect.extend(matchers);
|
|
8
|
+
*
|
|
9
|
+
* await expect(asUser(bob, () => rename(f.id, "x"))).rejects.toBeRefused("update", "folder.edit");
|
|
10
|
+
* await expect(asUser(bob, () => rename(hidden, "x"))).rejects.toBeNotFound();
|
|
11
|
+
*
|
|
12
|
+
* A database per worker: databasePerWorker(ownerUrl) copies the migrated test database (with the policy) once
|
|
13
|
+
* for each worker, so tests that write don't meet each other.
|
|
14
|
+
*/
|
|
15
|
+
import { type Who } from "@rowstile/client";
|
|
16
|
+
/** Runs fn acting for `who`: every transaction it begins signs in as them. */
|
|
17
|
+
export declare function asUser<R>(who: Who, fn: () => R): R;
|
|
18
|
+
interface Result {
|
|
19
|
+
pass: boolean;
|
|
20
|
+
message: () => string;
|
|
21
|
+
}
|
|
22
|
+
export declare const matchers: {
|
|
23
|
+
/** The write was refused; optionally by this command's rule ("update"), and with this in its reason ("folder.edit"). */
|
|
24
|
+
toBeRefused(received: unknown, command?: string, reason?: string): Result;
|
|
25
|
+
/** The row isn't there for this user (hidden, or gone). */
|
|
26
|
+
toBeNotFound(received: unknown): Result;
|
|
27
|
+
};
|
|
28
|
+
declare module "vitest" {
|
|
29
|
+
interface Matchers {
|
|
30
|
+
toBeRefused(command?: string, reason?: string): void | Promise<void>;
|
|
31
|
+
toBeNotFound(): void | Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** This worker's number: Vitest's VITEST_POOL_ID, Jest's JEST_WORKER_ID. */
|
|
35
|
+
export declare function workerId(): string;
|
|
36
|
+
/** A database for this worker, copied from `url`'s (migrated, with the policy): its URL, with the same user.
|
|
37
|
+
* The copy is made once per run by a role that may create databases (the owner), while nothing else is
|
|
38
|
+
* connected to the original. appUrl: the app role's URL for the copy, if given. */
|
|
39
|
+
export declare function databasePerWorker(url: string, options?: {
|
|
40
|
+
appUrl?: string;
|
|
41
|
+
fresh?: boolean;
|
|
42
|
+
}): Promise<{
|
|
43
|
+
url: string;
|
|
44
|
+
appUrl?: string;
|
|
45
|
+
}>;
|
|
46
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rowstile with Vitest (and Jest: the matchers are plain functions).
|
|
3
|
+
*
|
|
4
|
+
* // vitest.setup.ts
|
|
5
|
+
* import { expect } from "vitest";
|
|
6
|
+
* import { matchers } from "@rowstile/vitest";
|
|
7
|
+
* expect.extend(matchers);
|
|
8
|
+
*
|
|
9
|
+
* await expect(asUser(bob, () => rename(f.id, "x"))).rejects.toBeRefused("update", "folder.edit");
|
|
10
|
+
* await expect(asUser(bob, () => rename(hidden, "x"))).rejects.toBeNotFound();
|
|
11
|
+
*
|
|
12
|
+
* A database per worker: databasePerWorker(ownerUrl) copies the migrated test database (with the policy) once
|
|
13
|
+
* for each worker, so tests that write don't meet each other.
|
|
14
|
+
*/
|
|
15
|
+
import { actingAs, translate, NotFound, Refused } from "@rowstile/client";
|
|
16
|
+
/** Runs fn acting for `who`: every transaction it begins signs in as them. */
|
|
17
|
+
export function asUser(who, fn) {
|
|
18
|
+
return actingAs(who, fn);
|
|
19
|
+
}
|
|
20
|
+
/** The error as rowstile's, whichever driver raised it. */
|
|
21
|
+
const asAuthz = (received) => translate(received) ?? received;
|
|
22
|
+
export const matchers = {
|
|
23
|
+
/** The write was refused; optionally by this command's rule ("update"), and with this in its reason ("folder.edit"). */
|
|
24
|
+
toBeRefused(received, command, reason) {
|
|
25
|
+
const e = asAuthz(received);
|
|
26
|
+
if (!(e instanceof Refused)) {
|
|
27
|
+
return { pass: false, message: () => `expected a refused write, got ${describe(received)}` };
|
|
28
|
+
}
|
|
29
|
+
if (command !== undefined && e.command !== command) {
|
|
30
|
+
return { pass: false, message: () => `expected the ${command} rule to refuse it, but the ${e.command} rule did: ${e.message}` };
|
|
31
|
+
}
|
|
32
|
+
if (reason !== undefined && !e.message.includes(reason) && !e.why.some((line) => line.includes(reason))) {
|
|
33
|
+
return { pass: false, message: () => `expected "${reason}" in the reason, got:\n${[e.message, ...e.why].join("\n")}` };
|
|
34
|
+
}
|
|
35
|
+
return { pass: true, message: () => `expected the write not to be refused, but: ${e.message}` };
|
|
36
|
+
},
|
|
37
|
+
/** The row isn't there for this user (hidden, or gone). */
|
|
38
|
+
toBeNotFound(received) {
|
|
39
|
+
const e = asAuthz(received);
|
|
40
|
+
return e instanceof NotFound
|
|
41
|
+
? { pass: true, message: () => `expected the row to be found, but: ${e.message}` }
|
|
42
|
+
: { pass: false, message: () => `expected NotFound, got ${describe(received)}` };
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
function describe(x) {
|
|
46
|
+
if (x instanceof Error)
|
|
47
|
+
return `${x.name}: ${x.message}`;
|
|
48
|
+
return JSON.stringify(x) ?? String(x);
|
|
49
|
+
}
|
|
50
|
+
/** This worker's number: Vitest's VITEST_POOL_ID, Jest's JEST_WORKER_ID. */
|
|
51
|
+
export function workerId() {
|
|
52
|
+
return process.env.VITEST_POOL_ID ?? process.env.VITEST_WORKER_ID ?? process.env.JEST_WORKER_ID ?? "1";
|
|
53
|
+
}
|
|
54
|
+
/** A database for this worker, copied from `url`'s (migrated, with the policy): its URL, with the same user.
|
|
55
|
+
* The copy is made once per run by a role that may create databases (the owner), while nothing else is
|
|
56
|
+
* connected to the original. appUrl: the app role's URL for the copy, if given. */
|
|
57
|
+
export async function databasePerWorker(url, options = {}) {
|
|
58
|
+
const { default: pg } = await import("pg");
|
|
59
|
+
const base = new URL(url);
|
|
60
|
+
const template = decodeURIComponent(base.pathname.slice(1));
|
|
61
|
+
const name = `${template}_w${workerId()}`;
|
|
62
|
+
const admin = new pg.Client({ connectionString: url });
|
|
63
|
+
await admin.connect();
|
|
64
|
+
try {
|
|
65
|
+
const exists = (await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [name])).rowCount;
|
|
66
|
+
if (exists && options.fresh === false) {
|
|
67
|
+
// keep it
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
const q = (s) => '"' + s.replace(/"/g, '""') + '"';
|
|
71
|
+
if (exists)
|
|
72
|
+
await admin.query(`DROP DATABASE ${q(name)} WITH (FORCE)`);
|
|
73
|
+
// CREATE DATABASE ... TEMPLATE needs no one else connected to the original: this connection moves off it
|
|
74
|
+
await admin.end();
|
|
75
|
+
const other = new pg.Client({ connectionString: withDatabase(url, "postgres") });
|
|
76
|
+
await other.connect();
|
|
77
|
+
try {
|
|
78
|
+
await other.query(`CREATE DATABASE ${q(name)} TEMPLATE ${q(template)}`);
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
// 55006: something is connected to the original (Postgres has waited five seconds for it to leave)
|
|
82
|
+
if (e.code !== "55006")
|
|
83
|
+
throw e;
|
|
84
|
+
throw new Error(`@rowstile/vitest: ${template} can't be copied while anything is connected to it: close ` +
|
|
85
|
+
"what holds it (the app, a migration tool, a console). Where the service keeps a connection of its own " +
|
|
86
|
+
"for minutes after yours (Neon does), a copy per worker can't be made: use one test database, where " +
|
|
87
|
+
"each test rolls back, or a branch for each run", { cause: e });
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
await other.end();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
await admin.end().catch(() => undefined);
|
|
96
|
+
}
|
|
97
|
+
return { url: withDatabase(url, name), appUrl: options.appUrl ? withDatabase(options.appUrl, name) : undefined };
|
|
98
|
+
}
|
|
99
|
+
function withDatabase(url, db) {
|
|
100
|
+
const u = new URL(url);
|
|
101
|
+
u.pathname = "/" + encodeURIComponent(db);
|
|
102
|
+
return u.toString();
|
|
103
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rowstile/vitest",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.0-alpha.3",
|
|
4
|
+
"description": "rowstile with Vitest (and Jest): asUser, toBeRefused, a database per worker",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": { "type": "git", "url": "git+https://github.com/rowstile/rowstile.git", "directory": "sdk/typescript/vitest" },
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@rowstile/client": "0.1.0-alpha.3"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"vitest": "^4.0.0 || ^5.0.0",
|
|
25
|
+
"pg": ">=8"
|
|
26
|
+
},
|
|
27
|
+
"peerDependenciesMeta": {
|
|
28
|
+
"pg": {
|
|
29
|
+
"optional": true
|
|
30
|
+
},
|
|
31
|
+
"vitest": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|