UNPKG

state-in-url

Version:

Store state in URL as in object, types and structure are preserved, with TS validation. Same API as React.useState, wthout any hasssle or boilerplate. Next.js@14-16, react-router@6-7, remix@2, and Astro.

2 lines (1 loc) • 1.3 kB
"use strict";var r=require("../constants/constants.cjs");var u=require("../utils.cjs");const p=/['"]/g;const v={"'":"%27",'"':"'"};const y=/'|%27/g;const l={"'":'"',"%27":"'"};function B(e){if(typeof e==="function"||typeof e==="symbol")return"";return JSON.stringify(c("",e)).replace(p,t=>v[t])}function c(e,t){const n=u.typeOf(t);if(n!=="object"&&n!=="array"){return f(t)}if(n==="object"){const i=t;const o={};for(const s of Object.keys(i)){o[s]=c(e,i[s])}return o}if(n==="array"){return t.map(i=>c(e,i))}return t}const a=e=>Object.values(r.SYMBOLS).some(t=>e.startsWith(t));const f=e=>{if(typeof e==="string"&&a(e)){return r.SYMBOLS.escape+e}switch(u.typeOf(e)){case"date":return r.SYMBOLS.date+new Date(e).toISOString();case"undefined":return r.SYMBOLS.undefined;default:return e}};function L(e,t){return d(e.replace(y,n=>l[n]),t)}function d(e,t){try{return JSON.parse(e,S)}catch{return t}}function S(e,t){return typeof t==="string"?O(t):t}const O=e=>{const t=e?.startsWith?.(r.SYMBOLS.escape)?e.slice(r.SYMBOLS.escape.length):void 0;if(t!==void 0&&a(t))return t;if(e===r.SYMBOLS.undefined)return void 0;if(e?.startsWith?.(r.SYMBOLS.date))return new Date(e.slice(1));return e};exports.decode=L;exports.decodePrimitive=O;exports.encode=B;exports.encodePrimitive=f;exports.parseJSON=d;exports.reviver=S;