@sanity/client 7.26.1 → 8.0.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 (128) hide show
  1. package/README.md +5 -377
  2. package/dist/browserUpload-CQgx9YYo.js +86 -0
  3. package/dist/browserUpload-CQgx9YYo.js.map +1 -0
  4. package/dist/browserUpload-icWlVP15.js +86 -0
  5. package/dist/browserUpload-icWlVP15.js.map +1 -0
  6. package/dist/config-a8VajuEY.js +126 -0
  7. package/dist/config-a8VajuEY.js.map +1 -0
  8. package/dist/csm.d.ts +122 -347
  9. package/dist/csm.js +79 -91
  10. package/dist/csm.js.map +1 -1
  11. package/dist/dist-C9ExSk2R.js +73 -0
  12. package/dist/dist-C9ExSk2R.js.map +1 -0
  13. package/dist/dist-Z8cIRxoB.js +69 -0
  14. package/dist/dist-Z8cIRxoB.js.map +1 -0
  15. package/dist/index.d.ts +107 -6758
  16. package/dist/index.js +2822 -2848
  17. package/dist/index.js.map +1 -1
  18. package/dist/{index.d.cts → index.node.d.ts} +4291 -5363
  19. package/dist/index.node.js +3131 -0
  20. package/dist/index.node.js.map +1 -0
  21. package/dist/isRecord-Kfmt-nk-.js +7 -0
  22. package/dist/isRecord-Kfmt-nk-.js.map +1 -0
  23. package/dist/media-library.d.ts +9 -100
  24. package/dist/media-library.js +36 -14
  25. package/dist/media-library.js.map +1 -1
  26. package/dist/request-CJxcN16k.js +372 -0
  27. package/dist/request-CJxcN16k.js.map +1 -0
  28. package/dist/request-k7VS_NnC.js +354 -0
  29. package/dist/request-k7VS_NnC.js.map +1 -0
  30. package/dist/resolveEditInfo-sq7yF78q.js +325 -0
  31. package/dist/resolveEditInfo-sq7yF78q.js.map +1 -0
  32. package/dist/rolldown-runtime-vyAXikos.js +9 -0
  33. package/dist/stega.d.ts +78 -7179
  34. package/dist/stega.js +27 -20
  35. package/dist/stega.js.map +1 -1
  36. package/dist/stegaClean-C18wLWau.js +21 -0
  37. package/dist/stegaClean-C18wLWau.js.map +1 -0
  38. package/dist/stegaEncodeSourceMap-B2fGArSf.js +163 -0
  39. package/dist/stegaEncodeSourceMap-B2fGArSf.js.map +1 -0
  40. package/dist/stegaEncodeSourceMap-DkoIlutY.js +367 -0
  41. package/dist/stegaEncodeSourceMap-DkoIlutY.js.map +1 -0
  42. package/dist/{index.browser.d.cts → types-CUxZSgB2.d.ts} +3956 -5295
  43. package/dist/types-CfGzbXrl.d.ts +108 -0
  44. package/package.json +69 -146
  45. package/src/SanityClient.ts +82 -117
  46. package/src/agent/actions/AgentActionsClient.ts +12 -12
  47. package/src/agent/actions/generate.ts +20 -3
  48. package/src/agent/actions/patch.ts +21 -4
  49. package/src/agent/actions/prompt.ts +17 -4
  50. package/src/agent/actions/transform.ts +21 -4
  51. package/src/agent/actions/translate.ts +21 -4
  52. package/src/assets/AssetsClient.ts +71 -23
  53. package/src/csm/createEditUrl.ts +1 -1
  54. package/src/csm/draftUtils.ts +0 -1
  55. package/src/csm/index.ts +2 -2
  56. package/src/csm/studioPath.ts +2 -1
  57. package/src/csm/types.ts +5 -1
  58. package/src/data/dataMethods.ts +801 -349
  59. package/src/data/eventsource.ts +13 -10
  60. package/src/data/listen.ts +16 -22
  61. package/src/data/live.ts +44 -27
  62. package/src/data/resolveEventSourceFetch.ts +96 -0
  63. package/src/datasets/DatasetsClient.ts +58 -41
  64. package/src/defineCreateClient.ts +35 -23
  65. package/src/http/browserMiddleware.ts +7 -1
  66. package/src/http/browserUpload.ts +162 -0
  67. package/src/http/errors.ts +60 -6
  68. package/src/http/nodeMiddleware.ts +94 -30
  69. package/src/http/request.ts +310 -87
  70. package/src/http/requestOptions.ts +131 -15
  71. package/src/{index.browser.ts → index.node.ts} +9 -4
  72. package/src/index.ts +4 -3
  73. package/src/mediaLibrary/MediaLibraryVideoClient.ts +26 -11
  74. package/src/projects/ProjectsClient.ts +18 -16
  75. package/src/releases/ReleasesClient.ts +34 -31
  76. package/src/stega/index.ts +1 -2
  77. package/src/stega/stegaEncodeSourceMap.ts +5 -0
  78. package/src/stega/types.ts +0 -1
  79. package/src/types.ts +110 -96
  80. package/src/users/UsersClient.ts +10 -14
  81. package/src/util/shareReplayLatest.ts +1 -1
  82. package/src/warnings.ts +6 -1
  83. package/dist/_chunks-cjs/config.cjs +0 -206
  84. package/dist/_chunks-cjs/config.cjs.map +0 -1
  85. package/dist/_chunks-cjs/isRecord.cjs +0 -6
  86. package/dist/_chunks-cjs/isRecord.cjs.map +0 -1
  87. package/dist/_chunks-cjs/resolveEditInfo.cjs +0 -334
  88. package/dist/_chunks-cjs/resolveEditInfo.cjs.map +0 -1
  89. package/dist/_chunks-cjs/stegaClean.cjs +0 -46
  90. package/dist/_chunks-cjs/stegaClean.cjs.map +0 -1
  91. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +0 -388
  92. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +0 -1
  93. package/dist/_chunks-es/config.js +0 -207
  94. package/dist/_chunks-es/config.js.map +0 -1
  95. package/dist/_chunks-es/isRecord.js +0 -7
  96. package/dist/_chunks-es/isRecord.js.map +0 -1
  97. package/dist/_chunks-es/resolveEditInfo.js +0 -335
  98. package/dist/_chunks-es/resolveEditInfo.js.map +0 -1
  99. package/dist/_chunks-es/stegaClean.js +0 -47
  100. package/dist/_chunks-es/stegaClean.js.map +0 -1
  101. package/dist/_chunks-es/stegaEncodeSourceMap.js +0 -389
  102. package/dist/_chunks-es/stegaEncodeSourceMap.js.map +0 -1
  103. package/dist/csm.cjs +0 -99
  104. package/dist/csm.cjs.map +0 -1
  105. package/dist/csm.d.cts +0 -403
  106. package/dist/index.browser.cjs +0 -3106
  107. package/dist/index.browser.cjs.map +0 -1
  108. package/dist/index.browser.d.ts +0 -6841
  109. package/dist/index.browser.js +0 -3082
  110. package/dist/index.browser.js.map +0 -1
  111. package/dist/index.cjs +0 -2947
  112. package/dist/index.cjs.map +0 -1
  113. package/dist/media-library.cjs +0 -20
  114. package/dist/media-library.cjs.map +0 -1
  115. package/dist/media-library.d.cts +0 -117
  116. package/dist/stega.browser.cjs +0 -29
  117. package/dist/stega.browser.cjs.map +0 -1
  118. package/dist/stega.browser.d.cts +0 -7242
  119. package/dist/stega.browser.d.ts +0 -7242
  120. package/dist/stega.browser.js +0 -24
  121. package/dist/stega.browser.js.map +0 -1
  122. package/dist/stega.cjs +0 -29
  123. package/dist/stega.cjs.map +0 -1
  124. package/dist/stega.d.cts +0 -7242
  125. package/src/data/eventsourcePolyfill.ts +0 -7
  126. package/umd/.gitkeep +0 -1
  127. package/umd/sanityClient.js +0 -6536
  128. package/umd/sanityClient.min.js +0 -6
