@sanity/client 7.3.0 → 7.4.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.
Files changed (53) hide show
  1. package/README.md +122 -1
  2. package/dist/_chunks-cjs/isRecord.cjs +6 -0
  3. package/dist/_chunks-cjs/isRecord.cjs.map +1 -0
  4. package/dist/_chunks-cjs/resolveEditInfo.cjs +3 -5
  5. package/dist/_chunks-cjs/resolveEditInfo.cjs.map +1 -1
  6. package/dist/_chunks-cjs/stegaClean.cjs +4 -0
  7. package/dist/_chunks-cjs/stegaClean.cjs.map +1 -1
  8. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +2 -5
  9. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +1 -1
  10. package/dist/_chunks-es/isRecord.js +7 -0
  11. package/dist/_chunks-es/isRecord.js.map +1 -0
  12. package/dist/_chunks-es/resolveEditInfo.js +1 -3
  13. package/dist/_chunks-es/resolveEditInfo.js.map +1 -1
  14. package/dist/_chunks-es/stegaClean.js +4 -0
  15. package/dist/_chunks-es/stegaClean.js.map +1 -1
  16. package/dist/_chunks-es/stegaEncodeSourceMap.js +1 -4
  17. package/dist/_chunks-es/stegaEncodeSourceMap.js.map +1 -1
  18. package/dist/index.browser.cjs +155 -32
  19. package/dist/index.browser.cjs.map +1 -1
  20. package/dist/index.browser.d.cts +473 -68
  21. package/dist/index.browser.d.ts +473 -68
  22. package/dist/index.browser.js +156 -33
  23. package/dist/index.browser.js.map +1 -1
  24. package/dist/index.cjs +157 -34
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +473 -68
  27. package/dist/index.d.ts +473 -68
  28. package/dist/index.js +157 -33
  29. package/dist/index.js.map +1 -1
  30. package/dist/stega.browser.d.cts +473 -68
  31. package/dist/stega.browser.d.ts +473 -68
  32. package/dist/stega.d.cts +473 -68
  33. package/dist/stega.d.ts +473 -68
  34. package/package.json +1 -1
  35. package/src/agent/actions/AgentActionsClient.ts +29 -2
  36. package/src/agent/actions/commonTypes.ts +57 -17
  37. package/src/agent/actions/generate.ts +36 -2
  38. package/src/agent/actions/patch.ts +136 -0
  39. package/src/agent/actions/prompt.ts +145 -0
  40. package/src/agent/actions/transform.ts +27 -4
  41. package/src/agent/actions/translate.ts +5 -2
  42. package/src/csm/walkMap.ts +1 -1
  43. package/src/data/eventsource.ts +16 -7
  44. package/src/data/listen.ts +10 -4
  45. package/src/data/live.ts +13 -5
  46. package/src/defineCreateClient.ts +7 -1
  47. package/src/http/errors.ts +92 -27
  48. package/src/http/request.ts +3 -3
  49. package/src/types.ts +25 -10
  50. package/src/util/codeFrame.ts +174 -0
  51. package/src/{csm → util}/isRecord.ts +1 -1
  52. package/umd/sanityClient.js +158 -35
  53. package/umd/sanityClient.min.js +2 -2
@@ -1893,6 +1893,9 @@
1893
1893
  identity;
1894
1894
  }
1895
1895
 
1896
+ function isRecord(value) {
1897
+ return typeof value == "object" && value !== null && !Array.isArray(value);
1898
+ }
1896
1899
  var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 }, u = new Array(4).fill(String.fromCodePoint(c[0])).join("");
