@sanity/client 7.22.1 → 7.23.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.
@@ -3363,6 +3363,20 @@ export declare class ObservableSanityClient {
3363
3363
  tag?: string
3364
3364
  },
3365
3365
  ): Observable<(SanityDocument<R> | null)[]>
3366
+ /**
3367
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
3368
+ * Returns a set of the IDs that exist.
3369
+ *
3370
+ * @param ids - Document IDs to check
3371
+ * @param options - Request options
3372
+ */
3373
+ documentsExists(
3374
+ ids: string[],
3375
+ options?: {
3376
+ signal?: AbortSignal
3377
+ tag?: string
3378
+ },
3379
+ ): Observable<Set<string>>
3366
3380
  /**
3367
3381
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
3368
3382
  * Returns an observable that resolves to the created document.
@@ -5286,6 +5300,20 @@ export declare class SanityClient {
5286
5300
  tag?: string
5287
5301
  },
5288
5302
  ): Promise<(SanityDocument<R> | null)[]>
5303
+ /**
5304
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
5305
+ * Returns a set of the IDs that exist.
5306
+ *
5307
+ * @param ids - Document IDs to check
5308
+ * @param options - Request options
5309
+ */
5310
+ documentsExists(
5311
+ ids: string[],
5312
+ options?: {
5313
+ signal?: AbortSignal
5314
+ tag?: string
5315
+ },
5316
+ ): Promise<Set<string>>
5289
5317
  /**
5290
5318
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
5291
5319
  * Returns a promise that resolves to the created document.
@@ -3363,6 +3363,20 @@ export declare class ObservableSanityClient {
3363
3363
  tag?: string
3364
3364
  },
3365
3365
  ): Observable<(SanityDocument<R> | null)[]>
3366
+ /**
3367
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
3368
+ * Returns a set of the IDs that exist.
3369
+ *
3370
+ * @param ids - Document IDs to check
3371
+ * @param options - Request options
3372
+ */
3373
+ documentsExists(
3374
+ ids: string[],
3375
+ options?: {
3376
+ signal?: AbortSignal
3377
+ tag?: string
3378
+ },
3379
+ ): Observable<Set<string>>
3366
3380
  /**
3367
3381
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
3368
3382
  * Returns an observable that resolves to the created document.
@@ -5286,6 +5300,20 @@ export declare class SanityClient {
5286
5300
  tag?: string
5287
5301
  },
5288
5302
  ): Promise<(SanityDocument<R> | null)[]>
5303
+ /**
5304
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
5305
+ * Returns a set of the IDs that exist.
5306
+ *
5307
+ * @param ids - Document IDs to check
5308
+ * @param options - Request options
5309
+ */
5310
+ documentsExists(
5311
+ ids: string[],
5312
+ options?: {
5313
+ signal?: AbortSignal
5314
+ tag?: string
5315
+ },
5316
+ ): Promise<Set<string>>
5289
5317
  /**
5290
5318
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
5291
5319
  * Returns a promise that resolves to the created document.
package/dist/stega.d.cts CHANGED
@@ -3363,6 +3363,20 @@ export declare class ObservableSanityClient {
3363
3363
  tag?: string
3364
3364
  },
3365
3365
  ): Observable<(SanityDocument<R> | null)[]>
3366
+ /**
3367
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
3368
+ * Returns a set of the IDs that exist.
3369
+ *
3370
+ * @param ids - Document IDs to check
3371
+ * @param options - Request options
3372
+ */
3373
+ documentsExists(
3374
+ ids: string[],
3375
+ options?: {
3376
+ signal?: AbortSignal
3377
+ tag?: string
3378
+ },
3379
+ ): Observable<Set<string>>
3366
3380
  /**
3367
3381
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
3368
3382
  * Returns an observable that resolves to the created document.
@@ -5286,6 +5300,20 @@ export declare class SanityClient {
5286
5300
  tag?: string
5287
5301
  },
5288
5302
  ): Promise<(SanityDocument<R> | null)[]>
5303
+ /**
5304
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
5305
+ * Returns a set of the IDs that exist.
5306
+ *
5307
+ * @param ids - Document IDs to check
5308
+ * @param options - Request options
5309
+ */
5310
+ documentsExists(
5311
+ ids: string[],
5312
+ options?: {
5313
+ signal?: AbortSignal
5314
+ tag?: string
5315
+ },
5316
+ ): Promise<Set<string>>
5289
5317
  /**
5290
5318
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
5291
5319
  * Returns a promise that resolves to the created document.
package/dist/stega.d.ts CHANGED
@@ -3363,6 +3363,20 @@ export declare class ObservableSanityClient {
3363
3363
  tag?: string
3364
3364
  },
3365
3365
  ): Observable<(SanityDocument<R> | null)[]>
3366
+ /**
3367
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
3368
+ * Returns a set of the IDs that exist.
3369
+ *
3370
+ * @param ids - Document IDs to check
3371
+ * @param options - Request options
3372
+ */
3373
+ documentsExists(
3374
+ ids: string[],
3375
+ options?: {
3376
+ signal?: AbortSignal
3377
+ tag?: string
3378
+ },
3379
+ ): Observable<Set<string>>
3366
3380
  /**
3367
3381
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
3368
3382
  * Returns an observable that resolves to the created document.
@@ -5286,6 +5300,20 @@ export declare class SanityClient {
5286
5300
  tag?: string
5287
5301
  },
5288
5302
  ): Promise<(SanityDocument<R> | null)[]>
5303
+ /**
5304
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
5305
+ * Returns a set of the IDs that exist.
5306
+ *
5307
+ * @param ids - Document IDs to check
5308
+ * @param options - Request options
5309
+ */
5310
+ documentsExists(
5311
+ ids: string[],
5312
+ options?: {
5313
+ signal?: AbortSignal
5314
+ tag?: string
5315
+ },
5316
+ ): Promise<Set<string>>
5289
5317
  /**
5290
5318
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
5291
5319
  * Returns a promise that resolves to the created document.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/client",
3
- "version": "7.22.1",
3
+ "version": "7.23.0",
4
4
  "description": "Client for retrieving, creating and patching data from Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
@@ -130,7 +130,7 @@
130
130
  },
131
131
  "dependencies": {
132
132
  "@sanity/eventsource": "^5.0.2",
133
- "get-it": "^8.7.2",
133
+ "get-it": "^8.8.0",
134
134
  "nanoid": "^3.3.11",
135
135
  "rxjs": "^7.0.0"
136
136
  },
@@ -324,6 +324,20 @@ export class ObservableSanityClient {
324
324
  return dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options)
325
325
  }
326
326
 
327
+ /**
328
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
329
+ * Returns a set of the IDs that exist.
330
+ *
331
+ * @param ids - Document IDs to check
332
+ * @param options - Request options
333
+ */
334
+ documentsExists(
335
+ ids: string[],
336
+ options?: {signal?: AbortSignal; tag?: string},
337
+ ): Observable<Set<string>> {
338
+ return dataMethods._documentsExists(this, this.#httpRequest, ids, options)
339
+ }
340
+
327
341
  /**
328
342
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
329
343
  * Returns an observable that resolves to the created document.
@@ -1390,6 +1404,20 @@ export class SanityClient {
1390
1404
  return lastValueFrom(dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options))
1391
1405
  }
1392
1406
 
1407
+ /**
1408
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
1409
+ * Returns a set of the IDs that exist.
1410
+ *
1411
+ * @param ids - Document IDs to check
1412
+ * @param options - Request options
1413
+ */
1414
+ documentsExists(
1415
+ ids: string[],
1416
+ options?: {signal?: AbortSignal; tag?: string},
1417
+ ): Promise<Set<string>> {
1418
+ return lastValueFrom(dataMethods._documentsExists(this, this.#httpRequest, ids, options))
1419
+ }
1420
+
1393
1421
  /**
1394
1422
  * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
1395
1423
  * Returns a promise that resolves to the created document.
@@ -1,6 +1,6 @@
1
1
  import {getDraftId, getVersionFromId, getVersionId, isDraftId} from '@sanity/client/csm'
2
- import {from, type MonoTypeOperatorFunction, Observable} from 'rxjs'
3
- import {combineLatestWith, filter, map} from 'rxjs/operators'
2
+ import {from, type MonoTypeOperatorFunction, Observable, of} from 'rxjs'
3
+ import {combineLatestWith, concatMap, filter, map, reduce} from 'rxjs/operators'
4
4
 
5
5
  import {validateApiPerspective} from '../config'
6
6
  import {requestOptions} from '../http/requestOptions'
@@ -231,6 +231,51 @@ export function _getDocuments<R extends Record<string, Any>>(
231
231
  )
232
232
  }
233
233
 
234
+ const DOCUMENTS_EXISTS_BATCH_SIZE = 100
235
+
236
+ /** @internal */
237
+ export function _documentsExists(
238
+ client: Client,
239
+ httpRequest: HttpRequest,
240
+ ids: string[],
241
+ opts: {signal?: AbortSignal; tag?: string} = {},
242
+ ): Observable<Set<string>> {
243
+ if (ids.length === 0) {
244
+ return of(new Set<string>())
245
+ }
246
+
247
+ const batches: string[][] = []
248
+ for (let i = 0; i < ids.length; i += DOCUMENTS_EXISTS_BATCH_SIZE) {
249
+ batches.push(ids.slice(i, i + DOCUMENTS_EXISTS_BATCH_SIZE))
250
+ }
251
+
252
+ const fetchBatch = (batchIds: string[]) =>
253
+ _requestObservable<Any>(client, httpRequest, {
254
+ uri: _getDataUrl(client, 'doc', batchIds.map(encodeURIComponent).join(',')),
255
+ tag: opts.tag,
256
+ signal: opts.signal,
257
+ query: {excludeContent: true},
258
+ }).pipe(
259
+ filter(isResponse),
260
+ map((event: Any) => {
261
+ const missing = new Set<string>()
262
+ for (const omitted of event.body.omitted || []) {
263
+ if (omitted.reason !== 'existence') continue
264
+ missing.add(omitted.id)
265
+ }
266
+ return new Set(batchIds.filter((id) => !missing.has(id)))
267
+ }),
268
+ )
269
+
270
+ return from(batches).pipe(
271
+ concatMap(fetchBatch),
272
+ reduce((acc, set) => {
273
+ for (const id of set) acc.add(id)
274
+ return acc
275
+ }, new Set<string>()),
276
+ )
277
+ }
278
+
234
279
  /** @internal */
235
280
  export function _getReleaseDocuments<R extends Record<string, Any>>(
236
281
  client: ObservableSanityClient | SanityClient,
@@ -598,6 +643,11 @@ export function _requestObservable<R>(
598
643
  httpRequest: HttpRequest,
599
644
  options: RequestObservableOptions,
600
645
  ): Observable<HttpRequestEvent<R>> {
646
+ // Capture the call-site error here, where the caller's code is still
647
+ // on the synchronous call stack, and pass it through to get-it so errors
648
+ // include the originating call site rather than just internal plumbing.
649
+ const callSiteStack = new Error()
650
+
601
651
  const uri = options.url || (options.uri as string)
602
652
  const config = client.config()
603
653
 
@@ -667,6 +717,7 @@ export function _requestObservable<R>(
667
717
  config,
668
718
  Object.assign({}, options, {
669
719
  url: _getUrl(client, uri, useCdn),
720
+ callSiteStack,
670
721
  }),
671
722
  ) as RequestOptions
672
723
 
@@ -21,7 +21,7 @@
21
21
 
22
22
  const e=!(typeof navigator>"u")&&"ReactNative"===navigator.product,t={timeout:e?6e4:12e4},r=function(r){const a={...t,..."string"==typeof r?{url:r}:r};if(a.timeout=n$1(a.timeout),a.query){const{url:t,searchParams:r}=function(t){const r=t.indexOf("?");if(-1===r)return {url:t,searchParams:new URLSearchParams};const n=t.slice(0,r),a=t.slice(r+1);if(!e)return {url:n,searchParams:new URLSearchParams(a)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const s=new URLSearchParams;for(const e of a.split("&")){const[t,r]=e.split("=");t&&s.append(o$1(t),o$1(r||""));}return {url:n,searchParams:s}}(a.url);for(const[e,o]of Object.entries(a.query)){if(void 0!==o)if(Array.isArray(o))for(const t of o)r.append(e,t);else r.append(e,o);const n=r.toString();n&&(a.url=`${t}?${n}`);}}return a.method=a.body&&!a.method?"POST":(a.method||"GET").toUpperCase(),a};function o$1(e){return decodeURIComponent(e.replace(/\+/g," "))}function n$1(e){if(false===e||0===e)return false;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?n$1(t.timeout):{connect:r,socket:r}}const a$2=/^https?:\/\//i,s$1=function(e){if(!a$2.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};function c$2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}
23
23
 
24
- const o=["request","response","progress","error","abort"],n=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function s(r$1,a){const i=[],u=n.reduce((e,t)=>(e[t]=e[t]||[],e),{processOptions:[r],validateOptions:[s$1]});function l(e){const t=o.reduce((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return {publish:function(t){for(const r in e)e[r](t);},subscribe:function(r){const o=t++;return e[o]=r,function(){delete e[o];}}}}(),e),{}),r=(e=>function(t,r,...o){const n="onError"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0, e[t][r])(s,...o),!n||s);r++);return s})(u),n=r("processOptions",e);r("validateOptions",n);const s={options:n,channels:t,applyMiddleware:r};let i;const l=t.request.subscribe(e=>{i=a(e,(o,n)=>((e,o,n)=>{let s=e,a=o;if(!s)try{a=r("onResponse",o,n);}catch(e){a=null,s=e;}s=s&&r("onError",s,n),s?t.error.publish(s):a&&t.response.publish(a);})(o,n,e));});t.abort.subscribe(()=>{l(),i&&i.abort();});const c=r("onReturn",t,s);return c===t&&t.request.publish(s),c}return l.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&u.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return n.forEach(t=>{e[t]&&u[t].push(e[t]);}),i.push(e),l},l.clone=()=>s(i,a),r$1.forEach(l.use),l}var a$1,i,u$2=/* @__PURE__ */c$2(function(){if(i)return a$1;i=1;var e=function(e){return e.replace(/^\s+|\s+$/g,"")},t=function(e){return "[object Array]"===Object.prototype.toString.call(e)};return a$1=function(r){if(!r)return {};for(var o=/* @__PURE__ */Object.create(null),n=e(r).split("\n"),s=0;s<n.length;s++){var a=n[s],i=a.indexOf(":"),u=e(a.slice(0,i)).toLowerCase(),l=e(a.slice(i+1));typeof o[u]>"u"?o[u]=l:t(o[u])?o[u].push(l):o[u]=[o[u],l];}return o}}());let l$2 = class l{onabort;onerror;onreadystatechange;ontimeout;readyState=0;response;responseText="";responseType="";status;statusText;withCredentials;#e;#t;#r;#o={};#n;#s={};#a;open(e,t,r){this.#e=e,this.#t=t,this.#r="",this.readyState=1,this.onreadystatechange?.(),this.#n=void 0;}abort(){this.#n&&this.#n.abort();}getAllResponseHeaders(){return this.#r}setRequestHeader(e,t){this.#o[e]=t;}setInit(e,t=true){this.#s=e,this.#a=t;}send(e){const t="arraybuffer"!==this.responseType,r={...this.#s,method:this.#e,headers:this.#o,body:e};"function"==typeof AbortController&&this.#a&&(this.#n=new AbortController,typeof EventTarget<"u"&&this.#n.signal instanceof EventTarget&&(r.signal=this.#n.signal)),typeof document<"u"&&(r.credentials=this.withCredentials?"include":"omit"),fetch(this.#t,r).then(e=>(e.headers.forEach((e,t)=>{this.#r+=`${t}: ${e}\r\n`;}),this.status=e.status,this.statusText=e.statusText,this.readyState=3,this.onreadystatechange?.(),t?e.text():e.arrayBuffer())).then(e=>{"string"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange?.();}).catch(e=>{"AbortError"!==e.name?this.onerror?.(e):this.onabort?.();});}};const c$1="function"==typeof XMLHttpRequest?"xhr":"fetch",h$1="xhr"===c$1?XMLHttpRequest:l$2,d$2=(e,t)=>{const r=e.options,o=e.applyMiddleware("finalizeOptions",r),n={},s=e.applyMiddleware("interceptRequest",void 0,{adapter:c$1,context:e});if(s){const e=setTimeout(t,0,null,s);return {abort:()=>clearTimeout(e)}}let a=new h$1;a instanceof l$2&&"object"==typeof o.fetch&&a.setInit(o.fetch,o.useAbortSignal??true);const i=o.headers,d=o.timeout;let p=false,f=false,b=false;if(a.onerror=e=>{m(a instanceof l$2?e instanceof Error?e:new Error(`Request error while attempting to reach is ${o.url}`,{cause:e}):new Error(`Request error while attempting to reach is ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`));},a.ontimeout=e=>{m(new Error(`Request timeout while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`));},a.onabort=()=>{w(true),p=true;},a.onreadystatechange=function(){d&&(w(),n.socket=setTimeout(()=>y("ESOCKETTIMEDOUT"),d.socket)),!p&&a&&4===a.readyState&&0!==a.status&&function(){if(!(p||f||b)){if(0===a.status)return void m(new Error("Unknown XHR error"));w(),f=true,t(null,{body:a.response||(""===a.responseType||"text"===a.responseType?a.responseText:""),url:o.url,method:o.method,headers:u$2(a.getAllResponseHeaders()),statusCode:a.status,statusMessage:a.statusText});}}();},a.open(o.method,o.url,true),a.withCredentials=!!o.withCredentials,i&&a.setRequestHeader)for(const e in i)i.hasOwnProperty(e)&&a.setRequestHeader(e,i[e]);return o.rawBody&&(a.responseType="arraybuffer"),e.applyMiddleware("onRequest",{options:o,adapter:c$1,request:a,context:e}),a.send(o.body||null),d&&(n.connect=setTimeout(()=>y("ETIMEDOUT"),d.connect)),{abort:function(){p=true,a&&a.abort();}};function y(t){b=true,a.abort();const r=new Error("ESOCKETTIMEDOUT"===t?`Socket timed out on request to ${o.url}`:`Connection timed out on request to ${o.url}`);r.code=t,e.channels.error.publish(r);}function w(e){(e||p||a&&a.readyState>=2&&n.connect)&&clearTimeout(n.connect),n.socket&&clearTimeout(n.socket);}function m(e){if(f)return;w(true),f=true,a=null;const r=e||new Error(`Network error while attempting to reach ${o.url}`);r.isNetworkError=true,r.request=o,t(r);}},p$2=(e=[],t=d$2)=>s(e,t),f="browser";
24
+ const o=["request","response","progress","error","abort"],n=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function s(r$1,i){const a=[],u=n.reduce((e,t)=>(e[t]=e[t]||[],e),{processOptions:[r],validateOptions:[s$1]});function c(e){const t="object"==typeof e&&e.callSiteStack?e.callSiteStack:void 0,r=t?void 0:new Error,n=o.reduce((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return {publish:function(t){for(const r in e)e[r](t);},subscribe:function(r){const o=t++;return e[o]=r,function(){delete e[o];}}}}(),e),{}),s=(e=>function(t,r,...o){const n="onError"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0, e[t][r])(s,...o),!n||s);r++);return s})(u),a=s("processOptions",e);s("validateOptions",a);const c={options:a,channels:n,applyMiddleware:s};let l;const h=n.request.subscribe(e=>{l=i(e,(o,i)=>((e,o,i)=>{let a=e,u=o;if(!a)try{u=s("onResponse",o,i);}catch(e){u=null,a=e;}if(a=a&&s("onError",a,i),a){if(a instanceof Error){const e=t?.stack||r?.stack;if("string"==typeof e){const r=e.split("\n").slice(t?1:2);r.length>0&&(a.stack+="\n"+r.join("\n"));}}n.error.publish(a);}else u&&n.response.publish(u);})(o,i,e));});n.abort.subscribe(()=>{h(),l&&l.abort();});const d=s("onReturn",n,c);return d===n&&n.request.publish(c),d}return c.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&u.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return n.forEach(t=>{e[t]&&u[t].push(e[t]);}),a.push(e),c},c.clone=()=>s(a,i),r$1.forEach(c.use),c}var i,a$1,u$2=/* @__PURE__ */c$2(function(){if(a$1)return i;a$1=1;var e=function(e){return e.replace(/^\s+|\s+$/g,"")},t=function(e){return "[object Array]"===Object.prototype.toString.call(e)};return i=function(r){if(!r)return {};for(var o=/* @__PURE__ */Object.create(null),n=e(r).split("\n"),s=0;s<n.length;s++){var i=n[s],a=i.indexOf(":"),u=e(i.slice(0,a)).toLowerCase(),c=e(i.slice(a+1));typeof o[u]>"u"?o[u]=c:t(o[u])?o[u].push(c):o[u]=[o[u],c];}return o}}());let c$1 = class c{onabort;onerror;onreadystatechange;ontimeout;readyState=0;response;responseText="";responseType="";status;statusText;withCredentials;#e;#t;#r;#o={};#n;#s={};#i;open(e,t,r){this.#e=e,this.#t=t,this.#r="",this.readyState=1,this.onreadystatechange?.(),this.#n=void 0;}abort(){this.#n&&this.#n.abort();}getAllResponseHeaders(){return this.#r}setRequestHeader(e,t){this.#o[e]=t;}setInit(e,t=true){this.#s=e,this.#i=t;}send(e){const t="arraybuffer"!==this.responseType,r={...this.#s,method:this.#e,headers:this.#o,body:e};"function"==typeof AbortController&&this.#i&&(this.#n=new AbortController,typeof EventTarget<"u"&&this.#n.signal instanceof EventTarget&&(r.signal=this.#n.signal)),typeof document<"u"&&(r.credentials=this.withCredentials?"include":"omit"),fetch(this.#t,r).then(e=>(e.headers.forEach((e,t)=>{this.#r+=`${t}: ${e}\r\n`;}),this.status=e.status,this.statusText=e.statusText,this.readyState=3,this.onreadystatechange?.(),t?e.text():e.arrayBuffer())).then(e=>{"string"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange?.();}).catch(e=>{"AbortError"!==e.name?this.onerror?.(e):this.onabort?.();});}};const l$2="function"==typeof XMLHttpRequest?"xhr":"fetch",h$1="xhr"===l$2?XMLHttpRequest:c$1,d$2=(e,t)=>{const r=e.options,o=e.applyMiddleware("finalizeOptions",r),n={},s=e.applyMiddleware("interceptRequest",void 0,{adapter:l$2,context:e});if(s){const e=setTimeout(t,0,null,s);return {abort:()=>clearTimeout(e)}}let i=new h$1;i instanceof c$1&&"object"==typeof o.fetch&&i.setInit(o.fetch,o.useAbortSignal??true);const a=o.headers,d=o.timeout;let p=false,f=false,b=false;if(i.onerror=e=>{m(i instanceof c$1?e instanceof Error?e:new Error(`Request error while attempting to reach ${o.url}`,{cause:e}):new Error(`Request error while attempting to reach is ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`));},i.ontimeout=e=>{m(new Error(`Request timeout while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`));},i.onabort=()=>{w(true),p=true;},i.onreadystatechange=function(){d&&(w(),n.socket=setTimeout(()=>y("ESOCKETTIMEDOUT"),d.socket)),!p&&i&&4===i.readyState&&0!==i.status&&function(){if(!(p||f||b)){if(0===i.status)return void m(new Error("Unknown XHR error"));w(),f=true,t(null,{body:i.response||(""===i.responseType||"text"===i.responseType?i.responseText:""),url:o.url,method:o.method,headers:u$2(i.getAllResponseHeaders()),statusCode:i.status,statusMessage:i.statusText});}}();},i.open(o.method,o.url,true),i.withCredentials=!!o.withCredentials,a&&i.setRequestHeader)for(const e in a)a.hasOwnProperty(e)&&i.setRequestHeader(e,a[e]);return o.rawBody&&(i.responseType="arraybuffer"),e.applyMiddleware("onRequest",{options:o,adapter:l$2,request:i,context:e}),i.send(o.body||null),d&&(n.connect=setTimeout(()=>y("ETIMEDOUT"),d.connect)),{abort:function(){p=true,i&&i.abort();}};function y(t){b=true,i.abort();const r=new Error("ESOCKETTIMEDOUT"===t?`Socket timed out on request to ${o.url}`:`Connection timed out on request to ${o.url}`);r.code=t,e.channels.error.publish(r);}function w(e){(e||p||i&&i.readyState>=2&&n.connect)&&clearTimeout(n.connect),n.socket&&clearTimeout(n.socket);}function m(e){if(f)return;w(true),f=true,i=null;const r=e||new Error(`Network error while attempting to reach ${o.url}`);r.isNetworkError=true,r.request=o,t(r);}},p$2=(e=[],t=d$2)=>s(e,t),f="browser";
25
25
 
26
26
  var a,c,u$1,l$1,p$1,d$1={exports:{}};/* @__PURE__ */c$2((p$1||(p$1=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const s="color: "+this.color;t.splice(1,0,s,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(r=n));}),t.splice(r,0,s);},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug");}catch{}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG");}catch{}return !e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if(typeof window<"u"&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return true;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return false;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch{}}(),t.destroy=/* @__PURE__ */(()=>{let e=false;return ()=>{e||(e=true,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."));}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=(l$1?u$1:(l$1=1,u$1=function(e){function t(e){let n,r,o,i=null;function a(...e){if(!a.enabled)return;const s=a,r=Number(/* @__PURE__ */new Date),o=r-(n||r);s.diff=o,s.prev=n,s.curr=r,n=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,r)=>{if("%%"===n)return "%";i++;const o=t.formatters[r];if("function"==typeof o){const t=e[i];n=o.call(s,t),e.splice(i,1),i--;}return n}),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e);}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=s,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:true,configurable:false,get:()=>null!==i?i:(r!==t.namespaces&&(r=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e;}}),"function"==typeof t.init&&t.init(a),a}function s(e,s){const n=t(this.namespace+(typeof s>"u"?":":s)+e);return n.log=this.log,n}function n(e,t){let s=0,n=0,r=-1,o=0;for(;s<e.length;)if(n<t.length&&(t[n]===e[s]||"*"===t[n]))"*"===t[n]?(r=n,o=s,n++):(s++,n++);else {if(-1===r)return false;n=r+1,o++,s=o;}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of s)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e);},t.enabled=function(e){for(const s of t.skips)if(n(e,s))return false;for(const s of t.names)if(n(e,s))return true;return false},t.humanize=function(){if(c)return a;c=1;var e=1e3,t=60*e,s=60*t,n=24*s,r=7*n;function o(e,t,s,n){var r=t>=1.5*s;return Math.round(e/s)+" "+n+(r?"s":"")}return a=function(i,a){a=a||{};var c,u,l=typeof i;if("string"===l&&i.length>0)return function(o){if(!((o=String(o)).length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case "years":case "year":case "yrs":case "yr":case "y":return 315576e5*a;case "weeks":case "week":case "w":return a*r;case "days":case "day":case "d":return a*n;case "hours":case "hour":case "hrs":case "hr":case "h":return a*s;case "minutes":case "minute":case "mins":case "min":case "m":return a*t;case "seconds":case "second":case "secs":case "sec":case "s":return a*e;case "milliseconds":case "millisecond":case "msecs":case "msec":case "ms":return a;default:return}}}}(i);if("number"===l&&isFinite(i))return a.long?(c=i,(u=Math.abs(c))>=n?o(c,u,n,"day"):u>=s?o(c,u,s,"hour"):u>=t?o(c,u,t,"minute"):u>=e?o(c,u,e,"second"):c+" ms"):function(r){var o=Math.abs(r);return o>=n?Math.round(r/n)+"d":o>=s?Math.round(r/s)+"h":o>=t?Math.round(r/t)+"m":o>=e?Math.round(r/e)+"s":r+"ms"}(i);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))}}(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");},Object.keys(e).forEach(s=>{t[s]=e[s];}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t}))(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return "[UnexpectedJSONParseError]: "+e.message}};}(d$1,d$1.exports)),d$1.exports));const F=typeof Buffer>"u"?()=>false:e=>Buffer.isBuffer(e);function O(e){return "[object Object]"===Object.prototype.toString.call(e)}function j(e){if(false===O(e))return false;const t=e.constructor;if(void 0===t)return true;const s=t.prototype;return !(false===O(s)||false===s.hasOwnProperty("isPrototypeOf"))}const v=["boolean","string","number"];function x$1(){return {processOptions:e=>{const t=e.body;return !t||"function"==typeof t.pipe||F(t)||-1===v.indexOf(typeof t)&&!Array.isArray(t)&&!j(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{"Content-Type":"application/json"})})}}}function E(e){return {onResponse:s=>{const n=s.headers["content-type"]||"",r=e&&e.force||-1!==n.indexOf("application/json");return s.body&&n&&r?Object.assign({},s,{body:t(s.body)}):s},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:"application/json"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}let R={};typeof globalThis<"u"?R=globalThis:typeof window<"u"?R=window:typeof global<"u"?R=global:typeof self<"u"&&(R=self);var q=R;function A$1(e={}){const t=e.implementation||q.Observable;if(!t)throw new Error("`Observable` is not available in global scope, and no implementation was passed");return {onReturn:(e,s)=>new t(t=>(e.error.subscribe(e=>t.error(e)),e.progress.subscribe(e=>t.next(Object.assign({type:"progress"},e))),e.response.subscribe(e=>{t.next(Object.assign({type:"response"},e)),t.complete();}),e.request.publish(s),()=>e.abort.publish()))}}function S$1(){return {onRequest:e=>{if("xhr"!==e.adapter)return;const t=e.request,s=e.context;function n(e){return t=>{const n=t.lengthComputable?t.loaded/t.total*100:-1;s.channels.progress.publish({stage:e,percent:n,total:t.total,loaded:t.loaded,lengthComputable:t.lengthComputable});}}"upload"in t&&"onprogress"in t.upload&&(t.upload.onprogress=n("upload")),"onprogress"in t&&(t.onprogress=n("download"));}}}var $=(e,t,s)=>("GET"===s.method||"HEAD"===s.method)&&(e.isNetworkError||false);function _(e){return 100*Math.pow(2,e)+100*Math.random()}const P$1=(e={})=>(e=>{const t=e.maxRetries||5,s=e.retryDelay||_,n=e.shouldRetry;return {onError:(e,r)=>{const o=r.options,i=o.maxRetries||t,a=o.retryDelay||s,c=o.shouldRetry||n,u=o.attemptNumber||0;if(null!==(l=o.body)&&"object"==typeof l&&"function"==typeof l.pipe||!c(e,u,o)||u>=i)return e;var l;const p=Object.assign({},r,{options:Object.assign({},o,{attemptNumber:u+1})});return setTimeout(()=>r.channels.request.publish(p),a(u)),null}}})({shouldRetry:$,...e});P$1.shouldRetry=$;
27
27
 
@@ -1731,6 +1731,29 @@
1731
1731
  });
