@sanity-labs/client-fake-for-test 0.19.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 CHANGED
@@ -79,9 +79,9 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
79
79
  | 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 }`) |
80
80
  | Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
81
81
  | 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 |
82
- | 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) |
82
+ | Config | `config()` | Returns `{ projectId?, dataset, resource?, perspective, token?, useProjectHostname, apiHost, apiVersion, useCdn }`. `apiHost` (default `https://api.sanity.io`), `apiVersion` (default `"1"`, a leading `v` dropped) and `useCdn` (default `true`) are taken as `createTestClient` and `withConfig` options and only decide the URL an error names (see [Errors are `ClientError`s](#errors-are-clienterrors)). `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) |
83
83
  | Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
84
- | 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 |
84
+ | Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname?, apiHost?, apiVersion?, useCdn? })` | 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 |
85
85
  | 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 |
86
86
  | HTTP | `request({ url? \| uri? })` | Present **only** when the handle has an acting identity (`accessControl`, or a bound `token`). Serves `/users/me` (host-aware: project-scoped record on the project host, `globalUser` on a global-hosted or `resource` handle), the handle's ACL (`<data base>/acl`, or an explicit `aclPath`), `/projects/<projectId>` (the project's members: `{ id, isRobot?, roles? }` rows, one per distinct resolved project user, plus `organizationId` when configured), `/projects/<projectId>/users/<ids>` (project-user records with `id` + `sanityUserId`), `/projects/<projectId>/roles` (the project role catalog), `/projects/<projectId>/features` (the project's feature names, seeded with `projectFeatures`), the History API, resource lookup and the Access API (see [Resource types](#resource-types-media-library-canvas-dashboard)). Calling it without one throws a guidance error. |
87
87
 
@@ -165,7 +165,7 @@ The refusal is the platform's answer, probed on staging and production, raised a
165
165
  statusCode: 401,
166
166
  statusMessage: "Unauthorized",
167
167
  method: "GET", // or "POST" for mutations and actions
168
- url: "/data/query/test", // the API path, without host or version
168
+ url: "https://test.apicdn.sanity.io/v1/data/query/test?query=*&returnQuery=false", // the URL @sanity/client requests
169
169
  headers: { "content-type": "application/json; charset=utf-8" },
170
170
  body: { error: "Unauthorized", errorCode: "SIO-401-ANF", message: "Session not found", statusCode: 401 },
171
171
  },
@@ -293,7 +293,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
293
293
  | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
294
294
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
295
295
 
296
- - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id the registry does not hold (never seeded, written or addressed) answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
296
+ - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id that does not exist answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. A Media Library, Canvas or dashboard exists once it is seeded (`resources`, `documents`, or `seed()` / `add()` on its handle or its `store()`) or written to through the fake; pointing a client at it (`withConfig({ resource })`) does not create it, as on the platform. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
297
297
  - **Members.** Every member listing (`/projects/<projectId>`, `…/users`, `…/roles`) sees the registered identities plus, on a handle created with inline `accessControl`, that handle's own actor. Inline config belongs to its handle: a token sibling does not see it.
298
298
  - **Roles.** `…/roles` answers `{ data: [role], nextCursor: null }` and `…/roles/<roleName>` one role (404 `Role not found` for a name no member holds). A role is `{ name, title, description?, resourceType, resourceId, appliesToUsers, appliesToRobots, permissions }`, collected from the roles the members hold on the resource. The fake does not model role definitions, so `title` is the name where the seed gives none, both `appliesTo…` flags are `true` and `permissions` is `[]`. A media library serves its roles only to an actor whose `"media-library:<id>"` entry holds `sanity.media-library.roles.read` in `permissions`, else 403, as the reference requires. Likewise a project serves its roles only to an actor whose `"project:<id>"` entry holds `sanity.project.roles.read` (on staging every stock user role holds it), else 403.
299
299
  - **Project role catalog.** `GET /projects/<projectId>/roles` answers the older projects API's bare array, one row per role the project's members hold: `{ name, title, description?, projectId, appliesToUsers, appliesToRobots }`, with the same unmodelled defaults as the Access API rows. The platform also sends `isCustom` and a `grants` tree per role; the fake does not model role definitions, so it omits both. It needs `sanity.project.roles.read` on the actor's `"project:<projectId>"` entry, else 403 with the Access API's permission body.
@@ -302,7 +302,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
302
302
  - **History.** Every committed write since the client was created is recorded per resource, authored by the acting identity; seeded documents can be read at their seeded `_rev`. A handle answers for its own resource, and hides documents its grants cannot read, as reads do (a transaction that also touched such a document is served without it). Events model `createLiveDocument` / `updateLiveDocument` only.
303
303
  - **Org lookup.** `createTestClient({ organizationId })` names the organization every resource of the client belongs to.
304
304
  - **Project features.** `GET /projects/<projectId>/features` answers the project's feature names as a bare array, sorted and once each, as the project API does. Seed them with `createTestClient({ projectFeatures: { "<projectId>": ["advancedRolesManagement"] } })`; a project without an entry has no features and answers `[]`. Only a project member may read it, as on the platform: an identity without `projectId` reads every project's features, and a project-scoped one only its own project's, with 401 `User must be a member of this project to perform this operation` for any other (see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)).
305
- - **ACL refusals.** A Media Library's ACL needs `sanity.media-library.read` in the actor's `"media-library:<id>"` `permissions`, else 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be able to read media libraries for this organization to perform this operation" }`. A Media Library or Canvas id the registry does not hold (never seeded, written or addressed by a handle) answers 404 `{ statusCode: 404, error: "Not Found", message: "Media library not found" }` / `{ …, message: "Resource not found" }`. That is the platform's answer for an unknown resource on a route it mounts, distinct from the `Cannot GET …` text body of a route it does not mount (a dashboard's ACL). An explicit `accessControl.aclPath` naming one of these ACLs is refused the same way.
305
+ - **ACL refusals.** A Media Library's ACL needs `sanity.media-library.read` in the actor's `"media-library:<id>"` `permissions`, else 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be able to read media libraries for this organization to perform this operation" }`. A Media Library or Canvas that does not exist (never seeded or written to; a client pointed at it does not create it) answers 404 `{ statusCode: 404, error: "Not Found", message: "Media library not found" }` / `{ …, message: "Resource not found" }`. That is the platform's answer for an unknown resource on a route it mounts, distinct from the `Cannot GET …` text body of a route it does not mount (a dashboard's ACL). An explicit `accessControl.aclPath` naming one of these ACLs is refused the same way.
306
306
  - **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
