ziggy-js
Version:
Use your Laravel named routes in JavaScript.
2 lines (1 loc) • 6.08 kB
JavaScript
import{parse as t,stringify as e}from"qs-esm";function r(){return r=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)({}).hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},r.apply(null,arguments)}class n{constructor(t,e,r){var n,i;this.name=t,this.definition=e,this.bindings=null!=(n=e.bindings)?n:{},this.wheres=null!=(i=e.wheres)?i:{},this.config=r}get template(){const t=`${this.origin}/${this.definition.uri}`.replace(/\/+$/,"");return""===t?"/":t}get origin(){return this.config.absolute?this.definition.domain?`${this.config.url.match(/^\w+:\/\//)[0]}${this.definition.domain}${this.config.port?`:${this.config.port}`:""}`:this.config.url:""}get parameterSegments(){var t,e;return null!=(t=null==(e=this.template.match(/{[^}?]+\??}/g))?void 0:e.map(t=>({name:t.replace(/{|\??}/g,""),required:!/\?}$/.test(t)})))?t:[]}matchesUrl(e){var r;if(!this.definition.methods.includes("GET"))return!1;const n=this.template.replace(/[.*+$()[\]]/g,"\\$&").replace(/(\/?){([^}?]*)(\??)}/g,(t,e,r,n)=>{var i;const s=`(?<${r}>${(null==(i=this.wheres[r])?void 0:i.replace(/(^\^)|(\$$)/g,""))||"[^/?]+"})`;return n?`(${e}${s})?`:`${e}${s}`}).replace(/^\w+:\/\//,""),[i,s]=e.replace(/^\w+:\/\//,"").split("?"),o=null!=(r=new RegExp(`^${n}/?$`).exec(i))?r:new RegExp(`^${n}/?$`).exec(decodeURI(i));if(o){for(const t in o.groups)o.groups[t]="string"==typeof o.groups[t]?decodeURIComponent(o.groups[t]):o.groups[t];return{params:o.groups,query:t(s)}}return!1}compile(t){return this.parameterSegments.length?this.template.replace(/{([^}?]+)(\??)}/g,(e,r,n)=>{var i,s;if(!n&&[null,void 0].includes(t[r]))throw new Error(`Ziggy error: '${r}' parameter is required for route '${this.name}'.`);if(this.wheres[r]&&!new RegExp(`^${n?`(${this.wheres[r]})?`:this.wheres[r]}$`).test(null!=(s=t[r])?s:""))throw new Error(`Ziggy error: '${r}' parameter '${t[r]}' does not match required format '${this.wheres[r]}' for route '${this.name}'.`);return encodeURI(null!=(i=t[r])?i:"").replace(/%7C/g,"|").replace(/%25/g,"%").replace(/\$/g,"%24")}).replace(this.config.absolute?/(\.[^/]+?)(\/\/)/:/(^)(\/\/)/,"$1/").replace(/\/+$/,""):this.template}}class i extends String{constructor(t,e,i=!0,s){if(super(),this.t=null!=s?s:"undefined"!=typeof Ziggy?Ziggy:null==globalThis?void 0:globalThis.Ziggy,!this.t&&"undefined"!=typeof document&&document.getElementById("ziggy-routes-json")&&(globalThis.Ziggy=JSON.parse(document.getElementById("ziggy-routes-json").textContent),this.t=globalThis.Ziggy),this.t=r({},this.t,{absolute:i}),t){if(!this.t.routes[t])throw new Error(`Ziggy error: route '${t}' is not in the route list.`);this.i=new n(t,this.t.routes[t],this.t),this.o=this.u(e)}}toString(){const t=Object.keys(this.o).filter(t=>!this.i.parameterSegments.some(({name:e})=>e===t)).filter(t=>"_query"!==t).reduce((t,e)=>r({},t,{[e]:this.o[e]}),{});return this.i.compile(this.o)+e(r({},t,this.o._query),{addQueryPrefix:!0,arrayFormat:"indices",encodeValuesOnly:!0,skipNulls:!0,encoder:(t,e)=>"boolean"==typeof t?Number(t):e(t)})}h(t){t?this.t.absolute&&t.startsWith("/")&&(t=this.l().host+t):t=this.m();let e={};const[i,s]=Object.entries(this.t.routes).find(([r,i])=>e=new n(r,i,this.t).matchesUrl(t))||[void 0,void 0];return r({name:i},e,{route:s})}m(){const{host:t,pathname:e,search:r}=this.l();return(this.t.absolute?t+e:e.replace(this.t.url.replace(/^\w*:\/\/[^/]+/,""),"").replace(/^\/+/,"/"))+r}current(t,e){const{name:i,params:s,query:o,route:u}=this.h();if(!t)return i;const h=new RegExp(`^${t.replace(/\./g,"\\.").replace(/\*/g,".*")}$`).test(i);if([null,void 0].includes(e)||!h)return h;const a=new n(i,u,this.t);e=this.u(e,a);const l=r({},s,o);if(Object.values(e).every(t=>!t)&&!Object.values(l).some(t=>void 0!==t))return!0;const c=(t,e)=>Object.entries(t).every(([t,r])=>Array.isArray(r)&&Array.isArray(e[t])?r.every(r=>e[t].includes(r)||e[t].includes(decodeURIComponent(r))):"object"==typeof r&&"object"==typeof e[t]&&null!==r&&null!==e[t]?c(r,e[t]):e[t]==r||e[t]==decodeURIComponent(r));return c(e,l)}l(){var t,e,r,n,i,s;const{host:o="",pathname:u="",search:h=""}="undefined"!=typeof window?window.location:{};return{host:null!=(t=null==(e=this.t.location)?void 0:e.host)?t:o,pathname:null!=(r=null==(n=this.t.location)?void 0:n.pathname)?r:u,search:null!=(i=null==(s=this.t.location)?void 0:s.search)?i:h}}get params(){const{params:t,query:e}=this.h();return r({},t,e)}get routeParams(){return this.h().params}get queryParams(){return this.h().query}has(t){return this.t.routes.hasOwnProperty(t)}u(t={},e=this.i){null!=t||(t={}),t=["string","number"].includes(typeof t)?[t]:t;const n=e.parameterSegments.filter(({name:t})=>!this.t.defaults[t]);return Array.isArray(t)?t=t.reduce((t,e,i)=>r({},t,n[i]?{[n[i].name]:e}:"object"==typeof e?e:{[e]:""}),{}):1!==n.length||t[n[0].name]||!t.hasOwnProperty(Object.values(e.bindings)[0])&&!t.hasOwnProperty("id")||(t={[n[0].name]:t}),r({},this.p(e),this.$(t,e))}p(t){return t.parameterSegments.filter(({name:t})=>this.t.defaults[t]).reduce((t,{name:e},n)=>r({},t,{[e]:this.t.defaults[e]}),{})}$(t,{bindings:e,parameterSegments:n}){return Object.entries(t).reduce((t,[i,s])=>{if(!s||"object"!=typeof s||Array.isArray(s)||!n.some(({name:t})=>t===i))return r({},t,{[i]:s});if(!s.hasOwnProperty(e[i])){if(!s.hasOwnProperty("id"))throw new Error(`Ziggy error: object passed as '${i}' parameter is missing route model binding key '${e[i]}'.`);e[i]="id"}return r({},t,{[i]:s[e[i]]})},{})}valueOf(){return this.toString()}}function s(t,e,r,n){const s=new i(t,e,r,n);return t?s.toString():s}const o={install(t,e){const r=(t,r,n,i=e)=>s(t,r,n,i);parseInt(t.version)>2?(t.config.globalProperties.route=r,t.provide("route",r)):t.mixin({methods:{route:r}})}};function u(t){if(!t&&!globalThis.Ziggy&&"undefined"==typeof Ziggy&&!document.getElementById("ziggy-routes-json"))throw new Error("Ziggy error: missing configuration. Ensure that a `Ziggy` variable is defined globally or pass a config object into the useRoute hook.");return(e,r,n,i=t)=>s(e,r,n,i)}export{o as ZiggyVue,s as route,u as useRoute};