@sanity/client 8.0.0 → 8.1.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 (54) hide show
  1. package/README.md +94 -0
  2. package/dist/{browserUpload-CQgx9YYo.js → browserUpload-2tz6Sdqp.js} +4 -3
  3. package/dist/browserUpload-2tz6Sdqp.js.map +1 -0
  4. package/dist/{browserUpload-icWlVP15.js → browserUpload-CwpNx7Vl.js} +4 -3
  5. package/dist/browserUpload-CwpNx7Vl.js.map +1 -0
  6. package/dist/{config-a8VajuEY.js → config-3wiPP-sZ.js} +2 -2
  7. package/dist/config-3wiPP-sZ.js.map +1 -0
  8. package/dist/csm.js +2 -2
  9. package/dist/csm.js.map +1 -1
  10. package/dist/index.d.ts +17 -11
  11. package/dist/index.js +247 -120
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.node.d.ts +270 -26
  14. package/dist/index.node.js +183 -50
  15. package/dist/index.node.js.map +1 -1
  16. package/dist/media-library.d.ts +1 -1
  17. package/dist/{request-CJxcN16k.js → request-BhMuKj0D.js} +10 -9
  18. package/dist/request-BhMuKj0D.js.map +1 -0
  19. package/dist/{request-k7VS_NnC.js → request-SnMg7nUX.js} +10 -9
  20. package/dist/request-SnMg7nUX.js.map +1 -0
  21. package/dist/{resolveEditInfo-sq7yF78q.js → resolveEditInfo-Cz-smq3a.js} +17 -3
  22. package/dist/resolveEditInfo-Cz-smq3a.js.map +1 -0
  23. package/dist/stega.js +1 -1
  24. package/dist/{stegaEncodeSourceMap-DkoIlutY.js → stegaEncodeSourceMap-DbM2fTN4.js} +8 -2
  25. package/dist/stegaEncodeSourceMap-DbM2fTN4.js.map +1 -0
  26. package/dist/{stegaEncodeSourceMap-B2fGArSf.js → stegaEncodeSourceMap-YR3NQ3iz.js} +2 -2
  27. package/dist/{stegaEncodeSourceMap-B2fGArSf.js.map → stegaEncodeSourceMap-YR3NQ3iz.js.map} +1 -1
  28. package/dist/{types-CUxZSgB2.d.ts → types-BODIEY7F.d.ts} +262 -24
  29. package/package.json +26 -11
  30. package/src/SanityClient.ts +19 -20
  31. package/src/assets/AssetsClient.ts +54 -5
  32. package/src/csm/applySourceDocuments.ts +2 -4
  33. package/src/csm/draftUtils.ts +23 -4
  34. package/src/data/dataMethods.ts +2 -19
  35. package/src/data/eventsource.ts +71 -41
  36. package/src/data/live.ts +17 -9
  37. package/src/data/resolveEventSourceFetch.ts +9 -1
  38. package/src/defineCreateClient.ts +5 -1
  39. package/src/functions/FunctionsClient.ts +66 -0
  40. package/src/functions/invoke.ts +176 -0
  41. package/src/http/browserUpload.ts +1 -0
  42. package/src/http/errors.ts +2 -1
  43. package/src/http/request.ts +8 -14
  44. package/src/mediaLibrary/MediaLibraryVideoClient.ts +1 -1
  45. package/src/types.ts +186 -4
  46. package/src/validators.ts +1 -1
  47. package/src/warnings.ts +7 -1
  48. package/dist/browserUpload-CQgx9YYo.js.map +0 -1
  49. package/dist/browserUpload-icWlVP15.js.map +0 -1
  50. package/dist/config-a8VajuEY.js.map +0 -1
  51. package/dist/request-CJxcN16k.js.map +0 -1
  52. package/dist/request-k7VS_NnC.js.map +0 -1
  53. package/dist/resolveEditInfo-sq7yF78q.js.map +0 -1
  54. package/dist/stegaEncodeSourceMap-DkoIlutY.js.map +0 -1
package/src/types.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  // deno-lint-ignore-file no-empty-interface
2
2
 
3
- import type {FetchFunction} from 'get-it'
3
+ import type {FetchFunction, RequestOptions as GetItRequestOptions} from 'get-it'
4
4
  import type {Observable} from 'rxjs'
5
5
 
6
6
  import type {InitializedStegaConfig, StegaConfig} from './stega/types'
7
7
 
8
8
  /**
9
- * Low-level requester returned by `defineHttpRequest`. Surfaces as
10
- * `client.config().requester` and as the named `requester` export.
9
+ * Low-level requester returned by `defineRequester(...).observable`.
10
+ * Surfaces as `client.config().requester` and as the named `requester`
11
+ * export.
11
12
  *
12
13
  * Defined locally rather than imported from `http/request` so api-extractor
13
14
  * inlines it into the bundled `.d.ts` instead of emitting a relative import
@@ -45,6 +46,30 @@ export interface RequestOptions {
45
46
  signal?: AbortSignal
46
47
  }
47
48
 
49
+ /**
50
+ * The fully resolved request passed to a {@link RequestHandler}.
51
+ *
52
+ * @public
53
+ */
54
+ export type RequestHandlerOptions = GetItRequestOptions
55
+
56
+ /**
57
+ * Intercepts a client request around the normal HTTP pipeline.
58
+ *
59
+ * Call `next(request)` to execute the request. It resolves to the parsed
60
+ * response body and rejects with the same errors the client normally exposes,
61
+ * including {@link ClientError} and {@link ServerError}. A handler can modify
62
+ * the request, retry it by calling `next` again, or return a synthetic body.
63
+ *
64
+ * Browser asset uploads and server-sent event connections do not use this handler.
65
+ *
66
+ * @public
67
+ */
68
+ export type RequestHandler = (
69
+ request: RequestHandlerOptions,
70
+ next: (request: RequestHandlerOptions) => Promise<unknown>,
71
+ ) => Promise<unknown>
72
+
48
73
  /**
49
74
  * @public
50
75
  * @deprecated – The `r`-prefix is not required, use `string` instead
@@ -159,6 +184,20 @@ export interface ClientConfig {
159
184
  */
160
185
  requestTagPrefix?: string
161
186
 
187
+ /**
188
+ * Intercepts requests after the client has resolved their URL, headers, and
189
+ * transport options. The handler wraps the normal client pipeline, so errors
190
+ * from `next` are already converted to {@link ClientError} or
191
+ * {@link ServerError}.
192
+ *
193
+ * A handler supplied through `withConfig()` replaces the current handler.
194
+ * To compose handlers, read the current handler from `client.config()` and
195
+ * call it from the replacement.
196
+ *
197
+ * Browser asset uploads and server-sent event connections are not intercepted.
198
+ */
199
+ requestHandler?: RequestHandler
200
+
162
201
  /**
163
202
  * Optional default headers to include with all requests
164
203
  *
@@ -256,6 +295,15 @@ export interface ClientConfig {
256
295
  * Lineage token for recursion control
257
296
  */
258
297
  lineage?: string
298
+ /**
299
+ * ID of the blueprints stack that `functions.invoke()` resolves function
300
+ * names against. Function names are unique within a stack
301
+ */
302
+ stackId?: string
303
+ /**
304
+ * ID of the organization owning the blueprints stack
305
+ */
306
+ organizationId?: string
259
307
  }
260
308
 
261
309
  /** @public */
