@sanity-labs/client-fake-for-test 0.16.0 → 0.17.1
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 +37 -2
- package/dist/index.cjs +196 -88
- 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 +196 -88
- 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
|
}
|
|
@@ -1291,7 +1381,7 @@ async function applyAction(store, action, hooks) {
|
|
|
1291
1381
|
return store.remove(release._id), { transactionId: cryptoRandomKey() };
|
|
1292
1382
|
}
|
|
1293
1383
|
case "sanity.action.document.version.create": {
|
|
1294
|
-
if ("baseId" in action) return createVersionFromBase(store, action);
|
|
1384
|
+
if ("baseId" in action) return createVersionFromBase(store, action, hooks);
|
|
1295
1385
|
const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
|
|
1296
1386
|
if (releaseId === void 0)
|
|
1297
1387
|
throw fakeError(
|
|
@@ -1303,7 +1393,7 @@ async function applyAction(store, action, hooks) {
|
|
|
1303
1393
|
...action.document,
|
|
1304
1394
|
_id: vid
|
|
1305
1395
|
}, existing = store.get(vid), promoted = promote(doc);
|
|
1306
|
-
return existing !== void 0 && (promoted._createdAt = existing._createdAt), store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1396
|
+
return existing !== void 0 && (promoted._createdAt = existing._createdAt), await hooks?.gate?.(existing ?? promoted, existing === void 0 ? "create" : "update"), store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1307
1397
|
}
|
|
1308
1398
|
case "sanity.action.document.version.replace": {
|
|
1309
1399
|
const id = action.document._id;
|
|
@@ -1363,7 +1453,7 @@ function requireDraftOf(action) {
|
|
|
1363
1453
|
`${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
|
|
1364
1454
|
);
|
|
1365
1455
|
}
|
|
1366
|
-
function createVersionFromBase(store, action) {
|
|
1456
|
+
async function createVersionFromBase(store, action, hooks) {
|
|
1367
1457
|
const { releaseId, publishedId } = parseVersionId(action.versionId);
|
|
1368
1458
|
if (publishedId !== action.publishedId)
|
|
1369
1459
|
throw fakeError(
|
|
@@ -1376,12 +1466,13 @@ function createVersionFromBase(store, action) {
|
|
|
1376
1466
|
`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.`
|
|
1377
1467
|
);
|
|
1378
1468
|
requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
|
|
1379
|
-
const existing = store.get(action.versionId),
|
|
1469
|
+
const existing = store.get(action.versionId), copy = {
|
|
1380
1470
|
...base,
|
|
1381
1471
|
_id: action.versionId,
|
|
1382
|
-
_createdAt: existing?._createdAt ?? nowIso()
|
|
1383
|
-
|
|
1384
|
-
|
|
1472
|
+
_createdAt: existing?._createdAt ?? nowIso(),
|
|
1473
|
+
_system: { base: { id: base._id, rev: base._rev } }
|
|
1474
|
+
}, promoted = promote(copy);
|
|
1475
|
+
return await hooks?.gate?.(existing ?? promoted, existing === void 0 ? "create" : "update"), store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1385
1476
|
}
|
|
1386
1477
|
function requireRevisionMatch(documentId, actualRev, expectedRev) {
|
|
1387
1478
|
if (!(expectedRev === void 0 || actualRev === expectedRev))
|
|
@@ -1543,7 +1634,7 @@ const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues",
|
|
|
1543
1634
|
},
|
|
1544
1635
|
request: {
|
|
1545
1636
|
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."
|
|
1637
|
+
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
1638
|
},
|
|
1548
1639
|
dryRun: {
|
|
1549
1640
|
what: "not a method \u2014 did you mean the `{ dryRun }` mutation option?",
|
|
@@ -1727,6 +1818,7 @@ function createTestClient(options = {}) {
|
|
|
1727
1818
|
const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
|
|
1728
1819
|
registry: /* @__PURE__ */ new Map(),
|
|
1729
1820
|
organizationId: options.organizationId,
|
|
1821
|
+
projectFeatures: options.projectFeatures ?? {},
|
|
1730
1822
|
log: [],
|
|
1731
1823
|
stubs: /* @__PURE__ */ new Map(),
|
|
1732
1824
|
calls: [],
|
|
@@ -1836,7 +1928,12 @@ function makeHandle(handleArgs) {
|
|
|
1836
1928
|
if (access === void 0)
|
|
1837
1929
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1838
1930
|
return access;
|
|
1839
|
-
},
|
|
1931
|
+
}, admitToLake = (request) => {
|
|
1932
|
+
const access = activeAccess();
|
|
1933
|
+
if (access === void 0) return;
|
|
1934
|
+
const refusal = refusedToken(request, access.grants);
|
|
1935
|
+
if (refusal !== void 0) throw refusal;
|
|
1936
|
+
}, lakeRequest = (method, operation, path) => ({ method, path: dataUrl({ resource, dataset, operation, path }) }), members = () => [
|
|
1840
1937
|
...backend.identities.values(),
|
|
1841
1938
|
...token === void 0 && accessControl !== void 0 ? [
|
|
1842
1939
|
{
|
|
@@ -1852,8 +1949,8 @@ function makeHandle(handleArgs) {
|
|
|
1852
1949
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
1853
1950
|
};
|
|
1854
1951
|
let beforeWrite;
|
|
1855
|
-
const write = (run) => serializeWrite(backend, async () => {
|
|
1856
|
-
beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
1952
|
+
const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
|
|
1953
|
+
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
|
|
1857
1954
|
try {
|
|
1858
1955
|
return await run();
|
|
1859
1956
|
} finally {
|
|
@@ -2015,14 +2112,14 @@ function makeHandle(handleArgs) {
|
|
|
2015
2112
|
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2016
2113
|
};
|
|
2017
2114
|
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
2115
|
return write(async () => {
|
|
2116
|
+
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2117
|
+
const refused = capabilities.refusedActions[action.actionType];
|
|
2118
|
+
if (refused !== void 0) throw refused(request);
|
|
2119
|
+
}
|
|
2023
2120
|
const result = await applyActions(store, actions, { gate, guard: guardGate });
|
|
2024
2121
|
return commitHistory(result.transactionId), result;
|
|
2025
|
-
});
|
|
2122
|
+
}, request);
|
|
2026
2123
|
}, accessVisibleDocs = async () => {
|
|
2027
2124
|
const all = store.all();
|
|
2028
2125
|
if (activeAccess() === void 0) return all;
|
|
@@ -2035,6 +2132,7 @@ function makeHandle(handleArgs) {
|
|
|
2035
2132
|
return applyPerspective(accessible, override ?? perspective);
|
|
2036
2133
|
}, client = {
|
|
2037
2134
|
fetch: async (query, params, opts) => {
|
|
2135
|
+
admitToLake(lakeRequest("GET", "query"));
|
|
2038
2136
|
const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
|
|
2039
2137
|
dataset: await visibleDocs(opts?.perspective),
|
|
2040
2138
|
...params !== void 0 ? { params } : {}
|
|
@@ -2046,6 +2144,7 @@ function makeHandle(handleArgs) {
|
|
|
2046
2144
|
return result;
|
|
2047
2145
|
},
|
|
2048
2146
|
getDocument: async (id, opts) => {
|
|
2147
|
+
admitToLake(lakeRequest("GET", "doc", id));
|
|
2049
2148
|
const effective = opts?.perspective ?? perspective;
|
|
2050
2149
|
if (effective === "raw") {
|
|
2051
2150
|
const doc = store.get(id);
|
|
@@ -2055,6 +2154,7 @@ function makeHandle(handleArgs) {
|
|
|
2055
2154
|
return resolveDocument(view, id, effective) ?? void 0;
|
|
2056
2155
|
},
|
|
2057
2156
|
getDocuments: async (ids, opts) => {
|
|
2157
|
+
admitToLake(lakeRequest("GET", "doc", ids.join(",")));
|
|
2058
2158
|
const effective = opts?.perspective ?? perspective;
|
|
2059
2159
|
if (effective === "raw") {
|
|
2060
2160
|
const result = [];
|
|
@@ -2168,10 +2268,16 @@ function makeHandle(handleArgs) {
|
|
|
2168
2268
|
};
|
|
2169
2269
|
},
|
|
2170
2270
|
edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
|
|
2171
|
-
|
|
2271
|
+
// `@sanity/client` reads a release by id and its documents by query.
|
|
2272
|
+
get: async ({ releaseId }) => {
|
|
2273
|
+
admitToLake(lakeRequest("GET", "doc", `_.releases.${releaseId}`));
|
|
2274
|
+
const doc = store.get(`_.releases.${releaseId}`);
|
|
2275
|
+
return doc !== void 0 && await canRead(doc) ? doc : void 0;
|
|
2276
|
+
},
|
|
2172
2277
|
fetchDocuments: async ({ releaseId }) => {
|
|
2278
|
+
admitToLake(lakeRequest("GET", "query"));
|
|
2173
2279
|
const prefix = `versions.${releaseId}.`;
|
|
2174
|
-
return
|
|
2280
|
+
return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
|
|
2175
2281
|
},
|
|
2176
2282
|
schedule: ({ releaseId, publishAt }) => runAction({
|
|
2177
2283
|
actionType: "sanity.action.release.schedule",
|
|
@@ -2219,11 +2325,13 @@ function makeHandle(handleArgs) {
|
|
|
2219
2325
|
platform: {
|
|
2220
2326
|
projectId,
|
|
2221
2327
|
organizationId: backend.organizationId,
|
|
2328
|
+
projectFeatures: backend.projectFeatures,
|
|
2222
2329
|
own: (asked) => registryKey(asked) === registryKey(target) ? {
|
|
2223
2330
|
grants: requireActiveAccess().grants,
|
|
2224
2331
|
documents: () => store.all(),
|
|
2225
2332
|
history,
|
|
2226
|
-
canRead
|
|
2333
|
+
canRead,
|
|
2334
|
+
admitToLake
|
|
2227
2335
|
} : void 0,
|
|
2228
2336
|
actorUser: () => {
|
|
2229
2337
|
const access = requireActiveAccess();
|