307
307
 
308
308
  ### Errors are `ClientError`s
@@ -315,6 +315,8 @@ Every error the fake throws for an HTTP answer of the platform is an instance of
315
315
  | `WriteAccessDeniedError` | a write the grants do not permit (403) |
316
316
  | `GuardDeniedError` | a write a mutation guard denies (403) |
317
317
 
318
+ `response.url` is the URL `@sanity/client` would have requested, as its errors carry it: the project host (`https://<projectId>.api.sanity.io`, or `apicdn` for a GET of the data API with `useCdn` on) or the global host for a `resource` or `useProjectHostname: false` client, then `/v<apiVersion>`, the path, and the query string the client sends (the tag with its `requestTagPrefix`, a GROQ query and its params, the perspective, the mutation options). A JSON body keeps it out of `message`, as in `@sanity/client`; a text body's message names it. For example, `createTestClient({ projectId: "p1", dataset: "production", apiVersion: "2025-02-19", useCdn: false })` names `https://p1.api.sanity.io/v2025-02-19/data/doc/production/x?tag=t` for a refused `getDocument("x", { tag: "t" })`.
319
+
318
320
  The fake hands `ClientError` the response the platform sends, and `ClientError` derives `statusCode`, `message`, `responseBody` and `details` from it, exactly as for a real response. `instanceof` needs the fake and your code to share one `@sanity/client`, so it is a peer dependency (7.21 or later, or 8); with several copies installed, dedupe them. Mistakes in a test's setup (an unknown token, a document without `_id`, an unimplemented member) stay plain `Error`s prefixed `[client-fake-for-test]`, as do refusals whose platform answer the fake does not model yet (a mutation's existing id, missing target or `ifRevisionId` mismatch, an unknown id at `/projects/<projectId>/users/<id>`, which carries `statusCode: 404`).
319
321
 
320
322
  ### Test-only helpers (not on real `SanityClient`)
package/dist/index.cjs CHANGED
@@ -11,10 +11,10 @@ class PlatformHttpError extends client.ClientError {
11
11
  }
12
12
  }
13
13
  function platformResponse(args) {
14
- const { method, path, statusCode, statusMessage, body } = args;
14
+ const { method, url, statusCode, statusMessage, body } = args;
15
15
  return {
16
16
  body,
17
- url: path,
17
+ url,
18
18
  method,
19
19
  headers: { "content-type": `${typeof body == "string" ? "text/html" : "application/json"}; charset=utf-8` },
20
20
  statusCode,
@@ -35,9 +35,13 @@ function transactionRefused(request, cause) {
35
35
  }
36
36
  });
37
37
  }