package/src/types.ts CHANGED
@@ -1,17 +1,29 @@
1
1
  // deno-lint-ignore-file no-empty-interface
2
- /* eslint-disable @typescript-eslint/no-empty-object-type */
3
2
 
4
- import type {Requester} from 'get-it'
3
+ import type {FetchFunction} from 'get-it'
5
4
  import type {Observable} from 'rxjs'
6
5
 
7
- import type {SanityClient} from './SanityClient'
8
6
  import type {InitializedStegaConfig, StegaConfig} from './stega/types'
9
7
 
8
+ /**
9
+ * Low-level requester returned by `defineHttpRequest`. Surfaces as
10
+ * `client.config().requester` and as the named `requester` export.
11
+ *
12
+ * Defined locally rather than imported from `http/request` so api-extractor
13
+ * inlines it into the bundled `.d.ts` instead of emitting a relative import
14
+ * that doesn't survive into `dist/` ([#1290][]).
15
+ *
16
+ * [#1290]: https://github.com/sanity-io/client/issues/1290
17
+ *
18
+ * @public
19
+ */
20
+ export type Requester = (options: Any) => Observable<unknown>
21
+
10
22
  /**
11
23
  * Used to tag types that is set to `any` as a temporary measure, but should be replaced with proper typings in the future
12
24
  * @internal
13
25
  */