1897
1900
  function E(t) {
1898
1901
  let e = JSON.stringify(t);
@@ -1977,13 +1980,82 @@
1977
1980
  let customAlphabet = (alphabet, size = 21) =>
1978
1981
  customRandom(alphabet, size, random);
1979
1982
 
1983
+ const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
1984
+ function codeFrame(query, location2, message) {
1985
+ const lines = query.split(NEWLINE), loc = {
1986
+ start: columnToLine(location2.start, lines),
1987
+ end: location2.end ? columnToLine(location2.end, lines) : void 0
1988
+ }, { start, end, markerLines } = getMarkerLines(loc, lines), numberMaxWidth = `${end}`.length;
1989
+ return query.split(NEWLINE, end).slice(start, end).map((line, index) => {
1990
+ const number = start + 1 + index, gutter = ` ${` ${number}`.slice(-numberMaxWidth)} |`, hasMarker = markerLines[number], lastMarkerLine = !markerLines[number + 1];
1991
+ if (!hasMarker)
1992
+ return ` ${gutter}${line.length > 0 ? ` ${line}` : ""}`;
1993
+ let markerLine = "";
1994
+ if (Array.isArray(hasMarker)) {
1995
+ const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "), numberOfMarkers = hasMarker[1] || 1;
1996
+ markerLine = [
1997
+ `
1998
+ `,
1999
+ gutter.replace(/\d/g, " "),
2000
+ " ",
2001
+ markerSpacing,
2002
+ "^".repeat(numberOfMarkers)
2003
+ ].join(""), lastMarkerLine && message && (markerLine += " " + message);
2004
+ }
2005
+ return [">", gutter, line.length > 0 ? ` ${line}` : "", markerLine].join("");
2006
+ }).join(`
2007
+ `);
2008
+ }
2009
+ function getMarkerLines(loc, source) {
2010
+ const startLoc = { ...loc.start }, endLoc = { ...startLoc, ...loc.end }, linesAbove = 2, linesBelow = 3, startLine = startLoc.line ?? -1, startColumn = startLoc.column ?? 0, endLine = endLoc.line, endColumn = endLoc.column;
2011
+ let start = Math.max(startLine - (linesAbove + 1), 0), end = Math.min(source.length, endLine + linesBelow);
2012
+ startLine === -1 && (start = 0), endLine === -1 && (end = source.length);
2013
+ const lineDiff = endLine - startLine, markerLines = {};
2014
+ if (lineDiff)
2015
+ for (let i = 0; i <= lineDiff; i++) {
2016
+ const lineNumber = i + startLine;
2017
+ if (!startColumn)
2018
+ markerLines[lineNumber] = true;
2019
+ else if (i === 0) {
2020
+ const sourceLength = source[lineNumber - 1].length;
2021
+ markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
2022
+ } else if (i === lineDiff)
2023
+ markerLines[lineNumber] = [0, endColumn];
2024
+ else {
2025
+ const sourceLength = source[lineNumber - i].length;
2026
+ markerLines[lineNumber] = [0, sourceLength];
2027
+ }
2028
+ }
2029
+ else
2030
+ startColumn === endColumn ? startColumn ? markerLines[startLine] = [startColumn, 0] : markerLines[startLine] = true : markerLines[startLine] = [startColumn, endColumn - startColumn];
2031
+ return { start, end, markerLines };
2032
+ }
2033
+ function columnToLine(column, lines) {
2034
+ let offset = 0;
2035
+ for (let i = 0; i < lines.length; i++) {
2036
+ const lineLength = lines[i].length + 1;
2037
+ if (offset + lineLength > column)
2038
+ return {
2039
+ line: i + 1,
2040
+ // 1-based line
2041
+ column: column - offset
2042
+ // 0-based column
2043
+ };
2044
+ offset += lineLength;
2045
+ }
2046
+ return {
2047
+ line: lines.length,
2048
+ column: lines[lines.length - 1]?.length ?? 0
2049
+ };
2050
+ }
2051
+ const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
1980
2052
  class ClientError extends Error {
1981
2053
  response;
1982
2054
  statusCode = 400;
1983
2055
  responseBody;
1984
2056
  details;
1985
- constructor(res) {
1986
- const props = extractErrorProps(res);
2057
+ constructor(res, context) {
2058
+ const props = extractErrorProps(res, context);
1987
2059
  super(props.message), Object.assign(this, props);
1988
2060
  }
1989
2061
  }
@@ -1997,7 +2069,7 @@
1997
2069
  super(props.message), Object.assign(this, props);
1998
2070
  }
1999
2071
  }
