@sanity/client 7.13.2 → 7.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -4
- package/dist/_chunks-cjs/config.cjs +21 -8
- package/dist/_chunks-cjs/config.cjs.map +1 -1
- package/dist/_chunks-es/config.js +21 -8
- package/dist/_chunks-es/config.js.map +1 -1
- package/dist/index.browser.cjs +40 -18
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.d.cts +22 -1
- package/dist/index.browser.d.ts +22 -1
- package/dist/index.browser.js +40 -18
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +20 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -1
- package/dist/index.d.ts +22 -1
- package/dist/index.js +20 -11
- package/dist/index.js.map +1 -1
- package/dist/stega.browser.d.cts +22 -1
- package/dist/stega.browser.d.ts +22 -1
- package/dist/stega.d.cts +22 -1
- package/dist/stega.d.ts +22 -1
- package/package.json +2 -2
- package/src/assets/AssetsClient.ts +25 -11
- package/src/config.ts +10 -2
- package/src/data/dataMethods.ts +12 -6
- package/src/mediaLibrary/MediaLibraryVideoClient.ts +3 -1
- package/src/types.ts +23 -1
- package/src/validators.ts +22 -6
- package/src/warnings.ts +5 -0
- package/umd/sanityClient.js +40 -18
- package/umd/sanityClient.min.js +2 -2
package/README.md
CHANGED
|
@@ -2278,22 +2278,84 @@ const result = await client.agent.action.patch({
|
|
|
2278
2278
|
|
|
2279
2279
|
### Media Library API
|
|
2280
2280
|
|
|
2281
|
-
The Media Library provides centralized asset management for your organization. Store, organize, and manage digital assets across multiple applications and datasets
|
|
2281
|
+
The Media Library provides centralized asset management for your organization. Store, organize, and manage digital assets across multiple applications and datasets.
|
|
2282
|
+
|
|
2283
|
+
When you configure the client with a Media Library resource, you can use familiar methods like `fetch()` and `assets.upload()` to work with your media library.
|
|
2282
2284
|
|
|
2283
2285
|
👉 Read more about [Media Library in Sanity](https://www.sanity.io/docs/media-library)
|
|
2284
2286
|
|
|
2285
|
-
####
|
|
2287
|
+
#### Configuration
|
|
2286
2288
|
|
|
2287
2289
|
```js
|
|
2290
|
+
import {createClient} from '@sanity/client'
|
|
2291
|
+
|
|
2288
2292
|
const client = createClient({
|
|
2289
2293
|
token: 'valid-token',
|
|
2290
2294
|
useCdn: false,
|
|
2291
|
-
|
|
2295
|
+
resource: {
|
|
2292
2296
|
type: 'media-library',
|
|
2293
|
-
id: '
|
|
2297
|
+
id: 'your-media-library-id',
|
|
2294
2298
|
},
|
|
2295
2299
|
})
|
|
2300
|
+
```
|
|
2301
|
+
|
|
2302
|
+
#### Querying assets
|
|
2303
|
+
|
|
2304
|
+
Use `client.fetch()` to query assets in your Media Library using GROQ:
|
|
2305
|
+
|
|
2306
|
+
```js
|
|
2307
|
+
// Query all assets
|
|
2308
|
+
const assets = await client.fetch('*[_type == "sanity.asset"]')
|
|
2309
|
+
|
|
2310
|
+
// Query video assets
|
|
2311
|
+
const videos = await client.fetch('*[assetType == "sanity.videoAsset"]')
|
|
2312
|
+
|
|
2313
|
+
// Query with filters
|
|
2314
|
+
const recentAssets = await client.fetch('*[_type == "sanity.asset" && _createdAt > $date]', {
|
|
2315
|
+
date: '2025-01-01',
|
|
2316
|
+
})
|
|
2317
|
+
```
|
|
2318
|
+
|
|
2319
|
+
#### Uploading assets
|
|
2320
|
+
|
|
2321
|
+
Use `client.assets.upload()` to upload assets to your Media Library:
|
|
2322
|
+
|
|
2323
|
+
```js
|
|
2324
|
+
import fs from 'node:fs'
|
|
2325
|
+
|
|
2326
|
+
// Upload an image
|
|
2327
|
+
const imageAsset = await client.assets.upload('image', fs.createReadStream('photo.jpg'), {
|
|
2328
|
+
filename: 'photo.jpg',
|
|
2329
|
+
title: 'My Photo',
|
|
2330
|
+
})
|
|
2331
|
+
|
|
2332
|
+
// Upload a video
|
|
2333
|
+
const videoAsset = await client.assets.upload('file', fs.createReadStream('video.mp4'), {
|
|
2334
|
+
filename: 'video.mp4',
|
|
2335
|
+
})
|
|
2336
|
+
```
|
|
2337
|
+
|
|
2338
|
+
#### Deleting assets
|
|
2339
|
+
|
|
2340
|
+
Media Library uses the mutation API for deletions:
|
|
2341
|
+
|
|
2342
|
+
```js
|
|
2343
|
+
// Delete a single asset
|
|
2344
|
+
await client.delete('36fOGtOJOadpl4F9xpksb9uKjYp')
|
|
2296
2345
|
|
|
2346
|
+
// Delete both the asset and its draft (recommended)
|
|
2347
|
+
await client
|
|
2348
|
+
.transaction()
|
|
2349
|
+
.delete('36fOGtOJOadpl4F9xpksb9uKjYp')
|
|
2350
|
+
.delete('drafts.36fOGtOJOadpl4F9xpksb9uKjYp')
|
|
2351
|
+
.commit()
|
|
2352
|
+
```
|
|
2353
|
+
|
|
2354
|
+
#### Getting video playback information
|
|
2355
|
+
|
|
2356
|
+
For video assets, use the specialized `getPlaybackInfo()` method to retrieve streaming URLs:
|
|
2357
|
+
|
|
2358
|
+
```js
|
|
2297
2359
|
// Basic usage with video asset ID
|
|
2298
2360
|
const playbackInfo = await client.mediaLibrary.video.getPlaybackInfo(
|
|
2299
2361
|
'video-30rh9U3GDEK3ToiId1Zje4uvalC-mp4',
|
|
@@ -47,9 +47,16 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
47
47
|
if (!Array.isArray(items))
|
|
48
48
|
throw new Error(`${signature} takes an "items"-argument which must be an array`);
|
|
49
49
|
}, hasDataset = (config) => {
|
|
50
|
-
if (
|
|
51
|
-
|
|
52
|
-
|
|
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");
|
|
53
60
|
}, requestTag = (tag) => {
|
|
54
61
|
if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
|
|
55
62
|
throw new Error(
|
|
@@ -57,9 +64,10 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
57
64
|
);
|
|
58
65
|
return tag;
|
|
59
66
|
}, resourceConfig = (config) => {
|
|
60
|
-
|
|
67
|
+
const resource = config.resource;
|
|
68
|
+
if (!resource)
|
|
61
69
|
throw new Error("`resource` must be provided to perform resource queries");
|
|
62
|
-
const { type, id } =
|
|
70
|
+
const { type, id } = resource;
|
|
63
71
|
switch (type) {
|
|
64
72
|
case "dataset": {
|
|
65
73
|
if (id.split(".").length !== 2)
|
|
@@ -74,7 +82,7 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
74
82
|
throw new Error(`Unsupported resource type: ${type.toString()}`);
|
|
75
83
|
}
|
|
76
84
|
}, resourceGuard = (service, config) => {
|
|
77
|
-
if (config
|
|
85
|
+
if (config.resource)
|
|
78
86
|
throw new Error(`\`${service}\` does not support resource-based operations`);
|
|
79
87
|
};
|
|
80
88
|
function once(fn) {
|
|
@@ -111,6 +119,9 @@ const createWarningPrinter = (message) => (
|
|
|
111
119
|
"The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
|
|
112
120
|
]), printCreateVersionWithBaseIdWarning = createWarningPrinter([
|
|
113
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."
|
|
114
125
|
]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
|
|
115
126
|
apiHost: "https://api.sanity.io",
|
|
116
127
|
apiVersion: "1",
|
|
@@ -143,14 +154,16 @@ const initConfig = (config, prevConfig) => {
|
|
|
143
154
|
const newConfig = {
|
|
144
155
|
...defaultConfig,
|
|
145
156
|
...specifiedConfig
|
|
146
|
-
}
|
|
157
|
+
};
|
|
158
|
+
newConfig["~experimental_resource"] && !newConfig.resource && (printDeprecatedResourceConfigWarning(), newConfig.resource = newConfig["~experimental_resource"]);
|
|
159
|
+
const resourceConfig$1 = newConfig.resource, projectBased = newConfig.useProjectHostname && !resourceConfig$1;
|
|
147
160
|
if (typeof Promise > "u") {
|
|
148
161
|
const helpUrl = generateHelpUrl("js-client-promise-polyfill");
|
|
149
162
|
throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
|
|
150
163
|
}
|
|
151
164
|
if (projectBased && !newConfig.projectId)
|
|
152
165
|
throw new Error("Configuration must contain `projectId`");
|
|
153
|
-
if (
|
|
166
|
+
if (resourceConfig$1 && resourceConfig(newConfig), typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
|
|
154
167
|
throw new Error(
|
|
155
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'?"
|
|
156
169
|
);
|
|
@@ -1 +1 @@
|
|
|
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 if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\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 if (!config['~experimental_resource']) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = config['~experimental_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 if (config['~experimental_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","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 const projectBased = newConfig.useProjectHostname && !newConfig['~experimental_resource']\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 (newConfig['~experimental_resource']) {\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","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;AACnC,MAAA,CAAC,qDAAqD,KAAK,IAAI;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAEJ,GAEa,YAAY,CAAC,OAAe;AACnC,MAAA,CAAC,gBAAgB,KAAK,EAAE;AACpB,UAAA,IAAI,MAAM,uDAAuD;AAE3E,GAEa,oBAAoB,CAAC,SAAiB;AAC7C,MAAA,kBAAkB,QAAQ,IAAI,MAAM;AAChC,UAAA,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,G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AAE,QAAQ,QAAQ,EAAE,IAClE,SAGN,UAAU,aAAa,GAAG,UAAU,UAAU,GAAG,QAAQ,MAAM,EAAE,GACjE,UAAU,eAAe,UAAU,YAAY,cAAc,SAEzD,UAAU,WAAW,MAAQ,UAAU,mBACzCC,kCAA2C,GAI7C,UAAU,SAAS,UAAU,WAAW,MAAS,CAAC,UAAU,iBAE5D,mBAAmB,UAAU,UAAU;AAEvC,QAAM,YAAY,UAAU,QAAQ,MAAM,OAAO,CAAC,GAC5C,WAAW,UAAU,CAAC,GACtB,OAAO,UAAU,CAAC,GAClB,UAAU,UAAU,eAAe,iBAAiB;AAE1D,SAAI,gBACF,UAAU,MAAM,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE3F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;;;;;;;;;;;;;;;;;;;;"}
|
|
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;AACnC,MAAA,CAAC,qDAAqD,KAAK,IAAI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IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE3F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -46,9 +46,16 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
46
46
|
if (!Array.isArray(items))
|
|
47
47
|
throw new Error(`${signature} takes an "items"-argument which must be an array`);
|
|
48
48
|
}, hasDataset = (config) => {
|
|
49
|
-
if (
|
|
50
|
-
|
|
51
|
-
|
|
49
|
+
if (config.dataset)
|
|
50
|
+
return config.dataset;
|
|
51
|
+
const resource = config.resource;
|
|
52
|
+
if (resource && resource.type === "dataset") {
|
|
53
|
+
const segments = resource.id.split(".");
|
|
54
|
+
if (segments.length !== 2)
|
|
55
|
+
throw new Error('Dataset resource ID must be in the format "project.dataset"');
|
|
56
|
+
return segments[1];
|
|
57
|
+
}
|
|
58
|
+
throw new Error("`dataset` must be provided to perform queries");
|
|
52
59
|
}, requestTag = (tag) => {
|
|
53
60
|
if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
|
|
54
61
|
throw new Error(
|
|
@@ -56,9 +63,10 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
56
63
|
);
|
|
57
64
|
return tag;
|
|
58
65
|
}, resourceConfig = (config) => {
|
|
59
|
-
|
|
66
|
+
const resource = config.resource;
|
|
67
|
+
if (!resource)
|
|
60
68
|
throw new Error("`resource` must be provided to perform resource queries");
|
|
61
|
-
const { type, id } =
|
|
69
|
+
const { type, id } = resource;
|
|
62
70
|
switch (type) {
|
|
63
71
|
case "dataset": {
|
|
64
72
|
if (id.split(".").length !== 2)
|
|
@@ -73,7 +81,7 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
73
81
|
throw new Error(`Unsupported resource type: ${type.toString()}`);
|
|
74
82
|
}
|
|
75
83
|
}, resourceGuard = (service, config) => {
|
|
76
|
-
if (config
|
|
84
|
+
if (config.resource)
|
|
77
85
|
throw new Error(`\`${service}\` does not support resource-based operations`);
|
|
78
86
|
};
|
|
79
87
|
function once(fn) {
|
|
@@ -110,6 +118,9 @@ const createWarningPrinter = (message) => (
|
|
|
110
118
|
"The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
|
|
111
119
|
]), printCreateVersionWithBaseIdWarning = createWarningPrinter([
|
|
112
120
|
"You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead."
|
|
121
|
+
]), printDeprecatedResourceConfigWarning = createWarningPrinter([
|
|
122
|
+
"The `~experimental_resource` configuration property has been renamed to `resource`.",
|
|
123
|
+
"Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version."
|
|
113
124
|
]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
|
|
114
125
|
apiHost: "https://api.sanity.io",
|
|
115
126
|
apiVersion: "1",
|
|
@@ -142,14 +153,16 @@ const initConfig = (config, prevConfig) => {
|
|
|
142
153
|
const newConfig = {
|
|
143
154
|
...defaultConfig,
|
|
144
155
|
...specifiedConfig
|
|
145
|
-
}
|
|
156
|
+
};
|
|
157
|
+
newConfig["~experimental_resource"] && !newConfig.resource && (printDeprecatedResourceConfigWarning(), newConfig.resource = newConfig["~experimental_resource"]);
|
|
158
|
+
const resourceConfig$1 = newConfig.resource, projectBased = newConfig.useProjectHostname && !resourceConfig$1;
|
|
146
159
|
if (typeof Promise > "u") {
|
|
147
160
|
const helpUrl = generateHelpUrl("js-client-promise-polyfill");
|
|
148
161
|
throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
|
|
149
162
|
}
|
|
150
163
|
if (projectBased && !newConfig.projectId)
|
|
151
164
|
throw new Error("Configuration must contain `projectId`");
|
|
152
|
-
if (
|
|
165
|
+
if (resourceConfig$1 && resourceConfig(newConfig), typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
|
|
153
166
|
throw new Error(
|
|
154
167
|
"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'?"
|
|
155
168
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","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 if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\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 if (!config['~experimental_resource']) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = config['~experimental_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 if (config['~experimental_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","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 const projectBased = newConfig.useProjectHostname && !newConfig['~experimental_resource']\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 (newConfig['~experimental_resource']) {\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","validate.resourceConfig","warnings.printCredentialedTokenWarning","warnings.printBrowserTokenWarning","warnings.print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AS,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE3F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;"}
|
|
1
|
+
{"version":3,"file":"config.js","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;AACnC,MAAA,CAAC,qDAAqD,KAAK,IAAI;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAEJ,GAEa,YAAY,CAAC,OAAe;AACnC,MAAA,CAAC,gBAAgB,KAAK,EAAE;AACpB,UAAA,IAAI,MAAM,uDAAuD;AAE3E,GAEa,oBAAoB,CAAC,SAAiB;AAC7C,MAAA,kBAAkB,QAAQ,IAAI,MAAM;AAChC,UAAA,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;AACxD,MAAA,OAAO,MAAO,YAAY,CA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AC/BC,8BAAuC,GACvC,UAAU,kBAAkB,KAG1B,aAAa,eAAe,YAAY,UAAU,8BAA8B,KAClFC,6BACS,OAAO,UAAU,SAAW,OACrCC,mBAGE,gBACFC,UAAmB,UAAU,SAAU,GAGrC,UAAU,WACZC,QAAiB,UAAU,OAAO,GAGhC,sBAAsB,cAExB,UAAU,mBAAmB,UAAU,mBACnCC,WAAoB,UAAU,gBAAgB,EAAE,QAAQ,QAAQ,EAAE,IAClE,SAGN,UAAU,aAAa,GAAG,UAAU,UAAU,GAAG,QAAQ,MAAM,EAAE,GACjE,UAAU,eAAe,UAAU,YAAY,cAAc,SAEzD,UAAU,WAAW,MAAQ,UAAU,mBACzCC,kCAA2C,GAI7C,UAAU,SAAS,UAAU,WAAW,MAAS,CAAC,UAAU,iBAE5D,mBAAmB,UAAU,UAAU;AAEvC,QAAM,YAAY,UAAU,QAAQ,MAAM,OAAO,CAAC,GAC5C,WAAW,UAAU,CAAC,GACtB,OAAO,UAAU,CAAC,GAClB,UAAU,UAAU,eAAe,iBAAiB;AAE1D,SAAI,gBACF,UAAU,MAAM,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE3F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;"}
|
package/dist/index.browser.cjs
CHANGED
|
@@ -271,9 +271,16 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
271
271
|
if (!Array.isArray(items))
|
|
272
272
|
throw new Error(`${signature} takes an "items"-argument which must be an array`);
|
|
273
273
|
}, hasDataset = (config) => {
|
|
274
|
-
if (
|
|
275
|
-
|
|
276
|
-
|
|
274
|
+
if (config.dataset)
|
|
275
|
+
return config.dataset;
|
|
276
|
+
const resource = config.resource;
|
|
277
|
+
if (resource && resource.type === "dataset") {
|
|
278
|
+
const segments = resource.id.split(".");
|
|
279
|
+
if (segments.length !== 2)
|
|
280
|
+
throw new Error('Dataset resource ID must be in the format "project.dataset"');
|
|
281
|
+
return segments[1];
|
|
282
|
+
}
|
|
283
|
+
throw new Error("`dataset` must be provided to perform queries");
|
|
277
284
|
}, requestTag = (tag) => {
|
|
278
285
|
if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
|
|
279
286
|
throw new Error(
|
|
@@ -281,9 +288,10 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
281
288
|
);
|
|
282
289
|
return tag;
|
|
283
290
|
}, resourceConfig = (config) => {
|
|
284
|
-
|
|
291
|
+
const resource = config.resource;
|
|
292
|
+
if (!resource)
|
|
285
293
|
throw new Error("`resource` must be provided to perform resource queries");
|
|
286
|
-
const { type, id } =
|
|
294
|
+
const { type, id } = resource;
|
|
287
295
|
switch (type) {
|
|
288
296
|
case "dataset": {
|
|
289
297
|
if (id.split(".").length !== 2)
|
|
@@ -298,7 +306,7 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
|
|
|
298
306
|
throw new Error(`Unsupported resource type: ${type.toString()}`);
|
|
299
307
|
}
|
|
300
308
|
}, resourceGuard = (service, config) => {
|
|
301
|
-
if (config
|
|
309
|
+
if (config.resource)
|
|
302
310
|
throw new Error(`\`${service}\` does not support resource-based operations`);
|
|
303
311
|
}, EXPERIMENTAL_API_WARNING = "This is an experimental API version";
|
|
304
312
|
function once(fn) {
|
|
@@ -335,6 +343,9 @@ const createWarningPrinter = (message) => (
|
|
|
335
343
|
"The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
|
|
336
344
|
]), printCreateVersionWithBaseIdWarning = createWarningPrinter([
|
|
337
345
|
"You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead."
|
|
346
|
+
]), printDeprecatedResourceConfigWarning = createWarningPrinter([
|
|
347
|
+
"The `~experimental_resource` configuration property has been renamed to `resource`.",
|
|
348
|
+
"Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version."
|
|
338
349
|
]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
|
|
339
350
|
apiHost: "https://api.sanity.io",
|
|
340
351
|
apiVersion: "1",
|
|
@@ -367,14 +378,16 @@ const initConfig = (config, prevConfig) => {
|
|
|
367
378
|
const newConfig = {
|
|
368
379
|
...defaultConfig,
|
|
369
380
|
...specifiedConfig
|
|
370
|
-
}
|
|
381
|
+
};
|
|
382
|
+
newConfig["~experimental_resource"] && !newConfig.resource && (printDeprecatedResourceConfigWarning(), newConfig.resource = newConfig["~experimental_resource"]);
|
|
383
|
+
const resourceConfig$1 = newConfig.resource, projectBased = newConfig.useProjectHostname && !resourceConfig$1;
|
|
371
384
|
if (typeof Promise > "u") {
|
|
372
385
|
const helpUrl = generateHelpUrl("js-client-promise-polyfill");
|
|
373
386
|
throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
|
|
374
387
|
}
|
|
375
388
|
if (projectBased && !newConfig.projectId)
|
|
376
389
|
throw new Error("Configuration must contain `projectId`");
|
|
377
|
-
if (
|
|
390
|
+
if (resourceConfig$1 && resourceConfig(newConfig), typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
|
|
378
391
|
throw new Error(
|
|
379
392
|
"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'?"
|
|
380
393
|
);
|
|
@@ -1090,7 +1103,10 @@ function _create(client, httpRequest, doc, op, options = {}) {
|
|
|
1090
1103
|
const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);
|
|
1091
1104
|
return _dataRequest(client, httpRequest, "mutate", { mutations: [mutation] }, opts);
|
|
1092
1105
|
}
|
|
1093
|
-
const hasDataConfig = (client) =>
|
|
1106
|
+
const hasDataConfig = (client) => {
|
|
1107
|
+
const config = client.config();
|
|
1108
|
+
return config.dataset !== void 0 && config.projectId !== void 0 || config.resource !== void 0;
|
|
1109
|
+
}, isQuery = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "query")), isMutate = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "mutate")), isDoc = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "doc", "")), isListener = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "listen")), isHistory = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "history", "")), isData = (client, uri) => uri.startsWith("/data/") || isQuery(client, uri) || isMutate(client, uri) || isDoc(client, uri) || isListener(client, uri) || isHistory(client, uri);
|
|
1094
1110
|
function _requestObservable(client, httpRequest, options) {
|
|
1095
1111
|
const uri = options.url || options.uri, config = client.config(), canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(client, uri) : options.canUseCdn;
|
|
1096
1112
|
let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn;
|
|
@@ -1123,7 +1139,7 @@ function _request(client, httpRequest, options) {
|
|
|
1123
1139
|
}
|
|
1124
1140
|
function _getDataUrl(client, operation, path) {
|
|
1125
1141
|
const config = client.config();
|
|
1126
|
-
if (config
|
|
1142
|
+
if (config.resource) {
|
|
1127
1143
|
resourceConfig(config);
|
|
1128
1144
|
const resourceBase = resourceDataBase(config), uri2 = path !== void 0 ? `${operation}/${path}` : operation;
|
|
1129
1145
|
return `${resourceBase}/${uri2}`.replace(/\/($|\?)/, "$1");
|
|
@@ -1156,9 +1172,10 @@ function _createAbortError(signal) {
|
|
|
1156
1172
|
return error.name = "AbortError", error;
|
|
1157
1173
|
}
|
|
1158
1174
|
const resourceDataBase = (config) => {
|
|
1159
|
-
|
|
1175
|
+
const resource = config.resource;
|
|
1176
|
+
if (!resource)
|
|
1160
1177
|
throw new Error("`resource` must be provided to perform resource queries");
|
|
1161
|
-
const { type, id } =
|
|
1178
|
+
const { type, id } = resource;
|
|
1162
1179
|
switch (type) {
|
|
1163
1180
|
case "dataset": {
|
|
1164
1181
|
const segments = id.split(".");
|
|
@@ -1319,7 +1336,12 @@ function _upload(client, httpRequest, assetType, body, opts = {}) {
|
|
|
1319
1336
|
validateAssetType(assetType);
|
|
1320
1337
|
let meta = opts.extract || void 0;
|
|
1321
1338
|
meta && !meta.length && (meta = ["none"]);
|
|
1322
|
-
const config = client.config(), options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, query = {
|
|
1339
|
+
const config = client.config(), options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, isMediaLibrary = config.resource?.type === "media-library", query = isMediaLibrary ? {
|
|
1340
|
+
// Media Library only supports basic parameters
|
|
1341
|
+
title,
|
|
1342
|
+
filename
|
|
1343
|
+
} : {
|
|
1344
|
+
// Content Lake supports full set of parameters
|
|
1323
1345
|
label,
|
|
1324
1346
|
title,
|
|
1325
1347
|
description,
|
|
@@ -1327,7 +1349,7 @@ function _upload(client, httpRequest, assetType, body, opts = {}) {
|
|
|
1327
1349
|
meta,
|
|
1328
1350
|
creditLine
|
|
1329
1351
|
};
|
|
1330
|
-
return source && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {
|
|
1352
|
+
return source && !isMediaLibrary && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {
|
|
1331
1353
|
tag,
|
|
1332
1354
|
method: "POST",
|
|
1333
1355
|
timeout: options.timeout || 0,
|
|
@@ -1338,9 +1360,9 @@ function _upload(client, httpRequest, assetType, body, opts = {}) {
|
|
|
1338
1360
|
});
|
|
1339
1361
|
}
|
|
1340
1362
|
function buildAssetUploadUrl(config, assetType) {
|
|
1341
|
-
const assetTypeEndpoint = assetType === "image" ? "images" : "files";
|
|
1342
|
-
if (
|
|
1343
|
-
const { type, id } =
|
|
1363
|
+
const assetTypeEndpoint = assetType === "image" ? "images" : "files", resource = config.resource;
|
|
1364
|
+
if (resource) {
|
|
1365
|
+
const { type, id } = resource;
|
|
1344
1366
|
switch (type) {
|
|
1345
1367
|
case "dataset":
|
|
1346
1368
|
throw new Error(
|
|
@@ -1640,7 +1662,7 @@ class ObservableMediaLibraryVideoClient {
|
|
|
1640
1662
|
* @param options - Options for transformations and expiration
|
|
1641
1663
|
*/
|
|
1642
1664
|
getPlaybackInfo(assetIdentifier, options = {}) {
|
|
1643
|
-
const
|
|
1665
|
+
const config = this.#client.config(), configMediaLibraryId = (config.resource || config["~experimental_resource"])?.id, { instanceId, libraryId } = parseAssetInstanceId(assetIdentifier), effectiveLibraryId = libraryId || configMediaLibraryId;
|
|
1644
1666
|
if (!effectiveLibraryId)
|
|
1645
1667
|
throw new Error(
|
|
1646
1668
|
"Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR"
|