@sanity-labs/client-fake-for-test 0.16.0 → 0.17.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 +36 -1
- package/dist/index.cjs +188 -81
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -6
- package/dist/index.d.ts +28 -6
- package/dist/index.js +188 -81
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -128,11 +128,18 @@ export declare interface CreateTestClientOptions {
|
|
|
128
128
|
* `/projects/<projectId>` answer as `organizationId`.
|
|
129
129
|
*/
|
|
130
130
|
organizationId?: string;
|
|
131
|
+
/**
|
|
132
|
+
* The features each project has, keyed by projectId: what
|
|
133
|
+
* `GET /projects/<projectId>/features` answers, sorted. A project
|
|
134
|
+
* without an entry has none and answers `[]`.
|
|
135
|
+
*/
|
|
136
|
+
projectFeatures?: Record<string, string[]>;
|
|
131
137
|
/**
|
|
132
138
|
* Opt-in access-control simulation. When set, the client exposes
|
|
133
139
|
* `request({ url })` that serves `/users/me` (host-aware), the
|
|
134
|
-
* configured ACL path, `/projects/<projectId>` (members),
|
|
135
|
-
* `/projects/<projectId>/users/<ids>`,
|
|
140
|
+
* configured ACL path, `/projects/<projectId>` (members),
|
|
141
|
+
* `/projects/<projectId>/users/<ids>`, `/projects/<projectId>/roles`,
|
|
142
|
+
* `/projects/<projectId>/features` and the other platform routes,
|
|
136
143
|
* AND every mutation is gated through the supplied `grants`
|
|
137
144
|
* — writes that the grants don't permit throw a `WriteAccessDeniedError`
|
|
138
145
|
* shaped like Sanity's 403. Lets tests demonstrate the full
|
|
@@ -401,10 +408,25 @@ export declare interface FetchOptions {
|
|
|
401
408
|
signal?: AbortSignal;
|
|
402
409
|
}
|
|
403
410
|
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
411
|
+
/**
|
|
412
|
+
* One grant: `permissions` on the documents a GROQ `filter` matches, as an
|
|
413
|
+
* ACL serves them, or on the ids a `path()` glob matches, as a token
|
|
414
|
+
* carries them (the token's `{ s, p }`). The Content Lake holds a grant as
|
|
415
|
+
* one or the other and evaluates a path grant as `_id in path("<path>")`
|
|
416
|
+
* (gradient `pkg/security/models.go` `Grant`, `FilterExpression`). A token
|
|
417
|
+
* grant's permissions are whatever the token names; the Content Lake
|
|
418
|
+
* refuses the token when one is not a permission it knows, or when the
|
|
419
|
+
* path does not parse (see `./token-grants.ts`).
|
|
420
|
+
*/
|
|
421
|
+
export declare type Grant =
|
|
422
|
+
| {
|
|
423
|
+
filter: string;
|
|
424
|
+
permissions: DocumentValuePermission[];
|
|
425
|
+
}
|
|
426
|
+
| {
|
|
427
|
+
path: string;
|
|
428
|
+
permissions: string[];
|
|
429
|
+
};
|
|
408
430
|
|
|
409
431
|
export declare interface GuardConfig {
|
|
410
432
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -128,11 +128,18 @@ export declare interface CreateTestClientOptions {
|
|
|
128
128
|
* `/projects/<projectId>` answer as `organizationId`.
|
|
129
129
|
*/
|
|
130
130
|
organizationId?: string;
|
|
131
|
+
/**
|
|
132
|
+
* The features each project has, keyed by projectId: what
|
|
133
|
+
* `GET /projects/<projectId>/features` answers, sorted. A project
|
|
134
|
+
* without an entry has none and answers `[]`.
|
|
135
|
+
*/
|
|
136
|
+
projectFeatures?: Record<string, string[]>;
|
|
131
137
|
/**
|
|
132
138
|
* Opt-in access-control simulation. When set, the client exposes
|
|
133
139
|
* `request({ url })` that serves `/users/me` (host-aware), the
|
|
134
|
-
* configured ACL path, `/projects/<projectId>` (members),
|
|
135
|
-
* `/projects/<projectId>/users/<ids>`,
|
|
140
|
+
* configured ACL path, `/projects/<projectId>` (members),
|
|
141
|
+
* `/projects/<projectId>/users/<ids>`, `/projects/<projectId>/roles`,
|
|
142
|
+
* `/projects/<projectId>/features` and the other platform routes,
|
|
136
143
|
* AND every mutation is gated through the supplied `grants`
|
|
137
144
|
* — writes that the grants don't permit throw a `WriteAccessDeniedError`
|
|
138
145
|
* shaped like Sanity's 403. Lets tests demonstrate the full
|
|
@@ -401,10 +408,25 @@ export declare interface FetchOptions {
|
|
|
401
408
|
signal?: AbortSignal;
|
|
402
409
|
}
|
|
403
410
|
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
411
|
+
/**
|
|
412
|
+
* One grant: `permissions` on the documents a GROQ `filter` matches, as an
|
|
413
|
+
* ACL serves them, or on the ids a `path()` glob matches, as a token
|
|
414
|
+
* carries them (the token's `{ s, p }`). The Content Lake holds a grant as
|
|
415
|
+
* one or the other and evaluates a path grant as `_id in path("<path>")`
|
|
416
|
+
* (gradient `pkg/security/models.go` `Grant`, `FilterExpression`). A token
|
|
417
|
+
* grant's permissions are whatever the token names; the Content Lake
|
|
418
|
+
* refuses the token when one is not a permission it knows, or when the
|
|
419
|
+
* path does not parse (see `./token-grants.ts`).
|
|
420
|
+
*/
|
|
421
|
+
export declare type Grant =
|
|
422
|
+
| {
|
|
423
|
+
filter: string;
|
|
424
|
+
permissions: DocumentValuePermission[];
|
|
425
|
+
}
|
|
426
|
+
| {
|
|
427
|
+
path: string;
|
|
428
|
+
permissions: string[];
|
|
429
|
+
};
|
|
408
430
|
|
|
409
431
|
export declare interface GuardConfig {
|
|
410
432
|
/**
|
package/dist/index.js
CHANGED
|
@@ -3,67 +3,6 @@ const ERR_PREFIX = "[client-fake-for-test]";
|
|
|
3
3
|
function fakeError(message) {
|
|
4
4
|
return new Error(`${ERR_PREFIX} ${message}`);
|
|
5
5
|
}
|
|
6
|
-
function createDocumentHistory() {
|
|
7
|
-
const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
|
|
8
|
-
return {
|
|
9
|
-
commit: ({ transactionId, author, before, after }) => {
|
|
10
|
-
const afterById = new Map(after.map((doc) => [doc._id, doc])), ids = /* @__PURE__ */ new Set([...before.keys(), ...afterById.keys()]), effects = [];
|
|
11
|
-
for (const id of ids) {
|
|
12
|
-
const previous = before.get(id), next = afterById.get(id);
|
|
13
|
-
previous !== next && (previous !== void 0 && keep(previous), next !== void 0 && keep(next), next === void 0 && previous !== void 0 ? deleted.set(id, structuredClone(previous)) : deleted.delete(id), effects.push({
|
|
14
|
-
documentId: id,
|
|
15
|
-
after: next === void 0 ? void 0 : structuredClone(next),
|
|
16
|
-
existed: previous !== void 0
|
|
17
|
-
}));
|
|
18
|
-
}
|
|
19
|
-
effects.length !== 0 && transactions.push({
|
|
20
|
-
id: transactionId,
|
|
21
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
22
|
-
author,
|
|
23
|
-
effects
|
|
24
|
-
});
|
|
25
|
-
},
|
|
26
|
-
documentsAt: ({ ids, revision, current }) => ids.flatMap((id) => {
|
|
27
|
-
const image = revisions.get(`${id} ${revision}`) ?? current.find((doc) => doc._id === id && doc._rev === revision);
|
|
28
|
-
return image === void 0 ? [] : [structuredClone(image)];
|
|
29
|
-
}),
|
|
30
|
-
lastImage: (id) => deleted.get(id),
|
|
31
|
-
documentIds: () => [
|
|
32
|
-
...new Set(transactions.flatMap((txn) => txn.effects.map((effect) => effect.documentId)))
|
|
33
|
-
],
|
|
34
|
-
transactions: (ids, visible) => transactions.filter((txn) => txn.effects.some((effect) => ids.includes(effect.documentId))).map((txn) => ({ ...txn, effects: txn.effects.filter((e) => visible(e.documentId)) })).map((txn) => ({
|
|
35
|
-
id: txn.id,
|
|
36
|
-
timestamp: txn.timestamp,
|
|
37
|
-
...txn.author !== void 0 ? { author: txn.author } : {},
|
|
38
|
-
mutations: txn.effects.map((effect) => {
|
|
39
|
-
if (effect.after === void 0) return { delete: { id: effect.documentId } };
|
|
40
|
-
const after = structuredClone(effect.after);
|
|
41
|
-
return effect.existed ? { createOrReplace: after } : { create: after };
|
|
42
|
-
}),
|
|
43
|
-
documentIDs: txn.effects.map((effect) => effect.documentId)
|
|
44
|
-
})),
|
|
45
|
-
events: (ids) => Object.fromEntries(
|
|
46
|
-
ids.map((id) => [
|
|
47
|
-
id,
|
|
48
|
-
transactions.flatMap(
|
|
49
|
-
(txn) => txn.effects.filter((effect) => effect.documentId === id && effect.after !== void 0).map(
|
|
50
|
-
(effect) => ({
|
|
51
|
-
type: effect.existed ? "updateLiveDocument" : "createLiveDocument",
|
|
52
|
-
id: txn.id,
|
|
53
|
-
documentId: id,
|
|
54
|
-
revisionId: effect.after._rev,
|
|
55
|
-
timestamp: txn.timestamp,
|
|
56
|
-
...txn.author !== void 0 ? { author: txn.author } : {}
|
|
57
|
-
})
|
|
58
|
-
)
|
|
59
|
-
).toReversed()
|
|
60
|
-
])
|
|
61
|
-
)
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
function historyIds(list) {
|
|
65
|
-
return list.split(",").map((id) => decodeURIComponent(id));
|
|
66
|
-
}
|
|
67
6
|
class PlatformHttpError extends Error {
|
|
68
7
|
statusCode;
|
|
69
8
|
response;
|
|
@@ -333,7 +272,148 @@ function dataUrl(args) {
|
|
|
333
272
|
const base = `/${operation}/${dataset}`;
|
|
334
273
|
return `/data${path !== void 0 ? `${base}/${path}` : base}`.replace(/\/($|\?)/, "$1");
|
|
335
274
|
}
|
|
336
|
-
const
|
|
275
|
+
const MAX_PATH_BYTES = 128, PERMISSIONS = /* @__PURE__ */ new Set(["read", "update", "create", "manage", "history", "editHistory"]), MISPLACED_WILDCARD = /* @__PURE__ */ new Map([
|
|
276
|
+
["*", "wildcard must be last component"],
|
|
277
|
+
["**", "descendant wildcard must be last component"]
|
|
278
|
+
]), ELEMENT_LINE = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
|
|
279
|
+
function validElement(element) {
|
|
280
|
+
return element.split(`
|
|
281
|
+
`).some((line) => ELEMENT_LINE.test(line));
|
|
282
|
+
}
|
|
283
|
+
const GO_ESCAPES = {
|
|
284
|
+
"\x07": "\\a",
|
|
285
|
+
"\b": "\\b",
|
|
286
|
+
"\f": "\\f",
|
|
287
|
+
"\n": "\\n",
|
|
288
|
+
"\r": "\\r",
|
|
289
|
+
" ": "\\t",
|
|
290
|
+
"\v": "\\v",
|
|
291
|
+
'"': '\\"',
|
|
292
|
+
"\\": "\\\\"
|
|
293
|
+
}, GO_PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S} ]$/u;
|
|
294
|
+
function quoted(value) {
|
|
295
|
+
let out = '"';
|
|
296
|
+
for (const char of value) {
|
|
297
|
+
const escape = GO_ESCAPES[char];
|
|
298
|
+
if (escape !== void 0) {
|
|
299
|
+
out += escape;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
if (GO_PRINTABLE.test(char)) {
|
|
303
|
+
out += char;
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const code = char.codePointAt(0);
|
|
307
|
+
out += code < 128 ? `\\x${code.toString(16).padStart(2, "0")}` : code <= 65535 ? `\\u${code.toString(16).padStart(4, "0")}` : `\\U${code.toString(16).padStart(8, "0")}`;
|
|
308
|
+
}
|
|
309
|
+
return `${out}"`;
|
|
310
|
+
}
|
|
311
|
+
function pathError(path) {
|
|
312
|
+
if (path === "") return "path must contain at least one element";
|
|
313
|
+
if (path.startsWith(".")) return 'path cannot begin with delimiter "."';
|
|
314
|
+
const elements = path.split(".");
|
|
315
|
+
if (elements.includes("")) return "path contains empty element";
|
|
316
|
+
if (new TextEncoder().encode(path).length > MAX_PATH_BYTES)
|
|
317
|
+
return `path exceeds maximum length of ${MAX_PATH_BYTES}`;
|
|
318
|
+
const last = elements.length - 1;
|
|
319
|
+
for (const [index, element] of elements.entries()) {
|
|
320
|
+
const misplaced = MISPLACED_WILDCARD.get(element);
|
|
321
|
+
if (misplaced !== void 0) {
|
|
322
|
+
if (index < last) return misplaced;
|
|
323
|
+
} else if (!validElement(element))
|
|
324
|
+
return `invalid element ${quoted(element)}`;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function pathIncludes(path, id) {
|
|
328
|
+
const pattern = path.split("."), elements = id.split(".");
|
|
329
|
+
for (const [index, element] of pattern.entries()) {
|
|
330
|
+
if (index >= elements.length) return !1;
|
|
331
|
+
if (element === "**") return !0;
|
|
332
|
+
if (element === "*" ? elements[index] === "**" : element !== elements[index]) return !1;
|
|
333
|
+
}
|
|
334
|
+
return pattern.length === elements.length;
|
|
335
|
+
}
|
|
336
|
+
function grantsError(grants) {
|
|
337
|
+
for (const grant of grants) {
|
|
338
|
+
if (!("path" in grant)) continue;
|
|
339
|
+
const error = pathError(grant.path);
|
|
340
|
+
if (error !== void 0) return error;
|
|
341
|
+
const invalid = grant.permissions.find((permission) => !PERMISSIONS.has(permission));
|
|
342
|
+
if (invalid !== void 0) return `invalid permission ${quoted(invalid)}`;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
function refusedToken(request, grants) {
|
|
346
|
+
const description = grantsError(grants);
|
|
347
|
+
if (description !== void 0)
|
|
348
|
+
return new PlatformHttpError({
|
|
349
|
+
...request,
|
|
350
|
+
statusCode: 400,
|
|
351
|
+
statusMessage: "Bad Request",
|
|
352
|
+
body: { error: { description, type: "httpBadRequest" } }
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
function createDocumentHistory() {
|
|
356
|
+
const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
|
|
357
|
+
return {
|
|
358
|
+
commit: ({ transactionId, author, before, after }) => {
|
|
359
|
+
const afterById = new Map(after.map((doc) => [doc._id, doc])), ids = /* @__PURE__ */ new Set([...before.keys(), ...afterById.keys()]), effects = [];
|
|
360
|
+
for (const id of ids) {
|
|
361
|
+
const previous = before.get(id), next = afterById.get(id);
|
|
362
|
+
previous !== next && (previous !== void 0 && keep(previous), next !== void 0 && keep(next), next === void 0 && previous !== void 0 ? deleted.set(id, structuredClone(previous)) : deleted.delete(id), effects.push({
|
|
363
|
+
documentId: id,
|
|
364
|
+
after: next === void 0 ? void 0 : structuredClone(next),
|
|
365
|
+
existed: previous !== void 0
|
|
366
|
+
}));
|
|
367
|
+
}
|
|
368
|
+
effects.length !== 0 && transactions.push({
|
|
369
|
+
id: transactionId,
|
|
370
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
371
|
+
author,
|
|
372
|
+
effects
|
|
373
|
+
});
|
|
374
|
+
},
|
|
375
|
+
documentsAt: ({ ids, revision, current }) => ids.flatMap((id) => {
|
|
376
|
+
const image = revisions.get(`${id} ${revision}`) ?? current.find((doc) => doc._id === id && doc._rev === revision);
|
|
377
|
+
return image === void 0 ? [] : [structuredClone(image)];
|
|
378
|
+
}),
|
|
379
|
+
lastImage: (id) => deleted.get(id),
|
|
380
|
+
documentIds: () => [
|
|
381
|
+
...new Set(transactions.flatMap((txn) => txn.effects.map((effect) => effect.documentId)))
|
|
382
|
+
],
|
|
383
|
+
transactions: (ids, visible) => transactions.filter((txn) => txn.effects.some((effect) => ids.includes(effect.documentId))).map((txn) => ({ ...txn, effects: txn.effects.filter((e) => visible(e.documentId)) })).map((txn) => ({
|
|
384
|
+
id: txn.id,
|
|
385
|
+
timestamp: txn.timestamp,
|
|
386
|
+
...txn.author !== void 0 ? { author: txn.author } : {},
|
|
387
|
+
mutations: txn.effects.map((effect) => {
|
|
388
|
+
if (effect.after === void 0) return { delete: { id: effect.documentId } };
|
|
389
|
+
const after = structuredClone(effect.after);
|
|
390
|
+
return effect.existed ? { createOrReplace: after } : { create: after };
|
|
391
|
+
}),
|
|
392
|
+
documentIDs: txn.effects.map((effect) => effect.documentId)
|
|
393
|
+
})),
|
|
394
|
+
events: (ids) => Object.fromEntries(
|
|
395
|
+
ids.map((id) => [
|
|
396
|
+
id,
|
|
397
|
+
transactions.flatMap(
|
|
398
|
+
(txn) => txn.effects.filter((effect) => effect.documentId === id && effect.after !== void 0).map(
|
|
399
|
+
(effect) => ({
|
|
400
|
+
type: effect.existed ? "updateLiveDocument" : "createLiveDocument",
|
|
401
|
+
id: txn.id,
|
|
402
|
+
documentId: id,
|
|
403
|
+
revisionId: effect.after._rev,
|
|
404
|
+
timestamp: txn.timestamp,
|
|
405
|
+
...txn.author !== void 0 ? { author: txn.author } : {}
|
|
406
|
+
})
|
|
407
|
+
)
|
|
408
|
+
).toReversed()
|
|
409
|
+
])
|
|
410
|
+
)
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
function historyIds(list) {
|
|
414
|
+
return list.split(",").map((id) => decodeURIComponent(id));
|
|
415
|
+
}
|
|
416
|
+
const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/;
|
|
337
417
|
function page(data) {
|
|
338
418
|
return { data, nextCursor: null };
|
|
339
419
|
}
|
|
@@ -352,6 +432,11 @@ async function servePlatformRequest(ctx, url) {
|
|
|
352
432
|
const projectId = decodeURIComponent(projectRoles[1]);
|
|
353
433
|
return serveProjectRoles({ ctx, request, projectId });
|
|
354
434
|
}
|
|
435
|
+
const projectFeatures = path.match(PROJECT_FEATURES_PATH);
|
|
436
|
+
if (projectFeatures !== null) {
|
|
437
|
+
const projectId = decodeURIComponent(projectFeatures[1]);
|
|
438
|
+
return { value: featuresOf(ctx, projectId) };
|
|
439
|
+
}
|
|
355
440
|
const access = path.match(ACCESS_PATH);
|
|
356
441
|
if (access !== null) {
|
|
357
442
|
const [, type, id, rest2] = access;
|
|
@@ -374,6 +459,10 @@ async function servePlatformRequest(ctx, url) {
|
|
|
374
459
|
if (rest.startsWith("/history/"))
|
|
375
460
|
return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
|
|
376
461
|
}
|
|
462
|
+
function featuresOf(ctx, projectId) {
|
|
463
|
+
const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
|
|
464
|
+
return [...new Set(features)].toSorted();
|
|
465
|
+
}
|
|
377
466
|
function serveLookup(ctx, resource) {
|
|
378
467
|
if (ctx.organizationId === void 0)
|
|
379
468
|
throw fakeError(
|
|
@@ -385,7 +474,8 @@ function serveHistory(args) {
|
|
|
385
474
|
const { ctx, request, resource, rest, query } = args;
|
|
386
475
|
return serveCapability(capabilitiesOf(resource.type).history, request, () => {
|
|
387
476
|
const own = ctx.own(resource);
|
|
388
|
-
|
|
477
|
+
if (own !== void 0)
|
|
478
|
+
return own.admitToLake(request), readHistory({ own, request, rest, query });
|
|
389
479
|
});
|
|
390
480
|
}
|
|
391
481
|
async function readHistory(args) {
|
|
@@ -612,15 +702,15 @@ async function matchesFilter(args) {
|
|
|
612
702
|
})).get();
|
|
613
703
|
return Array.isArray(data) && data.length === 1;
|
|
614
704
|
}
|
|
705
|
+
async function grantMatches(args) {
|
|
706
|
+
const { document, grant, userId } = args;
|
|
707
|
+
return "path" in grant ? typeof document._id == "string" && pathIncludes(grant.path, document._id) : matchesFilter({ document, filter: grant.filter, userId });
|
|
708
|
+
}
|
|
615
709
|
async function evaluateWriteAccess(args) {
|
|
616
710
|
const { document, grants, permission, userId } = args;
|
|
617
711
|
let matching = 0;
|
|
618
712
|
for (const grant of grants)
|
|
619
|
-
if (await
|
|
620
|
-
document,
|
|
621
|
-
filter: grant.filter,
|
|
622
|
-
userId
|
|
623
|
-
}) && (matching++, grant.permissions.includes(permission)))
|
|
713
|
+
if (await grantMatches({ document, grant, userId }) && (matching++, grant.permissions.includes(permission)))
|
|
624
714
|
return { allowed: !0, matchingGrants: matching };
|
|
625
715
|
return { allowed: !1, matchingGrants: matching };
|
|
626
716
|
}
|
|
@@ -745,7 +835,7 @@ function makeRequestImpl(ctx) {
|
|
|
745
835
|
const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
|
|
746
836
|
if (served !== void 0) return served.value;
|
|
747
837
|
throw fakeError(
|
|
748
|
-
`request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
|
|
838
|
+
`request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", "/projects/<projectId>/features", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
|
|
749
839
|
);
|
|
750
840
|
};
|
|
751
841
|
}
|
|
@@ -1543,7 +1633,7 @@ const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues",
|
|
|
1543
1633
|
},
|
|
1544
1634
|
request: {
|
|
1545
1635
|
what: "generic HTTP request hook \u2014 only wired up when the handle has an acting identity",
|
|
1546
|
-
workaround: "Create the client with `accessControl`, or bind a registered token (`identities` + `token` / `withConfig({ token })`), to enable request() (it serves /users/me, the ACL path, /projects/<projectId>, /projects/<projectId>/users/<ids>, the History API, resource lookup and the Access API). Or register a stub."
|
|
1636
|
+
workaround: "Create the client with `accessControl`, or bind a registered token (`identities` + `token` / `withConfig({ token })`), to enable request() (it serves /users/me, the ACL path, /projects/<projectId>, /projects/<projectId>/users/<ids>, /projects/<projectId>/features, the History API, resource lookup and the Access API). Or register a stub."
|
|
1547
1637
|
},
|
|
1548
1638
|
dryRun: {
|
|
1549
1639
|
what: "not a method \u2014 did you mean the `{ dryRun }` mutation option?",
|
|
@@ -1727,6 +1817,7 @@ function createTestClient(options = {}) {
|
|
|
1727
1817
|
const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
|
|
1728
1818
|
registry: /* @__PURE__ */ new Map(),
|
|
1729
1819
|
organizationId: options.organizationId,
|
|
1820
|
+
projectFeatures: options.projectFeatures ?? {},
|
|
1730
1821
|
log: [],
|
|
1731
1822
|
stubs: /* @__PURE__ */ new Map(),
|
|
1732
1823
|
calls: [],
|
|
@@ -1836,7 +1927,12 @@ function makeHandle(handleArgs) {
|
|
|
1836
1927
|
if (access === void 0)
|
|
1837
1928
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1838
1929
|
return access;
|
|
1839
|
-
},
|
|
1930
|
+
}, admitToLake = (request) => {
|
|
1931
|
+
const access = activeAccess();
|
|
1932
|
+
if (access === void 0) return;
|
|
1933
|
+
const refusal = refusedToken(request, access.grants);
|
|
1934
|
+
if (refusal !== void 0) throw refusal;
|
|
1935
|
+
}, lakeRequest = (method, operation, path) => ({ method, path: dataUrl({ resource, dataset, operation, path }) }), members = () => [
|
|
1840
1936
|
...backend.identities.values(),
|
|
1841
1937
|
...token === void 0 && accessControl !== void 0 ? [
|
|
1842
1938
|
{
|
|
@@ -1852,8 +1948,8 @@ function makeHandle(handleArgs) {
|
|
|
1852
1948
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
1853
1949
|
};
|
|
1854
1950
|
let beforeWrite;
|
|
1855
|
-
const write = (run) => serializeWrite(backend, async () => {
|
|
1856
|
-
beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
1951
|
+
const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
|
|
1952
|
+
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
1857
1953
|
try {
|
|
1858
1954
|
return await run();
|
|
1859
1955
|
} finally {
|
|
@@ -2015,14 +2111,14 @@ function makeHandle(handleArgs) {
|
|
|
2015
2111
|
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2016
2112
|
};
|
|
2017
2113
|
if (capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2018
|
-
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2019
|
-
const refused = capabilities.refusedActions[action.actionType];
|
|
2020
|
-
if (refused !== void 0) throw refused(request);
|
|
2021
|
-
}
|
|
2022
2114
|
return write(async () => {
|
|
2115
|
+
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2116
|
+
const refused = capabilities.refusedActions[action.actionType];
|
|
2117
|
+
if (refused !== void 0) throw refused(request);
|
|
2118
|
+
}
|
|
2023
2119
|
const result = await applyActions(store, actions, { gate, guard: guardGate });
|
|
2024
2120
|
return commitHistory(result.transactionId), result;
|
|
2025
|
-
});
|
|
2121
|
+
}, request);
|
|
2026
2122
|
}, accessVisibleDocs = async () => {
|
|
2027
2123
|
const all = store.all();
|
|
2028
2124
|
if (activeAccess() === void 0) return all;
|
|
@@ -2035,6 +2131,7 @@ function makeHandle(handleArgs) {
|
|
|
2035
2131
|
return applyPerspective(accessible, override ?? perspective);
|
|
2036
2132
|
}, client = {
|
|
2037
2133
|
fetch: async (query, params, opts) => {
|
|
2134
|
+
admitToLake(lakeRequest("GET", "query"));
|
|
2038
2135
|
const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
|
|
2039
2136
|
dataset: await visibleDocs(opts?.perspective),
|
|
2040
2137
|
...params !== void 0 ? { params } : {}
|
|
@@ -2046,6 +2143,7 @@ function makeHandle(handleArgs) {
|
|
|
2046
2143
|
return result;
|
|
2047
2144
|
},
|
|
2048
2145
|
getDocument: async (id, opts) => {
|
|
2146
|
+
admitToLake(lakeRequest("GET", "doc", id));
|
|
2049
2147
|
const effective = opts?.perspective ?? perspective;
|
|
2050
2148
|
if (effective === "raw") {
|
|
2051
2149
|
const doc = store.get(id);
|
|
@@ -2055,6 +2153,7 @@ function makeHandle(handleArgs) {
|
|
|
2055
2153
|
return resolveDocument(view, id, effective) ?? void 0;
|
|
2056
2154
|
},
|
|
2057
2155
|
getDocuments: async (ids, opts) => {
|
|
2156
|
+
admitToLake(lakeRequest("GET", "doc", ids.join(",")));
|
|
2058
2157
|
const effective = opts?.perspective ?? perspective;
|
|
2059
2158
|
if (effective === "raw") {
|
|
2060
2159
|
const result = [];
|
|
@@ -2168,10 +2267,16 @@ function makeHandle(handleArgs) {
|
|
|
2168
2267
|
};
|
|
2169
2268
|
},
|
|
2170
2269
|
edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
|
|
2171
|
-
|
|
2270
|
+
// `@sanity/client` reads a release by id and its documents by query.
|
|
2271
|
+
get: async ({ releaseId }) => {
|
|
2272
|
+
admitToLake(lakeRequest("GET", "doc", `_.releases.${releaseId}`));
|
|
2273
|
+
const doc = store.get(`_.releases.${releaseId}`);
|
|
2274
|
+
return doc !== void 0 && await canRead(doc) ? doc : void 0;
|
|
2275
|
+
},
|
|
2172
2276
|
fetchDocuments: async ({ releaseId }) => {
|
|
2277
|
+
admitToLake(lakeRequest("GET", "query"));
|
|
2173
2278
|
const prefix = `versions.${releaseId}.`;
|
|
2174
|
-
return
|
|
2279
|
+
return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
|
|
2175
2280
|
},
|
|
2176
2281
|
schedule: ({ releaseId, publishAt }) => runAction({
|
|
2177
2282
|
actionType: "sanity.action.release.schedule",
|
|
@@ -2219,11 +2324,13 @@ function makeHandle(handleArgs) {
|
|
|
2219
2324
|
platform: {
|
|
2220
2325
|
projectId,
|
|
2221
2326
|
organizationId: backend.organizationId,
|
|
2327
|
+
projectFeatures: backend.projectFeatures,
|
|
2222
2328
|
own: (asked) => registryKey(asked) === registryKey(target) ? {
|
|
2223
2329
|
grants: requireActiveAccess().grants,
|
|
2224
2330
|
documents: () => store.all(),
|
|
2225
2331
|
history,
|
|
2226
|
-
canRead
|
|
2332
|
+
canRead,
|
|
2333
|
+
admitToLake
|
|
2227
2334
|
} : void 0,
|
|
2228
2335
|
actorUser: () => {
|
|
2229
2336
|
const access = requireActiveAccess();
|