@sanity-labs/client-fake-for-test 0.17.2 → 0.17.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -1
- package/dist/index.cjs +60 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -1
- package/dist/index.d.ts +14 -1
- package/dist/index.js +60 -35
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -77,7 +77,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
77
77
|
| Transaction | `transaction()` chain → `.commit()` | Mutations: `.create`, `.createOrReplace`, `.createIfNotExists`, `.delete`, `.patch(id, recipe)`. Atomic — any throw rolls back the whole batch. Default result is a `MultipleMutationResult` (`{ transactionId, documentIds, results }`) |
|
|
78
78
|
| Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
|
|
79
79
|
| Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish. `createVersion({ baseId, publishedId, releaseId })` (or `version.create` with `baseId` + `versionId`) copies the base document, `_type` included, into the version and records it in `_system.base` (`{ id, rev }`); a missing base fails. With access control, `version.create` in either form needs `create` on the resulting version, or `update` on the version it replaces (as `createOrReplace` does), as the Content Lake does; the base is not access-checked. A failed revision precondition (`ifDraftRevisionId`, `ifPublishedRevisionId`, `ifBaseRevisionId`) carries `statusCode: 409`, as the Actions API answers |
|
|
80
|
-
| Config | `config()` | Returns `{ projectId
|
|
80
|
+
| Config | `config()` | Returns `{ projectId?, dataset, resource?, perspective, token?, useProjectHostname }`. `projectId` defaults to `"test"`, and is absent on a client created with `useProjectHostname: false` and no `projectId`, as `@sanity/client` leaves it unset there (its siblings too, until one names a project) |
|
|
81
81
|
| Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
|
|
82
82
|
| Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname? })` | Sibling handle into the same multi-resource registry; `resource` points it at a Media Library, Canvas, dashboard or dataset (see [Resource types](#resource-types-media-library-canvas-dashboard)); `token` binds a registered identity (see the token→identity registry below), `accessControl` rebinds it inline — the two are mutually exclusive; `useProjectHostname: false` mints a global-hosted sibling |
|
|
83
83
|
| Perspectives | `raw` / `published` / `drafts` / release stacks / a single release name or comma-joined stack (`"rA"`, `"drafts,rA"`), as `@sanity/client` sends them | Per-client default or per-`fetch` override; draft/version layering with `_originalId` projection |
|
|
@@ -144,6 +144,34 @@ const bob = alice.withConfig({ token: "t-bob" });
|
|
|
144
144
|
|
|
145
145
|
Register more identities after creation with `client.addIdentity(token, { user, grants })` — an upsert into the family-shared registry; already-bound siblings resolve lazily and pick the change up immediately. For a one-off identity without a registry, `withConfig({ accessControl })` still works (mutually exclusive with `token` in the same call).
|
|
146
146
|
|
|
147
|
+
#### Unknown tokens and revoked tokens
|
|
148
|
+
|
|
149
|
+
The fake tells apart two kinds of bad token:
|
|
150
|
+
|
|
151
|
+
- **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
|
+
- **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
|
+
|
|
154
|
+
The refusal is the platform's answer, probed on staging and production, raised as a `PlatformHttpError` shaped like `@sanity/client`'s `ClientError`:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
{
|
|
158
|
+
statusCode: 401,
|
|
159
|
+
message: "Unauthorized - Session not found",
|
|
160
|
+
details: undefined, // @sanity/client sets details only for `{ error: { … } }` bodies
|
|
161
|
+
responseBody: '{\n "error": "Unauthorized", …}', // the body, JSON.stringify(body, null, 2)
|
|
162
|
+
response: {
|
|
163
|
+
statusCode: 401,
|
|
164
|
+
statusMessage: "Unauthorized",
|
|
165
|
+
method: "GET", // or "POST" for mutations and actions
|
|
166
|
+
url: "/data/query/test", // the API path, without host or version
|
|
167
|
+
headers: {},
|
|
168
|
+
body: { error: "Unauthorized", errorCode: "SIO-401-ANF", message: "Session not found", statusCode: 401 },
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The platform checks the session before it routes, so the 401 comes before a resource's 404 for a route it does not mount.
|
|
174
|
+
|
|
147
175
|
#### Token grants: filters and paths
|
|
148
176
|
|
|
149
177
|
A grant is either a GROQ `filter`, as a project's ACL serves it, or a `path` glob, as a token carries it (an internal token's `{ s, p }` grant is `{ path: s, permissions: p }`). The Content Lake holds a grant as one or the other and evaluates a path grant as `_id in path("<path>")` (gradient `pkg/security/models.go`): the id's dot-separated elements compare literally, `*` matches one element and a trailing `**` one or more. The fake matches `{ path }` grants the same way. A `path()` call inside a GROQ query or a `{ filter }` grant still runs through groq-js, which matches `.` there as any character:
|
|
@@ -275,6 +303,7 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
|
|
|
275
303
|
| `client.stubs()` | The currently-registered stubs |
|
|
276
304
|
| `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
|
|
277
305
|
| `client.identities()` | Snapshot of the registered token→identity entries |
|
|
306
|
+
| `client.revokeIdentity(token)` | Make every later request on a registered token answer 401 `Session not found` (see [Unknown tokens and revoked tokens](#unknown-tokens-and-revoked-tokens)) |
|
|
278
307
|
| `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
|
|
279
308
|
| `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
|
|
280
309
|
|
package/dist/index.cjs
CHANGED
|
@@ -24,8 +24,12 @@ function clientErrorMessage(args) {
|
|
|
24
24
|
const { body } = args;
|
|
25
25
|
if (isRecord(body)) {
|
|
26
26
|
const { error, message } = body;
|
|
27
|
-
if (
|
|
28
|
-
if (typeof
|
|
27
|
+
if (typeof error == "string" && typeof message == "string") return `${error} - ${message}`;
|
|
28
|
+
if (typeof error == "string") return error;
|
|
29
|
+
if (isRecord(error)) {
|
|
30
|
+
if (typeof error.description == "string") return error.description;
|
|
31
|
+
} else if (typeof message == "string")
|
|
32
|
+
return message;
|
|
29
33
|
}
|
|
30
34
|
const details = typeof body == "string" ? ` (${body.length > 100 ? `${body.slice(0, 100)}\u2026` : body})` : "";
|
|
31
35
|
return `${args.method}-request to ${args.path} resulted in HTTP ${args.statusCode} ${args.statusMessage}${details}`;
|
|
@@ -46,7 +50,17 @@ function accessApiError(args) {
|
|
|
46
50
|
body: { statusCode, error: statusMessage, message }
|
|
47
51
|
});
|
|
48
52
|
}
|
|
49
|
-
const
|
|
53
|
+
const sessionNotFound = (request) => new PlatformHttpError({
|
|
54
|
+
...request,
|
|
55
|
+
statusCode: 401,
|
|
56
|
+
statusMessage: "Unauthorized",
|
|
57
|
+
body: {
|
|
58
|
+
error: "Unauthorized",
|
|
59
|
+
errorCode: "SIO-401-ANF",
|
|
60
|
+
message: "Session not found",
|
|
61
|
+
statusCode: 401
|
|
62
|
+
}
|
|
63
|
+
}), noPermission = (request) => accessApiError({
|
|
50
64
|
request,
|
|
51
65
|
statusCode: 403,
|
|
52
66
|
statusMessage: "Forbidden",
|
|
@@ -1836,6 +1850,7 @@ function createTestClient(options = {}) {
|
|
|
1836
1850
|
calls: [],
|
|
1837
1851
|
concurrentEdits: /* @__PURE__ */ new Map(),
|
|
1838
1852
|
identities: new Map(Object.entries(options.identities ?? {})),
|
|
1853
|
+
revoked: /* @__PURE__ */ new Set(),
|
|
1839
1854
|
writeChain: Promise.resolve()
|
|
1840
1855
|
}, registry = backend.registry;
|
|
1841
1856
|
if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
|
|
@@ -1860,7 +1875,8 @@ function createTestClient(options = {}) {
|
|
|
1860
1875
|
requestTagPrefix: options.requestTagPrefix,
|
|
1861
1876
|
mutationGuard: options.mutationGuard,
|
|
1862
1877
|
token: options.token,
|
|
1863
|
-
useProjectHostname: options.useProjectHostname ?? !0
|
|
1878
|
+
useProjectHostname: options.useProjectHostname ?? !0,
|
|
1879
|
+
hasProjectId: options.projectId !== void 0
|
|
1864
1880
|
});
|
|
1865
1881
|
}
|
|
1866
1882
|
function dedupeIds(results) {
|
|
@@ -1923,7 +1939,7 @@ function makeHandle(handleArgs) {
|
|
|
1923
1939
|
mutationGuard,
|
|
1924
1940
|
token,
|
|
1925
1941
|
useProjectHostname
|
|
1926
|
-
} = handleArgs, { registry } = backend, { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
1942
|
+
} = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
1927
1943
|
if (token === void 0) return accessControl;
|
|
1928
1944
|
const identity = backend.identities.get(token);
|
|
1929
1945
|
if (identity === void 0)
|
|
@@ -1940,7 +1956,10 @@ function makeHandle(handleArgs) {
|
|
|
1940
1956
|
if (access === void 0)
|
|
1941
1957
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1942
1958
|
return access;
|
|
1943
|
-
},
|
|
1959
|
+
}, refuseRevoked = (request) => {
|
|
1960
|
+
if (token !== void 0 && backend.revoked.has(token)) throw sessionNotFound(request);
|
|
1961
|
+
}, withSession = (request) => async (opts) => (refuseRevoked({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
|
|
1962
|
+
refuseRevoked(request);
|
|
1944
1963
|
const access = activeAccess();
|
|
1945
1964
|
if (access === void 0) return;
|
|
1946
1965
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -2126,7 +2145,7 @@ function makeHandle(handleArgs) {
|
|
|
2126
2145
|
method: "POST",
|
|
2127
2146
|
path: `${capabilities.dataBase(target.id)}/actions`
|
|
2128
2147
|
};
|
|
2129
|
-
if (capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2148
|
+
if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2130
2149
|
return write(async () => {
|
|
2131
2150
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2132
2151
|
const refused = capabilities.refusedActions[action.actionType];
|
|
@@ -2330,36 +2349,38 @@ function makeHandle(handleArgs) {
|
|
|
2330
2349
|
publishedId
|
|
2331
2350
|
}),
|
|
2332
2351
|
...token !== void 0 || accessControl !== void 0 ? {
|
|
2333
|
-
request:
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
listIdentities: members,
|
|
2340
|
-
platform: {
|
|
2341
|
-
projectId,
|
|
2352
|
+
request: withSession(
|
|
2353
|
+
makeRequestImpl({
|
|
2354
|
+
getAccess: requireActiveAccess,
|
|
2355
|
+
// `@sanity/client` sends every request of a `resource`-configured
|
|
2356
|
+
// client to the global API host.
|
|
2357
|
+
useProjectHostname: useProjectHostname && resource === void 0,
|
|
2342
2358
|
organizationId: backend.organizationId,
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2359
|
+
listIdentities: members,
|
|
2360
|
+
platform: {
|
|
2361
|
+
projectId,
|
|
2362
|
+
organizationId: backend.organizationId,
|
|
2363
|
+
projectFeatures: backend.projectFeatures,
|
|
2364
|
+
own: (asked) => registryKey(asked) === registryKey(target) ? {
|
|
2365
|
+
grants: requireActiveAccess().grants,
|
|
2366
|
+
documents: () => store.all(),
|
|
2367
|
+
history,
|
|
2368
|
+
canRead,
|
|
2369
|
+
admitToLake
|
|
2370
|
+
} : void 0,
|
|
2371
|
+
actorUser: () => {
|
|
2372
|
+
const access = requireActiveAccess();
|
|
2373
|
+
return access.globalUser ?? access.currentUser;
|
|
2374
|
+
},
|
|
2375
|
+
actorAccess: () => requireActiveAccess().access,
|
|
2376
|
+
identities: members,
|
|
2377
|
+
resources: () => [...registry.values()].map((entry) => entry.resource)
|
|
2378
|
+
}
|
|
2379
|
+
})
|
|
2380
|
+
)
|
|
2360
2381
|
} : {},
|
|
2361
2382
|
config: () => ({
|
|
2362
|
-
projectId,
|
|
2383
|
+
...hasProjectId || resource !== void 0 ? { projectId } : {},
|
|
2363
2384
|
dataset,
|
|
2364
2385
|
...resource !== void 0 ? { resource } : {},
|
|
2365
2386
|
perspective,
|
|
@@ -2380,7 +2401,8 @@ function makeHandle(handleArgs) {
|
|
|
2380
2401
|
requestTagPrefix: config.requestTagPrefix ?? requestTagPrefix,
|
|
2381
2402
|
mutationGuard,
|
|
2382
2403
|
token: rebinds ? config.token : token,
|
|
2383
|
-
useProjectHostname: config.useProjectHostname ?? useProjectHostname
|
|
2404
|
+
useProjectHostname: config.useProjectHostname ?? useProjectHostname,
|
|
2405
|
+
hasProjectId: hasProjectId || config.projectId !== void 0
|
|
2384
2406
|
});
|
|
2385
2407
|
},
|
|
2386
2408
|
seed: (documents) => store.seed(documents),
|
|
@@ -2402,6 +2424,9 @@ function makeHandle(handleArgs) {
|
|
|
2402
2424
|
backend.identities.set(identityToken, identity);
|
|
2403
2425
|
},
|
|
2404
2426
|
identities: () => Object.fromEntries(backend.identities),
|
|
2427
|
+
revokeIdentity: (revokedToken) => {
|
|
2428
|
+
requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
|
|
2429
|
+
},
|
|
2405
2430
|
mutations: () => backend.log.flatMap((entry) => entry.mutations),
|
|
2406
2431
|
transactions: () => [...backend.log],
|
|
2407
2432
|
clearLog: () => {
|