@sanity-labs/client-fake-for-test 0.17.3 → 0.19.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 +43 -6
- package/dist/index.cjs +175 -96
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +72 -40
- package/dist/index.d.ts +72 -40
- package/dist/index.js +171 -91
- package/dist/index.js.map +1 -1
- package/package.json +5 -1
package/dist/index.js
CHANGED
|
@@ -1,38 +1,40 @@
|
|
|
1
1
|
import { parse, evaluate } from "groq-js";
|
|
2
|
+
import { ClientError } from "@sanity/client";
|
|
2
3
|
const ERR_PREFIX = "[client-fake-for-test]";
|
|
3
4
|
function fakeError(message) {
|
|
4
5
|
return new Error(`${ERR_PREFIX} ${message}`);
|
|
5
6
|
}
|
|
6
|
-
class PlatformHttpError extends
|
|
7
|
-
statusCode;
|
|
8
|
-
response;
|
|
9
|
-
responseBody;
|
|
10
|
-
details;
|
|
7
|
+
class PlatformHttpError extends ClientError {
|
|
11
8
|
constructor(args) {
|
|
12
|
-
|
|
13
|
-
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);
|
|
14
|
-
const error = isRecord(body) ? body.error : void 0;
|
|
15
|
-
this.details = isRecord(error) ? error : void 0;
|
|
9
|
+
super(platformResponse(args)), this.name = "PlatformHttpError";
|
|
16
10
|
}
|
|
17
11
|
}
|
|
18
|
-
function
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
12
|
+
function platformResponse(args) {
|
|
13
|
+
const { method, path, statusCode, statusMessage, body } = args;
|
|
14
|
+
return {
|
|
15
|
+
body,
|
|
16
|
+
url: path,
|
|
17
|
+
method,
|
|
18
|
+
headers: { "content-type": `${typeof body == "string" ? "text/html" : "application/json"}; charset=utf-8` },
|
|
19
|
+
statusCode,
|
|
20
|
+
statusMessage
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function transactionRefused(request, cause) {
|
|
24
|
+
return platformResponse({
|
|
25
|
+
...request,
|
|
26
|
+
statusCode: 403,
|
|
27
|
+
statusMessage: "Forbidden",
|
|
28
|
+
body: {
|
|
29
|
+
error: {
|
|
30
|
+
description: `transaction failed: ${cause.description}`,
|
|
31
|
+
items: [{ error: cause, index: 0 }],
|
|
32
|
+
type: "mutationError"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
});
|
|
34
36
|
}
|
|
35
|
-
const notMounted = ({ method, path }) => new PlatformHttpError({
|
|
37
|
+
const DEFAULT_WRITE = { method: "POST", path: "/data/mutate" }, notMounted = ({ method, path }) => new PlatformHttpError({
|
|
36
38
|
method,
|
|
37
39
|
path,
|
|
38
40
|
statusCode: 404,
|
|
@@ -58,6 +60,26 @@ const sessionNotFound = (request) => new PlatformHttpError({
|
|
|
58
60
|
message: "Session not found",
|
|
59
61
|
statusCode: 401
|
|
60
62
|
}
|
|
63
|
+
}), sessionHostMismatch = (request) => new PlatformHttpError({
|
|
64
|
+
...request,
|
|
65
|
+
statusCode: 401,
|
|
66
|
+
statusMessage: "Unauthorized",
|
|
67
|
+
body: {
|
|
68
|
+
statusCode: 401,
|
|
69
|
+
errorCode: "SIO-401-AWH",
|
|
70
|
+
error: "Unauthorized",
|
|
71
|
+
message: "Session does not match project host"
|
|
72
|
+
}
|
|
73
|
+
}), projectMembershipRequired = (request) => accessApiError({
|
|
74
|
+
request,
|
|
75
|
+
statusCode: 401,
|
|
76
|
+
statusMessage: "Unauthorized",
|
|
77
|
+
message: "User must be a member of this project to perform this operation"
|
|
78
|
+
}), mediaLibraryReadRequired = (request) => accessApiError({
|
|
79
|
+
request,
|
|
80
|
+
statusCode: 401,
|
|
81
|
+
statusMessage: "Unauthorized",
|
|
82
|
+
message: "User must be able to read media libraries for this organization to perform this operation"
|
|
61
83
|
}), noPermission = (request) => accessApiError({
|
|
62
84
|
request,
|
|
63
85
|
statusCode: 403,
|
|
@@ -113,6 +135,9 @@ function datasetParts(id) {
|
|
|
113
135
|
const dot = id.indexOf(".");
|
|
114
136
|
return { projectId: id.slice(0, dot), dataset: id.slice(dot + 1) };
|
|
115
137
|
}
|
|
138
|
+
function isProjectMember(tokenProjectId, projectId) {
|
|
139
|
+
return tokenProjectId === void 0 || tokenProjectId === projectId;
|
|
140
|
+
}
|
|
116
141
|
function accessEntryRoles(type) {
|
|
117
142
|
return ({ identity, id }) => identity.access?.[accessKey(type, id)]?.roles;
|
|
118
143
|
}
|
|
@@ -147,6 +172,10 @@ const RESOURCE_CAPABILITIES = {
|
|
|
147
172
|
lookupAtBase: !0,
|
|
148
173
|
identity: "global",
|
|
149
174
|
acl: "served",
|
|
175
|
+
aclRefusals: {
|
|
176
|
+
unknown: notFound("Media library"),
|
|
177
|
+
read: { permission: "sanity.media-library.read", refusal: mediaLibraryReadRequired }
|
|
178
|
+
},
|
|
150
179
|
history: "served",
|
|
151
180
|
actions: "served",
|
|
152
181
|
refusedActions: { "sanity.action.release.create": releaseLimitExceeded },
|
|
@@ -159,6 +188,7 @@ const RESOURCE_CAPABILITIES = {
|
|
|
159
188
|
lookupAtBase: !0,
|
|
160
189
|
identity: "global",
|
|
161
190
|
acl: "served",
|
|
191
|
+
aclRefusals: { unknown: notFound("Resource") },
|
|
162
192
|
history: "served",
|
|
163
193
|
actions: notMounted,
|
|
164
194
|
refusedActions: {},
|
|
@@ -241,8 +271,8 @@ const ACCESS_CAPABILITIES = {
|
|
|
241
271
|
// Single-user reads are served only where the fake checks members read (the
|
|
242
272
|
// organization); elsewhere they refuse rather than answer unchecked.
|
|
243
273
|
user: noPermission,
|
|
244
|
-
//
|
|
245
|
-
memberRoles: ({ identity, id }) => (identity.usersByProject?.[id] ?? identity.user).roles ?? []
|
|
274
|
+
// A member holds its project roles; see `isProjectMember`.
|
|
275
|
+
memberRoles: ({ identity, id }) => isProjectMember(identity.projectId, id) ? (identity.usersByProject?.[id] ?? identity.user).roles ?? [] : void 0
|
|
246
276
|
},
|
|
247
277
|
"media-library": {
|
|
248
278
|
// Staging refuses it only because no probe token held roles read.
|
|
@@ -449,6 +479,8 @@ async function servePlatformRequest(ctx, url) {
|
|
|
449
479
|
const projectFeatures = path.match(PROJECT_FEATURES_PATH);
|
|
450
480
|
if (projectFeatures !== null) {
|
|
451
481
|
const projectId = decodeURIComponent(projectFeatures[1]);
|
|
482
|
+
if (!isProjectMember(ctx.actorProjectId(), projectId))
|
|
483
|
+
throw projectMembershipRequired(request);
|
|
452
484
|
return { value: featuresOf(ctx, projectId) };
|
|
453
485
|
}
|
|
454
486
|
const access = path.match(ACCESS_PATH);
|
|
@@ -467,12 +499,32 @@ async function servePlatformRequest(ctx, url) {
|
|
|
467
499
|
if (rest === "") return row.lookupAtBase ? serveLookup(ctx, resource) : void 0;
|
|
468
500
|
if (rest === "/acl")
|
|
469
501
|
return serveCapability(row.acl, request, () => {
|
|
502
|
+
refuseAcl({ ctx, request, resource, row });
|
|
470
503
|
const own = ctx.own(resource);
|
|
471
504
|
return own === void 0 ? void 0 : { value: own.grants };
|
|
472
505
|
});
|
|
473
506
|
if (rest.startsWith("/history/"))
|
|
474
507
|
return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
|
|
475
508
|
}
|
|
509
|
+
function refuseAclRequest(ctx, url) {
|
|
510
|
+
const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), matched = matchResourcePath(path);
|
|
511
|
+
if (matched?.rest !== "/acl") return;
|
|
512
|
+
const row = capabilitiesOf(matched.resource.type), request = { method: "GET", path };
|
|
513
|
+
serveCapability(
|
|
514
|
+
row.acl,
|
|
515
|
+
request,
|
|
516
|
+
() => refuseAcl({ ctx, request, resource: matched.resource, row })
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
function refuseAcl(args) {
|
|
520
|
+
const { ctx, request, resource, row } = args;
|
|
521
|
+
if (row.aclRefusals === void 0) return;
|
|
522
|
+
const type = row.access.type, id = row.access.id(resource.id), registry = { organizationId: ctx.organizationId, resources: ctx.resources };
|
|
523
|
+
if (!holdsResource(type)(registry, id)) throw row.aclRefusals.unknown(request);
|
|
524
|
+
const { read } = row.aclRefusals;
|
|
525
|
+
if (read !== void 0 && !(ctx.actorAccess()?.[accessKey(type, id)]?.permissions ?? []).includes(read.permission))
|
|
526
|
+
throw read.refusal(request);
|
|
527
|
+
}
|
|
476
528
|
function featuresOf(ctx, projectId) {
|
|
477
529
|
const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
|
|
478
530
|
return [...new Set(features)].toSorted();
|
|
@@ -693,13 +745,17 @@ function attributeRecord(attribute) {
|
|
|
693
745
|
);
|
|
694
746
|
return { type, key, values: { ...values }, activeSource, activeValue };
|
|
695
747
|
}
|
|
696
|
-
class WriteAccessDeniedError extends
|
|
748
|
+
class WriteAccessDeniedError extends ClientError {
|
|
697
749
|
documentId;
|
|
698
750
|
permission;
|
|
699
751
|
matchingGrants;
|
|
700
752
|
constructor(args) {
|
|
701
753
|
super(
|
|
702
|
-
|
|
754
|
+
transactionRefused(args.request ?? DEFAULT_WRITE, {
|
|
755
|
+
description: `Insufficient permissions; permission "${args.permission}" required`,
|
|
756
|
+
permission: args.permission,
|
|
757
|
+
type: "insufficientPermissionsError"
|
|
758
|
+
})
|
|
703
759
|
), this.name = "WriteAccessDeniedError", this.documentId = args.documentId, this.permission = args.permission, this.matchingGrants = args.matchingGrants;
|
|
704
760
|
}
|
|
705
761
|
}
|
|
@@ -729,7 +785,7 @@ async function evaluateWriteAccess(args) {
|
|
|
729
785
|
return { allowed: !1, matchingGrants: matching };
|
|
730
786
|
}
|
|
731
787
|
async function enforceWriteAccess(args) {
|
|
732
|
-
const { document, grants, permission, userId } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
|
|
788
|
+
const { document, grants, permission, userId, request } = args, { allowed, matchingGrants } = await evaluateWriteAccess({
|
|
733
789
|
document,
|
|
734
790
|
grants,
|
|
735
791
|
permission,
|
|
@@ -739,22 +795,18 @@ async function enforceWriteAccess(args) {
|
|
|
739
795
|
throw typeof document._id != "string" ? new WriteAccessDeniedError({
|
|
740
796
|
documentId: "(unknown)",
|
|
741
797
|
permission,
|
|
742
|
-
matchingGrants
|
|
798
|
+
matchingGrants,
|
|
799
|
+
request
|
|
743
800
|
}) : new WriteAccessDeniedError({
|
|
744
801
|
documentId: document._id,
|
|
745
802
|
permission,
|
|
746
|
-
matchingGrants
|
|
803
|
+
matchingGrants,
|
|
804
|
+
request
|
|
747
805
|
});
|
|
748
806
|
}
|
|
749
807
|
function defaultAclPath(projectId, dataset) {
|
|
750
808
|
return `/projects/${projectId}/datasets/${dataset}/acl`;
|
|
751
809
|
}
|
|
752
|
-
function refusedAcl(path) {
|
|
753
|
-
const matched = matchResourcePath(path);
|
|
754
|
-
if (matched?.rest !== "/acl") return;
|
|
755
|
-
const { acl } = capabilitiesOf(matched.resource.type);
|
|
756
|
-
return acl === "served" ? void 0 : acl({ method: "GET", path });
|
|
757
|
-
}
|
|
758
810
|
function projectUserOf(identity, projectId) {
|
|
759
811
|
return identity.usersByProject?.[projectId] ?? identity.user;
|
|
760
812
|
}
|
|
@@ -791,7 +843,7 @@ function serveProjectUsers(args) {
|
|
|
791
843
|
};
|
|
792
844
|
}, byId = consistentProjectRecords({
|
|
793
845
|
projectId: pathProjectId,
|
|
794
|
-
records: identities.map(toRecord)
|
|
846
|
+
records: identities.filter((identity) => isProjectMember(identity.projectId, pathProjectId)).map(toRecord)
|
|
795
847
|
}), ids = requestedIds.split(","), [firstId] = ids;
|
|
796
848
|
if (ids.length === 1 && firstId !== void 0) {
|
|
797
849
|
const record = byId.get(firstId);
|
|
@@ -811,17 +863,19 @@ function serveProjectUsers(args) {
|
|
|
811
863
|
}
|
|
812
864
|
const PROJECT_USERS_PATH = /^\/projects\/([^/]+)\/users\/([^/]+)$/, PROJECT_PATH = /^\/projects\/([^/]+)$/;
|
|
813
865
|
function serveProject(args) {
|
|
814
|
-
const records = args.identities.
|
|
866
|
+
const records = args.identities.filter(
|
|
867
|
+
(identity) => isProjectMember(identity.projectId, args.pathProjectId)
|
|
868
|
+
).map((identity) => {
|
|
815
869
|
const projectUser = projectUserOf(identity, args.pathProjectId);
|
|
816
870
|
return {
|
|
817
871
|
id: projectUser.id,
|
|
818
872
|
...projectUser.id.startsWith("p-") ? { isRobot: !0 } : {},
|
|
819
873
|
...projectUser.roles !== void 0 ? { roles: canonicalProjectRoles(projectUser.roles) } : {}
|
|
820
874
|
};
|
|
821
|
-
}),
|
|
875
|
+
}), byId = consistentProjectRecords({ projectId: args.pathProjectId, records });
|
|
822
876
|
return {
|
|
823
877
|
...args.organizationId !== void 0 ? { organizationId: args.organizationId } : {},
|
|
824
|
-
members: [...
|
|
878
|
+
members: [...byId.values()]
|
|
825
879
|
};
|
|
826
880
|
}
|
|
827
881
|
function makeRequestImpl(ctx) {
|
|
@@ -830,8 +884,8 @@ function makeRequestImpl(ctx) {
|
|
|
830
884
|
const accessControl = getAccess(), path = opts.uri ?? opts.url;
|
|
831
885
|
if (path === "/users/me")
|
|
832
886
|
return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
|
|
833
|
-
if (path !== void 0 && path === accessControl.aclPath
|
|
834
|
-
return accessControl.grants;
|
|
887
|
+
if (path !== void 0 && path === accessControl.aclPath)
|
|
888
|
+
return refuseAclRequest(platform, path), accessControl.grants;
|
|
835
889
|
const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
|
|
836
890
|
if (pathProjectId !== void 0 && requestedIds !== void 0)
|
|
837
891
|
return serveProjectUsers({
|
|
@@ -853,24 +907,24 @@ function makeRequestImpl(ctx) {
|
|
|
853
907
|
);
|
|
854
908
|
};
|
|
855
909
|
}
|
|
856
|
-
class GuardDeniedError extends
|
|
857
|
-
statusCode = 403;
|
|
910
|
+
class GuardDeniedError extends ClientError {
|
|
858
911
|
type = "guardDeniedError";
|
|
859
912
|
denials;
|
|
860
|
-
|
|
861
|
-
response;
|
|
862
|
-
constructor(denials) {
|
|
913
|
+
constructor(denials, request = DEFAULT_WRITE) {
|
|
863
914
|
const unique = uniqueDenials(denials);
|
|
864
|
-
super(
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
};
|
|
915
|
+
super(
|
|
916
|
+
transactionRefused(request, {
|
|
917
|
+
description: guardDeniedDescription(unique),
|
|
918
|
+
denials: unique,
|
|
919
|
+
type: "guardDeniedError"
|
|
920
|
+
})
|
|
921
|
+
), this.name = "GuardDeniedError", this.denials = unique;
|
|
872
922
|
}
|
|
873
923
|
}
|
|
924
|
+
function guardDeniedDescription(denials) {
|
|
925
|
+
const named = denials.map(({ guardID, name }) => name ? `${guardID} (${name})` : guardID);
|
|
926
|
+
return `mutation denied by ${denials.length} guard(s): ${named.join(" ")}`;
|
|
927
|
+
}
|
|
874
928
|
function uniqueDenials(denials) {
|
|
875
929
|
const seen = /* @__PURE__ */ new Set();
|
|
876
930
|
return denials.filter((denial) => seen.has(denial.guardID) ? !1 : (seen.add(denial.guardID), !0));
|
|
@@ -886,14 +940,14 @@ function mutationContexts(images) {
|
|
|
886
940
|
return context === void 0 ? [] : [context];
|
|
887
941
|
});
|
|
888
942
|
}
|
|
889
|
-
async function enforceMutationGuards(guard, contexts) {
|
|
943
|
+
async function enforceMutationGuards(guard, contexts, request) {
|
|
890
944
|
if (guard === void 0) return;
|
|
891
945
|
const denials = [];
|
|
892
946
|
for (const context of contexts) {
|
|
893
947
|
const denied = await guard(context);
|
|
894
948
|
denied !== void 0 && denials.push(...denied);
|
|
895
949
|
}
|
|
896
|
-
if (denials.length > 0) throw new GuardDeniedError(denials);
|
|
950
|
+
if (denials.length > 0) throw new GuardDeniedError(denials, request);
|
|
897
951
|
}
|
|
898
952
|
function describeType(value) {
|
|
899
953
|
return value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`;
|
|
@@ -1291,7 +1345,7 @@ function requireActive(release) {
|
|
|
1291
1345
|
`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.`
|
|
1292
1346
|
);
|
|
1293
1347
|
}
|
|
1294
|
-
async function applyAction(store, action) {
|
|
1348
|
+
async function applyAction(store, action, request = ACTIONS_REQUEST) {
|
|
1295
1349
|
switch (action.actionType) {
|
|
1296
1350
|
case "sanity.action.release.create": {
|
|
1297
1351
|
if (maybeRelease(store, action.releaseId) !== void 0)
|
|
@@ -1395,7 +1449,7 @@ async function applyAction(store, action) {
|
|
|
1395
1449
|
return store.remove(release._id), { transactionId: cryptoRandomKey() };
|
|
1396
1450
|
}
|
|
1397
1451
|
case "sanity.action.document.version.create": {
|
|
1398
|
-
if ("baseId" in action) return createVersionFromBase(store, action);
|
|
1452
|
+
if ("baseId" in action) return createVersionFromBase(store, action, request);
|
|
1399
1453
|
const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
|
|
1400
1454
|
if (releaseId === void 0)
|
|
1401
1455
|
throw fakeError(
|
|
@@ -1442,7 +1496,12 @@ async function applyAction(store, action) {
|
|
|
1442
1496
|
`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}", ... })).`
|
|
1443
1497
|
);
|
|
1444
1498
|
const published = store.get(action.publishedId);
|
|
1445
|
-
requireRevisionMatch(action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
|
|
1499
|
+
requireRevisionMatch(request, action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(
|
|
1500
|
+
request,
|
|
1501
|
+
action.publishedId,
|
|
1502
|
+
published?._rev,
|
|
1503
|
+
action.ifPublishedRevisionId
|
|
1504
|
+
);
|
|
1446
1505
|
const promoted = promote({ ...draft, _id: action.publishedId });
|
|
1447
1506
|
return published !== void 0 && (promoted._createdAt = published._createdAt), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
|
|
1448
1507
|
}
|
|
@@ -1467,7 +1526,7 @@ function requireDraftOf(action) {
|
|
|
1467
1526
|
`${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
|
|
1468
1527
|
);
|
|
1469
1528
|
}
|
|
1470
|
-
async function createVersionFromBase(store, action) {
|
|
1529
|
+
async function createVersionFromBase(store, action, request) {
|
|
1471
1530
|
const { releaseId, publishedId } = parseVersionId(action.versionId);
|
|
1472
1531
|
if (publishedId !== action.publishedId)
|
|
1473
1532
|
throw fakeError(
|
|
@@ -1479,7 +1538,7 @@ async function createVersionFromBase(store, action) {
|
|
|
1479
1538
|
throw fakeError(
|
|
1480
1539
|
`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.`
|
|
1481
1540
|
);
|
|
1482
|
-
requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1541
|
+
requireRevisionMatch(request, action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1483
1542
|
const existing = store.get(action.versionId), copy = {
|
|
1484
1543
|
...base,
|
|
1485
1544
|
_id: action.versionId,
|
|
@@ -1488,14 +1547,33 @@ async function createVersionFromBase(store, action) {
|
|
|
1488
1547
|
}, promoted = promote(copy);
|
|
1489
1548
|
return store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1490
1549
|
}
|
|
1491
|
-
|
|
1550
|
+
const ACTIONS_REQUEST = { method: "POST", path: "/data/actions" };
|
|
1551
|
+
function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
|
|
1492
1552
|
if (!(expectedRev === void 0 || actualRev === expectedRev))
|
|
1493
|
-
throw
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1553
|
+
throw actualRev === void 0 ? new PlatformHttpError({
|
|
1554
|
+
...request,
|
|
1555
|
+
statusCode: 404,
|
|
1556
|
+
statusMessage: "Not Found",
|
|
1557
|
+
body: {
|
|
1558
|
+
error: {
|
|
1559
|
+
description: `The document with the ID ${JSON.stringify(documentId)} was not found`,
|
|
1560
|
+
id: documentId,
|
|
1561
|
+
type: "documentNotFoundError"
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
}) : new PlatformHttpError({
|
|
1565
|
+
...request,
|
|
1566
|
+
statusCode: 409,
|
|
1567
|
+
statusMessage: "Conflict",
|
|
1568
|
+
body: {
|
|
1569
|
+
error: {
|
|
1570
|
+
currentRevisionID: actualRev,
|
|
1571
|
+
description: `Document ${JSON.stringify(documentId)} has unexpected revision ID (${JSON.stringify(actualRev)}), expected ${JSON.stringify(expectedRev)}`,
|
|
1572
|
+
expectedRevisionID: expectedRev,
|
|
1573
|
+
type: "documentRevisionIDDoesNotMatchError"
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
});
|
|
1499
1577
|
}
|
|
1500
1578
|
async function applyActions(store, actions, hooks) {
|
|
1501
1579
|
const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), gatedIds = /* @__PURE__ */ new Set(), remember = (id) => {
|
|
@@ -1550,7 +1628,7 @@ async function applyActions(store, actions, hooks) {
|
|
|
1550
1628
|
remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
|
|
1551
1629
|
break;
|
|
1552
1630
|
}
|
|
1553
|
-
last = await applyAction(store, a);
|
|
1631
|
+
last = await applyAction(store, a, hooks?.request);
|
|
1554
1632
|
}
|
|
1555
1633
|
for (const id of gatedIds) {
|
|
1556
1634
|
const before = snapshot.get(id), after = store.get(id);
|
|
@@ -1954,10 +2032,14 @@ function makeHandle(handleArgs) {
|
|
|
1954
2032
|
if (access === void 0)
|
|
1955
2033
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1956
2034
|
return access;
|
|
1957
|
-
},
|
|
1958
|
-
if (token
|
|
1959
|
-
|
|
1960
|
-
|
|
2035
|
+
}, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
|
|
2036
|
+
if (token === void 0) return;
|
|
2037
|
+
if (backend.revoked.has(token)) throw sessionNotFound(request);
|
|
2038
|
+
const tokenProjectId = backend.identities.get(token)?.projectId;
|
|
2039
|
+
if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
|
|
2040
|
+
throw sessionHostMismatch(request);
|
|
2041
|
+
}, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
|
|
2042
|
+
refuseSession(request);
|
|
1961
2043
|
const access = activeAccess();
|
|
1962
2044
|
if (access === void 0) return;
|
|
1963
2045
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -1977,13 +2059,13 @@ function makeHandle(handleArgs) {
|
|
|
1977
2059
|
if (access !== void 0)
|
|
1978
2060
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
1979
2061
|
};
|
|
1980
|
-
let beforeWrite;
|
|
2062
|
+
let beforeWrite, writeRequest = DEFAULT_WRITE;
|
|
1981
2063
|
const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
|
|
1982
|
-
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
2064
|
+
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
|
|
1983
2065
|
try {
|
|
1984
2066
|
return await run();
|
|
1985
2067
|
} finally {
|
|
1986
|
-
beforeWrite = void 0;
|
|
2068
|
+
beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
|
|
1987
2069
|
}
|
|
1988
2070
|
}), commitHistory = (transactionId) => {
|
|
1989
2071
|
beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
|
|
@@ -2050,13 +2132,15 @@ function makeHandle(handleArgs) {
|
|
|
2050
2132
|
document,
|
|
2051
2133
|
grants: access.grants,
|
|
2052
2134
|
permission,
|
|
2053
|
-
userId: actorId()
|
|
2135
|
+
userId: actorId(),
|
|
2136
|
+
request: writeRequest
|
|
2054
2137
|
});
|
|
2055
2138
|
}, guardGate = async (contexts) => {
|
|
2056
2139
|
const identity = actorId();
|
|
2057
2140
|
await enforceMutationGuards(
|
|
2058
2141
|
mutationGuard,
|
|
2059
|
-
contexts.map((context) => ({ ...context, identity }))
|
|
2142
|
+
contexts.map((context) => ({ ...context, identity })),
|
|
2143
|
+
writeRequest
|
|
2060
2144
|
);
|
|
2061
2145
|
}, guardOne = async (action, before, after) => {
|
|
2062
2146
|
await guardGate([{ action, before, after }]);
|
|
@@ -2139,17 +2223,14 @@ function makeHandle(handleArgs) {
|
|
|
2139
2223
|
txnOptions?.returnFirst ?? !1
|
|
2140
2224
|
);
|
|
2141
2225
|
}, runAction = async (actions) => {
|
|
2142
|
-
const request =
|
|
2143
|
-
|
|
2144
|
-
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2145
|
-
};
|
|
2146
|
-
if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2226
|
+
const request = lakeRequest("POST", "actions");
|
|
2227
|
+
if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2147
2228
|
return write(async () => {
|
|
2148
2229
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2149
2230
|
const refused = capabilities.refusedActions[action.actionType];
|
|
2150
2231
|
if (refused !== void 0) throw refused(request);
|
|
2151
2232
|
}
|
|
2152
|
-
const result = await applyActions(store, actions, { gate, guard: guardGate });
|
|
2233
|
+
const result = await applyActions(store, actions, { gate, guard: guardGate, request });
|
|
2153
2234
|
return commitHistory(result.transactionId), result;
|
|
2154
2235
|
}, request);
|
|
2155
2236
|
}, accessVisibleDocs = async () => {
|
|
@@ -2350,9 +2431,7 @@ function makeHandle(handleArgs) {
|
|
|
2350
2431
|
request: withSession(
|
|
2351
2432
|
makeRequestImpl({
|
|
2352
2433
|
getAccess: requireActiveAccess,
|
|
2353
|
-
|
|
2354
|
-
// client to the global API host.
|
|
2355
|
-
useProjectHostname: useProjectHostname && resource === void 0,
|
|
2434
|
+
useProjectHostname: projectHosted,
|
|
2356
2435
|
organizationId: backend.organizationId,
|
|
2357
2436
|
listIdentities: members,
|
|
2358
2437
|
platform: {
|
|
@@ -2371,6 +2450,7 @@ function makeHandle(handleArgs) {
|
|
|
2371
2450
|
return access.globalUser ?? access.currentUser;
|
|
2372
2451
|
},
|
|
2373
2452
|
actorAccess: () => requireActiveAccess().access,
|
|
2453
|
+
actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
|
|
2374
2454
|
identities: members,
|
|
2375
2455
|
resources: () => [...registry.values()].map((entry) => entry.resource)
|
|
2376
2456
|
}
|