1732
1732
  }
1733
1733
 
1734
+ function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
1735
+ return function (source, subscriber) {
1736
+ var hasState = hasSeed;
1737
+ var state = seed;
1738
+ var index = 0;
1739
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1740
+ var i = index++;
1741
+ state = hasState
1742
+ ?
1743
+ accumulator(state, value, i)
1744
+ :
1745
+ ((hasState = true), value);
1746
+ }, (function () {
1747
+ hasState && subscriber.next(state);
1748
+ subscriber.complete();
1749
+ })));
1750
+ };
1751
+ }
1752
+
1753
+ function reduce(accumulator, seed) {
1754
+ return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));
1755
+ }
1756
+
1734
1757
  function combineLatest() {
1735
1758
  var args = [];
1736
1759
  for (var _i = 0; _i < arguments.length; _i++) {
@@ -1752,6 +1775,10 @@
1752
1775
  return combineLatest.apply(void 0, __spreadArray([], __read(otherSources)));
1753
1776
  }
1754
1777
 
1778
+ function concatMap(project, resultSelector) {
1779
+ return isFunction(resultSelector) ? mergeMap(project, resultSelector, 1) : mergeMap(project, 1);
1780
+ }
1781
+
1755
1782
  function finalize(callback) {
1756
1783
  return operate(function (source, subscriber) {
1757
1784
  try {
@@ -2939,6 +2966,35 @@ ${selectionOpts}`);
2939
2966
  })
2940
2967
  );
2941
2968
  }
2969
+ const DOCUMENTS_EXISTS_BATCH_SIZE = 100;
2970
+ function _documentsExists(client, httpRequest, ids, opts = {}) {
2971
+ if (ids.length === 0)
2972
+ return of(/* @__PURE__ */ new Set());
2973
+ const batches = [];
2974
+ for (let i = 0; i < ids.length; i += DOCUMENTS_EXISTS_BATCH_SIZE)
2975
+ batches.push(ids.slice(i, i + DOCUMENTS_EXISTS_BATCH_SIZE));
2976
+ const fetchBatch = (batchIds) => _requestObservable(client, httpRequest, {
2977
+ uri: _getDataUrl(client, "doc", batchIds.map(encodeURIComponent).join(",")),
2978
+ tag: opts.tag,
2979
+ signal: opts.signal,
2980
+ query: { excludeContent: true }
2981
+ }).pipe(
2982
+ filter(isResponse),
2983
+ map((event) => {
2984
+ const missing = /* @__PURE__ */ new Set();
2985
+ for (const omitted of event.body.omitted || [])
2986
+ omitted.reason === "existence" && missing.add(omitted.id);
2987
+ return new Set(batchIds.filter((id) => !missing.has(id)));
2988
+ })
2989
+ );
2990
+ return from(batches).pipe(
2991
+ concatMap(fetchBatch),
2992
+ reduce((acc, set) => {
2993
+ for (const id of set) acc.add(id);
2994
+ return acc;
2995
+ }, /* @__PURE__ */ new Set())
2996
+ );
2997
+ }
2942
2998
  function _getReleaseDocuments(client, httpRequest, releaseId, opts = {}) {
2943
2999
  return _dataRequest(
2944
3000
  client,
@@ -3075,7 +3131,7 @@ ${selectionOpts}`);
3075
3131
  return config.dataset !== void 0 && config.projectId !== void 0 || config.resource !== void 0;
3076
3132
  }, 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);
3077
3133
  function _requestObservable(client, httpRequest, options) {
3078
- 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;
3134
+ const callSiteStack = new Error(), 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;
3079
3135
  let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn;
3080
3136
  const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
3081
3137
  if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && isQuery(client, uri)) {
@@ -3091,7 +3147,8 @@ ${selectionOpts}`);
3091
3147
  const reqOptions = requestOptions(
3092
3148
  config,
3093
3149
  Object.assign({}, options, {
3094
- url: _getUrl(client, uri, useCdn)
3150
+ url: _getUrl(client, uri, useCdn),
3151
+ callSiteStack
3095
3152
  })
3096
3153
  ), request = new Observable(
3097
3154
  (subscriber) => httpRequest(reqOptions, config.requester).subscribe(subscriber)
@@ -4445,6 +4502,16 @@ ${selectionOpts}`);
4445
4502
  getDocuments(ids, options) {
4446
4503
  return _getDocuments(this, this.#httpRequest, ids, options);
4447
4504
  }
4505
+ /**
4506
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
4507
+ * Returns a set of the IDs that exist.
4508
+ *
4509
+ * @param ids - Document IDs to check
4510
+ * @param options - Request options
4511
+ */
4512
+ documentsExists(ids, options) {
4513
+ return _documentsExists(this, this.#httpRequest, ids, options);
4514
+ }
4448
4515
  create(document, options) {
4449
4516
  return _create(this, this.#httpRequest, document, "create", options);
4450
4517
  }
@@ -4722,6 +4789,16 @@ ${selectionOpts}`);
4722
4789
  getDocuments(ids, options) {
4723
4790
  return lastValueFrom(_getDocuments(this, this.#httpRequest, ids, options));
4724
4791
  }
4792
+ /**
4793
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
4794
+ * Returns a set of the IDs that exist.
4795
+ *
4796
+ * @param ids - Document IDs to check
4797
+ * @param options - Request options
4798
+ */
4799
+ documentsExists(ids, options) {
4800
+ return lastValueFrom(_documentsExists(this, this.#httpRequest, ids, options));
4801
+ }
4725
4802
  create(document, options) {
4726
4803
  return lastValueFrom(
4727
4804
  _create(this, this.#httpRequest, document, "create", options)
@@ -6437,7 +6514,7 @@ ${selectionOpts}`);
6437
6514
  exports.isHttpError = isHttpError;
6438
6515
  exports.isQueryParseError = isQueryParseError;
6439
6516
  exports.requester = requester;
6440
- exports.unstable__adapter = c$1;
6517
+ exports.unstable__adapter = l$2;
6441
6518
  exports.unstable__environment = f;
6442
6519
  exports.validateApiPerspective = validateApiPerspective;
6443
6520