@@ -484,7 +532,7 @@ export interface ErrorProps {
484
532
  * @internal
485
533
  */
486
534
  export type HttpRequest = {
487
- (options: Any): Promise<unknown>
535
+ (options: Any, requestHandler?: RequestHandler): Promise<unknown>
488
536
  }
489
537
 
490
538
  /**
@@ -776,6 +824,15 @@ export type ReleaseAction =
776
824
  | DeleteReleaseAction
777
825
  | ImportReleaseAction
778
826
 
827
+ /**
828
+ * @public
829
+ * @beta
830
+ */
831
+ export type VariantDefinitionAction =
832
+ | CreateVariantDefinitionAction
833
+ | EditVariantDefinitionAction
834
+ | DeleteVariantDefinitionAction
835
+
779
836
  /** @public */
780
837
  export type VersionAction =
781
838
  | CreateVersionAction
@@ -794,6 +851,7 @@ export type Action =
794
851
  | UnpublishAction
795
852
  | VersionAction
796
853
  | ReleaseAction
854
+ | VariantDefinitionAction
797
855
 
798
856
  /** @public */
799
857
  export type ImportReleaseAction =
@@ -951,6 +1009,88 @@ export interface UnpublishVersionAction {
951
1009
  publishedId: string
952
1010
  }
953
1011
 
1012
+ /**
1013
+ * Creates a new `system.variant` definition document.
1014
+ *
1015
+ * @public
1016
+ * @beta
1017
+ */
1018
+ export interface CreateVariantDefinitionAction {
1019
+ actionType: 'sanity.action.variant.definition.create'
1020
+
1021
+ /**
1022
+ * Name of the variant definition to create, as in
1023
+ * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
1024
+ */
1025
+ variantId: string
1026
+
1027
+ /**
1028
+ * Conditions used to select this variant.
1029
+ */
1030
+ conditions?: ClientVariantConditions
1031
+
1032
+ /**
1033
+ * Selection priority. Higher values are preferred when multiple variants
1034
+ * match.
1035
+ *
1036
+ * Defaults to `0`.
1037
+ */
1038
+ priority?: number
1039
+
1040
+ metadata?: Record<string, Any>
1041
+ }
1042
+
1043
+ /**
1044
+ * Edits an existing variant definition.
1045
+ *
1046
+ * @public
1047
+ * @beta
1048
+ */
1049
+ export interface EditVariantDefinitionAction {
1050
+ actionType: 'sanity.action.variant.definition.edit'
1051
+
1052
+ /**
1053
+ * Name of the variant definition to edit, as in `_.variants.{variantName}`.
1054
+ * Must be a bare name, not a full document ID.
1055
+ */
1056
+ variantId: string
1057
+
1058
+ /**
1059
+ * Patch operations to apply.
1060
+ */
1061
+ patch: PatchOperations
1062
+
1063
+ /**
1064
+ * When set, the action fails unless the current revision of the variant
1065
+ * definition matches this value.
1066
+ */
1067
+ ifRevisionId?: string
1068
+ }
1069
+
1070
+ /**
1071
+ * Deletes a variant definition.
1072
+ *
1073
+ * Deletion fails if any document holds a strong reference to this variant.
1074
+ *
1075
+ * @public
1076
+ * @beta
1077
+ */
1078
+ export interface DeleteVariantDefinitionAction {
1079
+ actionType: 'sanity.action.variant.definition.delete'
1080
+
1081
+ /**
1082
+ * Name of the variant definition to delete, as in
1083
+ * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
1084
+ */
1085
+ variantId: string
1086
+
1087
+ /**
1088
+ * When set, the action fails unless the current revision of the variant
1089
+ * definition matches this value.
1090
+ */
1091
+ ifRevisionId?: string
1092
+ }
1093
+
954
1094
  /**
955
1095
  * Creates a new draft document. The published version of the document must not already exist.
956
1096
  * If the draft version of the document already exists the action will fail by default, but
@@ -1938,6 +2078,7 @@ export type {
1938
2078
  TranslateTarget,
1939
2079
  TranslateTargetInclude,
1940
2080
  } from './agent/actions/translate'
2081
+ export type {InvokeFunctionEvent, InvokeFunctionRequest} from './functions/invoke'
1941
2082
  export type {
1942
2083
  ContentSourceMapParsedPath,
1943
2084
  ContentSourceMapParsedPathKeyedSegment,
@@ -2159,3 +2300,44 @@ export interface VideoPlaybackTokens {
2159
2300
 
2160
2301
  /** @public */
2161
2302
  export type MediaLibraryAssetInstanceIdentifier = string | SanityReference
2303
+
2304
+ /**
2305
+ * A single tracked version of a Media Library asset - one uploaded instance,
2306
+ * referencing the underlying (Content Lake shaped) asset document it wraps.
2307
+ *
2308
+ * @public
2309
+ */
2310
+ export interface MediaLibraryAssetVersion {
2311
+ _key: string
2312
+ _type: 'sanity.asset.version'
2313
+ title?: string
2314
+ instance: SanityReference
2315
+ }
2316
+
2317
+ /**
2318
+ * The document returned by the Media Library upload endpoint
2319
+ * (`POST /media-libraries/:id/upload`).
2320
+ *
2321
+ * This is _not_ the same shape as {@link SanityAssetDocument} /
2322
+ * {@link SanityImageAssetDocument}: a Media Library asset is a `sanity.asset`
2323
+ * document that tracks one or more uploaded versions, each pointing at its
2324
+ * own underlying Content Lake asset document via `currentVersion`/`versions`.
2325
+ *
2326
+ * Modelled directly on an observed API response. Fields whose full shape has
2327
+ * not been confirmed (`parent`, `rootDirectory`, `aspects`) are typed loosely
2328
+ * on purpose - widen them once their shape is confirmed.
2329
+ *
2330
+ * @public
2331
+ */
2332
+ export interface MediaLibraryAssetDocument {
2333
+ _id: string
2334
+ _type: 'sanity.asset'
2335
+ assetType: string
2336
+ title?: string
2337
+ cdnAccessPolicy?: string
2338
+ currentVersion: SanityReference
2339
+ versions: MediaLibraryAssetVersion[]
2340
+ aspects?: Record<string, Any>
2341
+ parent?: SanityReference | null
2342
+ rootDirectory?: Any
2343
+ }
package/src/validators.ts CHANGED
@@ -43,7 +43,7 @@ export const requireDocumentId = (op: string, doc: Record<string, Any>) => {
43
43
  validateDocumentId(op, doc._id)
44
44
  }
45
45
 
46
- export const validateDocumentType = (op: string, type: string) => {
46
+ const validateDocumentType = (op: string, type: string) => {
47
47
  if (typeof type !== 'string') {
48
48
  throw new Error(`\`${op}()\`: \`${type}\` is not a valid document type`)
49
49
  }
package/src/warnings.ts CHANGED
@@ -47,8 +47,14 @@ export const printNoDefaultExport = createWarningPrinter([
47
47
  'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',
48
48
  ])
49
49
 
50
+ // Phrased as a condition rather than as a correction, because the client cannot
51
+ // tell the two cases apart. `baseId` creates a version of a document that
52
+ // already exists, so a caller creating a genuinely new document inside a release
53
+ // has no alternative to `document` - and the previous wording told them they had
54
+ // picked the wrong approach when they had not.
50
55
  export const printCreateVersionWithBaseIdWarning = createWarningPrinter([
51
- 'You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead.',
56
+ 'You have called `createVersion()` with a defined `document`.',
57
+ 'If you are creating a version of a document that already exists, prefer providing `baseId` and `releaseId` instead.',
52
58
  ])
53
59
 
54
60
  export const printDeprecatedUriOptionWarning = createWarningPrinter([
@@ -1 +0,0 @@
1
- {"version":3,"file":"browserUpload-CQgx9YYo.js","names":[],"sources":["../src/http/browserUpload.ts"],"sourcesContent":["import {createDebug} from 'obug'\nimport {Observable} from 'rxjs'\n\nimport type {UploadEvent} from '../types'\nimport {ClientError, httpResponseFromFetch, ServerError} from './errors'\nimport {parseJsonText} from './request'\n\nconst log = createDebug('sanity:client')\n\nlet nextRequestId = 1\n\n/**\n * Options for a browser-side asset upload that needs progress events.\n *\n * @internal\n */\nexport interface BrowserUploadOptions {\n url: string\n method: string\n headers: Record<string, string>\n body: unknown\n withCredentials: boolean\n /** Milliseconds before the upload is aborted; `false` and `0` both disable the timeout. */\n timeout?: number | false\n signal?: AbortSignal\n}\n\n/**\n * Run an asset upload through `XMLHttpRequest` so we can surface per-chunk\n * upload progress events. get-it v9 / fetch has no equivalent hook in the\n * browser, so the observable asset-upload API falls back to this path when\n * `XMLHttpRequest` is available.\n *\n * @internal\n */\nexport function uploadWithProgress<T>(options: BrowserUploadOptions): Observable<UploadEvent<T>> {\n return new Observable<UploadEvent<T>>((subscriber) => {\n const xhr = new XMLHttpRequest()\n const requestId = nextRequestId++\n const {url, method, headers, body, withCredentials, timeout, signal} = options\n\n log('[%d] %s %s (XHR upload with progress)', requestId, method, url)\n\n xhr.open(method, url)\n xhr.withCredentials = withCredentials\n if (typeof timeout === 'number' && timeout > 0) {\n xhr.timeout = timeout\n }\n\n for (const [key, value] of Object.entries(headers)) {\n xhr.setRequestHeader(key, value)\n }\n\n xhr.upload.onprogress = (e) => {\n subscriber.next({\n type: 'progress',\n stage: 'upload',\n percent: e.lengthComputable ? Math.round((e.loaded / e.total) * 100) : 0,\n total: e.total || undefined,\n loaded: e.loaded,\n lengthComputable: e.lengthComputable,\n })\n }\n\n xhr.onload = () => {\n log('[%d] %s %s — %d', requestId, method, url, xhr.status)\n\n if (xhr.status >= 400) {\n // Same typed errors as the fetch transport, so consumers can keep\n // detecting `ClientError`/`ServerError` and reading `statusCode`,\n // `responseBody` and the structured API `details` on failed uploads.\n const errorHeaders = parseXhrResponseHeaders(xhr.getAllResponseHeaders())\n const canonical = httpResponseFromFetch(\n {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: errorHeaders,\n body: parseJsonText(xhr.responseText, errorHeaders),\n },\n url,\n method,\n )\n subscriber.error(\n xhr.status >= 500 ? new ServerError(canonical) : new ClientError(canonical),\n )\n return\n }\n\n let responseBody: T\n try {\n responseBody = JSON.parse(xhr.responseText) as T\n } catch {\n subscriber.error(new Error('Failed to parse upload response as JSON'))\n return\n }\n\n subscriber.next({type: 'response', body: responseBody})\n subscriber.complete()\n }\n\n xhr.onerror = () => {\n log('[%d] %s %s — network error', requestId, method, url)\n subscriber.error(new Error('XHR upload network error'))\n }\n\n xhr.ontimeout = () => {\n log('[%d] %s %s — timed out after %dms', requestId, method, url, timeout)\n // Same error shape as the fetch transport's timeout rejection.\n subscriber.error(\n new DOMException(\n `The operation timed out after ${timeout}ms while attempting to reach ${url}`,\n 'TimeoutError',\n ),\n )\n }\n\n xhr.onabort = () => {\n subscriber.error(new DOMException('Upload aborted', 'AbortError'))\n }\n\n const onSignalAbort = () => xhr.abort()\n if (signal) {\n if (signal.aborted) {\n // `xhr.abort()` before `send()` fires no `abort` event per spec, so\n // error out directly instead of relying on `onabort`.\n subscriber.error(new DOMException('Upload aborted', 'AbortError'))\n return undefined\n }\n signal.addEventListener('abort', onSignalAbort, {once: true})\n }\n\n xhr.send(body as XMLHttpRequestBodyInit)\n\n // Unsubscribing cancels the in-flight upload, mirroring how the fetch\n // path aborts its request (`_observe`). After settle this is a no-op —\n // except for detaching from the caller's signal, which may be long-lived\n // and must not accumulate a listener per upload.\n return () => {\n signal?.removeEventListener('abort', onSignalAbort)\n xhr.abort()\n }\n })\n}\n\n/**\n * Parse `XMLHttpRequest.getAllResponseHeaders()` output (CRLF-separated\n * `name: value` lines) into a `Headers` instance.\n */\nfunction parseXhrResponseHeaders(raw: string): Headers {\n const headers = new Headers()\n for (const line of raw.split('\\r\\n')) {\n const separator = line.indexOf(':')\n if (separator <= 0) continue\n try {\n headers.append(line.slice(0, separator).trim(), line.slice(separator + 1).trim())\n } catch {\n // Skip header lines the Headers constructor rejects — better a partial\n // header record on the error than no error details at all.\n }\n }\n return headers\n}\n"],"mappings":";;;AAOA,MAAM,MAAM,YAAY,eAAe;AAEvC,IAAI,gBAAgB;;;;;;;;;AA0BpB,SAAgB,mBAAsB,SAA2D;CAC/F,OAAO,IAAI,YAA4B,eAAe;EACpD,IAAM,MAAM,IAAI,eAAe,GACzB,YAAY,iBACZ,EAAC,KAAK,QAAQ,SAAS,MAAM,iBAAiB,SAAS,WAAU;EAMvE,AAJA,IAAI,yCAAyC,WAAW,QAAQ,GAAG,GAEnE,IAAI,KAAK,QAAQ,GAAG,GACpB,IAAI,kBAAkB,iBAClB,OAAO,WAAY,YAAY,UAAU,MAC3C,IAAI,UAAU;EAGhB,KAAK,IAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC/C,IAAI,iBAAiB,KAAK,KAAK;EAkEjC,AA/DA,IAAI,OAAO,cAAc,MAAM;GAC7B,WAAW,KAAK;IACd,MAAM;IACN,OAAO;IACP,SAAS,EAAE,mBAAmB,KAAK,MAAO,EAAE,SAAS,EAAE,QAAS,GAAG,IAAI;IACvE,OAAO,EAAE,SAAS,KAAA;IAClB,QAAQ,EAAE;IACV,kBAAkB,EAAE;GACtB,CAAC;EACH,GAEA,IAAI,eAAe;GAGjB,IAFA,IAAI,mBAAmB,WAAW,QAAQ,KAAK,IAAI,MAAM,GAErD,IAAI,UAAU,KAAK;IAIrB,IAAM,eAAe,wBAAwB,IAA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AAK,QAAQ,GAAG;EAC9B,mBAAa,IACjB,IAAI;GACF,QAAQ,OAAO,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC,KAAK,GAAG,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC;EAClF,QAAQ,CAGR;CACF;CACA,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"browserUpload-icWlVP15.js","names":[],"sources":["../src/http/browserUpload.ts"],"sourcesContent":["import {createDebug} from 'obug'\nimport {Observable} from 'rxjs'\n\nimport type {UploadEvent} from '../types'\nimport {ClientError, httpResponseFromFetch, ServerError} from './errors'\nimport {parseJsonText} from './request'\n\nconst log = createDebug('sanity:client')\n\nlet nextRequestId = 1\n\n/**\n * Options for a browser-side asset upload that needs progress events.\n *\n * @internal\n */\nexport interface BrowserUploadOptions {\n url: string\n method: string\n headers: Record<string, string>\n body: unknown\n withCredentials: boolean\n /** Milliseconds before the upload is aborted; `false` and `0` both disable the timeout. */\n timeout?: number | false\n signal?: AbortSignal\n}\n\n/**\n * Run an asset upload through `XMLHttpRequest` so we can surface per-chunk\n * upload progress events. get-it v9 / fetch has no equivalent hook in the\n * browser, so the observable asset-upload API falls back to this path when\n * `XMLHttpRequest` is available.\n *\n * @internal\n */\nexport function uploadWithProgress<T>(options: BrowserUploadOptions): Observable<UploadEvent<T>> {\n return new Observable<UploadEvent<T>>((subscriber) => {\n const xhr = new XMLHttpRequest()\n const requestId = nextRequestId++\n const {url, method, headers, body, withCredentials, timeout, signal} = options\n\n log('[%d] %s %s (XHR upload with progress)', requestId, method, url)\n\n xhr.open(method, url)\n xhr.withCredentials = withCredentials\n if (typeof timeout === 'number' && timeout > 0) {\n xhr.timeout = timeout\n }\n\n for (const [key, value] of Object.entries(headers)) {\n xhr.setRequestHeader(key, value)\n }\n\n xhr.upload.onprogress = (e) => {\n subscriber.next({\n type: 'progress',\n stage: 'upload',\n percent: e.lengthComputable ? Math.round((e.loaded / e.total) * 100) : 0,\n total: e.total || undefined,\n loaded: e.loaded,\n lengthComputable: e.lengthComputable,\n })\n }\n\n xhr.onload = () => {\n log('[%d] %s %s — %d', requestId, method, url, xhr.status)\n\n if (xhr.status >= 400) {\n // Same typed errors as the fetch transport, so consumers can keep\n // detecting `ClientError`/`ServerError` and reading `statusCode`,\n // `responseBody` and the structured API `details` on failed uploads.\n const errorHeaders = parseXhrResponseHeaders(xhr.getAllResponseHeaders())\n const canonical = httpResponseFromFetch(\n {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: errorHeaders,\n body: parseJsonText(xhr.responseText, errorHeaders),\n },\n url,\n method,\n )\n subscriber.error(\n xhr.status >= 500 ? new ServerError(canonical) : new ClientError(canonical),\n )\n return\n }\n\n let responseBody: T\n try {\n responseBody = JSON.parse(xhr.responseText) as T\n } catch {\n subscriber.error(new Error('Failed to parse upload response as JSON'))\n return\n }\n\n subscriber.next({type: 'response', body: responseBody})\n subscriber.complete()\n }\n\n xhr.onerror = () => {\n log('[%d] %s %s — network error', requestId, method, url)\n subscriber.error(new Error('XHR upload network error'))\n }\n\n xhr.ontimeout = () => {\n log('[%d] %s %s — timed out after %dms', requestId, method, url, timeout)\n // Same error shape as the fetch transport's timeout rejection.\n subscriber.error(\n new DOMException(\n `The operation timed out after ${timeout}ms while attempting to reach ${url}`,\n 'TimeoutError',\n ),\n )\n }\n\n xhr.onabort = () => {\n subscriber.error(new DOMException('Upload aborted', 'AbortError'))\n }\n\n const onSignalAbort = () => xhr.abort()\n if (signal) {\n if (signal.aborted) {\n // `xhr.abort()` before `send()` fires no `abort` event per spec, so\n // error out directly instead of relying on `onabort`.\n subscriber.error(new DOMException('Upload aborted', 'AbortError'))\n return undefined\n }\n signal.addEventListener('abort', onSignalAbort, {once: true})\n }\n\n xhr.send(body as XMLHttpRequestBodyInit)\n\n // Unsubscribing cancels the in-flight upload, mirroring how the fetch\n // path aborts its request (`_observe`). After settle this is a no-op —\n // except for detaching from the caller's signal, which may be long-lived\n // and must not accumulate a listener per upload.\n return () => {\n signal?.removeEventListener('abort', onSignalAbort)\n xhr.abort()\n }\n })\n}\n\n/**\n * Parse `XMLHttpRequest.getAllResponseHeaders()` output (CRLF-separated\n * `name: value` lines) into a `Headers` instance.\n */\nfunction parseXhrResponseHeaders(raw: string): Headers {\n const headers = new Headers()\n for (const line of raw.split('\\r\\n')) {\n const separator = line.indexOf(':')\n if (separator <= 0) continue\n try {\n headers.append(line.slice(0, separator).trim(), line.slice(separator + 1).trim())\n } catch {\n // Skip header lines the Headers constructor rejects — better a partial\n // header record on the error than no error details at all.\n }\n }\n return headers\n}\n"],"mappings":";;;AAOA,MAAM,MAAM,YAAY,eAAe;AAEvC,IAAI,gBAAgB;;;;;;;;;AA0BpB,SAAgB,mBAAsB,SAA2D;CAC/F,OAAO,IAAI,YAA4B,eAAe;EACpD,IAAM,MAAM,IAAI,eAAe,GACzB,YAAY,iBACZ,EAAC,KAAK,QAAQ,SAAS,MAAM,iBAAiB,SAAS,WAAU;EAMvE,AAJA,IAAI,yCAAyC,WAAW,QAAQ,GAAG,GAEnE,IAAI,KAAK,QAAQ,GAAG,GACpB,IAAI,kBAAkB,iBAClB,OAAO,WAAY,YAAY,UAAU,MAC3C,IAAI,UAAU;EAGhB,KAAK,IAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC/C,IAAI,iBAAiB,KAAK,KAAK;EAkEjC,AA/DA,IAAI,OAAO,cAAc,MAAM;GAC7B,WAAW,KAAK;IACd,MAAM;IACN,OAAO;IACP,SAAS,EAAE,mBAAmB,KAAK,MAAO,EAAE,SAAS,EAAE,QAAS,GAAG,IAAI;IACvE,OAAO,EAAE,SAAS,KAAA;IAClB,QAAQ,EAAE;IACV,kBAAkB,EAAE;GACtB,CAAC;EACH,GAEA,IAAI,eAAe;GAGjB,IAFA,IAAI,mBAAmB,WAAW,QAAQ,KAAK,IAAI,MAAM,GAErD,IAAI,UAAU,KAAK;IAIrB,IAAM,eAAe,wBAAwB,IAAI,sBAAsB,CAAC,GACl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C9B,mBAAa,IACjB,IAAI;GACF,QAAQ,OAAO,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC,KAAK,GAAG,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC;EAClF,QAAQ,CAGR;CACF;CACA,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"config-a8VajuEY.js","names":["resourceConfig","validate.requestTag"],"sources":["../src/generateHelpUrl.ts","../src/validators.ts","../src/util/once.ts","../src/warnings.ts","../src/config.ts"],"sourcesContent":["const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig, SanityDocumentStub} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateDocumentType = (op: string, type: string) => {\n if (typeof type !== 'string') {\n throw new Error(`\\`${op}()\\`: \\`${type}\\` is not a valid document type`)\n }\n}\n\nexport const requireDocumentType = (op: string, doc: Record<string, Any>) => {\n if (!doc._type) {\n throw new Error(`\\`${op}()\\` requires that the document contains a type (\\`_type\\` property)`)\n }\n\n validateDocumentType(op, doc._type)\n}\n\nexport const validateVersionIdMatch = (builtVersionId: string, document: SanityDocumentStub) => {\n if (document._id && document._id !== builtVersionId) {\n throw new Error(\n `The provided document ID (\\`${document._id}\\`) does not match the generated version ID (\\`${builtVersionId}\\`)`,\n )\n }\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n // Check if dataset is directly on the config\n if (config.dataset) {\n return config.dataset\n }\n\n // Check if dataset is in resource configuration\n // Note: ~experimental_resource is normalized to resource during client initialization\n const resource = config.resource\n if (resource && resource.type === 'dataset') {\n const segments = resource.id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"')\n }\n return segments[1]\n }\n\n throw new Error('`dataset` must be provided to perform queries')\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n\nexport const resourceConfig = (config: InitializedClientConfig): void => {\n // Note: ~experimental_resource is normalized to resource during client initialization\n const resource = config.resource\n if (!resource) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = resource\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"')\n }\n return\n }\n case 'dashboard':\n case 'media-library':\n case 'canvas': {\n return\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n\nexport const resourceGuard = (service: string, config: InitializedClientConfig): void => {\n // Note: ~experimental_resource is normalized to resource during client initialization\n const resource = config.resource\n if (resource) {\n throw new Error(`\\`${service}\\` does not support resource-based operations`)\n }\n}\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // oxlint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`drafts\\` or \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printPreviewDraftsDeprecationWarning = createWarningPrinter([\n `The \\`previewDrafts\\` perspective has been renamed to \\`drafts\\` and will be removed in a future API version`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printCredentialedTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token, but also provided `withCredentials: true`.',\n 'This is no longer supported - only token will be used - remove `withCredentials: true`.',\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n\nexport const printCreateVersionWithBaseIdWarning = createWarningPrinter([\n 'You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead.',\n])\n\nexport const printDeprecatedUriOptionWarning = createWarningPrinter([\n 'The `uri` request option has been renamed to `url`.',\n 'Please update your code to use `url` instead. Support for `uri` will be removed in a future version.',\n])\n\nexport const printDeprecatedResourceConfigWarning = createWarningPrinter([\n 'The `~experimental_resource` configuration property has been renamed to `resource`.',\n 'Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective) && perspective.length > 1 && perspective.includes('raw')) {\n throw new TypeError(\n `Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives`,\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n\n // Normalize resource configuration - prefer `resource` over deprecated `~experimental_resource`\n if (newConfig['~experimental_resource'] && !newConfig.resource) {\n warnings.printDeprecatedResourceConfigWarning()\n newConfig.resource = newConfig['~experimental_resource']\n }\n\n const resourceConfig = newConfig.resource\n const projectBased = newConfig.useProjectHostname && !resourceConfig\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (resourceConfig) {\n validate.resourceConfig(newConfig)\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n const hasToken = Boolean(newConfig.token)\n if (newConfig.withCredentials && hasToken) {\n warnings.printCredentialedTokenWarning()\n newConfig.withCredentials = false\n }\n\n if (isBrowser && isLocalhost && hasToken && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (projectBased) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n"],"mappings":"AAEA,SAAgB,gBAAgB,MAAc;CAC5C,OAAO,gCAAW;AACpB;ACFA,MAAM,oBAAoB,CAAC,SAAS,MAAM,GACpC,yBAAyB;CAAC;CAAU;CAAS;AAAS,GAE/C,WAAW,SAAiB;CACvC,IAAI,CAAC,qDAAqD,KAAK,IAAI,GACjE,MAAU,MACR,qIACF;AAEJ,GAEa,aAAa,OAAe;CACvC,IAAI,CAAC,gBAAgB,KAAK,EAAE,GAC1B,MAAU,MAAM,uDAAuD;AAE3E,GAEa,qBAAqB,SAAiB;CACjD,IAAI,kBAAkB,QAAQ,IAAI,MAAM,IACtC,MAAU,MAAM,uBAAuB,KAAK,mBAAmB,kBAAkB,KAAK,IAAI,GAAG;AAEjG,GAEa,kBAAkB,IAAY,QAAa;CACtD,IAAoB,OAAO,OAAQ,aAA/B,OAA2C,MAAM,QAAQ,GAAG,GAC9D,MAAU,MAAM,GAAG,GAAG,iCAAiC;AAE3D,GAEa,sBAAsB,IAAY,OAAe;CAC5D,IAAI,OAAO,MAAO,YAAY,CAAC,iCAAiC,KAAK,EAAE,KAAK,GAAG,SAAS,IAAI,GAC1F,MAAU,MAAM,GAAG,GAAG,OAAO,GAAG,6BAA6B;AAEjE,G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1D,OARI,gBACF,UAAU,MAAM,GAAG,SAAS,KAAK,UAAU,UAAU,GAAG,KAAK,IAAI,UAAU,cAC3E,UAAU,SAAS,GAAG,SAAS,KAAK,UAAU,UAAU,GAAG,QAAQ,IAAI,UAAU,iBAEjF,UAAU,MAAM,GAAG,UAAU,QAAQ,IAAI,UAAU,cACnD,UAAU,SAAS,UAAU,MAGxB;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"request-CJxcN16k.js","names":["headersToRecord","GetItHttpError"],"sources":["../src/util/codeFrame.ts","../src/http/errors.ts","../src/http/request.ts"],"sourcesContent":["/**\n * Inlined, modified version of the `codeFrameColumns` function from `@babel/code-frame`.\n * MIT-licensed - https://github.com/babel/babel/blob/main/LICENSE\n * Copyright (c) 2014-present Sebastian McKenzie and other contributors.\n */\ntype Location = {\n column: number\n line: number\n}\n\ntype NodeLocation = {\n start: Location\n end?: Location\n}\n\ntype GroqLocation = {\n start: number\n end?: number\n}\n\n/**\n * RegExp to test for newlines.\n */\n\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/\n\n/**\n * Extract what lines should be marked and highlighted.\n */\n\ntype MarkerLines = Record<number, true | [number, number]>\n\n/**\n * Highlight a code frame with the given location and message.\n *\n * @param query - The query to be highlighted.\n * @param location - The location of the error in the code/query.\n * @param message - Message to be displayed inline (if possible) next to the highlighted\n * location in the code. If it can't be positioned inline, it will be placed above the\n * code frame.\n * @returns The highlighted code frame.\n */\nexport function codeFrame(query: string, location: GroqLocation, message?: string): string {\n const lines = query.split(NEWLINE)\n const loc = {\n start: columnToLine(location.start, lines),\n end: location.end ? columnToLine(location.end, lines) : undefined,\n }\n\n const {start, end, markerLines} = getMarkerLines(loc, lines)\n\n const numberMaxWidth = `${end}`.length\n\n return query\n .split(NEWLINE, end)\n .slice(start, end)\n .map((line, index) => {\n const number = start + 1 + index\n const paddedNumber = ` ${number}`.slice(-numberMaxWidth)\n const gutter = ` ${paddedNumber} |`\n const hasMarker = markerLines[number]\n const lastMarkerLine = !markerLines[number + 1]\n if (!hasMarker) {\n return ` ${gutter}${line.length > 0 ? ` ${line}` : ''}`\n }\n\n let markerLine = ''\n if (Array.isArray(hasMarker)) {\n const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\\t]/g, ' ')\n const numberOfMarkers = hasMarker[1] || 1\n\n markerLine = [\n '\\n ',\n gutter.replace(/\\d/g, ' '),\n ' ',\n markerSpacing,\n '^'.repeat(numberOfMarkers),\n ].join('')\n\n if (lastMarkerLine && message) {\n markerLine += ' ' + message\n }\n }\n return ['>', gutter, line.length > 0 ? ` ${line}` : '', markerLine].join('')\n })\n .join('\\n')\n}\n\nfunction getMarkerLines(\n loc: NodeLocation,\n source: Array<string>,\n): {\n start: number\n end: number\n markerLines: MarkerLines\n} {\n const startLoc: Location = {...loc.start}\n const endLoc: Location = {...startLoc, ...loc.end}\n const linesAbove = 2\n const linesBelow = 3\n const startLine = startLoc.line ?? -1\n const startColumn = startLoc.column ?? 0\n const endLine = endLoc.line\n const endColumn = endLoc.column\n\n let start = Math.max(startLine - (linesAbove + 1), 0)\n let end = Math.min(source.length, endLine + linesBelow)\n\n if (startLine === -1) {\n start = 0\n }\n\n if (endLine === -1) {\n end = source.length\n }\n\n const lineDiff = endLine - startLine\n const markerLines: MarkerLines = {}\n\n if (lineDiff) {\n for (let i = 0; i <= lineDiff; i++) {\n const lineNumber = i + startLine\n\n if (!startColumn) {\n markerLines[lineNumber] = true\n } else if (i === 0) {\n const sourceLength = source[lineNumber - 1].length\n\n markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]\n } else if (i === lineDiff) {\n markerLines[lineNumber] = [0, endColumn]\n } else {\n const sourceLength = source[lineNumber - i].length\n\n markerLines[lineNumber] = [0, sourceLength]\n }\n }\n } else {\n if (startColumn === endColumn) {\n if (startColumn) {\n markerLines[startLine] = [startColumn, 0]\n } else {\n markerLines[startLine] = true\n }\n } else {\n markerLines[startLine] = [startColumn, endColumn - startColumn]\n }\n }\n\n return {start, end, markerLines}\n}\n\nfunction columnToLine(column: number, lines: string[]): Location {\n let offset = 0\n\n for (let i = 0; i < lines.length; i++) {\n const lineLength = lines[i].length + 1 // assume '\\n' after each line\n\n if (offset + lineLength > column) {\n return {\n line: i + 1, // 1-based line\n column: column - offset, // 0-based column\n }\n }\n\n offset += lineLength\n }\n\n // Fallback: beyond last line\n return {\n line: lines.length,\n column: lines[lines.length - 1]?.length ?? 0,\n }\n}\n","import type {ActionError, Any, ErrorProps, MutationError, QueryParseError} from '../types'\nimport {codeFrame} from '../util/codeFrame'\nimport {isRecord} from '../util/isRecord'\n\nconst MAX_ITEMS_IN_ERROR_MESSAGE = 5\n\n/**\n * Canonical HTTP response shape used internally to build {@link ClientError}\n * and {@link ServerError}. Decouples the error layer from any particular\n * transport library — adapters in the HTTP layer (e.g. `httpResponseFromGetIt`)\n * project transport-specific response shapes into this stable form before\n * constructing errors.\n *\n * Matches the public {@link HttpError.response} shape so consumers see no\n * difference in error properties when the underlying transport changes.\n *\n * @internal\n */\nexport interface CanonicalHttpResponse {\n statusCode: number\n statusMessage: string | null\n headers: Record<string, string>\n body: unknown\n url: string\n method: string\n}\n\n/**\n * Adapter for buffered responses from get-it v9 (`BufferedResponse`-shaped).\n *\n * The URL and method aren't on the response itself in v9, so the request\n * options must be passed alongside.\n *\n * @internal\n */\nexport function httpResponseFromFetch(\n res: {\n status: number\n statusText: string\n headers: Headers\n body: unknown\n },\n reqUrl: string,\n reqMethod: string,\n): CanonicalHttpResponse {\n return {\n statusCode: res.status,\n statusMessage: res.statusText || null,\n headers: headersToRecord(res.headers),\n body: res.body,\n url: reqUrl,\n method: reqMethod,\n }\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/**\n * Shared properties for HTTP errors (eg both ClientError and ServerError)\n * Use `isHttpError` for type narrowing and accessing response properties.\n *\n * @public\n */\nexport interface HttpError {\n statusCode: number\n message: string\n response: {\n body: unknown\n url: string\n method: string\n headers: Record<string, string>\n statusCode: number\n statusMessage: string | null\n }\n}\n\n/**\n * Checks if the provided error is an HTTP error.\n *\n * @param error - The error to check.\n * @returns `true` if the error is an HTTP error, `false` otherwise.\n * @public\n */\nexport function isHttpError(error: unknown): error is HttpError {\n if (!isRecord(error)) {\n return false\n }\n\n const response = error.response\n if (\n typeof error.statusCode !== 'number' ||\n typeof error.message !== 'string' ||\n !isRecord(response)\n ) {\n return false\n }\n\n if (\n typeof response.body === 'undefined' ||\n typeof response.url !== 'string' ||\n typeof response.method !== 'string' ||\n typeof response.headers !== 'object' ||\n typeof response.statusCode !== 'number'\n ) {\n return false\n }\n\n return true\n}\n\n/** @public */\nexport class ClientError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 400\n responseBody: ErrorProps['responseBody']\n traceId: ErrorProps['traceId']\n details: ErrorProps['details']\n\n constructor(res: Any, tag?: string) {\n const props = extractErrorProps(res, tag)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\n/** @public */\nexport class ServerError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 500\n responseBody: ErrorProps['responseBody']\n traceId: ErrorProps['traceId']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\nfunction extractErrorProps(res: Any, tag?: string): ErrorProps {\n const body = res.body\n const props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n traceId: extractTraceId(res),\n message: '',\n details: undefined as Any,\n }\n\n // Fall back early if we didn't get a JSON object returned as expected\n if (!isRecord(body)) {\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n return props\n }\n\n const error = body.error\n\n // API/Boom style errors ({statusCode, error, message})\n if (typeof error === 'string' && typeof body.message === 'string') {\n props.message = `${error} - ${body.message}${formatTraceId(props.traceId)}`\n return props\n }\n\n // Content Lake errors with a `error` prop being an object\n if (typeof error !== 'object' || error === null) {\n if (typeof error === 'string') {\n props.message = `${error}${formatTraceId(props.traceId)}`\n } else if (typeof body.message === 'string') {\n props.message = `${body.message}${formatTraceId(props.traceId)}`\n } else {\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n }\n return props\n }\n\n // Mutation errors (specifically)\n if (isMutationError(error) || isActionError(error)) {\n const allItems = error.items || []\n const items = allItems\n .slice(0, MAX_ITEMS_IN_ERROR_MESSAGE)\n .map((item) => item.error?.description)\n .filter(Boolean)\n let itemsStr = items.length ? `:\\n- ${items.join('\\n- ')}` : ''\n if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {\n itemsStr += `\\n...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`\n }\n props.message = `${error.description}${formatTraceId(props.traceId)}${itemsStr}`\n props.details = body.error\n return props\n }\n\n // Query parse errors\n if (isQueryParseError(error)) {\n props.message = formatQueryParseError(error, tag, props.traceId)\n props.details = body.error\n return props\n }\n\n if ('description' in error && typeof error.description === 'string') {\n // Query/database errors ({error: {description, other, arb, props}})\n props.message = `${error.description}${formatTraceId(props.traceId)}`\n props.details = error\n return props\n }\n\n // Other, more arbitrary errors\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n return props\n}\n\nfunction isMutationError(error: object): error is MutationError {\n return (\n 'type' in error &&\n error.type === 'mutationError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\nfunction isActionError(error: object): error is ActionError {\n return (\n 'type' in error &&\n error.type === 'actionError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\n/** @internal */\nexport function isQueryParseError(error: object): error is QueryParseError {\n return (\n isRecord(error) &&\n error.type === 'queryParseError' &&\n typeof error.query === 'string' &&\n typeof error.start === 'number' &&\n typeof error.end === 'number'\n )\n}\n\n/**\n * Formats a GROQ query parse error into a human-readable string.\n *\n * @param error - The error object containing details about the parse error.\n * @param tag - An optional tag to include in the error message.\n * @returns A formatted error message string.\n * @public\n */\nexport function formatQueryParseError(\n error: QueryParseError,\n tag?: string | null,\n traceId?: string,\n) {\n const {query, start, end, description} = error\n const withTraceId = traceId ? `\\n(traceId: ${traceId})` : ''\n\n if (!query || typeof start === 'undefined') {\n return `GROQ query parse error: ${description}${withTraceId}`\n }\n\n const withTag = tag ? `\\n\\nTag: ${tag}` : ''\n const framed = codeFrame(query, {start, end}, description)\n\n return `GROQ query parse error:\\n${framed}${withTag}${withTraceId}`\n}\n\nfunction httpErrorMessage(res: Any, body: unknown) {\n const details = typeof body === 'string' ? ` (${sliceWithEllipsis(body, 100)})` : ''\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`\n}\n\n/**\n * Extract the traceId from the traceparent header on the response.\n *\n * The traceparent is on the format [version]-[traceId]-[parentId]-[traceFlags], but\n * when debugging end-user issues it's the traceId we need to be able to get hold of\n * the relevant traces.\n *\n * @see https://www.w3.org/TR/trace-context/\n * @returns The traceId for HTTP response\n */\nfunction extractTraceId(res: Any): string | undefined {\n const traceparent = res?.headers?.['traceparent']\n if (!traceparent) return\n\n return traceparent.split('-')[1]\n}\n\nfunction stringifyBody(body: Any, res: Any) {\n const contentType = (res.headers['content-type'] || '').toLowerCase()\n const isJson = contentType.indexOf('application/json') !== -1\n return isJson ? JSON.stringify(body, null, 2) : body\n}\n\nfunction formatTraceId(traceId: string | undefined): string {\n return traceId ? ` (traceId: ${traceId})` : ''\n}\n\nfunction sliceWithEllipsis(str: string, max: number) {\n return str.length > max ? `${str.slice(0, max)}…` : str\n}\n\n/** @public */\nexport class CorsOriginError extends Error {\n projectId?: string\n addOriginUrl?: URL\n\n constructor({projectId, credentials}: {projectId?: string; credentials?: boolean} = {}) {\n super('CorsOriginError')\n this.name = 'CorsOriginError'\n this.projectId = projectId\n\n // Only build a deep-link when we know which project the user needs to\n // configure - without `projectId` the management URL can't actually route\n // them anywhere useful.\n if (projectId && typeof location !== 'undefined') {\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n const {origin} = location\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n if (credentials) {\n // Pre-selects the \"Allow credentials (token-based auth)\" toggle in\n // the Sanity management CORS form.\n url.searchParams.set('credentials', '')\n }\n this.addOriginUrl = url\n this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`\n } else if (projectId) {\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: https://sanity.io/manage/project/${projectId}/api`\n } else {\n this.message = `The current origin is not allowed to connect to the Live Content API.`\n }\n }\n}\n","import {\n createRequester,\n type FetchFunction,\n HttpError as GetItHttpError,\n type RequestOptions as FetchRequestOptions,\n type TransformMiddleware,\n type WrappingMiddleware,\n} from 'get-it'\nimport {isRetryableRequest, retry} from 'get-it/middleware'\nimport {from, Observable} from 'rxjs'\n\nimport type {Any} from '../types'\nimport {ClientError, httpResponseFromFetch, ServerError} from './errors'\n\n/**\n * Middleware accepted by the internal HTTP layer. Two flavors per get-it v9:\n * a flat-pipeline transform (`beforeRequest`/`afterResponse`) or a wrapping\n * middleware that surrounds the fetch chain.\n *\n * @internal\n */\nexport type LegacyMiddleware = TransformMiddleware | WrappingMiddleware\n\n/**\n * The shape this client's internal pipeline produces. Mirrors the historical\n * `ResponseEvent` from the get-it v8 multi-event observable, so all the existing\n * downstream code (`_requestObservable`, `_uploadObservable`,\n * `defineCreateClient`) keeps working without churn.\n *\n * @internal\n */\nexport interface ResponseEvent {\n type: 'response'\n body: unknown\n statusCode: number\n statusMessage: string | null\n headers: Record<string, string>\n url: string\n method: string\n}\n\n/**\n * Legacy \"requester\" type — the result of `defineHttpRequest`. Returns a\n * single-event Observable for compatibility with the rest of the codebase.\n *\n * @internal\n */\nexport type LegacyRequester = (options: Any) => Observable<ResponseEvent>\n\n/**\n * Promise-based sibling of {@link LegacyRequester}. Resolves directly to the\n * single `ResponseEvent` the transport produces, skipping the RxJS wrapper.\n * Used by the promise-based client surface so it never constructs an\n * Observable.\n *\n * @internal\n */\nexport type PromiseRequester = (options: Any) => Promise<ResponseEvent>\n\n/**\n * Both forms of the transport, sharing a single underlying get-it requester\n * (so retry state and the one-shot warning de-duplication are shared between\n * the observable and promise paths).\n *\n * @internal\n */\nexport interface DualRequester {\n observable: LegacyRequester\n promise: PromiseRequester\n}\n\n/**\n * Options for tuning the HTTP request pipeline per-client.\n *\n * @internal\n */\nexport interface HttpRequestConfig {\n ignoreWarnings?: string | RegExp | Array<string | RegExp>\n maxRetries?: number\n retryDelay?: (attemptNumber: number) => number\n}\n\n/**\n * Build both the observable and promise transport forms from a single get-it\n * requester. The promise form is the primitive (`executeRequest` is already\n * promise-based); the observable form wraps it lazily so each subscription\n * starts its own request (cold), and unsubscribing aborts the in-flight\n * fetch — the same contract as the get-it v8 observable adapter.\n *\n * @internal\n */\nexport function defineRequester(\n envOptions: EnvironmentOptions,\n config: HttpRequestConfig = {},\n): DualRequester {\n // Framework-patched fetch implementations read extra `RequestInit` fields\n // for caching semantics — Next.js App Router's `cache` and `next` options in\n // particular. Legacy callers pass those via an object-valued `fetch` request\n // option (see `adaptToFetchOptions`, which stashes it in `meta.fetchInit`\n // since get-it v9's own `fetch` option only accepts a function). Merge them\n // into the init of whichever fetch implementation is effective for the\n // request: per-request/test-override fetch, the environment default, or the\n // global fetch.\n const applyFetchInit: WrappingMiddleware = (opts, next) => {\n const fetchInit = opts.meta?.fetchInit\n if (typeof fetchInit !== 'object' || fetchInit === null) return next(opts)\n const baseFetch: NonNullable<FetchRequestOptions['fetch']> =\n opts.fetch ?? envOptions.fetch ?? globalThis.fetch\n const fetchWithInit: typeof baseFetch = (input, init) =>\n baseFetch(input, {...fetchInit, ...init})\n return next({...opts, fetch: fetchWithInit})\n }\n\n const requester = createRequester({\n ...(envOptions.fetch ? {fetch: envOptions.fetch} : {}),\n headers: envOptions.headers,\n // Keep get-it's built-in 4xx/5xx → HttpError so the retry middleware can\n // see them; we translate to ClientError/ServerError after the retry loop\n // has exhausted in `executeRequest`.\n httpErrors: true,\n middleware: [\n retry({\n shouldRetry: shouldRetryRequest,\n maxRetries: config.maxRetries ?? 5,\n ...(config.retryDelay ? {retryDelay: config.retryDelay} : {}),\n }),\n ...envOptions.middleware,\n applyFetchInit,\n printWarnings(config),\n ],\n })\n\n const promise: PromiseRequester = (options: Any) => {\n // Options arrive fetch-shaped from `requestOptions` — the single\n // translation boundary between public option names and the transport.\n if (typeof options.url !== 'string') {\n throw new TypeError('Request options must include a `url`')\n }\n return executeRequest(requester, options)\n }\n\n // Same per-subscription AbortController pattern as `_observe` in\n // dataMethods: a caller-supplied signal is combined in via\n // `AbortSignal.any`, so the request aborts both on the caller's signal and\n // on unsubscribe. `AbortSignal.any` (rather than `addEventListener`)\n // because the caller's signal can be long-lived and reused — a manually\n // added listener would accumulate there once per subscription, since\n // `{once: true}` only cleans up if the signal actually fires.\n const observable: LegacyRequester = (options: Any) =>\n new Observable<ResponseEvent>((subscriber) => {\n const controller = new AbortController()\n const userSignal: AbortSignal | undefined = options.signal\n const signal = userSignal\n ? AbortSignal.any([userSignal, controller.signal])\n : controller.signal\n const subscription = from(promise({...options, signal})).subscribe(subscriber)\n return () => {\n subscription.unsubscribe()\n controller.abort()\n }\n })\n\n return {promise, observable}\n}\n\n/** @internal */\nexport function defineHttpRequest(\n envOptions: EnvironmentOptions,\n config: HttpRequestConfig = {},\n): LegacyRequester {\n return defineRequester(envOptions, config).observable\n}\n\n/**\n * Options describing the environment-specific defaults (Node vs. browser).\n *\n * @internal\n */\nexport interface EnvironmentOptions {\n fetch?: FetchRequestOptions['fetch']\n headers?: Record<string, string>\n middleware: LegacyMiddleware[]\n /**\n * Resolves the environment's fetch implementation — the same transport\n * regular requests use (custom fetch variants, undici configuration,\n * env-proxy support and all), optionally configured for an explicit proxy\n * URL. Lets consumers of the resolved config (the EventSource fetch\n * resolver) avoid falling back to whatever `globalThis.fetch` happens to\n * be. The Node environment supplies get-it's undici-backed fetch; the\n * browser environment leaves it unset (the global fetch IS the\n * environment's fetch there).\n *\n * Looked up via the env rather than imported directly so that the Node-only\n * `get-it/node` (which transitively pulls in `undici`) never ends up in the\n * browser bundle, even via rollup's inlined dynamic imports.\n */\n resolveFetch?: (proxyUrl?: string) => FetchFunction\n}\n\nasync function executeRequest(\n requester: ReturnType<typeof createRequester>,\n fetchOptions: FetchRequestOptions,\n): Promise<ResponseEvent> {\n const url = fetchOptions.url\n const method = (fetchOptions.method ?? 'GET').toUpperCase()\n\n let response\n try {\n response = await requester(fetchOptions)\n } catch (err) {\n if (err instanceof GetItHttpError) {\n // `err.body` is the response body as a string (get-it v9 stores the\n // already-decoded text), regardless of which response variant\n // `err.response` is.\n const errBodyText = typeof err.body === 'string' ? err.body : ''\n const errBody = parseJsonText(errBodyText, err.headers)\n const canonical = httpResponseFromFetch(\n {\n status: err.status,\n statusText: err.statusText,\n headers: err.headers,\n body: errBody,\n },\n url,\n method,\n )\n const tag = extractRequestTag(fetchOptions.query)\n if (canonical.statusCode >= 500) {\n throw new ServerError(canonical)\n }\n throw new ClientError(canonical, tag)\n }\n throw err\n }\n\n const body = parseJsonBody(response)\n return {\n type: 'response',\n body,\n statusCode: response.status,\n statusMessage: response.statusText || null,\n headers: headersToRecord(response.headers),\n url,\n method,\n }\n}\n\n/**\n * Extract the GROQ request tag (used for error messages) from the query.\n */\nfunction extractRequestTag(query: FetchRequestOptions['query']): string | undefined {\n if (!query) return undefined\n if (query instanceof URLSearchParams) return query.get('tag') ?? undefined\n const tag = query.tag\n return typeof tag === 'string' ? tag : undefined\n}\n\nfunction parseJsonBody(response: {headers: Headers; text(): string}): unknown {\n return parseJsonText(response.text(), response.headers)\n}\n\n/**\n * Parse a response body according to its `content-type`: JSON when the header\n * says so (falling back to the raw text on malformed JSON), text otherwise.\n * Shared with the browser XHR upload path so error bodies parse identically\n * on both transports.\n *\n * @internal\n */\nexport function parseJsonText(text: string, headers: Headers): unknown {\n const contentType = (headers.get('content-type') ?? '').toLowerCase()\n if (!text) return undefined\n if (contentType.includes('application/json')) {\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n }\n return text\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\nfunction shouldRetryRequest(err: unknown, attempt: number, options: FetchRequestOptions): boolean {\n // HTTP errors aren't usually retryable, but Content Lake gives us a few\n // status codes where retrying *is* the right move.\n if (err instanceof GetItHttpError) {\n const isSafe = (options.method ?? 'GET') === 'GET' || options.method === 'HEAD'\n const isQuery = (options.url ?? '').includes('/data/query')\n const status = err.status\n const retryableStatus = status === 429 || status === 502 || status === 503\n if ((isSafe || isQuery) && retryableStatus) return true\n return false\n }\n\n return isRetryableRequest(err, attempt, options)\n}\n\nfunction printWarnings(config: HttpRequestConfig): TransformMiddleware {\n const seen: Record<string, boolean> = {}\n\n const shouldIgnore = (message: string): boolean => {\n if (config.ignoreWarnings === undefined) return false\n const patterns = Array.isArray(config.ignoreWarnings)\n ? config.ignoreWarnings\n : [config.ignoreWarnings]\n return patterns.some((pattern) =>\n typeof pattern === 'string' ? message.includes(pattern) : pattern.test(message),\n )\n }\n\n return {\n afterResponse(response) {\n const header = response.headers.get('x-sanity-warning')\n if (!header) return response\n // Multiple warnings can be comma-separated per HTTP header semantics.\n for (const msg of header.split(',').map((m) => m.trim())) {\n if (!msg || seen[msg] || shouldIgnore(msg)) continue\n seen[msg] = true\n // oxlint-disable-next-line no-console\n console.warn(msg)\n }\n return response\n },\n }\n}\n"],"mappings":";;;;;;;AAwBA,MAAM,UAAU;;;;;;;;;;;AAkBhB,SAAgB,UAAU,OAAe,UAAwB,SAA0B;CACzF,IAAM,QAAQ,MAAM,MAAM,OAAO,GAM3B,EAAC,OAAO,KAAK,gBAAe,eAAe;EAJ/C,OAAO,aAAa,SAAS,OAAO,KAAK;EACzC,KAAK,SAAS,MAAM,aAAa,SAAS,K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,EAAE,KAAK,CAAC,GACjD,CAAC,OAAO,KAAK,QAAQ,aAAa,GAAG,MACzC,KAAK,OAAO,IAEZ,QAAQ,KAAK,GAAG;EAElB,OAAO;CACT,EACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"request-k7VS_NnC.js","names":["headersToRecord","GetItHttpError"],"sources":["../src/util/codeFrame.ts","../src/http/errors.ts","../src/http/request.ts"],"sourcesContent":["/**\n * Inlined, modified version of the `codeFrameColumns` function from `@babel/code-frame`.\n * MIT-licensed - https://github.com/babel/babel/blob/main/LICENSE\n * Copyright (c) 2014-present Sebastian McKenzie and other contributors.\n */\ntype Location = {\n column: number\n line: number\n}\n\ntype NodeLocation = {\n start: Location\n end?: Location\n}\n\ntype GroqLocation = {\n start: number\n end?: number\n}\n\n/**\n * RegExp to test for newlines.\n */\n\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/\n\n/**\n * Extract what lines should be marked and highlighted.\n */\n\ntype MarkerLines = Record<number, true | [number, number]>\n\n/**\n * Highlight a code frame with the given location and message.\n *\n * @param query - The query to be highlighted.\n * @param location - The location of the error in the code/query.\n * @param message - Message to be displayed inline (if possible) next to the highlighted\n * location in the code. If it can't be positioned inline, it will be placed above the\n * code frame.\n * @returns The highlighted code frame.\n */\nexport function codeFrame(query: string, location: GroqLocation, message?: string): string {\n const lines = query.split(NEWLINE)\n const loc = {\n start: columnToLine(location.start, lines),\n end: location.end ? columnToLine(location.end, lines) : undefined,\n }\n\n const {start, end, markerLines} = getMarkerLines(loc, lines)\n\n const numberMaxWidth = `${end}`.length\n\n return query\n .split(NEWLINE, end)\n .slice(start, end)\n .map((line, index) => {\n const number = start + 1 + index\n const paddedNumber = ` ${number}`.slice(-numberMaxWidth)\n const gutter = ` ${paddedNumber} |`\n const hasMarker = markerLines[number]\n const lastMarkerLine = !markerLines[number + 1]\n if (!hasMarker) {\n return ` ${gutter}${line.length > 0 ? ` ${line}` : ''}`\n }\n\n let markerLine = ''\n if (Array.isArray(hasMarker)) {\n const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\\t]/g, ' ')\n const numberOfMarkers = hasMarker[1] || 1\n\n markerLine = [\n '\\n ',\n gutter.replace(/\\d/g, ' '),\n ' ',\n markerSpacing,\n '^'.repeat(numberOfMarkers),\n ].join('')\n\n if (lastMarkerLine && message) {\n markerLine += ' ' + message\n }\n }\n return ['>', gutter, line.length > 0 ? ` ${line}` : '', markerLine].join('')\n })\n .join('\\n')\n}\n\nfunction getMarkerLines(\n loc: NodeLocation,\n source: Array<string>,\n): {\n start: number\n end: number\n markerLines: MarkerLines\n} {\n const startLoc: Location = {...loc.start}\n const endLoc: Location = {...startLoc, ...loc.end}\n const linesAbove = 2\n const linesBelow = 3\n const startLine = startLoc.line ?? -1\n const startColumn = startLoc.column ?? 0\n const endLine = endLoc.line\n const endColumn = endLoc.column\n\n let start = Math.max(startLine - (linesAbove + 1), 0)\n let end = Math.min(source.length, endLine + linesBelow)\n\n if (startLine === -1) {\n start = 0\n }\n\n if (endLine === -1) {\n end = source.length\n }\n\n const lineDiff = endLine - startLine\n const markerLines: MarkerLines = {}\n\n if (lineDiff) {\n for (let i = 0; i <= lineDiff; i++) {\n const lineNumber = i + startLine\n\n if (!startColumn) {\n markerLines[lineNumber] = true\n } else if (i === 0) {\n const sourceLength = source[lineNumber - 1].length\n\n markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]\n } else if (i === lineDiff) {\n markerLines[lineNumber] = [0, endColumn]\n } else {\n const sourceLength = source[lineNumber - i].length\n\n markerLines[lineNumber] = [0, sourceLength]\n }\n }\n } else {\n if (startColumn === endColumn) {\n if (startColumn) {\n markerLines[startLine] = [startColumn, 0]\n } else {\n markerLines[startLine] = true\n }\n } else {\n markerLines[startLine] = [startColumn, endColumn - startColumn]\n }\n }\n\n return {start, end, markerLines}\n}\n\nfunction columnToLine(column: number, lines: string[]): Location {\n let offset = 0\n\n for (let i = 0; i < lines.length; i++) {\n const lineLength = lines[i].length + 1 // assume '\\n' after each line\n\n if (offset + lineLength > column) {\n return {\n line: i + 1, // 1-based line\n column: column - offset, // 0-based column\n }\n }\n\n offset += lineLength\n }\n\n // Fallback: beyond last line\n return {\n line: lines.length,\n column: lines[lines.length - 1]?.length ?? 0,\n }\n}\n","import type {ActionError, Any, ErrorProps, MutationError, QueryParseError} from '../types'\nimport {codeFrame} from '../util/codeFrame'\nimport {isRecord} from '../util/isRecord'\n\nconst MAX_ITEMS_IN_ERROR_MESSAGE = 5\n\n/**\n * Canonical HTTP response shape used internally to build {@link ClientError}\n * and {@link ServerError}. Decouples the error layer from any particular\n * transport library — adapters in the HTTP layer (e.g. `httpResponseFromGetIt`)\n * project transport-specific response shapes into this stable form before\n * constructing errors.\n *\n * Matches the public {@link HttpError.response} shape so consumers see no\n * difference in error properties when the underlying transport changes.\n *\n * @internal\n */\nexport interface CanonicalHttpResponse {\n statusCode: number\n statusMessage: string | null\n headers: Record<string, string>\n body: unknown\n url: string\n method: string\n}\n\n/**\n * Adapter for buffered responses from get-it v9 (`BufferedResponse`-shaped).\n *\n * The URL and method aren't on the response itself in v9, so the request\n * options must be passed alongside.\n *\n * @internal\n */\nexport function httpResponseFromFetch(\n res: {\n status: number\n statusText: string\n headers: Headers\n body: unknown\n },\n reqUrl: string,\n reqMethod: string,\n): CanonicalHttpResponse {\n return {\n statusCode: res.status,\n statusMessage: res.statusText || null,\n headers: headersToRecord(res.headers),\n body: res.body,\n url: reqUrl,\n method: reqMethod,\n }\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/**\n * Shared properties for HTTP errors (eg both ClientError and ServerError)\n * Use `isHttpError` for type narrowing and accessing response properties.\n *\n * @public\n */\nexport interface HttpError {\n statusCode: number\n message: string\n response: {\n body: unknown\n url: string\n method: string\n headers: Record<string, string>\n statusCode: number\n statusMessage: string | null\n }\n}\n\n/**\n * Checks if the provided error is an HTTP error.\n *\n * @param error - The error to check.\n * @returns `true` if the error is an HTTP error, `false` otherwise.\n * @public\n */\nexport function isHttpError(error: unknown): error is HttpError {\n if (!isRecord(error)) {\n return false\n }\n\n const response = error.response\n if (\n typeof error.statusCode !== 'number' ||\n typeof error.message !== 'string' ||\n !isRecord(response)\n ) {\n return false\n }\n\n if (\n typeof response.body === 'undefined' ||\n typeof response.url !== 'string' ||\n typeof response.method !== 'string' ||\n typeof response.headers !== 'object' ||\n typeof response.statusCode !== 'number'\n ) {\n return false\n }\n\n return true\n}\n\n/** @public */\nexport class ClientError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 400\n responseBody: ErrorProps['responseBody']\n traceId: ErrorProps['traceId']\n details: ErrorProps['details']\n\n constructor(res: Any, tag?: string) {\n const props = extractErrorProps(res, tag)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\n/** @public */\nexport class ServerError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 500\n responseBody: ErrorProps['responseBody']\n traceId: ErrorProps['traceId']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\nfunction extractErrorProps(res: Any, tag?: string): ErrorProps {\n const body = res.body\n const props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n traceId: extractTraceId(res),\n message: '',\n details: undefined as Any,\n }\n\n // Fall back early if we didn't get a JSON object returned as expected\n if (!isRecord(body)) {\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n return props\n }\n\n const error = body.error\n\n // API/Boom style errors ({statusCode, error, message})\n if (typeof error === 'string' && typeof body.message === 'string') {\n props.message = `${error} - ${body.message}${formatTraceId(props.traceId)}`\n return props\n }\n\n // Content Lake errors with a `error` prop being an object\n if (typeof error !== 'object' || error === null) {\n if (typeof error === 'string') {\n props.message = `${error}${formatTraceId(props.traceId)}`\n } else if (typeof body.message === 'string') {\n props.message = `${body.message}${formatTraceId(props.traceId)}`\n } else {\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n }\n return props\n }\n\n // Mutation errors (specifically)\n if (isMutationError(error) || isActionError(error)) {\n const allItems = error.items || []\n const items = allItems\n .slice(0, MAX_ITEMS_IN_ERROR_MESSAGE)\n .map((item) => item.error?.description)\n .filter(Boolean)\n let itemsStr = items.length ? `:\\n- ${items.join('\\n- ')}` : ''\n if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {\n itemsStr += `\\n...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`\n }\n props.message = `${error.description}${formatTraceId(props.traceId)}${itemsStr}`\n props.details = body.error\n return props\n }\n\n // Query parse errors\n if (isQueryParseError(error)) {\n props.message = formatQueryParseError(error, tag, props.traceId)\n props.details = body.error\n return props\n }\n\n if ('description' in error && typeof error.description === 'string') {\n // Query/database errors ({error: {description, other, arb, props}})\n props.message = `${error.description}${formatTraceId(props.traceId)}`\n props.details = error\n return props\n }\n\n // Other, more arbitrary errors\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n return props\n}\n\nfunction isMutationError(error: object): error is MutationError {\n return (\n 'type' in error &&\n error.type === 'mutationError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\nfunction isActionError(error: object): error is ActionError {\n return (\n 'type' in error &&\n error.type === 'actionError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\n/** @internal */\nexport function isQueryParseError(error: object): error is QueryParseError {\n return (\n isRecord(error) &&\n error.type === 'queryParseError' &&\n typeof error.query === 'string' &&\n typeof error.start === 'number' &&\n typeof error.end === 'number'\n )\n}\n\n/**\n * Formats a GROQ query parse error into a human-readable string.\n *\n * @param error - The error object containing details about the parse error.\n * @param tag - An optional tag to include in the error message.\n * @returns A formatted error message string.\n * @public\n */\nexport function formatQueryParseError(\n error: QueryParseError,\n tag?: string | null,\n traceId?: string,\n) {\n const {query, start, end, description} = error\n const withTraceId = traceId ? `\\n(traceId: ${traceId})` : ''\n\n if (!query || typeof start === 'undefined') {\n return `GROQ query parse error: ${description}${withTraceId}`\n }\n\n const withTag = tag ? `\\n\\nTag: ${tag}` : ''\n const framed = codeFrame(query, {start, end}, description)\n\n return `GROQ query parse error:\\n${framed}${withTag}${withTraceId}`\n}\n\nfunction httpErrorMessage(res: Any, body: unknown) {\n const details = typeof body === 'string' ? ` (${sliceWithEllipsis(body, 100)})` : ''\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`\n}\n\n/**\n * Extract the traceId from the traceparent header on the response.\n *\n * The traceparent is on the format [version]-[traceId]-[parentId]-[traceFlags], but\n * when debugging end-user issues it's the traceId we need to be able to get hold of\n * the relevant traces.\n *\n * @see https://www.w3.org/TR/trace-context/\n * @returns The traceId for HTTP response\n */\nfunction extractTraceId(res: Any): string | undefined {\n const traceparent = res?.headers?.['traceparent']\n if (!traceparent) return\n\n return traceparent.split('-')[1]\n}\n\nfunction stringifyBody(body: Any, res: Any) {\n const contentType = (res.headers['content-type'] || '').toLowerCase()\n const isJson = contentType.indexOf('application/json') !== -1\n return isJson ? JSON.stringify(body, null, 2) : body\n}\n\nfunction formatTraceId(traceId: string | undefined): string {\n return traceId ? ` (traceId: ${traceId})` : ''\n}\n\nfunction sliceWithEllipsis(str: string, max: number) {\n return str.length > max ? `${str.slice(0, max)}…` : str\n}\n\n/** @public */\nexport class CorsOriginError extends Error {\n projectId?: string\n addOriginUrl?: URL\n\n constructor({projectId, credentials}: {projectId?: string; credentials?: boolean} = {}) {\n super('CorsOriginError')\n this.name = 'CorsOriginError'\n this.projectId = projectId\n\n // Only build a deep-link when we know which project the user needs to\n // configure - without `projectId` the management URL can't actually route\n // them anywhere useful.\n if (projectId && typeof location !== 'undefined') {\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n const {origin} = location\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n if (credentials) {\n // Pre-selects the \"Allow credentials (token-based auth)\" toggle in\n // the Sanity management CORS form.\n url.searchParams.set('credentials', '')\n }\n this.addOriginUrl = url\n this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`\n } else if (projectId) {\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: https://sanity.io/manage/project/${projectId}/api`\n } else {\n this.message = `The current origin is not allowed to connect to the Live Content API.`\n }\n }\n}\n","import {\n createRequester,\n type FetchFunction,\n HttpError as GetItHttpError,\n type RequestOptions as FetchRequestOptions,\n type TransformMiddleware,\n type WrappingMiddleware,\n} from 'get-it'\nimport {isRetryableRequest, retry} from 'get-it/middleware'\nimport {from, Observable} from 'rxjs'\n\nimport type {Any} from '../types'\nimport {ClientError, httpResponseFromFetch, ServerError} from './errors'\n\n/**\n * Middleware accepted by the internal HTTP layer. Two flavors per get-it v9:\n * a flat-pipeline transform (`beforeRequest`/`afterResponse`) or a wrapping\n * middleware that surrounds the fetch chain.\n *\n * @internal\n */\nexport type LegacyMiddleware = TransformMiddleware | WrappingMiddleware\n\n/**\n * The shape this client's internal pipeline produces. Mirrors the historical\n * `ResponseEvent` from the get-it v8 multi-event observable, so all the existing\n * downstream code (`_requestObservable`, `_uploadObservable`,\n * `defineCreateClient`) keeps working without churn.\n *\n * @internal\n */\nexport interface ResponseEvent {\n type: 'response'\n body: unknown\n statusCode: number\n statusMessage: string | null\n headers: Record<string, string>\n url: string\n method: string\n}\n\n/**\n * Legacy \"requester\" type — the result of `defineHttpRequest`. Returns a\n * single-event Observable for compatibility with the rest of the codebase.\n *\n * @internal\n */\nexport type LegacyRequester = (options: Any) => Observable<ResponseEvent>\n\n/**\n * Promise-based sibling of {@link LegacyRequester}. Resolves directly to the\n * single `ResponseEvent` the transport produces, skipping the RxJS wrapper.\n * Used by the promise-based client surface so it never constructs an\n * Observable.\n *\n * @internal\n */\nexport type PromiseRequester = (options: Any) => Promise<ResponseEvent>\n\n/**\n * Both forms of the transport, sharing a single underlying get-it requester\n * (so retry state and the one-shot warning de-duplication are shared between\n * the observable and promise paths).\n *\n * @internal\n */\nexport interface DualRequester {\n observable: LegacyRequester\n promise: PromiseRequester\n}\n\n/**\n * Options for tuning the HTTP request pipeline per-client.\n *\n * @internal\n */\nexport interface HttpRequestConfig {\n ignoreWarnings?: string | RegExp | Array<string | RegExp>\n maxRetries?: number\n retryDelay?: (attemptNumber: number) => number\n}\n\n/**\n * Build both the observable and promise transport forms from a single get-it\n * requester. The promise form is the primitive (`executeRequest` is already\n * promise-based); the observable form wraps it lazily so each subscription\n * starts its own request (cold), and unsubscribing aborts the in-flight\n * fetch — the same contract as the get-it v8 observable adapter.\n *\n * @internal\n */\nexport function defineRequester(\n envOptions: EnvironmentOptions,\n config: HttpRequestConfig = {},\n): DualRequester {\n // Framework-patched fetch implementations read extra `RequestInit` fields\n // for caching semantics — Next.js App Router's `cache` and `next` options in\n // particular. Legacy callers pass those via an object-valued `fetch` request\n // option (see `adaptToFetchOptions`, which stashes it in `meta.fetchInit`\n // since get-it v9's own `fetch` option only accepts a function). Merge them\n // into the init of whichever fetch implementation is effective for the\n // request: per-request/test-override fetch, the environment default, or the\n // global fetch.\n const applyFetchInit: WrappingMiddleware = (opts, next) => {\n const fetchInit = opts.meta?.fetchInit\n if (typeof fetchInit !== 'object' || fetchInit === null) return next(opts)\n const baseFetch: NonNullable<FetchRequestOptions['fetch']> =\n opts.fetch ?? envOptions.fetch ?? globalThis.fetch\n const fetchWithInit: typeof baseFetch = (input, init) =>\n baseFetch(input, {...fetchInit, ...init})\n return next({...opts, fetch: fetchWithInit})\n }\n\n const requester = createRequester({\n ...(envOptions.fetch ? {fetch: envOptions.fetch} : {}),\n headers: envOptions.headers,\n // Keep get-it's built-in 4xx/5xx → HttpError so the retry middleware can\n // see them; we translate to ClientError/ServerError after the retry loop\n // has exhausted in `executeRequest`.\n httpErrors: true,\n middleware: [\n retry({\n shouldRetry: shouldRetryRequest,\n maxRetries: config.maxRetries ?? 5,\n ...(config.retryDelay ? {retryDelay: config.retryDelay} : {}),\n }),\n ...envOptions.middleware,\n applyFetchInit,\n printWarnings(config),\n ],\n })\n\n const promise: PromiseRequester = (options: Any) => {\n // Options arrive fetch-shaped from `requestOptions` — the single\n // translation boundary between public option names and the transport.\n if (typeof options.url !== 'string') {\n throw new TypeError('Request options must include a `url`')\n }\n return executeRequest(requester, options)\n }\n\n // Same per-subscription AbortController pattern as `_observe` in\n // dataMethods: a caller-supplied signal is combined in via\n // `AbortSignal.any`, so the request aborts both on the caller's signal and\n // on unsubscribe. `AbortSignal.any` (rather than `addEventListener`)\n // because the caller's signal can be long-lived and reused — a manually\n // added listener would accumulate there once per subscription, since\n // `{once: true}` only cleans up if the signal actually fires.\n const observable: LegacyRequester = (options: Any) =>\n new Observable<ResponseEvent>((subscriber) => {\n const controller = new AbortController()\n const userSignal: AbortSignal | undefined = options.signal\n const signal = userSignal\n ? AbortSignal.any([userSignal, controller.signal])\n : controller.signal\n const subscription = from(promise({...options, signal})).subscribe(subscriber)\n return () => {\n subscription.unsubscribe()\n controller.abort()\n }\n })\n\n return {promise, observable}\n}\n\n/** @internal */\nexport function defineHttpRequest(\n envOptions: EnvironmentOptions,\n config: HttpRequestConfig = {},\n): LegacyRequester {\n return defineRequester(envOptions, config).observable\n}\n\n/**\n * Options describing the environment-specific defaults (Node vs. browser).\n *\n * @internal\n */\nexport interface EnvironmentOptions {\n fetch?: FetchRequestOptions['fetch']\n headers?: Record<string, string>\n middleware: LegacyMiddleware[]\n /**\n * Resolves the environment's fetch implementation — the same transport\n * regular requests use (custom fetch variants, undici configuration,\n * env-proxy support and all), optionally configured for an explicit proxy\n * URL. Lets consumers of the resolved config (the EventSource fetch\n * resolver) avoid falling back to whatever `globalThis.fetch` happens to\n * be. The Node environment supplies get-it's undici-backed fetch; the\n * browser environment leaves it unset (the global fetch IS the\n * environment's fetch there).\n *\n * Looked up via the env rather than imported directly so that the Node-only\n * `get-it/node` (which transitively pulls in `undici`) never ends up in the\n * browser bundle, even via rollup's inlined dynamic imports.\n */\n resolveFetch?: (proxyUrl?: string) => FetchFunction\n}\n\nasync function executeRequest(\n requester: ReturnType<typeof createRequester>,\n fetchOptions: FetchRequestOptions,\n): Promise<ResponseEvent> {\n const url = fetchOptions.url\n const method = (fetchOptions.method ?? 'GET').toUpperCase()\n\n let response\n try {\n response = await requester(fetchOptions)\n } catch (err) {\n if (err instanceof GetItHttpError) {\n // `err.body` is the response body as a string (get-it v9 stores the\n // already-decoded text), regardless of which response variant\n // `err.response` is.\n const errBodyText = typeof err.body === 'string' ? err.body : ''\n const errBody = parseJsonText(errBodyText, err.headers)\n const canonical = httpResponseFromFetch(\n {\n status: err.status,\n statusText: err.statusText,\n headers: err.headers,\n body: errBody,\n },\n url,\n method,\n )\n const tag = extractRequestTag(fetchOptions.query)\n if (canonical.statusCode >= 500) {\n throw new ServerError(canonical)\n }\n throw new ClientError(canonical, tag)\n }\n throw err\n }\n\n const body = parseJsonBody(response)\n return {\n type: 'response',\n body,\n statusCode: response.status,\n statusMessage: response.statusText || null,\n headers: headersToRecord(response.headers),\n url,\n method,\n }\n}\n\n/**\n * Extract the GROQ request tag (used for error messages) from the query.\n */\nfunction extractRequestTag(query: FetchRequestOptions['query']): string | undefined {\n if (!query) return undefined\n if (query instanceof URLSearchParams) return query.get('tag') ?? undefined\n const tag = query.tag\n return typeof tag === 'string' ? tag : undefined\n}\n\nfunction parseJsonBody(response: {headers: Headers; text(): string}): unknown {\n return parseJsonText(response.text(), response.headers)\n}\n\n/**\n * Parse a response body according to its `content-type`: JSON when the header\n * says so (falling back to the raw text on malformed JSON), text otherwise.\n * Shared with the browser XHR upload path so error bodies parse identically\n * on both transports.\n *\n * @internal\n */\nexport function parseJsonText(text: string, headers: Headers): unknown {\n const contentType = (headers.get('content-type') ?? '').toLowerCase()\n if (!text) return undefined\n if (contentType.includes('application/json')) {\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n }\n return text\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\nfunction shouldRetryRequest(err: unknown, attempt: number, options: FetchRequestOptions): boolean {\n // HTTP errors aren't usually retryable, but Content Lake gives us a few\n // status codes where retrying *is* the right move.\n if (err instanceof GetItHttpError) {\n const isSafe = (options.method ?? 'GET') === 'GET' || options.method === 'HEAD'\n const isQuery = (options.url ?? '').includes('/data/query')\n const status = err.status\n const retryableStatus = status === 429 || status === 502 || status === 503\n if ((isSafe || isQuery) && retryableStatus) return true\n return false\n }\n\n return isRetryableRequest(err, attempt, options)\n}\n\nfunction printWarnings(config: HttpRequestConfig): TransformMiddleware {\n const seen: Record<string, boolean> = {}\n\n const shouldIgnore = (message: string): boolean => {\n if (config.ignoreWarnings === undefined) return false\n const patterns = Array.isArray(config.ignoreWarnings)\n ? config.ignoreWarnings\n : [config.ignoreWarnings]\n return patterns.some((pattern) =>\n typeof pattern === 'string' ? message.includes(pattern) : pattern.test(message),\n )\n }\n\n return {\n afterResponse(response) {\n const header = response.headers.get('x-sanity-warning')\n if (!header) return response\n // Multiple warnings can be comma-separated per HTTP header semantics.\n for (const msg of header.split(',').map((m) => m.trim())) {\n if (!msg || seen[msg] || shouldIgnore(msg)) continue\n seen[msg] = true\n // oxlint-disable-next-line no-console\n console.warn(msg)\n }\n return response\n },\n }\n}\n"],"mappings":";;;;;;;AAwBA,MAAM,UAAU;;;;;;;;;;;AAkBhB,SAAgB,UAAU,OAAe,UAAwB,SAA0B;CACzF,IAAM,QAAQ,MAAM,MAAM,OAAO,GAM3B,EAAC,OAAO,KAAK,gBAAe,eAAe;EAJ/C,OAAO,aAAa,SAAS,OAAO,KAAK;EACzC,KAAK,SAAS,MAAM,aAAa,SAAS,KAAK,KAAK,IAAI,KAAA;CAGP,GAAG,KAAK,GAErD,iBAAiB,GAAG,MAAM;CAEhC,OAAO,MACJ,MAAM,SAAS,GAAG,CAA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T;AAEA,SAAS,mBAAmB,KAAc,SAAiB,SAAuC;CAGhG,IAAI,eAAeA,WAAgB;EACjC,IAAM,UAAU,QAAQ,UAAU,WAAW,SAAS,QAAQ,WAAW,QACnE,WAAW,QAAQ,OAAO,GAAA,CAAI,SAAS,aAAa,GACpD,SAAS,IAAI;EAGnB,OADA,IAAK,UAAU,aADS,WAAW,OAAO,WAAW,OAAO,WAAW;CAGzE;CAEA,OAAO,mBAAmB,KAAK,SAAS,OAAO;AACjD;AAEA,SAAS,cAAc,QAAgD;CACrE,IAAM,OAAgC,CAAC,GAEjC,gBAAgB,YAChB,OAAO,mBAAmB,KAAA,MACb,MAAM,QAAQ,OAAO,cAAc,IAChD,OAAO,iBACP,CAAC,OAAO,cAAc,EAAA,CACV,MAAM,YACpB,OAAO,WAAY,WAAW,QAAQ,SAAS,OAAO,IAAI,QAAQ,KAAK,OAAO,CAChF;CAGF,OAAO,EACL,cAAc,UAAU;EACtB,IAAM,SAAS,SAAS,QAAQ,IAAI,kBAAkB;EACtD,IAAI,CAAC,QAAQ,OAAO;EAEpB,KAAK,IAAM,OAAO,OAAO,MAAM,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK,CAAC,GACjD,CAAC,OAAO,KAAK,QAAQ,aAAa,GAAG,MACzC,KAAK,OAAO,IAEZ,QAAQ,KAAK,GAAG;EAElB,OAAO;CACT,EACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolveEditInfo-sq7yF78q.js","names":["studioPath.fromString","studioPath.toString"],"sources":["../src/csm/studioPath.ts","../src/csm/draftUtils.ts","../src/csm/jsonPath.ts","../src/csm/resolveMapping.ts","../src/csm/isArray.ts","../src/csm/walkMap.ts","../src/csm/createEditUrl.ts","../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\n// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- caller-supplied return type; removing it breaks `get<Result>(...)` call sites\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","// nominal/opaque type hack\ntype Opaque<T, K> = T & {__opaqueId__: K}\n\n/** @internal */\nexport type DraftId = Opaque<string, 'draftId'>\n\n/** @internal */\nexport type PublishedId = Opaque<string, 'publishedId'>\n\n/** @internal */\nexport const DRAFTS_FOLDER = 'drafts'\n\n/** @internal */\nexport const VERSION_FOLDER = 'versions'\n\nconst PATH_SEPARATOR = '.'\nconst DRAFTS_PREFIX = `${DRAFTS_FOLDER}${PATH_SEPARATOR}`\nconst VERSION_PREFIX = `${VERSION_FOLDER}${PATH_SEPARATOR}`\n\n/** @internal */\nexport function isDraftId(id: string): id is DraftId {\n return id.startsWith(DRAFTS_PREFIX)\n}\n\n/** @internal */\nexport function isVersionId(id: string): boolean {\n return id.startsWith(VERSION_PREFIX)\n}\n\n/** @internal */\nexport function isPublishedId(id: string): id is PublishedId {\n return !isDraftId(id) && !isVersionId(id)\n}\n\n/** @internal */\nexport function getDraftId(id: string): DraftId {\n if (isVersionId(id)) {\n const publishedId = getPublishedId(id)\n return (DRAFTS_PREFIX + publishedId) as DraftId\n }\n\n return isDraftId(id) ? id : ((DRAFTS_PREFIX + id) as DraftId)\n}\n\n/** @internal */\nexport function getVersionId(id: string, version: string): string {\n if (version === 'drafts' || version === 'published') {\n throw new Error('Version can not be \"published\" or \"drafts\"')\n }\n\n return `${VERSION_PREFIX}${version}${PATH_SEPARATOR}${getPublishedId(id)}`\n}\n\n/**\n * @internal\n * Given an id, returns the versionId if it exists.\n * e.g. `versions.summer-drop.foo` = `summer-drop`\n * e.g. `drafts.foo` = `undefined`\n * e.g. `foo` = `undefined`\n */\nexport function getVersionFromId(id: string): string | undefined {\n if (!isVersionId(id)) return undefined\n const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR)\n\n return versionId\n}\n\n/** @internal */\nexport function getPublishedId(id: string): PublishedId {\n if (isVersionId(id)) {\n // make sure to only remove the versions prefix and the bundle name\n return id.split(PATH_SEPARATOR).slice(2).join(PATH_SEPARATOR) as PublishedId as PublishedId\n }\n\n if (isDraftId(id)) {\n return id.slice(DRAFTS_PREFIX.length) as PublishedId\n }\n\n return id as PublishedId\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n/**\n * @internal\n */\nexport function jsonPathArray(path: ContentSourceMapParsedPath): string[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathArray, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const resultMappingPathArray = jsonPathArray(jsonPathToMappingPath(resultPath))\n for (let i = resultMappingPathArray.length - 1; i >= 0; i--) {\n const key = `$${resultMappingPathArray.slice(0, i).join('')}`\n const mappingFound = csm.mappings[key]\n if (mappingFound) {\n const pathSuffix = resultMappingPath.substring(key.length)\n return {mapping: mappingFound, matchedPath: key, pathSuffix}\n }\n }\n\n return undefined\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","import {isRecord} from '../util/isRecord'\nimport {isArray} from './isArray'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n // Handle Portable Text in a faster way\n if (value._type === 'block' || value._type === 'span') {\n const result = {...value}\n if (value._type === 'block') {\n result.children = walkMap(value.children, mappingFn, path.concat('children'))\n } else if (value._type === 'span') {\n result.text = walkMap(value.text, mappingFn, path.concat('text'))\n }\n return result\n }\n\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {getPublishedId, getVersionFromId, isPublishedId, isVersionId} from './draftUtils'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // oxlint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (isPublishedId(_id)) {\n searchParams.set('perspective', 'published')\n } else if (isVersionId(_id)) {\n const versionId = getVersionFromId(_id)!\n searchParams.set('perspective', versionId)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"mappings":";;;;;;;;;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