confbox
Version:
Compact YAML, TOML, JSONC, JSON5 and INI parser and serializer
2 lines (1 loc) • 1.54 kB
JavaScript
const b=/^(?:( )+|\t+)/,d="space",h="tab";function g(e,t){const n=new Map;let s=0,o,i;for(const c of e.split(/\n/g)){if(!c)continue;let f,a,l,p,r;const y=c.match(b);if(y===null)s=0,o="";else{if(f=y[0].length,a=y[1]?d:h,t&&a===d&&f===1)continue;a!==o&&(s=0),o=a,l=1,p=0;const u=f-s;if(s=f,u===0)l=0,p=1;else{const I=u>0?u:-u;i=T(a,I)}r=n.get(i),r=r===void 0?[1,0]:[r[0]+l,r[1]+p],n.set(i,r)}}return n}function T(e,t){return(e===d?"s":"t")+String(t)}function w(e){const n=e[0]==="s"?d:h,s=Number(e.slice(1));return{type:n,amount:s}}function E(e){let t,n=0,s=0;for(const[o,[i,c]]of e)(i>n||i===n&&c>s)&&(n=i,s=c,t=o);return t}function S(e,t){return(e===d?" ":" ").repeat(t)}function _(e){if(typeof e!="string")throw new TypeError("Expected a string");let t=g(e,!0);t.size===0&&(t=g(e,!1));const n=E(t);let s,o=0,i="";return n!==void 0&&({type:s,amount:o}=w(n),i=S(s,o)),{amount:o,type:s,indent:i}}const m=Symbol.for("__confbox_fmt__"),k=/^(\s+)/,v=/(\s+)$/;function x(e,t={}){const n=t.indent===void 0&&t.preserveIndentation!==!1&&e.slice(0,t?.sampleSize||1024),s=t.preserveWhitespace===!1?void 0:{start:k.exec(e)?.[0]||"",end:v.exec(e)?.[0]||""};return{sample:n,whiteSpace:s}}function N(e,t,n){!t||typeof t!="object"||Object.defineProperty(t,m,{enumerable:!1,configurable:!0,writable:!0,value:x(e,n)})}function C(e,t){if(!e||typeof e!="object"||!(m in e))return{indent:t?.indent??2,whitespace:{start:"",end:""}};const n=e[m];return{indent:t?.indent||_(n.sample||"").indent,whitespace:n.whiteSpace||{start:"",end:""}}}export{C as g,N as s};