UNPKG

prismic-javascript

Version:
17 lines (14 loc) 17.9 kB
import t from"cross-fetch"; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */var e=function(){return(e=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},r=function(){function t(t){this.data={},this.data=t}return t.prototype.id=function(){return this.data.id},t.prototype.ref=function(){return this.data.ref},t.prototype.label=function(){return this.data.label},t}(),n=function(){function t(t){this.data={},this.data=t,this.variations=(t.variations||[]).map((function(t){return new r(t)}))}return t.prototype.id=function(){return this.data.id},t.prototype.googleId=function(){return this.data.googleId},t.prototype.name=function(){return this.data.name},t}(),i=function(){function t(t){t&&(this.drafts=(t.drafts||[]).map((function(t){return new n(t)})),this.running=(t.running||[]).map((function(t){return new n(t)})))}return t.prototype.current=function(){return this.running.length>0?this.running[0]:null},t.prototype.refFromCookie=function(t){if(!t||""===t.trim())return null;var e=t.trim().split(" ");if(e.length<2)return null;var r=e[0],n=parseInt(e[1],10),i=this.running.filter((function(t){return t.googleId()===r&&t.variations.length>n}))[0];return i?i.variations[n].ref():null},t}(),o=function(){function t(t,e){this.id=t,this.api=e,this.fields={}}return t.prototype.set=function(t,e){return this.fields[t]=e,this},t.prototype.ref=function(t){return this.set("ref",t)},t.prototype.query=function(t){return this.set("q",t)},t.prototype.pageSize=function(t){return this.set("pageSize",t)},t.prototype.fetch=function(t){return console.warn("Warning: Using Fetch is deprecated. Use the property `graphQuery` instead."),this.set("fetch",t)},t.prototype.fetchLinks=function(t){return console.warn("Warning: Using FetchLinks is deprecated. Use the property `graphQuery` instead."),this.set("fetchLinks",t)},t.prototype.graphQuery=function(t){return this.set("graphQuery",t)},t.prototype.lang=function(t){return this.set("lang",t)},t.prototype.page=function(t){return this.set("page",t)},t.prototype.after=function(t){return this.set("after",t)},t.prototype.orderings=function(t){return this.set("orderings",t)},t.prototype.url=function(){var e=this;return this.api.get().then((function(r){return t.toSearchForm(e,r).url()}))},t.prototype.submit=function(e){var r=this;return this.api.get().then((function(n){return t.toSearchForm(r,n).submit(e)}))},t.toSearchForm=function(t,e){var r=e.form(t.id);if(r)return Object.keys(t.fields).reduce((function(e,r){var n=t.fields[r];return"q"===r?e.query(n):"pageSize"===r?e.pageSize(n):"fetch"===r?e.fetch(n):"fetchLinks"===r?e.fetchLinks(n):"graphQuery"===r?e.graphQuery(n):"lang"===r?e.lang(n):"page"===r?e.page(n):"after"===r?e.after(n):"orderings"===r?e.orderings(n):e.set(r,n)}),r);throw new Error("Unable to access to form "+t.id)},t}(),u=function(){function t(t,e){for(var r in this.httpClient=e,this.form=t,this.data={},t.fields)t.fields[r].default&&(this.data[r]=[t.fields[r].default])}return t.prototype.set=function(t,e){var r=this.form.fields[t];if(!r)throw new Error("Unknown field "+t);var n=""===e||void 0===e?null:e,i=this.data[t]||[];return i=r.multiple?n?i.concat([n]):i:n?[n]:i,this.data[t]=i,this},t.prototype.ref=function(t){return this.set("ref",t)},t.prototype.query=function(t){if("string"==typeof t)return this.query([t]);if(Array.isArray(t))return this.set("q","["+t.join("")+"]");throw new Error("Invalid query : "+t)},t.prototype.pageSize=function(t){return this.set("pageSize",t)},t.prototype.fetch=function(t){console.warn("Warning: Using Fetch is deprecated. Use the property `graphQuery` instead.");var e=Array.isArray(t)?t.join(","):t;return this.set("fetch",e)},t.prototype.fetchLinks=function(t){console.warn("Warning: Using FetchLinks is deprecated. Use the property `graphQuery` instead.");var e=Array.isArray(t)?t.join(","):t;return this.set("fetchLinks",e)},t.prototype.graphQuery=function(t){return this.set("graphQuery",t)},t.prototype.lang=function(t){return this.set("lang",t)},t.prototype.page=function(t){return this.set("page",t)},t.prototype.after=function(t){return this.set("after",t)},t.prototype.orderings=function(t){return t?this.set("orderings","["+t.join(",")+"]"):this},t.prototype.url=function(){var t=this.form.action;if(this.data){var e=t.indexOf("?")>-1?"&":"?";for(var r in this.data)if(Object.prototype.hasOwnProperty.call(this.data,r)){var n=this.data[r];if(n)for(var i=0;i<n.length;i++)t+=e+r+"="+encodeURIComponent(n[i]),e="&"}}return t},t.prototype.submit=function(t){return this.httpClient.cachedRequest(this.url()).then((function(e){return t&&t(null,e),e})).catch((function(e){throw t&&t(e),e}))},t}(),s="at",a="not",f="missing",h="has",p="any",c="in",l="fulltext",y="similar",d="number.gt",g="number.lt",m="number.inRange",v="date.before",w="date.after",k="date.between",b="date.day-of-month",A="date.day-of-month-after",q="date.day-of-month-before",B="date.day-of-week",I="date.day-of-week-after",O="date.day-of-week-before",x="date.month",D="date.month-before",S="date.month-after",U="date.year",R="date.hour",E="date.hour-before",C="date.hour-after",F="geopoint.near";function j(t){if("string"==typeof t)return'"'+t+'"';if("number"==typeof t)return t.toString();if(t instanceof Date)return t.getTime().toString();if(Array.isArray(t))return"["+t.map((function(t){return j(t)})).join(",")+"]";if("boolean"==typeof t)return t.toString();throw new Error("Unable to encode "+t+" of type "+typeof t)}var M={near:function(t,e,r,n){return"["+F+"("+t+", "+e+", "+r+", "+n+")]"}},T={before:function(t,e){return"["+v+"("+t+", "+j(e)+")]"},after:function(t,e){return"["+w+"("+t+", "+j(e)+")]"},between:function(t,e,r){return"["+k+"("+t+", "+j(e)+", "+j(r)+")]"},dayOfMonth:function(t,e){return"["+b+"("+t+", "+e+")]"},dayOfMonthAfter:function(t,e){return"["+A+"("+t+", "+e+")]"},dayOfMonthBefore:function(t,e){return"["+q+"("+t+", "+e+")]"},dayOfWeek:function(t,e){return"["+B+"("+t+", "+j(e)+")]"},dayOfWeekAfter:function(t,e){return"["+I+"("+t+", "+j(e)+")]"},dayOfWeekBefore:function(t,e){return"["+O+"("+t+", "+j(e)+")]"},month:function(t,e){return"["+x+"("+t+", "+j(e)+")]"},monthBefore:function(t,e){return"["+D+"("+t+", "+j(e)+")]"},monthAfter:function(t,e){return"["+S+"("+t+", "+j(e)+")]"},year:function(t,e){return"["+U+"("+t+", "+e+")]"},hour:function(t,e){return"["+R+"("+t+", "+e+")]"},hourBefore:function(t,e){return"["+E+"("+t+", "+e+")]"},hourAfter:function(t,e){return"["+C+"("+t+", "+e+")]"}},W={gt:function(t,e){return"["+d+"("+t+", "+e+")]"},lt:function(t,e){return"["+g+"("+t+", "+e+")]"},inRange:function(t,e,r){return"["+m+"("+t+", "+e+", "+r+")]"}},z={at:function(t,e){return"["+s+"("+t+", "+j(e)+")]"},not:function(t,e){return"["+a+"("+t+", "+j(e)+")]"},missing:function(t){return"["+f+"("+t+")]"},has:function(t){return"["+h+"("+t+")]"},any:function(t,e){return"["+p+"("+t+", "+j(e)+")]"},in:function(t,e){return"["+c+"("+t+", "+j(e)+")]"},fulltext:function(t,e){return"["+l+"("+t+", "+j(e)+")]"},similar:function(t,e){return"["+y+'("'+t+'", '+e+")]"},date:T,dateBefore:T.before,dateAfter:T.after,dateBetween:T.between,dayOfMonth:T.dayOfMonth,dayOfMonthAfter:T.dayOfMonthAfter,dayOfMonthBefore:T.dayOfMonthBefore,dayOfWeek:T.dayOfWeek,dayOfWeekAfter:T.dayOfWeekAfter,dayOfWeekBefore:T.dayOfWeekBefore,month:T.month,monthBefore:T.monthBefore,monthAfter:T.monthAfter,year:T.year,hour:T.hour,hourBefore:T.hourBefore,hourAfter:T.hourAfter,number:W,gt:W.gt,lt:W.lt,inRange:W.inRange,near:M.near,geopoint:M},L=decodeURIComponent;var P={parse:function(t,e){if("string"!=typeof t)throw new TypeError("argument str must be a string");var r={},n=e||{},i=t.split(/; */),o=n.decode||L;return i.forEach((function(t){var e=t.indexOf("=");if(!(e<0)){var n=t.substr(0,e).trim(),i=t.substr(++e,t.length).trim();'"'==i[0]&&(i=i.slice(1,-1)),null==r[n]&&(r[n]=function(t,e){try{return e(t)}catch(e){return t}}(i,o))}})),r}};function _(t,e,r){return{token:t,documentId:e,resolve:function(n,i,o){return e&&r?r(e,{ref:t}).then((function(t){if(t){var e=n&&n(t)||t.url||i;return o&&o(null,e),e}return o&&o(null,i),i})):Promise.resolve(i)}}}var Q=function(){function t(t,e,r){this.data=t,this.masterRef=t.refs.filter((function(t){return t.isMasterRef}))[0],this.experiments=new i(t.experiments),this.bookmarks=t.bookmarks,this.httpClient=e,this.options=r,this.refs=t.refs,this.tags=t.tags,this.types=t.types,this.languages=t.languages}return t.prototype.form=function(t){var e=this.data.forms[t];return e?new u(e,this.httpClient):null},t.prototype.everything=function(){var t=this.form("everything");if(!t)throw new Error("Missing everything form");return t},t.prototype.master=function(){return this.masterRef.ref},t.prototype.ref=function(t){var e=this.data.refs.filter((function(e){return e.label===t}))[0];return e?e.ref:null},t.prototype.currentExperiment=function(){return this.experiments.current()},t.prototype.query=function(t,e,r){void 0===r&&(r=function(){});var n="function"==typeof e?{options:{},callback:e}:{options:e||{},callback:r},i=n.options,o=n.callback,u=this.everything();for(var s in i)u=u.set(s,i[s]);if(!i.ref){var a="";this.options.req?a=this.options.req.headers.cookie||"":"undefined"!=typeof window&&window.document&&(a=window.document.cookie||"");var f=P.parse(a),h=f["io.prismic.preview"],p=this.experiments.refFromCookie(f["io.prismic.experiment"]);u=u.ref(h||p||this.masterRef.ref)}return t&&u.query(t),u.submit(o)},t.prototype.queryFirst=function(t,e,r){var n="function"==typeof e?{options:{},callback:e}:{options:e||{},callback:r||function(){}},i=n.options,o=n.callback;return i.page=1,i.pageSize=1,this.query(t,i).then((function(t){var e=t&&t.results&&t.results[0];return o(null,e),e})).catch((function(t){throw o(t),t}))},t.prototype.getByID=function(t,r,n){var i=r?e({},r):{};return i.lang||(i.lang="*"),this.queryFirst(z.at("document.id",t),i,n)},t.prototype.getByIDs=function(t,r,n){var i=r?e({},r):{};return i.lang||(i.lang="*"),this.query(z.in("document.id",t),i,n)},t.prototype.getByUID=function(t,r,n,i){var o=n?e({},n):{};if("*"===o.lang)throw new Error("FORBIDDEN. You can't use getByUID with *, use the predicates instead.");return o.page||(o.page=1),this.queryFirst(z.at("my."+t+".uid",r),o,i)},t.prototype.getSingle=function(t,r,n){var i=r?e({},r):{};return this.queryFirst(z.at("document.type",t),i,n)},t.prototype.getBookmark=function(t,e,r){var n=this.data.bookmarks[t];return n?this.getByID(n,e,r):Promise.reject("Error retrieving bookmarked id")},t.prototype.getPreviewResolver=function(t,e){return _(t,e,this.getByID.bind(this))},t.prototype.previewSession=function(t,e,r,n){var i=this;return console.warn("previewSession function is deprecated in favor of getPreviewResolver function."),new Promise((function(o,u){i.httpClient.request(t,(function(s,a){if(s)n&&n(s),u(s);else if(a){if(a.mainDocument)return i.getByID(a.mainDocument,{ref:t}).then((function(t){if(t){var i=e&&e(t)||t.url||r;n&&n(null,i),o(i)}else n&&n(null,r),o(r)})).catch(u);n&&n(null,r),o(r)}}))}))},t}();function H(t){this.size=0,this.limit=t,this._keymap={}}H.prototype.put=function(t,e){var r={key:t,value:e};if(this._keymap[t]=r,this.tail?(this.tail.newer=r,r.older=this.tail):this.head=r,this.tail=r,this.size===this.limit)return this.shift();this.size++},H.prototype.shift=function(){var t=this.head;return t&&(this.head.newer?(this.head=this.head.newer,this.head.older=void 0):this.head=void 0,t.newer=t.older=void 0,delete this._keymap[t.key]),console.log("purging ",t.key),t},H.prototype.get=function(t,e){var r=this._keymap[t];if(void 0!==r)return r===this.tail||(r.newer&&(r===this.head&&(this.head=r.newer),r.newer.older=r.older),r.older&&(r.older.newer=r.newer),r.newer=void 0,r.older=this.tail,this.tail&&(this.tail.newer=r),this.tail=r),e?r:r.value},H.prototype.find=function(t){return this._keymap[t]},H.prototype.set=function(t,e){var r,n=this.get(t,!0);return n?(r=n.value,n.value=e):(r=this.put(t,e))&&(r=r.value),r},H.prototype.remove=function(t){var e=this._keymap[t];if(e)return delete this._keymap[e.key],e.newer&&e.older?(e.older.newer=e.newer,e.newer.older=e.older):e.newer?(e.newer.older=void 0,this.head=e.newer):e.older?(e.older.newer=void 0,this.tail=e.older):this.head=this.tail=void 0,this.size--,e.value},H.prototype.removeAll=function(){this.head=this.tail=void 0,this.size=0,this._keymap={}},"function"==typeof Object.keys?H.prototype.keys=function(){return Object.keys(this._keymap)}:H.prototype.keys=function(){var t=[];for(var e in this._keymap)t.push(e);return t},H.prototype.forEach=function(t,e,r){var n;if(!0===e?(r=!0,e=void 0):"object"!=typeof e&&(e=this),r)for(n=this.tail;n;)t.call(e,n.key,n.value,this),n=n.older;else for(n=this.head;n;)t.call(e,n.key,n.value,this),n=n.newer},H.prototype.toString=function(){for(var t="",e=this.head;e;)t+=String(e.key)+":"+e.value,(e=e.newer)&&(t+=" < ");return t};var N=function(){function t(t){void 0===t&&(t=1e3),this.lru=function(t){return new H(t)}(t)}return t.prototype.isExpired=function(t){var e=this.lru.get(t,!1);return!!e&&(0!==e.expiredIn&&e.expiredIn<Date.now())},t.prototype.get=function(t,e){var r=this.lru.get(t,!1);r&&!this.isExpired(t)?e(null,r.data):e&&e(null)},t.prototype.set=function(t,e,r,n){this.lru.remove(t),this.lru.put(t,{data:e,expiredIn:r?Date.now()+1e3*r:0}),n&&n(null)},t.prototype.remove=function(t,e){this.lru.remove(t),e&&e(null)},t.prototype.clear=function(t){this.lru.removeAll(),t&&t(null)},t}();var J=function(){function e(t){this.options=t||{}}return e.prototype.request=function(e,r){!function(e,r,n){var i,o={headers:{Accept:"application/json"}};r&&r.proxyAgent&&(o.agent=r.proxyAgent);var u=t(e,o);(r.timeoutInMs?Promise.race([u,new Promise((function(t,n){i=setTimeout((function(){return n(new Error(e+" response timeout"))}),r.timeoutInMs)}))]):u).then((function(t){return clearTimeout(i),~~(t.status/100!=2)?t.text().then((function(){var r=new Error("Unexpected status code ["+t.status+"] on URL "+e);throw r.status=t.status,r})):t.json().then((function(e){var r=t.headers.get("cache-control"),i=r?/max-age=(\d+)/.exec(r):null,o=i?parseInt(i[1],10):void 0;n(null,e,t,o)}))})).catch((function(t){clearTimeout(i),n(t)}))}(e,this.options,r)},e}(),K=function(){function t(t,e,r,n){this.requestHandler=t||new J({proxyAgent:r,timeoutInMs:n}),this.cache=e||new N}return t.prototype.request=function(t,e){this.requestHandler.request(t,(function(t,r,n,i){t?e&&e(t,null,n,i):r&&e&&e(null,r,n,i)}))},t.prototype.cachedRequest=function(t,e){var r=this,n=e||{};return new Promise((function(e,i){var o,u;o=function(t,r){t&&i(t),r&&e(r)},u=n.cacheKey||t,r.cache.get(u,(function(e,i){e||i?o(e,i):r.request(t,(function(t,e,i,s){if(t)o(t,null);else{var a=s||n.ttl;a&&r.cache.set(u,e,a,o),o(null,e)}}))}))}))},t}();function Y(t){return t.indexOf("?")>-1?"&":"?"}var G=function(){function t(t,e){if(this.options=e||{},this.url=t,this.options.accessToken){var r="access_token="+this.options.accessToken;this.url+=Y(t)+r}this.options.routes&&(this.url+=Y(t)+"routes="+encodeURIComponent(JSON.stringify(this.options.routes))),this.apiDataTTL=this.options.apiDataTTL||5,this.httpClient=new K(this.options.requestHandler,this.options.apiCache,this.options.proxyAgent,this.options.timeoutInMs)}return t.prototype.get=function(t){var e=this;return this.httpClient.cachedRequest(this.url,{ttl:this.apiDataTTL}).then((function(r){var n=new Q(r,e.httpClient,e.options);return t&&t(null,n),n})).catch((function(e){throw t&&t(e),e}))},t}(),V=function(){function t(t,e){this.api=new G(t,e)}return t.prototype.getApi=function(){return this.api.get()},t.prototype.everything=function(){return this.form("everything")},t.prototype.form=function(t){return new o(t,this.api)},t.prototype.query=function(t,e,r){return this.getApi().then((function(n){return n.query(t,e,r)}))},t.prototype.queryFirst=function(t,e,r){return this.getApi().then((function(n){return n.queryFirst(t,e,r)}))},t.prototype.getByID=function(t,e,r){return this.getApi().then((function(n){return n.getByID(t,e,r)}))},t.prototype.getByIDs=function(t,e,r){return this.getApi().then((function(n){return n.getByIDs(t,e,r)}))},t.prototype.getByUID=function(t,e,r,n){return this.getApi().then((function(i){return i.getByUID(t,e,r,n)}))},t.prototype.getSingle=function(t,e,r){return this.getApi().then((function(n){return n.getSingle(t,e,r)}))},t.prototype.getBookmark=function(t,e,r){return this.getApi().then((function(n){return n.getBookmark(t,e,r)}))},t.prototype.previewSession=function(t,e,r,n){return this.getApi().then((function(i){return i.previewSession(t,e,r,n)}))},t.prototype.getPreviewResolver=function(t,e){var r=this;return _(t,e,(function(t,e){return r.getApi().then((function(r){return r.getByID(t,e)}))}))},t.getApi=function(t,e){return new G(t,e).get()},t}(),X={experimentCookie:"io.prismic.experiment",previewCookie:"io.prismic.preview",Predicates:z,Experiments:i,Api:G,client:function(t,e){return new V(t,e)},getApi:Z,api:function(t,e){return Z(t,e)}};function Z(t,e){return V.getApi(t,e)}export default X; //# sourceMappingURL=prismic-javascript.min.mjs.map