UNPKG

remark-accurate-remove

Version:

Remove anything from the markdown accurately.

3 lines (2 loc) 2.53 kB
import*as n from"cheerio";const t=(t=[])=>e=>{const o=n=>n?"string"==typeof n.value?n.value:(n=>Array.isArray(n.children))(n)?n.children.map(o).join(""):"":"",i=(n,t,e)=>{const i=n.children;let c=-1,s=-1;const r=n=>{const t=n.trim(),e=t.match(/^#+/),o=e?e[0].length:void 0;return{level:o,text:e?t.slice(o).trim():t}},d=r(t),f=r(e);for(let n=0;i.length>n;n++){const t=i[n];if(t&&"heading"===t.type){const e=t;if(o(e).trim()===d.text&&(void 0===d.level||e.depth===d.level)){c=n;break}}}for(let n=c+1;i.length>n;n++){const t=i[n];if(t&&"heading"===t.type){const e=t;if(o(e).trim()===f.text&&(void 0===f.level||e.depth===f.level)){s=n;break}}}return{startIndex:c,endIndex:s}},c=new Set(["including-start-boundary","including-end-boundary","including-boundaries"]),s=n=>"string"==typeof n&&c.has(n),r=n=>n.includes("all-content");for(const o of t){const{remove:t,range:c}=o;if(r(t)){if(!c)continue;const[n,o]=c,{startIndex:r,endIndex:d}=i(e,n,o);if(-1===r)continue;const f=-1===d?e.children.length:d,l=t.filter(s);let u=l.includes("including-start-boundary")||l.includes("including-boundaries")?r:r+1,a=l.includes("including-end-boundary")||l.includes("including-boundaries")?f:f-1;if(0>u&&(u=0),e.children.length>a||(a=e.children.length-1),u>a)continue;e.children.splice(u,a-u+1);continue}const[d]=t;if("html"===d){const o=2===t.length&&"object"==typeof t[1]?t[1].$:null,s=t=>{if(t.children)for(let e=t.children.length-1;e>=0;e--){const i=t.children[e];if("html"===i.type){const c=i;if(!o){t.children.splice(e,1);continue}const s=n.load(c.value,{xml:{decodeEntities:!1,xmlMode:!1}});try{s(o).remove()}catch{}const r=s.html();r&&""!==r.trim()?c.value=r:t.children.splice(e,1)}else i.children&&s(i)}};if(c){const[n,t]=c,{startIndex:o,endIndex:r}=i(e,n,t);if(-1===o)continue;for(let n=(-1===r?e.children.length:r)-1;n>o;n--){const t=e.children[n];if(t.children&&s(t),"html"===t.type){const o={children:[t]};s(o),0===o.children.length?e.children.splice(n,1):o.children[0]!==t&&(e.children[n]=o.children[0])}}}else s(e)}else if("regex"===d){const n=t[1];let o;if("string"==typeof n)o=RegExp(n,"g");else{const t=n.flags.includes("g")?n.flags:n.flags+"g";o=RegExp(n.source,t)}const s=n=>{if(n)if("text"===n.type){n.value=n.value.replace(o,"")}else if(n.children)for(const t of n.children)s(t)};if(c){const[n,t]=c,{startIndex:o,endIndex:r}=i(e,n,t);if(-1===o)continue;const d=-1===r?e.children.length:r;for(let n=o+1;d>n;n++)s(e.children[n])}else s(e)}}return e};export{t as remarkAccurateRemove}; //# sourceMappingURL=index.esm.min.js.map