14
- export type Any = any // eslint-disable-line @typescript-eslint/no-explicit-any
26
+ export type Any = any // oxlint-disable-line typescript/no-explicit-any
15
27
 
16
28
  declare global {
17
29
  // Declare empty stub interfaces for environments where "dom" lib is not included
@@ -45,7 +57,7 @@ export type ReleaseId = `r${string}`
45
57
  type DeprecatedPreviewDrafts = 'previewDrafts'
46
58
 
47
59
  /** @public */
48
- export type StackablePerspective = ('published' | 'drafts' | string) & {}
60
+ export type StackablePerspective = 'published' | 'drafts' | (string & {})
49
61
 
50
62
  /** @public */
51
63
  export type ClientPerspective =
@@ -134,6 +146,12 @@ export interface ClientConfig {
134
146
  * As of API version `v2025-02-19`, the default perspective has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog}
135
147
  */
136
148
  apiVersion?: string
149
+ /**
150
+ * Route requests through an HTTP(S) proxy. Node.js only. Can be replaced
151
+ * on an existing client via `client.config({proxy})` or
152
+ * `client.withConfig({proxy})`. For environment-driven proxying, set
153
+ * `HTTP_PROXY`/`HTTPS_PROXY`/`NO_PROXY` before the process starts.
154
+ */
137
155
  proxy?: string
138
156
 
139
157
  /**
@@ -196,16 +214,33 @@ export interface ClientConfig {
196
214
  useProjectHostname?: boolean
197
215
 
198
216
  /**
199
- * @deprecated Don't use
217
+ * Resolves the fetch implementation every request (including EventSource
218
+ * connections) goes through. Defaults to the environment entry point's
219
+ * fetch — the Node entry supplies get-it's undici-backed fetch (resolved
220
+ * via the entry point instead of a direct import so `get-it/node`/`undici`
221
+ * stays out of the browser bundle), the browser entry leaves it unset (the
222
+ * global fetch IS the environment's fetch there). Receives the explicit
223
+ * `proxy` config, when set, as its argument.
224
+ *
225
+ * Supplying it in the client config replaces the transport wholesale —
226
+ * custom fetch variants, alternative undici configurations, or a mock
227
+ * (the test suite injects `get-it/mock` this way).
228
+ *
229
+ * Returns get-it's minimal `FetchFunction` contract rather than the full
230
+ * `typeof fetch` — that is what the environments actually provide, and
231
+ * every consumer (the transport, the EventSource fetch resolver) only
232
+ * needs that subset.
233
+ *
234
+ * @internal
200
235
  */
201
- requester?: Requester
236
+ resolveFetch?: (proxyUrl?: string) => FetchFunction
202
237
 
203
238
  /**
204
239
  * Adds a `resultSourceMap` key to the API response, with the type `ContentSourceMap`
205
240
  */
206
241
  resultSourceMap?: boolean | 'withKeyArraySelector'
207
242
  /**
208
- *@deprecated set `cache` and `next` options on `client.fetch` instead
243
+ * @deprecated set `cache` and `next` options on `client.fetch` instead
209
244
  */
210
245
  fetch?:
211
246
  | {
@@ -221,33 +256,6 @@ export interface ClientConfig {
221
256
  * Lineage token for recursion control
222
257
  */
223
258
  lineage?: string
224
-
225
- /**
226
- * A custom request handler that intercepts all HTTP requests made by the client.
227
- *
228
- * Useful for logging, adding custom headers, refreshing auth tokens, rate limiting, etc.
229
- *
230
- * When using `withConfig()`, the new handler **replaces** the previous one (it does not
231
- * wrap it). To compose handlers, you can chain them manually:
232
- *
233
- * ```ts
234
- * const parent = createClient({...config, _requestHandler: handlerA})
235
- * const child = parent.withConfig({
236
- * _requestHandler: (req, defaultRequester) =>
237
- * handlerB(req, (opts) => handlerA(opts, defaultRequester)),
238
- * })
239
- * ```
240
- *
241
- * Setting `_requestHandler` to `undefined` via `withConfig()` removes the handler.
242
- *
243
- * Note: This only applies to HTTP requests. Real-time listener connections
244
- * (`client.listen()`) use EventSource and are not intercepted by this handler.
245
- *
246
- * @internal
247
- * @deprecated Don't use outside of Sanity internals
248
- * @see {@link RequestHandler}
249
- */
250
- _requestHandler?: RequestHandler
251
259
  }
252
260
 
253
261
  /** @public */
@@ -274,6 +282,14 @@ export interface InitializedClientConfig extends ClientConfig {
274
282
  * The fully initialized stega config, can be used to check if stega is enabled
275
283
  */
276
284
  stega: InitializedStegaConfig
285
+ /**
286
+ * The resolved low-level requester for this client. Always populated by
287
+ * `createClient` so internal paths (e.g. the asset upload event stream) can
288
+ * reach the underlying transport.
289
+ *
290
+ * @internal
291
+ */
292
+ requester: Requester
277
293
  /**
278
294
  * Default headers to include with all requests
279
295
  *
@@ -311,7 +327,10 @@ export interface UploadClientConfig {
311
327
  filename?: string
312
328
 
313
329
  /**
314
- * Milliseconds to wait before timing the request out
330
+ * Milliseconds to wait before timing the request out.
331
+ *
332
+ * Unlike other requests, uploads have NO timeout unless one is explicitly
333
+ * set here — uploads can legitimately be slow, so timing out is opt-in.
315
334
  */
316
335
  timeout?: number
317
336
 
@@ -453,63 +472,56 @@ export interface ErrorProps {
453
472
  details: Any
454
473
  }
455
474
 
456
- /** @public */
475
+ /**
476
+ * The internal HTTP request abstraction used by the client. Resolves directly
477
+ * to the parsed response body as a Promise — middleware-level transport
478
+ * details (status codes, headers, progress events) are not exposed. The
479
+ * observable client surface wraps this in an Observable; the promise surface
480
+ * uses it directly.
481
+ *
482
+ * The body is typed as `unknown`; consumers narrow at their own boundary.
483
+ *
484
+ * @internal
485
+ */
457
486
  export type HttpRequest = {
458
- (options: RequestOptions, requester: Requester): ReturnType<Requester>
487
+ (options: Any): Promise<unknown>
459
488
  }
460
489
 
461
490
  /**
462
- * A function that intercepts HTTP requests made by the client.
463
- *
464
- * Receives the resolved request options, a `defaultRequester` function that
465
- * executes the request through the normal pipeline, and a `client` instance
466
- * without a `_requestHandler` (to avoid recursive interception).
467
- *
468
- * The consumer can:
469
- * - Modify request options before calling `defaultRequester`
470
- * - Transform the response stream (e.g. via `pipe`)
471
- * - Skip `defaultRequester` entirely and return a custom Observable
472
- * - Use `client` to make additional requests (e.g. refresh an auth token on 401)
473
- *
474
- * When set via `withConfig()`, the new handler **replaces** (not wraps) the previous one.
475
- *
476
- * Note: This only applies to HTTP requests. Real-time listener connections
477
- * (`client.listen()`) use EventSource and are not intercepted by this handler.
478
- *
479
- * @param request - The resolved request options including `url`
480
- * @param defaultRequester - Executes the request through the normal pipeline
481
- * @param client - A client instance with the same configuration but without a `_requestHandler`,
482
- * useful for making side requests (e.g. token refresh) without triggering the handler recursively
491
+ * Target URL for a request. Exactly one of `url` or the deprecated `uri` alias
492
+ * must be given.
483
493
  *
484
494
  * @internal
485
- * @deprecated Don't use outside of Sanity internals
486
495
  */
487
- export type RequestHandler = (
488
- request: RequestOptions & {url: string},
489
- defaultRequester: (options: RequestOptions & {url: string}) => Observable<HttpRequestEvent>,
490
- client: SanityClient,
491
- ) => Observable<HttpRequestEvent>
496
+ export type RequestUrlOptions =
497
+ | {url: string; uri?: never}
498
+ | {
499
+ /**
500
+ * @deprecated Use `url` instead. Support for `uri` will be removed in a future version.
501
+ */
502
+ uri: string
503
+ url?: never
504
+ }
492
505
 
493
506
  /** @internal */
494
- export interface RequestObservableOptions extends Omit<RequestOptions, 'url'> {
495
- url?: string
496
- uri?: string
497
- canUseCdn?: boolean
498
- useCdn?: boolean
499
- tag?: string
500
- returnQuery?: boolean
501
- resultSourceMap?: boolean | 'withKeyArraySelector'
502
- perspective?: ClientPerspective
503
- /**
504
- * @beta
505
- */
506
- variant?: ClientVariant
507
- lastLiveEventId?: string
508
- cacheMode?: 'noStale'
509
- }
507
+ export type RequestObservableOptions = RequestUrlOptions &
508
+ Omit<RequestOptions, 'url'> & {
509
+ canUseCdn?: boolean
510
+ useCdn?: boolean
511
+ tag?: string
512
+ returnQuery?: boolean
513
+ resultSourceMap?: boolean | 'withKeyArraySelector'
514
+ perspective?: ClientPerspective
515
+ /**
516
+ * @beta
517
+ */
518
+ variant?: ClientVariant
519
+ lastLiveEventId?: string
520
+ cacheMode?: 'noStale'
521
+ }
510
522
 
511
523
  /** @public */
512
- export interface ProgressEvent {
524
+ export interface UploadProgressEvent {
513
525
  type: 'progress'
514
526
  stage: 'upload' | 'download'
515
527
  percent: number
@@ -519,18 +531,20 @@ export interface ProgressEvent {
519
531
  }
520
532
 
521
533
  /** @public */
522
- export interface ResponseEvent<T = unknown> {
534
+ export interface UploadResponseEvent<T = unknown> {
523
535
  type: 'response'
524
536
  body: T
525
- url: string
526
- method: string
527
- statusCode: number
528
- statusMessage?: string
529
- headers: Record<string, string>
530
537
  }
531
538
 
532
- /** @public */
533
- export type HttpRequestEvent<T = unknown> = ResponseEvent<T> | ProgressEvent
539
+ /**
540
+ * Events emitted by `client.assets.upload()` when called via the observable
541
+ * API. Progress events are best-effort — they're only emitted when the
542
+ * environment supports tracking upload/download bytes (e.g. browsers via
543
+ * `XMLHttpRequest`). Other runtimes only emit the terminal `response` event.
544
+ *
545
+ * @public
546
+ */
547
+ export type UploadEvent<T = unknown> = UploadResponseEvent<T> | UploadProgressEvent
534
548
 
535
549
  /** @internal */
536
550
  export interface AuthProvider {
@@ -682,7 +696,7 @@ export interface PatchOperations {
682
696
 
683
697
  /** @public */
684
698
  export interface QueryParams {
685
- /* eslint-disable @typescript-eslint/no-explicit-any */
699
+ /* oxlint-disable typescript/no-explicit-any */
686
700
  [key: string]: any
687
701
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
688
702
  body?: never
@@ -722,7 +736,7 @@ export interface QueryParams {
722
736
  lastLiveEventId?: never
723
737
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
724
738
  cacheMode?: never
725
- /* eslint-enable @typescript-eslint/no-explicit-any */
739
+ /* oxlint-enable typescript/no-explicit-any */
726
740
  }
727
741
 
728
742
  /**
@@ -1619,11 +1633,10 @@ export interface MultipleActionResult {
1619
1633
  }
1620
1634
 
1621
1635
  /** @internal */
1622
- export interface RawRequestOptions {
1623
- url?: string
1624
- uri?: string
1636
+ export type RawRequestOptions = RequestUrlOptions & {
1625
1637
  method?: string
1626
1638
  token?: string
1639
+ /** @deprecated has no effect — response parsing is driven by the response `content-type` */
1627
1640
  json?: boolean
1628
1641
  tag?: string
1629
1642
  useGlobalApi?: boolean
@@ -1631,9 +1644,10 @@ export interface RawRequestOptions {
1631
1644
  query?: {[key: string]: string | string[]}
1632
1645
  headers?: {[key: string]: string}
1633
1646
  timeout?: number
1634
- proxy?: string
1635
1647
  body?: Any
1636
1648
  maxRedirects?: number
1649
+ /** Max retries for this request; `0` disables retries. Overrides the client-level maximum in both directions. */
1650
+ maxRetries?: number
1637
1651
  signal?: AbortSignal
1638
1652
  }
1639
1653
 
@@ -1,6 +1,6 @@
1
- import {lastValueFrom, type Observable} from 'rxjs'
1
+ import {type Observable} from 'rxjs'
2
2
 
3
- import {_request} from '../data/dataMethods'
3
+ import {_request, _requestObservable} from '../data/dataMethods'
4
4
  import type {ObservableSanityClient, SanityClient} from '../SanityClient'
5
5
  import type {CurrentSanityUser, HttpRequest, SanityUser} from '../types'
6
6
 
@@ -18,13 +18,11 @@ export class ObservableUsersClient {
18
18
  *
19
19
  * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
20
20
  */
21
- getById<T extends 'me' | string>(
22
- id: T,
23
- ): Observable<T extends 'me' ? CurrentSanityUser : SanityUser> {
24
- return _request<T extends 'me' ? CurrentSanityUser : SanityUser>(
21
+ getById<T extends string>(id: T): Observable<T extends 'me' ? CurrentSanityUser : SanityUser> {
22
+ return _requestObservable<T extends 'me' ? CurrentSanityUser : SanityUser>(
25
23
  this.#client,
26
24
  this.#httpRequest,
27
- {uri: `/users/${id}`},
25
+ {url: `/users/${id}`},
28
26
  )
29
27
  }
30
28
  }
@@ -43,13 +41,11 @@ export class UsersClient {
43
41
  *
44
42
  * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
45
43
  */
46
- getById<T extends 'me' | string>(
47
- id: T,
48
- ): Promise<T extends 'me' ? CurrentSanityUser : SanityUser> {
49
- return lastValueFrom(
50
- _request<T extends 'me' ? CurrentSanityUser : SanityUser>(this.#client, this.#httpRequest, {
51
- uri: `/users/${id}`,
52
- }),
44
+ getById<T extends string>(id: T): Promise<T extends 'me' ? CurrentSanityUser : SanityUser> {
45
+ return _request<T extends 'me' ? CurrentSanityUser : SanityUser>(
46
+ this.#client,
47
+ this.#httpRequest,
48
+ {url: `/users/${id}`},
53
49
  )
54
50
  }
55
51
  }
@@ -44,7 +44,7 @@ function _shareReplayLatest<T>(config: ShareReplayLatestConfig<T>): MonoTypeOper
44
44
  let latest: T | undefined
45
45
  let emitted = false
46
46
 
47
- // eslint-disable-next-line unused-imports/no-unused-vars
47
+ // oxlint-disable-next-line no-unused-vars
48
48
  const {predicate, ...shareConfig} = config
49
49
 
50
50
  const wrapped = source.pipe(
package/src/warnings.ts CHANGED
@@ -3,7 +3,7 @@ import {type Any} from './types'
3
3
  import {once} from './util/once'
4
4
 
5
5
  const createWarningPrinter = (message: string[]) =>
6
- // eslint-disable-next-line no-console
6
+ // oxlint-disable-next-line no-console
7
7
  once((...args: Any[]) => console.warn(message.join(' '), ...args))
8
8
 
9
9
  export const printCdnAndWithCredentialsWarning = createWarningPrinter([
@@ -51,6 +51,11 @@ export const printCreateVersionWithBaseIdWarning = createWarningPrinter([
51
51
  'You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead.',
52
52
  ])
53
53
 
54
+ export const printDeprecatedUriOptionWarning = createWarningPrinter([
55
+ 'The `uri` request option has been renamed to `url`.',
56
+ 'Please update your code to use `url` instead. Support for `uri` will be removed in a future version.',
57
+ ])
58
+
54
59
  export const printDeprecatedResourceConfigWarning = createWarningPrinter([
55
60
  'The `~experimental_resource` configuration property has been renamed to `resource`.',
56
61
  'Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version.',
@@ -1,206 +0,0 @@
1
- "use strict";
2
- const BASE_URL = "https://www.sanity.io/help/";
3
- function generateHelpUrl(slug) {
4
- return BASE_URL + slug;
5
- }
6
- const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before", "after", "replace"], dataset = (name) => {
7
- if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name))
8
- throw new Error(
9
- "Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters"
10
- );
11
- }, projectId = (id) => {
12
- if (!/^[-a-z0-9]+$/i.test(id))
13
- throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
14
- }, validateAssetType = (type) => {
15
- if (VALID_ASSET_TYPES.indexOf(type) === -1)
16
- throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
17
- }, validateObject = (op, val) => {
18
- if (val === null || typeof val != "object" || Array.isArray(val))
19
- throw new Error(`${op}() takes an object of properties`);
20
- }, validateDocumentId = (op, id) => {
21
- if (typeof id != "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(".."))
22
- throw new Error(`${op}(): "${id}" is not a valid document ID`);
23
- }, requireDocumentId = (op, doc) => {
24
- if (!doc._id)
25
- throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
26
- validateDocumentId(op, doc._id);
27
- }, validateDocumentType = (op, type) => {
28
- if (typeof type != "string")
29
- throw new Error(`\`${op}()\`: \`${type}\` is not a valid document type`);
30
- }, requireDocumentType = (op, doc) => {
31
- if (!doc._type)
32
- throw new Error(`\`${op}()\` requires that the document contains a type (\`_type\` property)`);
33
- validateDocumentType(op, doc._type);
34
- }, validateVersionIdMatch = (builtVersionId, document) => {
35
- if (document._id && document._id !== builtVersionId)
36
- throw new Error(
37
- `The provided document ID (\`${document._id}\`) does not match the generated version ID (\`${builtVersionId}\`)`
38
- );
39
- }, validateInsert = (at, selector, items) => {
40
- const signature = "insert(at, selector, items)";
41
- if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
42
- const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
43
- throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
44
- }
45
- if (typeof selector != "string")
46
- throw new Error(`${signature} takes a "selector"-argument which must be a string`);
47
- if (!Array.isArray(items))
48
- throw new Error(`${signature} takes an "items"-argument which must be an array`);
49
- }, hasDataset = (config) => {
50
- if (config.dataset)
51
- return config.dataset;
52
- const resource = config.resource;
53
- if (resource && resource.type === "dataset") {
54
- const segments = resource.id.split(".");
55
- if (segments.length !== 2)
56
- throw new Error('Dataset resource ID must be in the format "project.dataset"');
57
- return segments[1];
58
- }
59
- throw new Error("`dataset` must be provided to perform queries");
60
- }, requestTag = (tag) => {
61
- if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
62
- throw new Error(
63
- "Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long."
64
- );
65
- return tag;
66
- }, resourceConfig = (config) => {
67
- const resource = config.resource;
68
- if (!resource)
69
- throw new Error("`resource` must be provided to perform resource queries");
70
- const { type, id } = resource;
71
- switch (type) {
72
- case "dataset": {
73
- if (id.split(".").length !== 2)
74
- throw new Error('Dataset resource ID must be in the format "project.dataset"');
75
- return;
76
- }
77
- case "dashboard":
78
- case "media-library":
79
- case "canvas":
80
- return;
81
- default:
82
- throw new Error(`Unsupported resource type: ${type.toString()}`);
83
- }
84
- }, resourceGuard = (service, config) => {
85
- if (config.resource)
86
- throw new Error(`\`${service}\` does not support resource-based operations`);
87
- };
88
- function once(fn) {
89
- let didCall = !1, returnValue;
90
- return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
91
- }
92
- const createWarningPrinter = (message) => (
93
- // eslint-disable-next-line no-console
94
- once((...args) => console.warn(message.join(" "), ...args))
95
- ), printCdnAndWithCredentialsWarning = createWarningPrinter([
96
- "Because you set `withCredentials` to true, we will override your `useCdn`",
97
- "setting to be false since (cookie-based) credentials are never set on the CDN"
98
- ]), printCdnWarning = createWarningPrinter([
99
- "Since you haven't set a value for `useCdn`, we will deliver content using our",
100
- "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
101
- "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
102
- ]), printCdnPreviewDraftsWarning = createWarningPrinter([
103
- "The Sanity client is configured with the `perspective` set to `drafts` or `previewDrafts`, which doesn't support the API-CDN.",
104
- "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
105
- ]), printPreviewDraftsDeprecationWarning = createWarningPrinter([
106
- "The `previewDrafts` perspective has been renamed to `drafts` and will be removed in a future API version"
107
- ]), printBrowserTokenWarning = createWarningPrinter([
108
- "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
109
- `See ${generateHelpUrl(
110
- "js-client-browser-token"
111
- )} for more information and how to hide this warning.`
112
- ]), printCredentialedTokenWarning = createWarningPrinter([
113
- "You have configured Sanity client to use a token, but also provided `withCredentials: true`.",
114
- "This is no longer supported - only token will be used - remove `withCredentials: true`."
115
- ]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
116
- "Using the Sanity client without specifying an API version is deprecated.",
117
- `See ${generateHelpUrl("js-client-api-version")}`
118
- ]), printNoDefaultExport = createWarningPrinter([
119
- "The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
120
- ]), printCreateVersionWithBaseIdWarning = createWarningPrinter([
121
- "You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead."
122
- ]), printDeprecatedResourceConfigWarning = createWarningPrinter([
123
- "The `~experimental_resource` configuration property has been renamed to `resource`.",
124
- "Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version."
125
- ]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
126
- apiHost: "https://api.sanity.io",
127
- apiVersion: "1",
128
- useProjectHostname: !0,
129
- stega: { enabled: !1 }
130
- }, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
131
- function validateApiVersion(apiVersion) {
132
- if (apiVersion === "1" || apiVersion === "X")
133
- return;
134
- const apiDate = new Date(apiVersion);
135
- if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
136
- throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
137
- }
138
- function validateApiPerspective(perspective) {
139
- if (Array.isArray(perspective) && perspective.length > 1 && perspective.includes("raw"))
140
- throw new TypeError(
141
- 'Invalid API perspective value: "raw". The raw-perspective can not be combined with other perspectives'
142
- );
143
- }
144
- const initConfig = (config, prevConfig) => {
145
- const specifiedConfig = {
146
- ...prevConfig,
147
- ...config,
148
- stega: {
149
- ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
150
- ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
151
- }
152
- };
153
- specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
154
- const newConfig = {
155
- ...defaultConfig,
156
- ...specifiedConfig
157
- };
158
- newConfig["~experimental_resource"] && !newConfig.resource && (printDeprecatedResourceConfigWarning(), newConfig.resource = newConfig["~experimental_resource"]);
159
- const resourceConfig$1 = newConfig.resource, projectBased = newConfig.useProjectHostname && !resourceConfig$1;
160
- if (typeof Promise > "u") {
161
- const helpUrl = generateHelpUrl("js-client-promise-polyfill");
162
- throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
163
- }
164
- if (projectBased && !newConfig.projectId)
165
- throw new Error("Configuration must contain `projectId`");
166
- if (resourceConfig$1 && resourceConfig(newConfig), typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
167
- throw new Error(
168
- "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'?"
169
- );
170
- if ("encodeSourceMapAtPath" in newConfig)
171
- throw new Error(
172
- "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'?"
173
- );
174
- if (typeof newConfig.stega.enabled != "boolean")
175
- throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
176
- if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
177
- throw new Error("stega.studioUrl must be defined when stega.enabled is true");
178
- if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
179
- throw new Error(
180
- `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
181
- );
182
- const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname), hasToken = !!newConfig.token;
183
- newConfig.withCredentials && hasToken && (printCredentialedTokenWarning(), newConfig.withCredentials = !1), isBrowser && isLocalhost && hasToken && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > "u" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), "requestTagPrefix" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, ""), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);
184
- const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
185
- return projectBased ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
186
- };
187
- exports.dataset = dataset;
188
- exports.defaultConfig = defaultConfig;
189
- exports.hasDataset = hasDataset;
190
- exports.initConfig = initConfig;
191
- exports.printCdnPreviewDraftsWarning = printCdnPreviewDraftsWarning;
192
- exports.printCreateVersionWithBaseIdWarning = printCreateVersionWithBaseIdWarning;
193
- exports.printNoDefaultExport = printNoDefaultExport;
194
- exports.printPreviewDraftsDeprecationWarning = printPreviewDraftsDeprecationWarning;
195
- exports.requestTag = requestTag;
196
- exports.requireDocumentId = requireDocumentId;
197
- exports.requireDocumentType = requireDocumentType;
198
- exports.resourceConfig = resourceConfig;
199
- exports.resourceGuard = resourceGuard;
200
- exports.validateApiPerspective = validateApiPerspective;
201
- exports.validateAssetType = validateAssetType;
202
- exports.validateDocumentId = validateDocumentId;
203
- exports.validateInsert = validateInsert;
204
- exports.validateObject = validateObject;
205
- exports.validateVersionIdMatch = validateVersionIdMatch;
206
- //# sourceMappingURL=config.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.cjs","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 // eslint-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 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"],"names":["warnings.printNoApiVersionSpecifiedWarning","warnings.printDeprecatedResourceConfigWarning","resourceConfig","validate.resourceConfig","warnings.printCredentialedTokenWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning"],"mappings":";AAAA,MAAM,WAAW;AAEV,SAAS,gBAAgB,MAAc;AAC5C,SAAO,WAAW;AACpB;ACFA,MAAM,oBAAoB,CAAC,SAAS,MAAM,GACpC,yBAAyB,CAAC,UAAU,SAAS,SAAS,GAE/C,UAAU,CAAC,SAAiB;AACvC,MAAI,CAAC,qDAAqD,KAAK,IAAI;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGN,GAEa,YAAY,CAAC,OAAe;AACvC,MAAI,CAAC,gBAAgB,KAAK,EAAE;AAC1B,UAAM,IAAI,MAAM,uDAAuD;AAE3E,GAEa,oBAAoB,CAAC,SAAiB;AACjD,MAAI,kBAAkB,QAAQ,IAAI,MAAM;AACtC,UAAM,IAAI,MAAM,uBAAuB,IAAI,oBAAoB,kBAAkB,KAAK,IAAI,CAAC,EAAE;AAEjG,GAEa,iBAAiB,CAAC,IAAY,QAAa;AACtD,MAAI,QAAQ,QAAQ,OAAO,OAAQ,YAAY,MAAM,QAAQ,GAAG;AAC9D,UAAM,IAAI,MAAM,GAAG,EAAE,kCAAkC;AAE3D,GAEa,qBAAqB,CAAC,IAAY,OAAe;AAC5D,MAAI,OAAO,MAAO,YAAY,CAAC,iCAAiC,KAAK,EAAE,KAAK,GAAG,SAAS,IAAI;AAC1F,UAAM,IAAI,MAAM,GAAG,EAAE,QAAQ,EAA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