@sanity-labs/client-fake-for-test 0.20.0 → 0.21.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 +5 -3
- package/dist/index.cjs +180 -40
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +40 -4
- package/dist/index.d.ts +40 -4
- package/dist/index.js +180 -40
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -209,6 +209,22 @@ export declare interface CreateTestClientOptions {
|
|
|
209
209
|
* mints siblings on the other host.
|
|
210
210
|
*/
|
|
211
211
|
useProjectHostname?: boolean;
|
|
212
|
+
/**
|
|
213
|
+
* The API host, as the real `createClient` config names it (default
|
|
214
|
+
* `https://api.sanity.io`). With {@link apiVersion}, `useCdn` and the
|
|
215
|
+
* host flag it decides the URL a platform error carries as
|
|
216
|
+
* `response.url`: the URL `@sanity/client` would have requested, e.g.
|
|
217
|
+
* `https://p1.api.sanity.io/v2025-02-19/data/doc/production/x?tag=t`.
|
|
218
|
+
*/
|
|
219
|
+
apiHost?: string;
|
|
220
|
+
/** The API version (default `"1"`, as in `@sanity/client`): `"YYYY-MM-DD"`, `"X"` or `"1"`, `v` prefix optional. */
|
|
221
|
+
apiVersion?: string;
|
|
222
|
+
/**
|
|
223
|
+
* Whether GET reads of the data API (queries, documents, history) go to
|
|
224
|
+
* the API CDN, as in `@sanity/client` (default `true`). Only the URL a
|
|
225
|
+
* platform error names depends on it; the fake serves the same data.
|
|
226
|
+
*/
|
|
227
|
+
useCdn?: boolean;
|
|
212
228
|
}
|
|
213
229
|
|
|
214
230
|
/**
|
|
@@ -726,16 +742,24 @@ export declare class PlatformHttpError extends ClientError {
|
|
|
726
742
|
constructor(args: PlatformResponseArgs);
|
|
727
743
|
}
|
|
728
744
|
|
|
729
|
-
/** A request the platform answers.
|
|
745
|
+
/** A request the platform answers. */
|
|
730
746
|
declare interface PlatformRequest {
|
|
731
747
|
method: "GET" | "POST";
|
|
748
|
+
/** The API path the platform routes on, without host, API version or query string. */
|
|
732
749
|
path: string;
|
|
750
|
+
/**
|
|
751
|
+
* The full URL `@sanity/client` requests, host, `/v<apiVersion>` and query
|
|
752
|
+
* string included, which its errors carry as `response.url` (see
|
|
753
|
+
* `./request-url.ts`).
|
|
754
|
+
*/
|
|
755
|
+
url: string;
|
|
733
756
|
}
|
|
734
757
|
|
|
735
758
|
/** What the platform answered, and to which request. */
|
|
736
759
|
declare interface PlatformResponseArgs {
|
|
737
760
|
method: string;
|
|
738
|
-
|
|
761
|
+
/** The URL `@sanity/client` requested; see {@link PlatformRequest.url}. */
|
|
762
|
+
url: string;
|
|
739
763
|
statusCode: number;
|
|
740
764
|
statusMessage: string;
|
|
741
765
|
body: unknown;
|
|
@@ -1087,6 +1111,12 @@ export declare interface TestClient {
|
|
|
1087
1111
|
requestTagPrefix?: string;
|
|
1088
1112
|
token?: string;
|
|
1089
1113
|
useProjectHostname: boolean;
|
|
1114
|
+
/** The API host, `https://api.sanity.io` unless configured. */
|
|
1115
|
+
apiHost: string;
|
|
1116
|
+
/** The API version, without a leading `v`; `"1"` unless configured, as in `@sanity/client`. */
|
|
1117
|
+
apiVersion: string;
|
|
1118
|
+
/** Whether GET reads of the data API go to the API CDN; `true` unless configured `false`. */
|
|
1119
|
+
useCdn: boolean;
|
|
1090
1120
|
};
|
|
1091
1121
|
/**
|
|
1092
1122
|
* Return a new client handle pointing at a different `(projectId, dataset)`
|
|
@@ -1106,8 +1136,8 @@ export declare interface TestClient {
|
|
|
1106
1136
|
*/
|
|
1107
1137
|
resource: TestClientResource | undefined;
|
|
1108
1138
|
perspective: Perspective;
|
|
1109
|
-
/** Prefix composed with request tags and used alone for untagged requests. */
|
|
1110
|
-
requestTagPrefix: string;
|
|
1139
|
+
/** Prefix composed with request tags and used alone for untagged requests; `undefined` unsets it. */
|
|
1140
|
+
requestTagPrefix: string | undefined;
|
|
1111
1141
|
/**
|
|
1112
1142
|
* Model the global API host (`false`) instead of the project host
|
|
1113
1143
|
* (default `true`). A global-hosted sibling's `/users/me` serves the
|
|
@@ -1116,6 +1146,12 @@ export declare interface TestClient {
|
|
|
1116
1146
|
* config routes requests to `api.sanity.io`.
|
|
1117
1147
|
*/
|
|
1118
1148
|
useProjectHostname: boolean;
|
|
1149
|
+
/** See {@link CreateTestClientOptions.apiHost}. */
|
|
1150
|
+
apiHost: string;
|
|
1151
|
+
/** See {@link CreateTestClientOptions.apiVersion}. */
|
|
1152
|
+
apiVersion: string;
|
|
1153
|
+
/** See {@link CreateTestClientOptions.useCdn}. */
|
|
1154
|
+
useCdn: boolean;
|
|
1119
1155
|
/**
|
|
1120
1156
|
* Rebind the acting identity (and its grants) on a sibling that shares
|
|
1121
1157
|
* the same store — the test analogue of a token-scoped client. Lets two
|
package/dist/index.d.ts
CHANGED
|
@@ -209,6 +209,22 @@ export declare interface CreateTestClientOptions {
|
|
|
209
209
|
* mints siblings on the other host.
|
|
210
210
|
*/
|
|
211
211
|
useProjectHostname?: boolean;
|
|
212
|
+
/**
|
|
213
|
+
* The API host, as the real `createClient` config names it (default
|
|
214
|
+
* `https://api.sanity.io`). With {@link apiVersion}, `useCdn` and the
|
|
215
|
+
* host flag it decides the URL a platform error carries as
|
|
216
|
+
* `response.url`: the URL `@sanity/client` would have requested, e.g.
|
|
217
|
+
* `https://p1.api.sanity.io/v2025-02-19/data/doc/production/x?tag=t`.
|
|
218
|
+
*/
|
|
219
|
+
apiHost?: string;
|
|
220
|
+
/** The API version (default `"1"`, as in `@sanity/client`): `"YYYY-MM-DD"`, `"X"` or `"1"`, `v` prefix optional. */
|
|
221
|
+
apiVersion?: string;
|
|
222
|
+
/**
|
|
223
|
+
* Whether GET reads of the data API (queries, documents, history) go to
|
|
224
|
+
* the API CDN, as in `@sanity/client` (default `true`). Only the URL a
|
|
225
|
+
* platform error names depends on it; the fake serves the same data.
|
|
226
|
+
*/
|
|
227
|
+
useCdn?: boolean;
|
|
212
228
|
}
|
|
213
229
|
|
|
214
230
|
/**
|
|
@@ -726,16 +742,24 @@ export declare class PlatformHttpError extends ClientError {
|
|
|
726
742
|
constructor(args: PlatformResponseArgs);
|
|
727
743
|
}
|
|
728
744
|
|
|
729
|
-
/** A request the platform answers.
|
|
745
|
+
/** A request the platform answers. */
|
|
730
746
|
declare interface PlatformRequest {
|
|
731
747
|
method: "GET" | "POST";
|
|
748
|
+
/** The API path the platform routes on, without host, API version or query string. */
|
|
732
749
|
path: string;
|
|
750
|
+
/**
|
|
751
|
+
* The full URL `@sanity/client` requests, host, `/v<apiVersion>` and query
|
|
752
|
+
* string included, which its errors carry as `response.url` (see
|
|
753
|
+
* `./request-url.ts`).
|
|
754
|
+
*/
|
|
755
|
+
url: string;
|
|
733
756
|
}
|
|
734
757
|
|
|
735
758
|
/** What the platform answered, and to which request. */
|
|
736
759
|
declare interface PlatformResponseArgs {
|
|
737
760
|
method: string;
|
|
738
|
-
|
|
761
|
+
/** The URL `@sanity/client` requested; see {@link PlatformRequest.url}. */
|
|
762
|
+
url: string;
|
|
739
763
|
statusCode: number;
|
|
740
764
|
statusMessage: string;
|
|
741
765
|
body: unknown;
|
|
@@ -1087,6 +1111,12 @@ export declare interface TestClient {
|
|
|
1087
1111
|
requestTagPrefix?: string;
|
|
1088
1112
|
token?: string;
|
|
1089
1113
|
useProjectHostname: boolean;
|
|
1114
|
+
/** The API host, `https://api.sanity.io` unless configured. */
|
|
1115
|
+
apiHost: string;
|
|
1116
|
+
/** The API version, without a leading `v`; `"1"` unless configured, as in `@sanity/client`. */
|
|
1117
|
+
apiVersion: string;
|
|
1118
|
+
/** Whether GET reads of the data API go to the API CDN; `true` unless configured `false`. */
|
|
1119
|
+
useCdn: boolean;
|
|
1090
1120
|
};
|
|
1091
1121
|
/**
|
|
1092
1122
|
* Return a new client handle pointing at a different `(projectId, dataset)`
|
|
@@ -1106,8 +1136,8 @@ export declare interface TestClient {
|
|
|
1106
1136
|
*/
|
|
1107
1137
|
resource: TestClientResource | undefined;
|
|
1108
1138
|
perspective: Perspective;
|
|
1109
|
-
/** Prefix composed with request tags and used alone for untagged requests. */
|
|
1110
|
-
requestTagPrefix: string;
|
|
1139
|
+
/** Prefix composed with request tags and used alone for untagged requests; `undefined` unsets it. */
|
|
1140
|
+
requestTagPrefix: string | undefined;
|
|
1111
1141
|
/**
|
|
1112
1142
|
* Model the global API host (`false`) instead of the project host
|
|
1113
1143
|
* (default `true`). A global-hosted sibling's `/users/me` serves the
|
|
@@ -1116,6 +1146,12 @@ export declare interface TestClient {
|
|
|
1116
1146
|
* config routes requests to `api.sanity.io`.
|
|
1117
1147
|
*/
|
|
1118
1148
|
useProjectHostname: boolean;
|
|
1149
|
+
/** See {@link CreateTestClientOptions.apiHost}. */
|
|
1150
|
+
apiHost: string;
|
|
1151
|
+
/** See {@link CreateTestClientOptions.apiVersion}. */
|
|
1152
|
+
apiVersion: string;
|
|
1153
|
+
/** See {@link CreateTestClientOptions.useCdn}. */
|
|
1154
|
+
useCdn: boolean;
|
|
1119
1155
|
/**
|
|
1120
1156
|
* Rebind the acting identity (and its grants) on a sibling that shares
|
|
1121
1157
|
* the same store — the test analogue of a token-scoped client. Lets two
|
package/dist/index.js
CHANGED
|
@@ -10,10 +10,10 @@ class PlatformHttpError extends ClientError {
|
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
12
|
function platformResponse(args) {
|
|
13
|
-
const { method,
|
|
13
|
+
const { method, url, statusCode, statusMessage, body } = args;
|
|
14
14
|
return {
|
|
15
15
|
body,
|
|
16
|
-
url
|
|
16
|
+
url,
|
|
17
17
|
method,
|
|
18
18
|
headers: { "content-type": `${typeof body == "string" ? "text/html" : "application/json"}; charset=utf-8` },
|
|
19
19
|
statusCode,
|
|
@@ -34,9 +34,13 @@ function transactionRefused(request, cause) {
|
|
|
34
34
|
}
|
|
35
35
|
});
|
|
36
36
|
}
|
|
37
|
-
const DEFAULT_WRITE = {
|
|
37
|
+
const DEFAULT_WRITE = {
|
|
38
|
+
method: "POST",
|
|
39
|
+
path: "/data/mutate",
|
|
40
|
+
url: "/data/mutate"
|
|
41
|
+
}, notMounted = ({ method, path, url }) => new PlatformHttpError({
|
|
38
42
|
method,
|
|
39
|
-
|
|
43
|
+
url,
|
|
40
44
|
statusCode: 404,
|
|
41
45
|
statusMessage: "Not Found",
|
|
42
46
|
body: `Cannot ${method} ${path}`
|
|
@@ -102,9 +106,9 @@ function notFound(name) {
|
|
|
102
106
|
message: `${name} not found`
|
|
103
107
|
});
|
|
104
108
|
}
|
|
105
|
-
const releaseLimitExceeded = ({ method,
|
|
109
|
+
const releaseLimitExceeded = ({ method, url }) => new PlatformHttpError({
|
|
106
110
|
method,
|
|
107
|
-
|
|
111
|
+
url,
|
|
108
112
|
statusCode: 403,
|
|
109
113
|
statusMessage: "Forbidden",
|
|
110
114
|
body: {
|
|
@@ -465,8 +469,8 @@ function usersPage(data) {
|
|
|
465
469
|
return { ...page(data), totalCount: data.length };
|
|
466
470
|
}
|
|
467
471
|
const UNMODELLED_PROFILE = { provider: "sanity", createdAt: (/* @__PURE__ */ new Date(0)).toISOString() };
|
|
468
|
-
async function servePlatformRequest(ctx,
|
|
469
|
-
const queryStart =
|
|
472
|
+
async function servePlatformRequest(ctx, uri, request) {
|
|
473
|
+
const { path } = request, queryStart = uri.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : uri.slice(queryStart + 1)), myAttributes = path.match(MY_ATTRIBUTES_PATH);
|
|
470
474
|
if (myAttributes !== null) {
|
|
471
475
|
const organizationId = decodeURIComponent(myAttributes[1]);
|
|
472
476
|
return serveMyAttributes({ ctx, request, organizationId, query });
|
|
@@ -506,10 +510,10 @@ async function servePlatformRequest(ctx, url) {
|
|
|
506
510
|
if (rest.startsWith("/history/"))
|
|
507
511
|
return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
|
|
508
512
|
}
|
|
509
|
-
function refuseAclRequest(ctx,
|
|
510
|
-
const
|
|
513
|
+
function refuseAclRequest(ctx, request) {
|
|
514
|
+
const matched = matchResourcePath(request.path);
|
|
511
515
|
if (matched?.rest !== "/acl") return;
|
|
512
|
-
const row = capabilitiesOf(matched.resource.type)
|
|
516
|
+
const row = capabilitiesOf(matched.resource.type);
|
|
513
517
|
serveCapability(
|
|
514
518
|
row.acl,
|
|
515
519
|
request,
|
|
@@ -879,13 +883,13 @@ function serveProject(args) {
|
|
|
879
883
|
};
|
|
880
884
|
}
|
|
881
885
|
function makeRequestImpl(ctx) {
|
|
882
|
-
const { getAccess, useProjectHostname, listIdentities, organizationId, platform } = ctx;
|
|
886
|
+
const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
|
|
883
887
|
return async (opts) => {
|
|
884
888
|
const accessControl = getAccess(), path = opts.uri ?? opts.url;
|
|
885
889
|
if (path === "/users/me")
|
|
886
890
|
return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
|
|
887
891
|
if (path !== void 0 && path === accessControl.aclPath)
|
|
888
|
-
return refuseAclRequest(platform,
|
|
892
|
+
return refuseAclRequest(platform, requestFor(opts)), accessControl.grants;
|
|
889
893
|
const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
|
|
890
894
|
if (pathProjectId !== void 0 && requestedIds !== void 0)
|
|
891
895
|
return serveProjectUsers({
|
|
@@ -900,7 +904,7 @@ function makeRequestImpl(ctx) {
|
|
|
900
904
|
identities: listIdentities(),
|
|
901
905
|
organizationId
|
|
902
906
|
});
|
|
903
|
-
const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
|
|
907
|
+
const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
|
|
904
908
|
if (served !== void 0) return served.value;
|
|
905
909
|
throw fakeError(
|
|
906
910
|
`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.`
|
|
@@ -1547,7 +1551,11 @@ async function createVersionFromBase(store, action, request) {
|
|
|
1547
1551
|
}, promoted = promote(copy);
|
|
1548
1552
|
return store.put(promoted), { transactionId: cryptoRandomKey() };
|
|
1549
1553
|
}
|
|
1550
|
-
const ACTIONS_REQUEST = {
|
|
1554
|
+
const ACTIONS_REQUEST = {
|
|
1555
|
+
method: "POST",
|
|
1556
|
+
path: "/data/actions",
|
|
1557
|
+
url: "/data/actions"
|
|
1558
|
+
};
|
|
1551
1559
|
function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
|
|
1552
1560
|
if (!(expectedRev === void 0 || actualRev === expectedRev))
|
|
1553
1561
|
throw actualRev === void 0 ? new PlatformHttpError({
|
|
@@ -1674,6 +1682,48 @@ function createTransaction(executor) {
|
|
|
1674
1682
|
};
|
|
1675
1683
|
return handle;
|
|
1676
1684
|
}
|
|
1685
|
+
const DEFAULT_API_HOST = "https://api.sanity.io", DEFAULT_API_VERSION = "1", DEFAULT_CDN_HOST = "apicdn.sanity.io", QUERY_SIZE_LIMIT = 11264;
|
|
1686
|
+
function normalizeTagPrefix(prefix) {
|
|
1687
|
+
return prefix?.replace(/\.+$/, "") || void 0;
|
|
1688
|
+
}
|
|
1689
|
+
function normalizeApiVersion(apiVersion) {
|
|
1690
|
+
const version = `${apiVersion}`.replace(/^v/, "");
|
|
1691
|
+
if (version === "1" || version === "X") return version;
|
|
1692
|
+
const date = new Date(version);
|
|
1693
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(version) || !(date.getTime() > 0))
|
|
1694
|
+
throw fakeError(
|
|
1695
|
+
`Invalid API version string, expected \`1\` or date in format \`YYYY-MM-DD\` (got ${JSON.stringify(apiVersion)}), the same rule @sanity/client applies to \`apiVersion\`.`
|
|
1696
|
+
);
|
|
1697
|
+
return version;
|
|
1698
|
+
}
|
|
1699
|
+
function apiBaseUrls(args) {
|
|
1700
|
+
const { apiHost, apiVersion, projectId } = args;
|
|
1701
|
+
if (projectId === void 0) {
|
|
1702
|
+
const url = `${apiHost}/v${apiVersion}`;
|
|
1703
|
+
return { url, cdnUrl: url };
|
|
1704
|
+
}
|
|
1705
|
+
const [protocol, host] = apiHost.split("://", 2), cdnHost = apiHost === DEFAULT_API_HOST ? DEFAULT_CDN_HOST : host;
|
|
1706
|
+
return {
|
|
1707
|
+
url: `${protocol}://${projectId}.${host}/v${apiVersion}`,
|
|
1708
|
+
cdnUrl: `${protocol}://${projectId}.${cdnHost}/v${apiVersion}`
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
function requestUrl(base, uri, query = []) {
|
|
1712
|
+
const url = `${base}/${uri.replace(/^\//, "")}`, params = new URLSearchParams();
|
|
1713
|
+
for (const [key, value] of query)
|
|
1714
|
+
value !== void 0 && params.append(key, `${value}`);
|
|
1715
|
+
const search = params.toString();
|
|
1716
|
+
if (search === "") return url;
|
|
1717
|
+
const fragmentStart = url.indexOf("#"), beforeFragment = fragmentStart === -1 ? url : url.slice(0, fragmentStart), fragment = fragmentStart === -1 ? "" : url.slice(fragmentStart);
|
|
1718
|
+
return `${beforeFragment}${beforeFragment.includes("?") ? "&" : "?"}${search}${fragment}`;
|
|
1719
|
+
}
|
|
1720
|
+
function encodeGroqQuery(query, params = {}) {
|
|
1721
|
+
const search = new URLSearchParams();
|
|
1722
|
+
search.append("query", query);
|
|
1723
|
+
for (const [key, value] of Object.entries(params))
|
|
1724
|
+
value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
|
|
1725
|
+
return `?${search}`;
|
|
1726
|
+
}
|
|
1677
1727
|
const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
|
|
1678
1728
|
"fetch",
|
|
1679
1729
|
"getDocument",
|
|
@@ -1957,11 +2007,15 @@ function createTestClient(options = {}) {
|
|
|
1957
2007
|
resource: options.resource,
|
|
1958
2008
|
accessControl: options.accessControl,
|
|
1959
2009
|
perspective: options.perspective ?? "raw",
|
|
1960
|
-
requestTagPrefix: options.requestTagPrefix,
|
|
2010
|
+
requestTagPrefix: normalizeTagPrefix(options.requestTagPrefix),
|
|
1961
2011
|
mutationGuard: options.mutationGuard,
|
|
1962
2012
|
token: options.token,
|
|
1963
2013
|
useProjectHostname: options.useProjectHostname ?? !0,
|
|
1964
|
-
hasProjectId: options.projectId !== void 0
|
|
2014
|
+
hasProjectId: options.projectId !== void 0,
|
|
2015
|
+
apiHost: options.apiHost ?? DEFAULT_API_HOST,
|
|
2016
|
+
apiVersion: normalizeApiVersion(options.apiVersion ?? DEFAULT_API_VERSION),
|
|
2017
|
+
useCdn: options.useCdn !== !1,
|
|
2018
|
+
configuredPerspective: options.perspective
|
|
1965
2019
|
});
|
|
1966
2020
|
}
|
|
1967
2021
|
function dedupeIds(results) {
|
|
@@ -2023,7 +2077,11 @@ function makeHandle(handleArgs) {
|
|
|
2023
2077
|
requestTagPrefix,
|
|
2024
2078
|
mutationGuard,
|
|
2025
2079
|
token,
|
|
2026
|
-
useProjectHostname
|
|
2080
|
+
useProjectHostname,
|
|
2081
|
+
apiHost,
|
|
2082
|
+
apiVersion,
|
|
2083
|
+
useCdn,
|
|
2084
|
+
configuredPerspective
|
|
2027
2085
|
} = 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 = () => {
|
|
2028
2086
|
if (token === void 0) return accessControl;
|
|
2029
2087
|
const identity = backend.identities.get(token);
|
|
@@ -2047,13 +2105,61 @@ function makeHandle(handleArgs) {
|
|
|
2047
2105
|
const tokenProjectId = backend.identities.get(token)?.projectId;
|
|
2048
2106
|
if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
|
|
2049
2107
|
throw sessionHostMismatch(request);
|
|
2050
|
-
}, withSession = (request) => async (opts) => (refuseSession(
|
|
2108
|
+
}, withSession = (request) => async (opts) => (refuseSession(rawRequest(opts)), request(opts)), admitToLake = (request) => {
|
|
2051
2109
|
refuseSession(request);
|
|
2052
2110
|
const access = activeAccess();
|
|
2053
2111
|
if (access === void 0) return;
|
|
2054
2112
|
const refusal = refusedToken(request, access.grants);
|
|
2055
2113
|
if (refusal !== void 0) throw refusal;
|
|
2056
|
-
},
|
|
2114
|
+
}, baseUrls = apiBaseUrls({
|
|
2115
|
+
apiHost,
|
|
2116
|
+
apiVersion,
|
|
2117
|
+
projectId: projectHosted ? projectId : void 0
|
|
2118
|
+
}), dataPath = (operation, path) => dataUrl({ resource, dataset, operation, path }), addresses = (uri, operation) => (hasProjectId || resource !== void 0) && uri.startsWith(dataPath(operation)), isDataUri = (uri) => uri.startsWith("/data/") || ["query", "mutate", "doc", "listen", "history"].some((operation) => addresses(uri, operation)), platformRequest = (args) => {
|
|
2119
|
+
const { method, uri, tag } = args, query = [...args.query ?? []];
|
|
2120
|
+
let cdn = useCdn && (args.canUseCdn ?? (method === "GET" && isDataUri(uri)));
|
|
2121
|
+
const effectiveTag = tag && requestTagPrefix ? `${requestTagPrefix}.${tag}` : tag || requestTagPrefix;
|
|
2122
|
+
if (effectiveTag && tag !== null && query.unshift(["tag", effectiveTag]), addresses(uri, "query")) {
|
|
2123
|
+
const perspectiveOption = args.perspective || configuredPerspective;
|
|
2124
|
+
if (perspectiveOption !== void 0) {
|
|
2125
|
+
const value = Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption;
|
|
2126
|
+
query.unshift(["perspective", value]), (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || perspectiveOption === "previewDrafts" || perspectiveOption === "drafts") && (cdn = !1);
|
|
2127
|
+
}
|
|
2128
|
+
args.returnQuery === !1 && query.unshift(["returnQuery", "false"]);
|
|
2129
|
+
}
|
|
2130
|
+
const queryStart = uri.indexOf("?");
|
|
2131
|
+
return {
|
|
2132
|
+
method,
|
|
2133
|
+
path: queryStart === -1 ? uri : uri.slice(0, queryStart),
|
|
2134
|
+
url: requestUrl(cdn ? baseUrls.cdnUrl : baseUrls.url, uri, query)
|
|
2135
|
+
};
|
|
2136
|
+
}, docRequest = (ids, tag) => platformRequest({ method: "GET", uri: dataPath("doc", ids), tag }), queryRequest = (args) => {
|
|
2137
|
+
const encoded = encodeGroqQuery(args.query, args.params), useGet = encoded.length < QUERY_SIZE_LIMIT;
|
|
2138
|
+
return platformRequest({
|
|
2139
|
+
method: useGet ? "GET" : "POST",
|
|
2140
|
+
uri: dataPath("query", useGet ? encoded : ""),
|
|
2141
|
+
tag: args.tag,
|
|
2142
|
+
canUseCdn: !0,
|
|
2143
|
+
perspective: args.perspective,
|
|
2144
|
+
returnQuery: args.returnQuery
|
|
2145
|
+
});
|
|
2146
|
+
}, mutateRequest = (options = {}) => {
|
|
2147
|
+
const { returnDocuments } = options;
|
|
2148
|
+
return platformRequest({
|
|
2149
|
+
method: "POST",
|
|
2150
|
+
uri: dataPath("mutate"),
|
|
2151
|
+
tag: options.tag,
|
|
2152
|
+
canUseCdn: !1,
|
|
2153
|
+
query: [
|
|
2154
|
+
["dryRun", options.dryRun],
|
|
2155
|
+
["returnIds", !0],
|
|
2156
|
+
["returnDocuments", returnDocuments === !1 ? void 0 : returnDocuments ?? !0],
|
|
2157
|
+
["visibility", options.visibility || "sync"],
|
|
2158
|
+
["autoGenerateArrayKeys", options.autoGenerateArrayKeys],
|
|
2159
|
+
["skipCrossDatasetReferenceValidation", options.skipCrossDatasetReferenceValidation]
|
|
2160
|
+
]
|
|
2161
|
+
});
|
|
2162
|
+
}, rawRequest = (opts) => platformRequest({ method: "GET", uri: opts.uri ?? opts.url ?? "", tag: opts.tag }), members = () => [
|
|
2057
2163
|
...backend.identities.values(),
|
|
2058
2164
|
...token === void 0 && accessControl !== void 0 ? [
|
|
2059
2165
|
{
|
|
@@ -2080,7 +2186,7 @@ function makeHandle(handleArgs) {
|
|
|
2080
2186
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
2081
2187
|
};
|
|
2082
2188
|
let beforeWrite, writeRequest = DEFAULT_WRITE;
|
|
2083
|
-
const write = (run, request
|
|
2189
|
+
const write = (run, request) => serializeWrite(backend, async () => {
|
|
2084
2190
|
admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
|
|
2085
2191
|
try {
|
|
2086
2192
|
return await run();
|
|
@@ -2242,8 +2348,13 @@ function makeHandle(handleArgs) {
|
|
|
2242
2348
|
txnOptions?.returnDocuments ?? !1,
|
|
2243
2349
|
txnOptions?.returnFirst ?? !1
|
|
2244
2350
|
);
|
|
2245
|
-
}, runAction = async (actions) => {
|
|
2246
|
-
const request =
|
|
2351
|
+
}, runAction = async (actions, tag) => {
|
|
2352
|
+
const request = platformRequest({
|
|
2353
|
+
method: "POST",
|
|
2354
|
+
uri: dataPath("actions"),
|
|
2355
|
+
tag,
|
|
2356
|
+
canUseCdn: !1
|
|
2357
|
+
});
|
|
2247
2358
|
if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2248
2359
|
return write(async () => {
|
|
2249
2360
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
@@ -2265,7 +2376,15 @@ function makeHandle(handleArgs) {
|
|
|
2265
2376
|
return applyPerspective(accessible, override ?? perspective);
|
|
2266
2377
|
}, client = {
|
|
2267
2378
|
fetch: async (query, params, opts) => {
|
|
2268
|
-
admitToLake(
|
|
2379
|
+
admitToLake(
|
|
2380
|
+
queryRequest({
|
|
2381
|
+
query,
|
|
2382
|
+
params,
|
|
2383
|
+
tag: opts?.tag,
|
|
2384
|
+
perspective: opts?.perspective,
|
|
2385
|
+
returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
|
|
2386
|
+
})
|
|
2387
|
+
);
|
|
2269
2388
|
const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
|
|
2270
2389
|
dataset: await visibleDocs(opts?.perspective),
|
|
2271
2390
|
...params !== void 0 ? { params } : {}
|
|
@@ -2277,7 +2396,7 @@ function makeHandle(handleArgs) {
|
|
|
2277
2396
|
return result;
|
|
2278
2397
|
},
|
|
2279
2398
|
getDocument: async (id, opts) => {
|
|
2280
|
-
admitToLake(
|
|
2399
|
+
admitToLake(docRequest(id, opts?.tag));
|
|
2281
2400
|
const effective = opts?.perspective ?? perspective;
|
|
2282
2401
|
if (effective === "raw") {
|
|
2283
2402
|
const doc = store.get(id);
|
|
@@ -2287,7 +2406,7 @@ function makeHandle(handleArgs) {
|
|
|
2287
2406
|
return resolveDocument(view, id, effective) ?? void 0;
|
|
2288
2407
|
},
|
|
2289
2408
|
getDocuments: async (ids, opts) => {
|
|
2290
|
-
admitToLake(
|
|
2409
|
+
admitToLake(docRequest(ids.join(","), opts?.tag));
|
|
2291
2410
|
const effective = opts?.perspective ?? perspective;
|
|
2292
2411
|
if (effective === "raw") {
|
|
2293
2412
|
const result = [];
|
|
@@ -2300,7 +2419,7 @@ function makeHandle(handleArgs) {
|
|
|
2300
2419
|
const view = await visibleDocs(effective);
|
|
2301
2420
|
return ids.map((id) => resolveDocument(view, id, effective) ?? null);
|
|
2302
2421
|
},
|
|
2303
|
-
getDataUrl:
|
|
2422
|
+
getDataUrl: dataPath,
|
|
2304
2423
|
create: (doc, opts) => write(async () => {
|
|
2305
2424
|
if (checkRevision(doc._id, opts?.ifRevisionId), store.get(doc._id) !== void 0)
|
|
2306
2425
|
throw fakeError(
|
|
@@ -2315,7 +2434,7 @@ function makeHandle(handleArgs) {
|
|
|
2315
2434
|
transactionId,
|
|
2316
2435
|
opts
|
|
2317
2436
|
);
|
|
2318
|
-
}),
|
|
2437
|
+
}, mutateRequest(opts)),
|
|
2319
2438
|
createOrReplace: (doc, opts) => write(async () => {
|
|
2320
2439
|
checkRevision(doc._id, opts?.ifRevisionId);
|
|
2321
2440
|
const promoted = promote2(doc), existing = store.get(doc._id);
|
|
@@ -2329,7 +2448,7 @@ function makeHandle(handleArgs) {
|
|
|
2329
2448
|
transactionId,
|
|
2330
2449
|
opts
|
|
2331
2450
|
);
|
|
2332
|
-
}),
|
|
2451
|
+
}, mutateRequest(opts)),
|
|
2333
2452
|
createIfNotExists: (doc, opts) => write(async () => {
|
|
2334
2453
|
checkRevision(doc._id, opts?.ifRevisionId);
|
|
2335
2454
|
const existing = store.get(doc._id), transactionId = opts?.transactionId ?? cryptoRandomKey();
|
|
@@ -2347,7 +2466,7 @@ function makeHandle(handleArgs) {
|
|
|
2347
2466
|
transactionId,
|
|
2348
2467
|
opts
|
|
2349
2468
|
);
|
|
2350
|
-
}),
|
|
2469
|
+
}, mutateRequest(opts)),
|
|
2351
2470
|
delete: (id, opts) => write(async () => {
|
|
2352
2471
|
checkRevision(id, opts?.ifRevisionId);
|
|
2353
2472
|
const existing = store.get(id);
|
|
@@ -2361,7 +2480,7 @@ function makeHandle(handleArgs) {
|
|
|
2361
2480
|
opts.returnDocuments ?? !0,
|
|
2362
2481
|
opts.returnFirst ?? !0
|
|
2363
2482
|
);
|
|
2364
|
-
}),
|
|
2483
|
+
}, mutateRequest(opts)),
|
|
2365
2484
|
patch: (documentId) => createPatch(documentId, {
|
|
2366
2485
|
apply: (docId, ops, ifRev, options) => write(async () => {
|
|
2367
2486
|
const doc = await applyPatch(docId, ops, ifRev);
|
|
@@ -2377,16 +2496,20 @@ function makeHandle(handleArgs) {
|
|
|
2377
2496
|
],
|
|
2378
2497
|
options?.tag
|
|
2379
2498
|
), doc;
|
|
2380
|
-
})
|
|
2499
|
+
}, mutateRequest(options))
|
|
2381
2500
|
}),
|
|
2382
2501
|
transaction: () => createTransaction({
|
|
2383
|
-
apply: (mutations, txnOptions) => write(
|
|
2502
|
+
apply: (mutations, txnOptions) => write(
|
|
2503
|
+
() => applyTransaction(mutations, txnOptions),
|
|
2504
|
+
// `Transaction.commit()` asks for ids unless told otherwise.
|
|
2505
|
+
mutateRequest({ ...txnOptions, returnDocuments: txnOptions?.returnDocuments ?? !1 })
|
|
2506
|
+
)
|
|
2384
2507
|
}),
|
|
2385
|
-
mutate: (operations, options) => write(() => applyTransaction(toTxnMutations(operations), options)),
|
|
2508
|
+
mutate: (operations, options) => write(() => applyTransaction(toTxnMutations(operations), options), mutateRequest(options)),
|
|
2386
2509
|
// Synchronous writes still take the lock: an action landing while a
|
|
2387
2510
|
// guarded patch is parked in its gate would otherwise be clobbered
|
|
2388
2511
|
// when that patch resumes over its pre-action snapshot.
|
|
2389
|
-
action: (action) => runAction(action),
|
|
2512
|
+
action: (action, options) => runAction(action, options?.tag),
|
|
2390
2513
|
releases: {
|
|
2391
2514
|
create: async ({ releaseId, metadata }) => {
|
|
2392
2515
|
const result = await runAction({
|
|
@@ -2403,12 +2526,20 @@ function makeHandle(handleArgs) {
|
|
|
2403
2526
|
edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
|
|
2404
2527
|
// `@sanity/client` reads a release by id and its documents by query.
|
|
2405
2528
|
get: async ({ releaseId }) => {
|
|
2406
|
-
admitToLake(
|
|
2529
|
+
admitToLake(docRequest(`_.releases.${releaseId}`, void 0));
|
|
2407
2530
|
const doc = store.get(`_.releases.${releaseId}`);
|
|
2408
2531
|
return doc !== void 0 && await canRead(doc) ? doc : void 0;
|
|
2409
2532
|
},
|
|
2410
2533
|
fetchDocuments: async ({ releaseId }) => {
|
|
2411
|
-
admitToLake(
|
|
2534
|
+
admitToLake(
|
|
2535
|
+
queryRequest({
|
|
2536
|
+
query: "*[sanity::partOfRelease($releaseId)]",
|
|
2537
|
+
params: { releaseId },
|
|
2538
|
+
tag: void 0,
|
|
2539
|
+
perspective: void 0,
|
|
2540
|
+
returnQuery: void 0
|
|
2541
|
+
})
|
|
2542
|
+
);
|
|
2412
2543
|
const prefix = `versions.${releaseId}.`;
|
|
2413
2544
|
return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
|
|
2414
2545
|
},
|
|
@@ -2451,6 +2582,7 @@ function makeHandle(handleArgs) {
|
|
|
2451
2582
|
request: withSession(
|
|
2452
2583
|
makeRequestImpl({
|
|
2453
2584
|
getAccess: requireActiveAccess,
|
|
2585
|
+
requestFor: rawRequest,
|
|
2454
2586
|
useProjectHostname: projectHosted,
|
|
2455
2587
|
organizationId: backend.organizationId,
|
|
2456
2588
|
listIdentities: members,
|
|
@@ -2486,7 +2618,10 @@ function makeHandle(handleArgs) {
|
|
|
2486
2618
|
perspective,
|
|
2487
2619
|
...requestTagPrefix !== void 0 ? { requestTagPrefix } : {},
|
|
2488
2620
|
...token !== void 0 ? { token } : {},
|
|
2489
|
-
useProjectHostname
|
|
2621
|
+
useProjectHostname,
|
|
2622
|
+
apiHost,
|
|
2623
|
+
apiVersion,
|
|
2624
|
+
useCdn
|
|
2490
2625
|
}),
|
|
2491
2626
|
withConfig: (config) => {
|
|
2492
2627
|
rejectAmbiguousIdentity("withConfig()", config), config.token !== void 0 && requireIdentity(backend, config.token, "withConfig()");
|
|
@@ -2498,11 +2633,16 @@ function makeHandle(handleArgs) {
|
|
|
2498
2633
|
resource: nextResource,
|
|
2499
2634
|
accessControl: rebinds ? config.accessControl : accessControl,
|
|
2500
2635
|
perspective: config.perspective ?? perspective,
|
|
2501
|
-
requestTagPrefix:
|
|
2636
|
+
// `requestTagPrefix: undefined` unsets the prefix, as in `@sanity/client`.
|
|
2637
|
+
requestTagPrefix: "requestTagPrefix" in config ? normalizeTagPrefix(config.requestTagPrefix) : requestTagPrefix,
|
|
2502
2638
|
mutationGuard,
|
|
2503
2639
|
token: rebinds ? config.token : token,
|
|
2504
2640
|
useProjectHostname: config.useProjectHostname ?? useProjectHostname,
|
|
2505
|
-
hasProjectId: hasProjectId || config.projectId !== void 0
|
|
2641
|
+
hasProjectId: hasProjectId || config.projectId !== void 0,
|
|
2642
|
+
apiHost: config.apiHost ?? apiHost,
|
|
2643
|
+
apiVersion: config.apiVersion !== void 0 ? normalizeApiVersion(config.apiVersion) : apiVersion,
|
|
2644
|
+
useCdn: config.useCdn ?? useCdn,
|
|
2645
|
+
configuredPerspective: config.perspective ?? configuredPerspective
|
|
2506
2646
|
});
|
|
2507
2647
|
},
|
|
2508
2648
|
seed: (documents) => publicStore.seed(documents),
|