2000
- function extractErrorProps(res) {
2072
+ function extractErrorProps(res, context) {
2001
2073
  const body = res.body, props = {
2002
2074
  response: res,
2003
2075
  statusCode: res.statusCode,
@@ -2005,34 +2077,56 @@
2005
2077
  message: "",
2006
2078
  details: void 0
2007
2079
  };
2008
- if (body.error && body.message)
2009
- return props.message = `${body.error} - ${body.message}`, props;
2010
- if (isMutationError(body) || isActionError(body)) {
2011
- const allItems = body.error.items || [], items = allItems.slice(0, 5).map((item) => item.error?.description).filter(Boolean);
2080
+ if (!isRecord(body))
2081
+ return props.message = httpErrorMessage(res, body), props;
2082
+ const error = body.error;
2083
+ if (typeof error == "string" && typeof body.message == "string")
2084
+ return props.message = `${error} - ${body.message}`, props;
2085
+ if (typeof error != "object" || error === null)
2086
+ return typeof error == "string" ? props.message = error : typeof body.message == "string" ? props.message = body.message : props.message = httpErrorMessage(res, body), props;
2087
+ if (isMutationError(error) || isActionError(error)) {
2088
+ const allItems = error.items || [], items = allItems.slice(0, MAX_ITEMS_IN_ERROR_MESSAGE).map((item) => item.error?.description).filter(Boolean);
2012
2089
  let itemsStr = items.length ? `:
2013
2090
  - ${items.join(`
2014
2091
  - `)}` : "";
2015
- return allItems.length > 5 && (itemsStr += `
2016
- ...and ${allItems.length - 5} more`), props.message = `${body.error.description}${itemsStr}`, props.details = body.error, props;
2092
+ return allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE && (itemsStr += `
2093
+ ...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`), props.message = `${error.description}${itemsStr}`, props.details = body.error, props;
2017
2094
  }
2018
- return body.error && body.error.description ? (props.message = body.error.description, props.details = body.error, props) : (props.message = body.error || body.message || httpErrorMessage(res), props);
2095
+ if (isQueryParseError(error)) {
2096
+ const tag = context?.options?.query?.tag;
2097
+ return props.message = formatQueryParseError(error, tag), props.details = body.error, props;
2098
+ }
2099
+ return "description" in error && typeof error.description == "string" ? (props.message = error.description, props.details = error, props) : (props.message = httpErrorMessage(res, body), props);
2100
+ }
2101
+ function isMutationError(error) {
2102
+ return "type" in error && error.type === "mutationError" && "description" in error && typeof error.description == "string";
2019
2103
  }
2020
- function isMutationError(body) {
2021
- return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description == "string";
2104
+ function isActionError(error) {
2105
+ return "type" in error && error.type === "actionError" && "description" in error && typeof error.description == "string";
2022
2106
  }
2023
- function isActionError(body) {
2024
- return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "actionError" && typeof body.error.description == "string";
2107
+ function isQueryParseError(error) {
2108
+ return isRecord(error) && error.type === "queryParseError" && typeof error.query == "string" && typeof error.start == "number" && typeof error.end == "number";
2025
2109
  }
2026
- function isPlainObject(obj) {
2027
- return typeof obj == "object" && obj !== null && !Array.isArray(obj);
2110
+ function formatQueryParseError(error, tag) {
2111
+ const { query, start, end, description } = error;
2112
+ if (!query || typeof start > "u")
2113
+ return `GROQ query parse error: ${description}`;
2114
+ const withTag = tag ? `
2115
+
2116
+ Tag: ${tag}` : "";
2117
+ return `GROQ query parse error:
2118
+ ${codeFrame(query, { start, end }, description)}${withTag}`;
2028
2119
  }
2029
- function httpErrorMessage(res) {
2030
- const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
2031
- return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;
2120
+ function httpErrorMessage(res, body) {
2121
+ const details = typeof body == "string" ? ` (${sliceWithEllipsis(body, 100)})` : "", statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
2122
+ return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`;
2032
2123
  }
2033
2124
  function stringifyBody(body, res) {
2034
2125
  return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? JSON.stringify(body, null, 2) : body;
2035
2126
  }
2127
+ function sliceWithEllipsis(str, max) {
2128
+ return str.length > max ? `${str.slice(0, max)}\u2026` : str;
2129
+ }
2036
2130
  class CorsOriginError extends Error {
2037
2131
  projectId;
2038
2132
  addOriginUrl;
@@ -2047,11 +2141,11 @@
2047
2141
  }
2048
2142
  }
2049
2143
  const httpError = {
2050
- onResponse: (res) => {
2144
+ onResponse: (res, context) => {
2051
2145
  if (res.statusCode >= 500)
2052
2146
  throw new ServerError(res);
2053
2147
  if (res.statusCode >= 400)
2054
- throw new ClientError(res);
2148
+ throw new ClientError(res, context);
2055
2149
  return res;
2056
2150
  }
2057
2151
  };
@@ -2312,7 +2406,8 @@
2312
2406
  return;
2313
2407
  }
2314
2408
  if (message.type === "channelError") {
2315
- observer.error(new ChannelError(extractErrorMessage(event?.data), event.data));
2409
+ const tag = new URL(es.url).searchParams.get("tag");
2410
+ observer.error(new ChannelError(extractErrorMessage(event?.data, tag), event.data));
2316
2411
  return;
2317
2412
  }
2318
2413
  if (message.type === "disconnect") {
@@ -2351,8 +2446,9 @@
2351
2446
  return [err, null];
2352
2447
  }
2353
2448
  }
2354
- function extractErrorMessage(err) {
2355
- return err.error ? err.error.description ? err.error.description : typeof err.error == "string" ? err.error : JSON.stringify(err.error, null, 2) : err.message || "Unknown listener error";
2449
+ function extractErrorMessage(err, tag) {
2450
+ const error = err.error;
2451
+ return error ? isQueryParseError(error) ? formatQueryParseError(error, tag) : error.description ? error.description : typeof error == "string" ? error : JSON.stringify(error, null, 2) : err.message || "Unknown listener error";
2356
2452
  }
2357
2453
  function isEmptyObject(data) {
2358
2454
  for (const _ in data)
@@ -3015,6 +3111,22 @@ ${selectionOpts}`);
3015
3111
  body: request
3016
3112
  });
3017
3113
  }
3114
+ function _patch(client, httpRequest, request) {
3115
+ const dataset2 = hasDataset(client.config());
3116
+ return _request(client, httpRequest, {
3117
+ method: "POST",
3118
+ uri: `/agent/action/patch/${dataset2}`,
3119
+ body: request
3120
+ });
3121
+ }
3122
+ function _prompt(client, httpRequest, request) {
3123
+ const dataset2 = hasDataset(client.config());
3124
+ return _request(client, httpRequest, {
3125
+ method: "POST",
3126
+ uri: `/agent/action/prompt/${dataset2}`,
3127
+ body: request
3128
+ });
3129
+ }
3018
3130
  function _transform(client, httpRequest, request) {
3019
3131
  const dataset2 = hasDataset(client.config());
3020
3132
  return _request(client, httpRequest, {
@@ -3086,6 +3198,21 @@ ${selectionOpts}`);
3086
3198
  translate(request) {
3087
3199
  return lastValueFrom(_translate(this.#client, this.#httpRequest, request));
3088
3200
  }
3201
+ /**
3202
+ * Run a raw instruction and return the result either as text or json
3203
+ * @param request - prompt request
3204
+ */
3205
+ prompt(request) {
3206
+ return lastValueFrom(_prompt(this.#client, this.#httpRequest, request));
3207
+ }
3208
+ /**
3209
+ * Patch a document using a schema aware API.
3210
+ * Does not use an LLM, but uses the schema to ensure paths and values matches the schema.
3211
+ * @param request - instruction request
3212
+ */
3213
+ patch(request) {
3214
+ return lastValueFrom(_patch(this.#client, this.#httpRequest, request));
3215
+ }
3089
3216
  }
3090
3217
  class ObservableAssetsClient {
3091
3218
  #client;
@@ -3192,13 +3319,11 @@ ${selectionOpts}`);
3192
3319
  includeResult: true
3193
3320
  };
3194
3321
  function _listen(query, params, opts = {}) {
3195
- const { url, token, withCredentials, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this, "listen", qs)}`;
3322
+ const { url, token, withCredentials, requestTagPrefix, headers: configHeaders } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this, "listen", qs)}`;
3196
3323
  if (uri.length > MAX_URL_LENGTH)
3197
3324
  return throwError(() => new Error("Query too large for listener"));
3198
3325
  const listenFor = options.events ? options.events : ["mutation"], esOptions = {};
3199
- return withCredentials && (esOptions.withCredentials = true), token && (esOptions.headers = {
3200
- Authorization: `Bearer ${token}`
3201
- }), connectEventSource(() => (
3326
+ return withCredentials && (esOptions.withCredentials = true), (token || configHeaders) && (esOptions.headers = {}, token && (esOptions.headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(esOptions.headers, configHeaders)), connectEventSource(() => (
3202
3327
  // use polyfill if there is no global EventSource or if we need to set headers
3203
3328
  (typeof EventSource > "u" || esOptions.headers ? eventSourcePolyfill : of(EventSource)).pipe(map((EventSource2) => new EventSource2(uri, esOptions)))
3204
3329
  ), listenFor).pipe(
@@ -3256,7 +3381,8 @@ ${selectionOpts}`);
3256
3381
  apiVersion: _apiVersion,
3257
3382
  token,
3258
3383
  withCredentials,
3259
- requestTagPrefix
3384
+ requestTagPrefix,
3385
+ headers: configHeaders
3260
3386
  } = this.#client.config(), apiVersion = _apiVersion.replace(/^v/, "");
3261
3387
  if (apiVersion !== "X" && apiVersion < requiredApiVersion)
3262
3388
  throw new Error(
@@ -3269,9 +3395,7 @@ ${selectionOpts}`);
3269
3395
  const path = _getDataUrl(this.#client, "live/events"), url = new URL(this.#client.getUrl(path, false)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(".") : _tag;
3270
3396
  tag && url.searchParams.set("tag", tag), includeDrafts && url.searchParams.set("includeDrafts", "true");
3271
3397
  const esOptions = {};
3272
- includeDrafts && token && (esOptions.headers = {
3273
- Authorization: `Bearer ${token}`
3274
- }), includeDrafts && withCredentials && (esOptions.withCredentials = true);
3398
+ includeDrafts && withCredentials && (esOptions.withCredentials = true), (includeDrafts && token || configHeaders) && (esOptions.headers = {}, includeDrafts && token && (esOptions.headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(esOptions.headers, configHeaders));
3275
3399
  const key = `${url.href}::${JSON.stringify(esOptions)}`, existing = eventsCache.get(key);
3276
3400
  if (existing)
3277
3401
  return existing;
@@ -4635,9 +4759,6 @@ ${selectionOpts}`);
4635
4759
  function isArray(value) {
4636
4760
  return value !== null && Array.isArray(value);
4637
4761
  }
4638
- function isRecord(value) {
4639
- return typeof value == "object" && value !== null;
4640
- }
4641
4762
  function walkMap(value, mappingFn, path = []) {
4642
4763
  if (isArray(value))
4643
4764
  return value.map((v, idx) => {
@@ -5986,6 +6107,8 @@ ${selectionOpts}`);
5986
6107
  exports.connectEventSource = connectEventSource;
5987
6108
  exports.createClient = createClient;
5988
6109
  exports.default = deprecatedCreateClient;
6110
+ exports.formatQueryParseError = formatQueryParseError;
6111
+ exports.isQueryParseError = isQueryParseError;
5989
6112
  exports.requester = requester;
5990
6113
  exports.unstable__adapter = c$2;
5991
6114
  exports.unstable__environment = f$1;