@sanity-labs/client-fake-for-test 0.17.3 → 0.18.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/README.md +19 -3
- package/dist/index.cjs +104 -74
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +62 -38
- package/dist/index.d.ts +62 -38
- package/dist/index.js +100 -69
- package/dist/index.js.map +1 -1
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
npm install -D @sanity-labs/client-fake-for-test
|
|
8
8
|
```
|
|
9
9
|
|
|
10
|
+
`@sanity/client` (7.21 or later, or 8) is a peer dependency: the fake's HTTP errors extend its `ClientError`, so they need the copy your code imports. See [Errors are `ClientError`s](#errors-are-clienterrors).
|
|
11
|
+
|
|
10
12
|
## What this is for
|
|
11
13
|
|
|
12
14
|
Any code typed against `SanityClient` (or a narrow subset of its methods) that you want to test without:
|
|
@@ -101,7 +103,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
101
103
|
|
|
102
104
|
`createTestClient({ mutationGuard })` installs a pluggable write interceptor. It runs once for each document's net change in a commit through the document mutation API — `create` / `createOrReplace` / `createIfNotExists` / `patch` / `delete` and the equivalent `transaction()` / `mutate()` operations. Document publish and unpublish actions are expanded into their published and draft mutations. Release and version actions (`releases.*`, `createVersion`, and `unpublishVersion`) are not intercepted.
|
|
103
105
|
|
|
104
|
-
The client owns the _seam_; the caller owns the _policy_. This is the hook a workflow test bench uses to enforce Content Lake **mutation guards** at the write path without re-implementing guard evaluation. Each call receives the original/final image (`before` is `null` on create, `after` is `null` on delete), the `action`, and the acting `identity`. Return every denying guard as `{ guardID, name? }`; the fake evaluates every net document mutation, aggregates the returned denials, deduplicates them by `guardID` in first-observed order, rolls back the commit, and throws
|
|
106
|
+
The client owns the _seam_; the caller owns the _policy_. This is the hook a workflow test bench uses to enforce Content Lake **mutation guards** at the write path without re-implementing guard evaluation. Each call receives the original/final image (`before` is `null` on create, `after` is `null` on delete), the `action`, and the acting `identity`. Return every denying guard as `{ guardID, name? }`; the fake evaluates every net document mutation, aggregates the returned denials, deduplicates them by `guardID` in first-observed order, rolls back the commit, and throws `GuardDeniedError`: the Content Lake's 403, a `ClientError` (see [Errors are `ClientError`s](#errors-are-clienterrors)), with `type: "guardDeniedError"` and `denials` on it. Other thrown callback errors propagate unchanged.
|
|
105
107
|
|
|
106
108
|
```ts
|
|
107
109
|
const client = createTestClient({
|
|
@@ -151,7 +153,7 @@ The fake tells apart two kinds of bad token:
|
|
|
151
153
|
- **Unknown** (never registered): binding it (`createTestClient({ token })`, `withConfig({ token })`) throws at once. That is a mistake in the test setup, not something production answers.
|
|
152
154
|
- **Revoked** (`client.revokeIdentity(token)`): models a token the platform has no session for any more, because it was revoked, expired or deleted. The token stays registered and still binds, as production clients accept any string. From the next request on, every request made with it on any handle in the family is refused: `fetch`, `getDocument(s)`, every mutation, transaction and action (release and version actions included), `releases.get` / `releases.fetchDocuments`, and `request()` (`/users/me`, the ACL, the project and Access APIs, the History API). Nothing is written, and a write already queued is refused when its turn comes. Requests made before the call keep their answers, so "the first read succeeds, then the token is refused" is `await read(); client.revokeIdentity(token);`. Revocation is permanent; `addIdentity` does not restore the token.
|
|
153
155
|
|
|
154
|
-
The refusal is the platform's answer, probed on staging and production, raised as a `PlatformHttpError`
|
|
156
|
+
The refusal is the platform's answer, probed on staging and production, raised as a `PlatformHttpError`, a `ClientError` (see [Errors are `ClientError`s](#errors-are-clienterrors)):
|
|
155
157
|
|
|
156
158
|
```ts
|
|
157
159
|
{
|
|
@@ -164,7 +166,7 @@ The refusal is the platform's answer, probed on staging and production, raised a
|
|
|
164
166
|
statusMessage: "Unauthorized",
|
|
165
167
|
method: "GET", // or "POST" for mutations and actions
|
|
166
168
|
url: "/data/query/test", // the API path, without host or version
|
|
167
|
-
headers: {},
|
|
169
|
+
headers: { "content-type": "application/json; charset=utf-8" },
|
|
168
170
|
body: { error: "Unauthorized", errorCode: "SIO-401-ANF", message: "Session not found", statusCode: 401 },
|
|
169
171
|
},
|
|
170
172
|
}
|
|
@@ -210,6 +212,8 @@ Filter grants come from the ACL, not the token, and are not checked. `/users/me`
|
|
|
210
212
|
|
|
211
213
|
The fake checks every written document the way the Content Lake does (gradient `pkg/security/document_permission_checker.go`): a create needs `create` on the new document; an update, replace or patch needs `update` on the document before the write **and** on the document after it; a delete needs `update` on the document before. So a patch or `createOrReplace` that moves a document out of the identity's `update` grant (a filter it stops matching) is refused with `WriteAccessDeniedError`, and nothing is written. The same holds for `version.create` replacing a version and for the documents `document.publish` / `document.unpublish` write and delete. A transaction, `mutate` or action batch is checked per document on its net change once every mutation is staged, so a document patched out of the grant and back again in one transaction passes, and one created and deleted in it is not checked. Reads inside a write are not checked.
|
|
212
214
|
|
|
215
|
+
The refusal is the Content Lake's 403, a `ClientError` with the `insufficientPermissionsError` wrapped in a `mutationError`, as gradient writes it; `message` is `transaction failed: Insufficient permissions; permission "update" required` followed by the item. The error also carries `documentId`, `permission` and `matchingGrants`, which the platform's answer does not name.
|
|
216
|
+
|
|
213
217
|
#### System-document grants
|
|
214
218
|
|
|
215
219
|
User-issued writes to system document IDs beginning with `_.` require the `manage` permission **in addition to** the `create` or `update` the write needs, each checked on the same documents (before and after the write), as the Content Lake's permission checker does. `create` and `update` alone do not authorize these writes, and neither does `manage` alone; grant `manage` alongside `create` / `update` to identities whose tests intentionally create, replace, patch, delete, transact, mutate, publish, or unpublish system documents. The fake's internal release/version bookkeeping remains outside access-control interception.
|
|
@@ -280,6 +284,18 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
|
|
|
280
284
|
- **Project features.** `GET /projects/<projectId>/features` answers the project's feature names as a bare array, sorted and once each, as the project API does. Seed them with `createTestClient({ projectFeatures: { "<projectId>": ["advancedRolesManagement"] } })`; a project without an entry has no features and answers `[]`. Like `/projects/<projectId>`, it answers any project id to any acting identity: the platform lets any project member read it, and every identity is a member of every project.
|
|
281
285
|
- **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
|
|
282
286
|
|
|
287
|
+
### Errors are `ClientError`s
|
|
288
|
+
|
|
289
|
+
Every error the fake throws for an HTTP answer of the platform is an instance of `@sanity/client`'s `ClientError`, so code that branches on `error instanceof ClientError` handles it as it handles production's:
|
|
290
|
+
|
|
291
|
+
| Class | Answer |
|
|
292
|
+
| --- | --- |
|
|
293
|
+
| `PlatformHttpError` | the platform's refusals: a revoked token's 401, a token grant the Content Lake cannot parse (400), the Access API's 400/403/404, a route a resource does not mount (404), a Media Library release (403), an action's failed `if…RevisionId` precondition (409 `documentRevisionIDDoesNotMatchError`, or 404 `documentNotFoundError` when the document is missing) |
|
|
294
|
+
| `WriteAccessDeniedError` | a write the grants do not permit (403) |
|
|
295
|
+
| `GuardDeniedError` | a write a mutation guard denies (403) |
|
|
296
|
+
|
|
297
|
+
The fake hands `ClientError` the response the platform sends, and `ClientError` derives `statusCode`, `message`, `responseBody` and `details` from it, exactly as for a real response. `instanceof` needs the fake and your code to share one `@sanity/client`, so it is a peer dependency (7.21 or later, or 8); with several copies installed, dedupe them. Mistakes in a test's setup (an unknown token, a document without `_id`, an unimplemented member) stay plain `Error`s prefixed `[client-fake-for-test]`, as do refusals whose platform answer the fake does not model yet (a mutation's existing id, missing target or `ifRevisionId` mismatch, an unknown id at `/projects/<projectId>/users/<id>`, which carries `statusCode: 404`).
|
|
298
|
+
|
|
283
299
|
### Test-only helpers (not on real `SanityClient`)
|
|
284
300
|
|
|
285
301
|
Useful in test bodies, but a giveaway that the code under test isn't using the real client. Keep them in the test file, not in the code being tested.
|
package/dist/index.cjs
CHANGED
|
@@ -1,40 +1,41 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: !0 });
|
|
3
|
-
var groqJs = require("groq-js");
|
|
3
|
+
var groqJs = require("groq-js"), client = require("@sanity/client");
|
|
4
4
|
const ERR_PREFIX = "[client-fake-for-test]";
|
|
5
5
|
function fakeError(message) {
|
|
6
6
|
return new Error(`${ERR_PREFIX} ${message}`);
|
|
7
7
|
}
|
|
8
|
-
class PlatformHttpError extends
|
|
9
|
-
statusCode;
|
|
10
|
-
response;
|
|
11
|
-
responseBody;
|
|
12
|
-
details;
|
|
8
|
+
class PlatformHttpError extends client.ClientError {
|
|
13
9
|
constructor(args) {
|
|
14
|
-
|
|
15
|
-
super(clientErrorMessage(args)), this.name = "PlatformHttpError", this.statusCode = statusCode, this.response = { body, url: path, method, headers: {}, statusCode, statusMessage }, this.responseBody = typeof body == "string" ? body : JSON.stringify(body, null, 2);
|
|
16
|
-
const error = isRecord(body) ? body.error : void 0;
|
|
17
|
-
this.details = isRecord(error) ? error : void 0;
|
|
10
|
+
super(platformResponse(args)), this.name = "PlatformHttpError";
|
|
18
11
|
}
|
|
19
12
|
}
|
|
20
|
-
function
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
13
|
+
function platformResponse(args) {
|
|
14
|
+
const { method, path, statusCode, statusMessage, body } = args;
|
|
15
|
+
return {
|
|
16
|
+
body,
|
|
17
|
+
url: path,
|
|
18
|
+
method,
|
|
19
|
+
headers: { "content-type": `${typeof body == "string" ? "text/html" : "application/json"}; charset=utf-8` },
|
|
20
|
+
statusCode,
|
|
21
|
+
statusMessage
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function transactionRefused(request, cause) {
|
|
25
|
+
return platformResponse({
|
|
26
|
+
...request,
|
|
27
|
+
statusCode: 403,
|
|
28
|
+
statusMessage: "Forbidden",
|
|
29
|
+
body: {
|
|
30
|
+
error: {
|
|
31
|
+
description: `transaction failed: ${cause.description}`,
|
|
32
|
+
items: [{ error: cause, index: 0 }],
|
|
33
|
+
type: "mutationError"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
});
|
|
36
37
|
}
|
|
37
|
-
const notMounted = ({ method, path }) => new PlatformHttpError({
|
|
38
|
+
const DEFAULT_WRITE = { method: "POST", path: "/data/mutate" }, notMounted = ({ method, path }) => new PlatformHttpError({
|
|
38
39
|
method,
|
|
39
40
|
path,
|
|
40
41
|
statusCode: 404,
|
|
@@ -695,13 +696,17 @@ function attributeRecord(attribute) {
|
|
|
695
696
|
);
|
|
696
697
|
return { type, key, values: { ...values }, activeSource, activeValue };
|
|
697
698
|
}
|
|
698
|
-
class WriteAccessDeniedError extends
|
|
699
|
+
class WriteAccessDeniedError extends client.ClientError {
|
|
699
700
|
documentId;
|
|
700
701
|
permission;
|
|
701
702
|
matchingGrants;
|
|
702
703
|
constructor(args) {
|
|
703
704
|
super(
|
|
704
|
-
|
|
705
|
+
transactionRefused(args.request ?? DEFAULT_WRITE, {
|
|
706
|
+
description: `Insufficient permissions; permission "${args.permission}" required`,
|
|
707
|
+
permission: args.permission,
|
|
708
|
+
type: "insufficientPermissionsError"
|
|
709
|
+
})
|
|
705
710
|
), this.name = "WriteAccessDeniedError", this.documentId = args.documentId, this.permission = args.permission, this.matchingGrants = args.matchingGrants;
|
|
706
711
|
}
|
|
707
712
|
}
|
|
@@ -731,7 +736,7 @@ async function evaluateWriteAccess(args) {
|
|
|
731
736
|
return { allowed: !1, matchingGrants: matching };
|
|
732
737
|
}
|
|
733
738
|
async function enforceWriteAccess(args) {
|
|
734
|
-
const { document, grants, permission, userId } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
|
|
739
|
+
const { document, grants, permission, userId, request } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
|
|
735
740
|
document,
|
|
736
741
|
grants,
|
|
737
742
|
permission,
|
|
@@ -741,11 +746,13 @@ async function enforceWriteAccess(args) {
|
|
|
741
746
|
throw typeof document._id != "string" ? new WriteAccessDeniedError({
|
|
742
747
|
documentId: "(unknown)",
|
|
743
748
|
permission,
|
|
744
|
-
matchingGrants
|
|
749
|
+
matchingGrants,
|
|
750
|
+
request
|
|
745
751
|
}) : new WriteAccessDeniedError({
|
|
746
752
|
documentId: document._id,
|
|
747
753
|
permission,
|
|
748
|
-
matchingGrants
|
|
754
|
+
matchingGrants,
|
|
755
|
+
request
|
|
749
756
|
});
|
|
750
757
|
}
|
|
751
758
|
function defaultAclPath(projectId, dataset) {
|
|
@@ -855,24 +862,24 @@ function makeRequestImpl(ctx) {
|
|
|
855
862
|
);
|
|
856
863
|
};
|
|
857
864
|
}
|
|
858
|
-
class GuardDeniedError extends
|
|
859
|
-
statusCode = 403;
|
|
865
|
+
class GuardDeniedError extends client.ClientError {
|
|
860
866
|
type = "guardDeniedError";
|
|
861
867
|
denials;
|
|
862
|
-
|
|
863
|
-
response;
|
|
864
|
-
constructor(denials) {
|
|
868
|
+
constructor(denials, request = DEFAULT_WRITE) {
|
|
865
869
|
const unique = uniqueDenials(denials);
|
|
866
|
-
super(
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
};
|
|
870
|
+
super(
|
|
871
|
+
transactionRefused(request, {
|
|
872
|
+
description: guardDeniedDescription(unique),
|
|
873
|
+
denials: unique,
|
|
874
|
+
type: "guardDeniedError"
|
|
875
|
+
})
|
|
876
|
+
), this.name = "GuardDeniedError", this.denials = unique;
|
|
874
877
|
}
|
|
875
878
|
}
|
|
879
|
+
function guardDeniedDescription(denials) {
|
|
880
|
+
const named = denials.map(({ guardID, name }) => name ? `${guardID} (${name})` : guardID);
|
|
881
|
+
return `mutation denied by ${denials.length} guard(s): ${named.join(" ")}`;
|
|
882
|
+
}
|
|
876
883
|
function uniqueDenials(denials) {
|
|
877
884
|
const seen = /* @__PURE__ */ new Set();
|
|
878
885
|
return denials.filter((denial) => seen.has(denial.guardID) ? !1 : (seen.add(denial.guardID), !0));
|
|
@@ -888,14 +895,14 @@ function mutationContexts(images) {
|
|
|
888
895
|
return context === void 0 ? [] : [context];
|
|
889
896
|
});
|
|
890
897
|
}
|
|
891
|
-
async function enforceMutationGuards(guard, contexts) {
|
|
898
|
+
async function enforceMutationGuards(guard, contexts, request) {
|
|
892
899
|
if (guard === void 0) return;
|
|
893
900
|
const denials = [];
|
|
894
901
|
for (const context of contexts) {
|
|
895
902
|
const denied = await guard(context);
|
|
896
903
|
denied !== void 0 && denials.push(...denied);
|
|
897
904
|
}
|
|
898
|
-
if (denials.length > 0) throw new GuardDeniedError(denials);
|
|
905
|
+
if (denials.length > 0) throw new GuardDeniedError(denials, request);
|
|
899
906
|
}
|
|
900
907
|
function describeType(value) {
|
|
901
908
|
return value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`;
|
|
@@ -1293,7 +1300,7 @@ function requireActive(release) {
|
|
|
1293
1300
|
`Release "${release.name}" is "${release.state}", but only "active" releases accept version writes (create / replace / discard / unpublish). Unschedule or unarchive it back to "active" first, or target a different release.`
|
|
1294
1301
|
);
|
|
1295
1302
|
}
|
|
1296
|
-
async function applyAction(store, action) {
|
|
1303
|
+
async function applyAction(store, action, request = ACTIONS_REQUEST) {
|
|
1297
1304
|
switch (action.actionType) {
|
|
1298
1305
|
case "sanity.action.release.create": {
|
|
1299
1306
|
if (maybeRelease(store, action.releaseId) !== void 0)
|
|
@@ -1397,7 +1404,7 @@ async function applyAction(store, action) {
|
|
|
1397
1404
|
return store.remove(release._id), { transactionId: cryptoRandomKey() };
|
|
1398
1405
|
}
|
|
1399
1406
|
case "sanity.action.document.version.create": {
|
|
1400
|
-
if ("baseId" in action) return createVersionFromBase(store, action);
|
|
1407
|
+
if ("baseId" in action) return createVersionFromBase(store, action, request);
|
|
1401
1408
|
const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
|
|
1402
1409
|
if (releaseId === void 0)
|
|
1403
1410
|
throw fakeError(
|
|
@@ -1444,7 +1451,12 @@ async function applyAction(store, action) {
|
|
|
1444
1451
|
`Cannot publish "${action.publishedId}": draft "${action.draftId}" not found. document.publish promotes an existing draft onto the published id \u2014 create the draft first (e.g. client.createOrReplace({ _id: "${action.draftId}", ... })).`
|
|
1445
1452
|
);
|
|
1446
1453
|
const published = store.get(action.publishedId);
|
|
1447
|
-
requireRevisionMatch(action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
|
|
1454
|
+
requireRevisionMatch(request, action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
|
|
1455
|
+
request,
|
|
1456
|
+
action.publishedId,
|
|
1457
|
+
published?._rev,
|
|
1458
|
+
action.ifPublishedRevisionId
|
|
1459
|
+
);
|
|
1448
1460
|
const promoted = promote({ ...draft, _id: action.publishedId });
|
|
1449
1461
|
return published !== void 0 && (promoted._createdAt = published._createdAt), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
|
|
1450
1462
|
}
|
|
@@ -1469,7 +1481,7 @@ function requireDraftOf(action) {
|
|
|
1469
1481
|
`${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
|
|
1470
1482
|
);
|
|
1471
1483
|
}
|
|
1472
|
-
async function createVersionFromBase(store, action) {
|
|
1484
|
+
async function createVersionFromBase(store, action, request) {
|
|
1473
1485
|
const { releaseId, publishedId } = parseVersionId(action.versionId);
|
|
1474
1486
|
if (publishedId !== action.publishedId)
|
|
1475
1487
|
throw fakeError(
|
|
@@ -1481,7 +1493,7 @@ async function createVersionFromBase(store, action) {
|
|
|
1481
1493
|
throw fakeError(
|
|
1482
1494
|
`Cannot create version "${action.versionId}": base document "${action.baseId}" not found. version.create with \`baseId\` copies an existing document; pass \`document\` instead when there is nothing to copy.`
|
|
1483
1495
|
);
|
|
1484
|
-
requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1496
|
+
requireRevisionMatch(request, action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1485
1497
|
const existing = store.get(action.versionId), copy = {
|
|
1486
1498
|
...base,
|
|
1487
1499
|
_id: action.versionId,
|
|
@@ -1490,14 +1502,33 @@ async function createVersionFromBase(store, action) {
|
|
|
1490
1502
|
}, promoted = promote(copy);
|
|
1491
1503
|
return store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1492
1504
|
}
|
|
1493
|
-
|
|
1505
|
+
const ACTIONS_REQUEST = { method: "POST", path: "/data/actions" };
|
|
1506
|
+
function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
|
|
1494
1507
|
if (!(expectedRev === void 0 || actualRev === expectedRev))
|
|
1495
|
-
throw
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1508
|
+
throw actualRev === void 0 ? new PlatformHttpError({
|
|
1509
|
+
...request,
|
|
1510
|
+
statusCode: 404,
|
|
1511
|
+
statusMessage: "Not Found",
|
|
1512
|
+
body: {
|
|
1513
|
+
error: {
|
|
1514
|
+
description: `The document with the ID ${JSON.stringify(documentId)} was not found`,
|
|
1515
|
+
id: documentId,
|
|
1516
|
+
type: "documentNotFoundError"
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
}) : new PlatformHttpError({
|
|
1520
|
+
...request,
|
|
1521
|
+
statusCode: 409,
|
|
1522
|
+
statusMessage: "Conflict",
|
|
1523
|
+
body: {
|
|
1524
|
+
error: {
|
|
1525
|
+
currentRevisionID: actualRev,
|
|
1526
|
+
description: `Document ${JSON.stringify(documentId)} has unexpected revision ID (${JSON.stringify(actualRev)}), expected ${JSON.stringify(expectedRev)}`,
|
|
1527
|
+
expectedRevisionID: expectedRev,
|
|
1528
|
+
type: "documentRevisionIDDoesNotMatchError"
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
});
|
|
1501
1532
|
}
|
|
1502
1533
|
async function applyActions(store, actions, hooks) {
|
|
1503
1534
|
const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), gatedIds = /* @__PURE__ */ new Set(), remember = (id) => {
|
|
@@ -1552,7 +1583,7 @@ async function applyActions(store, actions, hooks) {
|
|
|
1552
1583
|
remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
|
|
1553
1584
|
break;
|
|
1554
1585
|
}
|
|
1555
|
-
last = await applyAction(store, a);
|
|
1586
|
+
last = await applyAction(store, a, hooks?.request);
|
|
1556
1587
|
}
|
|
1557
1588
|
for (const id of gatedIds) {
|
|
1558
1589
|
const before = snapshot.get(id), after = store.get(id);
|
|
@@ -1727,9 +1758,9 @@ function wrapNamespace(ns, prefix, onCall) {
|
|
|
1727
1758
|
}
|
|
1728
1759
|
});
|
|
1729
1760
|
}
|
|
1730
|
-
function wrapWithGuards(
|
|
1761
|
+
function wrapWithGuards(client2, config) {
|
|
1731
1762
|
const { getStub, onCall, recorded } = config;
|
|
1732
|
-
return new Proxy(
|
|
1763
|
+
return new Proxy(client2, {
|
|
1733
1764
|
get(target, prop, receiver) {
|
|
1734
1765
|
if (typeof prop == "symbol") return Reflect.get(target, prop, receiver);
|
|
1735
1766
|
if (prop in target) {
|
|
@@ -1979,13 +2010,13 @@ function makeHandle(handleArgs) {
|
|
|
1979
2010
|
if (access !== void 0)
|
|
1980
2011
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
1981
2012
|
};
|
|
1982
|
-
let beforeWrite;
|
|
2013
|
+
let beforeWrite, writeRequest = DEFAULT_WRITE;
|
|
1983
2014
|
const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
|
|
1984
|
-
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
2015
|
+
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
|
|
1985
2016
|
try {
|
|
1986
2017
|
return await run();
|
|
1987
2018
|
} finally {
|
|
1988
|
-
beforeWrite = void 0;
|
|
2019
|
+
beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
|
|
1989
2020
|
}
|
|
1990
2021
|
}), commitHistory = (transactionId) => {
|
|
1991
2022
|
beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
|
|
@@ -2052,13 +2083,15 @@ function makeHandle(handleArgs) {
|
|
|
2052
2083
|
document,
|
|
2053
2084
|
grants: access.grants,
|
|
2054
2085
|
permission,
|
|
2055
|
-
userId: actorId()
|
|
2086
|
+
userId: actorId(),
|
|
2087
|
+
request: writeRequest
|
|
2056
2088
|
});
|
|
2057
2089
|
}, guardGate = async (contexts) => {
|
|
2058
2090
|
const identity = actorId();
|
|
2059
2091
|
await enforceMutationGuards(
|
|
2060
2092
|
mutationGuard,
|
|
2061
|
-
contexts.map((context) => ({ ...context, identity }))
|
|
2093
|
+
contexts.map((context) => ({ ...context, identity })),
|
|
2094
|
+
writeRequest
|
|
2062
2095
|
);
|
|
2063
2096
|
}, guardOne = async (action, before, after) => {
|
|
2064
2097
|
await guardGate([{ action, before, after }]);
|
|
@@ -2141,17 +2174,14 @@ function makeHandle(handleArgs) {
|
|
|
2141
2174
|
txnOptions?.returnFirst ?? !1
|
|
2142
2175
|
);
|
|
2143
2176
|
}, runAction = async (actions) => {
|
|
2144
|
-
const request =
|
|
2145
|
-
method: "POST",
|
|
2146
|
-
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2147
|
-
};
|
|
2177
|
+
const request = lakeRequest("POST", "actions");
|
|
2148
2178
|
if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2149
2179
|
return write(async () => {
|
|
2150
2180
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2151
2181
|
const refused = capabilities.refusedActions[action.actionType];
|
|
2152
2182
|
if (refused !== void 0) throw refused(request);
|
|
2153
2183
|
}
|
|
2154
|
-
const result = await applyActions(store, actions, { gate, guard: guardGate });
|
|
2184
|
+
const result = await applyActions(store, actions, { gate, guard: guardGate, request });
|
|
2155
2185
|
return commitHistory(result.transactionId), result;
|
|
2156
2186
|
}, request);
|
|
2157
2187
|
}, accessVisibleDocs = async () => {
|
|
@@ -2164,7 +2194,7 @@ function makeHandle(handleArgs) {
|
|
|
2164
2194
|
}, visibleDocs = async (override) => {
|
|
2165
2195
|
const accessible = await accessVisibleDocs();
|
|
2166
2196
|
return applyPerspective(accessible, override ?? perspective);
|
|
2167
|
-
},
|
|
2197
|
+
}, client2 = {
|
|
2168
2198
|
fetch: async (query, params, opts) => {
|
|
2169
2199
|
admitToLake(lakeRequest("GET", "query"));
|
|
2170
2200
|
const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
|
|
@@ -2438,7 +2468,7 @@ function makeHandle(handleArgs) {
|
|
|
2438
2468
|
backend.calls.length = 0;
|
|
2439
2469
|
}
|
|
2440
2470
|
};
|
|
2441
|
-
return wrapWithGuards(
|
|
2471
|
+
return wrapWithGuards(client2, {
|
|
2442
2472
|
getStub: (name) => backend.stubs.get(name),
|
|
2443
2473
|
onCall: (method, args) => {
|
|
2444
2474
|
const rec = {
|