38
- const DEFAULT_WRITE = { method: "POST", path: "/data/mutate" }, notMounted = ({ method, path }) => new PlatformHttpError({
38
+ const DEFAULT_WRITE = {
39
+ method: "POST",
40
+ path: "/data/mutate",
41
+ url: "/data/mutate"
42
+ }, notMounted = ({ method, path, url }) => new PlatformHttpError({
39
43
  method,
40
- path,
44
+ url,
41
45
  statusCode: 404,
42
46
  statusMessage: "Not Found",
43
47
  body: `Cannot ${method} ${path}`
@@ -103,9 +107,9 @@ function notFound(name) {
103
107
  message: `${name} not found`
104
108
  });
105
109
  }
106
- const releaseLimitExceeded = ({ method, path }) => new PlatformHttpError({
110
+ const releaseLimitExceeded = ({ method, url }) => new PlatformHttpError({
107
111
  method,
108
- path,
112
+ url,
109
113
  statusCode: 403,
110
114
  statusMessage: "Forbidden",
111
115
  body: {
@@ -466,8 +470,8 @@ function usersPage(data) {
466
470
  return { ...page(data), totalCount: data.length };
467
471
  }
468
472
  const UNMODELLED_PROFILE = { provider: "sanity", createdAt: (/* @__PURE__ */ new Date(0)).toISOString() };
469
- async function servePlatformRequest(ctx, url) {
470
- const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), query = new URLSearchParams(queryStart === -1 ? "" : url.slice(queryStart + 1)), request = { method: "GET", path }, myAttributes = path.match(MY_ATTRIBUTES_PATH);
473
+ async function servePlatformRequest(ctx, uri, request) {
474
+ const { path } = request, queryStart = uri.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : uri.slice(queryStart + 1)), myAttributes = path.match(MY_ATTRIBUTES_PATH);
471
475
  if (myAttributes !== null) {
472
476
  const organizationId = decodeURIComponent(myAttributes[1]);
473
477
  return serveMyAttributes({ ctx, request, organizationId, query });
@@ -507,10 +511,10 @@ async function servePlatformRequest(ctx, url) {
507
511
  if (rest.startsWith("/history/"))
508
512
  return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
509
513
  }
510
- function refuseAclRequest(ctx, url) {
511
- const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), matched = matchResourcePath(path);
514
+ function refuseAclRequest(ctx, request) {
515
+ const matched = matchResourcePath(request.path);
512
516
  if (matched?.rest !== "/acl") return;
513
- const row = capabilitiesOf(matched.resource.type), request = { method: "GET", path };
517
+ const row = capabilitiesOf(matched.resource.type);
514
518
  serveCapability(
515
519
  row.acl,
516
520
  request,
@@ -880,13 +884,13 @@ function serveProject(args) {
880
884
  };
881
885
  }
882
886
  function makeRequestImpl(ctx) {
883
- const { getAccess, useProjectHostname, listIdentities, organizationId, platform } = ctx;
887
+ const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
884
888
  return async (opts) => {
885
889
  const accessControl = getAccess(), path = opts.uri ?? opts.url;
886
890
  if (path === "/users/me")
887
891
  return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
888
892
  if (path !== void 0 && path === accessControl.aclPath)
889
- return refuseAclRequest(platform, path), accessControl.grants;
893
+ return refuseAclRequest(platform, requestFor(opts)), accessControl.grants;
890
894
  const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
891
895
  if (pathProjectId !== void 0 && requestedIds !== void 0)
892
896
  return serveProjectUsers({
@@ -901,7 +905,7 @@ function makeRequestImpl(ctx) {
901
905
  identities: listIdentities(),
902
906
  organizationId
903
907
  });
904
- const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
908
+ const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
905
909
  if (served !== void 0) return served.value;
906
910
  throw fakeError(
907
911
  `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.`
@@ -1548,7 +1552,11 @@ async function createVersionFromBase(store, action, request) {
1548
1552
  }, promoted = promote(copy);
1549
1553
  return store.put(promoted), { transactionId: cryptoRandomKey() };
1550
1554
  }
1551
- const ACTIONS_REQUEST = { method: "POST", path: "/data/actions" };
1555
+ const ACTIONS_REQUEST = {
1556
+ method: "POST",
1557
+ path: "/data/actions",
1558
+ url: "/data/actions"
1559
+ };
1552
1560
  function requireRevisionMatch(request, documentId, actualRev, expectedRev) {
1553
1561
  if (!(expectedRev === void 0 || actualRev === expectedRev))
1554
1562
  throw actualRev === void 0 ? new PlatformHttpError({
@@ -1675,6 +1683,48 @@ function createTransaction(executor) {
1675
1683
  };
1676
1684
  return handle;
1677
1685
  }
1686
+ const DEFAULT_API_HOST = "https://api.sanity.io", DEFAULT_API_VERSION = "1", DEFAULT_CDN_HOST = "apicdn.sanity.io", QUERY_SIZE_LIMIT = 11264;
1687
+ function normalizeTagPrefix(prefix) {
1688
+ return prefix?.replace(/\.+$/, "") || void 0;
1689
+ }
1690
+ function normalizeApiVersion(apiVersion) {
1691
+ const version = `${apiVersion}`.replace(/^v/, "");
1692
+ if (version === "1" || version === "X") return version;
1693
+ const date = new Date(version);
1694
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(version) || !(date.getTime() > 0))
1695
+ throw fakeError(
1696
+ `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\`.`
1697
+ );
1698
+ return version;
1699
+ }
1700
+ function apiBaseUrls(args) {
1701
+ const { apiHost, apiVersion, projectId } = args;
1702
+ if (projectId === void 0) {
1703
+ const url = `${apiHost}/v${apiVersion}`;
1704
+ return { url, cdnUrl: url };
1705
+ }
1706
+ const [protocol, host] = apiHost.split("://", 2), cdnHost = apiHost === DEFAULT_API_HOST ? DEFAULT_CDN_HOST : host;
1707
+ return {
1708
+ url: `${protocol}://${projectId}.${host}/v${apiVersion}`,
1709
+ cdnUrl: `${protocol}://${projectId}.${cdnHost}/v${apiVersion}`
1710
+ };
1711
+ }
1712
+ function requestUrl(base, uri, query = []) {
1713
+ const url = `${base}/${uri.replace(/^\//, "")}`, params = new URLSearchParams();
1714
+ for (const [key, value] of query)
1715
+ value !== void 0 && params.append(key, `${value}`);
1716
+ const search = params.toString();
1717
+ if (search === "") return url;
1718
+ const fragmentStart = url.indexOf("#"), beforeFragment = fragmentStart === -1 ? url : url.slice(0, fragmentStart), fragment = fragmentStart === -1 ? "" : url.slice(fragmentStart);
1719
+ return `${beforeFragment}${beforeFragment.includes("?") ? "&" : "?"}${search}${fragment}`;
1720
+ }
1721
+ function encodeGroqQuery(query, params = {}) {
1722
+ const search = new URLSearchParams();
1723
+ search.append("query", query);
1724
+ for (const [key, value] of Object.entries(params))
1725
+ value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
1726
+ return `?${search}`;
1727
+ }
1678
1728
  const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
1679
1729
  "fetch",
1680
1730
  "getDocument",
@@ -1915,7 +1965,16 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
1915
1965
  function ensureEntry(registry, resource) {
1916
1966
  const key = registryKey(resource);
1917
1967
  let entry = registry.get(key);
1918
- return entry === void 0 && (entry = { resource, store: createTestStore(), history: createDocumentHistory() }, registry.set(key, entry)), entry;
1968
+ return entry === void 0 && (entry = {
1969
+ resource,
1970
+ store: createTestStore(),
1971
+ history: createDocumentHistory(),
1972
+ exists: !1
1973
+ }, registry.set(key, entry)), entry;
1974
+ }
1975
+ function seedEntry(registry, resource, documents) {
1976
+ const entry = ensureEntry(registry, resource);
1977
+ entry.store.seed(documents), entry.exists = !0;
1919
1978
  }
1920
1979
  function createTestClient(options = {}) {
1921
1980
  const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
@@ -1932,16 +1991,16 @@ function createTestClient(options = {}) {
1932
1991
  }, registry = backend.registry;
1933
1992
  if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
1934
1993
  const root = options.resource ?? datasetResource(defaultProjectId, defaultDataset);
1935
- ensureEntry(registry, root).store.seed(options.documents);
1994
+ seedEntry(registry, root, options.documents);
1936
1995
  }
1937
1996
  if (options.datasets)
1938
1997
  for (const [key, docs] of Object.entries(options.datasets)) {
1939
1998
  const { projectId, dataset } = parseDatasetKey(key);
1940
- ensureEntry(registry, datasetResource(projectId, dataset)).store.seed(docs);
1999
+ seedEntry(registry, datasetResource(projectId, dataset), docs);
1941
2000
  }
1942
2001
  if (options.resources)
1943
2002
  for (const [key, docs] of Object.entries(options.resources))
1944
- ensureEntry(registry, parseResourceKey(key)).store.seed(docs);
2003
+ seedEntry(registry, parseResourceKey(key), docs);
1945
2004
  return makeHandle({
1946
2005
  backend,
1947
2006
  projectId: defaultProjectId,
@@ -1949,11 +2008,15 @@ function createTestClient(options = {}) {
1949
2008
  resource: options.resource,
1950
2009
  accessControl: options.accessControl,
1951
2010
  perspective: options.perspective ?? "raw",
1952
- requestTagPrefix: options.requestTagPrefix,
2011
+ requestTagPrefix: normalizeTagPrefix(options.requestTagPrefix),
1953
2012
  mutationGuard: options.mutationGuard,
1954
2013
  token: options.token,
1955
2014
  useProjectHostname: options.useProjectHostname ?? !0,
1956
- hasProjectId: options.projectId !== void 0
2015
+ hasProjectId: options.projectId !== void 0,
2016
+ apiHost: options.apiHost ?? DEFAULT_API_HOST,
2017
+ apiVersion: normalizeApiVersion(options.apiVersion ?? DEFAULT_API_VERSION),
2018
+ useCdn: options.useCdn !== !1,
2019
+ configuredPerspective: options.perspective
1957
2020
  });
1958
2021
  }
1959
2022
  function dedupeIds(results) {
@@ -2015,7 +2078,11 @@ function makeHandle(handleArgs) {
2015
2078
  requestTagPrefix,
2016
2079
  mutationGuard,
2017
2080
  token,
2018
- useProjectHostname
2081
+ useProjectHostname,
2082
+ apiHost,
2083
+ apiVersion,
2084
+ useCdn,
2085
+ configuredPerspective
2019
2086
  } = 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 = () => {
2020
2087
  if (token === void 0) return accessControl;
2021
2088
  const identity = backend.identities.get(token);
@@ -2039,13 +2106,61 @@ function makeHandle(handleArgs) {
2039
2106
  const tokenProjectId = backend.identities.get(token)?.projectId;
2040
2107
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2041
2108
  throw sessionHostMismatch(request);
2042
- }, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
2109
+ }, withSession = (request) => async (opts) => (refuseSession(rawRequest(opts)), request(opts)), admitToLake = (request) => {
2043
2110
  refuseSession(request);
2044
2111
  const access = activeAccess();
2045
2112
  if (access === void 0) return;
2046
2113
  const refusal = refusedToken(request, access.grants);
2047
2114
  if (refusal !== void 0) throw refusal;
2048
- }, lakeRequest = (method, operation, path) => ({ method, path: dataUrl({ resource, dataset, operation, path }) }), members = () => [
2115
+ }, baseUrls = apiBaseUrls({
2116
+ apiHost,
2117
+ apiVersion,
2118
+ projectId: projectHosted ? projectId : void 0
2119
+ }), 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) => {
2120
+ const { method, uri, tag } = args, query = [...args.query ?? []];
2121
+ let cdn = useCdn && (args.canUseCdn ?? (method === "GET" && isDataUri(uri)));
2122
+ const effectiveTag = tag && requestTagPrefix ? `${requestTagPrefix}.${tag}` : tag || requestTagPrefix;
2123
+ if (effectiveTag && tag !== null && query.unshift(["tag", effectiveTag]), addresses(uri, "query")) {
2124
+ const perspectiveOption = args.perspective || configuredPerspective;
2125
+ if (perspectiveOption !== void 0) {
2126
+ const value = Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption;
2127
+ query.unshift(["perspective", value]), (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || perspectiveOption === "previewDrafts" || perspectiveOption === "drafts") && (cdn = !1);
2128
+ }
2129
+ args.returnQuery === !1 && query.unshift(["returnQuery", "false"]);
2130
+ }
2131
+ const queryStart = uri.indexOf("?");
2132
+ return {
2133
+ method,
2134
+ path: queryStart === -1 ? uri : uri.slice(0, queryStart),
2135
+ url: requestUrl(cdn ? baseUrls.cdnUrl : baseUrls.url, uri, query)
2136
+ };
2137
+ }, docRequest = (ids, tag) => platformRequest({ method: "GET", uri: dataPath("doc", ids), tag }), queryRequest = (args) => {
2138
+ const encoded = encodeGroqQuery(args.query, args.params), useGet = encoded.length < QUERY_SIZE_LIMIT;
2139
+ return platformRequest({
2140
+ method: useGet ? "GET" : "POST",
2141
+ uri: dataPath("query", useGet ? encoded : ""),
2142
+ tag: args.tag,
2143
+ canUseCdn: !0,
2144
+ perspective: args.perspective,
2145
+ returnQuery: args.returnQuery
2146
+ });
2147
+ }, mutateRequest = (options = {}) => {
2148
+ const { returnDocuments } = options;
2149
+ return platformRequest({
2150
+ method: "POST",
2151
+ uri: dataPath("mutate"),
2152
+ tag: options.tag,
2153
+ canUseCdn: !1,
2154
+ query: [
2155
+ ["dryRun", options.dryRun],
2156
+ ["returnIds", !0],
2157
+ ["returnDocuments", returnDocuments === !1 ? void 0 : returnDocuments ?? !0],
2158
+ ["visibility", options.visibility || "sync"],
2159
+ ["autoGenerateArrayKeys", options.autoGenerateArrayKeys],
2160
+ ["skipCrossDatasetReferenceValidation", options.skipCrossDatasetReferenceValidation]
2161
+ ]
2162
+ });
2163
+ }, rawRequest = (opts) => platformRequest({ method: "GET", uri: opts.uri ?? opts.url ?? "", tag: opts.tag }), members = () => [
2049
2164
  ...backend.identities.values(),
2050
2165
  ...token === void 0 && accessControl !== void 0 ? [
2051
2166
  {
@@ -2055,13 +2170,24 @@ function makeHandle(handleArgs) {
2055
2170
  ...accessControl.access !== void 0 ? { access: accessControl.access } : {}
2056
2171
  }
2057
2172
  ] : []
2058
- ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), { store, history } = ensureEntry(registry, target), concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
2173
+ ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, publicStore = {
2174
+ ...store,
2175
+ seed: (documents) => {
2176
+ store.seed(documents), targetEntry.exists = !0;
2177
+ },
2178
+ add: (documents) => {
2179
+ store.add(documents), targetEntry.exists = !0;
2180
+ },
2181
+ put: (doc) => {
2182
+ store.put(doc), targetEntry.exists = !0;
2183
+ }
2184
+ }, concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
2059
2185
  const access = activeAccess();
2060
2186
  if (access !== void 0)
2061
2187
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
2062
2188
  };
2063
2189
  let beforeWrite, writeRequest = DEFAULT_WRITE;
2064
- const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
2190
+ const write = (run, request) => serializeWrite(backend, async () => {
2065
2191
  admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc])), writeRequest = request;
2066
2192
  try {
2067
2193
  return await run();
@@ -2069,7 +2195,7 @@ function makeHandle(handleArgs) {
2069
2195
  beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
2070
2196
  }
2071
2197
  }), commitHistory = (transactionId) => {
2072
- beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
2198
+ beforeWrite !== void 0 && (targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() }));
2073
2199
  }, record = (transactionId, mutations, tag) => {
2074
2200
  const effectiveTag = effectiveRequestTag(tag);
2075
2201
  commitHistory(transactionId), backend.log.push({
@@ -2223,8 +2349,13 @@ function makeHandle(handleArgs) {
2223
2349
  txnOptions?.returnDocuments ?? !1,
2224
2350
  txnOptions?.returnFirst ?? !1
2225
2351
  );
2226
- }, runAction = async (actions) => {
2227
- const request = lakeRequest("POST", "actions");
2352
+ }, runAction = async (actions, tag) => {
2353
+ const request = platformRequest({
2354
+ method: "POST",
2355
+ uri: dataPath("actions"),
2356
+ tag,
2357
+ canUseCdn: !1
2358
+ });
2228
2359
  if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
2229
2360
  return write(async () => {
2230
2361
  for (const action of Array.isArray(actions) ? actions : [actions]) {
@@ -2246,7 +2377,15 @@ function makeHandle(handleArgs) {
2246
2377
  return applyPerspective(accessible, override ?? perspective);
2247
2378
  }, client2 = {
2248
2379
  fetch: async (query, params, opts) => {
2249
- admitToLake(lakeRequest("GET", "query"));
2380
+ admitToLake(
2381
+ queryRequest({
2382
+ query,
2383
+ params,
2384
+ tag: opts?.tag,
2385
+ perspective: opts?.perspective,
2386
+ returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
2387
+ })
2388
+ );
2250
2389
  const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
2251
2390
  dataset: await visibleDocs(opts?.perspective),
2252
2391
  ...params !== void 0 ? { params } : {}
@@ -2258,7 +2397,7 @@ function makeHandle(handleArgs) {
2258
2397
  return result;
2259
2398
  },
2260
2399
  getDocument: async (id, opts) => {
2261
- admitToLake(lakeRequest("GET", "doc", id));
2400
+ admitToLake(docRequest(id, opts?.tag));
2262
2401
  const effective = opts?.perspective ?? perspective;
2263
2402
  if (effective === "raw") {
2264
2403
  const doc = store.get(id);
@@ -2268,7 +2407,7 @@ function makeHandle(handleArgs) {
2268
2407
  return resolveDocument(view, id, effective) ?? void 0;
2269
2408
  },
2270
2409
  getDocuments: async (ids, opts) => {
2271
- admitToLake(lakeRequest("GET", "doc", ids.join(",")));
2410
+ admitToLake(docRequest(ids.join(","), opts?.tag));
2272
2411
  const effective = opts?.perspective ?? perspective;
2273
2412
  if (effective === "raw") {
2274
2413
  const result = [];
@@ -2281,7 +2420,7 @@ function makeHandle(handleArgs) {
2281
2420
  const view = await visibleDocs(effective);
2282
2421
  return ids.map((id) => resolveDocument(view, id, effective) ?? null);
2283
2422
  },
2284
- getDataUrl: (operation, path) => dataUrl({ resource, dataset, operation, path }),
2423
+ getDataUrl: dataPath,
2285
2424
  create: (doc, opts) => write(async () => {
2286
2425
  if (checkRevision(doc._id, opts?.ifRevisionId), store.get(doc._id) !== void 0)
2287
2426
  throw fakeError(
@@ -2296,7 +2435,7 @@ function makeHandle(handleArgs) {
2296
2435
  transactionId,
2297
2436
  opts
2298
2437
  );
2299
- }),
2438
+ }, mutateRequest(opts)),
2300
2439
  createOrReplace: (doc, opts) => write(async () => {
2301
2440
  checkRevision(doc._id, opts?.ifRevisionId);
2302
2441
  const promoted = promote2(doc), existing = store.get(doc._id);
@@ -2310,7 +2449,7 @@ function makeHandle(handleArgs) {
2310
2449
  transactionId,
2311
2450
  opts
2312
2451
  );
2313
- }),
2452
+ }, mutateRequest(opts)),
2314
2453
  createIfNotExists: (doc, opts) => write(async () => {
2315
2454
  checkRevision(doc._id, opts?.ifRevisionId);
2316
2455
  const existing = store.get(doc._id), transactionId = opts?.transactionId ?? cryptoRandomKey();
@@ -2328,7 +2467,7 @@ function makeHandle(handleArgs) {
2328
2467
  transactionId,
2329
2468
  opts
2330
2469
  );
2331
- }),
2470
+ }, mutateRequest(opts)),
2332
2471
  delete: (id, opts) => write(async () => {
2333
2472
  checkRevision(id, opts?.ifRevisionId);
2334
2473
  const existing = store.get(id);
@@ -2342,7 +2481,7 @@ function makeHandle(handleArgs) {
2342
2481
  opts.returnDocuments ?? !0,
2343
2482
  opts.returnFirst ?? !0
2344
2483
  );
2345
- }),
2484
+ }, mutateRequest(opts)),
2346
2485
  patch: (documentId) => createPatch(documentId, {
2347
2486
  apply: (docId, ops, ifRev, options) => write(async () => {
2348
2487
  const doc = await applyPatch(docId, ops, ifRev);
@@ -2358,16 +2497,20 @@ function makeHandle(handleArgs) {
2358
2497
  ],
2359
2498
  options?.tag
2360
2499
  ), doc;
2361
- })
2500
+ }, mutateRequest(options))
2362
2501
  }),
2363
2502
  transaction: () => createTransaction({
2364
- apply: (mutations, txnOptions) => write(() => applyTransaction(mutations, txnOptions))
2503
+ apply: (mutations, txnOptions) => write(
2504
+ () => applyTransaction(mutations, txnOptions),
2505
+ // `Transaction.commit()` asks for ids unless told otherwise.
2506
+ mutateRequest({ ...txnOptions, returnDocuments: txnOptions?.returnDocuments ?? !1 })
2507
+ )
2365
2508
  }),
2366
- mutate: (operations, options) => write(() => applyTransaction(toTxnMutations(operations), options)),
2509
+ mutate: (operations, options) => write(() => applyTransaction(toTxnMutations(operations), options), mutateRequest(options)),
2367
2510
  // Synchronous writes still take the lock: an action landing while a
2368
2511
  // guarded patch is parked in its gate would otherwise be clobbered
2369
2512
  // when that patch resumes over its pre-action snapshot.
2370
- action: (action) => runAction(action),
2513
+ action: (action, options) => runAction(action, options?.tag),
2371
2514
  releases: {
2372
2515
  create: async ({ releaseId, metadata }) => {
2373
2516
  const result = await runAction({
@@ -2384,12 +2527,20 @@ function makeHandle(handleArgs) {
2384
2527
  edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
2385
2528
  // `@sanity/client` reads a release by id and its documents by query.
2386
2529
  get: async ({ releaseId }) => {
2387
- admitToLake(lakeRequest("GET", "doc", `_.releases.${releaseId}`));
2530
+ admitToLake(docRequest(`_.releases.${releaseId}`, void 0));
2388
2531
  const doc = store.get(`_.releases.${releaseId}`);
2389
2532
  return doc !== void 0 && await canRead(doc) ? doc : void 0;
2390
2533
  },
2391
2534
  fetchDocuments: async ({ releaseId }) => {
2392
- admitToLake(lakeRequest("GET", "query"));
2535
+ admitToLake(
2536
+ queryRequest({
2537
+ query: "*[sanity::partOfRelease($releaseId)]",
2538
+ params: { releaseId },
2539
+ tag: void 0,
2540
+ perspective: void 0,
2541
+ returnQuery: void 0
2542
+ })
2543
+ );
2393
2544
  const prefix = `versions.${releaseId}.`;
2394
2545
  return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
2395
2546
  },
@@ -2432,6 +2583,7 @@ function makeHandle(handleArgs) {
2432
2583
  request: withSession(
2433
2584
  makeRequestImpl({
2434
2585
  getAccess: requireActiveAccess,
2586
+ requestFor: rawRequest,
2435
2587
  useProjectHostname: projectHosted,
2436
2588
  organizationId: backend.organizationId,
2437
2589
  listIdentities: members,
@@ -2453,7 +2605,9 @@ function makeHandle(handleArgs) {
2453
2605
  actorAccess: () => requireActiveAccess().access,
2454
2606
  actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
2455
2607
  identities: members,
2456
- resources: () => [...registry.values()].map((entry) => entry.resource)
2608
+ // A dataset stands for its project, and every project exists in
2609
+ // the fake, so a dataset handle still counts as before.
2610
+ resources: () => [...registry.values()].filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
2457
2611
  }
2458
2612
  })
2459
2613
  )
@@ -2465,7 +2619,10 @@ function makeHandle(handleArgs) {
2465
2619
  perspective,
2466
2620
  ...requestTagPrefix !== void 0 ? { requestTagPrefix } : {},
2467
2621
  ...token !== void 0 ? { token } : {},
2468
- useProjectHostname
2622
+ useProjectHostname,
2623
+ apiHost,
2624
+ apiVersion,
2625
+ useCdn
2469
2626
  }),
2470
2627
  withConfig: (config) => {
2471
2628
  rejectAmbiguousIdentity("withConfig()", config), config.token !== void 0 && requireIdentity(backend, config.token, "withConfig()");
@@ -2477,18 +2634,23 @@ function makeHandle(handleArgs) {
2477
2634
  resource: nextResource,
2478
2635
  accessControl: rebinds ? config.accessControl : accessControl,
2479
2636
  perspective: config.perspective ?? perspective,
2480
- requestTagPrefix: config.requestTagPrefix ?? requestTagPrefix,
2637
+ // `requestTagPrefix: undefined` unsets the prefix, as in `@sanity/client`.
2638
+ requestTagPrefix: "requestTagPrefix" in config ? normalizeTagPrefix(config.requestTagPrefix) : requestTagPrefix,
2481
2639
  mutationGuard,
2482
2640
  token: rebinds ? config.token : token,
2483
2641
  useProjectHostname: config.useProjectHostname ?? useProjectHostname,
2484
- hasProjectId: hasProjectId || config.projectId !== void 0
2642
+ hasProjectId: hasProjectId || config.projectId !== void 0,
2643
+ apiHost: config.apiHost ?? apiHost,
2644
+ apiVersion: config.apiVersion !== void 0 ? normalizeApiVersion(config.apiVersion) : apiVersion,
2645
+ useCdn: config.useCdn ?? useCdn,
2646
+ configuredPerspective: config.perspective ?? configuredPerspective
2485
2647
  });
2486
2648
  },
2487
- seed: (documents) => store.seed(documents),
2488
- add: (documents) => store.add(documents),
2649
+ seed: (documents) => publicStore.seed(documents),
2650
+ add: (documents) => publicStore.add(documents),
2489
2651
  reset: () => store.reset(),
2490
2652
  snapshot: () => store.snapshot(),
2491
- store: () => store,
2653
+ store: () => publicStore,
2492
2654
  simulateConcurrentEdit: (id, count = 1) => {
2493
2655
  const editKey = concurrentEditKey(id);
2494
2656
  backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);