@sanity/groq-store
Advanced tools
Comparing version 0.2.1 to 0.2.2
@@ -1,2 +0,2 @@ | ||
function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var r=e(require("groq")),t=e(require("fast-deep-equal")),n=require("throttle-debounce"),o=require("groq-js"),i=require("mendoza");function u(){return(u=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function c(e,r,t){var n,o=r.token,i=new e("https://"+r.projectId+".api.sanity.io/v1/data/listen/"+r.dataset+"?query=*&effectFormat=mendoza",{withCredentials:!0,headers:o?{Authorization:"Bearer "+o}:void 0});return i.addEventListener("welcome",t.open,!1),i.addEventListener("mutation",(n=t.next,function(e){var r;try{r=JSON.parse(e.data)}catch(e){return}n(r)}),!1),i.addEventListener("channelError",function(e){var r;i.close();try{r=JSON.parse(e.data)}catch(e){return void t.error(new Error("Unknown error parsing listener message"))}t.error(new Error(r.message||r.error||"Listener returned HTTP "+r.statusCode))},!1),i.addEventListener("error",function(){var e="undefined"!=typeof window&&window.location.origin;t.error(new Error("Error establishing listener - check that the project ID and dataset are correct"+(e?", and that the CORS-origin ("+e+") is allowed":"")))},!1),{unsubscribe:function(){return Promise.resolve(i.close())}}}function s(e){return e._id.startsWith("drafts.")?e._id.slice(7):e._id}function a(e,r){var t=u({},e);return delete t._rev,i.applyPatch(t,r)}function f(){return Promise.resolve()}function d(){var e,r,t=(e=["*[_id == $id][0]"],r||(r=e.slice(0)),e.raw=r,e);return d=function(){return t},t}function v(e,r,t){if(!e.s){if(t instanceof h){if(!t.s)return void(t.o=v.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(v.bind(null,e,r),v.bind(null,e,2));e.s=r,e.v=t;var n=e.o;n&&n(e)}}var h=function(){function e(){}return e.prototype.then=function(r,t){var n=new e,o=this.s;if(o){var i=1&o?r:t;if(i){try{v(n,1,i(this.v))}catch(e){v(n,2,e)}return n}return this}return this.o=function(e){try{var o=e.v;1&e.s?v(n,1,r?r(o):o):t?v(n,1,t(o)):v(n,2,o)}catch(e){v(n,2,e)}},n},e}();function l(e){return e instanceof h&&1&e.s}var m=function(e){var r=e.projectId,t=e.dataset,n=e.token,o=e.documentLimit;try{return Promise.resolve(fetch("https://"+r+".api.sanity.io/v1/data/export/"+t,{credentials:"include",headers:n?{Authorization:"Bearer "+n}:void 0})).then(function(e){function r(r){var t,n,i=function(e){if(!e)throw new Error("Failed to read body from response");var r,t=!1;function n(){t=!0,r&&r.cancel()}return new ReadableStream({start:function(o){r=e.getReader();var i=new TextDecoder,u="";r.read().then(function e(c){try{if(c.done)return t?Promise.resolve():0===(u=u.trim()).length?(o.close(),Promise.resolve()):(o.enqueue(JSON.parse(u)),o.close(),Promise.resolve());for(var s=(u+=i.decode(c.value,{stream:!0})).split("\n"),a=0;a<s.length-1;++a){var f=s[a].trim();if(0===f.length)return Promise.resolve();try{o.enqueue(JSON.parse(f))}catch(e){return o.error(e),n(),Promise.resolve()}}if(u=s[s.length-1],!r)return Promise.resolve();var d=function(t,n){try{var o=Promise.resolve(r.read()).then(function(r){e(r)})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){o.error(e)});return Promise.resolve(d&&d.then?d.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}).catch(function(e){return o.error(e)})},cancel:n})}(e.body).getReader(),u=[],c=function(e,r){var t;do{var n=e();if(n&&n.then){if(!l(n)){t=!0;break}n=n.v}var o=r();if(l(o)&&(o=o.v),!o)return n}while(!o.then);var i=new h,u=v.bind(null,i,2);return(t?n.then(c):o.then(s)).then(void 0,u),i;function c(t){for(n=t;l(o=r())&&(o=o.v),o;){if(o.then)return void o.then(s).then(void 0,u);if((n=e())&&n.then){if(!l(n))return void n.then(c).then(void 0,u);n=n.v}}v(i,1,n)}function s(t){if(t){do{if((n=e())&&n.then){if(!l(n))return void n.then(c).then(void 0,u);n=n.v}if(l(t=r())&&(t=t.v),!t)return void v(i,1,n)}while(!t.then);t.then(s).then(void 0,u)}else v(i,1,n)}}(function(){return Promise.resolve(i.read()).then(function(e){if(function(e){return!!e&&"error"in e&&"object"==typeof e.error&&null!==e.error&&"description"in e.error&&"string"==typeof e.error.description&&!("_id"in e)}(n=(t=e).value))throw new Error("Error streaming dataset: "+n.error);if(n&&!n._id.startsWith("_.")&&u.push(n),o&&u.length>o)throw i.cancel("Reached document limit"),new Error("Error streaming dataset: Reached limit of "+o+" documents")})},function(){return!t.done});return c&&c.then?c.then(function(e){return u}):u}var t=function(){if(200!==e.status)return Promise.resolve(e.json()).then(function(e){throw new Error("Error streaming dataset: "+("object"==typeof(r=e)&&"error"in r&&"message"in r?r.message||r.error:"<unknown error>"));var r})}();return t&&t.then?t.then(r):r()})}catch(e){return Promise.reject(e)}};exports.groq=r,exports.groqStore=function(e){if(function(){var e=["EventSource","ReadableStream","fetch"].filter(function(e){return!(e in window)});if(e.length>0)throw new Error("Browser not supported. Missing browser APIs: "+e.join(", "))}(),e.token)throw new Error("`token` option not currently supported in browser");return function(e,i){var v,h=function(e,r){try{return Promise.resolve(l()).then(function(){var t=o.parse(e,{params:r});return Promise.resolve(o.evaluate(t,{dataset:m,params:r})).then(function(e){return e.get()})})}catch(e){return Promise.reject(e)}},l=function(){try{return v||(v=function(e,r,t){var n=t.getDocuments,o=t.EventSource,i=e.projectId,d=e.dataset,v=e.overlayDrafts,h=e.documentLimit;if(!e.listen)return{unsubscribe:f,loaded:n({projectId:i,dataset:d,documentLimit:h}).then(j).then(f)};var l,m,p,w,b,g,y=new Map,P=[],E=new Promise(function(e,r){m=e,p=r});return{unsubscribe:c(o,e,{next:function(e){l?(function(e){if(e.effects&&!e.documentId.startsWith("_.")){var r=y.get(e.documentId)||null;!function(e,r){var t=y.get(e),n=l||[],o=t?n.indexOf(t):-1;-1===o&&r?(n.push(r),y.set(e,r)):r?(n.splice(o,1,r),y.set(e,r)):(n.splice(o,1),y.delete(e))}(e.documentId,a(r,e.effects.apply))}}(e),function(e,r){clearTimeout(g),b!==r.transactionId&&w?(j(w),b=void 0):(b=r.transactionId,w=e.slice()),g=setTimeout(j,25,e.slice())}(l,e)):P.push(e)},open:function(){try{return Promise.resolve(n({projectId:i,dataset:d,documentLimit:h})).then(function(e){(l=function(e,r){var t=new Map;return r.forEach(function(e){var r=t.get(e.documentId)||[];r.push(e),t.set(e.documentId,r)}),t.forEach(function(r,t){var n=e.find(function(e){return e._id===t});if(n){var o=!1,i=n;r.forEach(function(e){(o=o||e.previousRev===n._rev)&&e.effects&&(i=a(i,e.effects.apply))}),e.splice(e.indexOf(n),1,i)}else console.warn("Received mutation for missing document %s",t)}),e}(e,P)).forEach(function(e){return y.set(e._id,e)}),j(l),m()})}catch(e){return Promise.reject(e)}},error:function(e){return p(e)}}).unsubscribe,loaded:E};function j(e){w=void 0,g=void 0,b=void 0,r(v?function(e){var r=new Map;return e.forEach(function(e){var t=r.get(s(e));e._id.startsWith("drafts.")?r.set(s(e),function(e){return u({},e,{_id:s(e)})}(e)):t||r.set(e._id,e)}),Array.from(r.values())}(e):e)}}(e,function(e){m=e,p()},i)),Promise.resolve(v.loaded).then(function(){})}catch(e){return Promise.reject(e)}},m=[],p=n.throttle(e.subscriptionThrottleMs||50,function(){w.forEach(b)}),w=[];function b(e){return h(e.query,e.params).then(function(r){"previousResult"in e&&t(e.previousResult,r)||(e.previousResult=r,e.callback(void 0,r))}).catch(function(r){e.callback(r)})}return{query:h,getDocument:function(e){try{return Promise.resolve(l()).then(function(){return h(r(d()),{id:e})})}catch(e){return Promise.reject(e)}},getDocuments:function(e){try{return Promise.resolve(l()).then(function(){var r=e.map(function(e){return'*[_id == "'+e+'"][0]'}).join(",\n");return h("["+r+"]")})}catch(e){return Promise.reject(e)}},subscribe:function(r,t,n){if(!e.listen)throw new Error("Cannot use `subscribe()` without `listen: true`");var o={query:r,params:t,callback:n};w.push(o);var i=!1;return b(o),{unsubscribe:function(){return i||(i=!0,w.splice(w.indexOf(o),1)),Promise.resolve()}}},close:function(){return p.cancel(),v?v.unsubscribe():Promise.resolve()}}}(e,{EventSource:window.EventSource,getDocuments:m})}; | ||
function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var r=e(require("groq")),t=e(require("fast-deep-equal")),n=require("throttle-debounce"),o=require("groq-js"),i=require("mendoza");function u(){return(u=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function s(e,r,t){var n,o=r.token,i=new e("https://"+r.projectId+".api.sanity.io/v1/data/listen/"+r.dataset+"?query=*&effectFormat=mendoza",{withCredentials:!0,headers:o?{Authorization:"Bearer "+o}:void 0});return i.addEventListener("welcome",t.open,!1),i.addEventListener("mutation",(n=t.next,function(e){var r;try{r=JSON.parse(e.data)}catch(e){return}n(r)}),!1),i.addEventListener("channelError",function(e){var r;i.close();try{r=JSON.parse(e.data)}catch(e){return void t.error(new Error("Unknown error parsing listener message"))}t.error(new Error(r.message||r.error||"Listener returned HTTP "+r.statusCode))},!1),i.addEventListener("error",function(e){var r="undefined"!=typeof window&&window.location.origin,n=r?", and that the CORS-origin ("+r+") is allowed":"",o=function(e){return"object"==typeof e&&null!==e&&"message"in e}(e)?" ("+e.message+")":"";t.error(new Error("Error establishing listener - check that the project ID and dataset are correct"+n+o))},!1),{unsubscribe:function(){return Promise.resolve(i.close())}}}function c(e){return e._id.startsWith("drafts.")?e._id.slice(7):e._id}function a(e,r){var t=u({},e);return delete t._rev,i.applyPatch(t,r)}function f(){return Promise.resolve()}function d(){var e,r,t=(e=["*[_id == $id][0]"],r||(r=e.slice(0)),e.raw=r,e);return d=function(){return t},t}function v(e,r,t){if(!e.s){if(t instanceof l){if(!t.s)return void(t.o=v.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(v.bind(null,e,r),v.bind(null,e,2));e.s=r,e.v=t;var n=e.o;n&&n(e)}}var l=function(){function e(){}return e.prototype.then=function(r,t){var n=new e,o=this.s;if(o){var i=1&o?r:t;if(i){try{v(n,1,i(this.v))}catch(e){v(n,2,e)}return n}return this}return this.o=function(e){try{var o=e.v;1&e.s?v(n,1,r?r(o):o):t?v(n,1,t(o)):v(n,2,o)}catch(e){v(n,2,e)}},n},e}();function h(e){return e instanceof l&&1&e.s}var m=function(e){var r=e.projectId,t=e.dataset,n=e.token,o=e.documentLimit;try{return Promise.resolve(fetch("https://"+r+".api.sanity.io/v1/data/export/"+t,{credentials:"include",headers:n?{Authorization:"Bearer "+n}:void 0})).then(function(e){function r(r){var t,n,i=function(e){if(!e)throw new Error("Failed to read body from response");var r,t=!1;function n(){t=!0,r&&r.cancel()}return new ReadableStream({start:function(o){r=e.getReader();var i=new TextDecoder,u="";r.read().then(function e(s){try{if(s.done)return t?Promise.resolve():0===(u=u.trim()).length?(o.close(),Promise.resolve()):(o.enqueue(JSON.parse(u)),o.close(),Promise.resolve());for(var c=(u+=i.decode(s.value,{stream:!0})).split("\n"),a=0;a<c.length-1;++a){var f=c[a].trim();if(0===f.length)return Promise.resolve();try{o.enqueue(JSON.parse(f))}catch(e){return o.error(e),n(),Promise.resolve()}}if(u=c[c.length-1],!r)return Promise.resolve();var d=function(t,n){try{var o=Promise.resolve(r.read()).then(function(r){e(r)})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){o.error(e)});return Promise.resolve(d&&d.then?d.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}).catch(function(e){return o.error(e)})},cancel:n})}(e.body).getReader(),u=[],s=function(e,r){var t;do{var n=e();if(n&&n.then){if(!h(n)){t=!0;break}n=n.v}var o=r();if(h(o)&&(o=o.v),!o)return n}while(!o.then);var i=new l,u=v.bind(null,i,2);return(t?n.then(s):o.then(c)).then(void 0,u),i;function s(t){for(n=t;h(o=r())&&(o=o.v),o;){if(o.then)return void o.then(c).then(void 0,u);if((n=e())&&n.then){if(!h(n))return void n.then(s).then(void 0,u);n=n.v}}v(i,1,n)}function c(t){if(t){do{if((n=e())&&n.then){if(!h(n))return void n.then(s).then(void 0,u);n=n.v}if(h(t=r())&&(t=t.v),!t)return void v(i,1,n)}while(!t.then);t.then(c).then(void 0,u)}else v(i,1,n)}}(function(){return Promise.resolve(i.read()).then(function(e){if(function(e){return!!e&&"error"in e&&"object"==typeof e.error&&null!==e.error&&"description"in e.error&&"string"==typeof e.error.description&&!("_id"in e)}(n=(t=e).value))throw new Error("Error streaming dataset: "+n.error);if(n&&!n._id.startsWith("_.")&&u.push(n),o&&u.length>o)throw i.cancel("Reached document limit"),new Error("Error streaming dataset: Reached limit of "+o+" documents")})},function(){return!t.done});return s&&s.then?s.then(function(e){return u}):u}var t=function(){if(200!==e.status)return Promise.resolve(e.json()).then(function(e){throw new Error("Error streaming dataset: "+("object"==typeof(r=e)&&"error"in r&&"message"in r?r.message||r.error:"<unknown error>"));var r})}();return t&&t.then?t.then(r):r()})}catch(e){return Promise.reject(e)}};exports.groq=r,exports.groqStore=function(e){if(function(){var e=["EventSource","ReadableStream","fetch"].filter(function(e){return!(e in window)});if(e.length>0)throw new Error("Browser not supported. Missing browser APIs: "+e.join(", "))}(),e.token)throw new Error("`token` option not currently supported in browser");return function(e,i){var v,l=function(e,r){try{return Promise.resolve(h()).then(function(){var t=o.parse(e,{params:r});return Promise.resolve(o.evaluate(t,{dataset:m,params:r})).then(function(e){return e.get()})})}catch(e){return Promise.reject(e)}},h=function(){try{return v||(v=function(e,r,t){var n=t.getDocuments,o=t.EventSource,i=e.projectId,d=e.dataset,v=e.overlayDrafts,l=e.documentLimit;if(!e.listen)return{unsubscribe:f,loaded:n({projectId:i,dataset:d,documentLimit:l}).then(j).then(f)};var h,m,p,w,b,g,y=new Map,P=[],E=new Promise(function(e,r){m=e,p=r});return{unsubscribe:s(o,e,{next:function(e){h?(function(e){if(e.effects&&!e.documentId.startsWith("_.")){var r=y.get(e.documentId)||null;!function(e,r){var t=y.get(e),n=h||[],o=t?n.indexOf(t):-1;-1===o&&r?(n.push(r),y.set(e,r)):r?(n.splice(o,1,r),y.set(e,r)):(n.splice(o,1),y.delete(e))}(e.documentId,a(r,e.effects.apply))}}(e),function(e,r){clearTimeout(g),b!==r.transactionId&&w?(j(w),b=void 0):(b=r.transactionId,w=e.slice()),g=setTimeout(j,25,e.slice())}(h,e)):P.push(e)},open:function(){try{return Promise.resolve(n({projectId:i,dataset:d,documentLimit:l})).then(function(e){(h=function(e,r){var t=new Map;return r.forEach(function(e){var r=t.get(e.documentId)||[];r.push(e),t.set(e.documentId,r)}),t.forEach(function(r,t){var n=e.find(function(e){return e._id===t});if(n){var o=!1,i=n;r.forEach(function(e){(o=o||e.previousRev===n._rev)&&e.effects&&(i=a(i,e.effects.apply))}),e.splice(e.indexOf(n),1,i)}else console.warn("Received mutation for missing document %s",t)}),e}(e,P)).forEach(function(e){return y.set(e._id,e)}),j(h),m()})}catch(e){return Promise.reject(e)}},error:function(e){return p(e)}}).unsubscribe,loaded:E};function j(e){w=void 0,g=void 0,b=void 0,r(v?function(e){var r=new Map;return e.forEach(function(e){var t=r.get(c(e));e._id.startsWith("drafts.")?r.set(c(e),function(e){return u({},e,{_id:c(e)})}(e)):t||r.set(e._id,e)}),Array.from(r.values())}(e):e)}}(e,function(e){m=e,p()},i)),Promise.resolve(v.loaded).then(function(){})}catch(e){return Promise.reject(e)}},m=[],p=n.throttle(e.subscriptionThrottleMs||50,function(){w.forEach(b)}),w=[];function b(e){return l(e.query,e.params).then(function(r){"previousResult"in e&&t(e.previousResult,r)||(e.previousResult=r,e.callback(void 0,r))}).catch(function(r){e.callback(r)})}return{query:l,getDocument:function(e){try{return Promise.resolve(h()).then(function(){return l(r(d()),{id:e})})}catch(e){return Promise.reject(e)}},getDocuments:function(e){try{return Promise.resolve(h()).then(function(){var r=e.map(function(e){return'*[_id == "'+e+'"][0]'}).join(",\n");return l("["+r+"]")})}catch(e){return Promise.reject(e)}},subscribe:function(r,t,n){if(!e.listen)throw new Error("Cannot use `subscribe()` without `listen: true`");var o={query:r,params:t,callback:n};w.push(o);var i=!1;return b(o),{unsubscribe:function(){return i||(i=!0,w.splice(w.indexOf(o),1)),Promise.resolve()}}},close:function(){return p.cancel(),v?v.unsubscribe():Promise.resolve()}}}(e,{EventSource:window.EventSource,getDocuments:m})}; | ||
//# sourceMappingURL=groq-store.js.map |
@@ -1,2 +0,2 @@ | ||
import e from"groq";export{default as groq}from"groq";import t from"fast-deep-equal";import{throttle as r}from"throttle-debounce";import{parse as n,evaluate as o}from"groq-js";import{applyPatch as i}from"mendoza";function s(){return(s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function a(e,t,r){const{projectId:n,dataset:o,token:i}=t,s=new e(`https://${n}.api.sanity.io/v1/data/listen/${o}?query=*&effectFormat=mendoza`,{withCredentials:!0,headers:i?{Authorization:"Bearer "+i}:void 0});var a;return s.addEventListener("welcome",r.open,!1),s.addEventListener("mutation",(a=r.next,e=>{let t;try{t=JSON.parse(e.data)}catch(e){return}a(t)}),!1),s.addEventListener("channelError",e=>{let t;s.close();try{t=JSON.parse(e.data)}catch(e){return void r.error(new Error("Unknown error parsing listener message"))}r.error(new Error(t.message||t.error||"Listener returned HTTP "+t.statusCode))},!1),s.addEventListener("error",()=>{const e="undefined"!=typeof window&&window.location.origin;r.error(new Error("Error establishing listener - check that the project ID and dataset are correct"+(e?`, and that the CORS-origin (${e}) is allowed`:"")))},!1),{unsubscribe:()=>Promise.resolve(s.close())}}function c(e){return e._id.startsWith("drafts.")?e._id.slice(7):e._id}function u(e,t){const r=s({},e);return delete r._rev,i(r,t)}function d(){return Promise.resolve()}let l,f=e=>e;const p=async function({projectId:e,dataset:t,token:r,documentLimit:n}){const o=`https://${e}.api.sanity.io/v1/data/export/${t}`,i=r?{Authorization:"Bearer "+r}:void 0,s=await fetch(o,{credentials:"include",headers:i});if(200!==s.status)throw new Error("Error streaming dataset: "+("object"==typeof(a=await s.json())&&"error"in a&&"message"in a?a.message||a.error:"<unknown error>"));var a;const c=function(e){if(!e)throw new Error("Failed to read body from response");let t,r=!1;function n(){r=!0,t&&t.cancel()}return new ReadableStream({start(o){t=e.getReader();const i=new TextDecoder;let s="";t.read().then(async function e(a){if(a.done){if(r)return;return s=s.trim(),0===s.length||o.enqueue(JSON.parse(s)),void o.close()}s+=i.decode(a.value,{stream:!0});const c=s.split("\n");for(let e=0;e<c.length-1;++e){const t=c[e].trim();if(0!==t.length)try{o.enqueue(JSON.parse(t))}catch(e){return o.error(e),void n()}}if(s=c[c.length-1],t)try{e(await t.read())}catch(e){o.error(e)}}).catch(e=>o.error(e))},cancel:n})}(s.body).getReader(),u=[];let d,l;do{if(d=await c.read(),l=d.value,m(l))throw new Error("Error streaming dataset: "+l.error);if(l&&!l._id.startsWith("_.")&&u.push(l),n&&u.length>n)throw c.cancel("Reached document limit"),new Error(`Error streaming dataset: Reached limit of ${n} documents`)}while(!d.done);return u};function m(e){return!!e&&"error"in e&&"object"==typeof e.error&&null!==e.error&&"description"in e.error&&"string"==typeof e.error.description&&!("_id"in e)}function h(i){if(function(){const e=["EventSource","ReadableStream","fetch"].filter(e=>!(e in window));if(e.length>0)throw new Error("Browser not supported. Missing browser APIs: "+e.join(", "))}(),i.token)throw new Error("`token` option not currently supported in browser");return function(i,p){let m=[];const h=r(i.subscriptionThrottleMs||50,function(){w.forEach(y)}),w=[];let v;async function g(){v||(v=function(e,t,{getDocuments:r,EventSource:n}){const{projectId:o,dataset:i,listen:l,overlayDrafts:f,documentLimit:p}=e;if(!l)return{unsubscribe:d,loaded:r({projectId:o,dataset:i,documentLimit:p}).then(j).then(d)};const m=new Map;let h;const w=[];let v,g;const b=new Promise((e,t)=>{v=e,g=t});let y,E,_;return{unsubscribe:a(n,e,{next:function(e){h?(function(e){if(!e.effects||e.documentId.startsWith("_."))return;const t=m.get(e.documentId)||null;!function(e,t){const r=m.get(e),n=h||[],o=r?n.indexOf(r):-1;-1===o&&t?(n.push(t),m.set(e,t)):t?(n.splice(o,1,t),m.set(e,t)):(n.splice(o,1),m.delete(e))}(e.documentId,u(t,e.effects.apply))}(e),function(e,t){clearTimeout(_),E!==t.transactionId&&y?(j(y),E=void 0):(E=t.transactionId,y=e.slice()),_=setTimeout(j,25,e.slice())}(h,e)):w.push(e)},open:async function(){const e=await r({projectId:o,dataset:i,documentLimit:p});h=function(e,t){const r=new Map;return t.forEach(e=>{const t=r.get(e.documentId)||[];t.push(e),r.set(e.documentId,t)}),r.forEach((t,r)=>{const n=e.find(e=>e._id===r);if(!n)return void console.warn("Received mutation for missing document %s",r);let o=!1,i=n;t.forEach(e=>{o=o||e.previousRev===n._rev,o&&e.effects&&(i=u(i,e.effects.apply))}),e.splice(e.indexOf(n),1,i)}),e}(e,w),h.forEach(e=>m.set(e._id,e)),j(h),v()},error:e=>g(e)}).unsubscribe,loaded:b};function j(e){y=void 0,_=void 0,E=void 0,t(f?function(e){const t=new Map;return e.forEach(e=>{const r=t.get(c(e));e._id.startsWith("drafts.")?t.set(c(e),function(e){return s({},e,{_id:c(e)})}(e)):r||t.set(e._id,e)}),Array.from(t.values())}(e):e)}}(i,e=>{m=e,h()},p)),await v.loaded}async function b(e,t){await g();const r=n(e,{params:t});return(await o(r,{dataset:m,params:t})).get()}function y(e){return b(e.query,e.params).then(r=>{"previousResult"in e&&t(e.previousResult,r)||(e.previousResult=r,e.callback(void 0,r))}).catch(t=>{e.callback(t)})}return{query:b,getDocument:async function(t){return await g(),b(e(l||(l=f`*[_id == $id][0]`)),{id:t})},getDocuments:async function(e){return await g(),b(`[${e.map(e=>`*[_id == "${e}"][0]`).join(",\n")}]`)},subscribe:function(e,t,r){if(!i.listen)throw new Error("Cannot use `subscribe()` without `listen: true`");const n={query:e,params:t,callback:r};w.push(n);let o=!1;return y(n),{unsubscribe:()=>(o||(o=!0,w.splice(w.indexOf(n),1)),Promise.resolve())}},close:function(){return h.cancel(),v?v.unsubscribe():Promise.resolve()}}}(i,{EventSource:window.EventSource,getDocuments:p})}export{h as groqStore}; | ||
import e from"groq";export{default as groq}from"groq";import t from"fast-deep-equal";import{throttle as r}from"throttle-debounce";import{parse as n,evaluate as o}from"groq-js";import{applyPatch as i}from"mendoza";function s(){return(s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function a(e,t,r){const{projectId:n,dataset:o,token:i}=t,s=new e(`https://${n}.api.sanity.io/v1/data/listen/${o}?query=*&effectFormat=mendoza`,{withCredentials:!0,headers:i?{Authorization:"Bearer "+i}:void 0});var a;return s.addEventListener("welcome",r.open,!1),s.addEventListener("mutation",(a=r.next,e=>{let t;try{t=JSON.parse(e.data)}catch(e){return}a(t)}),!1),s.addEventListener("channelError",e=>{let t;s.close();try{t=JSON.parse(e.data)}catch(e){return void r.error(new Error("Unknown error parsing listener message"))}r.error(new Error(t.message||t.error||"Listener returned HTTP "+t.statusCode))},!1),s.addEventListener("error",e=>{const t="undefined"!=typeof window&&window.location.origin,n=t?`, and that the CORS-origin (${t}) is allowed`:"",o=function(e){return"object"==typeof e&&null!==e&&"message"in e}(e)?` (${e.message})`:"";r.error(new Error(`Error establishing listener - check that the project ID and dataset are correct${n}${o}`))},!1),{unsubscribe:()=>Promise.resolve(s.close())}}function c(e){return e._id.startsWith("drafts.")?e._id.slice(7):e._id}function u(e,t){const r=s({},e);return delete r._rev,i(r,t)}function d(){return Promise.resolve()}let l,f=e=>e;const p=async function({projectId:e,dataset:t,token:r,documentLimit:n}){const o=`https://${e}.api.sanity.io/v1/data/export/${t}`,i=r?{Authorization:"Bearer "+r}:void 0,s=await fetch(o,{credentials:"include",headers:i});if(200!==s.status)throw new Error("Error streaming dataset: "+("object"==typeof(a=await s.json())&&"error"in a&&"message"in a?a.message||a.error:"<unknown error>"));var a;const c=function(e){if(!e)throw new Error("Failed to read body from response");let t,r=!1;function n(){r=!0,t&&t.cancel()}return new ReadableStream({start(o){t=e.getReader();const i=new TextDecoder;let s="";t.read().then(async function e(a){if(a.done){if(r)return;return s=s.trim(),0===s.length||o.enqueue(JSON.parse(s)),void o.close()}s+=i.decode(a.value,{stream:!0});const c=s.split("\n");for(let e=0;e<c.length-1;++e){const t=c[e].trim();if(0!==t.length)try{o.enqueue(JSON.parse(t))}catch(e){return o.error(e),void n()}}if(s=c[c.length-1],t)try{e(await t.read())}catch(e){o.error(e)}}).catch(e=>o.error(e))},cancel:n})}(s.body).getReader(),u=[];let d,l;do{if(d=await c.read(),l=d.value,m(l))throw new Error("Error streaming dataset: "+l.error);if(l&&!l._id.startsWith("_.")&&u.push(l),n&&u.length>n)throw c.cancel("Reached document limit"),new Error(`Error streaming dataset: Reached limit of ${n} documents`)}while(!d.done);return u};function m(e){return!!e&&"error"in e&&"object"==typeof e.error&&null!==e.error&&"description"in e.error&&"string"==typeof e.error.description&&!("_id"in e)}function h(i){if(function(){const e=["EventSource","ReadableStream","fetch"].filter(e=>!(e in window));if(e.length>0)throw new Error("Browser not supported. Missing browser APIs: "+e.join(", "))}(),i.token)throw new Error("`token` option not currently supported in browser");return function(i,p){let m=[];const h=r(i.subscriptionThrottleMs||50,function(){w.forEach(y)}),w=[];let v;async function g(){v||(v=function(e,t,{getDocuments:r,EventSource:n}){const{projectId:o,dataset:i,listen:l,overlayDrafts:f,documentLimit:p}=e;if(!l)return{unsubscribe:d,loaded:r({projectId:o,dataset:i,documentLimit:p}).then(j).then(d)};const m=new Map;let h;const w=[];let v,g;const b=new Promise((e,t)=>{v=e,g=t});let y,E,_;return{unsubscribe:a(n,e,{next:function(e){h?(function(e){if(!e.effects||e.documentId.startsWith("_."))return;const t=m.get(e.documentId)||null;!function(e,t){const r=m.get(e),n=h||[],o=r?n.indexOf(r):-1;-1===o&&t?(n.push(t),m.set(e,t)):t?(n.splice(o,1,t),m.set(e,t)):(n.splice(o,1),m.delete(e))}(e.documentId,u(t,e.effects.apply))}(e),function(e,t){clearTimeout(_),E!==t.transactionId&&y?(j(y),E=void 0):(E=t.transactionId,y=e.slice()),_=setTimeout(j,25,e.slice())}(h,e)):w.push(e)},open:async function(){const e=await r({projectId:o,dataset:i,documentLimit:p});h=function(e,t){const r=new Map;return t.forEach(e=>{const t=r.get(e.documentId)||[];t.push(e),r.set(e.documentId,t)}),r.forEach((t,r)=>{const n=e.find(e=>e._id===r);if(!n)return void console.warn("Received mutation for missing document %s",r);let o=!1,i=n;t.forEach(e=>{o=o||e.previousRev===n._rev,o&&e.effects&&(i=u(i,e.effects.apply))}),e.splice(e.indexOf(n),1,i)}),e}(e,w),h.forEach(e=>m.set(e._id,e)),j(h),v()},error:e=>g(e)}).unsubscribe,loaded:b};function j(e){y=void 0,_=void 0,E=void 0,t(f?function(e){const t=new Map;return e.forEach(e=>{const r=t.get(c(e));e._id.startsWith("drafts.")?t.set(c(e),function(e){return s({},e,{_id:c(e)})}(e)):r||t.set(e._id,e)}),Array.from(t.values())}(e):e)}}(i,e=>{m=e,h()},p)),await v.loaded}async function b(e,t){await g();const r=n(e,{params:t});return(await o(r,{dataset:m,params:t})).get()}function y(e){return b(e.query,e.params).then(r=>{"previousResult"in e&&t(e.previousResult,r)||(e.previousResult=r,e.callback(void 0,r))}).catch(t=>{e.callback(t)})}return{query:b,getDocument:async function(t){return await g(),b(e(l||(l=f`*[_id == $id][0]`)),{id:t})},getDocuments:async function(e){return await g(),b(`[${e.map(e=>`*[_id == "${e}"][0]`).join(",\n")}]`)},subscribe:function(e,t,r){if(!i.listen)throw new Error("Cannot use `subscribe()` without `listen: true`");const n={query:e,params:t,callback:r};w.push(n);let o=!1;return y(n),{unsubscribe:()=>(o||(o=!0,w.splice(w.indexOf(n),1)),Promise.resolve())}},close:function(){return h.cancel(),v?v.unsubscribe():Promise.resolve()}}}(i,{EventSource:window.EventSource,getDocuments:p})}export{h as groqStore}; | ||
//# sourceMappingURL=groq-store.modern.js.map |
@@ -59,6 +59,7 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
}, false); | ||
es.addEventListener('error', () => { | ||
es.addEventListener('error', err => { | ||
const origin = typeof window !== 'undefined' && window.location.origin; | ||
const hintSuffix = origin ? `, and that the CORS-origin (${origin}) is allowed` : ''; | ||
handlers.error(new Error(`Error establishing listener - check that the project ID and dataset are correct${hintSuffix}`)); | ||
const errorMessage = isErrorLike(err) ? ` (${err.message})` : ''; | ||
handlers.error(new Error(`Error establishing listener - check that the project ID and dataset are correct${hintSuffix}${errorMessage}`)); | ||
}, false); | ||
@@ -85,2 +86,6 @@ return { | ||
function isErrorLike(err) { | ||
return typeof err === 'object' && err !== null && 'message' in err; | ||
} | ||
function isDraft(doc) { | ||
@@ -87,0 +92,0 @@ return doc._id.startsWith('drafts.'); |
{ | ||
"name": "@sanity/groq-store", | ||
"version": "0.2.1", | ||
"version": "0.2.2", | ||
"description": "Stream dataset to memory for in-memory querying", | ||
@@ -9,3 +9,3 @@ "main": "dist/node/groq-store.js", | ||
"typings": "dist/typings/index.d.ts", | ||
"sideEffects": "false", | ||
"sideEffects": false, | ||
"scripts": { | ||
@@ -12,0 +12,0 @@ "start": "cd example && npm start", |
@@ -43,8 +43,9 @@ import {Subscription, MutationEvent, Config, ApiError} from './types' | ||
'error', | ||
() => { | ||
(err) => { | ||
const origin = typeof window !== 'undefined' && window.location.origin | ||
const hintSuffix = origin ? `, and that the CORS-origin (${origin}) is allowed` : '' | ||
const errorMessage = isErrorLike(err) ? ` (${err.message})` : '' | ||
handlers.error( | ||
new Error( | ||
`Error establishing listener - check that the project ID and dataset are correct${hintSuffix}` | ||
`Error establishing listener - check that the project ID and dataset are correct${hintSuffix}${errorMessage}` | ||
) | ||
@@ -74,1 +75,5 @@ ) | ||
} | ||
function isErrorLike(err: unknown): err is {message: string} { | ||
return typeof err === 'object' && err !== null && 'message' in err | ||
} |
@@ -29,3 +29,3 @@ import sanityClient, {SanityClient} from '@sanity/client' | ||
store = groqStore({...config, listen: true, overlayDrafts: true}) | ||
errStore = groqStore({...config, projectId: 'n-o-p-e', listen: true, overlayDrafts: true}) | ||
errStore = groqStore({...config, dataset: 'n-o-p-e', listen: true, overlayDrafts: true}) | ||
}) | ||
@@ -32,0 +32,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
156481
1620