slack-term 1.38.0 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,21 +1,21 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{createRequire as ld}from"node:module";var sd=Object.create;var{getPrototypeOf:od,defineProperty:ki,getOwnPropertyNames:rd}=Object;var Ci=Object.prototype.hasOwnProperty;function id(e){return this[e]}var ad,cd,Ei=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?ad??=new WeakMap:cd??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?sd(od(e)):{};let i=t||!e||!e.__esModule||!Ci.call(e,"default")?ki(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of rd(e))if(!Ci.call(i,c))ki(i,c,{get:id.bind(e,c),enumerable:!0})}if(o)s.set(e,i);return i};var xi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var bn=ld(import.meta.url);var Ui=xi(function(sm,Wi){Wi.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var ha=xi(function(Hm,pa){pa.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(s,r){return r};var o=Error().stack;if(Error.prepareStackTrace=n,o!==null&&typeof o==="object")return o[t]?o[t].getFileName():void 0}});import{createHash as Fh}from"crypto";import{existsSync as Ju,readFileSync as Hu,mkdirSync as Sh,realpathSync as _h,writeFileSync as zu}from"fs";import{homedir as Iu}from"os";import{join as xt,resolve as $h}from"path";import{notStrictEqual as Gd,strictEqual as Xd}from"assert";var ud={right:pd,center:hd};class Si{constructor(e){var t;this.width=e.width,this.wrap=(t=e.wrap)!==null&&t!==void 0?t:!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==="string")return this.applyLayoutDSL(e[0]);let t=e.map((n)=>{if(typeof n==="string")return this.colFromString(n);return n});return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
3
+ import{createRequire as $d}from"node:module";var xd=Object.create;var{getPrototypeOf:Cd,defineProperty:Ti,getOwnPropertyNames:Ed}=Object;var Ii=Object.prototype.hasOwnProperty;function Sd(e){return this[e]}var Fd,_d,Oi=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?Fd??=new WeakMap:_d??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?xd(Cd(e)):{};let i=t||!e||!e.__esModule||!Ii.call(e,"default")?Ti(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of Ed(e))if(!Ii.call(i,c))Ti(i,c,{get:Sd.bind(e,c),enumerable:!0})}if(o)s.set(e,i);return i};var Pi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var bn=$d(import.meta.url);var Vi=Pi(function(Fm,Yi){Yi.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var Ca=Pi(function(hD,xa){xa.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(s,r){return r};var o=Error().stack;if(Error.prepareStackTrace=n,o!==null&&typeof o==="object")return o[t]?o[t].getFileName():void 0}});import{createHash as Kh}from"crypto";import{existsSync as cd,readFileSync as ld,mkdirSync as Hh,realpathSync as zh,writeFileSync as ud}from"fs";import{homedir as Yu}from"os";import{join as St,resolve as qh}from"path";import{notStrictEqual as hf,strictEqual as gf}from"assert";var Ad={right:Od,center:Pd};class Ni{constructor(e){var t;this.width=e.width,this.wrap=(t=e.wrap)!==null&&t!==void 0?t:!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==="string")return this.applyLayoutDSL(e[0]);let t=e.map((n)=>{if(typeof n==="string")return this.colFromString(n);return n});return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
4
4
  `).map((o)=>o.split("\t")),n=0;return t.forEach((o)=>{if(o.length>1&&Oe.stringWidth(o[0])>n)n=Math.min(Math.floor(this.width*0.5),Oe.stringWidth(o[0]))}),t.forEach((o)=>{this.div(...o.map((s,r)=>({text:s.trim(),padding:this.measurePadding(s),width:r===0&&o.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=Oe.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach((t)=>{this.rowToString(t,e)}),e.filter((t)=>!t.hidden).map((t)=>t.text).join(`
5
- `)}rowToString(e,t){return this.rasterize(e).forEach((n,o)=>{let s="";n.forEach((r,i)=>{let{width:c}=e[i],a=this.negatePadding(e[i]),l=r;if(a>Oe.stringWidth(r))l+=" ".repeat(a-Oe.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=ud[e[i].align];if(l=d(l,a),Oe.stringWidth(l)<a)l+=" ".repeat((c||0)-Oe.stringWidth(l)-1)}let u=e[i].padding||[0,0,0,0];if(u[3])s+=" ".repeat(u[3]);if(s+=Fi(e[i],l,"| "),s+=l,s+=Fi(e[i],l," |"),u[1])s+=" ".repeat(u[1]);if(o===0&&t.length>0)s=this.renderInline(s,t[t.length-1])}),t.push({text:s.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),o=n?n[0].length:0,s=t.text,r=Oe.stringWidth(s.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,s+e;if(o<r)return e;return t.hidden=!0,s.trimRight()+" ".repeat(o-r)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),o;return e.forEach((s,r)=>{if(s.width=n[r],this.wrap)o=Oe.wrap(s.text,this.negatePadding(s),{hard:!0}).split(`
5
+ `)}rowToString(e,t){return this.rasterize(e).forEach((n,o)=>{let s="";n.forEach((r,i)=>{let{width:c}=e[i],a=this.negatePadding(e[i]),l=r;if(a>Oe.stringWidth(r))l+=" ".repeat(a-Oe.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Ad[e[i].align];if(l=d(l,a),Oe.stringWidth(l)<a)l+=" ".repeat((c||0)-Oe.stringWidth(l)-1)}let u=e[i].padding||[0,0,0,0];if(u[3])s+=" ".repeat(u[3]);if(s+=Ri(e[i],l,"| "),s+=l,s+=Ri(e[i],l," |"),u[1])s+=" ".repeat(u[1]);if(o===0&&t.length>0)s=this.renderInline(s,t[t.length-1])}),t.push({text:s.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),o=n?n[0].length:0,s=t.text,r=Oe.stringWidth(s.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,s+e;if(o<r)return e;return t.hidden=!0,s.trimRight()+" ".repeat(o-r)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),o;return e.forEach((s,r)=>{if(s.width=n[r],this.wrap)o=Oe.wrap(s.text,this.negatePadding(s),{hard:!0}).split(`
6
6
  `);else o=s.text.split(`
7
- `);if(s.border)o.unshift("."+"-".repeat(this.negatePadding(s)+2)+"."),o.push("'"+"-".repeat(this.negatePadding(s)+2)+"'");if(s.padding)o.unshift(...Array(s.padding[0]||0).fill("")),o.push(...Array(s.padding[2]||0).fill(""));o.forEach((i,c)=>{if(!t[c])t.push([]);let a=t[c];for(let l=0;l<r;l++)if(a[l]===void 0)a.push("");a.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((r)=>r.width||Oe.stringWidth(r.text));let t=e.length,n=this.width,o=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),s=t?Math.floor(n/t):0;return o.map((r,i)=>{if(r===void 0)return Math.max(s,dd(e[i]));return r})}}function Fi(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function dd(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function fd(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function pd(e,t){e=e.trim();let n=Oe.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function hd(e,t){e=e.trim();let n=Oe.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Oe;function _i(e,t){return Oe=t,new Si({width:(e===null||e===void 0?void 0:e.width)||fd(),wrap:e===null||e===void 0?void 0:e.wrap})}function Do({onlyFirst:e=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",e?void 0:"g")}var gd=Do();function $t(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(gd,"")}var $i=161,Ai=1114109,Ti=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Oi=12288,Ii=65510,Pi=[12288,12288,65281,65376,65504,65510];var Ri=4352,Ni=262141,yo=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var is=(e,t)=>{let n=0,o=Math.floor(e.length/2)-1;while(n<=o){let s=Math.floor((n+o)/2),r=s*2;if(t<e[r])o=s-1;else if(t>e[r+1])n=s+1;else return!0}return!1};var Bi=19968,[md,Dd]=yd(yo);function yd(e){let t=e[0],n=e[1];for(let o=0;o<e.length;o+=2){let s=e[o],r=e[o+1];if(Bi>=s&&Bi<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var Mi=(e)=>{if(e<$i||e>Ai)return!1;return is(Ti,e)},vi=(e)=>{if(e<Oi||e>Ii)return!1;return is(Pi,e)};var Li=(e)=>{if(e>=md&&e<=Dd)return!0;if(e<Ri||e>Ni)return!1;return is(yo,e)};function wd(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function ji(e,{ambiguousAsWide:t=!1}={}){if(wd(e),vi(e)||Li(e)||t&&Mi(e))return 2;return 1}var Ki=Ei(Ui(),1),bd=new Intl.Segmenter,kd=/^\p{Default_Ignorable_Code_Point}$/u;function Ye(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=$t(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of bd.segment(e)){let c=i.codePointAt(0);if(c<=31||c>=127&&c<=159)continue;if(c>=8203&&c<=8207||c===65279)continue;if(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)continue;if(c>=55296&&c<=57343)continue;if(c>=65024&&c<=65039)continue;if(kd.test(i))continue;if(Ki.default().test(i)){s+=2;continue}s+=ji(c,r)}return s}var Ji=(e=0)=>(t)=>`\x1B[${t+e}m`,Hi=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,zi=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,ae={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},am=Object.keys(ae.modifier),Cd=Object.keys(ae.color),Ed=Object.keys(ae.bgColor),cm=[...Cd,...Ed];function xd(){let e=new Map;for(let[t,n]of Object.entries(ae)){for(let[o,s]of Object.entries(n))ae[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=ae[o],e.set(s[0],s[1]);Object.defineProperty(ae,t,{value:n,enumerable:!1})}return Object.defineProperty(ae,"codes",{value:e,enumerable:!1}),ae.color.close="\x1B[39m",ae.bgColor.close="\x1B[49m",ae.color.ansi=Ji(),ae.color.ansi256=Hi(),ae.color.ansi16m=zi(),ae.bgColor.ansi=Ji(10),ae.bgColor.ansi256=Hi(10),ae.bgColor.ansi16m=zi(10),Object.defineProperties(ae,{rgbToAnsi256:{value(t,n,o){if(t===n&&n===o){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[o]=n;if(o.length===3)o=[...o].map((r)=>r+r).join("");let s=Number.parseInt(o,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:(t)=>ae.rgbToAnsi256(...ae.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,o,s;if(t>=232)n=((t-232)*10+8)/255,o=n,s=n;else{t-=16;let c=t%36;n=Math.floor(t/36)/5,o=Math.floor(c/6)/5,s=c%6/5}let r=Math.max(n,o,s)*2;if(r===0)return 30;let i=30+(Math.round(s)<<2|Math.round(o)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,o)=>ae.ansi256ToAnsi(ae.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>ae.ansi256ToAnsi(ae.hexToAnsi256(t)),enumerable:!1}}),ae}var Fd=xd(),qi=Fd;var cs=new Set(["\x1B","›"]),Sd=39,bo="\x07",Yi="[",_d="]",Vi="m",as=`${_d}8;;`,Gi=(e)=>`${cs.values().next().value}${Yi}${e}${Vi}`,Xi=(e)=>`${cs.values().next().value}${as}${e}${bo}`,$d=(e)=>e.split(" ").map((t)=>Ye(t)),wo=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=Ye($t(e.at(-1)));for(let[c,a]of o.entries()){let l=Ye(a);if(i+l<=n)e[e.length-1]+=a;else e.push(a),i=0;if(cs.has(a))s=!0,r=o.slice(c+1,c+1+as.length).join("")===as;if(s){if(r){if(a===bo)s=!1,r=!1}else if(a===Vi)s=!1;continue}if(i+=l,i===n&&c<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},Ad=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(Ye(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Td=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=$d(e),c=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)c[c.length-1]=c.at(-1).trimStart();let h=Ye(c.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))c.push(""),h=0;if(h>0||n.trim===!1)c[c.length-1]+=" ",h++}if(n.hard&&i[d]>t){let m=t-h,p=1+Math.floor((i[d]-m-1)/t);if(Math.floor((i[d]-1)/t)<p)c.push("");wo(c,f,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){wo(c,f,t);continue}c.push("")}if(h+i[d]>t&&n.wordWrap===!1){wo(c,f,t);continue}c[c.length-1]+=f}if(n.trim!==!1)c=c.map((d)=>Ad(d));let a=c.join(`
8
- `),l=[...a],u=0;for(let[d,f]of l.entries()){if(o+=f,cs.has(f)){let{groups:m}=new RegExp(`(?:\\${Yi}(?<code>\\d+)m|\\${as}(?<uri>.*)${bo})`).exec(a.slice(u))||{groups:{}};if(m.code!==void 0){let p=Number.parseFloat(m.code);s=p===Sd?void 0:p}else if(m.uri!==void 0)r=m.uri.length===0?void 0:m.uri}let h=qi.codes.get(Number(s));if(l[d+1]===`
9
- `){if(r)o+=Xi("");if(s&&h)o+=Gi(h)}else if(f===`
10
- `){if(s&&h)o+=Gi(s);if(r)o+=Xi(r)}u+=f.length}return o};function ko(e,t,n){return String(e).normalize().replaceAll(`\r
7
+ `);if(s.border)o.unshift("."+"-".repeat(this.negatePadding(s)+2)+"."),o.push("'"+"-".repeat(this.negatePadding(s)+2)+"'");if(s.padding)o.unshift(...Array(s.padding[0]||0).fill("")),o.push(...Array(s.padding[2]||0).fill(""));o.forEach((i,c)=>{if(!t[c])t.push([]);let a=t[c];for(let l=0;l<r;l++)if(a[l]===void 0)a.push("");a.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((r)=>r.width||Oe.stringWidth(r.text));let t=e.length,n=this.width,o=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),s=t?Math.floor(n/t):0;return o.map((r,i)=>{if(r===void 0)return Math.max(s,Td(e[i]));return r})}}function Ri(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Td(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Id(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Od(e,t){e=e.trim();let n=Oe.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Pd(e,t){e=e.trim();let n=Oe.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Oe;function Bi(e,t){return Oe=t,new Ni({width:(e===null||e===void 0?void 0:e.width)||Id(),wrap:e===null||e===void 0?void 0:e.wrap})}function ko({onlyFirst:e=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",e?void 0:"g")}var Rd=ko();function At(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(Rd,"")}var Mi=161,vi=1114109,Li=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],ji=12288,Wi=65510,Ui=[12288,12288,65281,65376,65504,65510];var Ji=4352,Ki=262141,xo=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var cs=(e,t)=>{let n=0,o=Math.floor(e.length/2)-1;while(n<=o){let s=Math.floor((n+o)/2),r=s*2;if(t<e[r])o=s-1;else if(t>e[r+1])n=s+1;else return!0}return!1};var Hi=19968,[Nd,Bd]=Md(xo);function Md(e){let t=e[0],n=e[1];for(let o=0;o<e.length;o+=2){let s=e[o],r=e[o+1];if(Hi>=s&&Hi<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var zi=(e)=>{if(e<Mi||e>vi)return!1;return cs(Li,e)},qi=(e)=>{if(e<ji||e>Wi)return!1;return cs(Ui,e)};var Gi=(e)=>{if(e>=Nd&&e<=Bd)return!0;if(e<Ji||e>Ki)return!1;return cs(xo,e)};function vd(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Xi(e,{ambiguousAsWide:t=!1}={}){if(vd(e),qi(e)||Gi(e)||t&&zi(e))return 2;return 1}var Zi=Oi(Vi(),1),Ld=new Intl.Segmenter,jd=/^\p{Default_Ignorable_Code_Point}$/u;function Ye(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=At(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of Ld.segment(e)){let c=i.codePointAt(0);if(c<=31||c>=127&&c<=159)continue;if(c>=8203&&c<=8207||c===65279)continue;if(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)continue;if(c>=55296&&c<=57343)continue;if(c>=65024&&c<=65039)continue;if(jd.test(i))continue;if(Zi.default().test(i)){s+=2;continue}s+=Xi(c,r)}return s}var Qi=(e=0)=>(t)=>`\x1B[${t+e}m`,ea=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,ta=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,ae={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Tm=Object.keys(ae.modifier),Wd=Object.keys(ae.color),Ud=Object.keys(ae.bgColor),Im=[...Wd,...Ud];function Jd(){let e=new Map;for(let[t,n]of Object.entries(ae)){for(let[o,s]of Object.entries(n))ae[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=ae[o],e.set(s[0],s[1]);Object.defineProperty(ae,t,{value:n,enumerable:!1})}return Object.defineProperty(ae,"codes",{value:e,enumerable:!1}),ae.color.close="\x1B[39m",ae.bgColor.close="\x1B[49m",ae.color.ansi=Qi(),ae.color.ansi256=ea(),ae.color.ansi16m=ta(),ae.bgColor.ansi=Qi(10),ae.bgColor.ansi256=ea(10),ae.bgColor.ansi16m=ta(10),Object.defineProperties(ae,{rgbToAnsi256:{value(t,n,o){if(t===n&&n===o){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[o]=n;if(o.length===3)o=[...o].map((r)=>r+r).join("");let s=Number.parseInt(o,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:(t)=>ae.rgbToAnsi256(...ae.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,o,s;if(t>=232)n=((t-232)*10+8)/255,o=n,s=n;else{t-=16;let c=t%36;n=Math.floor(t/36)/5,o=Math.floor(c/6)/5,s=c%6/5}let r=Math.max(n,o,s)*2;if(r===0)return 30;let i=30+(Math.round(s)<<2|Math.round(o)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,o)=>ae.ansi256ToAnsi(ae.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>ae.ansi256ToAnsi(ae.hexToAnsi256(t)),enumerable:!1}}),ae}var Kd=Jd(),na=Kd;var us=new Set(["\x1B","›"]),Hd=39,Eo="\x07",ra="[",zd="]",ia="m",ls=`${zd}8;;`,sa=(e)=>`${us.values().next().value}${ra}${e}${ia}`,oa=(e)=>`${us.values().next().value}${ls}${e}${Eo}`,qd=(e)=>e.split(" ").map((t)=>Ye(t)),Co=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=Ye(At(e.at(-1)));for(let[c,a]of o.entries()){let l=Ye(a);if(i+l<=n)e[e.length-1]+=a;else e.push(a),i=0;if(us.has(a))s=!0,r=o.slice(c+1,c+1+ls.length).join("")===ls;if(s){if(r){if(a===Eo)s=!1,r=!1}else if(a===ia)s=!1;continue}if(i+=l,i===n&&c<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},Gd=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(Ye(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Xd=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=qd(e),c=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)c[c.length-1]=c.at(-1).trimStart();let h=Ye(c.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))c.push(""),h=0;if(h>0||n.trim===!1)c[c.length-1]+=" ",h++}if(n.hard&&i[d]>t){let m=t-h,p=1+Math.floor((i[d]-m-1)/t);if(Math.floor((i[d]-1)/t)<p)c.push("");Co(c,f,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){Co(c,f,t);continue}c.push("")}if(h+i[d]>t&&n.wordWrap===!1){Co(c,f,t);continue}c[c.length-1]+=f}if(n.trim!==!1)c=c.map((d)=>Gd(d));let a=c.join(`
8
+ `),l=[...a],u=0;for(let[d,f]of l.entries()){if(o+=f,us.has(f)){let{groups:m}=new RegExp(`(?:\\${ra}(?<code>\\d+)m|\\${ls}(?<uri>.*)${Eo})`).exec(a.slice(u))||{groups:{}};if(m.code!==void 0){let p=Number.parseFloat(m.code);s=p===Hd?void 0:p}else if(m.uri!==void 0)r=m.uri.length===0?void 0:m.uri}let h=na.codes.get(Number(s));if(l[d+1]===`
9
+ `){if(r)o+=oa("");if(s&&h)o+=sa(h)}else if(f===`
10
+ `){if(s&&h)o+=sa(s);if(r)o+=oa(r)}u+=f.length}return o};function So(e,t,n){return String(e).normalize().replaceAll(`\r
11
11
  `,`
12
12
  `).split(`
13
- `).map((o)=>Td(o,t,n)).join(`
14
- `)}function Co(e){return _i(e,{stringWidth:Ye,stripAnsi:$t,wrap:ko})}import{dirname as Zi,resolve as Qi}from"path";import{readdirSync as Od,statSync as Id}from"fs";function Eo(e,t){let n=Qi(".",e),o;if(!Id(n).isDirectory())n=Zi(n);while(!0){if(o=t(n,Od(n)),o)return Qi(n,o);if(n=Zi(o=n),o===n)break}}import{inspect as Yd}from"util";import{fileURLToPath as ma}from"url";import{format as Nd}from"util";import{normalize as Bd,resolve as Md}from"path";function At(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",o=!1,s=e.match(/^-+/);for(let r=s?s[0].length:0;r<e.length;r++){let i=e.charAt(r);if(o)o=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))o=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function ls(e,t){let n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){let r=n.charAt(s),i=e.charAt(s);if(r!==i&&s>0)o+=`${t}${n.charAt(s)}`;else o+=i}return o}function us(e){if(e===null||e===void 0)return!1;if(typeof e==="number")return!0;if(/^0x[0-9a-f]+$/i.test(e))return!0;if(/^0[^.]/.test(e))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function ea(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,o=null,s=null,r=[];for(let i=0;i<e.length;i++){if(n=o,o=e.charAt(i),o===" "&&!s){if(n!==" ")t++;continue}if(o===s)s=null;else if((o==="'"||o==='"')&&!s)s=o;if(!r[t])r[t]="";r[t]+=o}return r}var je;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(je||(je={}));var it;class Fo{constructor(e){it=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=ea(e),s=typeof e==="string",r=Pd(Object.assign(Object.create(null),n.alias)),i=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),c=Object.assign(Object.create(null),n.default),a=n.configObjects||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",f=Object.create(null),h=Object.create(null),m=n.__||it.format,p={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},D=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,C=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(y){let k=typeof y==="object"?y.key:y,P=Object.keys(y).map(function(x){return{boolean:"bools",string:"strings",number:"numbers"}[x]}).filter(Boolean).pop();if(P)p[P][k]=!0;p.arrays[k]=!0,p.keys.push(k)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(y){p.bools[y]=!0,p.keys.push(y)}),[].concat(n.string||[]).filter(Boolean).forEach(function(y){p.strings[y]=!0,p.keys.push(y)}),[].concat(n.number||[]).filter(Boolean).forEach(function(y){p.numbers[y]=!0,p.keys.push(y)}),[].concat(n.count||[]).filter(Boolean).forEach(function(y){p.counts[y]=!0,p.keys.push(y)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(y){p.normalize[y]=!0,p.keys.push(y)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([y,k])=>{if(typeof k==="number")p.nargs[y]=k,p.keys.push(y)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([y,k])=>{if(typeof k==="function")p.coercions[y]=k,p.keys.push(y)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(y){p.configs[y]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([y,k])=>{if(typeof k==="boolean"||typeof k==="function")p.configs[y]=k})}rt(n.key,r,n.default,p.arrays),Object.keys(c).forEach(function(y){(p.aliases[y]||[]).forEach(function(k){c[k]=c[y]})});let b=null;mo();let _=[],A=Object.assign(Object.create(null),{_:[]}),N={};for(let y=0;y<o.length;y++){let k=o[y],P=k.replace(/^-{3,}/,"---"),x,w,W,M,H,De;if(k!=="--"&&/^-/.test(k)&&se(k))j(k);else if(P.match(/^---+(=|$)/)){j(k);continue}else if(k.match(/^--.+=/)||!i["short-option-groups"]&&k.match(/^-.+=/)){if(M=k.match(/^--?([^=]+)=([\s\S]*)$/),M!==null&&Array.isArray(M)&&M.length>=3)if(R(M[1],p.arrays))y=J(y,M[1],o,M[2]);else if(R(M[1],p.nargs)!==!1)y=I(y,M[1],o,M[2]);else U(M[1],M[2],!0)}else if(k.match(C)&&i["boolean-negation"]){if(M=k.match(C),M!==null&&Array.isArray(M)&&M.length>=2)w=M[1],U(w,R(w,p.arrays)?[!1]:!1)}else if(k.match(/^--.+/)||!i["short-option-groups"]&&k.match(/^-[^-]+/)){if(M=k.match(/^--?(.+)/),M!==null&&Array.isArray(M)&&M.length>=2)if(w=M[1],R(w,p.arrays))y=J(y,w,o);else if(R(w,p.nargs)!==!1)y=I(y,w,o);else if(H=o[y+1],H!==void 0&&(!H.match(/^-/)||H.match(D))&&!R(w,p.bools)&&!R(w,p.counts))U(w,H),y++;else if(/^(true|false)$/.test(H))U(w,H),y++;else U(w,ee(w))}else if(k.match(/^-.\..+=/)){if(M=k.match(/^-([^=]+)=([\s\S]*)$/),M!==null&&Array.isArray(M)&&M.length>=3)U(M[1],M[2])}else if(k.match(/^-.\..+/)&&!k.match(D)){if(H=o[y+1],M=k.match(/^-(.\..+)/),M!==null&&Array.isArray(M)&&M.length>=2)if(w=M[1],H!==void 0&&!H.match(/^-/)&&!R(w,p.bools)&&!R(w,p.counts))U(w,H),y++;else U(w,ee(w))}else if(k.match(/^-[^-]+/)&&!k.match(D)){W=k.slice(1,-1).split(""),x=!1;for(let Ce=0;Ce<W.length;Ce++){if(H=k.slice(Ce+2),W[Ce+1]&&W[Ce+1]==="="){if(De=k.slice(Ce+3),w=W[Ce],R(w,p.arrays))y=J(y,w,o,De);else if(R(w,p.nargs)!==!1)y=I(y,w,o,De);else U(w,De);x=!0;break}if(H==="-"){U(W[Ce],H);continue}if(/[A-Za-z]/.test(W[Ce])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(H)&&R(H,p.bools)===!1){U(W[Ce],H),x=!0;break}if(W[Ce+1]&&W[Ce+1].match(/\W/)){U(W[Ce],H),x=!0;break}else U(W[Ce],ee(W[Ce]))}if(w=k.slice(-1)[0],!x&&w!=="-")if(R(w,p.arrays))y=J(y,w,o);else if(R(w,p.nargs)!==!1)y=I(y,w,o);else if(H=o[y+1],H!==void 0&&(!/^(-|--)[^-]/.test(H)||H.match(D))&&!R(w,p.bools)&&!R(w,p.counts))U(w,H),y++;else if(/^(true|false)$/.test(H))U(w,H),y++;else U(w,ee(w))}else if(k.match(/^-[0-9]$/)&&k.match(D)&&R(k.slice(1),p.bools))w=k.slice(1),U(w,ee(w));else if(k==="--"){_=o.slice(y+1);break}else if(i["halt-at-non-option"]){_=o.slice(y);break}else j(k)}if(Z(A,!0),Z(A,!1),T(A),B(),Me(A,p.aliases,c,!0),X(A),i["set-placeholder-key"])oe(A);if(Object.keys(p.counts).forEach(function(y){if(!ne(A,y.split(".")))U(y,0)}),u&&_.length)A[d]=[];if(_.forEach(function(y){A[d].push(y)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(A).filter((y)=>y!=="--"&&y.includes("-")).forEach((y)=>{delete A[y]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((y)=>r[y])).forEach((y)=>{if(i["camel-case-expansion"]&&y.includes("-"))delete A[y.split(".").map((k)=>At(k)).join(".")];delete A[y]});function j(y){let k=E("_",y);if(typeof k==="string"||typeof k==="number")A._.push(k)}function I(y,k,P,x){let w,W=R(k,p.nargs);if(W=typeof W!=="number"||isNaN(W)?1:W,W===0){if(!ge(x))b=Error(m("Argument unexpected for: %s",k));return U(k,ee(k)),y}let M=ge(x)?0:1;if(i["nargs-eats-options"]){if(P.length-(y+1)+M<W)b=Error(m("Not enough arguments following: %s",k));M=W}else{for(w=y+1;w<P.length;w++)if(!P[w].match(/^-[^0-9]/)||P[w].match(D)||se(P[w]))M++;else break;if(M<W)b=Error(m("Not enough arguments following: %s",k))}let H=Math.min(M,W);if(!ge(x)&&H>0)U(k,x),H--;for(w=y+1;w<H+y+1;w++)U(k,P[w]);return y+H}function J(y,k,P,x){let w=[],W=x||P[y+1],M=R(k,p.nargs);if(R(k,p.bools)&&!/^(true|false)$/.test(W))w.push(!0);else if(ge(W)||ge(x)&&/^-/.test(W)&&!D.test(W)&&!se(W)){if(c[k]!==void 0){let H=c[k];w=Array.isArray(H)?H:[H]}}else{if(!ge(x))w.push(F(k,x,!0));for(let H=y+1;H<P.length;H++){if(!i["greedy-arrays"]&&w.length>0||M&&typeof M==="number"&&w.length>=M)break;if(W=P[H],/^-/.test(W)&&!D.test(W)&&!se(W))break;y=H,w.push(F(k,W,s))}}if(typeof M==="number"&&(M&&w.length<M||isNaN(M)&&w.length===0))b=Error(m("Not enough arguments following: %s",k));return U(k,w),y}function U(y,k,P=s){if(/-/.test(y)&&i["camel-case-expansion"]){let W=y.split(".").map(function(M){return At(M)}).join(".");Q(y,W)}let x=F(y,k,P),w=y.split(".");if(ve(A,w,x),p.aliases[y])p.aliases[y].forEach(function(W){let M=W.split(".");ve(A,M,x)});if(w.length>1&&i["dot-notation"])(p.aliases[w[0]]||[]).forEach(function(W){let M=W.split("."),H=[].concat(w);if(H.shift(),M=M.concat(H),!(p.aliases[y]||[]).includes(M.join(".")))ve(A,M,x)});if(R(y,p.normalize)&&!R(y,p.arrays))[y].concat(p.aliases[y]||[]).forEach(function(M){Object.defineProperty(N,M,{enumerable:!0,get(){return k},set(H){k=typeof H==="string"?it.normalize(H):H}})})}function Q(y,k){if(!(p.aliases[y]&&p.aliases[y].length))p.aliases[y]=[k],f[k]=!0;if(!(p.aliases[k]&&p.aliases[k].length))Q(k,y)}function F(y,k,P){if(P)k=Rd(k);if(R(y,p.bools)||R(y,p.counts)){if(typeof k==="string")k=k==="true"}let x=Array.isArray(k)?k.map(function(w){return E(y,w)}):E(y,k);if(R(y,p.counts)&&(ge(x)||typeof x==="boolean"))x=xo();if(R(y,p.normalize)&&R(y,p.arrays))if(Array.isArray(k))x=k.map((w)=>it.normalize(w));else x=it.normalize(k);return x}function E(y,k){if(!i["parse-positional-numbers"]&&y==="_")return k;if(!R(y,p.strings)&&!R(y,p.bools)&&!Array.isArray(k)){if(us(k)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${k}`)))||!ge(k)&&R(y,p.numbers))k=Number(k)}return k}function T(y){let k=Object.create(null);Me(k,p.aliases,c),Object.keys(p.configs).forEach(function(P){let x=y[P]||k[P];if(x)try{let w=null,W=it.resolve(it.cwd(),x),M=p.configs[P];if(typeof M==="function"){try{w=M(W)}catch(H){w=H}if(w instanceof Error){b=w;return}}else w=it.require(W);S(w)}catch(w){if(w.name==="PermissionDenied")b=w;else if(y[P])b=Error(m("Invalid JSON config file: %s",x))}})}function S(y,k){Object.keys(y).forEach(function(P){let x=y[P],w=k?k+"."+P:P;if(typeof x==="object"&&x!==null&&!Array.isArray(x)&&i["dot-notation"])S(x,w);else if(!ne(A,w.split("."))||R(w,p.arrays)&&i["combine-arrays"])U(w,x)})}function B(){if(typeof a<"u")a.forEach(function(y){S(y)})}function Z(y,k){if(typeof l>"u")return;let P=typeof l==="string"?l:"",x=it.env();Object.keys(x).forEach(function(w){if(P===""||w.lastIndexOf(P,0)===0){let W=w.split("__").map(function(M,H){if(H===0)M=M.substring(P.length);return At(M)});if((k&&p.configs[W.join(".")]||!k)&&!ne(y,W))U(W.join("."),x[w])}})}function X(y){let k,P=new Set;Object.keys(y).forEach(function(x){if(!P.has(x)){if(k=R(x,p.coercions),typeof k==="function")try{let w=E(x,k(y[x]));[].concat(p.aliases[x]||[],x).forEach((W)=>{P.add(W),y[W]=w})}catch(w){b=w}}})}function oe(y){return p.keys.forEach((k)=>{if(~k.indexOf("."))return;if(typeof y[k]>"u")y[k]=void 0}),y}function Me(y,k,P,x=!1){Object.keys(P).forEach(function(w){if(!ne(y,w.split("."))){if(ve(y,w.split("."),P[w]),x)h[w]=!0;(k[w]||[]).forEach(function(W){if(ne(y,W.split(".")))return;ve(y,W.split("."),P[w])})}})}function ne(y,k){let P=y;if(!i["dot-notation"])k=[k.join(".")];k.slice(0,-1).forEach(function(w){P=P[w]||{}});let x=k[k.length-1];if(typeof P!=="object")return!1;else return x in P}function ve(y,k,P){let x=y;if(!i["dot-notation"])k=[k.join(".")];k.slice(0,-1).forEach(function(De){if(De=ta(De),typeof x==="object"&&x[De]===void 0)x[De]={};if(typeof x[De]!=="object"||Array.isArray(x[De])){if(Array.isArray(x[De]))x[De].push({});else x[De]=[x[De],{}];x=x[De][x[De].length-1]}else x=x[De]});let w=ta(k[k.length-1]),W=R(k.join("."),p.arrays),M=Array.isArray(P),H=i["duplicate-arguments-array"];if(!H&&R(w,p.nargs)){if(H=!0,!ge(x[w])&&p.nargs[w]===1||Array.isArray(x[w])&&x[w].length===p.nargs[w])x[w]=void 0}if(P===xo())x[w]=xo(x[w]);else if(Array.isArray(x[w]))if(H&&W&&M)x[w]=i["flatten-duplicate-arrays"]?x[w].concat(P):(Array.isArray(x[w][0])?x[w]:[x[w]]).concat([P]);else if(!H&&Boolean(W)===Boolean(M))x[w]=P;else x[w]=x[w].concat([P]);else if(x[w]===void 0&&W)x[w]=M?P:[P];else if(H&&!(x[w]===void 0||R(w,p.counts)||R(w,p.bools)))x[w]=[x[w],P];else x[w]=P}function rt(...y){y.forEach(function(k){Object.keys(k||{}).forEach(function(P){if(p.aliases[P])return;p.aliases[P]=[].concat(r[P]||[]),p.aliases[P].concat(P).forEach(function(x){if(/-/.test(x)&&i["camel-case-expansion"]){let w=At(x);if(w!==P&&p.aliases[P].indexOf(w)===-1)p.aliases[P].push(w),f[w]=!0}}),p.aliases[P].concat(P).forEach(function(x){if(x.length>1&&/[A-Z]/.test(x)&&i["camel-case-expansion"]){let w=ls(x,"-");if(w!==P&&p.aliases[P].indexOf(w)===-1)p.aliases[P].push(w),f[w]=!0}}),p.aliases[P].forEach(function(x){p.aliases[x]=[P].concat(p.aliases[P].filter(function(w){return x!==w}))})})})}function R(y,k){let P=[].concat(p.aliases[y]||[],y),x=Object.keys(k),w=P.find((W)=>x.includes(W));return w?k[w]:!1}function le(y){let k=Object.keys(p);return[].concat(k.map((x)=>p[x])).some(function(x){return Array.isArray(x)?x.includes(y):x[y]})}function Le(y,...k){return[].concat(...k).some(function(x){let w=y.match(x);return w&&le(w[1])})}function z(y){if(y.match(D)||!y.match(/^-[^-]+/))return!1;let k=!0,P,x=y.slice(1).split("");for(let w=0;w<x.length;w++){if(P=y.slice(w+2),!le(x[w])){k=!1;break}if(x[w+1]&&x[w+1]==="="||P==="-"||/[A-Za-z]/.test(x[w])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(P)||x[w+1]&&x[w+1].match(/\W/))break}return k}function se(y){return i["unknown-options-as-args"]&&he(y)}function he(y){if(y=y.replace(/^-{3,}/,"--"),y.match(D))return!1;if(z(y))return!1;return!Le(y,/^-+([^=]+?)=[\s\S]*$/,C,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function ee(y){if(!R(y,p.bools)&&!R(y,p.counts)&&`${y}`in c)return c[y];else return we(ue(y))}function we(y){return{[je.BOOLEAN]:!0,[je.STRING]:"",[je.NUMBER]:void 0,[je.ARRAY]:[]}[y]}function ue(y){let k=je.BOOLEAN;if(R(y,p.strings))k=je.STRING;else if(R(y,p.numbers))k=je.NUMBER;else if(R(y,p.bools))k=je.BOOLEAN;else if(R(y,p.arrays))k=je.ARRAY;return k}function ge(y){return y===void 0}function mo(){Object.keys(p.counts).find((y)=>{if(R(y,p.arrays))return b=Error(m("Invalid configuration: %s, opts.count excludes opts.array.",y)),!0;else if(R(y,p.nargs))return b=Error(m("Invalid configuration: %s, opts.count excludes opts.narg.",y)),!0;return!1})}return{aliases:Object.assign({},p.aliases),argv:Object.assign(N,A),configuration:i,defaulted:Object.assign({},h),error:b,newAliases:Object.assign({},f)}}}function Pd(e){let t=[],n=Object.create(null),o=!0;Object.keys(e).forEach(function(s){t.push([].concat(e[s],s))});while(o){o=!1;for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++)if(t[s].filter(function(c){return t[r].indexOf(c)!==-1}).length){t[s]=t[s].concat(t[r]),t.splice(r,1),o=!0;break}}return t.forEach(function(s){s=s.filter(function(i,c,a){return a.indexOf(i)===c});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function xo(e){return e!==void 0?e+1:1}function ta(e){if(e==="__proto__")return"___proto___";return e}function Rd(e){return typeof e==="string"&&(e[0]==="'"||e[0]==='"')&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}import{readFileSync as vd}from"fs";import{createRequire as na}from"node:module";var So,_o,$o,sa=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,oa=(_o=(So=process===null||process===void 0?void 0:process.versions)===null||So===void 0?void 0:So.node)!==null&&_o!==void 0?_o:($o=process===null||process===void 0?void 0:process.version)===null||$o===void 0?void 0:$o.slice(1);if(oa){if(Number(oa.match(/^([^.]+)/)[1])<sa)throw Error(`yargs parser supports a minimum Node.js version of ${sa}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Ld=process?process.env:{},ra=na?na(import.meta.url):void 0,ia=new Fo({cwd:process.cwd,env:()=>Ld,format:Nd,normalize:Bd,resolve:Md,require:(e)=>{if(typeof ra<"u")return ra(e);else if(e.match(/\.json$/))return JSON.parse(vd(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),kn=function(t,n){return ia.parse(t.slice(),n).argv};kn.detailed=function(e,t){return ia.parse(e.slice(),t)};kn.camelCase=At;kn.decamelize=ls;kn.looksLikeNumber=us;var Ao=kn;import{basename as Vd,dirname as Zd,extname as Qd,relative as ef,resolve as ga,join as tf}from"path";function aa(){if(jd())return 0;return 1}function jd(){return Wd()&&!process.defaultApp}function Wd(){return!!process.versions.electron}function To(e){return e.slice(aa()+1)}function ca(){return process.argv[aa()]}import{readFileSync as Ud,statSync as Kd,writeFile as Jd}from"fs";import{format as Hd}from"util";import{resolve as zd}from"path";var la={fs:{readFileSync:Ud,writeFile:Jd},format:Hd,resolve:zd,exists:(e)=>{try{return Kd(e).isFile()}catch(t){return!1}}};var Ve;class ua{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles=typeof e.updateFiles==="boolean"?e.updateFiles:!0,this.locale=e.locale||"en",this.fallbackToLanguage=typeof e.fallbackToLanguage==="boolean"?e.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};if(typeof e[e.length-1]==="function")n=e.pop();if(n=n||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n});else n();return Ve.format.apply(Ve.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift(),s=function(){};if(typeof e[e.length-1]==="function")s=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=o===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][o===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s});else s();let i=[r];if(~r.indexOf("%d"))i.push(o);return Ve.format.apply(Ve.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(o,s){let r=t[s+1];if(n+=o,typeof r<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:o,cb:s}=t,r=this._resolveLocaleFile(n,o),i=JSON.stringify(this.cache[o],null,2);Ve.fs.writeFile(r,i,"utf-8",function(c){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(c)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(Ve.fs.readFileSync)e=JSON.parse(Ve.fs.readFileSync(t,"utf-8"))}catch(n){if(n instanceof SyntaxError)n.message="syntax error in "+t;if(n.code==="ENOENT")e={};else throw n}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=Ve.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=Ve.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return Ve.exists(e)}}function da(e,t){Ve=t;let n=new ua(e);return{__:n.__.bind(n),__n:n.__n.bind(n),setLocale:n.setLocale.bind(n),getLocale:n.getLocale.bind(n),updateLocale:n.updateLocale.bind(n),locale:n.locale}}var qd=(e)=>da(e,la),fa=qd;var Da=Ei(ha(),1);import{createRequire as nf}from"node:module";import{readFileSync as sf,readdirSync as of}from"node:fs";var Oo=ma(import.meta.url),rf=Oo.substring(0,Oo.lastIndexOf("node_modules")),af=nf(import.meta.url),Io={assert:{notStrictEqual:Gd,strictEqual:Xd},cliui:Co,findUp:Eo,getEnv:(e)=>process.env[e],inspect:Yd,getProcessArgvBin:ca,mainFilename:rf||process.cwd(),Parser:Ao,path:{basename:Vd,dirname:Zd,extname:Qd,relative:ef,resolve:ga,join:tf},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:(e)=>{process.exit(e)},nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:sf,readdirSync:of,require:af,getCallerFile:()=>{let e=Da.default(3);return e.match(/^file:\/\//)?ma(e):e},stringWidth:Ye,y18n:fa({directory:ga(Oo,"../../../locales"),updateFiles:!1})};function Ee(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function Po(e,t){t.assert.strictEqual(typeof e,"string")}function en(e){return Object.keys(e)}function re(e){return!!e&&!!e.then&&typeof e.then==="function"}class de extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,de)}}function ft(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),o=/\.*[\][<>]/g,s=n.shift();if(!s)throw Error(`No command found in: ${e}`);let r={cmd:s.replace(o,""),demanded:[],optional:[]};return n.forEach((i,c)=>{let a=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&c===n.length-1)a=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:a});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:a})}),r}var cf=["first","second","third","fourth","fifth","sixth"];function v(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[ft(`cmd ${e}`),t,n]}try{let s=0,[r,i,c]=o(),a=[].slice.call(i);while(a.length&&a[a.length-1]===void 0)a.pop();let l=c||a.length;if(l<r.demanded.length)throw new de(`Not enough arguments provided. Expected ${r.demanded.length} but received ${a.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new de(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let f=a.shift(),h=ya(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)wa(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(a.length===0)return;let f=a.shift(),h=ya(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)wa(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function ya(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function wa(e,t,n){throw new de(`Invalid ${cf[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class Ro{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(v("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let s=0;s<e.length;s++){if(typeof e[s]!=="function")throw Error("middleware must be a function");let r=e[s];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let s=e;s.applyBeforeValidation=t,s.global=n,s.mutates=o,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((o)=>{let s=[...n[t]||[],t];if(!o.option)return!0;else return!s.includes(o.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function ba(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function Tt(e,t,n,o){return n.reduce((s,r)=>{if(r.applyBeforeValidation!==o)return s;if(r.mutates){if(r.applied)return s;r.applied=!0}if(re(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,c])=>Object.assign(i,c));else{let i=r(s,t);return re(i)?i.then((c)=>Object.assign(s,c)):Object.assign(s,i)}},e)}function Ot(e,t,n=(o)=>{throw o}){try{let o=lf(e)?e():e;return re(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function lf(e){return typeof e==="function"}var tn=/(^\*)|(^\$0)/;class Ca{constructor(e,t,n,o){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=o,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,o){o=o||{},this.requireCache.add(n);let s=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(s,{recursive:o.recurse?!0:!1});if(!Array.isArray(o.extensions))o.extensions=["js"];let i=typeof o.visit==="function"?o.visit:(c)=>c;for(let c of r){let a=c.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(a);else u=o.exclude.test(a);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(a);else u=o.include.test(a);if(!u)continue}let l=!1;for(let u of o.extensions)if(a.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,a),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,u,a)){if(this.requireCache.has(u))continue;else this.requireCache.add(u);if(!f.command)f.command=this.shim.path.basename(u,this.shim.path.extname(u));this.addHandler(f)}}}}addHandler(e,t,n,o,s,r){let i=[],c=ba(s);if(o=o||(()=>{}),Array.isArray(e))if(uf(e))[e,...i]=e;else for(let a of e)this.addHandler(a);else if(ff(e)){let a=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(a===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)a=[].concat(a).concat(e.aliases);this.addHandler(a,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(ka(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let a=ft(e);i=i.map((d)=>ft(d).cmd);let l=!1,u=[a.cmd].concat(i).filter((d)=>{if(tn.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)a.cmd=u[0],i=u.slice(1),e=e.replace(tn,a.cmd);if(i.forEach((d)=>{this.aliasMap[d]=a.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[a.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:c,deprecated:r,demanded:a.demanded,optional:a.optional},l)this.defaultCommand=this.handlers[a.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,o,s,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,c=t.getInternalMethods().getContext(),a=c.commands.slice(),l=!e;if(e)c.commands.push(e),c.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,a,o,s,r);return re(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,c,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,c,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,c){let a=t.builder,l=n;if(ds(a)){n.getInternalMethods().getUsageInstance().freeze();let u=a(n.getInternalMethods().reset(o),c);if(re(u))return u.then((d)=>(l=xa(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(df(a))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,a[u])});return this.parseAndUpdateUsage(e,t,l,s,r,i)}parseAndUpdateUsage(e,t,n,o,s,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(o,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,s,r);return re(i)?i.then((c)=>({aliases:n.parsed.aliases,innerArgv:c})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=tn.test(t.original)?t.original.replace(tn,"").trim():t.original,o=e.filter((s)=>!tn.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,c){if(!r.getInternalMethods().getHasOutput()){let a=r.getInternalMethods().runValidation(s,c,r.parsed.error,e);n=Ot(n,(l)=>(a(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let a=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,a,!1,!1),n=Tt(n,r,i,!1),n=Ot(n,(l)=>{let u=t.handler(l);return re(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(re(n)&&!r.getInternalMethods().hasParseCallback())n.catch((l)=>{try{r.getInternalMethods().getUsageInstance().fail(null,l)}catch(u){}})}if(!e)o.commands.pop(),o.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,o,s,r,i){let c={};if(s)return n;if(!i.getInternalMethods().getHasOutput())c=this.populatePositionals(t,n,o,i);let a=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=Tt(n,i,a,!0);return re(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,a,c)):this.handleValidationAndGetResult(e,t,l,o,r,i,a,c)}populatePositionals(e,t,n,o){t._=t._.slice(n.commands.length);let s=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(s.length,t._.length);while(s.length){let c=s.shift();this.populatePositional(c,t,i)}while(r.length){let c=r.shift();this.populatePositional(c,t,i)}return t._=n.commands.concat(t._.map((c)=>""+c)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),o),i}populatePositional(e,t,n){let o=e.cmd[0];if(e.variadic)n[o]=t._.splice(0).map(String);else if(t._.length)n[o]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=ft(e);return n.demanded.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r,t.demand[s]=!0}),n.optional.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r}),t}postProcessPositionals(e,t,n,o){let s=Object.assign({},o.getOptions());s.default=Object.assign(n.default,s.default);for(let a of Object.keys(n.alias))s.alias[a]=(s.alias[a]||[]).concat(n.alias[a]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((a)=>{t[a].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[a]=!0;r.push(`--${a}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),c=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(c.error)o.getInternalMethods().getUsageInstance().fail(c.error.message,c.error);else{let a=Object.keys(t);Object.keys(t).forEach((l)=>{a.push(...c.aliases[l])}),Object.keys(c.argv).forEach((l)=>{if(a.includes(l)){if(!t[l])t[l]=c.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(c.argv,l)&&(Array.isArray(e[l])||Array.isArray(c.argv[l])))e[l]=[].concat(e[l],c.argv[l]);else e[l]=c.argv[l]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((o)=>Object.prototype.hasOwnProperty.call(o,t))||n.some((o)=>Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=tn.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");e.getInternalMethods().getUsageInstance().usage(n,this.defaultCommand.description)}let t=this.defaultCommand.builder;if(ds(t))return t(e,!0);else if(!ka(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let o of[e,t,n]){if(typeof o==="string"||o===!1)return o;Ee(o,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Ee(e,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=e}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function Ea(e,t,n,o){return new Ca(e,t,n,o)}function ka(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function uf(e){return e.every((t)=>typeof t==="string")}function ds(e){return typeof e==="function"}function df(e){return typeof e==="object"}function ff(e){return typeof e==="object"&&!Array.isArray(e)}function pt(e={},t=()=>!0){let n={};return en(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function ht(e){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((t)=>{let n=t;if(n._handle&&n.isTTY&&typeof n._handle.setBlocking==="function")n._handle.setBlocking(e)})}function pf(e){return typeof e==="boolean"}function Sa(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(E){s.push(E)};let r=null,i=null,c=!0;o.showHelpOnFail=function(E=!0,T){let[S,B]=typeof E==="string"?[!0,E]:[E,T];if(e.getInternalMethods().isGlobalContext())i=B;return r=B,c=S,o};let a=!1;o.fail=function(E,T){let S=e.getInternalMethods().getLoggerInstance();if(s.length)for(let B=s.length-1;B>=0;--B){let Z=s[B];if(pf(Z)){if(T)throw T;else if(E)throw Error(E)}else Z(E,T,o)}else{if(e.getExitProcess())ht(!0);if(!a){if(a=!0,c)e.showHelp("error"),S.error();if(E||T)S.error(E||T);let B=r||i;if(B){if(E||T)S.error("");S.error(B)}}if(T=T||new de(E),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,T);else throw T}};let l=[],u=!1;o.usage=(F,E)=>{if(F===null)return u=!0,l=[],o;return u=!1,l.push([F,E||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(F,E)=>{d.push([F,E||""])};let f=[];o.command=function(E,T,S,B,Z=!1){if(S)f=f.map((X)=>(X[2]=!1,X));f.push([E,T||"",S,B,Z])},o.getCommands=()=>f;let h={};o.describe=function(E,T){if(Array.isArray(E))E.forEach((S)=>{o.describe(S,T)});else if(typeof E==="object")Object.keys(E).forEach((S)=>{o.describe(S,E[S])});else h[E]=T},o.getDescriptions=()=>h;let m=[];o.epilog=(F)=>{m.push(F)};let p=!1,D;o.wrap=(F)=>{p=!0,D=F},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!p)D=J(),p=!0;return D};let C="__yargsString__:";o.deferY18nLookup=(F)=>C+F,o.help=function(){if(A)return A;_();let E=e.customScriptName?e.$0:t.path.basename(e.$0),T=e.getDemandedOptions(),S=e.getDemandedCommands(),B=e.getDeprecatedOptions(),Z=e.getGroups(),X=e.getOptions(),oe=[];oe=oe.concat(Object.keys(h)),oe=oe.concat(Object.keys(T)),oe=oe.concat(Object.keys(S)),oe=oe.concat(Object.keys(X.default)),oe=oe.filter(j),oe=Object.keys(oe.reduce((z,se)=>{if(se!=="_")z[se]=!0;return z},{}));let Me=o.getWrap(),ne=t.cliui({width:Me,wrap:!!Me});if(!u){if(l.length)l.forEach((z)=>{if(ne.div({text:`${z[0].replace(/\$0/g,E)}`}),z[1])ne.div({text:`${z[1]}`,padding:[1,0,0,0]})}),ne.div();else if(f.length){let z=null;if(S._)z=`${E} <${n("command")}>
15
- `;else z=`${E} [${n("command")}]
16
- `;ne.div(`${z}`)}}if(f.length>1||f.length===1&&!f[0][2]){ne.div(n("Commands:"));let z=e.getInternalMethods().getContext(),se=z.commands.length?`${z.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((ee,we)=>ee[0].localeCompare(we[0]));let he=E?`${E} `:"";f.forEach((ee)=>{let we=`${he}${se}${ee[0].replace(/^\$0 ?/,"")}`;ne.span({text:we,padding:[0,2,0,2],width:b(f,Me,`${E}${se}`)+4},{text:ee[1]});let ue=[];if(ee[2])ue.push(`[${n("default")}]`);if(ee[3]&&ee[3].length)ue.push(`[${n("aliases:")} ${ee[3].join(", ")}]`);if(ee[4])if(typeof ee[4]==="string")ue.push(`[${n("deprecated: %s",ee[4])}]`);else ue.push(`[${n("deprecated")}]`);if(ue.length)ne.div({text:ue.join(" "),padding:[0,0,0,2],align:"right"});else ne.div()}),ne.div()}let ve=(Object.keys(X.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);oe=oe.filter((z)=>!e.parsed.newAliases[z]&&ve.every((se)=>(X.alias[se]||[]).indexOf(z)===-1));let rt=n("Options:");if(!Z[rt])Z[rt]=[];N(oe,X.alias,Z,rt);let R=(z)=>/^--/.test(fs(z)),le=Object.keys(Z).filter((z)=>Z[z].length>0).map((z)=>{let se=Z[z].filter(j).map((he)=>{if(ve.includes(he))return he;for(let ee=0,we;(we=ve[ee])!==void 0;ee++)if((X.alias[we]||[]).includes(he))return we;return he});return{groupName:z,normalizedKeys:se}}).filter(({normalizedKeys:z})=>z.length>0).map(({groupName:z,normalizedKeys:se})=>{let he=se.reduce((ee,we)=>(ee[we]=[we].concat(X.alias[we]||[]).map((ue)=>{if(z===o.getPositionalGroupName())return ue;else return(/^[0-9]$/.test(ue)?X.boolean.includes(we)?"-":"--":ue.length>1?"--":"-")+ue}).sort((ue,ge)=>R(ue)===R(ge)?0:R(ue)?1:-1).join(", "),ee),{});return{groupName:z,normalizedKeys:se,switches:he}});if(le.filter(({groupName:z})=>z!==o.getPositionalGroupName()).some(({normalizedKeys:z,switches:se})=>!z.every((he)=>R(se[he]))))le.filter(({groupName:z})=>z!==o.getPositionalGroupName()).forEach(({normalizedKeys:z,switches:se})=>{z.forEach((he)=>{if(R(se[he]))se[he]=hf(se[he],4)})});if(le.forEach(({groupName:z,normalizedKeys:se,switches:he})=>{ne.div(z),se.forEach((ee)=>{let we=he[ee],ue=h[ee]||"",ge=null;if(ue.includes(C))ue=n(ue.substring(C.length));if(X.boolean.includes(ee))ge=`[${n("boolean")}]`;if(X.count.includes(ee))ge=`[${n("count")}]`;if(X.string.includes(ee))ge=`[${n("string")}]`;if(X.normalize.includes(ee))ge=`[${n("string")}]`;if(X.array.includes(ee))ge=`[${n("array")}]`;if(X.number.includes(ee))ge=`[${n("number")}]`;let mo=(P)=>typeof P==="string"?`[${n("deprecated: %s",P)}]`:`[${n("deprecated")}]`,y=[ee in B?mo(B[ee]):null,ge,ee in T?`[${n("required")}]`:null,X.choices&&X.choices[ee]?`[${n("choices:")} ${o.stringifiedValues(X.choices[ee])}]`:null,I(X.default[ee],X.defaultDescription[ee])].filter(Boolean).join(" ");ne.span({text:fs(we),padding:[0,2,0,2+Fa(we)],width:b(he,Me)+4},ue);let k=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(y&&!k)ne.div({text:y,padding:[0,0,0,2],align:"right"});else ne.div()}),ne.div()}),d.length)ne.div(n("Examples:")),d.forEach((z)=>{z[0]=z[0].replace(/\$0/g,E)}),d.forEach((z)=>{if(z[1]==="")ne.div({text:z[0],padding:[0,2,0,2]});else ne.div({text:z[0],padding:[0,2,0,2],width:b(d,Me)+4},{text:z[1]})}),ne.div();if(m.length>0){let z=m.map((se)=>se.replace(/\$0/g,E)).join(`
13
+ `).map((o)=>Xd(o,t,n)).join(`
14
+ `)}function Fo(e){return Bi(e,{stringWidth:Ye,stripAnsi:At,wrap:So})}import{dirname as aa,resolve as ca}from"path";import{readdirSync as Yd,statSync as Vd}from"fs";function _o(e,t){let n=ca(".",e),o;if(!Vd(n).isDirectory())n=aa(n);while(!0){if(o=t(n,Yd(n)),o)return ca(n,o);if(n=aa(o=n),o===n)break}}import{inspect as mf}from"util";import{fileURLToPath as Sa}from"url";import{format as ef}from"util";import{normalize as tf,resolve as nf}from"path";function Tt(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",o=!1,s=e.match(/^-+/);for(let r=s?s[0].length:0;r<e.length;r++){let i=e.charAt(r);if(o)o=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))o=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function ds(e,t){let n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){let r=n.charAt(s),i=e.charAt(s);if(r!==i&&s>0)o+=`${t}${n.charAt(s)}`;else o+=i}return o}function fs(e){if(e===null||e===void 0)return!1;if(typeof e==="number")return!0;if(/^0x[0-9a-f]+$/i.test(e))return!0;if(/^0[^.]/.test(e))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function la(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,o=null,s=null,r=[];for(let i=0;i<e.length;i++){if(n=o,o=e.charAt(i),o===" "&&!s){if(n!==" ")t++;continue}if(o===s)s=null;else if((o==="'"||o==='"')&&!s)s=o;if(!r[t])r[t]="";r[t]+=o}return r}var je;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(je||(je={}));var at;class Ao{constructor(e){at=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=la(e),s=typeof e==="string",r=Zd(Object.assign(Object.create(null),n.alias)),i=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),c=Object.assign(Object.create(null),n.default),a=n.configObjects||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",f=Object.create(null),h=Object.create(null),m=n.__||at.format,p={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},D=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,x=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(y){let k=typeof y==="object"?y.key:y,P=Object.keys(y).map(function(E){return{boolean:"bools",string:"strings",number:"numbers"}[E]}).filter(Boolean).pop();if(P)p[P][k]=!0;p.arrays[k]=!0,p.keys.push(k)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(y){p.bools[y]=!0,p.keys.push(y)}),[].concat(n.string||[]).filter(Boolean).forEach(function(y){p.strings[y]=!0,p.keys.push(y)}),[].concat(n.number||[]).filter(Boolean).forEach(function(y){p.numbers[y]=!0,p.keys.push(y)}),[].concat(n.count||[]).filter(Boolean).forEach(function(y){p.counts[y]=!0,p.keys.push(y)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(y){p.normalize[y]=!0,p.keys.push(y)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([y,k])=>{if(typeof k==="number")p.nargs[y]=k,p.keys.push(y)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([y,k])=>{if(typeof k==="function")p.coercions[y]=k,p.keys.push(y)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(y){p.configs[y]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([y,k])=>{if(typeof k==="boolean"||typeof k==="function")p.configs[y]=k})}it(n.key,r,n.default,p.arrays),Object.keys(c).forEach(function(y){(p.aliases[y]||[]).forEach(function(k){c[k]=c[y]})});let b=null;bo();let _=[],A=Object.assign(Object.create(null),{_:[]}),N={};for(let y=0;y<o.length;y++){let k=o[y],P=k.replace(/^-{3,}/,"---"),E,w,W,M,H,be;if(k!=="--"&&/^-/.test(k)&&se(k))j(k);else if(P.match(/^---+(=|$)/)){j(k);continue}else if(k.match(/^--.+=/)||!i["short-option-groups"]&&k.match(/^-.+=/)){if(M=k.match(/^--?([^=]+)=([\s\S]*)$/),M!==null&&Array.isArray(M)&&M.length>=3)if(R(M[1],p.arrays))y=K(y,M[1],o,M[2]);else if(R(M[1],p.nargs)!==!1)y=O(y,M[1],o,M[2]);else U(M[1],M[2],!0)}else if(k.match(x)&&i["boolean-negation"]){if(M=k.match(x),M!==null&&Array.isArray(M)&&M.length>=2)w=M[1],U(w,R(w,p.arrays)?[!1]:!1)}else if(k.match(/^--.+/)||!i["short-option-groups"]&&k.match(/^-[^-]+/)){if(M=k.match(/^--?(.+)/),M!==null&&Array.isArray(M)&&M.length>=2)if(w=M[1],R(w,p.arrays))y=K(y,w,o);else if(R(w,p.nargs)!==!1)y=O(y,w,o);else if(H=o[y+1],H!==void 0&&(!H.match(/^-/)||H.match(D))&&!R(w,p.bools)&&!R(w,p.counts))U(w,H),y++;else if(/^(true|false)$/.test(H))U(w,H),y++;else U(w,ee(w))}else if(k.match(/^-.\..+=/)){if(M=k.match(/^-([^=]+)=([\s\S]*)$/),M!==null&&Array.isArray(M)&&M.length>=3)U(M[1],M[2])}else if(k.match(/^-.\..+/)&&!k.match(D)){if(H=o[y+1],M=k.match(/^-(.\..+)/),M!==null&&Array.isArray(M)&&M.length>=2)if(w=M[1],H!==void 0&&!H.match(/^-/)&&!R(w,p.bools)&&!R(w,p.counts))U(w,H),y++;else U(w,ee(w))}else if(k.match(/^-[^-]+/)&&!k.match(D)){W=k.slice(1,-1).split(""),E=!1;for(let Fe=0;Fe<W.length;Fe++){if(H=k.slice(Fe+2),W[Fe+1]&&W[Fe+1]==="="){if(be=k.slice(Fe+3),w=W[Fe],R(w,p.arrays))y=K(y,w,o,be);else if(R(w,p.nargs)!==!1)y=O(y,w,o,be);else U(w,be);E=!0;break}if(H==="-"){U(W[Fe],H);continue}if(/[A-Za-z]/.test(W[Fe])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(H)&&R(H,p.bools)===!1){U(W[Fe],H),E=!0;break}if(W[Fe+1]&&W[Fe+1].match(/\W/)){U(W[Fe],H),E=!0;break}else U(W[Fe],ee(W[Fe]))}if(w=k.slice(-1)[0],!E&&w!=="-")if(R(w,p.arrays))y=K(y,w,o);else if(R(w,p.nargs)!==!1)y=O(y,w,o);else if(H=o[y+1],H!==void 0&&(!/^(-|--)[^-]/.test(H)||H.match(D))&&!R(w,p.bools)&&!R(w,p.counts))U(w,H),y++;else if(/^(true|false)$/.test(H))U(w,H),y++;else U(w,ee(w))}else if(k.match(/^-[0-9]$/)&&k.match(D)&&R(k.slice(1),p.bools))w=k.slice(1),U(w,ee(w));else if(k==="--"){_=o.slice(y+1);break}else if(i["halt-at-non-option"]){_=o.slice(y);break}else j(k)}if(Z(A,!0),Z(A,!1),T(A),B(),Me(A,p.aliases,c,!0),X(A),i["set-placeholder-key"])oe(A);if(Object.keys(p.counts).forEach(function(y){if(!ne(A,y.split(".")))U(y,0)}),u&&_.length)A[d]=[];if(_.forEach(function(y){A[d].push(y)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(A).filter((y)=>y!=="--"&&y.includes("-")).forEach((y)=>{delete A[y]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((y)=>r[y])).forEach((y)=>{if(i["camel-case-expansion"]&&y.includes("-"))delete A[y.split(".").map((k)=>Tt(k)).join(".")];delete A[y]});function j(y){let k=C("_",y);if(typeof k==="string"||typeof k==="number")A._.push(k)}function O(y,k,P,E){let w,W=R(k,p.nargs);if(W=typeof W!=="number"||isNaN(W)?1:W,W===0){if(!me(E))b=Error(m("Argument unexpected for: %s",k));return U(k,ee(k)),y}let M=me(E)?0:1;if(i["nargs-eats-options"]){if(P.length-(y+1)+M<W)b=Error(m("Not enough arguments following: %s",k));M=W}else{for(w=y+1;w<P.length;w++)if(!P[w].match(/^-[^0-9]/)||P[w].match(D)||se(P[w]))M++;else break;if(M<W)b=Error(m("Not enough arguments following: %s",k))}let H=Math.min(M,W);if(!me(E)&&H>0)U(k,E),H--;for(w=y+1;w<H+y+1;w++)U(k,P[w]);return y+H}function K(y,k,P,E){let w=[],W=E||P[y+1],M=R(k,p.nargs);if(R(k,p.bools)&&!/^(true|false)$/.test(W))w.push(!0);else if(me(W)||me(E)&&/^-/.test(W)&&!D.test(W)&&!se(W)){if(c[k]!==void 0){let H=c[k];w=Array.isArray(H)?H:[H]}}else{if(!me(E))w.push(S(k,E,!0));for(let H=y+1;H<P.length;H++){if(!i["greedy-arrays"]&&w.length>0||M&&typeof M==="number"&&w.length>=M)break;if(W=P[H],/^-/.test(W)&&!D.test(W)&&!se(W))break;y=H,w.push(S(k,W,s))}}if(typeof M==="number"&&(M&&w.length<M||isNaN(M)&&w.length===0))b=Error(m("Not enough arguments following: %s",k));return U(k,w),y}function U(y,k,P=s){if(/-/.test(y)&&i["camel-case-expansion"]){let W=y.split(".").map(function(M){return Tt(M)}).join(".");Q(y,W)}let E=S(y,k,P),w=y.split(".");if(ve(A,w,E),p.aliases[y])p.aliases[y].forEach(function(W){let M=W.split(".");ve(A,M,E)});if(w.length>1&&i["dot-notation"])(p.aliases[w[0]]||[]).forEach(function(W){let M=W.split("."),H=[].concat(w);if(H.shift(),M=M.concat(H),!(p.aliases[y]||[]).includes(M.join(".")))ve(A,M,E)});if(R(y,p.normalize)&&!R(y,p.arrays))[y].concat(p.aliases[y]||[]).forEach(function(M){Object.defineProperty(N,M,{enumerable:!0,get(){return k},set(H){k=typeof H==="string"?at.normalize(H):H}})})}function Q(y,k){if(!(p.aliases[y]&&p.aliases[y].length))p.aliases[y]=[k],f[k]=!0;if(!(p.aliases[k]&&p.aliases[k].length))Q(k,y)}function S(y,k,P){if(P)k=Qd(k);if(R(y,p.bools)||R(y,p.counts)){if(typeof k==="string")k=k==="true"}let E=Array.isArray(k)?k.map(function(w){return C(y,w)}):C(y,k);if(R(y,p.counts)&&(me(E)||typeof E==="boolean"))E=$o();if(R(y,p.normalize)&&R(y,p.arrays))if(Array.isArray(k))E=k.map((w)=>at.normalize(w));else E=at.normalize(k);return E}function C(y,k){if(!i["parse-positional-numbers"]&&y==="_")return k;if(!R(y,p.strings)&&!R(y,p.bools)&&!Array.isArray(k)){if(fs(k)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${k}`)))||!me(k)&&R(y,p.numbers))k=Number(k)}return k}function T(y){let k=Object.create(null);Me(k,p.aliases,c),Object.keys(p.configs).forEach(function(P){let E=y[P]||k[P];if(E)try{let w=null,W=at.resolve(at.cwd(),E),M=p.configs[P];if(typeof M==="function"){try{w=M(W)}catch(H){w=H}if(w instanceof Error){b=w;return}}else w=at.require(W);F(w)}catch(w){if(w.name==="PermissionDenied")b=w;else if(y[P])b=Error(m("Invalid JSON config file: %s",E))}})}function F(y,k){Object.keys(y).forEach(function(P){let E=y[P],w=k?k+"."+P:P;if(typeof E==="object"&&E!==null&&!Array.isArray(E)&&i["dot-notation"])F(E,w);else if(!ne(A,w.split("."))||R(w,p.arrays)&&i["combine-arrays"])U(w,E)})}function B(){if(typeof a<"u")a.forEach(function(y){F(y)})}function Z(y,k){if(typeof l>"u")return;let P=typeof l==="string"?l:"",E=at.env();Object.keys(E).forEach(function(w){if(P===""||w.lastIndexOf(P,0)===0){let W=w.split("__").map(function(M,H){if(H===0)M=M.substring(P.length);return Tt(M)});if((k&&p.configs[W.join(".")]||!k)&&!ne(y,W))U(W.join("."),E[w])}})}function X(y){let k,P=new Set;Object.keys(y).forEach(function(E){if(!P.has(E)){if(k=R(E,p.coercions),typeof k==="function")try{let w=C(E,k(y[E]));[].concat(p.aliases[E]||[],E).forEach((W)=>{P.add(W),y[W]=w})}catch(w){b=w}}})}function oe(y){return p.keys.forEach((k)=>{if(~k.indexOf("."))return;if(typeof y[k]>"u")y[k]=void 0}),y}function Me(y,k,P,E=!1){Object.keys(P).forEach(function(w){if(!ne(y,w.split("."))){if(ve(y,w.split("."),P[w]),E)h[w]=!0;(k[w]||[]).forEach(function(W){if(ne(y,W.split(".")))return;ve(y,W.split("."),P[w])})}})}function ne(y,k){let P=y;if(!i["dot-notation"])k=[k.join(".")];k.slice(0,-1).forEach(function(w){P=P[w]||{}});let E=k[k.length-1];if(typeof P!=="object")return!1;else return E in P}function ve(y,k,P){let E=y;if(!i["dot-notation"])k=[k.join(".")];k.slice(0,-1).forEach(function(be){if(be=ua(be),typeof E==="object"&&E[be]===void 0)E[be]={};if(typeof E[be]!=="object"||Array.isArray(E[be])){if(Array.isArray(E[be]))E[be].push({});else E[be]=[E[be],{}];E=E[be][E[be].length-1]}else E=E[be]});let w=ua(k[k.length-1]),W=R(k.join("."),p.arrays),M=Array.isArray(P),H=i["duplicate-arguments-array"];if(!H&&R(w,p.nargs)){if(H=!0,!me(E[w])&&p.nargs[w]===1||Array.isArray(E[w])&&E[w].length===p.nargs[w])E[w]=void 0}if(P===$o())E[w]=$o(E[w]);else if(Array.isArray(E[w]))if(H&&W&&M)E[w]=i["flatten-duplicate-arrays"]?E[w].concat(P):(Array.isArray(E[w][0])?E[w]:[E[w]]).concat([P]);else if(!H&&Boolean(W)===Boolean(M))E[w]=P;else E[w]=E[w].concat([P]);else if(E[w]===void 0&&W)E[w]=M?P:[P];else if(H&&!(E[w]===void 0||R(w,p.counts)||R(w,p.bools)))E[w]=[E[w],P];else E[w]=P}function it(...y){y.forEach(function(k){Object.keys(k||{}).forEach(function(P){if(p.aliases[P])return;p.aliases[P]=[].concat(r[P]||[]),p.aliases[P].concat(P).forEach(function(E){if(/-/.test(E)&&i["camel-case-expansion"]){let w=Tt(E);if(w!==P&&p.aliases[P].indexOf(w)===-1)p.aliases[P].push(w),f[w]=!0}}),p.aliases[P].concat(P).forEach(function(E){if(E.length>1&&/[A-Z]/.test(E)&&i["camel-case-expansion"]){let w=ds(E,"-");if(w!==P&&p.aliases[P].indexOf(w)===-1)p.aliases[P].push(w),f[w]=!0}}),p.aliases[P].forEach(function(E){p.aliases[E]=[P].concat(p.aliases[P].filter(function(w){return E!==w}))})})})}function R(y,k){let P=[].concat(p.aliases[y]||[],y),E=Object.keys(k),w=P.find((W)=>E.includes(W));return w?k[w]:!1}function ue(y){let k=Object.keys(p);return[].concat(k.map((E)=>p[E])).some(function(E){return Array.isArray(E)?E.includes(y):E[y]})}function Le(y,...k){return[].concat(...k).some(function(E){let w=y.match(E);return w&&ue(w[1])})}function z(y){if(y.match(D)||!y.match(/^-[^-]+/))return!1;let k=!0,P,E=y.slice(1).split("");for(let w=0;w<E.length;w++){if(P=y.slice(w+2),!ue(E[w])){k=!1;break}if(E[w+1]&&E[w+1]==="="||P==="-"||/[A-Za-z]/.test(E[w])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(P)||E[w+1]&&E[w+1].match(/\W/))break}return k}function se(y){return i["unknown-options-as-args"]&&ge(y)}function ge(y){if(y=y.replace(/^-{3,}/,"--"),y.match(D))return!1;if(z(y))return!1;return!Le(y,/^-+([^=]+?)=[\s\S]*$/,x,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function ee(y){if(!R(y,p.bools)&&!R(y,p.counts)&&`${y}`in c)return c[y];else return Ce(de(y))}function Ce(y){return{[je.BOOLEAN]:!0,[je.STRING]:"",[je.NUMBER]:void 0,[je.ARRAY]:[]}[y]}function de(y){let k=je.BOOLEAN;if(R(y,p.strings))k=je.STRING;else if(R(y,p.numbers))k=je.NUMBER;else if(R(y,p.bools))k=je.BOOLEAN;else if(R(y,p.arrays))k=je.ARRAY;return k}function me(y){return y===void 0}function bo(){Object.keys(p.counts).find((y)=>{if(R(y,p.arrays))return b=Error(m("Invalid configuration: %s, opts.count excludes opts.array.",y)),!0;else if(R(y,p.nargs))return b=Error(m("Invalid configuration: %s, opts.count excludes opts.narg.",y)),!0;return!1})}return{aliases:Object.assign({},p.aliases),argv:Object.assign(N,A),configuration:i,defaulted:Object.assign({},h),error:b,newAliases:Object.assign({},f)}}}function Zd(e){let t=[],n=Object.create(null),o=!0;Object.keys(e).forEach(function(s){t.push([].concat(e[s],s))});while(o){o=!1;for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++)if(t[s].filter(function(c){return t[r].indexOf(c)!==-1}).length){t[s]=t[s].concat(t[r]),t.splice(r,1),o=!0;break}}return t.forEach(function(s){s=s.filter(function(i,c,a){return a.indexOf(i)===c});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function $o(e){return e!==void 0?e+1:1}function ua(e){if(e==="__proto__")return"___proto___";return e}function Qd(e){return typeof e==="string"&&(e[0]==="'"||e[0]==='"')&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}import{readFileSync as sf}from"fs";import{createRequire as da}from"node:module";var To,Io,Oo,fa=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,pa=(Io=(To=process===null||process===void 0?void 0:process.versions)===null||To===void 0?void 0:To.node)!==null&&Io!==void 0?Io:(Oo=process===null||process===void 0?void 0:process.version)===null||Oo===void 0?void 0:Oo.slice(1);if(pa){if(Number(pa.match(/^([^.]+)/)[1])<fa)throw Error(`yargs parser supports a minimum Node.js version of ${fa}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var of=process?process.env:{},ha=da?da(import.meta.url):void 0,ga=new Ao({cwd:process.cwd,env:()=>of,format:ef,normalize:tf,resolve:nf,require:(e)=>{if(typeof ha<"u")return ha(e);else if(e.match(/\.json$/))return JSON.parse(sf(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),kn=function(t,n){return ga.parse(t.slice(),n).argv};kn.detailed=function(e,t){return ga.parse(e.slice(),t)};kn.camelCase=Tt;kn.decamelize=ds;kn.looksLikeNumber=fs;var Po=kn;import{basename as Df,dirname as yf,extname as wf,relative as bf,resolve as Ea,join as kf}from"path";function ma(){if(rf())return 0;return 1}function rf(){return af()&&!process.defaultApp}function af(){return!!process.versions.electron}function Ro(e){return e.slice(ma()+1)}function Da(){return process.argv[ma()]}import{readFileSync as cf,statSync as lf,writeFile as uf}from"fs";import{format as df}from"util";import{resolve as ff}from"path";var ya={fs:{readFileSync:cf,writeFile:uf},format:df,resolve:ff,exists:(e)=>{try{return lf(e).isFile()}catch(t){return!1}}};var Ve;class wa{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles=typeof e.updateFiles==="boolean"?e.updateFiles:!0,this.locale=e.locale||"en",this.fallbackToLanguage=typeof e.fallbackToLanguage==="boolean"?e.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};if(typeof e[e.length-1]==="function")n=e.pop();if(n=n||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n});else n();return Ve.format.apply(Ve.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift(),s=function(){};if(typeof e[e.length-1]==="function")s=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=o===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][o===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s});else s();let i=[r];if(~r.indexOf("%d"))i.push(o);return Ve.format.apply(Ve.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(o,s){let r=t[s+1];if(n+=o,typeof r<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:o,cb:s}=t,r=this._resolveLocaleFile(n,o),i=JSON.stringify(this.cache[o],null,2);Ve.fs.writeFile(r,i,"utf-8",function(c){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(c)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(Ve.fs.readFileSync)e=JSON.parse(Ve.fs.readFileSync(t,"utf-8"))}catch(n){if(n instanceof SyntaxError)n.message="syntax error in "+t;if(n.code==="ENOENT")e={};else throw n}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=Ve.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=Ve.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return Ve.exists(e)}}function ba(e,t){Ve=t;let n=new wa(e);return{__:n.__.bind(n),__n:n.__n.bind(n),setLocale:n.setLocale.bind(n),getLocale:n.getLocale.bind(n),updateLocale:n.updateLocale.bind(n),locale:n.locale}}var pf=(e)=>ba(e,ya),ka=pf;var Fa=Oi(Ca(),1);import{createRequire as xf}from"node:module";import{readFileSync as Cf,readdirSync as Ef}from"node:fs";var No=Sa(import.meta.url),Sf=No.substring(0,No.lastIndexOf("node_modules")),Ff=xf(import.meta.url),Bo={assert:{notStrictEqual:hf,strictEqual:gf},cliui:Fo,findUp:_o,getEnv:(e)=>process.env[e],inspect:mf,getProcessArgvBin:Da,mainFilename:Sf||process.cwd(),Parser:Po,path:{basename:Df,dirname:yf,extname:wf,relative:bf,resolve:Ea,join:kf},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:(e)=>{process.exit(e)},nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:Cf,readdirSync:Ef,require:Ff,getCallerFile:()=>{let e=Fa.default(3);return e.match(/^file:\/\//)?Sa(e):e},stringWidth:Ye,y18n:ka({directory:Ea(No,"../../../locales"),updateFiles:!1})};function _e(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function Mo(e,t){t.assert.strictEqual(typeof e,"string")}function tn(e){return Object.keys(e)}function re(e){return!!e&&!!e.then&&typeof e.then==="function"}class fe extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,fe)}}function ht(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),o=/\.*[\][<>]/g,s=n.shift();if(!s)throw Error(`No command found in: ${e}`);let r={cmd:s.replace(o,""),demanded:[],optional:[]};return n.forEach((i,c)=>{let a=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&c===n.length-1)a=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:a});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:a})}),r}var _f=["first","second","third","fourth","fifth","sixth"];function v(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[ht(`cmd ${e}`),t,n]}try{let s=0,[r,i,c]=o(),a=[].slice.call(i);while(a.length&&a[a.length-1]===void 0)a.pop();let l=c||a.length;if(l<r.demanded.length)throw new fe(`Not enough arguments provided. Expected ${r.demanded.length} but received ${a.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new fe(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let f=a.shift(),h=_a(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)$a(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(a.length===0)return;let f=a.shift(),h=_a(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)$a(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function _a(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function $a(e,t,n){throw new fe(`Invalid ${_f[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class vo{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(v("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let s=0;s<e.length;s++){if(typeof e[s]!=="function")throw Error("middleware must be a function");let r=e[s];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let s=e;s.applyBeforeValidation=t,s.global=n,s.mutates=o,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((o)=>{let s=[...n[t]||[],t];if(!o.option)return!0;else return!s.includes(o.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function Aa(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function It(e,t,n,o){return n.reduce((s,r)=>{if(r.applyBeforeValidation!==o)return s;if(r.mutates){if(r.applied)return s;r.applied=!0}if(re(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,c])=>Object.assign(i,c));else{let i=r(s,t);return re(i)?i.then((c)=>Object.assign(s,c)):Object.assign(s,i)}},e)}function Ot(e,t,n=(o)=>{throw o}){try{let o=$f(e)?e():e;return re(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function $f(e){return typeof e==="function"}var nn=/(^\*)|(^\$0)/;class Ia{constructor(e,t,n,o){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=o,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,o){o=o||{},this.requireCache.add(n);let s=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(s,{recursive:o.recurse?!0:!1});if(!Array.isArray(o.extensions))o.extensions=["js"];let i=typeof o.visit==="function"?o.visit:(c)=>c;for(let c of r){let a=c.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(a);else u=o.exclude.test(a);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(a);else u=o.include.test(a);if(!u)continue}let l=!1;for(let u of o.extensions)if(a.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,a),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,u,a)){if(this.requireCache.has(u))continue;else this.requireCache.add(u);if(!f.command)f.command=this.shim.path.basename(u,this.shim.path.extname(u));this.addHandler(f)}}}}addHandler(e,t,n,o,s,r){let i=[],c=Aa(s);if(o=o||(()=>{}),Array.isArray(e))if(Af(e))[e,...i]=e;else for(let a of e)this.addHandler(a);else if(If(e)){let a=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(a===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)a=[].concat(a).concat(e.aliases);this.addHandler(a,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(Ta(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let a=ht(e);i=i.map((d)=>ht(d).cmd);let l=!1,u=[a.cmd].concat(i).filter((d)=>{if(nn.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)a.cmd=u[0],i=u.slice(1),e=e.replace(nn,a.cmd);if(i.forEach((d)=>{this.aliasMap[d]=a.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[a.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:c,deprecated:r,demanded:a.demanded,optional:a.optional},l)this.defaultCommand=this.handlers[a.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,o,s,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,c=t.getInternalMethods().getContext(),a=c.commands.slice(),l=!e;if(e)c.commands.push(e),c.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,a,o,s,r);return re(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,c,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,c,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,c){let a=t.builder,l=n;if(ps(a)){n.getInternalMethods().getUsageInstance().freeze();let u=a(n.getInternalMethods().reset(o),c);if(re(u))return u.then((d)=>(l=Pa(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(Tf(a))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,a[u])});return this.parseAndUpdateUsage(e,t,l,s,r,i)}parseAndUpdateUsage(e,t,n,o,s,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(o,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,s,r);return re(i)?i.then((c)=>({aliases:n.parsed.aliases,innerArgv:c})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=nn.test(t.original)?t.original.replace(nn,"").trim():t.original,o=e.filter((s)=>!nn.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,c){if(!r.getInternalMethods().getHasOutput()){let a=r.getInternalMethods().runValidation(s,c,r.parsed.error,e);n=Ot(n,(l)=>(a(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let a=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,a,!1,!1),n=It(n,r,i,!1),n=Ot(n,(l)=>{let u=t.handler(l);return re(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(re(n)&&!r.getInternalMethods().hasParseCallback())n.catch((l)=>{try{r.getInternalMethods().getUsageInstance().fail(null,l)}catch(u){}})}if(!e)o.commands.pop(),o.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,o,s,r,i){let c={};if(s)return n;if(!i.getInternalMethods().getHasOutput())c=this.populatePositionals(t,n,o,i);let a=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=It(n,i,a,!0);return re(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,a,c)):this.handleValidationAndGetResult(e,t,l,o,r,i,a,c)}populatePositionals(e,t,n,o){t._=t._.slice(n.commands.length);let s=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(s.length,t._.length);while(s.length){let c=s.shift();this.populatePositional(c,t,i)}while(r.length){let c=r.shift();this.populatePositional(c,t,i)}return t._=n.commands.concat(t._.map((c)=>""+c)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),o),i}populatePositional(e,t,n){let o=e.cmd[0];if(e.variadic)n[o]=t._.splice(0).map(String);else if(t._.length)n[o]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=ht(e);return n.demanded.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r,t.demand[s]=!0}),n.optional.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r}),t}postProcessPositionals(e,t,n,o){let s=Object.assign({},o.getOptions());s.default=Object.assign(n.default,s.default);for(let a of Object.keys(n.alias))s.alias[a]=(s.alias[a]||[]).concat(n.alias[a]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((a)=>{t[a].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[a]=!0;r.push(`--${a}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),c=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(c.error)o.getInternalMethods().getUsageInstance().fail(c.error.message,c.error);else{let a=Object.keys(t);Object.keys(t).forEach((l)=>{a.push(...c.aliases[l])}),Object.keys(c.argv).forEach((l)=>{if(a.includes(l)){if(!t[l])t[l]=c.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(c.argv,l)&&(Array.isArray(e[l])||Array.isArray(c.argv[l])))e[l]=[].concat(e[l],c.argv[l]);else e[l]=c.argv[l]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((o)=>Object.prototype.hasOwnProperty.call(o,t))||n.some((o)=>Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=nn.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");e.getInternalMethods().getUsageInstance().usage(n,this.defaultCommand.description)}let t=this.defaultCommand.builder;if(ps(t))return t(e,!0);else if(!Ta(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let o of[e,t,n]){if(typeof o==="string"||o===!1)return o;_e(o,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();_e(e,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=e}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function Oa(e,t,n,o){return new Ia(e,t,n,o)}function Ta(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Af(e){return e.every((t)=>typeof t==="string")}function ps(e){return typeof e==="function"}function Tf(e){return typeof e==="object"}function If(e){return typeof e==="object"&&!Array.isArray(e)}function gt(e={},t=()=>!0){let n={};return tn(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function mt(e){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((t)=>{let n=t;if(n._handle&&n.isTTY&&typeof n._handle.setBlocking==="function")n._handle.setBlocking(e)})}function Of(e){return typeof e==="boolean"}function Na(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(C){s.push(C)};let r=null,i=null,c=!0;o.showHelpOnFail=function(C=!0,T){let[F,B]=typeof C==="string"?[!0,C]:[C,T];if(e.getInternalMethods().isGlobalContext())i=B;return r=B,c=F,o};let a=!1;o.fail=function(C,T){let F=e.getInternalMethods().getLoggerInstance();if(s.length)for(let B=s.length-1;B>=0;--B){let Z=s[B];if(Of(Z)){if(T)throw T;else if(C)throw Error(C)}else Z(C,T,o)}else{if(e.getExitProcess())mt(!0);if(!a){if(a=!0,c)e.showHelp("error"),F.error();if(C||T)F.error(C||T);let B=r||i;if(B){if(C||T)F.error("");F.error(B)}}if(T=T||new fe(C),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,T);else throw T}};let l=[],u=!1;o.usage=(S,C)=>{if(S===null)return u=!0,l=[],o;return u=!1,l.push([S,C||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(S,C)=>{d.push([S,C||""])};let f=[];o.command=function(C,T,F,B,Z=!1){if(F)f=f.map((X)=>(X[2]=!1,X));f.push([C,T||"",F,B,Z])},o.getCommands=()=>f;let h={};o.describe=function(C,T){if(Array.isArray(C))C.forEach((F)=>{o.describe(F,T)});else if(typeof C==="object")Object.keys(C).forEach((F)=>{o.describe(F,C[F])});else h[C]=T},o.getDescriptions=()=>h;let m=[];o.epilog=(S)=>{m.push(S)};let p=!1,D;o.wrap=(S)=>{p=!0,D=S},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!p)D=K(),p=!0;return D};let x="__yargsString__:";o.deferY18nLookup=(S)=>x+S,o.help=function(){if(A)return A;_();let C=e.customScriptName?e.$0:t.path.basename(e.$0),T=e.getDemandedOptions(),F=e.getDemandedCommands(),B=e.getDeprecatedOptions(),Z=e.getGroups(),X=e.getOptions(),oe=[];oe=oe.concat(Object.keys(h)),oe=oe.concat(Object.keys(T)),oe=oe.concat(Object.keys(F)),oe=oe.concat(Object.keys(X.default)),oe=oe.filter(j),oe=Object.keys(oe.reduce((z,se)=>{if(se!=="_")z[se]=!0;return z},{}));let Me=o.getWrap(),ne=t.cliui({width:Me,wrap:!!Me});if(!u){if(l.length)l.forEach((z)=>{if(ne.div({text:`${z[0].replace(/\$0/g,C)}`}),z[1])ne.div({text:`${z[1]}`,padding:[1,0,0,0]})}),ne.div();else if(f.length){let z=null;if(F._)z=`${C} <${n("command")}>
15
+ `;else z=`${C} [${n("command")}]
16
+ `;ne.div(`${z}`)}}if(f.length>1||f.length===1&&!f[0][2]){ne.div(n("Commands:"));let z=e.getInternalMethods().getContext(),se=z.commands.length?`${z.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((ee,Ce)=>ee[0].localeCompare(Ce[0]));let ge=C?`${C} `:"";f.forEach((ee)=>{let Ce=`${ge}${se}${ee[0].replace(/^\$0 ?/,"")}`;ne.span({text:Ce,padding:[0,2,0,2],width:b(f,Me,`${C}${se}`)+4},{text:ee[1]});let de=[];if(ee[2])de.push(`[${n("default")}]`);if(ee[3]&&ee[3].length)de.push(`[${n("aliases:")} ${ee[3].join(", ")}]`);if(ee[4])if(typeof ee[4]==="string")de.push(`[${n("deprecated: %s",ee[4])}]`);else de.push(`[${n("deprecated")}]`);if(de.length)ne.div({text:de.join(" "),padding:[0,0,0,2],align:"right"});else ne.div()}),ne.div()}let ve=(Object.keys(X.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);oe=oe.filter((z)=>!e.parsed.newAliases[z]&&ve.every((se)=>(X.alias[se]||[]).indexOf(z)===-1));let it=n("Options:");if(!Z[it])Z[it]=[];N(oe,X.alias,Z,it);let R=(z)=>/^--/.test(hs(z)),ue=Object.keys(Z).filter((z)=>Z[z].length>0).map((z)=>{let se=Z[z].filter(j).map((ge)=>{if(ve.includes(ge))return ge;for(let ee=0,Ce;(Ce=ve[ee])!==void 0;ee++)if((X.alias[Ce]||[]).includes(ge))return Ce;return ge});return{groupName:z,normalizedKeys:se}}).filter(({normalizedKeys:z})=>z.length>0).map(({groupName:z,normalizedKeys:se})=>{let ge=se.reduce((ee,Ce)=>(ee[Ce]=[Ce].concat(X.alias[Ce]||[]).map((de)=>{if(z===o.getPositionalGroupName())return de;else return(/^[0-9]$/.test(de)?X.boolean.includes(Ce)?"-":"--":de.length>1?"--":"-")+de}).sort((de,me)=>R(de)===R(me)?0:R(de)?1:-1).join(", "),ee),{});return{groupName:z,normalizedKeys:se,switches:ge}});if(ue.filter(({groupName:z})=>z!==o.getPositionalGroupName()).some(({normalizedKeys:z,switches:se})=>!z.every((ge)=>R(se[ge]))))ue.filter(({groupName:z})=>z!==o.getPositionalGroupName()).forEach(({normalizedKeys:z,switches:se})=>{z.forEach((ge)=>{if(R(se[ge]))se[ge]=Pf(se[ge],4)})});if(ue.forEach(({groupName:z,normalizedKeys:se,switches:ge})=>{ne.div(z),se.forEach((ee)=>{let Ce=ge[ee],de=h[ee]||"",me=null;if(de.includes(x))de=n(de.substring(x.length));if(X.boolean.includes(ee))me=`[${n("boolean")}]`;if(X.count.includes(ee))me=`[${n("count")}]`;if(X.string.includes(ee))me=`[${n("string")}]`;if(X.normalize.includes(ee))me=`[${n("string")}]`;if(X.array.includes(ee))me=`[${n("array")}]`;if(X.number.includes(ee))me=`[${n("number")}]`;let bo=(P)=>typeof P==="string"?`[${n("deprecated: %s",P)}]`:`[${n("deprecated")}]`,y=[ee in B?bo(B[ee]):null,me,ee in T?`[${n("required")}]`:null,X.choices&&X.choices[ee]?`[${n("choices:")} ${o.stringifiedValues(X.choices[ee])}]`:null,O(X.default[ee],X.defaultDescription[ee])].filter(Boolean).join(" ");ne.span({text:hs(Ce),padding:[0,2,0,2+Ra(Ce)],width:b(ge,Me)+4},de);let k=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(y&&!k)ne.div({text:y,padding:[0,0,0,2],align:"right"});else ne.div()}),ne.div()}),d.length)ne.div(n("Examples:")),d.forEach((z)=>{z[0]=z[0].replace(/\$0/g,C)}),d.forEach((z)=>{if(z[1]==="")ne.div({text:z[0],padding:[0,2,0,2]});else ne.div({text:z[0],padding:[0,2,0,2],width:b(d,Me)+4},{text:z[1]})}),ne.div();if(m.length>0){let z=m.map((se)=>se.replace(/\$0/g,C)).join(`
17
17
  `);ne.div(`${z}
18
- `)}return ne.toString().replace(/\s*$/,"")};function b(F,E,T){let S=0;if(!Array.isArray(F))F=Object.values(F).map((B)=>[B]);if(F.forEach((B)=>{S=Math.max(t.stringWidth(T?`${T} ${fs(B[0])}`:fs(B[0]))+Fa(B[0]),S)}),E)S=Math.min(S,parseInt((E*0.5).toString(),10));return S}function _(){let F=e.getDemandedOptions(),E=e.getOptions();(Object.keys(E.alias)||[]).forEach((T)=>{E.alias[T].forEach((S)=>{if(h[S])o.describe(T,h[S]);if(S in F)e.demandOption(T,F[S]);if(E.boolean.includes(S))e.boolean(T);if(E.count.includes(S))e.count(T);if(E.string.includes(S))e.string(T);if(E.normalize.includes(S))e.normalize(T);if(E.array.includes(S))e.array(T);if(E.number.includes(S))e.number(T)})})}let A;o.cacheHelpMessage=function(){A=this.help()},o.clearCachedHelpMessage=function(){A=void 0},o.hasCachedHelpMessage=function(){return!!A};function N(F,E,T,S){let B=[],Z=null;return Object.keys(T).forEach((X)=>{B=B.concat(T[X])}),F.forEach((X)=>{if(Z=[X].concat(E[X]),!Z.some((oe)=>B.indexOf(oe)!==-1))T[S].push(X)}),B}function j(F){return e.getOptions().hiddenOptions.indexOf(F)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}o.showHelp=(F)=>{let E=e.getInternalMethods().getLoggerInstance();if(!F)F="error";(typeof F==="function"?F:E[F])(o.help())},o.functionDescription=(F)=>["(",F.name?t.Parser.decamelize(F.name,"-"):n("generated-value"),")"].join(""),o.stringifiedValues=function(E,T){let S="",B=T||", ",Z=[].concat(E);if(!E||!Z.length)return S;return Z.forEach((X)=>{if(S.length)S+=B;S+=JSON.stringify(X)}),S};function I(F,E){let T=`[${n("default:")} `;if(F===void 0&&!E)return null;if(E)T+=E;else switch(typeof F){case"string":T+=`"${F}"`;break;case"object":T+=JSON.stringify(F);break;default:T+=F}return`${T}]`}function J(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let U=null;o.version=(F)=>{U=F},o.showVersion=(F)=>{let E=e.getInternalMethods().getLoggerInstance();if(!F)F="error";(typeof F==="function"?F:E[F])(U)},o.reset=function(E){return r=null,a=!1,l=[],u=!1,m=[],d=[],f=[],h=pt(h,(T)=>!E[T]),o};let Q=[];return o.freeze=function(){Q.push({failMessage:r,failureOutput:a,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:h})},o.unfreeze=function(E=!1){let T=Q.pop();if(!T)return;if(E)h={...T.descriptions,...h},f=[...T.commands,...f],l=[...T.usages,...l],d=[...T.examples,...d],m=[...T.epilogs,...m];else({failMessage:r,failureOutput:a,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:h}=T)},o}function No(e){return typeof e==="object"}function hf(e,t){return No(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Fa(e){return No(e)?e.indentation:0}function fs(e){return No(e)?e.text:e}var _a=`###-begin-{{app_name}}-completions-###
18
+ `)}return ne.toString().replace(/\s*$/,"")};function b(S,C,T){let F=0;if(!Array.isArray(S))S=Object.values(S).map((B)=>[B]);if(S.forEach((B)=>{F=Math.max(t.stringWidth(T?`${T} ${hs(B[0])}`:hs(B[0]))+Ra(B[0]),F)}),C)F=Math.min(F,parseInt((C*0.5).toString(),10));return F}function _(){let S=e.getDemandedOptions(),C=e.getOptions();(Object.keys(C.alias)||[]).forEach((T)=>{C.alias[T].forEach((F)=>{if(h[F])o.describe(T,h[F]);if(F in S)e.demandOption(T,S[F]);if(C.boolean.includes(F))e.boolean(T);if(C.count.includes(F))e.count(T);if(C.string.includes(F))e.string(T);if(C.normalize.includes(F))e.normalize(T);if(C.array.includes(F))e.array(T);if(C.number.includes(F))e.number(T)})})}let A;o.cacheHelpMessage=function(){A=this.help()},o.clearCachedHelpMessage=function(){A=void 0},o.hasCachedHelpMessage=function(){return!!A};function N(S,C,T,F){let B=[],Z=null;return Object.keys(T).forEach((X)=>{B=B.concat(T[X])}),S.forEach((X)=>{if(Z=[X].concat(C[X]),!Z.some((oe)=>B.indexOf(oe)!==-1))T[F].push(X)}),B}function j(S){return e.getOptions().hiddenOptions.indexOf(S)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}o.showHelp=(S)=>{let C=e.getInternalMethods().getLoggerInstance();if(!S)S="error";(typeof S==="function"?S:C[S])(o.help())},o.functionDescription=(S)=>["(",S.name?t.Parser.decamelize(S.name,"-"):n("generated-value"),")"].join(""),o.stringifiedValues=function(C,T){let F="",B=T||", ",Z=[].concat(C);if(!C||!Z.length)return F;return Z.forEach((X)=>{if(F.length)F+=B;F+=JSON.stringify(X)}),F};function O(S,C){let T=`[${n("default:")} `;if(S===void 0&&!C)return null;if(C)T+=C;else switch(typeof S){case"string":T+=`"${S}"`;break;case"object":T+=JSON.stringify(S);break;default:T+=S}return`${T}]`}function K(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let U=null;o.version=(S)=>{U=S},o.showVersion=(S)=>{let C=e.getInternalMethods().getLoggerInstance();if(!S)S="error";(typeof S==="function"?S:C[S])(U)},o.reset=function(C){return r=null,a=!1,l=[],u=!1,m=[],d=[],f=[],h=gt(h,(T)=>!C[T]),o};let Q=[];return o.freeze=function(){Q.push({failMessage:r,failureOutput:a,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:h})},o.unfreeze=function(C=!1){let T=Q.pop();if(!T)return;if(C)h={...T.descriptions,...h},f=[...T.commands,...f],l=[...T.usages,...l],d=[...T.examples,...d],m=[...T.epilogs,...m];else({failMessage:r,failureOutput:a,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:h}=T)},o}function Lo(e){return typeof e==="object"}function Pf(e,t){return Lo(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Ra(e){return Lo(e)?e.indentation:0}function hs(e){return Lo(e)?e.text:e}var Ba=`###-begin-{{app_name}}-completions-###
19
19
  #
20
20
  # yargs command completion script
21
21
  #
@@ -44,7 +44,7 @@ _{{app_name}}_yargs_completions()
44
44
  }
45
45
  complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
46
46
  ###-end-{{app_name}}-completions-###
47
- `,$a=`#compdef {{app_name}}
47
+ `,Ma=`#compdef {{app_name}}
48
48
  ###-begin-{{app_name}}-completions-###
49
49
  #
50
50
  # yargs command completion script
@@ -71,19 +71,19 @@ else
71
71
  compdef _{{app_name}}_yargs_completions {{app_name}}
72
72
  fi
73
73
  ###-end-{{app_name}}-completions-###
74
- `;class Aa{constructor(e,t,n,o){var s,r,i;this.yargs=e,this.usage=t,this.command=n,this.shim=o,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((s=this.shim.getEnv("SHELL"))===null||s===void 0?void 0:s.includes("zsh"))||((r=this.shim.getEnv("ZSH_NAME"))===null||r===void 0?void 0:r.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,o){let s=this.command.getCommandHandlers();for(let i=0,c=e.length;i<c;++i)if(s[e[i]]&&s[e[i]].builder){let a=s[e[i]].builder;if(ds(a)){this.indexAfterLastReset=i+1;let l=this.yargs.getInternalMethods().reset();return a(l,!0),l.argv}}let r=[];this.commandCompletions(r,e,n),this.optionCompletions(r,e,t,n),this.choicesFromOptionsCompletions(r,e,t,n),this.choicesFromPositionalsCompletions(r,e,t,n),o(null,r)}commandCompletions(e,t,n){let o=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&o[o.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((s)=>{let r=ft(s[0]).cmd;if(t.indexOf(r)===-1)if(!this.zshShell)e.push(r);else{let i=s[1]||"";e.push(r.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,o){if((o.match(/^-/)||o===""&&e.length===0)&&!this.previousArgHasChoices(t)){let s=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((i)=>{let c=!!s.configuration["boolean-negation"]&&s.boolean.includes(i);if(!r.includes(i)&&!s.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,c))this.completeOptionKey(i,e,o,c&&!!s.default[i])})}}choicesFromOptionsCompletions(e,t,n,o){if(this.previousArgHasChoices(t)){let s=this.getPreviousArgChoices(t);if(s&&s.length>0)e.push(...s.map((r)=>r.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,o){if(o===""&&e.length>0&&this.previousArgHasChoices(t))return;let s=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=s[n._.length-r-1];if(!i)return;let c=this.yargs.getOptions().choices[i]||[];for(let a of c)if(a.startsWith(o))e.push(a.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n="";if(!t.startsWith("-")&&e.length>1)n=t,t=e[e.length-2];if(!t.startsWith("-"))return;let o=t.replace(/^-+/,""),s=this.yargs.getOptions(),r=[o,...this.yargs.getAliases()[o]||[]],i;for(let c of r)if(Object.prototype.hasOwnProperty.call(s.key,c)&&Array.isArray(s.choices[c])){i=s.choices[c];break}if(i)return i.filter((c)=>!n||c.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let o=(s)=>e.indexOf((/^[^0-9]$/.test(s)?"-":"--")+s)!==-1;if(o(t))return!0;if(n&&o(`no-${t}`))return!0;if(this.aliases){for(let s of this.aliases[t])if(o(s))return!0}return!1}completeOptionKey(e,t,n,o){var s,r,i,c;let a=e;if(this.zshShell){let f=this.usage.getDescriptions(),h=(r=(s=this===null||this===void 0?void 0:this.aliases)===null||s===void 0?void 0:s[e])===null||r===void 0?void 0:r.find((D)=>{let C=f[D];return typeof C==="string"&&C.length>0}),m=h?f[h]:void 0,p=(c=(i=f[e])!==null&&i!==void 0?i:m)!==null&&c!==void 0?c:"";a=`${e.replace(/:/g,"\\:")}:${p.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let l=(f)=>/^--/.test(f),u=(f)=>/^[^0-9]$/.test(f),d=!l(n)&&u(e)?"-":"--";if(t.push(d+a),o)t.push(d+"no-"+a)}customCompletion(e,t,n,o){if(Ee(this.customCompletionFunction,null,this.shim),mf(this.customCompletionFunction)){let s=this.customCompletionFunction(n,t);if(re(s))return s.then((r)=>{this.shim.process.nextTick(()=>{o(null,r)})}).catch((r)=>{this.shim.process.nextTick(()=>{o(r,void 0)})});return o(null,s)}else if(Df(this.customCompletionFunction))return this.customCompletionFunction(n,t,(s=o)=>this.defaultCompletion(e,t,n,s),(s)=>{o(null,s)});else return this.customCompletionFunction(n,t,(s)=>{o(null,s)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",o=this.yargs.parse(e,!0),s=this.customCompletionFunction?(r)=>this.customCompletion(e,r,n,t):(r)=>this.defaultCompletion(e,r,n,t);return re(o)?o.then(s):s(o)}generateCompletionScript(e,t){let n=this.zshShell?$a:_a,o=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,o),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function Ta(e,t,n,o){return new Aa(e,t,n,o)}function mf(e){return e.length<3}function Df(e){return e.length>3}function Oa(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],o;for(o=0;o<=t.length;o++)n[o]=[o];let s;for(s=0;s<=e.length;s++)n[0][s]=s;for(o=1;o<=t.length;o++)for(s=1;s<=e.length;s++)if(t.charAt(o-1)===e.charAt(s-1))n[o][s]=n[o-1][s-1];else if(o>1&&s>1&&t.charAt(o-2)===e.charAt(s-1)&&t.charAt(o-1)===e.charAt(s-2))n[o][s]=n[o-2][s-2]+1;else n[o][s]=Math.min(n[o-1][s-1]+1,Math.min(n[o][s-1]+1,n[o-1][s]+1));return n[t.length][e.length]}var Ia=["$0","--","_"];function Pa(e,t,n){let o=n.y18n.__,s=n.y18n.__n,r={};r.nonOptionCount=function(d){let f=e.getDemandedCommands(),m=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(f._&&(m<f._.min||m>f._.max)){if(m<f._.min)if(f._.minMsg!==void 0)t.fail(f._.minMsg?f._.minMsg.replace(/\$0/g,m.toString()).replace(/\$1/,f._.min.toString()):null);else t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",m,m.toString(),f._.min.toString()));else if(m>f._.max)if(f._.maxMsg!==void 0)t.fail(f._.maxMsg?f._.maxMsg.replace(/\$0/g,m.toString()).replace(/\$1/,f._.max.toString()):null);else t.fail(s("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",m,m.toString(),f._.max.toString()))}},r.positionalCount=function(d,f){if(f<d)t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",f,f+"",d+""))},r.requiredArguments=function(d,f){let h=null;for(let m of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,m)||typeof d[m]>"u")h=h||{},h[m]=f[m];if(h){let m=[];for(let D of Object.keys(h)){let C=h[D];if(C&&m.indexOf(C)<0)m.push(C)}let p=m.length?`
74
+ `;class va{constructor(e,t,n,o){var s,r,i;this.yargs=e,this.usage=t,this.command=n,this.shim=o,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((s=this.shim.getEnv("SHELL"))===null||s===void 0?void 0:s.includes("zsh"))||((r=this.shim.getEnv("ZSH_NAME"))===null||r===void 0?void 0:r.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,o){let s=this.command.getCommandHandlers();for(let i=0,c=e.length;i<c;++i)if(s[e[i]]&&s[e[i]].builder){let a=s[e[i]].builder;if(ps(a)){this.indexAfterLastReset=i+1;let l=this.yargs.getInternalMethods().reset();return a(l,!0),l.argv}}let r=[];this.commandCompletions(r,e,n),this.optionCompletions(r,e,t,n),this.choicesFromOptionsCompletions(r,e,t,n),this.choicesFromPositionalsCompletions(r,e,t,n),o(null,r)}commandCompletions(e,t,n){let o=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&o[o.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((s)=>{let r=ht(s[0]).cmd;if(t.indexOf(r)===-1)if(!this.zshShell)e.push(r);else{let i=s[1]||"";e.push(r.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,o){if((o.match(/^-/)||o===""&&e.length===0)&&!this.previousArgHasChoices(t)){let s=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((i)=>{let c=!!s.configuration["boolean-negation"]&&s.boolean.includes(i);if(!r.includes(i)&&!s.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,c))this.completeOptionKey(i,e,o,c&&!!s.default[i])})}}choicesFromOptionsCompletions(e,t,n,o){if(this.previousArgHasChoices(t)){let s=this.getPreviousArgChoices(t);if(s&&s.length>0)e.push(...s.map((r)=>r.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,o){if(o===""&&e.length>0&&this.previousArgHasChoices(t))return;let s=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=s[n._.length-r-1];if(!i)return;let c=this.yargs.getOptions().choices[i]||[];for(let a of c)if(a.startsWith(o))e.push(a.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n="";if(!t.startsWith("-")&&e.length>1)n=t,t=e[e.length-2];if(!t.startsWith("-"))return;let o=t.replace(/^-+/,""),s=this.yargs.getOptions(),r=[o,...this.yargs.getAliases()[o]||[]],i;for(let c of r)if(Object.prototype.hasOwnProperty.call(s.key,c)&&Array.isArray(s.choices[c])){i=s.choices[c];break}if(i)return i.filter((c)=>!n||c.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let o=(s)=>e.indexOf((/^[^0-9]$/.test(s)?"-":"--")+s)!==-1;if(o(t))return!0;if(n&&o(`no-${t}`))return!0;if(this.aliases){for(let s of this.aliases[t])if(o(s))return!0}return!1}completeOptionKey(e,t,n,o){var s,r,i,c;let a=e;if(this.zshShell){let f=this.usage.getDescriptions(),h=(r=(s=this===null||this===void 0?void 0:this.aliases)===null||s===void 0?void 0:s[e])===null||r===void 0?void 0:r.find((D)=>{let x=f[D];return typeof x==="string"&&x.length>0}),m=h?f[h]:void 0,p=(c=(i=f[e])!==null&&i!==void 0?i:m)!==null&&c!==void 0?c:"";a=`${e.replace(/:/g,"\\:")}:${p.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let l=(f)=>/^--/.test(f),u=(f)=>/^[^0-9]$/.test(f),d=!l(n)&&u(e)?"-":"--";if(t.push(d+a),o)t.push(d+"no-"+a)}customCompletion(e,t,n,o){if(_e(this.customCompletionFunction,null,this.shim),Nf(this.customCompletionFunction)){let s=this.customCompletionFunction(n,t);if(re(s))return s.then((r)=>{this.shim.process.nextTick(()=>{o(null,r)})}).catch((r)=>{this.shim.process.nextTick(()=>{o(r,void 0)})});return o(null,s)}else if(Bf(this.customCompletionFunction))return this.customCompletionFunction(n,t,(s=o)=>this.defaultCompletion(e,t,n,s),(s)=>{o(null,s)});else return this.customCompletionFunction(n,t,(s)=>{o(null,s)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",o=this.yargs.parse(e,!0),s=this.customCompletionFunction?(r)=>this.customCompletion(e,r,n,t):(r)=>this.defaultCompletion(e,r,n,t);return re(o)?o.then(s):s(o)}generateCompletionScript(e,t){let n=this.zshShell?Ma:Ba,o=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,o),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function La(e,t,n,o){return new va(e,t,n,o)}function Nf(e){return e.length<3}function Bf(e){return e.length>3}function ja(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],o;for(o=0;o<=t.length;o++)n[o]=[o];let s;for(s=0;s<=e.length;s++)n[0][s]=s;for(o=1;o<=t.length;o++)for(s=1;s<=e.length;s++)if(t.charAt(o-1)===e.charAt(s-1))n[o][s]=n[o-1][s-1];else if(o>1&&s>1&&t.charAt(o-2)===e.charAt(s-1)&&t.charAt(o-1)===e.charAt(s-2))n[o][s]=n[o-2][s-2]+1;else n[o][s]=Math.min(n[o-1][s-1]+1,Math.min(n[o][s-1]+1,n[o-1][s]+1));return n[t.length][e.length]}var Wa=["$0","--","_"];function Ua(e,t,n){let o=n.y18n.__,s=n.y18n.__n,r={};r.nonOptionCount=function(d){let f=e.getDemandedCommands(),m=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(f._&&(m<f._.min||m>f._.max)){if(m<f._.min)if(f._.minMsg!==void 0)t.fail(f._.minMsg?f._.minMsg.replace(/\$0/g,m.toString()).replace(/\$1/,f._.min.toString()):null);else t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",m,m.toString(),f._.min.toString()));else if(m>f._.max)if(f._.maxMsg!==void 0)t.fail(f._.maxMsg?f._.maxMsg.replace(/\$0/g,m.toString()).replace(/\$1/,f._.max.toString()):null);else t.fail(s("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",m,m.toString(),f._.max.toString()))}},r.positionalCount=function(d,f){if(f<d)t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",f,f+"",d+""))},r.requiredArguments=function(d,f){let h=null;for(let m of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,m)||typeof d[m]>"u")h=h||{},h[m]=f[m];if(h){let m=[];for(let D of Object.keys(h)){let x=h[D];if(x&&m.indexOf(x)<0)m.push(x)}let p=m.length?`
75
75
  ${m.join(`
76
- `)}`:"";t.fail(s("Missing required argument: %s","Missing required arguments: %s",Object.keys(h).length,Object.keys(h).join(", ")+p))}},r.unknownArguments=function(d,f,h,m,p=!0){var D;let C=e.getInternalMethods().getCommandInstance().getCommands(),b=[],_=e.getInternalMethods().getContext();if(Object.keys(d).forEach((A)=>{if(!Ia.includes(A)&&!Object.prototype.hasOwnProperty.call(h,A)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),A)&&!r.isValidAndSomeAliasIsNotNew(A,f))b.push(A)}),p&&(_.commands.length>0||C.length>0||m))d._.slice(_.commands.length).forEach((A)=>{if(!C.includes(""+A))b.push(""+A)});if(p){let N=((D=e.getDemandedCommands()._)===null||D===void 0?void 0:D.max)||0,j=_.commands.length+N;if(j<d._.length)d._.slice(j).forEach((I)=>{if(I=String(I),!_.commands.includes(I)&&!b.includes(I))b.push(I)})}if(b.length)t.fail(s("Unknown argument: %s","Unknown arguments: %s",b.length,b.map((A)=>A.trim()?A:`"${A}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),h=[],m=e.getInternalMethods().getContext();if(m.commands.length>0||f.length>0)d._.slice(m.commands.length).forEach((p)=>{if(!f.includes(""+p))h.push(""+p)});if(h.length>0)return t.fail(s("Unknown command: %s","Unknown commands: %s",h.length,h.join(", "))),!0;else return!1},r.isValidAndSomeAliasIsNotNew=function(d,f){if(!Object.prototype.hasOwnProperty.call(f,d))return!1;let h=e.parsed.newAliases;return[d,...f[d]].some((m)=>!Object.prototype.hasOwnProperty.call(h,m)||!h[d])},r.limitedChoices=function(d){let f=e.getOptions(),h={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((D)=>{if(Ia.indexOf(D)===-1&&Object.prototype.hasOwnProperty.call(f.choices,D))[].concat(d[D]).forEach((C)=>{if(f.choices[D].indexOf(C)===-1&&C!==void 0)h[D]=(h[D]||[]).concat(C)})});let m=Object.keys(h);if(!m.length)return;let p=o("Invalid values:");m.forEach((D)=>{p+=`
77
- ${o("Argument: %s, Given: %s, Choices: %s",D,t.stringifiedValues(h[D]),t.stringifiedValues(f.choices[D]))}`}),t.fail(p)};let i={};r.implies=function(d,f){if(v("<string|object> [array|number|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.implies(h,d[h])});else{if(e.global(d),!i[d])i[d]=[];if(Array.isArray(f))f.forEach((h)=>r.implies(d,h));else Ee(f,void 0,n),i[d].push(f)}},r.getImplied=function(){return i};function c(u,d){let f=Number(d);if(d=isNaN(f)?d:f,typeof d==="number")d=u._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(u,d);else d=Object.prototype.hasOwnProperty.call(u,d);return d}r.implications=function(d){let f=[];if(Object.keys(i).forEach((h)=>{let m=h;(i[h]||[]).forEach((p)=>{let D=m,C=p;if(D=c(d,D),p=c(d,p),D&&!p)f.push(` ${m} -> ${C}`)})}),f.length){let h=`${o("Implications failed:")}
78
- `;f.forEach((m)=>{h+=m}),t.fail(h)}};let a={};r.conflicts=function(d,f){if(v("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.conflicts(h,d[h])});else{if(e.global(d),!a[d])a[d]=[];if(Array.isArray(f))f.forEach((h)=>r.conflicts(d,h));else a[d].push(f)}},r.getConflicting=()=>a,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(a[f])a[f].forEach((h)=>{if(h&&d[f]!==void 0&&d[h]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(a).forEach((f)=>{a[f].forEach((h)=>{if(h&&d[n.Parser.camelCase(f)]!==void 0&&d[n.Parser.camelCase(h)]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})})},r.recommendCommands=function(d,f){f=f.sort((D,C)=>C.length-D.length);let m=null,p=1/0;for(let D=0,C;(C=f[D])!==void 0;D++){let b=Oa(d,C);if(b<=3&&b<p)p=b,m=C}if(m)t.fail(o("Did you mean %s?",m))},r.reset=function(d){return i=pt(i,(f)=>!d[f]),a=pt(a,(f)=>!d[f]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:a})},r.unfreeze=function(){let d=l.pop();Ee(d,void 0,n),{implied:i,conflicting:a}=d},r}var Bo=[],Cn;function En(e,t,n,o){Cn=o;let s={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return s;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(c){return e}else i=wf(t,e.extends);yf(i),Bo.push(i),s=r?JSON.parse(Cn.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=En(s,Cn.path.dirname(i),n,Cn)}return Bo=[],n?Ra(s,e):Object.assign({},s,e)}function yf(e){if(Bo.indexOf(e)>-1)throw new de(`Circular extended configurations: '${e}'.`)}function wf(e,t){return Cn.path.resolve(e,t)}function Ra(e,t){let n={};function o(s){return s&&typeof s==="object"&&!Array.isArray(s)}Object.assign(n,e);for(let s of Object.keys(t))if(o(t[s])&&o(n[s]))n[s]=Ra(e[s],t[s]);else n[s]=t[s];return n}var L=function(e,t,n,o,s){if(o==="m")throw TypeError("Private method is not writable");if(o==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?s.call(e,n):s?s.value=n:t.set(e,n),n},g=function(e,t,n,o){if(n==="a"&&!o)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(e):o?o.value:t.get(e)},fe,It,xn,_e,Ie,ps,gt,Pt,hs,We,gs,Ue,st,Pe,Ke,ms,Rt,ye,K,Ds,ys,Re,Nt,nn,Bt,mt,ws,G,Mt,vt,Lt,V,bs,ot,ce;function ec(e){return(t=[],n=e.process.cwd(),o)=>{let s=new tc(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var Na=Symbol("copyDoubleDash"),Ba=Symbol("copyDoubleDash"),Mo=Symbol("deleteFromParserHintObject"),Ma=Symbol("emitWarning"),va=Symbol("freeze"),La=Symbol("getDollarZero"),jt=Symbol("getParserConfiguration"),ja=Symbol("getUsageConfiguration"),vo=Symbol("guessLocale"),Wa=Symbol("guessVersion"),Ua=Symbol("parsePositionalNumbers"),Lo=Symbol("pkgUp"),Dt=Symbol("populateParserHintArray"),sn=Symbol("populateParserHintSingleValueDictionary"),jo=Symbol("populateParserHintArrayDictionary"),Wo=Symbol("populateParserHintDictionary"),Uo=Symbol("sanitizeKey"),Ko=Symbol("setKey"),Jo=Symbol("unfreeze"),Ka=Symbol("validateAsync"),Ja=Symbol("getCommandInstance"),Ha=Symbol("getContext"),za=Symbol("getHasOutput"),qa=Symbol("getLoggerInstance"),Ga=Symbol("getParseContext"),Xa=Symbol("getUsageInstance"),Ya=Symbol("getValidationInstance"),ks=Symbol("hasParseCallback"),Va=Symbol("isGlobalContext"),Wt=Symbol("postProcess"),Za=Symbol("rebase"),Ho=Symbol("reset"),Fn=Symbol("runYargsParserAndExecuteCommands"),zo=Symbol("runValidation"),Qa=Symbol("setHasOutput"),Ut=Symbol("kTrackManuallySetKeys"),bf="en_US";class tc{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,fe.set(this,void 0),It.set(this,void 0),xn.set(this,{commands:[],fullCommands:[]}),_e.set(this,null),Ie.set(this,null),ps.set(this,"show-hidden"),gt.set(this,null),Pt.set(this,!0),hs.set(this,{}),We.set(this,!0),gs.set(this,[]),Ue.set(this,void 0),st.set(this,{}),Pe.set(this,!1),Ke.set(this,null),ms.set(this,!0),Rt.set(this,void 0),ye.set(this,""),K.set(this,void 0),Ds.set(this,void 0),ys.set(this,{}),Re.set(this,null),Nt.set(this,null),nn.set(this,{}),Bt.set(this,{}),mt.set(this,void 0),ws.set(this,!1),G.set(this,void 0),Mt.set(this,!1),vt.set(this,!1),Lt.set(this,!1),V.set(this,void 0),bs.set(this,{}),ot.set(this,null),ce.set(this,void 0),L(this,G,o,"f"),L(this,mt,e,"f"),L(this,It,t,"f"),L(this,Ds,n,"f"),L(this,Ue,new Ro(this),"f"),this.$0=this[La](),this[Ho](),L(this,fe,g(this,fe,"f"),"f"),L(this,V,g(this,V,"f"),"f"),L(this,ce,g(this,ce,"f"),"f"),L(this,K,g(this,K,"f"),"f"),g(this,K,"f").showHiddenOpt=g(this,ps,"f"),L(this,Rt,this[Ba](),"f"),g(this,G,"f").y18n.setLocale(bf)}addHelpOpt(e,t){if(v("[string|boolean] [string]",[e,t],arguments.length),g(this,Ke,"f"))this[Mo](g(this,Ke,"f")),L(this,Ke,null,"f");if(e===!1&&t===void 0)return this;return L(this,Ke,typeof e==="string"?e:"help","f"),this.boolean(g(this,Ke,"f")),this.describe(g(this,Ke,"f"),t||g(this,V,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(v("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:g(this,ps,"f");return this.boolean(n),this.describe(n,t||g(this,V,"f").deferY18nLookup("Show hidden options")),g(this,K,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return v("<object|string|array> [string|array]",[e,t],arguments.length),this[jo](this.alias.bind(this),"alias",e,t),this}array(e){return v("<array|string>",[e],arguments.length),this[Dt]("array",e),this[Ut](e),this}boolean(e){return v("<array|string>",[e],arguments.length),this[Dt]("boolean",e),this[Ut](e),this}check(e,t){return v("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>Ot(()=>e(n,o.getOptions()),(s)=>{if(!s)g(this,V,"f").fail(g(this,G,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)g(this,V,"f").fail(s.toString(),s);return n},(s)=>(g(this,V,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return v("<object|string|array> [string|array]",[e,t],arguments.length),this[jo](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(v("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new de("coerce callback must be provided");for(let o of e)this.coerce(o,t);return this}else if(typeof e==="object"){for(let o of Object.keys(e))this.coerce(o,e[o]);return this}if(!t)throw new de("coerce callback must be provided");let n=e;return g(this,K,"f").key[n]=!0,g(this,Ue,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],c=[n,...i].filter((a)=>Object.prototype.hasOwnProperty.call(o,a));if(c.length===0)return o;return Ot(()=>t(o[c[0]]),(a)=>(c.forEach((l)=>{o[l]=a}),o),(a)=>{throw new de(a.message)})},n),this}conflicts(e,t){return v("<string|object> [string|array]",[e,t],arguments.length),g(this,ce,"f").conflicts(e,t),this}config(e="config",t,n){if(v("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=En(e,g(this,It,"f"),this[jt]()["deep-merge-config"]||!1,g(this,G,"f")),g(this,K,"f").configObjects=(g(this,K,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||g(this,V,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{g(this,K,"f").config[o]=n||!0}),this}completion(e,t,n){if(v("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(L(this,Ie,e||g(this,Ie,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(g(this,Ie,"f"),t),n)g(this,_e,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return v("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),g(this,fe,"f").addHandler(e,t,n,o,s,r),this}commands(e,t,n,o,s,r){return this.command(e,t,n,o,s,r)}commandDir(e,t){v("<string> [object]",[e,t],arguments.length);let n=g(this,Ds,"f")||g(this,G,"f").require;return g(this,fe,"f").addDirectory(e,n,g(this,G,"f").getCallerFile(),t),this}count(e){return v("<array|string>",[e],arguments.length),this[Dt]("count",e),this[Ut](e),this}default(e,t,n){if(v("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)Po(e,g(this,G,"f")),g(this,K,"f").defaultDescription[e]=n;if(typeof t==="function"){if(Po(e,g(this,G,"f")),!g(this,K,"f").defaultDescription[e])g(this,K,"f").defaultDescription[e]=g(this,V,"f").functionDescription(t);t=t.call()}return this[sn](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,o){if(v("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,o],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),g(this,K,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{Ee(n,!0,g(this,G,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")Ee(n,!0,g(this,G,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{Ee(n,!0,g(this,G,"f")),this.demandOption(o,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return v("<object|string|array> [string]",[e,t],arguments.length),this[sn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return v("<string> [string|boolean]",[e,t],arguments.length),g(this,K,"f").deprecatedOptions[e]=t,this}describe(e,t){return v("<object|string|array> [string]",[e,t],arguments.length),this[Ko](e,!0),g(this,V,"f").describe(e,t),this}detectLocale(e){return v("<boolean>",[e],arguments.length),L(this,Pt,e,"f"),this}env(e){if(v("[string|boolean]",[e],arguments.length),e===!1)delete g(this,K,"f").envPrefix;else g(this,K,"f").envPrefix=e||"";return this}epilogue(e){return v("<string>",[e],arguments.length),g(this,V,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(v("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else g(this,V,"f").example(e,t);return this}exit(e,t){if(L(this,Pe,!0,"f"),L(this,gt,t,"f"),g(this,We,"f"))g(this,G,"f").process.exit(e)}exitProcess(e=!0){return v("[boolean]",[e],arguments.length),L(this,We,e,"f"),this}fail(e){if(v("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new de("Invalid first argument. Expected function or boolean 'false'");return g(this,V,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(v("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{g(this,_e,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return g(this,_e,"f").getCompletion(e,t)}getDemandedOptions(){return v([],0),g(this,K,"f").demandedOptions}getDemandedCommands(){return v([],0),g(this,K,"f").demandedCommands}getDeprecatedOptions(){return v([],0),g(this,K,"f").deprecatedOptions}getDetectLocale(){return g(this,Pt,"f")}getExitProcess(){return g(this,We,"f")}getGroups(){return Object.assign({},g(this,st,"f"),g(this,Bt,"f"))}getHelp(){if(L(this,Pe,!0,"f"),!g(this,V,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[Fn](g(this,mt,"f"),void 0,void 0,0,!0);if(re(t))return t.then(()=>g(this,V,"f").help())}let e=g(this,fe,"f").runDefaultBuilderOn(this);if(re(e))return e.then(()=>g(this,V,"f").help())}return Promise.resolve(g(this,V,"f").help())}getOptions(){return g(this,K,"f")}getStrict(){return g(this,Mt,"f")}getStrictCommands(){return g(this,vt,"f")}getStrictOptions(){return g(this,Lt,"f")}global(e,t){if(v("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)g(this,K,"f").local=g(this,K,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!g(this,K,"f").local.includes(n))g(this,K,"f").local.push(n)});return this}group(e,t){v("<string|array> <string>",[e,t],arguments.length);let n=g(this,Bt,"f")[t]||g(this,st,"f")[t];if(g(this,Bt,"f")[t])delete g(this,Bt,"f")[t];let o={};return g(this,st,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return v("<string>",[e],arguments.length),g(this,K,"f").hiddenOptions.push(e),this}implies(e,t){return v("<string|object> [number|string|array]",[e,t],arguments.length),g(this,ce,"f").implies(e,t),this}locale(e){if(v("[string]",[e],arguments.length),e===void 0)return this[vo](),g(this,G,"f").y18n.getLocale();return L(this,Pt,!1,"f"),g(this,G,"f").y18n.setLocale(e),this}middleware(e,t,n){return g(this,Ue,"f").addMiddleware(e,!!t,n)}nargs(e,t){return v("<string|object|array> [number]",[e,t],arguments.length),this[sn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return v("<array|string>",[e],arguments.length),this[Dt]("normalize",e),this}number(e){return v("<array|string>",[e],arguments.length),this[Dt]("number",e),this[Ut](e),this}option(e,t){if(v("<string|object> [object]",[e,t],arguments.length),typeof e==="object")Object.keys(e).forEach((n)=>{this.options(n,e[n])});else{if(typeof t!=="object")t={};if(this[Ut](e),g(this,ot,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[Ma](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
79
- `),void 0,"versionWarning");if(g(this,K,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let o=t.demand||t.required||t.require;if(o)this.demand(e,o);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)g(this,K,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let s=t.describe||t.description||t.desc,r=g(this,V,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(r,e)||typeof s==="string")this.describe(e,s);if(t.hidden)this.hide(e);if(t.requiresArg)this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){if(v("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[va](),typeof e>"u")e=g(this,mt,"f");if(typeof t==="object")L(this,Nt,t,"f"),t=n;if(typeof t==="function")L(this,Re,t,"f"),t=!1;if(!t)L(this,mt,e,"f");if(g(this,Re,"f"))L(this,We,!1,"f");let o=this[Fn](e,!!t),s=this.parsed;if(g(this,_e,"f").setParsed(this.parsed),re(o))return o.then((r)=>{if(g(this,Re,"f"))g(this,Re,"f").call(this,g(this,gt,"f"),r,g(this,ye,"f"));return r}).catch((r)=>{if(g(this,Re,"f"))g(this,Re,"f")(r,this.parsed.argv,g(this,ye,"f"));throw r}).finally(()=>{this[Jo](),this.parsed=s});else{if(g(this,Re,"f"))g(this,Re,"f").call(this,g(this,gt,"f"),o,g(this,ye,"f"));this[Jo](),this.parsed=s}return o}parseAsync(e,t,n){let o=this.parse(e,t,n);return!re(o)?Promise.resolve(o):o}parseSync(e,t,n){let o=this.parse(e,t,n);if(re(o))throw new de(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return o}parserConfiguration(e){return v("<object>",[e],arguments.length),L(this,ys,e,"f"),this}pkgConf(e,t){v("<string> [string]",[e,t],arguments.length);let n=null,o=this[Lo](t||g(this,It,"f"));if(o[e]&&typeof o[e]==="object")n=En(o[e],t||g(this,It,"f"),this[jt]()["deep-merge-config"]||!1,g(this,G,"f")),g(this,K,"f").configObjects=(g(this,K,"f").configObjects||[]).concat(n);return this}positional(e,t){v("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=pt(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let o=g(this,xn,"f").fullCommands[g(this,xn,"f").fullCommands.length-1],s=o?g(this,fe,"f").cmdToParseOptions(o):{array:[],alias:{},default:{},demand:{}};return en(s).forEach((r)=>{let i=s[r];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[r]=!0}else if(i[e]&&!(r in t))t[r]=i[e]}),this.group(e,g(this,V,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return v("[boolean]",[e],arguments.length),L(this,ws,e,"f"),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){if(v("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&g(this,K,"f").narg[e])return this;else this[sn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return v("[string] [string]",[e,t],arguments.length),e=e||this.$0,g(this,Rt,"f").log(g(this,_e,"f").generateCompletionScript(e,t||g(this,Ie,"f")||"completion")),this}showHelp(e){if(v("[string|function]",[e],arguments.length),L(this,Pe,!0,"f"),!g(this,V,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[Fn](g(this,mt,"f"),void 0,void 0,0,!0);if(re(n))return n.then(()=>{g(this,V,"f").showHelp(e)}),this}let t=g(this,fe,"f").runDefaultBuilderOn(this);if(re(t))return t.then(()=>{g(this,V,"f").showHelp(e)}),this}return g(this,V,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return v("[boolean|string] [string]",[e,t],arguments.length),g(this,V,"f").showHelpOnFail(e,t),this}showVersion(e){return v("[string|function]",[e],arguments.length),g(this,V,"f").showVersion(e),this}skipValidation(e){return v("<array|string>",[e],arguments.length),this[Dt]("skipValidation",e),this}strict(e){return v("[boolean]",[e],arguments.length),L(this,Mt,e!==!1,"f"),this}strictCommands(e){return v("[boolean]",[e],arguments.length),L(this,vt,e!==!1,"f"),this}strictOptions(e){return v("[boolean]",[e],arguments.length),L(this,Lt,e!==!1,"f"),this}string(e){return v("<array|string>",[e],arguments.length),this[Dt]("string",e),this[Ut](e),this}terminalWidth(){return v([],0),g(this,G,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return v("<object>",[e],arguments.length),L(this,Pt,!1,"f"),g(this,G,"f").y18n.updateLocale(e),this}usage(e,t,n,o){if(v("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,o],arguments.length),t!==void 0)if(Ee(e,null,g(this,G,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,o);else throw new de(".usage() description must start with $0 if being used as alias for .command()");else return g(this,V,"f").usage(e),this}usageConfiguration(e){return v("<object>",[e],arguments.length),L(this,bs,e,"f"),this}version(e,t,n){if(v("[boolean|string] [string] [string]",[e,t,n],arguments.length),g(this,ot,"f"))this[Mo](g(this,ot,"f")),g(this,V,"f").version(void 0),L(this,ot,null,"f");if(arguments.length===0)n=this[Wa](),e="version";else if(arguments.length===1){if(e===!1)return this;n=e,e="version"}else if(arguments.length===2)n=t,t=void 0;return L(this,ot,typeof e==="string"?e:"version","f"),t=t||g(this,V,"f").deferY18nLookup("Show version number"),g(this,V,"f").version(n||void 0),this.boolean(g(this,ot,"f")),this.describe(g(this,ot,"f"),t),this}wrap(e){return v("<number|null|undefined>",[e],arguments.length),g(this,V,"f").wrap(e),this}[(fe=new WeakMap,It=new WeakMap,xn=new WeakMap,_e=new WeakMap,Ie=new WeakMap,ps=new WeakMap,gt=new WeakMap,Pt=new WeakMap,hs=new WeakMap,We=new WeakMap,gs=new WeakMap,Ue=new WeakMap,st=new WeakMap,Pe=new WeakMap,Ke=new WeakMap,ms=new WeakMap,Rt=new WeakMap,ye=new WeakMap,K=new WeakMap,Ds=new WeakMap,ys=new WeakMap,Re=new WeakMap,Nt=new WeakMap,nn=new WeakMap,Bt=new WeakMap,mt=new WeakMap,ws=new WeakMap,G=new WeakMap,Mt=new WeakMap,vt=new WeakMap,Lt=new WeakMap,V=new WeakMap,bs=new WeakMap,ot=new WeakMap,ce=new WeakMap,Na)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[Ba](){return{log:(...e)=>{if(!this[ks]())console.log(...e);if(L(this,Pe,!0,"f"),g(this,ye,"f").length)L(this,ye,g(this,ye,"f")+`
80
- `,"f");L(this,ye,g(this,ye,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[ks]())console.error(...e);if(L(this,Pe,!0,"f"),g(this,ye,"f").length)L(this,ye,g(this,ye,"f")+`
81
- `,"f");L(this,ye,g(this,ye,"f")+e.join(" "),"f")}}}[Mo](e){en(g(this,K,"f")).forEach((t)=>{if(((o)=>o==="configObjects")(t))return;let n=g(this,K,"f")[t];if(Array.isArray(n)){if(n.includes(e))n.splice(n.indexOf(e),1)}else if(typeof n==="object")delete n[e]}),delete g(this,V,"f").getDescriptions()[e]}[Ma](e,t,n){if(!g(this,hs,"f")[n])g(this,G,"f").process.emitWarning(e,t),g(this,hs,"f")[n]=!0}[va](){g(this,gs,"f").push({options:g(this,K,"f"),configObjects:g(this,K,"f").configObjects.slice(0),exitProcess:g(this,We,"f"),groups:g(this,st,"f"),strict:g(this,Mt,"f"),strictCommands:g(this,vt,"f"),strictOptions:g(this,Lt,"f"),completionCommand:g(this,Ie,"f"),output:g(this,ye,"f"),exitError:g(this,gt,"f"),hasOutput:g(this,Pe,"f"),parsed:this.parsed,parseFn:g(this,Re,"f"),parseContext:g(this,Nt,"f")}),g(this,V,"f").freeze(),g(this,ce,"f").freeze(),g(this,fe,"f").freeze(),g(this,Ue,"f").freeze()}[La](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(g(this,G,"f").process.argv()[0]))t=g(this,G,"f").process.argv().slice(1,2);else t=g(this,G,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let o=this[Za](g(this,It,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&o.length<n.length?o:n}).join(" ").trim(),g(this,G,"f").getEnv("_")&&g(this,G,"f").getProcessArgvBin()===g(this,G,"f").getEnv("_"))e=g(this,G,"f").getEnv("_").replace(`${g(this,G,"f").path.dirname(g(this,G,"f").process.execPath())}/`,"");return e}[jt](){return g(this,ys,"f")}[ja](){return g(this,bs,"f")}[vo](){if(!g(this,Pt,"f"))return;let e=g(this,G,"f").getEnv("LC_ALL")||g(this,G,"f").getEnv("LC_MESSAGES")||g(this,G,"f").getEnv("LANG")||g(this,G,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[Wa](){return this[Lo]().version||"unknown"}[Ua](e){let t=e["--"]?e["--"]:e._;for(let n=0,o;(o=t[n])!==void 0;n++)if(g(this,G,"f").Parser.looksLikeNumber(o)&&Number.isSafeInteger(Math.floor(parseFloat(`${o}`))))t[n]=Number(o);return e}[Lo](e){let t=e||"*";if(g(this,nn,"f")[t])return g(this,nn,"f")[t];let n={};try{let o=e||g(this,G,"f").mainFilename;if(g(this,G,"f").path.extname(o))o=g(this,G,"f").path.dirname(o);let s=g(this,G,"f").findUp(o,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});Ee(s,void 0,g(this,G,"f")),n=JSON.parse(g(this,G,"f").readFileSync(s,"utf8"))}catch(o){}return g(this,nn,"f")[t]=n||{},g(this,nn,"f")[t]}[Dt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[Uo](n),g(this,K,"f")[e].push(n)})}[sn](e,t,n,o){this[Wo](e,t,n,o,(s,r,i)=>{g(this,K,"f")[s][r]=i})}[jo](e,t,n,o){this[Wo](e,t,n,o,(s,r,i)=>{g(this,K,"f")[s][r]=(g(this,K,"f")[s][r]||[]).concat(i)})}[Wo](e,t,n,o,s){if(Array.isArray(n))n.forEach((r)=>{e(r,o)});else if(((r)=>typeof r==="object")(n))for(let r of en(n))e(r,n[r]);else s(t,this[Uo](n),o)}[Uo](e){if(e==="__proto__")return"___proto___";return e}[Ko](e,t){return this[sn](this[Ko].bind(this),"key",e,t),this}[Jo](){var e,t,n,o,s,r,i,c,a,l,u,d;let f=g(this,gs,"f").pop();Ee(f,void 0,g(this,G,"f"));let h;e=this,t=this,n=this,o=this,s=this,r=this,i=this,c=this,a=this,l=this,u=this,d=this,{options:{set value(m){L(e,K,m,"f")}}.value,configObjects:h,exitProcess:{set value(m){L(t,We,m,"f")}}.value,groups:{set value(m){L(n,st,m,"f")}}.value,output:{set value(m){L(o,ye,m,"f")}}.value,exitError:{set value(m){L(s,gt,m,"f")}}.value,hasOutput:{set value(m){L(r,Pe,m,"f")}}.value,parsed:this.parsed,strict:{set value(m){L(i,Mt,m,"f")}}.value,strictCommands:{set value(m){L(c,vt,m,"f")}}.value,strictOptions:{set value(m){L(a,Lt,m,"f")}}.value,completionCommand:{set value(m){L(l,Ie,m,"f")}}.value,parseFn:{set value(m){L(u,Re,m,"f")}}.value,parseContext:{set value(m){L(d,Nt,m,"f")}}.value}=f,g(this,K,"f").configObjects=h,g(this,V,"f").unfreeze(),g(this,ce,"f").unfreeze(),g(this,fe,"f").unfreeze(),g(this,Ue,"f").unfreeze()}[Ka](e,t){return Ot(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[Ja].bind(this),getContext:this[Ha].bind(this),getHasOutput:this[za].bind(this),getLoggerInstance:this[qa].bind(this),getParseContext:this[Ga].bind(this),getParserConfiguration:this[jt].bind(this),getUsageConfiguration:this[ja].bind(this),getUsageInstance:this[Xa].bind(this),getValidationInstance:this[Ya].bind(this),hasParseCallback:this[ks].bind(this),isGlobalContext:this[Va].bind(this),postProcess:this[Wt].bind(this),reset:this[Ho].bind(this),runValidation:this[zo].bind(this),runYargsParserAndExecuteCommands:this[Fn].bind(this),setHasOutput:this[Qa].bind(this)}}[Ja](){return g(this,fe,"f")}[Ha](){return g(this,xn,"f")}[za](){return g(this,Pe,"f")}[qa](){return g(this,Rt,"f")}[Ga](){return g(this,Nt,"f")||{}}[Xa](){return g(this,V,"f")}[Ya](){return g(this,ce,"f")}[ks](){return!!g(this,Re,"f")}[Va](){return g(this,ms,"f")}[Wt](e,t,n,o){if(n)return e;if(re(e))return e;if(!t)e=this[Na](e);if(this[jt]()["parse-positional-numbers"]||this[jt]()["parse-positional-numbers"]===void 0)e=this[Ua](e);if(o)e=Tt(e,this,g(this,Ue,"f").getMiddleware(),!1);return e}[Ho](e={}){L(this,K,g(this,K,"f")||{},"f");let t={};t.local=g(this,K,"f").local||[],t.configObjects=g(this,K,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(g(this,Bt,"f"),Object.keys(g(this,st,"f")).reduce((r,i)=>{let c=g(this,st,"f")[i].filter((a)=>!(a in n));if(c.length>0)r[i]=c;return r},{})),L(this,st,{},"f");let o=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],s=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(o.forEach((r)=>{t[r]=(g(this,K,"f")[r]||[]).filter((i)=>!n[i])}),s.forEach((r)=>{t[r]=pt(g(this,K,"f")[r],(i)=>!n[i])}),t.envPrefix=g(this,K,"f").envPrefix,L(this,K,t,"f"),L(this,V,g(this,V,"f")?g(this,V,"f").reset(n):Sa(this,g(this,G,"f")),"f"),L(this,ce,g(this,ce,"f")?g(this,ce,"f").reset(n):Pa(this,g(this,V,"f"),g(this,G,"f")),"f"),L(this,fe,g(this,fe,"f")?g(this,fe,"f").reset():Ea(g(this,V,"f"),g(this,ce,"f"),g(this,Ue,"f"),g(this,G,"f")),"f"),!g(this,_e,"f"))L(this,_e,Ta(this,g(this,V,"f"),g(this,fe,"f"),g(this,G,"f")),"f");return g(this,Ue,"f").reset(),L(this,Ie,null,"f"),L(this,ye,"","f"),L(this,gt,null,"f"),L(this,Pe,!1,"f"),this.parsed=!1,this}[Za](e,t){return g(this,G,"f").path.relative(e,t)}[Fn](e,t,n,o=0,s=!1){var r,i,c,a;let l=!!n||s;e=e||g(this,mt,"f"),g(this,K,"f").__=g(this,G,"f").y18n.__,g(this,K,"f").configuration=this[jt]();let u=!!g(this,K,"f").configuration["populate--"],d=Object.assign({},g(this,K,"f").configuration,{"populate--":!0}),f=g(this,G,"f").Parser.detailed(e,Object.assign({},g(this,K,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),h=Object.assign(f.argv,g(this,Nt,"f")),m=void 0,p=f.aliases,D=!1,C=!1;if(Object.keys(h).forEach((b)=>{if(b===g(this,Ke,"f")&&h[b])D=!0;else if(b===g(this,ot,"f")&&h[b])C=!0}),h.$0=this.$0,this.parsed=f,o===0)g(this,V,"f").clearCachedHelpMessage();try{if(this[vo](),t)return this[Wt](h,u,!!n,!1);if(g(this,Ke,"f")){if([g(this,Ke,"f")].concat(p[g(this,Ke,"f")]||[]).filter((j)=>j.length>1).includes(""+h._[h._.length-1]))h._.pop(),D=!0}L(this,ms,!1,"f");let b=g(this,fe,"f").getCommands(),_=((r=g(this,_e,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=g(this,_e,"f"))===null||i===void 0?void 0:i.completionKey,...(a=this.getAliases()[(c=g(this,_e,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&a!==void 0?a:[]].some((N)=>Object.prototype.hasOwnProperty.call(h,N)):!1,A=D||_||s;if(h._.length){if(b.length){let N;for(let j=o||0,I;h._[j]!==void 0;j++)if(I=String(h._[j]),b.includes(I)&&I!==g(this,Ie,"f")){let J=g(this,fe,"f").runCommand(I,this,f,j+1,s,D||C||s);return this[Wt](J,u,!!n,!1)}else if(!N&&I!==g(this,Ie,"f")){N=I;break}if(!g(this,fe,"f").hasDefaultCommand()&&g(this,ws,"f")&&N&&!A)g(this,ce,"f").recommendCommands(N,b)}if(g(this,Ie,"f")&&h._.includes(g(this,Ie,"f"))&&!_){if(g(this,We,"f"))ht(!0);this.showCompletionScript(),this.exit(0)}}if(g(this,fe,"f").hasDefaultCommand()&&!A){let N=g(this,fe,"f").runCommand(null,this,f,0,s,D||C||s);return this[Wt](N,u,!!n,!1)}if(_){if(g(this,We,"f"))ht(!0);e=[].concat(e);let N=e.slice(e.indexOf(`--${g(this,_e,"f").completionKey}`)+1);return g(this,_e,"f").getCompletion(N,(j,I)=>{if(j)throw new de(j.message);(I||[]).forEach((J)=>{g(this,Rt,"f").log(J)}),this.exit(0)}),this[Wt](h,!u,!!n,!1)}if(!g(this,Pe,"f")){if(D){if(g(this,We,"f"))ht(!0);l=!0,this.showHelp((N)=>{g(this,Rt,"f").log(N),this.exit(0)})}else if(C){if(g(this,We,"f"))ht(!0);l=!0,g(this,V,"f").showVersion("log"),this.exit(0)}}if(!l&&g(this,K,"f").skipValidation.length>0)l=Object.keys(h).some((N)=>g(this,K,"f").skipValidation.indexOf(N)>=0&&h[N]===!0);if(!l){if(f.error)throw new de(f.error.message);if(!_){let N=this[zo](p,{},f.error);if(!n)m=Tt(h,this,g(this,Ue,"f").getMiddleware(),!0);if(m=this[Ka](N,m!==null&&m!==void 0?m:h),re(m)&&!n)m=m.then(()=>Tt(h,this,g(this,Ue,"f").getMiddleware(),!1))}}}catch(b){if(b instanceof de)g(this,V,"f").fail(b.message,b);else throw b}return this[Wt](m!==null&&m!==void 0?m:h,u,!!n,!0)}[zo](e,t,n,o){let s={...this.getDemandedOptions()};return(r)=>{if(n)throw new de(n.message);g(this,ce,"f").nonOptionCount(r),g(this,ce,"f").requiredArguments(r,s);let i=!1;if(g(this,vt,"f"))i=g(this,ce,"f").unknownCommands(r);if(g(this,Mt,"f")&&!i)g(this,ce,"f").unknownArguments(r,e,t,!!o);else if(g(this,Lt,"f"))g(this,ce,"f").unknownArguments(r,e,{},!1,!1);g(this,ce,"f").limitedChoices(r),g(this,ce,"f").implications(r),g(this,ce,"f").conflicting(r)}}[Qa](){L(this,Pe,!0,"f")}[Ut](e){if(typeof e==="string")g(this,K,"f").key[e]=!0;else for(let t of e)g(this,K,"f").key[t]=!0}}function xa(e){return!!e&&typeof e.getInternalMethods==="function"}var kf=ec(Io),nc=kf;function Cf(e){return[...e.matchAll(/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <]+/gi)].map(([n])=>n).filter((n)=>!n.startsWith("<")&&(/[^\x00-\x7f]/.test(n)||n.includes(">")))}function yt(e,t=!1,n=console.error){let o=Cf(e);if(!o.length)return;let s=`Ambiguous URL boundary: ${o.map((r)=>JSON.stringify(r)).join(", ")}. Put the URL on its own line, or wrap it as <url> / <url|label>. Use --allow-url-adjacent to warn only.`;if(!t)throw Error(s);n(`Warning: ${s}`)}import{existsSync as _n,readFileSync as Xo,writeFileSync as qo,mkdirSync as ic,chmodSync as sc}from"node:fs";import{homedir as Ef}from"node:os";import{join as Kt,dirname as Yo}from"node:path";function Vo(){return process.env.HOME||Ef()}function ac(){return Kt(Vo(),".config","slack-cli","profiles.json")}function Cs(){return Kt(process.cwd(),".slack-cli","workspace")}function Es(){return Kt(Vo(),".slack-cli","workspace")}function $n(){let e=ac();if(!_n(e))return{profiles:{}};return JSON.parse(Xo(e,"utf8"))}function xf(e){let t=ac();if(ic(Yo(t),{recursive:!0}),process.platform!=="win32"&&_n(t))sc(t,384);if(qo(t,JSON.stringify(e,null,2)+`
82
- `,{mode:384}),process.platform!=="win32")sc(t,384)}function on(e){if(!_n(e))return;return Xo(e,"utf8").trim()||void 0}function oc(e,t){let n=Yo(e);ic(n,{recursive:!0});let o=Kt(n,".gitignore");if(!_n(o))qo(o,`*
83
- `);qo(e,t+`
84
- `)}function Ff(e){let t={};for(let n of e.split(`
85
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function rc(e){if(!_n(e))return{};try{return Ff(Xo(e,"utf8"))}catch{return{}}}function Go(e,t){let n=Vo(),o=e;while(!0){for(let i of[Kt(o,".slack-term",".env.local"),Kt(o,".env.local")]){let c=rc(i);for(let a of t)if(c[a])return c[a]}if(o===n)break;let r=Yo(o);if(r===o)break;o=r}let s=rc(Kt(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function Zo(){let e=$n(),t=on(Cs()),n=on(Es()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Sn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Sn(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function cc(e){let t=$n();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],xf(t)}function lc(e,t=!1){let n=$n();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)oc(Es(),e);else oc(Cs(),e)}function An(e){let n=$n().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=Go(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
86
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Go(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let c=process.env.SLACK_WORKSPACE;if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let a=on(Cs());if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=on(Es());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
76
+ `)}`:"";t.fail(s("Missing required argument: %s","Missing required arguments: %s",Object.keys(h).length,Object.keys(h).join(", ")+p))}},r.unknownArguments=function(d,f,h,m,p=!0){var D;let x=e.getInternalMethods().getCommandInstance().getCommands(),b=[],_=e.getInternalMethods().getContext();if(Object.keys(d).forEach((A)=>{if(!Wa.includes(A)&&!Object.prototype.hasOwnProperty.call(h,A)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),A)&&!r.isValidAndSomeAliasIsNotNew(A,f))b.push(A)}),p&&(_.commands.length>0||x.length>0||m))d._.slice(_.commands.length).forEach((A)=>{if(!x.includes(""+A))b.push(""+A)});if(p){let N=((D=e.getDemandedCommands()._)===null||D===void 0?void 0:D.max)||0,j=_.commands.length+N;if(j<d._.length)d._.slice(j).forEach((O)=>{if(O=String(O),!_.commands.includes(O)&&!b.includes(O))b.push(O)})}if(b.length)t.fail(s("Unknown argument: %s","Unknown arguments: %s",b.length,b.map((A)=>A.trim()?A:`"${A}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),h=[],m=e.getInternalMethods().getContext();if(m.commands.length>0||f.length>0)d._.slice(m.commands.length).forEach((p)=>{if(!f.includes(""+p))h.push(""+p)});if(h.length>0)return t.fail(s("Unknown command: %s","Unknown commands: %s",h.length,h.join(", "))),!0;else return!1},r.isValidAndSomeAliasIsNotNew=function(d,f){if(!Object.prototype.hasOwnProperty.call(f,d))return!1;let h=e.parsed.newAliases;return[d,...f[d]].some((m)=>!Object.prototype.hasOwnProperty.call(h,m)||!h[d])},r.limitedChoices=function(d){let f=e.getOptions(),h={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((D)=>{if(Wa.indexOf(D)===-1&&Object.prototype.hasOwnProperty.call(f.choices,D))[].concat(d[D]).forEach((x)=>{if(f.choices[D].indexOf(x)===-1&&x!==void 0)h[D]=(h[D]||[]).concat(x)})});let m=Object.keys(h);if(!m.length)return;let p=o("Invalid values:");m.forEach((D)=>{p+=`
77
+ ${o("Argument: %s, Given: %s, Choices: %s",D,t.stringifiedValues(h[D]),t.stringifiedValues(f.choices[D]))}`}),t.fail(p)};let i={};r.implies=function(d,f){if(v("<string|object> [array|number|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.implies(h,d[h])});else{if(e.global(d),!i[d])i[d]=[];if(Array.isArray(f))f.forEach((h)=>r.implies(d,h));else _e(f,void 0,n),i[d].push(f)}},r.getImplied=function(){return i};function c(u,d){let f=Number(d);if(d=isNaN(f)?d:f,typeof d==="number")d=u._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(u,d);else d=Object.prototype.hasOwnProperty.call(u,d);return d}r.implications=function(d){let f=[];if(Object.keys(i).forEach((h)=>{let m=h;(i[h]||[]).forEach((p)=>{let D=m,x=p;if(D=c(d,D),p=c(d,p),D&&!p)f.push(` ${m} -> ${x}`)})}),f.length){let h=`${o("Implications failed:")}
78
+ `;f.forEach((m)=>{h+=m}),t.fail(h)}};let a={};r.conflicts=function(d,f){if(v("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.conflicts(h,d[h])});else{if(e.global(d),!a[d])a[d]=[];if(Array.isArray(f))f.forEach((h)=>r.conflicts(d,h));else a[d].push(f)}},r.getConflicting=()=>a,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(a[f])a[f].forEach((h)=>{if(h&&d[f]!==void 0&&d[h]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(a).forEach((f)=>{a[f].forEach((h)=>{if(h&&d[n.Parser.camelCase(f)]!==void 0&&d[n.Parser.camelCase(h)]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})})},r.recommendCommands=function(d,f){f=f.sort((D,x)=>x.length-D.length);let m=null,p=1/0;for(let D=0,x;(x=f[D])!==void 0;D++){let b=ja(d,x);if(b<=3&&b<p)p=b,m=x}if(m)t.fail(o("Did you mean %s?",m))},r.reset=function(d){return i=gt(i,(f)=>!d[f]),a=gt(a,(f)=>!d[f]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:a})},r.unfreeze=function(){let d=l.pop();_e(d,void 0,n),{implied:i,conflicting:a}=d},r}var jo=[],xn;function Cn(e,t,n,o){xn=o;let s={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return s;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(c){return e}else i=vf(t,e.extends);Mf(i),jo.push(i),s=r?JSON.parse(xn.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=Cn(s,xn.path.dirname(i),n,xn)}return jo=[],n?Ja(s,e):Object.assign({},s,e)}function Mf(e){if(jo.indexOf(e)>-1)throw new fe(`Circular extended configurations: '${e}'.`)}function vf(e,t){return xn.path.resolve(e,t)}function Ja(e,t){let n={};function o(s){return s&&typeof s==="object"&&!Array.isArray(s)}Object.assign(n,e);for(let s of Object.keys(t))if(o(t[s])&&o(n[s]))n[s]=Ja(e[s],t[s]);else n[s]=t[s];return n}var L=function(e,t,n,o,s){if(o==="m")throw TypeError("Private method is not writable");if(o==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?s.call(e,n):s?s.value=n:t.set(e,n),n},g=function(e,t,n,o){if(n==="a"&&!o)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(e):o?o.value:t.get(e)},pe,Pt,En,$e,Pe,gs,Dt,Rt,ms,We,Ds,Ue,st,Re,Je,ys,Nt,ke,J,ws,bs,Ne,Bt,sn,Mt,yt,ks,G,vt,Lt,jt,V,xs,ot,le;function lc(e){return(t=[],n=e.process.cwd(),o)=>{let s=new uc(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var Ka=Symbol("copyDoubleDash"),Ha=Symbol("copyDoubleDash"),Wo=Symbol("deleteFromParserHintObject"),za=Symbol("emitWarning"),qa=Symbol("freeze"),Ga=Symbol("getDollarZero"),Wt=Symbol("getParserConfiguration"),Xa=Symbol("getUsageConfiguration"),Uo=Symbol("guessLocale"),Ya=Symbol("guessVersion"),Va=Symbol("parsePositionalNumbers"),Jo=Symbol("pkgUp"),wt=Symbol("populateParserHintArray"),on=Symbol("populateParserHintSingleValueDictionary"),Ko=Symbol("populateParserHintArrayDictionary"),Ho=Symbol("populateParserHintDictionary"),zo=Symbol("sanitizeKey"),qo=Symbol("setKey"),Go=Symbol("unfreeze"),Za=Symbol("validateAsync"),Qa=Symbol("getCommandInstance"),ec=Symbol("getContext"),tc=Symbol("getHasOutput"),nc=Symbol("getLoggerInstance"),sc=Symbol("getParseContext"),oc=Symbol("getUsageInstance"),rc=Symbol("getValidationInstance"),Cs=Symbol("hasParseCallback"),ic=Symbol("isGlobalContext"),Ut=Symbol("postProcess"),ac=Symbol("rebase"),Xo=Symbol("reset"),Sn=Symbol("runYargsParserAndExecuteCommands"),Yo=Symbol("runValidation"),cc=Symbol("setHasOutput"),Jt=Symbol("kTrackManuallySetKeys"),Lf="en_US";class uc{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,pe.set(this,void 0),Pt.set(this,void 0),En.set(this,{commands:[],fullCommands:[]}),$e.set(this,null),Pe.set(this,null),gs.set(this,"show-hidden"),Dt.set(this,null),Rt.set(this,!0),ms.set(this,{}),We.set(this,!0),Ds.set(this,[]),Ue.set(this,void 0),st.set(this,{}),Re.set(this,!1),Je.set(this,null),ys.set(this,!0),Nt.set(this,void 0),ke.set(this,""),J.set(this,void 0),ws.set(this,void 0),bs.set(this,{}),Ne.set(this,null),Bt.set(this,null),sn.set(this,{}),Mt.set(this,{}),yt.set(this,void 0),ks.set(this,!1),G.set(this,void 0),vt.set(this,!1),Lt.set(this,!1),jt.set(this,!1),V.set(this,void 0),xs.set(this,{}),ot.set(this,null),le.set(this,void 0),L(this,G,o,"f"),L(this,yt,e,"f"),L(this,Pt,t,"f"),L(this,ws,n,"f"),L(this,Ue,new vo(this),"f"),this.$0=this[Ga](),this[Xo](),L(this,pe,g(this,pe,"f"),"f"),L(this,V,g(this,V,"f"),"f"),L(this,le,g(this,le,"f"),"f"),L(this,J,g(this,J,"f"),"f"),g(this,J,"f").showHiddenOpt=g(this,gs,"f"),L(this,Nt,this[Ha](),"f"),g(this,G,"f").y18n.setLocale(Lf)}addHelpOpt(e,t){if(v("[string|boolean] [string]",[e,t],arguments.length),g(this,Je,"f"))this[Wo](g(this,Je,"f")),L(this,Je,null,"f");if(e===!1&&t===void 0)return this;return L(this,Je,typeof e==="string"?e:"help","f"),this.boolean(g(this,Je,"f")),this.describe(g(this,Je,"f"),t||g(this,V,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(v("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:g(this,gs,"f");return this.boolean(n),this.describe(n,t||g(this,V,"f").deferY18nLookup("Show hidden options")),g(this,J,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return v("<object|string|array> [string|array]",[e,t],arguments.length),this[Ko](this.alias.bind(this),"alias",e,t),this}array(e){return v("<array|string>",[e],arguments.length),this[wt]("array",e),this[Jt](e),this}boolean(e){return v("<array|string>",[e],arguments.length),this[wt]("boolean",e),this[Jt](e),this}check(e,t){return v("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>Ot(()=>e(n,o.getOptions()),(s)=>{if(!s)g(this,V,"f").fail(g(this,G,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)g(this,V,"f").fail(s.toString(),s);return n},(s)=>(g(this,V,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return v("<object|string|array> [string|array]",[e,t],arguments.length),this[Ko](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(v("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new fe("coerce callback must be provided");for(let o of e)this.coerce(o,t);return this}else if(typeof e==="object"){for(let o of Object.keys(e))this.coerce(o,e[o]);return this}if(!t)throw new fe("coerce callback must be provided");let n=e;return g(this,J,"f").key[n]=!0,g(this,Ue,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],c=[n,...i].filter((a)=>Object.prototype.hasOwnProperty.call(o,a));if(c.length===0)return o;return Ot(()=>t(o[c[0]]),(a)=>(c.forEach((l)=>{o[l]=a}),o),(a)=>{throw new fe(a.message)})},n),this}conflicts(e,t){return v("<string|object> [string|array]",[e,t],arguments.length),g(this,le,"f").conflicts(e,t),this}config(e="config",t,n){if(v("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=Cn(e,g(this,Pt,"f"),this[Wt]()["deep-merge-config"]||!1,g(this,G,"f")),g(this,J,"f").configObjects=(g(this,J,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||g(this,V,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{g(this,J,"f").config[o]=n||!0}),this}completion(e,t,n){if(v("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(L(this,Pe,e||g(this,Pe,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(g(this,Pe,"f"),t),n)g(this,$e,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return v("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),g(this,pe,"f").addHandler(e,t,n,o,s,r),this}commands(e,t,n,o,s,r){return this.command(e,t,n,o,s,r)}commandDir(e,t){v("<string> [object]",[e,t],arguments.length);let n=g(this,ws,"f")||g(this,G,"f").require;return g(this,pe,"f").addDirectory(e,n,g(this,G,"f").getCallerFile(),t),this}count(e){return v("<array|string>",[e],arguments.length),this[wt]("count",e),this[Jt](e),this}default(e,t,n){if(v("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)Mo(e,g(this,G,"f")),g(this,J,"f").defaultDescription[e]=n;if(typeof t==="function"){if(Mo(e,g(this,G,"f")),!g(this,J,"f").defaultDescription[e])g(this,J,"f").defaultDescription[e]=g(this,V,"f").functionDescription(t);t=t.call()}return this[on](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,o){if(v("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,o],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),g(this,J,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{_e(n,!0,g(this,G,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")_e(n,!0,g(this,G,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{_e(n,!0,g(this,G,"f")),this.demandOption(o,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return v("<object|string|array> [string]",[e,t],arguments.length),this[on](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return v("<string> [string|boolean]",[e,t],arguments.length),g(this,J,"f").deprecatedOptions[e]=t,this}describe(e,t){return v("<object|string|array> [string]",[e,t],arguments.length),this[qo](e,!0),g(this,V,"f").describe(e,t),this}detectLocale(e){return v("<boolean>",[e],arguments.length),L(this,Rt,e,"f"),this}env(e){if(v("[string|boolean]",[e],arguments.length),e===!1)delete g(this,J,"f").envPrefix;else g(this,J,"f").envPrefix=e||"";return this}epilogue(e){return v("<string>",[e],arguments.length),g(this,V,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(v("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else g(this,V,"f").example(e,t);return this}exit(e,t){if(L(this,Re,!0,"f"),L(this,Dt,t,"f"),g(this,We,"f"))g(this,G,"f").process.exit(e)}exitProcess(e=!0){return v("[boolean]",[e],arguments.length),L(this,We,e,"f"),this}fail(e){if(v("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new fe("Invalid first argument. Expected function or boolean 'false'");return g(this,V,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(v("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{g(this,$e,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return g(this,$e,"f").getCompletion(e,t)}getDemandedOptions(){return v([],0),g(this,J,"f").demandedOptions}getDemandedCommands(){return v([],0),g(this,J,"f").demandedCommands}getDeprecatedOptions(){return v([],0),g(this,J,"f").deprecatedOptions}getDetectLocale(){return g(this,Rt,"f")}getExitProcess(){return g(this,We,"f")}getGroups(){return Object.assign({},g(this,st,"f"),g(this,Mt,"f"))}getHelp(){if(L(this,Re,!0,"f"),!g(this,V,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[Sn](g(this,yt,"f"),void 0,void 0,0,!0);if(re(t))return t.then(()=>g(this,V,"f").help())}let e=g(this,pe,"f").runDefaultBuilderOn(this);if(re(e))return e.then(()=>g(this,V,"f").help())}return Promise.resolve(g(this,V,"f").help())}getOptions(){return g(this,J,"f")}getStrict(){return g(this,vt,"f")}getStrictCommands(){return g(this,Lt,"f")}getStrictOptions(){return g(this,jt,"f")}global(e,t){if(v("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)g(this,J,"f").local=g(this,J,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!g(this,J,"f").local.includes(n))g(this,J,"f").local.push(n)});return this}group(e,t){v("<string|array> <string>",[e,t],arguments.length);let n=g(this,Mt,"f")[t]||g(this,st,"f")[t];if(g(this,Mt,"f")[t])delete g(this,Mt,"f")[t];let o={};return g(this,st,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return v("<string>",[e],arguments.length),g(this,J,"f").hiddenOptions.push(e),this}implies(e,t){return v("<string|object> [number|string|array]",[e,t],arguments.length),g(this,le,"f").implies(e,t),this}locale(e){if(v("[string]",[e],arguments.length),e===void 0)return this[Uo](),g(this,G,"f").y18n.getLocale();return L(this,Rt,!1,"f"),g(this,G,"f").y18n.setLocale(e),this}middleware(e,t,n){return g(this,Ue,"f").addMiddleware(e,!!t,n)}nargs(e,t){return v("<string|object|array> [number]",[e,t],arguments.length),this[on](this.nargs.bind(this),"narg",e,t),this}normalize(e){return v("<array|string>",[e],arguments.length),this[wt]("normalize",e),this}number(e){return v("<array|string>",[e],arguments.length),this[wt]("number",e),this[Jt](e),this}option(e,t){if(v("<string|object> [object]",[e,t],arguments.length),typeof e==="object")Object.keys(e).forEach((n)=>{this.options(n,e[n])});else{if(typeof t!=="object")t={};if(this[Jt](e),g(this,ot,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[za](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
79
+ `),void 0,"versionWarning");if(g(this,J,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let o=t.demand||t.required||t.require;if(o)this.demand(e,o);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)g(this,J,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let s=t.describe||t.description||t.desc,r=g(this,V,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(r,e)||typeof s==="string")this.describe(e,s);if(t.hidden)this.hide(e);if(t.requiresArg)this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){if(v("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[qa](),typeof e>"u")e=g(this,yt,"f");if(typeof t==="object")L(this,Bt,t,"f"),t=n;if(typeof t==="function")L(this,Ne,t,"f"),t=!1;if(!t)L(this,yt,e,"f");if(g(this,Ne,"f"))L(this,We,!1,"f");let o=this[Sn](e,!!t),s=this.parsed;if(g(this,$e,"f").setParsed(this.parsed),re(o))return o.then((r)=>{if(g(this,Ne,"f"))g(this,Ne,"f").call(this,g(this,Dt,"f"),r,g(this,ke,"f"));return r}).catch((r)=>{if(g(this,Ne,"f"))g(this,Ne,"f")(r,this.parsed.argv,g(this,ke,"f"));throw r}).finally(()=>{this[Go](),this.parsed=s});else{if(g(this,Ne,"f"))g(this,Ne,"f").call(this,g(this,Dt,"f"),o,g(this,ke,"f"));this[Go](),this.parsed=s}return o}parseAsync(e,t,n){let o=this.parse(e,t,n);return!re(o)?Promise.resolve(o):o}parseSync(e,t,n){let o=this.parse(e,t,n);if(re(o))throw new fe(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return o}parserConfiguration(e){return v("<object>",[e],arguments.length),L(this,bs,e,"f"),this}pkgConf(e,t){v("<string> [string]",[e,t],arguments.length);let n=null,o=this[Jo](t||g(this,Pt,"f"));if(o[e]&&typeof o[e]==="object")n=Cn(o[e],t||g(this,Pt,"f"),this[Wt]()["deep-merge-config"]||!1,g(this,G,"f")),g(this,J,"f").configObjects=(g(this,J,"f").configObjects||[]).concat(n);return this}positional(e,t){v("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=gt(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let o=g(this,En,"f").fullCommands[g(this,En,"f").fullCommands.length-1],s=o?g(this,pe,"f").cmdToParseOptions(o):{array:[],alias:{},default:{},demand:{}};return tn(s).forEach((r)=>{let i=s[r];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[r]=!0}else if(i[e]&&!(r in t))t[r]=i[e]}),this.group(e,g(this,V,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return v("[boolean]",[e],arguments.length),L(this,ks,e,"f"),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){if(v("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&g(this,J,"f").narg[e])return this;else this[on](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return v("[string] [string]",[e,t],arguments.length),e=e||this.$0,g(this,Nt,"f").log(g(this,$e,"f").generateCompletionScript(e,t||g(this,Pe,"f")||"completion")),this}showHelp(e){if(v("[string|function]",[e],arguments.length),L(this,Re,!0,"f"),!g(this,V,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[Sn](g(this,yt,"f"),void 0,void 0,0,!0);if(re(n))return n.then(()=>{g(this,V,"f").showHelp(e)}),this}let t=g(this,pe,"f").runDefaultBuilderOn(this);if(re(t))return t.then(()=>{g(this,V,"f").showHelp(e)}),this}return g(this,V,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return v("[boolean|string] [string]",[e,t],arguments.length),g(this,V,"f").showHelpOnFail(e,t),this}showVersion(e){return v("[string|function]",[e],arguments.length),g(this,V,"f").showVersion(e),this}skipValidation(e){return v("<array|string>",[e],arguments.length),this[wt]("skipValidation",e),this}strict(e){return v("[boolean]",[e],arguments.length),L(this,vt,e!==!1,"f"),this}strictCommands(e){return v("[boolean]",[e],arguments.length),L(this,Lt,e!==!1,"f"),this}strictOptions(e){return v("[boolean]",[e],arguments.length),L(this,jt,e!==!1,"f"),this}string(e){return v("<array|string>",[e],arguments.length),this[wt]("string",e),this[Jt](e),this}terminalWidth(){return v([],0),g(this,G,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return v("<object>",[e],arguments.length),L(this,Rt,!1,"f"),g(this,G,"f").y18n.updateLocale(e),this}usage(e,t,n,o){if(v("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,o],arguments.length),t!==void 0)if(_e(e,null,g(this,G,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,o);else throw new fe(".usage() description must start with $0 if being used as alias for .command()");else return g(this,V,"f").usage(e),this}usageConfiguration(e){return v("<object>",[e],arguments.length),L(this,xs,e,"f"),this}version(e,t,n){if(v("[boolean|string] [string] [string]",[e,t,n],arguments.length),g(this,ot,"f"))this[Wo](g(this,ot,"f")),g(this,V,"f").version(void 0),L(this,ot,null,"f");if(arguments.length===0)n=this[Ya](),e="version";else if(arguments.length===1){if(e===!1)return this;n=e,e="version"}else if(arguments.length===2)n=t,t=void 0;return L(this,ot,typeof e==="string"?e:"version","f"),t=t||g(this,V,"f").deferY18nLookup("Show version number"),g(this,V,"f").version(n||void 0),this.boolean(g(this,ot,"f")),this.describe(g(this,ot,"f"),t),this}wrap(e){return v("<number|null|undefined>",[e],arguments.length),g(this,V,"f").wrap(e),this}[(pe=new WeakMap,Pt=new WeakMap,En=new WeakMap,$e=new WeakMap,Pe=new WeakMap,gs=new WeakMap,Dt=new WeakMap,Rt=new WeakMap,ms=new WeakMap,We=new WeakMap,Ds=new WeakMap,Ue=new WeakMap,st=new WeakMap,Re=new WeakMap,Je=new WeakMap,ys=new WeakMap,Nt=new WeakMap,ke=new WeakMap,J=new WeakMap,ws=new WeakMap,bs=new WeakMap,Ne=new WeakMap,Bt=new WeakMap,sn=new WeakMap,Mt=new WeakMap,yt=new WeakMap,ks=new WeakMap,G=new WeakMap,vt=new WeakMap,Lt=new WeakMap,jt=new WeakMap,V=new WeakMap,xs=new WeakMap,ot=new WeakMap,le=new WeakMap,Ka)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[Ha](){return{log:(...e)=>{if(!this[Cs]())console.log(...e);if(L(this,Re,!0,"f"),g(this,ke,"f").length)L(this,ke,g(this,ke,"f")+`
80
+ `,"f");L(this,ke,g(this,ke,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[Cs]())console.error(...e);if(L(this,Re,!0,"f"),g(this,ke,"f").length)L(this,ke,g(this,ke,"f")+`
81
+ `,"f");L(this,ke,g(this,ke,"f")+e.join(" "),"f")}}}[Wo](e){tn(g(this,J,"f")).forEach((t)=>{if(((o)=>o==="configObjects")(t))return;let n=g(this,J,"f")[t];if(Array.isArray(n)){if(n.includes(e))n.splice(n.indexOf(e),1)}else if(typeof n==="object")delete n[e]}),delete g(this,V,"f").getDescriptions()[e]}[za](e,t,n){if(!g(this,ms,"f")[n])g(this,G,"f").process.emitWarning(e,t),g(this,ms,"f")[n]=!0}[qa](){g(this,Ds,"f").push({options:g(this,J,"f"),configObjects:g(this,J,"f").configObjects.slice(0),exitProcess:g(this,We,"f"),groups:g(this,st,"f"),strict:g(this,vt,"f"),strictCommands:g(this,Lt,"f"),strictOptions:g(this,jt,"f"),completionCommand:g(this,Pe,"f"),output:g(this,ke,"f"),exitError:g(this,Dt,"f"),hasOutput:g(this,Re,"f"),parsed:this.parsed,parseFn:g(this,Ne,"f"),parseContext:g(this,Bt,"f")}),g(this,V,"f").freeze(),g(this,le,"f").freeze(),g(this,pe,"f").freeze(),g(this,Ue,"f").freeze()}[Ga](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(g(this,G,"f").process.argv()[0]))t=g(this,G,"f").process.argv().slice(1,2);else t=g(this,G,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let o=this[ac](g(this,Pt,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&o.length<n.length?o:n}).join(" ").trim(),g(this,G,"f").getEnv("_")&&g(this,G,"f").getProcessArgvBin()===g(this,G,"f").getEnv("_"))e=g(this,G,"f").getEnv("_").replace(`${g(this,G,"f").path.dirname(g(this,G,"f").process.execPath())}/`,"");return e}[Wt](){return g(this,bs,"f")}[Xa](){return g(this,xs,"f")}[Uo](){if(!g(this,Rt,"f"))return;let e=g(this,G,"f").getEnv("LC_ALL")||g(this,G,"f").getEnv("LC_MESSAGES")||g(this,G,"f").getEnv("LANG")||g(this,G,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[Ya](){return this[Jo]().version||"unknown"}[Va](e){let t=e["--"]?e["--"]:e._;for(let n=0,o;(o=t[n])!==void 0;n++)if(g(this,G,"f").Parser.looksLikeNumber(o)&&Number.isSafeInteger(Math.floor(parseFloat(`${o}`))))t[n]=Number(o);return e}[Jo](e){let t=e||"*";if(g(this,sn,"f")[t])return g(this,sn,"f")[t];let n={};try{let o=e||g(this,G,"f").mainFilename;if(g(this,G,"f").path.extname(o))o=g(this,G,"f").path.dirname(o);let s=g(this,G,"f").findUp(o,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});_e(s,void 0,g(this,G,"f")),n=JSON.parse(g(this,G,"f").readFileSync(s,"utf8"))}catch(o){}return g(this,sn,"f")[t]=n||{},g(this,sn,"f")[t]}[wt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[zo](n),g(this,J,"f")[e].push(n)})}[on](e,t,n,o){this[Ho](e,t,n,o,(s,r,i)=>{g(this,J,"f")[s][r]=i})}[Ko](e,t,n,o){this[Ho](e,t,n,o,(s,r,i)=>{g(this,J,"f")[s][r]=(g(this,J,"f")[s][r]||[]).concat(i)})}[Ho](e,t,n,o,s){if(Array.isArray(n))n.forEach((r)=>{e(r,o)});else if(((r)=>typeof r==="object")(n))for(let r of tn(n))e(r,n[r]);else s(t,this[zo](n),o)}[zo](e){if(e==="__proto__")return"___proto___";return e}[qo](e,t){return this[on](this[qo].bind(this),"key",e,t),this}[Go](){var e,t,n,o,s,r,i,c,a,l,u,d;let f=g(this,Ds,"f").pop();_e(f,void 0,g(this,G,"f"));let h;e=this,t=this,n=this,o=this,s=this,r=this,i=this,c=this,a=this,l=this,u=this,d=this,{options:{set value(m){L(e,J,m,"f")}}.value,configObjects:h,exitProcess:{set value(m){L(t,We,m,"f")}}.value,groups:{set value(m){L(n,st,m,"f")}}.value,output:{set value(m){L(o,ke,m,"f")}}.value,exitError:{set value(m){L(s,Dt,m,"f")}}.value,hasOutput:{set value(m){L(r,Re,m,"f")}}.value,parsed:this.parsed,strict:{set value(m){L(i,vt,m,"f")}}.value,strictCommands:{set value(m){L(c,Lt,m,"f")}}.value,strictOptions:{set value(m){L(a,jt,m,"f")}}.value,completionCommand:{set value(m){L(l,Pe,m,"f")}}.value,parseFn:{set value(m){L(u,Ne,m,"f")}}.value,parseContext:{set value(m){L(d,Bt,m,"f")}}.value}=f,g(this,J,"f").configObjects=h,g(this,V,"f").unfreeze(),g(this,le,"f").unfreeze(),g(this,pe,"f").unfreeze(),g(this,Ue,"f").unfreeze()}[Za](e,t){return Ot(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[Qa].bind(this),getContext:this[ec].bind(this),getHasOutput:this[tc].bind(this),getLoggerInstance:this[nc].bind(this),getParseContext:this[sc].bind(this),getParserConfiguration:this[Wt].bind(this),getUsageConfiguration:this[Xa].bind(this),getUsageInstance:this[oc].bind(this),getValidationInstance:this[rc].bind(this),hasParseCallback:this[Cs].bind(this),isGlobalContext:this[ic].bind(this),postProcess:this[Ut].bind(this),reset:this[Xo].bind(this),runValidation:this[Yo].bind(this),runYargsParserAndExecuteCommands:this[Sn].bind(this),setHasOutput:this[cc].bind(this)}}[Qa](){return g(this,pe,"f")}[ec](){return g(this,En,"f")}[tc](){return g(this,Re,"f")}[nc](){return g(this,Nt,"f")}[sc](){return g(this,Bt,"f")||{}}[oc](){return g(this,V,"f")}[rc](){return g(this,le,"f")}[Cs](){return!!g(this,Ne,"f")}[ic](){return g(this,ys,"f")}[Ut](e,t,n,o){if(n)return e;if(re(e))return e;if(!t)e=this[Ka](e);if(this[Wt]()["parse-positional-numbers"]||this[Wt]()["parse-positional-numbers"]===void 0)e=this[Va](e);if(o)e=It(e,this,g(this,Ue,"f").getMiddleware(),!1);return e}[Xo](e={}){L(this,J,g(this,J,"f")||{},"f");let t={};t.local=g(this,J,"f").local||[],t.configObjects=g(this,J,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(g(this,Mt,"f"),Object.keys(g(this,st,"f")).reduce((r,i)=>{let c=g(this,st,"f")[i].filter((a)=>!(a in n));if(c.length>0)r[i]=c;return r},{})),L(this,st,{},"f");let o=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],s=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(o.forEach((r)=>{t[r]=(g(this,J,"f")[r]||[]).filter((i)=>!n[i])}),s.forEach((r)=>{t[r]=gt(g(this,J,"f")[r],(i)=>!n[i])}),t.envPrefix=g(this,J,"f").envPrefix,L(this,J,t,"f"),L(this,V,g(this,V,"f")?g(this,V,"f").reset(n):Na(this,g(this,G,"f")),"f"),L(this,le,g(this,le,"f")?g(this,le,"f").reset(n):Ua(this,g(this,V,"f"),g(this,G,"f")),"f"),L(this,pe,g(this,pe,"f")?g(this,pe,"f").reset():Oa(g(this,V,"f"),g(this,le,"f"),g(this,Ue,"f"),g(this,G,"f")),"f"),!g(this,$e,"f"))L(this,$e,La(this,g(this,V,"f"),g(this,pe,"f"),g(this,G,"f")),"f");return g(this,Ue,"f").reset(),L(this,Pe,null,"f"),L(this,ke,"","f"),L(this,Dt,null,"f"),L(this,Re,!1,"f"),this.parsed=!1,this}[ac](e,t){return g(this,G,"f").path.relative(e,t)}[Sn](e,t,n,o=0,s=!1){var r,i,c,a;let l=!!n||s;e=e||g(this,yt,"f"),g(this,J,"f").__=g(this,G,"f").y18n.__,g(this,J,"f").configuration=this[Wt]();let u=!!g(this,J,"f").configuration["populate--"],d=Object.assign({},g(this,J,"f").configuration,{"populate--":!0}),f=g(this,G,"f").Parser.detailed(e,Object.assign({},g(this,J,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),h=Object.assign(f.argv,g(this,Bt,"f")),m=void 0,p=f.aliases,D=!1,x=!1;if(Object.keys(h).forEach((b)=>{if(b===g(this,Je,"f")&&h[b])D=!0;else if(b===g(this,ot,"f")&&h[b])x=!0}),h.$0=this.$0,this.parsed=f,o===0)g(this,V,"f").clearCachedHelpMessage();try{if(this[Uo](),t)return this[Ut](h,u,!!n,!1);if(g(this,Je,"f")){if([g(this,Je,"f")].concat(p[g(this,Je,"f")]||[]).filter((j)=>j.length>1).includes(""+h._[h._.length-1]))h._.pop(),D=!0}L(this,ys,!1,"f");let b=g(this,pe,"f").getCommands(),_=((r=g(this,$e,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=g(this,$e,"f"))===null||i===void 0?void 0:i.completionKey,...(a=this.getAliases()[(c=g(this,$e,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&a!==void 0?a:[]].some((N)=>Object.prototype.hasOwnProperty.call(h,N)):!1,A=D||_||s;if(h._.length){if(b.length){let N;for(let j=o||0,O;h._[j]!==void 0;j++)if(O=String(h._[j]),b.includes(O)&&O!==g(this,Pe,"f")){let K=g(this,pe,"f").runCommand(O,this,f,j+1,s,D||x||s);return this[Ut](K,u,!!n,!1)}else if(!N&&O!==g(this,Pe,"f")){N=O;break}if(!g(this,pe,"f").hasDefaultCommand()&&g(this,ks,"f")&&N&&!A)g(this,le,"f").recommendCommands(N,b)}if(g(this,Pe,"f")&&h._.includes(g(this,Pe,"f"))&&!_){if(g(this,We,"f"))mt(!0);this.showCompletionScript(),this.exit(0)}}if(g(this,pe,"f").hasDefaultCommand()&&!A){let N=g(this,pe,"f").runCommand(null,this,f,0,s,D||x||s);return this[Ut](N,u,!!n,!1)}if(_){if(g(this,We,"f"))mt(!0);e=[].concat(e);let N=e.slice(e.indexOf(`--${g(this,$e,"f").completionKey}`)+1);return g(this,$e,"f").getCompletion(N,(j,O)=>{if(j)throw new fe(j.message);(O||[]).forEach((K)=>{g(this,Nt,"f").log(K)}),this.exit(0)}),this[Ut](h,!u,!!n,!1)}if(!g(this,Re,"f")){if(D){if(g(this,We,"f"))mt(!0);l=!0,this.showHelp((N)=>{g(this,Nt,"f").log(N),this.exit(0)})}else if(x){if(g(this,We,"f"))mt(!0);l=!0,g(this,V,"f").showVersion("log"),this.exit(0)}}if(!l&&g(this,J,"f").skipValidation.length>0)l=Object.keys(h).some((N)=>g(this,J,"f").skipValidation.indexOf(N)>=0&&h[N]===!0);if(!l){if(f.error)throw new fe(f.error.message);if(!_){let N=this[Yo](p,{},f.error);if(!n)m=It(h,this,g(this,Ue,"f").getMiddleware(),!0);if(m=this[Za](N,m!==null&&m!==void 0?m:h),re(m)&&!n)m=m.then(()=>It(h,this,g(this,Ue,"f").getMiddleware(),!1))}}}catch(b){if(b instanceof fe)g(this,V,"f").fail(b.message,b);else throw b}return this[Ut](m!==null&&m!==void 0?m:h,u,!!n,!0)}[Yo](e,t,n,o){let s={...this.getDemandedOptions()};return(r)=>{if(n)throw new fe(n.message);g(this,le,"f").nonOptionCount(r),g(this,le,"f").requiredArguments(r,s);let i=!1;if(g(this,Lt,"f"))i=g(this,le,"f").unknownCommands(r);if(g(this,vt,"f")&&!i)g(this,le,"f").unknownArguments(r,e,t,!!o);else if(g(this,jt,"f"))g(this,le,"f").unknownArguments(r,e,{},!1,!1);g(this,le,"f").limitedChoices(r),g(this,le,"f").implications(r),g(this,le,"f").conflicting(r)}}[cc](){L(this,Re,!0,"f")}[Jt](e){if(typeof e==="string")g(this,J,"f").key[e]=!0;else for(let t of e)g(this,J,"f").key[t]=!0}}function Pa(e){return!!e&&typeof e.getInternalMethods==="function"}var jf=lc(Bo),dc=jf;function Wf(e){return[...e.matchAll(/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <]+/gi)].map(([n])=>n).filter((n)=>!n.startsWith("<")&&(/[^\x00-\x7f]/.test(n)||n.includes(">")))}function bt(e,t=!1,n=console.error){let o=Wf(e);if(!o.length)return;let s=`Ambiguous URL boundary: ${o.map((r)=>JSON.stringify(r)).join(", ")}. Put the URL on its own line, or wrap it as <url> / <url|label>. Use --allow-url-adjacent to warn only.`;if(!t)throw Error(s);n(`Warning: ${s}`)}import{existsSync as _n,readFileSync as Qo,writeFileSync as Vo,mkdirSync as gc,chmodSync as fc}from"node:fs";import{homedir as Uf}from"node:os";import{join as Kt,dirname as er}from"node:path";function tr(){return process.env.HOME||Uf()}function mc(){return Kt(tr(),".config","slack-cli","profiles.json")}function Es(){return Kt(process.cwd(),".slack-cli","workspace")}function Ss(){return Kt(tr(),".slack-cli","workspace")}function $n(){let e=mc();if(!_n(e))return{profiles:{}};return JSON.parse(Qo(e,"utf8"))}function Jf(e){let t=mc();if(gc(er(t),{recursive:!0}),process.platform!=="win32"&&_n(t))fc(t,384);if(Vo(t,JSON.stringify(e,null,2)+`
82
+ `,{mode:384}),process.platform!=="win32")fc(t,384)}function rn(e){if(!_n(e))return;return Qo(e,"utf8").trim()||void 0}function pc(e,t){let n=er(e);gc(n,{recursive:!0});let o=Kt(n,".gitignore");if(!_n(o))Vo(o,`*
83
+ `);Vo(e,t+`
84
+ `)}function Kf(e){let t={};for(let n of e.split(`
85
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function hc(e){if(!_n(e))return{};try{return Kf(Qo(e,"utf8"))}catch{return{}}}function Zo(e,t){let n=tr(),o=e;while(!0){for(let i of[Kt(o,".slack-term",".env.local"),Kt(o,".env.local")]){let c=hc(i);for(let a of t)if(c[a])return c[a]}if(o===n)break;let r=er(o);if(r===o)break;o=r}let s=hc(Kt(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function nr(){let e=$n(),t=rn(Es()),n=rn(Ss()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Fn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Fn(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function Dc(e){let t=$n();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],Jf(t)}function yc(e,t=!1){let n=$n();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)pc(Ss(),e);else pc(Es(),e)}function An(e){let n=$n().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=Zo(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
86
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Zo(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let c=process.env.SLACK_WORKSPACE;if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let a=rn(Es());if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=rn(Ss());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
87
87
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
88
88
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
89
89
  Run one of:
@@ -92,13 +92,13 @@ ${m.join(`
92
92
  `+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
93
93
  `+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
94
94
  `+` slack auth token --token xoxp-... — paste an existing token
95
- `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function wt(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Qo(e){let t=$n(),n=t.profiles;if(e)return Sn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=Go(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Sn(t,r);let i=on(Cs());if(i)return Sn(t,i);let c=on(Es());if(c)return Sn(t,c);return}import{existsSync as an,readFileSync as Fs,writeFileSync as dc,mkdirSync as fc,chmodSync as xs}from"node:fs";import{homedir as Sf}from"node:os";import{join as rn,dirname as tr}from"node:path";function nr(){return process.env.HOME||Sf()}function pc(){return rn(nr(),".config","slack-cli","profiles.json")}function sr(){return rn(process.cwd(),".slack-cli","workspace")}function or(){return rn(nr(),".slack-cli","workspace")}function ln(){let e=pc();if(!an(e))return{profiles:{}};return JSON.parse(Fs(e,"utf8"))}function rr(e){let t=pc();if(fc(tr(t),{recursive:!0}),process.platform!=="win32"&&an(t))xs(t,384);if(dc(t,JSON.stringify(e,null,2)+`
96
- `,{mode:384}),process.platform!=="win32")xs(t,384)}function cn(e){if(!an(e))return;return Fs(e,"utf8").trim()||void 0}function _f(e){let t={};for(let n of e.split(`
97
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function uc(e){if(!an(e))return{};try{return _f(Fs(e,"utf8"))}catch{return{}}}function er(e,t){let n=nr(),o=e;while(!0){for(let i of[rn(o,".slack-term",".env.local"),rn(o,".env.local")]){let c=uc(i);for(let a of t)if(c[a])return c[a]}if(o===n)break;let r=tr(o);if(r===o)break;o=r}let s=uc(rn(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function ir(e,t){fc(tr(e),{recursive:!0});let n=an(e)?Fs(e,"utf8"):"",o=n?n.split(`
98
- `):[];for(let[s,r]of Object.entries(t)){let i=o.findIndex((a)=>{let l=a.trim();return l.startsWith(s+"=")||l.startsWith(s+" =")}),c=`${s}=${r}`;if(i!==-1)o[i]=c;else o.push(c)}if(process.platform!=="win32"&&an(e))xs(e,384);if(dc(e,o.join(`
95
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function ct(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function sr(e){let t=$n(),n=t.profiles;if(e)return Fn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=Zo(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Fn(t,r);let i=rn(Es());if(i)return Fn(t,i);let c=rn(Ss());if(c)return Fn(t,c);return}import{existsSync as cn,readFileSync as _s,writeFileSync as bc,mkdirSync as kc,chmodSync as Fs}from"node:fs";import{homedir as Hf}from"node:os";import{join as an,dirname as rr}from"node:path";function ir(){return process.env.HOME||Hf()}function xc(){return an(ir(),".config","slack-cli","profiles.json")}function ar(){return an(process.cwd(),".slack-cli","workspace")}function cr(){return an(ir(),".slack-cli","workspace")}function un(){let e=xc();if(!cn(e))return{profiles:{}};return JSON.parse(_s(e,"utf8"))}function lr(e){let t=xc();if(kc(rr(t),{recursive:!0}),process.platform!=="win32"&&cn(t))Fs(t,384);if(bc(t,JSON.stringify(e,null,2)+`
96
+ `,{mode:384}),process.platform!=="win32")Fs(t,384)}function ln(e){if(!cn(e))return;return _s(e,"utf8").trim()||void 0}function zf(e){let t={};for(let n of e.split(`
97
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function wc(e){if(!cn(e))return{};try{return zf(_s(e,"utf8"))}catch{return{}}}function or(e,t){let n=ir(),o=e;while(!0){for(let i of[an(o,".slack-term",".env.local"),an(o,".env.local")]){let c=wc(i);for(let a of t)if(c[a])return c[a]}if(o===n)break;let r=rr(o);if(r===o)break;o=r}let s=wc(an(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function ur(e,t){kc(rr(e),{recursive:!0});let n=cn(e)?_s(e,"utf8"):"",o=n?n.split(`
98
+ `):[];for(let[s,r]of Object.entries(t)){let i=o.findIndex((a)=>{let l=a.trim();return l.startsWith(s+"=")||l.startsWith(s+" =")}),c=`${s}=${r}`;if(i!==-1)o[i]=c;else o.push(c)}if(process.platform!=="win32"&&cn(e))Fs(e,384);if(bc(e,o.join(`
99
99
  `).trimEnd()+`
100
- `,{mode:384}),process.platform!=="win32")xs(e,384)}function On(){let e=ln(),t=cn(sr()),n=cn(or()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Tn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Ss(e,t){let n=ln();if(t.identity&&t.cookie){n.users??={};let o=n.users[t.identity]??{};n.users[t.identity]={...o,cookie:t.cookie};let{cookie:s,...r}=t;n.profiles[e]=r}else n.profiles[e]=t;rr(n)}function ar(e,t){let n=ln(),o=n.profiles[e];if(!o)throw Error(`Profile not found: ${e}`);if(o.identity)n.users??={},n.users[o.identity]={...n.users[o.identity]??{},cookie:t};else o.cookie=t;rr(n)}function hc(e,t,n){let o=ln();o.users??={},o.users[e]={...o.users[e]??{},cookie:t,...n?{source:n}:{}},rr(o)}function Tn(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function gc(e){let n=ln().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=er(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
101
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=er(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let c=process.env.SLACK_WORKSPACE;if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let a=cn(sr());if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=cn(or());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
100
+ `,{mode:384}),process.platform!=="win32")Fs(e,384)}function In(){let e=un(),t=ln(ar()),n=ln(cr()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Tn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function $s(e,t){let n=un();if(t.identity&&t.cookie){n.users??={};let o=n.users[t.identity]??{};n.users[t.identity]={...o,cookie:t.cookie};let{cookie:s,...r}=t;n.profiles[e]=r}else n.profiles[e]=t;lr(n)}function dr(e,t){let n=un(),o=n.profiles[e];if(!o)throw Error(`Profile not found: ${e}`);if(o.identity)n.users??={},n.users[o.identity]={...n.users[o.identity]??{},cookie:t};else o.cookie=t;lr(n)}function Cc(e,t,n){let o=un();o.users??={},o.users[e]={...o.users[e]??{},cookie:t,...n?{source:n}:{}},lr(o)}function Tn(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function Ec(e){let n=un().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=or(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
101
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=or(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let c=process.env.SLACK_WORKSPACE;if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let a=ln(ar());if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=ln(cr());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
102
102
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
103
103
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
104
104
  Run one of:
@@ -107,31 +107,31 @@ ${m.join(`
107
107
  `+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
108
108
  `+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
109
109
  `+` slack auth token --token xoxp-... — paste an existing token
110
- `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function _s(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function bt(e){let t=ln(),n=t.profiles;if(e)return Tn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=er(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Tn(t,r);let i=cn(sr());if(i)return Tn(t,i);let c=cn(or());if(c)return Tn(t,c);return}class Ze extends Error{retryAfter;constructor(e){super(`Slack rate limited — retry after ${e}s`);this.name="RateLimitError",this.retryAfter=e}}function lr(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function ur(e,t,n,o){o=e.startsWith("xoxc-")?o??bt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${lr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new Ze(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new Ze(60);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
110
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function As(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function kt(e){let t=un(),n=t.profiles;if(e)return Tn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=or(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Tn(t,r);let i=ln(ar());if(i)return Tn(t,i);let c=ln(cr());if(c)return Tn(t,c);return}class Ze extends Error{retryAfter;constructor(e){super(`Slack rate limited — retry after ${e}s`);this.name="RateLimitError",this.retryAfter=e}}function pr(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function hr(e,t,n,o){o=e.startsWith("xoxc-")?o??kt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${pr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new Ze(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new Ze(60);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
111
111
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
112
112
  Or replace the token with an xoxp- user token:
113
113
  slack auth login`);if((c==="missing_scope"||c==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${c}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${c} — ${c==="cannot_dm_bot"?`you're authenticated as a bot, so "@you" is the bot itself and it can't DM itself`:"this bot token lacks the user scope this action needs"}.
114
114
  Tailing/DMing people and listing users need a user session, not a bot token.
115
115
  Switch workspace: slack auth ls then slack auth use <name>
116
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}`)}return i}async function $f(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${lr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new Ze(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new Ze(60);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`The draft API requires a desktop app session token (xoxc-).
116
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}`)}return i}async function qf(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${pr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new Ze(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new Ze(60);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`The draft API requires a desktop app session token (xoxc-).
117
117
  Import from Slack desktop: slack auth login`);if((c==="invalid_auth"||c==="not_authed")&&!o)throw Error(`drafts.list also requires the xoxd session cookie.
118
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}`)}return i}function Af(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return $f(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function be(e,t,n,o){let s=new URLSearchParams(n).toString();return ur(e,`${t}?${s}`,{method:"GET"},o)}function dr(e,t,n,o){return ur(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function wc(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return ur(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Pn(e,t,n){return wc(e,"agents.sessions.setStatus",{...t,status:n})}function fr(e,t,n){return wc(e,"agents.sessions.rename",{...t,title:n})}async function un(e,t){let n=await be(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function bc(e,t){t=e.startsWith("xoxc-")?t??bt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${lr()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new Ze(isNaN(i)?60:i)}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function kc(e,t,n){let o=await be(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function Rn(e,t,n=20,o,s,r,i){let c={channel:t,limit:String(n)};if(o!==void 0)c.oldest=o;if(s!==void 0)c.cursor=s;if(i)c.inclusive="true";return be(e,"conversations.history",c,r)}async function Cc(e,t,n,o=50,s){return be(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function $s(e,t,n,o,s){await dr(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Ec(e,t,n,o){return((await be(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function As(e,t,n,o,s){await dr(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function Tf(e,t,n){let s=(await dr(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function xc(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await be(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function cr(e,t,n,o){let s=await xc(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function In(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function mc(e,t){let n=In(e.name??""),o=In(e.real_name??e.profile?.real_name??""),s=In(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Fc=200;async function Of(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await be(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(mc(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,c=0,a=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await be(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Fc){a=!0;break}s.add(h),i++;let m;try{m=(await be(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof Ze)throw p;c++;continue}if(m&&mc(m,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:c,capped:a}}if(a)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:c,capped:a}}function If(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
118
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}`)}return i}function Gf(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return qf(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function Ee(e,t,n,o){let s=new URLSearchParams(n).toString();return hr(e,`${t}?${s}`,{method:"GET"},o)}function gr(e,t,n,o){return hr(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function $c(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return hr(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Pn(e,t,n){return $c(e,"agents.sessions.setStatus",{...t,status:n})}function mr(e,t,n){return $c(e,"agents.sessions.rename",{...t,title:n})}async function dn(e,t){let n=await Ee(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Ac(e,t){t=e.startsWith("xoxc-")?t??kt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${pr()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new Ze(isNaN(i)?60:i)}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Tc(e,t,n){let o=await Ee(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function Rn(e,t,n=20,o,s,r,i){let c={channel:t,limit:String(n)};if(o!==void 0)c.oldest=o;if(s!==void 0)c.cursor=s;if(i)c.inclusive="true";return Ee(e,"conversations.history",c,r)}async function Ic(e,t,n,o=50,s){return Ee(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Ts(e,t,n,o,s){await gr(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Oc(e,t,n,o){return((await Ee(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Is(e,t,n,o,s){await gr(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function Xf(e,t,n){let s=(await gr(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Pc(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await Ee(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function fr(e,t,n,o){let s=await Pc(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function On(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Sc(e,t){let n=On(e.name??""),o=On(e.real_name??e.profile?.real_name??""),s=On(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Rc=200;async function Yf(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await Ee(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(Sc(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,c=0,a=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await Ee(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Rc){a=!0;break}s.add(h),i++;let m;try{m=(await Ee(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof Ze)throw p;c++;continue}if(m&&Sc(m,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:c,capped:a}}if(a)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:c,capped:a}}function Vf(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
119
119
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
120
- Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${Fc} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
120
+ Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${Rc} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
121
121
  `+(o.length?`This search was incomplete: ${o.join("; ")}.
122
122
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
123
123
  DMed you they cannot be found by name at all. Look them up and use their ID:
124
- slack user ls --external`)}function pr(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function Pf(e){return pr(e)?.channel}function Dc(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function yc(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Ts(e,t,n){let o=Pf(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Dc(t))return t;if(yc(t))return cr(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Dc(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=In(r);if(s){if(yc(r))return cr(e,r,n);let l=await be(e,"auth.test",{},n);if(i==="you"||i==="me"||In(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await xc(e,f,n)||Tf(e,f,n)}let d=await Of(e,i,n);if(!d.id)throw If(t,d);if(d.dm)return d.dm;return cr(e,d.id,n,t)}let c=r.toLowerCase(),a="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(a)l.cursor=a;let u=await be(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===c)return String(d.id??"");if(a=u.response_metadata?.next_cursor??"",!a)break}throw Error(`channel not found: ${t}`)}async function Os(e,t,n){try{let o=await be(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Is(e,t,n){try{let o=await be(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function Ps(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await be(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function hr(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await be(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function gr(e,t,n){return be(e,"users.info",{user:t},n)}async function Sc(e,t,n){return be(e,"conversations.info",{channel:t},n)}async function _c(e,t){let n=await Af(e,"client.boot",{},t),o=typeof n.url==="string"?n.url:void 0;if(!o){let r=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${r}`)}let s=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:o,selfId:typeof s.id==="string"?s.id:""}}var Rf=["chat:write","im:write"],Nf=["im:history","im:read"];async function Rs(e){let{userId:t,botId:n,team:o,scopes:s}=await bc(e),r="";if(n)try{r=(await kc(e,n)).appId}catch{r=""}let i=(l)=>s.includes(l),c=Rf.filter((l)=>!i(l)),a=Nf.filter((l)=>!i(l));return{canSend:c.length===0,canReceiveReplies:a.length===0,ok:c.length===0&&a.length===0,botUserId:t,appId:r,team:o,grantedScopes:s,missingSendScopes:c,missingReplyScopes:a}}function $c(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function Ns(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let s=["✓ Bot DM scopes are complete (send + read replies)."," Two-way replies also require the Messages Tab, which is not API-detectable.",' If recipients see "Sending messages to this app is turned off", enable it:',` ${n} → App Home → "Messages Tab" ON + "Allow users to send messages".`];return t?s:[...s,...$c(e)]}let o=[];if(!e.canSend)o.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else o.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return o.push(" Make escalation DMs two-way:"),o.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),o.push(' "Allow users to send Slash commands and messages".'),o.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),o.push(" 3. Reinstall the app to apply the new scopes."),t?o:[...o,...$c(e)]}import{createInterface as $e}from"node:readline/promises";import{join as Fr,resolve as ap}from"node:path";import{homedir as cp}from"node:os";import{readdirSync as Mn,readFileSync as Bn,existsSync as Ne,copyFileSync as yr,mkdtempSync as Ic,rmSync as Pc}from"node:fs";import{homedir as Ms,tmpdir as Rc}from"node:os";import{join as te,dirname as vf}from"node:path";import{pbkdf2Sync as Bs,createDecipheriv as Nc,createHash as Lf,timingSafeEqual as jf}from"node:crypto";import{execSync as Bc,execFileSync as Wf}from"node:child_process";function Nn(e,t){let n=0,o=0,s=t;while(s<e.length){let r=e[s++];if(n+=(r&127)*2**o,(r&128)===0)break;o+=7}return{value:n,pos:s}}function Bf(e){let t=0,n=0,o=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**o,(i&128)===0)break;o+=7}let s=Buffer.allocUnsafe(n),r=0;while(t<e.length&&r<n){let i=e[t++],c=i&3;if(c===0){let a=i>>2;if(a>=60){let l=a-59;a=0;for(let u=0;u<l;u++)a+=e[t++]*2**(8*u)}a+=1,e.copy(s,r,t,t+a),t+=a,r+=a}else{let a,l;if(c===1)a=4+(i>>2&7),l=(i>>5&7)*256+e[t++];else if(c===2)a=1+(i>>2),l=e[t]+e[t+1]*256,t+=2;else a=1+(i>>2),l=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let u=r-l;for(let d=0;d<a&&r<n;d++)s[r++]=s[u++]}}return r===n?s:s.subarray(0,r)}function mr(e,t){let n=Nn(e,t),o=Nn(e,n.pos);return{handle:{offset:n.value,size:o.value},pos:o.pos}}function Ac(e,t){let{offset:n,size:o}=t,s=e.subarray(n,n+o);return e[n+o]===1?Bf(s):Buffer.from(s)}function Mf(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,o=[],s=0,r=Buffer.alloc(0);while(s<n){let i=Nn(e,s),c=Nn(e,i.pos),a=Nn(e,c.pos);s=a.pos;let l=i.value,u=c.value,d=a.value,f=e.subarray(s,s+u);s+=u;let h=e.subarray(s,s+d);s+=d,r=Buffer.concat([r.subarray(0,l),f]),o.push(h)}return o}function Tc(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=mr(e,t),o=mr(e,n.pos),s=Ac(e,o.handle),r=[];for(let i of Mf(s))try{let{handle:c}=mr(i,0);r.push(Ac(e,c))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function Oc(){let e=process.env.HOME??Ms();if(process.platform==="darwin")return[te(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[te(e,".config","Slack","Local Storage","leveldb"),te(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),te(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??te(e,"AppData","Roaming");return[te(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Uf(){let e=process.env.HOME??Ms();if(process.platform==="darwin")return te(e,"Library","Application Support","Slack","Cookies");return""}function Kf(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),o=e.slice(35),s=Nc("aes-128-cbc",t,n);return s.setAutoPadding(!0),Buffer.concat([s.update(o),s.final()]).toString("utf8")}function Jf(){if(process.platform!=="darwin")return;let e=Uf();if(!Ne(e))return;let t;try{t=Bc('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=Bs(t,"saltysalt",1003,16,"sha1");try{let{default:o}=bn("bun:sqlite"),s=new o(e,{readonly:!0}),r=s.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(s.close(),!r)return;return Kf(Buffer.from(r.encrypted_value),n)}catch{return}}function Mc(e){if(!Ne(e))return[];let t=Mn(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,o=(i)=>{let c=n.get(i);if(c!==void 0)return c;let a="";try{let l=Bn(te(e,i));a=i.endsWith(".ldb")?Tc(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{a=""}return n.set(i,a),a},s=new Map;for(let i of t){let c=o(i);for(let a of c.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=a[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,a.index-2000),f=Math.min(c.length,a.index+2000),h=c.slice(d,f),m=h.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),p=h.match(/"(?:team_name|name)":"([^"]{2,60})"/),D=s.get(u);if(!D||l.length>D.token.length){let C={token:l,teamId:u},b=m?.[1]??D?.url,_=p?.[1]??D?.teamName;if(b)C.url=b;if(_)C.teamName=_;s.set(u,C)}}}let r=t.map((i)=>o(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of s.values()){if(i.teamName)continue;let c=r.indexOf(i.teamId);if(c!==-1){let a=Math.max(0,c-500),l=Math.min(r.length,c+500),d=r.slice(a,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let a=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(a){let l=r.indexOf(a);if(l!==-1){let u=Math.max(0,l-500),d=Math.min(r.length,l+500),h=r.slice(u,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(h?.[1]){i.teamName=h[1];continue}}i.teamName=a.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...s.values()]}async function wr(e){let t=e??Oc().find(Ne);if(!t)throw Error(`Slack desktop app LevelDB not found at:
125
- ${Oc().join(`
124
+ slack user ls --external`)}function Dr(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function Zf(e){return Dr(e)?.channel}function Fc(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function _c(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Os(e,t,n){let o=Zf(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Fc(t))return t;if(_c(t))return fr(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Fc(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=On(r);if(s){if(_c(r))return fr(e,r,n);let l=await Ee(e,"auth.test",{},n);if(i==="you"||i==="me"||On(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Pc(e,f,n)||Xf(e,f,n)}let d=await Yf(e,i,n);if(!d.id)throw Vf(t,d);if(d.dm)return d.dm;return fr(e,d.id,n,t)}let c=r.toLowerCase(),a="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(a)l.cursor=a;let u=await Ee(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===c)return String(d.id??"");if(a=u.response_metadata?.next_cursor??"",!a)break}throw Error(`channel not found: ${t}`)}async function Ps(e,t,n){try{let o=await Ee(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Rs(e,t,n){try{let o=await Ee(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function Ns(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await Ee(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function yr(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await Ee(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function wr(e,t,n){return Ee(e,"users.info",{user:t},n)}async function Nc(e,t,n){return Ee(e,"conversations.info",{channel:t},n)}async function Bc(e,t){let n=await Gf(e,"client.boot",{},t),o=typeof n.url==="string"?n.url:void 0;if(!o){let r=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${r}`)}let s=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:o,selfId:typeof s.id==="string"?s.id:""}}var Qf=["chat:write","im:write"],ep=["im:history","im:read"];async function Bs(e){let{userId:t,botId:n,team:o,scopes:s}=await Ac(e),r="";if(n)try{r=(await Tc(e,n)).appId}catch{r=""}let i=(l)=>s.includes(l),c=Qf.filter((l)=>!i(l)),a=ep.filter((l)=>!i(l));return{canSend:c.length===0,canReceiveReplies:a.length===0,ok:c.length===0&&a.length===0,botUserId:t,appId:r,team:o,grantedScopes:s,missingSendScopes:c,missingReplyScopes:a}}function Mc(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function Ms(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let s=["✓ Bot DM scopes are complete (send + read replies)."," Two-way replies also require the Messages Tab, which is not API-detectable.",' If recipients see "Sending messages to this app is turned off", enable it:',` ${n} → App Home → "Messages Tab" ON + "Allow users to send messages".`];return t?s:[...s,...Mc(e)]}let o=[];if(!e.canSend)o.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else o.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return o.push(" Make escalation DMs two-way:"),o.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),o.push(' "Allow users to send Slash commands and messages".'),o.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),o.push(" 3. Reinstall the app to apply the new scopes."),t?o:[...o,...Mc(e)]}import{createInterface as Ae}from"node:readline/promises";import{join as Ar,resolve as Fp}from"node:path";import{homedir as _p}from"node:os";import{readdirSync as Mn,readFileSync as Bn,existsSync as Be,copyFileSync as xr,mkdtempSync as Wc,rmSync as Uc}from"node:fs";import{homedir as Ls,tmpdir as Jc}from"node:os";import{join as te,dirname as sp}from"node:path";import{pbkdf2Sync as vs,createDecipheriv as Kc,createHash as op,timingSafeEqual as rp}from"node:crypto";import{execSync as Hc,execFileSync as ip}from"node:child_process";function Nn(e,t){let n=0,o=0,s=t;while(s<e.length){let r=e[s++];if(n+=(r&127)*2**o,(r&128)===0)break;o+=7}return{value:n,pos:s}}function tp(e){let t=0,n=0,o=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**o,(i&128)===0)break;o+=7}let s=Buffer.allocUnsafe(n),r=0;while(t<e.length&&r<n){let i=e[t++],c=i&3;if(c===0){let a=i>>2;if(a>=60){let l=a-59;a=0;for(let u=0;u<l;u++)a+=e[t++]*2**(8*u)}a+=1,e.copy(s,r,t,t+a),t+=a,r+=a}else{let a,l;if(c===1)a=4+(i>>2&7),l=(i>>5&7)*256+e[t++];else if(c===2)a=1+(i>>2),l=e[t]+e[t+1]*256,t+=2;else a=1+(i>>2),l=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let u=r-l;for(let d=0;d<a&&r<n;d++)s[r++]=s[u++]}}return r===n?s:s.subarray(0,r)}function br(e,t){let n=Nn(e,t),o=Nn(e,n.pos);return{handle:{offset:n.value,size:o.value},pos:o.pos}}function vc(e,t){let{offset:n,size:o}=t,s=e.subarray(n,n+o);return e[n+o]===1?tp(s):Buffer.from(s)}function np(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,o=[],s=0,r=Buffer.alloc(0);while(s<n){let i=Nn(e,s),c=Nn(e,i.pos),a=Nn(e,c.pos);s=a.pos;let l=i.value,u=c.value,d=a.value,f=e.subarray(s,s+u);s+=u;let h=e.subarray(s,s+d);s+=d,r=Buffer.concat([r.subarray(0,l),f]),o.push(h)}return o}function Lc(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=br(e,t),o=br(e,n.pos),s=vc(e,o.handle),r=[];for(let i of np(s))try{let{handle:c}=br(i,0);r.push(vc(e,c))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function jc(){let e=process.env.HOME??Ls();if(process.platform==="darwin")return[te(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[te(e,".config","Slack","Local Storage","leveldb"),te(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),te(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??te(e,"AppData","Roaming");return[te(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function ap(){let e=process.env.HOME??Ls();if(process.platform==="darwin")return te(e,"Library","Application Support","Slack","Cookies");return""}function cp(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),o=e.slice(35),s=Kc("aes-128-cbc",t,n);return s.setAutoPadding(!0),Buffer.concat([s.update(o),s.final()]).toString("utf8")}function lp(){if(process.platform!=="darwin")return;let e=ap();if(!Be(e))return;let t;try{t=Hc('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=vs(t,"saltysalt",1003,16,"sha1");try{let{default:o}=bn("bun:sqlite"),s=new o(e,{readonly:!0}),r=s.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(s.close(),!r)return;return cp(Buffer.from(r.encrypted_value),n)}catch{return}}function zc(e){if(!Be(e))return[];let t=Mn(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,o=(i)=>{let c=n.get(i);if(c!==void 0)return c;let a="";try{let l=Bn(te(e,i));a=i.endsWith(".ldb")?Lc(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{a=""}return n.set(i,a),a},s=new Map;for(let i of t){let c=o(i);for(let a of c.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=a[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,a.index-2000),f=Math.min(c.length,a.index+2000),h=c.slice(d,f),m=h.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),p=h.match(/"(?:team_name|name)":"([^"]{2,60})"/),D=s.get(u);if(!D||l.length>D.token.length){let x={token:l,teamId:u},b=m?.[1]??D?.url,_=p?.[1]??D?.teamName;if(b)x.url=b;if(_)x.teamName=_;s.set(u,x)}}}let r=t.map((i)=>o(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of s.values()){if(i.teamName)continue;let c=r.indexOf(i.teamId);if(c!==-1){let a=Math.max(0,c-500),l=Math.min(r.length,c+500),d=r.slice(a,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let a=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(a){let l=r.indexOf(a);if(l!==-1){let u=Math.max(0,l-500),d=Math.min(r.length,l+500),h=r.slice(u,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(h?.[1]){i.teamName=h[1];continue}}i.teamName=a.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...s.values()]}async function Cr(e){let t=e??jc().find(Be);if(!t)throw Error(`Slack desktop app LevelDB not found at:
125
+ ${jc().join(`
126
126
  `)}
127
- Is Slack installed and opened at least once?`);let n=Mc(t),o=e?void 0:Jf();if(o)for(let s of n)s.cookie=o;return n}function Hf(e,t){try{return JSON.parse(Bn(te(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function br(){let e=kr();if(!e||!Ne(e))return[];let t=["Default",...Mn(e).filter((o)=>o.startsWith("Profile "))],n=[];for(let o of t){let s=te(e,o,"Local Storage","leveldb"),r=Mc(s);if(r.length===0)continue;let i=Hf(e,o);n.push({profileDir:o,...i?{email:i}:{},label:vc(e,o),sessions:r})}return n}function Dr(e,t,n,o=!1){let s=(r,i)=>{try{let c=Nc("aes-128-cbc",t,r);c.setAutoPadding(!0);let a=Buffer.concat([c.update(i),c.final()]);if(a.subarray(0,5).toString()==="xoxd-")return a.toString("utf8");if(a.length>=37){let l=Lf("sha256").update(n).digest();if(jf(a.subarray(0,32),l)){let u=a.subarray(32).toString("utf8");if(u.startsWith("xoxd-"))return u}}return}catch{return}};return s(Buffer.alloc(16,32),e.slice(3))??(o&&e.length>=35?s(e.slice(19,35),e.slice(35)):void 0)}function vc(e,t){let n=(o,s)=>{if(o&&s)return`${o} (${s})`;return o||s||t};try{let s=JSON.parse(Bn(te(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(s&&(s.name||s.user_name))return n(s.name??"",s.user_name??"")}catch{}try{let s=JSON.parse(Bn(te(e,t,"Preferences"),"utf8")).profile;return n(s?.name??"",s?.user_name??"")}catch{return t}}function kr(){let e=process.env.HOME??Ms();if(process.platform==="darwin")return te(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return te(process.env.XDG_CONFIG_HOME??te(e,".config"),"google-chrome");return""}function zf(){try{return Wf("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function vn(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=kr();if(!Ne(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=Bc('security find-generic-password -a Chrome -s "Chrome Safe Storage" -w',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return{candidates:[],totalProfiles:0}}if(!i)return{candidates:[],totalProfiles:0};t=Bs(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Mn(e).filter((i)=>i.startsWith("Profile "))],o=[],s,r=!1;for(let i of n){let c=[te(e,i,"Network","Cookies"),te(e,i,"Cookies")].find(Ne);if(!c)continue;let a=Ic(te(Rc(),"slack-chrome-cookies-")),l=te(a,"Cookies");try{if(yr(c,l),Ne(`${c}-wal`))yr(`${c}-wal`,`${l}-wal`);let{default:u}=bn("bun:sqlite"),d=new u(l,{readonly:!0}),f;try{f=d.prepare("SELECT encrypted_value, value, host_key FROM cookies WHERE name='d' AND (host_key='slack.com' OR host_key LIKE '%.slack.com') LIMIT 1").get()}finally{d.close()}if(!f)continue;let h=Buffer.from(f.encrypted_value),m=h.subarray(0,3).toString(),p;if(m==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!h.length&&f.value?.startsWith("xoxd-"))p=f.value;else if(m==="v10")p=Dr(h,Bs("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(m==="v11"){if(!s){let D=zf();if(D)s=Bs(D,"saltysalt",1,16,"sha1")}if(s)p=Dr(h,s,f.host_key);else r=!0}}else if(m==="v10"&&t)p=Dr(h,t,f.host_key,!0);else if(m!=="v10")throw Error("Unknown cookie encryption prefix.");if(p)o.push({profileDir:i,profileName:vc(e,i),cookie:p})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{Pc(a,{recursive:!0,force:!0})}}if(r&&o.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:o,totalProfiles:n.length}}async function Cr(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=kr();if(!Ne(e))throw Error("Chrome profile directory was not found.");let t=new Map(vn().candidates.map((s)=>[s.profileDir,s.cookie])),n=new Map,o=["Default",...Mn(e).filter((s)=>s.startsWith("Profile "))];for(let s of o){let r=te(e,s,"Local Storage","leveldb");if(!Ne(r))continue;let i;try{i=await wr(r)}catch{continue}for(let c of i){if(n.has(c.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let a=t.get(s);if(a)c.cookie=a;n.set(c.teamId,c)}}return[...n.values()]}function qf(){let e=process.env.HOME??Ms();if(process.platform==="darwin")return[te(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[te(e,".mozilla","firefox"),te(e,"snap","firefox","common",".mozilla","firefox"),te(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[te(process.env.APPDATA??te(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Gf(e){let t=te(e,"profiles.ini"),n=Ne(t)?t:te(vf(e),"profiles.ini"),o={};if(!Ne(n))return o;try{let s=Bn(n,"utf8"),r="",i="";for(let c of s.split(`
128
- `)){let a=c.trim();if(a.startsWith("[")){r="",i="";continue}let l=a.indexOf("=");if(l===-1)continue;let u=a.slice(0,l).trim().toLowerCase(),d=a.slice(l+1).trim();if(u==="name")r=d;if(u==="path")i=d.split(/[\\/]/).pop()??d;if(r&&i)o[i]=r,r="",i=""}}catch{}return o}function vs(){let e=[];for(let t of qf().filter(Ne)){let n=Gf(t),o;try{o=Mn(t)}catch{continue}for(let s of o){let r=te(t,s,"cookies.sqlite");if(!Ne(r))continue;let i=Ic(te(Rc(),"slack-firefox-cookies-")),c=te(i,"cookies.sqlite");try{yr(r,c);let{default:a}=bn("bun:sqlite"),l=new a(c,{readonly:!0}),u=l.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(l.close(),!u?.value||!u.value.startsWith("xoxd-"))continue;let d=n[s]??s;e.push({profileDir:s,profileName:d,cookie:u.value})}catch{}finally{Pc(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as Er,writeFileSync as xr,mkdirSync as Xf,existsSync as Ln,rmSync as Yf}from"node:fs";import{join as Je}from"node:path";import{createDecipheriv as Ls}from"node:crypto";import{spawnSync as Vf}from"node:child_process";var Zf=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),Qf=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),ep=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),Qe="C:\\ProgramData\\slack-term-abe";function tp(){let e=process.env.LOCALAPPDATA??Je(process.env.USERPROFILE??"","AppData","Local");return Je(e,"Google","Chrome","User Data")}var np=String.raw`try {
127
+ Is Slack installed and opened at least once?`);let n=zc(t),o=e?void 0:lp();if(o)for(let s of n)s.cookie=o;return n}function up(e,t){try{return JSON.parse(Bn(te(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function Er(){let e=Sr();if(!e||!Be(e))return[];let t=["Default",...Mn(e).filter((o)=>o.startsWith("Profile "))],n=[];for(let o of t){let s=te(e,o,"Local Storage","leveldb"),r=zc(s);if(r.length===0)continue;let i=up(e,o);n.push({profileDir:o,...i?{email:i}:{},label:qc(e,o),sessions:r})}return n}function kr(e,t,n,o=!1){let s=(r,i)=>{try{let c=Kc("aes-128-cbc",t,r);c.setAutoPadding(!0);let a=Buffer.concat([c.update(i),c.final()]);if(a.subarray(0,5).toString()==="xoxd-")return a.toString("utf8");if(a.length>=37){let l=op("sha256").update(n).digest();if(rp(a.subarray(0,32),l)){let u=a.subarray(32).toString("utf8");if(u.startsWith("xoxd-"))return u}}return}catch{return}};return s(Buffer.alloc(16,32),e.slice(3))??(o&&e.length>=35?s(e.slice(19,35),e.slice(35)):void 0)}function qc(e,t){let n=(o,s)=>{if(o&&s)return`${o} (${s})`;return o||s||t};try{let s=JSON.parse(Bn(te(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(s&&(s.name||s.user_name))return n(s.name??"",s.user_name??"")}catch{}try{let s=JSON.parse(Bn(te(e,t,"Preferences"),"utf8")).profile;return n(s?.name??"",s?.user_name??"")}catch{return t}}function Sr(){let e=process.env.HOME??Ls();if(process.platform==="darwin")return te(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return te(process.env.XDG_CONFIG_HOME??te(e,".config"),"google-chrome");return""}function dp(){try{return ip("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function vn(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=Sr();if(!Be(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=Hc('security find-generic-password -a Chrome -s "Chrome Safe Storage" -w',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return{candidates:[],totalProfiles:0}}if(!i)return{candidates:[],totalProfiles:0};t=vs(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Mn(e).filter((i)=>i.startsWith("Profile "))],o=[],s,r=!1;for(let i of n){let c=[te(e,i,"Network","Cookies"),te(e,i,"Cookies")].find(Be);if(!c)continue;let a=Wc(te(Jc(),"slack-chrome-cookies-")),l=te(a,"Cookies");try{if(xr(c,l),Be(`${c}-wal`))xr(`${c}-wal`,`${l}-wal`);let{default:u}=bn("bun:sqlite"),d=new u(l,{readonly:!0}),f;try{f=d.prepare("SELECT encrypted_value, value, host_key FROM cookies WHERE name='d' AND (host_key='slack.com' OR host_key LIKE '%.slack.com') LIMIT 1").get()}finally{d.close()}if(!f)continue;let h=Buffer.from(f.encrypted_value),m=h.subarray(0,3).toString(),p;if(m==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!h.length&&f.value?.startsWith("xoxd-"))p=f.value;else if(m==="v10")p=kr(h,vs("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(m==="v11"){if(!s){let D=dp();if(D)s=vs(D,"saltysalt",1,16,"sha1")}if(s)p=kr(h,s,f.host_key);else r=!0}}else if(m==="v10"&&t)p=kr(h,t,f.host_key,!0);else if(m!=="v10")throw Error("Unknown cookie encryption prefix.");if(p)o.push({profileDir:i,profileName:qc(e,i),cookie:p})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{Uc(a,{recursive:!0,force:!0})}}if(r&&o.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:o,totalProfiles:n.length}}async function Fr(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Sr();if(!Be(e))throw Error("Chrome profile directory was not found.");let t=new Map(vn().candidates.map((s)=>[s.profileDir,s.cookie])),n=new Map,o=["Default",...Mn(e).filter((s)=>s.startsWith("Profile "))];for(let s of o){let r=te(e,s,"Local Storage","leveldb");if(!Be(r))continue;let i;try{i=await Cr(r)}catch{continue}for(let c of i){if(n.has(c.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let a=t.get(s);if(a)c.cookie=a;n.set(c.teamId,c)}}return[...n.values()]}function fp(){let e=process.env.HOME??Ls();if(process.platform==="darwin")return[te(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[te(e,".mozilla","firefox"),te(e,"snap","firefox","common",".mozilla","firefox"),te(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[te(process.env.APPDATA??te(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function pp(e){let t=te(e,"profiles.ini"),n=Be(t)?t:te(sp(e),"profiles.ini"),o={};if(!Be(n))return o;try{let s=Bn(n,"utf8"),r="",i="";for(let c of s.split(`
128
+ `)){let a=c.trim();if(a.startsWith("[")){r="",i="";continue}let l=a.indexOf("=");if(l===-1)continue;let u=a.slice(0,l).trim().toLowerCase(),d=a.slice(l+1).trim();if(u==="name")r=d;if(u==="path")i=d.split(/[\\/]/).pop()??d;if(r&&i)o[i]=r,r="",i=""}}catch{}return o}function js(){let e=[];for(let t of fp().filter(Be)){let n=pp(t),o;try{o=Mn(t)}catch{continue}for(let s of o){let r=te(t,s,"cookies.sqlite");if(!Be(r))continue;let i=Wc(te(Jc(),"slack-firefox-cookies-")),c=te(i,"cookies.sqlite");try{xr(r,c);let{default:a}=bn("bun:sqlite"),l=new a(c,{readonly:!0}),u=l.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(l.close(),!u?.value||!u.value.startsWith("xoxd-"))continue;let d=n[s]??s;e.push({profileDir:s,profileName:d,cookie:u.value})}catch{}finally{Uc(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as _r,writeFileSync as $r,mkdirSync as hp,existsSync as Ln,rmSync as gp}from"node:fs";import{join as Ke}from"node:path";import{createDecipheriv as Ws}from"node:crypto";import{spawnSync as mp}from"node:child_process";var Dp=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),yp=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),wp=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),Qe="C:\\ProgramData\\slack-term-abe";function bp(){let e=process.env.LOCALAPPDATA??Ke(process.env.USERPROFILE??"","AppData","Local");return Ke(e,"Google","Chrome","User Data")}var kp=String.raw`try {
129
129
  Add-Type -AssemblyName System.Security
130
130
  $d = [IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\in.bin')
131
131
  $o = [Security.Cryptography.ProtectedData]::Unprotect($d, $null, 'CurrentUser')
132
132
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\sys.bin', $o)
133
133
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\dpapi.err' ($_.Exception.Message) }
134
- `,sp=String.raw`try {
134
+ `,xp=String.raw`try {
135
135
  Add-Type -TypeDefinition @'
136
136
  using System; using System.Runtime.InteropServices;
137
137
  public static class NC {
@@ -147,7 +147,7 @@ public static class NC {
147
147
  '@
148
148
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\cng.bin', [NC]::Dec([IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\eak.bin')))
149
149
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\cng.err' ($_.Exception.Message) }
150
- `;function op(e,t){let n=(o)=>`'${o.replace(/'/g,"''")}'`;return String.raw`
150
+ `;function Cp(e,t){let n=(o)=>`'${o.replace(/'/g,"''")}'`;return String.raw`
151
151
  $ErrorActionPreference = 'Stop'
152
152
  Add-Type -AssemblyName System.Security
153
153
  $work = 'C:\ProgramData\slack-term-abe'
@@ -213,46 +213,46 @@ icacls "$work\Cookies" /grant "$($u):(R)" | Out-Null
213
213
  if (Test-Path "$work\cng.bin") { icacls "$work\cng.bin" /grant "$($u):(R)" | Out-Null }
214
214
  Write-Host 'OK'
215
215
  try { Stop-Transcript | Out-Null } catch {}
216
- `}function rp(e,t){let o=4+e.readUInt32LE(0)+4,s=e[o];if(s===1||s===2){let r=e.subarray(o+1,o+13),i=e.subarray(o+13,o+45),c=e.subarray(o+45,o+61),a=s===1?Ls("aes-256-gcm",Zf,r):Ls("chacha20-poly1305",Qf,r,{authTagLength:16});return a.setAuthTag(c),Buffer.concat([a.update(i),a.final()])}if(s===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let r=e.subarray(o+33,o+45),i=e.subarray(o+45,o+77),c=e.subarray(o+77,o+93),a=Buffer.from(t.map((u,d)=>u^ep[d])),l=Ls("aes-256-gcm",a,r);return l.setAuthTag(c),Buffer.concat([l.update(i),l.final()])}throw Error(`Unsupported app-bound key flag: ${s}`)}function ip(e,t){let n=t.subarray(3,15),o=t.subarray(15,t.length-16),s=t.subarray(t.length-16),r=Ls("aes-256-gcm",e,n);return r.setAuthTag(s),Buffer.concat([r.update(o),r.final()]).subarray(32).toString("utf8")}async function Lc(e){if(process.platform!=="win32")throw Error("Windows-only");let t=tp();if(!Ln(Je(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);Xf(Qe,{recursive:!0});let n=Je(Qe,"extract.ps1");xr(n,op(t,e)),xr(Je(Qe,"inner_dpapi.ps1"),np),xr(Je(Qe,"inner_cng.ps1"),sp);let o=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,s=Vf("powershell",["-NoProfile","-Command",o],{encoding:"utf8",windowsHide:!0});if(s.status!==0&&s.error)throw Error(`Failed to launch elevated helper: ${s.error.message}`);let r=Je(Qe,"out.bin"),i=Je(Qe,"Cookies");if(!Ln(r)||!Ln(i)){let c=Ln(Je(Qe,"log.txt"))?Er(Je(Qe,"log.txt"),"utf8").split(`
217
- `).filter((a)=>a.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${c?` (${c.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let c=Er(r),a=Ln(Je(Qe,"cng.bin"))?Er(Je(Qe,"cng.bin")):void 0,l=rp(c,a),{Database:u}=bn("bun:sqlite"),d=new u(i,{readonly:!0}),f=d.query("SELECT encrypted_value v FROM cookies WHERE name = char(100) AND host_key LIKE char(37,115,108,97,99,107,37) LIMIT 1").get();if(d.close(),!f)throw Error("no Slack `d` cookie in that Chrome profile");let h=Buffer.from(f.v);if(h.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${h.subarray(0,3).toString("latin1")}`);let m=ip(l,h);if(!m.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return m}finally{if(!process.env.SLACK_KEEP_ABE)Yf(Qe,{recursive:!0,force:!0})}}var lp=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],up=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function dn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function dp(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:lp}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function fp(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:up}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function kt(e,t){return(await e.question(t)).trim()}async function jn(e,t){if(t)return!0;if(!e)return!1;let n=await kt(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function Jt(e,t,n,o){console.error("Verifying token...");let s=await un(t,o),r=dn(s.team),i;if(n)i=n;else if(e)i=await kt(e,`Workspace name [${r}]: `)||r;else i=r;let c=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-term/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-term/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let a=await kt(e,"Choice [1/2/3/4, Enter=1]: ");if(a==="2")c=Fr(process.cwd(),".slack-term",".env.local");else if(a==="3")c=Fr(cp(),".slack-term",".env.local");else if(a==="4")c=null;else c=Fr(process.cwd(),".env.local")}if(c===null)if(Ss(i,{token:t,...s,...o?{cookie:o}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${s.team} (${s.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let a={SLACK_TOKEN:t};if(o)a.SLACK_COOKIE=o;ir(c,a),console.log(`Saved token to ${c}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function Sr(e,t=!1,n="auto",o=!1){console.error("Scanning Slack desktop app...");let s=await wr();if(s.length===0)console.error("No sessions found. Make sure Slack is installed and you have signed in at least once."),process.exit(1);if(process.platform==="linux"&&n!=="none"&&s.some((r)=>!r.cookie)&&await jn(e,t)){let r=[];if(n!=="chrome")for(let i of vs())r.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&r.length===0)try{for(let i of vn().candidates)r.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(r.length===1){for(let i of s)i.cookie??=r[0].cookie;console.log(`Found Slack session cookie in ${r[0].source} profile: ${r[0].profileName}`)}else if(r.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(s.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await _r(s,e,o)}async function _r(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let o=e[0],s=o.teamName??o.teamId;console.log(`Found workspace: ${s}${o.cookie?" (+ xoxd cookie)":""}`),await Jt(t,o.token,dn(s),o.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let o of e){let s=o.teamName??o.teamId,r=dn(s);Ss(r,{token:o.token,team:s,teamId:o.teamId,url:o.url??"",user:"",...o.cookie?{cookie:o.cookie}:{}}),console.log(`Added workspace "${r}": ${s}${o.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let o=dn(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${o}`)}else console.log("Run: slack auth ls then: slack auth use -g <name>");console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- user token by re-running: slack auth login")}async function jc(e){console.log("Which token type does your app use?"),console.log(""),console.log(" 1) User token (xoxp-) -full access including search [recommended]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await kt(e,"Choice [1/2]: ")==="2"?"bot":"user",o=n==="user"?"xoxp-":"xoxb-",s=n==="user"?"User OAuth Token":"Bot User OAuth Token";console.log(""),console.log("Find your token here:"),console.log(" https://api.slack.com/apps"),console.log(" -> Select your app -> OAuth & Permissions"),console.log(` -> Copy the "${s}" (starts with ${o})`),console.log("");let r=await kt(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(o))console.error(`Expected a ${o} token, got: ${r.slice(0,10)}...`),process.exit(1);await Jt(e,r)}async function js(e,t){let n=t==="user"?dp():fp(),o=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",s=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${o}`),console.log("");let r=await kt(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(s))console.error(`Expected a ${s} token, got: ${r.slice(0,10)}...`),process.exit(1);await Jt(e,r)}async function pp(e,t){let n=br();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let o=e.profile.token.split("-")[1],s=n.find((r)=>r.sessions.some((i)=>i.teamId===o));if(!s&&t){if(s=n.find((r)=>r.email===t||r.profileDir===t||r.profileDir===`Profile ${t}`),!s)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((r)=>r.email??r.profileDir).join(", ")}`),process.exit(1)}if(!s)if(n.length===1)s=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((a,l)=>console.log(` ${l+1}) ${a.email??a.label} [${a.profileDir}]`));let r=$e({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=n.length)console.error("Invalid choice."),process.exit(1);s=n[c]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((r)=>console.error(` slack auth cookie -w ${e.name} --profile "${r.email??r.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${s.email??s.label} [${s.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Lc(s.profileDir)}catch(r){console.error(`
218
- Could not extract the cookie automatically: ${r instanceof Error?r.message:String(r)}`),console.error("Fallback (manual): Chrome > DevTools (F12) > Application > Cookies > https://app.slack.com > copy the `d` value,"),console.error("then set it via an env file: SLACK_COOKIE=xoxd-... (in .slack-term/.env.local)"),process.exit(1)}}async function Wc(e={}){if(process.platform!=="darwin"&&process.platform!=="linux"&&process.platform!=="win32")console.error("Chrome cookie extraction is supported on macOS, Linux, and Windows."),process.exit(1);let t=On();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((i)=>i.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((i)=>i.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let r=t.find((i)=>i.current);if(r)n=r.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((l,u)=>console.log(` ${u+1}) ${l.name} (${l.profile.team})`));let i=$e({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let a=parseInt(c,10)-1;if(isNaN(a)||a<0||a>=t.length)console.error("Invalid choice."),process.exit(1);n=t[a].name}}let o=t.find((r)=>r.name===n);if(o.profile.token.startsWith("xoxb-")){console.error(`
216
+ `}function Ep(e,t){let o=4+e.readUInt32LE(0)+4,s=e[o];if(s===1||s===2){let r=e.subarray(o+1,o+13),i=e.subarray(o+13,o+45),c=e.subarray(o+45,o+61),a=s===1?Ws("aes-256-gcm",Dp,r):Ws("chacha20-poly1305",yp,r,{authTagLength:16});return a.setAuthTag(c),Buffer.concat([a.update(i),a.final()])}if(s===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let r=e.subarray(o+33,o+45),i=e.subarray(o+45,o+77),c=e.subarray(o+77,o+93),a=Buffer.from(t.map((u,d)=>u^wp[d])),l=Ws("aes-256-gcm",a,r);return l.setAuthTag(c),Buffer.concat([l.update(i),l.final()])}throw Error(`Unsupported app-bound key flag: ${s}`)}function Sp(e,t){let n=t.subarray(3,15),o=t.subarray(15,t.length-16),s=t.subarray(t.length-16),r=Ws("aes-256-gcm",e,n);return r.setAuthTag(s),Buffer.concat([r.update(o),r.final()]).subarray(32).toString("utf8")}async function Gc(e){if(process.platform!=="win32")throw Error("Windows-only");let t=bp();if(!Ln(Ke(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);hp(Qe,{recursive:!0});let n=Ke(Qe,"extract.ps1");$r(n,Cp(t,e)),$r(Ke(Qe,"inner_dpapi.ps1"),kp),$r(Ke(Qe,"inner_cng.ps1"),xp);let o=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,s=mp("powershell",["-NoProfile","-Command",o],{encoding:"utf8",windowsHide:!0});if(s.status!==0&&s.error)throw Error(`Failed to launch elevated helper: ${s.error.message}`);let r=Ke(Qe,"out.bin"),i=Ke(Qe,"Cookies");if(!Ln(r)||!Ln(i)){let c=Ln(Ke(Qe,"log.txt"))?_r(Ke(Qe,"log.txt"),"utf8").split(`
217
+ `).filter((a)=>a.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${c?` (${c.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let c=_r(r),a=Ln(Ke(Qe,"cng.bin"))?_r(Ke(Qe,"cng.bin")):void 0,l=Ep(c,a),{Database:u}=bn("bun:sqlite"),d=new u(i,{readonly:!0}),f=d.query("SELECT encrypted_value v FROM cookies WHERE name = char(100) AND host_key LIKE char(37,115,108,97,99,107,37) LIMIT 1").get();if(d.close(),!f)throw Error("no Slack `d` cookie in that Chrome profile");let h=Buffer.from(f.v);if(h.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${h.subarray(0,3).toString("latin1")}`);let m=Sp(l,h);if(!m.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return m}finally{if(!process.env.SLACK_KEEP_ABE)gp(Qe,{recursive:!0,force:!0})}}var $p=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],Ap=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function fn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Tp(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:$p}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function Ip(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:Ap}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function xt(e,t){return(await e.question(t)).trim()}async function jn(e,t){if(t)return!0;if(!e)return!1;let n=await xt(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function Ht(e,t,n,o){console.error("Verifying token...");let s=await dn(t,o),r=fn(s.team),i;if(n)i=n;else if(e)i=await xt(e,`Workspace name [${r}]: `)||r;else i=r;let c=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-term/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-term/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let a=await xt(e,"Choice [1/2/3/4, Enter=1]: ");if(a==="2")c=Ar(process.cwd(),".slack-term",".env.local");else if(a==="3")c=Ar(_p(),".slack-term",".env.local");else if(a==="4")c=null;else c=Ar(process.cwd(),".env.local")}if(c===null)if($s(i,{token:t,...s,...o?{cookie:o}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${s.team} (${s.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let a={SLACK_TOKEN:t};if(o)a.SLACK_COOKIE=o;ur(c,a),console.log(`Saved token to ${c}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function Tr(e,t=!1,n="auto",o=!1){console.error("Scanning Slack desktop app...");let s=await Cr();if(s.length===0)console.error("No sessions found. Make sure Slack is installed and you have signed in at least once."),process.exit(1);if(process.platform==="linux"&&n!=="none"&&s.some((r)=>!r.cookie)&&await jn(e,t)){let r=[];if(n!=="chrome")for(let i of js())r.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&r.length===0)try{for(let i of vn().candidates)r.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(r.length===1){for(let i of s)i.cookie??=r[0].cookie;console.log(`Found Slack session cookie in ${r[0].source} profile: ${r[0].profileName}`)}else if(r.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(s.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await Ir(s,e,o)}async function Ir(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let o=e[0],s=o.teamName??o.teamId;console.log(`Found workspace: ${s}${o.cookie?" (+ xoxd cookie)":""}`),await Ht(t,o.token,fn(s),o.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let o of e){let s=o.teamName??o.teamId,r=fn(s);$s(r,{token:o.token,team:s,teamId:o.teamId,url:o.url??"",user:"",...o.cookie?{cookie:o.cookie}:{}}),console.log(`Added workspace "${r}": ${s}${o.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let o=fn(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${o}`)}else console.log("Run: slack auth ls then: slack auth use -g <name>");console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- user token by re-running: slack auth login")}async function Xc(e){console.log("Which token type does your app use?"),console.log(""),console.log(" 1) User token (xoxp-) -full access including search [recommended]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await xt(e,"Choice [1/2]: ")==="2"?"bot":"user",o=n==="user"?"xoxp-":"xoxb-",s=n==="user"?"User OAuth Token":"Bot User OAuth Token";console.log(""),console.log("Find your token here:"),console.log(" https://api.slack.com/apps"),console.log(" -> Select your app -> OAuth & Permissions"),console.log(` -> Copy the "${s}" (starts with ${o})`),console.log("");let r=await xt(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(o))console.error(`Expected a ${o} token, got: ${r.slice(0,10)}...`),process.exit(1);await Ht(e,r)}async function Us(e,t){let n=t==="user"?Tp():Ip(),o=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",s=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${o}`),console.log("");let r=await xt(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(s))console.error(`Expected a ${s} token, got: ${r.slice(0,10)}...`),process.exit(1);await Ht(e,r)}async function Op(e,t){let n=Er();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let o=e.profile.token.split("-")[1],s=n.find((r)=>r.sessions.some((i)=>i.teamId===o));if(!s&&t){if(s=n.find((r)=>r.email===t||r.profileDir===t||r.profileDir===`Profile ${t}`),!s)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((r)=>r.email??r.profileDir).join(", ")}`),process.exit(1)}if(!s)if(n.length===1)s=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((a,l)=>console.log(` ${l+1}) ${a.email??a.label} [${a.profileDir}]`));let r=Ae({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=n.length)console.error("Invalid choice."),process.exit(1);s=n[c]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((r)=>console.error(` slack auth cookie -w ${e.name} --profile "${r.email??r.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${s.email??s.label} [${s.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Gc(s.profileDir)}catch(r){console.error(`
218
+ Could not extract the cookie automatically: ${r instanceof Error?r.message:String(r)}`),console.error("Fallback (manual): Chrome > DevTools (F12) > Application > Cookies > https://app.slack.com > copy the `d` value,"),console.error("then set it via an env file: SLACK_COOKIE=xoxd-... (in .slack-term/.env.local)"),process.exit(1)}}async function Yc(e={}){if(process.platform!=="darwin"&&process.platform!=="linux"&&process.platform!=="win32")console.error("Chrome cookie extraction is supported on macOS, Linux, and Windows."),process.exit(1);let t=In();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((i)=>i.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((i)=>i.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let r=t.find((i)=>i.current);if(r)n=r.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((l,u)=>console.log(` ${u+1}) ${l.name} (${l.profile.team})`));let i=Ae({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let a=parseInt(c,10)-1;if(isNaN(a)||a<0||a>=t.length)console.error("Invalid choice."),process.exit(1);n=t[a].name}}let o=t.find((r)=>r.name===n);if(o.profile.token.startsWith("xoxb-")){console.error(`
219
219
  Workspace "${n}" uses a bot token (xoxb-). A Chrome session cookie only
220
220
  `+`augments a user session token (xoxc-) — it has no effect on a bot token, so user-level
221
- `+"actions (tail @user, DMs, listing users) would still fail.");let r=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(r.length>0)console.error(` Target a user-token workspace instead: ${r.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${r[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let s;if(process.platform==="win32")s=await pp(o,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let r=e.yes?void 0:$e({input:process.stdin,output:process.stdout});try{if(!await jn(r,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{r?.close()}if(console.log("Scanning Chrome profiles for Slack session..."),process.platform==="darwin")console.log("macOS may show a dialog asking for your login password — click Allow.");let i,c;try{({candidates:i,totalProfiles:c}=vn())}catch(a){console.error(`Failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${c} profile${c!==1?"s":""}). Possible reasons:`),console.error(" - You denied the keychain dialog (try running again and click Allow)"),console.error(" - Chrome is not installed or has no Slack session"),console.error(" - You're not logged in to Slack in Chrome"),process.exit(1);if(i.length===1&&c<=1)s=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let a=i.length===1?`Found 1 Slack session across ${c} Chrome profiles:`:`Found ${i.length} Slack sessions across ${c} Chrome profiles:`;console.log(a),i.forEach((h,m)=>console.log(` ${m+1}) ${h.profileName} [${h.profileDir}]`)),console.log("");let l=$e({input:process.stdin,output:process.stdout}),u=i.length===1?" [Enter=1]":"",d=(await l.question(`Choice [1-${i.length}]${u}: `)).trim();l.close();let f=d===""&&i.length===1?0:parseInt(d,10)-1;if(isNaN(f)||f<0||f>=i.length)console.error("Invalid choice."),process.exit(1);s=i[f].cookie}}ar(n,s),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function $r(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=br();if(t.length===0)console.error("No Slack session found in Chrome."),console.error(" Open Slack in Chrome (https://app.slack.com) and sign in, then retry."),process.exit(1);let n;if(e.profile){let r=e.profile,i=t.find((c)=>c.email===r||c.profileDir===r||c.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" has no Slack session. Available:`),t.forEach((c)=>console.error(` - ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`)),process.exit(1);n=i}else if(t.length===1)n=t[0];else if(process.stdin.isTTY){console.log("Found Slack sessions in multiple Chrome profiles:"),t.forEach((a,l)=>console.log(` ${l+1}) ${a.email??a.label} [${a.profileDir}] (${a.sessions.length} workspace${a.sessions.length!==1?"s":""})`));let r=$e({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((r)=>console.error(` slack auth login chrome --profile "${r.email??r.profileDir}"`)),process.exit(1);let o=n.email??n.label??n.profileDir,s;if(process.platform==="darwin")try{let{candidates:r}=vn();s=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(s)hc(o,s,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,c=dn(i);Ss(c,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:o}),console.log(`Added workspace "${c}": ${i} (identity: ${o})`)}if(console.log(""),s)console.log(`Captured xoxd cookie for ${o} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${dn(n.sessions[0].teamName??n.sessions[0].teamId)}`);console.log(""),console.log("Select a workspace: slack auth use <name> (see: slack auth ls)")}async function Ar(e={}){let t=On();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((c)=>c.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((c)=>c.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((c)=>c.current);if(i)n=i.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((u,d)=>console.log(` ${d+1}) ${u.name} (${u.profile.team})`));let c=$e({input:process.stdin,output:process.stdout}),a=(await c.question("Choice: ")).trim();c.close();let l=parseInt(a,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let o=e.yes?void 0:$e({input:process.stdin,output:process.stdout});try{if(!await jn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}console.log("Scanning Firefox profiles for Slack session...");let s=vs();if(s.length===0)console.error("No Slack session found in Firefox. Possible reasons:"),console.error(" - Firefox is not installed"),console.error(" - You are not logged in to Slack in Firefox"),process.exit(1);let r;if(s.length===1)r=s[0].cookie,console.log(`Found session in Firefox profile: ${s[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),s.forEach((l,u)=>console.log(` ${u+1}) ${l.profileName} [${l.profileDir}]`));let i=$e({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let a=parseInt(c,10)-1;if(isNaN(a)||a<0||a>=s.length)console.error("Invalid choice."),process.exit(1);r=s[a].cookie}ar(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Uc(e={}){if(e.token){await Jt(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let s of process.stdin)n.push(s);let o=Buffer.concat(n).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await Jt(null,o,e.name);return}let t=$e({input:process.stdin,output:process.stdout});try{await jc(t)}finally{t.close()}}async function Kc(e={}){let t=$e({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await js(t,e.bot?"bot":"user");return}console.log("Which token type?"),console.log(" 1) User token (xoxp-) -full access including search [default]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await kt(t,"Choice [1/2, Enter=1]: ");await js(t,n==="2"?"bot":"user")}finally{t.close()}}function Jc(e={}){let t=(s,r)=>{if(/[\r\n]/.test(r))throw Error(`Invalid newline in ${s}.`);return`${s}=${/^[A-Za-z0-9._=-]+$/.test(r)?r:JSON.stringify(r)}`},n=[t("SLACK_TOKEN",gc(e.workspace))],o=bt(e.workspace);if(o)n.push(t("SLACK_COOKIE",o));if(!e.workspace){let s=_s();if(s)n.push(t("SLACK_BOT_TOKEN",s))}console.log(n.join(`
222
- `))}function Hc(e){let t=On(),n=e.workspace?t.find((s)=>s.name===e.workspace):t.find((s)=>s.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let o=ap(e.envfile);ir(o,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${o}`)}async function Wn(e={}){let t=On();if(t.length>0){console.log("Currently logged in:");for(let{name:o,profile:s,current:r}of t)console.log(` ${r?"*":" "} ${o} ${s.team} (${s.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?$e({input:process.stdin,output:process.stdout}):void 0;try{if(!await jn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let s=await Cr();if(s.length===0)throw Error("No Slack session token found in Chrome profiles.");await _r(s,o,!0)}finally{o?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?$e({input:process.stdin,output:process.stdout}):void 0;try{try{await Sr(o,e.yes??!1,"all",!0)}catch(s){if(!(s instanceof Error)||!s.message.startsWith("Slack desktop app LevelDB not found"))throw s;if(!await jn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await Cr();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=vs();if(i.length===1)for(let c of r)c.cookie=i[0].cookie}await _r(r,o,!0)}}finally{o?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let o=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(o!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?$e({input:process.stdin,output:process.stdout}):void 0;try{await Sr(s,e.yes??!1,o,!0)}finally{s?.close()}return}if(e.token){await Jt(null,e.token,e.name);return}if(!process.stdin.isTTY){let o=[];for await(let r of process.stdin)o.push(r);let s=Buffer.concat(o).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await Jt(null,s,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=$e({input:process.stdin,output:process.stdout});try{let o=await kt(n,"Choice [1/2/3/4/5]: ");if(console.log(""),o==="1")await Sr(n,e.yes??!1);else if(o==="2"){n.close(),await $r();return}else if(o==="3")await jc(n);else if(o==="4")await js(n,"user");else if(o==="5")await js(n,"bot");else console.error(`Invalid choice: "${o}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function Ws(e,t,n,o){let s=t,r=[],i=s,c=0;while(!0){let a=i.indexOf("<@U",c);if(a===-1)break;let l=i.slice(a+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);c=a+1}for(let a of r){if(!n.has(a))n.set(a,await Is(e,a,o));let l=n.get(a)??a;s=s.replaceAll(`<@${a}>`,`@${l}`),s=s.replace(new RegExp(`<@${a}\\|[^>]*>`,"g"),`@${l}`)}return s}function Us(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=i[r.getUTCDay()]??"",l=c[r.getUTCMonth()]??"";return`${a}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function qc(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function hp(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),a=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${c}:${a}:${l}.${u}`}async function gp(e,t,n){let o=typeof t.ts==="string"?t.ts:"0.000000",s=hp(o),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,h]=await Os(e,d);n.set(f,h)}r=n.get(f)??d}else if(typeof t.username==="string")r=t.username;let i=typeof t.text==="string"?t.text:"",a=Us(await Ws(e,i,n)).split(`
221
+ `+"actions (tail @user, DMs, listing users) would still fail.");let r=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(r.length>0)console.error(` Target a user-token workspace instead: ${r.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${r[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let s;if(process.platform==="win32")s=await Op(o,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let r=e.yes?void 0:Ae({input:process.stdin,output:process.stdout});try{if(!await jn(r,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{r?.close()}if(console.log("Scanning Chrome profiles for Slack session..."),process.platform==="darwin")console.log("macOS may show a dialog asking for your login password — click Allow.");let i,c;try{({candidates:i,totalProfiles:c}=vn())}catch(a){console.error(`Failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${c} profile${c!==1?"s":""}). Possible reasons:`),console.error(" - You denied the keychain dialog (try running again and click Allow)"),console.error(" - Chrome is not installed or has no Slack session"),console.error(" - You're not logged in to Slack in Chrome"),process.exit(1);if(i.length===1&&c<=1)s=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let a=i.length===1?`Found 1 Slack session across ${c} Chrome profiles:`:`Found ${i.length} Slack sessions across ${c} Chrome profiles:`;console.log(a),i.forEach((h,m)=>console.log(` ${m+1}) ${h.profileName} [${h.profileDir}]`)),console.log("");let l=Ae({input:process.stdin,output:process.stdout}),u=i.length===1?" [Enter=1]":"",d=(await l.question(`Choice [1-${i.length}]${u}: `)).trim();l.close();let f=d===""&&i.length===1?0:parseInt(d,10)-1;if(isNaN(f)||f<0||f>=i.length)console.error("Invalid choice."),process.exit(1);s=i[f].cookie}}dr(n,s),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Or(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=Er();if(t.length===0)console.error("No Slack session found in Chrome."),console.error(" Open Slack in Chrome (https://app.slack.com) and sign in, then retry."),process.exit(1);let n;if(e.profile){let r=e.profile,i=t.find((c)=>c.email===r||c.profileDir===r||c.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" has no Slack session. Available:`),t.forEach((c)=>console.error(` - ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`)),process.exit(1);n=i}else if(t.length===1)n=t[0];else if(process.stdin.isTTY){console.log("Found Slack sessions in multiple Chrome profiles:"),t.forEach((a,l)=>console.log(` ${l+1}) ${a.email??a.label} [${a.profileDir}] (${a.sessions.length} workspace${a.sessions.length!==1?"s":""})`));let r=Ae({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((r)=>console.error(` slack auth login chrome --profile "${r.email??r.profileDir}"`)),process.exit(1);let o=n.email??n.label??n.profileDir,s;if(process.platform==="darwin")try{let{candidates:r}=vn();s=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(s)Cc(o,s,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,c=fn(i);$s(c,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:o}),console.log(`Added workspace "${c}": ${i} (identity: ${o})`)}if(console.log(""),s)console.log(`Captured xoxd cookie for ${o} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${fn(n.sessions[0].teamName??n.sessions[0].teamId)}`);console.log(""),console.log("Select a workspace: slack auth use <name> (see: slack auth ls)")}async function Pr(e={}){let t=In();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((c)=>c.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((c)=>c.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((c)=>c.current);if(i)n=i.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((u,d)=>console.log(` ${d+1}) ${u.name} (${u.profile.team})`));let c=Ae({input:process.stdin,output:process.stdout}),a=(await c.question("Choice: ")).trim();c.close();let l=parseInt(a,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let o=e.yes?void 0:Ae({input:process.stdin,output:process.stdout});try{if(!await jn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}console.log("Scanning Firefox profiles for Slack session...");let s=js();if(s.length===0)console.error("No Slack session found in Firefox. Possible reasons:"),console.error(" - Firefox is not installed"),console.error(" - You are not logged in to Slack in Firefox"),process.exit(1);let r;if(s.length===1)r=s[0].cookie,console.log(`Found session in Firefox profile: ${s[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),s.forEach((l,u)=>console.log(` ${u+1}) ${l.profileName} [${l.profileDir}]`));let i=Ae({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let a=parseInt(c,10)-1;if(isNaN(a)||a<0||a>=s.length)console.error("Invalid choice."),process.exit(1);r=s[a].cookie}dr(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Vc(e={}){if(e.token){await Ht(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let s of process.stdin)n.push(s);let o=Buffer.concat(n).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await Ht(null,o,e.name);return}let t=Ae({input:process.stdin,output:process.stdout});try{await Xc(t)}finally{t.close()}}async function Zc(e={}){let t=Ae({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await Us(t,e.bot?"bot":"user");return}console.log("Which token type?"),console.log(" 1) User token (xoxp-) -full access including search [default]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await xt(t,"Choice [1/2, Enter=1]: ");await Us(t,n==="2"?"bot":"user")}finally{t.close()}}function Qc(e={}){let t=(s,r)=>{if(/[\r\n]/.test(r))throw Error(`Invalid newline in ${s}.`);return`${s}=${/^[A-Za-z0-9._=-]+$/.test(r)?r:JSON.stringify(r)}`},n=[t("SLACK_TOKEN",Ec(e.workspace))],o=kt(e.workspace);if(o)n.push(t("SLACK_COOKIE",o));if(!e.workspace){let s=As();if(s)n.push(t("SLACK_BOT_TOKEN",s))}console.log(n.join(`
222
+ `))}function el(e){let t=In(),n=e.workspace?t.find((s)=>s.name===e.workspace):t.find((s)=>s.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let o=Fp(e.envfile);ur(o,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${o}`)}async function Wn(e={}){let t=In();if(t.length>0){console.log("Currently logged in:");for(let{name:o,profile:s,current:r}of t)console.log(` ${r?"*":" "} ${o} ${s.team} (${s.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Ae({input:process.stdin,output:process.stdout}):void 0;try{if(!await jn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let s=await Fr();if(s.length===0)throw Error("No Slack session token found in Chrome profiles.");await Ir(s,o,!0)}finally{o?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Ae({input:process.stdin,output:process.stdout}):void 0;try{try{await Tr(o,e.yes??!1,"all",!0)}catch(s){if(!(s instanceof Error)||!s.message.startsWith("Slack desktop app LevelDB not found"))throw s;if(!await jn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await Fr();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=js();if(i.length===1)for(let c of r)c.cookie=i[0].cookie}await Ir(r,o,!0)}}finally{o?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let o=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(o!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ae({input:process.stdin,output:process.stdout}):void 0;try{await Tr(s,e.yes??!1,o,!0)}finally{s?.close()}return}if(e.token){await Ht(null,e.token,e.name);return}if(!process.stdin.isTTY){let o=[];for await(let r of process.stdin)o.push(r);let s=Buffer.concat(o).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await Ht(null,s,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Ae({input:process.stdin,output:process.stdout});try{let o=await xt(n,"Choice [1/2/3/4/5]: ");if(console.log(""),o==="1")await Tr(n,e.yes??!1);else if(o==="2"){n.close(),await Or();return}else if(o==="3")await Xc(n);else if(o==="4")await Us(n,"user");else if(o==="5")await Us(n,"bot");else console.error(`Invalid choice: "${o}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function Js(e,t,n,o){let s=t,r=[],i=s,c=0;while(!0){let a=i.indexOf("<@U",c);if(a===-1)break;let l=i.slice(a+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);c=a+1}for(let a of r){if(!n.has(a))n.set(a,await Rs(e,a,o));let l=n.get(a)??a;s=s.replaceAll(`<@${a}>`,`@${l}`),s=s.replace(new RegExp(`<@${a}\\|[^>]*>`,"g"),`@${l}`)}return s}function Ks(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=i[r.getUTCDay()]??"",l=c[r.getUTCMonth()]??"";return`${a}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function nl(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Pp(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),a=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${c}:${a}:${l}.${u}`}async function Rp(e,t,n){let o=typeof t.ts==="string"?t.ts:"0.000000",s=Pp(o),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,h]=await Ps(e,d);n.set(f,h)}r=n.get(f)??d}else if(typeof t.username==="string")r=t.username;let i=typeof t.text==="string"?t.text:"",a=Ks(await Js(e,i,n)).split(`
223
223
  `),l=a[0]+(a.length>1?`
224
224
  `+a.slice(1).map((d)=>` ${d}`).join(`
225
- `):""),u=qc(t)?"↳ ":"";return`${s} ${u}@${r}: ${l}`}async function mp(e,t,n,o,s,r,i,c){if(c?.aborted)return;return new Promise((a)=>{let l=new e(n);c?.addEventListener("abort",()=>{l.close(),a()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
226
- `)}),l.addEventListener("close",()=>a()),l.addEventListener("error",()=>a()),l.addEventListener("message",(u)=>{(async()=>{try{let d;try{d=JSON.parse(String(u.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){l.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==o)return;let m=typeof d.ts==="string"?d.ts:"";if(!m||r.has(m))return;let p=typeof d.subtype==="string"?d.subtype:"";if(p==="message_changed"||p==="message_deleted")return;if(s.thread){if((typeof d.thread_ts==="string"?d.thread_ts:m)!==s.thread&&m!==s.thread)return}if(s.watchThread&&qc(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==s.watchThread)return}if(s.me&&s.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${s.myUserId}>`))return}if(r.add(m),r.size>1000){let C=r.values().next().value;if(C!==void 0)r.delete(C)}let D=await gp(t,d,i);process.stdout.write(D+`
225
+ `):""),u=nl(t)?"↳ ":"";return`${s} ${u}@${r}: ${l}`}async function Np(e,t,n,o,s,r,i,c){if(c?.aborted)return;return new Promise((a)=>{let l=new e(n);c?.addEventListener("abort",()=>{l.close(),a()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
226
+ `)}),l.addEventListener("close",()=>a()),l.addEventListener("error",()=>a()),l.addEventListener("message",(u)=>{(async()=>{try{let d;try{d=JSON.parse(String(u.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){l.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==o)return;let m=typeof d.ts==="string"?d.ts:"";if(!m||r.has(m))return;let p=typeof d.subtype==="string"?d.subtype:"";if(p==="message_changed"||p==="message_deleted")return;if(s.thread){if((typeof d.thread_ts==="string"?d.thread_ts:m)!==s.thread&&m!==s.thread)return}if(s.watchThread&&nl(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==s.watchThread)return}if(s.me&&s.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${s.myUserId}>`))return}if(r.add(m),r.size>1000){let x=r.values().next().value;if(x!==void 0)r.delete(x)}let D=await Rp(t,d,i);process.stdout.write(D+`
227
227
  `)}catch(d){process.stderr.write(`RTM message error: ${d instanceof Error?d.message:String(d)}
228
- `)}})()})})}var zc=3,Dp=2000,Tr={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:_c,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function Gc(e,t,n,o,s,r,i){let c=Tr.getWebSocket();if(!c)return;for(let a=0;a<zc;a++){if(i?.aborted)return;try{let{wsUrl:l}=await Tr.clientBoot(e,t);await mp(c,e,l,n,o,s,r,i)}catch{}if(i?.aborted)return;if(a<zc-1)await Tr.sleep(Dp)}}function Xc(e){let t=e.match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/);if(!t)throw Error(`Invalid --since format: "${e}" (expected e.g. 10m, 2h, 1d)`);let n=parseFloat(t[1]);switch(t[2]){case"s":return n;case"m":return n*60;case"h":return n*3600;case"d":return n*86400}}var et={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:Gc};function at(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Or(e){return Array.isArray(e)?e:[]}function Yc(e){return Number(e)||0}function Vc(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function yp(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),a=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${c}:${a}:${l}.${u}`}async function wp(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:"0.000000",i=yp(r),c="?";if(typeof t.user==="string"){let m=t.user,p="@"+m;if(!n.has(p)){let[,D]=await Os(e,m,s);n.set(p,D)}c=n.get(p)??m}else if(typeof t.username==="string")c=t.username;let a=typeof t.text==="string"?t.text:"",u=Us(await Ws(e,a,n,s)).split(`
228
+ `)}})()})})}var tl=3,Bp=2000,Rr={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:Bc,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function sl(e,t,n,o,s,r,i){let c=Rr.getWebSocket();if(!c)return;for(let a=0;a<tl;a++){if(i?.aborted)return;try{let{wsUrl:l}=await Rr.clientBoot(e,t);await Np(c,e,l,n,o,s,r,i)}catch{}if(i?.aborted)return;if(a<tl-1)await Rr.sleep(Bp)}}function ol(e){let t=e.match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/);if(!t)throw Error(`Invalid --since format: "${e}" (expected e.g. 10m, 2h, 1d)`);let n=parseFloat(t[1]);switch(t[2]){case"s":return n;case"m":return n*60;case"h":return n*3600;case"d":return n*86400}}var et={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:sl};function lt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Nr(e){return Array.isArray(e)?e:[]}function rl(e){return Number(e)||0}function il(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Mp(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),a=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${c}:${a}:${l}.${u}`}async function vp(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:"0.000000",i=Mp(r),c="?";if(typeof t.user==="string"){let m=t.user,p="@"+m;if(!n.has(p)){let[,D]=await Ps(e,m,s);n.set(p,D)}c=n.get(p)??m}else if(typeof t.username==="string")c=t.username;let a=typeof t.text==="string"?t.text:"",u=Ks(await Js(e,a,n,s)).split(`
229
229
  `),d=u[0]+(u.length>1?`
230
230
  `+u.slice(1).map((m)=>` ${m}`).join(`
231
- `):""),f=Vc(t)?"↳ ":"",h=o?`${o} @${c}`:`@${c}`;return`${i} ${f}${h}: ${d}`}async function bp(e,t,n,o,s,r,i){let c=at(await Rn(e,t,20,i?void 0:n||void 0,i,o.cookie)),a=Or(c.messages).map(at).reverse(),l=at(c.response_metadata),u=c.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(o.watchThread&&!i){let D=at(await Cc(e,t,o.watchThread,50,o.cookie));d=Or(D.messages).map(at).filter((C)=>(typeof C.ts==="string"?C.ts:"")!==o.watchThread)}let f=[...a.map((D)=>({m:D,fromHistory:!0})),...d.map((D)=>({m:D,fromHistory:!1}))].sort((D,C)=>Yc(typeof D.m.ts==="string"?D.m.ts:"")-Yc(typeof C.m.ts==="string"?C.m.ts:"")),h=[],m=n,p=!1;for(let{m:D,fromHistory:C}of f){let b=typeof D.ts==="string"?D.ts:"";if(!b||s.has(b))continue;let _=typeof D.subtype==="string"?D.subtype:"";if(_==="message_changed"||_==="message_deleted")continue;if(o.thread){if((typeof D.thread_ts==="string"?D.thread_ts:b)!==o.thread&&b!==o.thread)continue}if(o.watchThread&&Vc(D)){if((typeof D.thread_ts==="string"?D.thread_ts:"")!==o.watchThread)continue}if(o.me&&o.myUserId){if(!(typeof D.text==="string"?D.text:"").includes(`<@${o.myUserId}>`))continue}if(s.add(b),s.size>1000){let N=s.values().next().value;if(N!==void 0)s.delete(N)}if(h.push(await wp(e,D,r,void 0,o.cookie)),C)m=b;let A=typeof D.user==="string"?D.user:"";if(!o.myUserId||A!==o.myUserId)p=!0}return{newCursor:m,lines:h,hasMore:c.has_more===!0,nextPageCursor:u,emittedOther:p}}function kp(e){if(e.includes("slack.com")){let t=pr(e),n=t?.threadTs??t?.ts;if(n)return n;throw Error(`--watch-thread: could not extract a timestamp from "${e}"`)}if(/^\d{10}\.\d{6}$/.test(e))return e;if(/^\d{16}$/.test(e))return`${e.slice(0,10)}.${e.slice(10)}`;throw Error(`--watch-thread: "${e}" is not a valid ts or permalink`)}async function Zc(e,t,n={},o){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
231
+ `):""),f=il(t)?"↳ ":"",h=o?`${o} @${c}`:`@${c}`;return`${i} ${f}${h}: ${d}`}async function Lp(e,t,n,o,s,r,i){let c=lt(await Rn(e,t,20,i?void 0:n||void 0,i,o.cookie)),a=Nr(c.messages).map(lt).reverse(),l=lt(c.response_metadata),u=c.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(o.watchThread&&!i){let D=lt(await Ic(e,t,o.watchThread,50,o.cookie));d=Nr(D.messages).map(lt).filter((x)=>(typeof x.ts==="string"?x.ts:"")!==o.watchThread)}let f=[...a.map((D)=>({m:D,fromHistory:!0})),...d.map((D)=>({m:D,fromHistory:!1}))].sort((D,x)=>rl(typeof D.m.ts==="string"?D.m.ts:"")-rl(typeof x.m.ts==="string"?x.m.ts:"")),h=[],m=n,p=!1;for(let{m:D,fromHistory:x}of f){let b=typeof D.ts==="string"?D.ts:"";if(!b||s.has(b))continue;let _=typeof D.subtype==="string"?D.subtype:"";if(_==="message_changed"||_==="message_deleted")continue;if(o.thread){if((typeof D.thread_ts==="string"?D.thread_ts:b)!==o.thread&&b!==o.thread)continue}if(o.watchThread&&il(D)){if((typeof D.thread_ts==="string"?D.thread_ts:"")!==o.watchThread)continue}if(o.me&&o.myUserId){if(!(typeof D.text==="string"?D.text:"").includes(`<@${o.myUserId}>`))continue}if(s.add(b),s.size>1000){let N=s.values().next().value;if(N!==void 0)s.delete(N)}if(h.push(await vp(e,D,r,void 0,o.cookie)),x)m=b;let A=typeof D.user==="string"?D.user:"";if(!o.myUserId||A!==o.myUserId)p=!0}return{newCursor:m,lines:h,hasMore:c.has_more===!0,nextPageCursor:u,emittedOther:p}}function jp(e){if(e.includes("slack.com")){let t=Dr(e),n=t?.threadTs??t?.ts;if(n)return n;throw Error(`--watch-thread: could not extract a timestamp from "${e}"`)}if(/^\d{10}\.\d{6}$/.test(e))return e;if(/^\d{16}$/.test(e))return`${e.slice(0,10)}.${e.slice(10)}`;throw Error(`--watch-thread: "${e}" is not a valid ts or permalink`)}async function al(e,t,n={},o){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
232
232
  Cross-channel mention streaming is not yet supported.
233
- Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let s=await Ts(e,t,n.cookie),r=n.interval??60000,i=n.timeout?et.now()+Xc(n.timeout)*1000:1/0,c=new Map,a=new Set;try{let p=at(await Sc(e,s,n.cookie));if(at(p.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(p){let D=p instanceof Error?p.message:String(p);if(D.includes("not_in_channel"))console.error("Error: you are not a member of that channel. Join it in Slack first, then retry."),process.exit(1);if(D.includes("missing_scope"))console.error("Error: token lacks the required history scope. Check your token's channels:history (or groups:history) permission."),process.exit(1);if(D.includes("channel_not_found"))console.error("Error: channel not found — it may be a private channel inaccessible with your token."),process.exit(1);console.error(`Warning: preflight check failed: ${D}`)}let l="";if(n.since){let p=Xc(n.since);l=(et.now()/1000-p).toFixed(6)}else{let p=at(await Rn(e,s,1,void 0,void 0,n.cookie)),D=Or(p.messages).map(at);if(D.length>0&&typeof D[0]?.ts==="string")l=D[0].ts,a.add(l);else l=(et.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await un(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=kp(n.watchThread)}catch(p){console.error(p instanceof Error?p.message:String(p)),process.exit(1)}let f={...n.thread!==void 0?{thread:n.thread}:{},...d!==void 0?{watchThread:d}:{},...n.me!==void 0?{me:n.me}:{},...u!==void 0?{myUserId:u}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await et.tailRTM(e,n.cookie,s,f,a,c,o),o?.aborted)return;console.error("RTM unavailable — switching to polling.")}let h=!0,m=et.now();while(!o?.aborted){if(et.now()>=i)return;let p=!1;try{let b=et.now()-m,_=r>0&&b>r*5,A,N=!0;do{let{newCursor:j,lines:I,nextPageCursor:J,emittedOther:U}=await bp(e,s,l,f,a,c,A);if(l=j,h&&N&&n.since&&I.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
234
- `);N=!1;for(let Q of I)process.stdout.write(Q+`
235
- `);if(U)p=!0;A=_?J:void 0}while(A);h=!1}catch(C){if(C instanceof Ze){console.error(`Warning: Slack rate limit hit — backing off for ${C.retryAfter}s`),await et.sleep(C.retryAfter*1000);continue}throw C}if(n.exitOnMessage&&p)return;m=et.now();let D=i-et.now();if(D<=0)return;await et.sleep(Math.min(r,D))}}import{spawn as Cp}from"node:child_process";import{constants as Qc}from"node:os";var Ep=["processing","active","suspended","closed"];function el(e){if(e!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error("--bot-token-env must name an environment variable, not contain a token.");let t=e===void 0?_s():process.env[e];if(!t?.startsWith("xoxb-"))throw Error("Agent commands require a bot token (xoxb). Set SLACK_BOT_TOKEN or --bot-token-env NAME; user tokens are refused.");return t}function tl(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function nl(e,t,n){let{ref:o,threadTs:s}=n(t);if(!s||!/^\d{10}\.\d{6}$/.test(s))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Ts(e,o),thread_ts:s}}function Ir(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function xp(e,t,n,o){let s,r,i,c,a,l=!1,u=!1,d=1,f=(p)=>{if(r)return;if(r=p,l=!0,s&&s.exitCode===null&&s.signalCode===null)s.kill(p),i=setTimeout(()=>s?.kill("SIGKILL"),5000)},h=()=>f("SIGINT"),m=()=>f("SIGTERM");process.on("SIGINT",h),process.on("SIGTERM",m);try{if(u=!0,await Pn(e,t,"processing"),!l&&o.title!==void 0)await fr(e,t,o.title);if(!l){s=Cp(n[0],n.slice(1),{stdio:"inherit"});let p=new Promise((D)=>{s.once("error",()=>{console.error("agent: could not start command"),D(127)}),s.once("exit",(C,b)=>{D(C??(b?128+Qc.signals[b]:1))})});c=setInterval(()=>{if(l||a)return;a=Pn(e,t,"processing").then(()=>{}).catch((D)=>Ir("heartbeat failed; retrying on next tick",D)).finally(()=>{a=void 0})},o.every*1000),d=await p}}catch(p){Ir("could not start agent session",p)}finally{if(l=!0,clearInterval(c),clearTimeout(i),await a,u)try{await Pn(e,t,o.close?"closed":"active")}catch(p){if(Ir("final status clear failed",p),d===0)d=1}process.removeListener("SIGINT",h),process.removeListener("SIGTERM",m)}return r?128+Qc.signals[r]:d}function sl(e,t){let n=(o)=>o.positional("target",{type:"string",demandOption:!0,describe:"Thread root: raw channel ID:ts (avoids listing), #channel:ts, or permalink"}).option("title",{type:"string",describe:"Rename the session (1–200 characters)"}).option("bot-token-env",{type:"string",describe:"Environment variable holding an agent-enabled app's xoxb token (default SLACK_BOT_TOKEN); requires chat:write and channel membership"});return e.command("status <target> <status>","Set a bot agent session's status",(o)=>n(o).positional("status",{type:"string",choices:Ep,demandOption:!0}),async(o)=>{tl(o.title);let s=el(o["bot-token-env"]),r=await nl(s,o.target,t);if(await Pn(s,r,o.status),o.title!==void 0)await fr(s,r,o.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(o)=>n(o).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(o)=>{if(tl(o.title),!Number.isFinite(o.every)||o.every<=0||o.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let s=process.argv.indexOf("--"),r=s<0?[]:process.argv.slice(s+1);if(!r[0])throw Error("agent run requires -- <command...>");let i=el(o["bot-token-env"]),c=await nl(i,o.target,t);process.exitCode=await xp(i,c,r,{every:o.every,close:o.close,...o.title!==void 0?{title:o.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}var He=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],Js=He.length,Hs="question";function Rr(e){let t=e.split(`
236
- `),n=t[t.length-2];if(n===void 0||!n.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")||!n.endsWith("_"))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function Nr(e,t){let n=e.split(`
237
- `);if(n.length<2)return e;if(Rr(e).length)n.splice(n.length-2,1);if(t.length)n.splice(n.length-1,0,`${"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: "}${t.map((s)=>`<@${s}>`).join(", ")}_`);let o=n.join(`
238
- `);return o===e?e:o}function Fp(e){return e!==void 0&&e.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")&&e.endsWith("_")}var Br="white_check_mark",Ks=`:${Br}: `;function rl(e){return`:${He[e].name}:`}function il(e,t){let n=He[t];for(let o of[rl(t),n.glyph]){if(e.startsWith(`${o} `))return e.slice(o.length+1);if(e===o)return""}return null}function Sp(e){return He.some((t,n)=>il(e,n)!==null)}function Ht(e){return e.replace(/\s*\n\s*/g," ")}function al(e,t,n,o,s){let r=[`:question: *${e}*`];if(t)r.push("",t);if(n.length){if(r.push(""),r.push(...n.map((i,c)=>`${rl(c)} ${Ht(i)}`)),o.length)r.push(""),r.push(...o.map((i,c)=>`(${c+11}) ${Ht(i)}`)),r.push("_11 番目以降はリアクションがないので、返信で答えてください。_");r.push(""),r.push(s?"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_":"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_")}else r.push(""),r.push(s?"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_":"_このメッセージに返信してください。本文がそのまま回答になります。_");return r.join(`
239
- `)}function cl(e,t,n){let o=t.answer.split(`
233
+ Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let s=await Os(e,t,n.cookie),r=n.interval??60000,i=n.timeout?et.now()+ol(n.timeout)*1000:1/0,c=new Map,a=new Set;try{let p=lt(await Nc(e,s,n.cookie));if(lt(p.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(p){let D=p instanceof Error?p.message:String(p);if(D.includes("not_in_channel"))console.error("Error: you are not a member of that channel. Join it in Slack first, then retry."),process.exit(1);if(D.includes("missing_scope"))console.error("Error: token lacks the required history scope. Check your token's channels:history (or groups:history) permission."),process.exit(1);if(D.includes("channel_not_found"))console.error("Error: channel not found — it may be a private channel inaccessible with your token."),process.exit(1);console.error(`Warning: preflight check failed: ${D}`)}let l="";if(n.since){let p=ol(n.since);l=(et.now()/1000-p).toFixed(6)}else{let p=lt(await Rn(e,s,1,void 0,void 0,n.cookie)),D=Nr(p.messages).map(lt);if(D.length>0&&typeof D[0]?.ts==="string")l=D[0].ts,a.add(l);else l=(et.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await dn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=jp(n.watchThread)}catch(p){console.error(p instanceof Error?p.message:String(p)),process.exit(1)}let f={...n.thread!==void 0?{thread:n.thread}:{},...d!==void 0?{watchThread:d}:{},...n.me!==void 0?{me:n.me}:{},...u!==void 0?{myUserId:u}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await et.tailRTM(e,n.cookie,s,f,a,c,o),o?.aborted)return;console.error("RTM unavailable — switching to polling.")}let h=!0,m=et.now();while(!o?.aborted){if(et.now()>=i)return;let p=!1;try{let b=et.now()-m,_=r>0&&b>r*5,A,N=!0;do{let{newCursor:j,lines:O,nextPageCursor:K,emittedOther:U}=await Lp(e,s,l,f,a,c,A);if(l=j,h&&N&&n.since&&O.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
234
+ `);N=!1;for(let Q of O)process.stdout.write(Q+`
235
+ `);if(U)p=!0;A=_?K:void 0}while(A);h=!1}catch(x){if(x instanceof Ze){console.error(`Warning: Slack rate limit hit — backing off for ${x.retryAfter}s`),await et.sleep(x.retryAfter*1000);continue}throw x}if(n.exitOnMessage&&p)return;m=et.now();let D=i-et.now();if(D<=0)return;await et.sleep(Math.min(r,D))}}import{spawn as Wp}from"node:child_process";import{constants as cl}from"node:os";var Up=["processing","active","suspended","closed"];function ll(e){if(e!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error("--bot-token-env must name an environment variable, not contain a token.");let t=e===void 0?As():process.env[e];if(!t?.startsWith("xoxb-"))throw Error("Agent commands require a bot token (xoxb). Set SLACK_BOT_TOKEN or --bot-token-env NAME; user tokens are refused.");return t}function ul(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function dl(e,t,n){let{ref:o,threadTs:s}=n(t);if(!s||!/^\d{10}\.\d{6}$/.test(s))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Os(e,o),thread_ts:s}}function Br(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function Jp(e,t,n,o){let s,r,i,c,a,l=!1,u=!1,d=1,f=(p)=>{if(r)return;if(r=p,l=!0,s&&s.exitCode===null&&s.signalCode===null)s.kill(p),i=setTimeout(()=>s?.kill("SIGKILL"),5000)},h=()=>f("SIGINT"),m=()=>f("SIGTERM");process.on("SIGINT",h),process.on("SIGTERM",m);try{if(u=!0,await Pn(e,t,"processing"),!l&&o.title!==void 0)await mr(e,t,o.title);if(!l){s=Wp(n[0],n.slice(1),{stdio:"inherit"});let p=new Promise((D)=>{s.once("error",()=>{console.error("agent: could not start command"),D(127)}),s.once("exit",(x,b)=>{D(x??(b?128+cl.signals[b]:1))})});c=setInterval(()=>{if(l||a)return;a=Pn(e,t,"processing").then(()=>{}).catch((D)=>Br("heartbeat failed; retrying on next tick",D)).finally(()=>{a=void 0})},o.every*1000),d=await p}}catch(p){Br("could not start agent session",p)}finally{if(l=!0,clearInterval(c),clearTimeout(i),await a,u)try{await Pn(e,t,o.close?"closed":"active")}catch(p){if(Br("final status clear failed",p),d===0)d=1}process.removeListener("SIGINT",h),process.removeListener("SIGTERM",m)}return r?128+cl.signals[r]:d}function fl(e,t){let n=(o)=>o.positional("target",{type:"string",demandOption:!0,describe:"Thread root: raw channel ID:ts (avoids listing), #channel:ts, or permalink"}).option("title",{type:"string",describe:"Rename the session (1–200 characters)"}).option("bot-token-env",{type:"string",describe:"Environment variable holding an agent-enabled app's xoxb token (default SLACK_BOT_TOKEN); requires chat:write and channel membership"});return e.command("status <target> <status>","Set a bot agent session's status",(o)=>n(o).positional("status",{type:"string",choices:Up,demandOption:!0}),async(o)=>{ul(o.title);let s=ll(o["bot-token-env"]),r=await dl(s,o.target,t);if(await Pn(s,r,o.status),o.title!==void 0)await mr(s,r,o.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(o)=>n(o).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(o)=>{if(ul(o.title),!Number.isFinite(o.every)||o.every<=0||o.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let s=process.argv.indexOf("--"),r=s<0?[]:process.argv.slice(s+1);if(!r[0])throw Error("agent run requires -- <command...>");let i=ll(o["bot-token-env"]),c=await dl(i,o.target,t);process.exitCode=await Jp(i,c,r,{every:o.every,close:o.close,...o.title!==void 0?{title:o.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}var He=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],zs=He.length,qs="question";function vr(e){let t=e.split(`
236
+ `),n=t[t.length-2];if(n===void 0||!n.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")||!n.endsWith("_"))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function Lr(e,t){let n=e.split(`
237
+ `);if(n.length<2)return e;if(vr(e).length)n.splice(n.length-2,1);if(t.length)n.splice(n.length-1,0,`${"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: "}${t.map((s)=>`<@${s}>`).join(", ")}_`);let o=n.join(`
238
+ `);return o===e?e:o}function Kp(e){return e!==void 0&&e.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")&&e.endsWith("_")}var jr="white_check_mark",Hs=`:${jr}: `;function hl(e){return`:${He[e].name}:`}function gl(e,t){let n=He[t];for(let o of[hl(t),n.glyph]){if(e.startsWith(`${o} `))return e.slice(o.length+1);if(e===o)return""}return null}function Hp(e){return He.some((t,n)=>gl(e,n)!==null)}function zt(e){return e.replace(/\s*\n\s*/g," ")}function ml(e,t,n,o,s){let r=[`:question: *${e}*`];if(t)r.push("",t);if(n.length){if(r.push(""),r.push(...n.map((i,c)=>`${hl(c)} ${zt(i)}`)),o.length)r.push(""),r.push(...o.map((i,c)=>`(${c+11}) ${zt(i)}`)),r.push("_11 番目以降はリアクションがないので、返信で答えてください。_");r.push(""),r.push(s?"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_":"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_")}else r.push(""),r.push(s?"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_":"_このメッセージに返信してください。本文がそのまま回答になります。_");return r.join(`
239
+ `)}function Dl(e,t,n){let o=t.answer.split(`
240
240
  `).map((s)=>`> ${s}`).join(`
241
- `);return`${Ks}*${e}*
241
+ `);return`${Hs}*${e}*
242
242
  _${t.how}で回答済み${n?` (${n})`:""}_
243
243
 
244
- ${o}`}function ol(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function ll(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
245
- `),n=t[t.length-1]??"";if(e.startsWith(Ks))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(":question: ")&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function ul(e){let t=e.split(`
246
- `);if(e.startsWith(Ks)){let u=t[0].slice(Ks.length),d=ol(u.replace(/^\*/,"").replace(/\*$/,"")),f=t.map((h)=>h.startsWith("> ")?h.slice(2):h.startsWith("&gt; ")?h.slice(5):null).filter((h)=>h!==null).map(ol).join(`
244
+ ${o}`}function pl(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function yl(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
245
+ `),n=t[t.length-1]??"";if(e.startsWith(Hs))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(":question: ")&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function wl(e){let t=e.split(`
246
+ `);if(e.startsWith(Hs)){let u=t[0].slice(Hs.length),d=pl(u.replace(/^\*/,"").replace(/\*$/,"")),f=t.map((h)=>h.startsWith("> ")?h.slice(2):h.startsWith("&gt; ")?h.slice(5):null).filter((h)=>h!==null).map(pl).join(`
247
247
  `);if(!f)return{kind:"other"};return{kind:"resolved",question:d,answer:f}}let n=t[t.length-1]??"",o,s;switch(n){case"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_":o=!0,s=!0;break;case"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_":o=!1,s=!0;break;case"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_":o=!0,s=!1;break;case"_このメッセージに返信してください。本文がそのまま回答になります。_":o=!1,s=!1;break;default:return{kind:"other"}}let r=t[0].startsWith(":question: ")?t[0].slice(11):t[0];if(t[0]=r,!t[0].startsWith("*"))return{kind:"other"};let i=0;while(i<t.length&&!(t[i].endsWith("*")&&(i>0||t[0].length>1)))i++;if(i>=t.length)return{kind:"other"};let c=t.slice(0,i+1).join(`
248
- `).replace(/^\*/,"").replace(/\*$/,""),a=[],l=[];if(s){let u=t.length-2;if(Fp(t[u]))u--;if(t[u]!=="")return{kind:"other"};if(u--,t[u]==="_11 番目以降はリアクションがないので、返信で答えてください。_"){u--;while(u>=0&&/^\(\d+\) /.test(t[u]))l.unshift(t[u].replace(/^\(\d+\) /,"")),u--;if(t[u]!=="")return{kind:"other"};u--}let d=[];while(u>=0){let f=t[u];if(!Sp(f))break;d.unshift(f),u--}if(!d.length||d.length>Js)return{kind:"other"};for(let f=0;f<d.length;f++){let h=il(d[f],f);if(h===null)return{kind:"other"};a.push(h)}if(t[u]!=="")return{kind:"other"};if(u<i+1)return{kind:"other"};for(let f=0;f<l.length;f++)if(!t.includes(`(${f+11}) ${l[f]}`))return{kind:"other"}}return{kind:"open",question:c,reactable:a,overflow:l,threadOnly:o}}function Pr(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function dl(e,t){let n=Pr(e);if(!n)return{kind:"none"};let o=t.map(Pr),s=new Set;o.forEach((l,u)=>{if(l&&l===n)s.add(u+1)}),He.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)s.add(u+1)});let r=0,i="",c=n.match(/^(\d{1,2})$/);if(c)r=Number(c[1]);else if(c=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(c[1]),i=Pr(c[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(r>=1&&r<=t.length&&(i===""||i===o[r-1]))s.add(r);let a=[...s].sort((l,u)=>l-u);if(!a.length)return{kind:"none"};if(a.length>1)return{kind:"ambiguous",indexes:a};return{kind:"chosen",index:a[0]}}var Mr=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],aw=Mr.length;function vr(e){let t=e.split(`
249
- `),n=t[t.length-2];if(n===void 0||!n.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")||!n.endsWith("_"))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function fl(e,t){let n=e.split(`
250
- `);if(n.length<2)return e;if(vr(e).length)n.splice(n.length-2,1);if(t.length)n.splice(n.length-1,0,`${"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: "}${t.map((s)=>`<@${s}>`).join(", ")}_`);let o=n.join(`
251
- `);return o===e?e:o}function pl(e){return e!==void 0&&e.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")&&e.endsWith("_")}var _p="white_check_mark",cw=`:${_p}: `;var tt=Mr,fn=tt.length,Kn="ballot_box_with_ballot",Lr=`:${Kn}: `,gl="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",ml="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",zs="_締切: ",qs="_",Wr="bar_chart",jr=`:${Wr}: `;function Gs(e){return`:${tt[e].name}:`}function hl(e,t){for(let n of[Gs(t),tt[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function $p(e){return tt.some((t,n)=>e.startsWith(`${Gs(n)} `)||e.startsWith(`${t.glyph} `))}function Un(e){return e.replace(/\s*\n\s*/g," ")}function Dl(e,t,n,o={}){let s=!!o.multi,r=o.deadline??"",i=o.invalid??[];if(!n.length||n.length>fn)throw Error(`poll needs 1..${fn} choices, got ${n.length}`);let c=[`${Lr}*${e}*`];if(t)c.push("",t);if(c.push(""),c.push(...n.map((a,l)=>`${Gs(l)} ${Un(a)}`)),c.push(""),r)c.push(`${zs}${Un(r)}${qs}`);return c.push(s?ml:gl),fl(c.join(`
252
- `),s?[]:i)}function yl(e,t){let n=t.reduce((s,r)=>s+r.count,0),o=[`${jr}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return o.push(...t.map((s,r)=>`${Gs(r)} ×${s.count} ${Un(s.choice)}`)),o.join(`
253
- `)}function wl(e){let t=e.split(`
254
- `);if(e.startsWith(jr)){let f=t[0].slice(jr.length).replace(/^\*/,"").replace(/\*$/,""),h=[];for(let m=0;m<tt.length;m++){let p=t.map((C)=>hl(C,m)).find((C)=>C!==null&&C.startsWith("×"));if(p===void 0)break;let D=/^×(\d+) (.*)$/.exec(p);if(!D)return{kind:"other"};h.push({choice:D[2],count:Number(D[1])})}if(!h.length)return{kind:"other"};return{kind:"closed",question:f,tallies:h}}let n=t[t.length-1]??"",o;if(n===gl)o=!1;else if(n===ml)o=!0;else return{kind:"other"};if(t[0].startsWith(Lr))t[0]=t[0].slice(Lr.length);if(!t[0].startsWith("*"))return{kind:"other"};let s=0;while(s<t.length&&!(t[s].endsWith("*")&&(s>0||t[0].length>1)))s++;if(s>=t.length)return{kind:"other"};let r=t.slice(0,s+1).join(`
255
- `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,c=vr(e);if(pl(t[i]))i--;let a="",l=t[i];if(l!==void 0&&l.startsWith(zs)&&l.endsWith(qs)&&l.length>zs.length+qs.length)a=l.slice(zs.length,-qs.length),i--;if(t[i]!=="")return{kind:"other"};i--;let u=[];while(i>=0){let f=t[i];if(!$p(f))break;u.unshift(f),i--}if(!u.length||u.length>fn)return{kind:"other"};let d=[];for(let f=0;f<u.length;f++){let h=hl(u[f],f);if(h===null)return{kind:"other"};d.push(h)}if(t[i]!=="")return{kind:"other"};if(i<s+1)return{kind:"other"};return{kind:"open",question:r,choices:d,multi:o,deadline:a,invalid:c}}function bl(e,t,n,o){let s=new Map(t.map((l)=>[l.name,l.users])),r=e.map((l,u)=>(s.get(tt[u].name)??[]).filter((d)=>!n.has(d))),i=[];if(!o){let l=new Map;for(let u of r)for(let d of u)l.set(d,(l.get(d)??0)+1);for(let[u,d]of l)if(d>1)i.push(u)}let c=new Set(i),a=r.map((l)=>l.filter((u)=>!c.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:a[u].length})),voters:a,ambiguous:i}}function Ap(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var kl={isTestEnv:()=>Ap(),sleep:(e)=>kl.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Tp(e=process.env){let t=e.SLACK_REACTION_SEED_GAP_MS;if(t===void 0||t==="")return 1100;let n=Number(t);if(!Number.isFinite(n)||n<0)return 1100;return n}async function Ur(e,t,n,o=Tp()){for(let s=0;s<e.length;s++){let r=!0;try{await t(e[s])}catch(i){r=!1,n(e[s],i)}if(r&&o>0&&s<e.length-1)await kl.sleep(o)}}import{spawnSync as El}from"node:child_process";import{chmodSync as Op,mkdirSync as Ip}from"node:fs";import{homedir as Pp,hostname as Rp}from"node:os";import{basename as Np,dirname as Bp,join as Mp}from"node:path";function Jr(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var xl={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function vp(e){try{let n=(El("ps",["-o","ppid=,comm=","-p",String(e)],{encoding:"utf8",timeout:2000}).stdout??"").trim().match(/^(\d+)\s+(.+)$/);if(!n)return;return{pid:e,ppid:Number(n[1]),comm:Np(n[2].trim())}}catch{return}}function Lp(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=vp(e);if(!n)return;if(xl[n.comm])return n;e=n.ppid}return}function Cl(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Fl(e=process.env){let t={pid:process.pid,host:jp(),cwd:process.cwd()},n=e.SLACK_TERM_AGENT_CLI||void 0;if(!n&&e.AI_AGENT)n=e.AI_AGENT.split("_")[0]||void 0;if(!n&&e.CLAUDECODE==="1")n="claude-code";let o=Cl(e.SLACK_TERM_AGENT_PID)??Cl(e.CLAUDE_PID);if(!o||!n){let i=Lp();if(i)o??=i.pid,n??=xl[i.comm]}if(n)t.cli=n;if(o)t.agentPid=o;let s=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(s)t.sessionId=s;let r=Wp(t.cwd);if(r)t.gitBranch=r;return t}function jp(){try{return Rp()}catch{return""}}function Wp(e){try{let t=El("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var Up="slack_term_sent";function Sl(e,t){let n={kind:e,pid:t.pid,host:t.host,cwd:t.cwd};if(t.agentPid)n.agent_pid=t.agentPid;if(t.gitBranch)n.git_branch=t.gitBranch;if(t.cli)n.cli=t.cli;if(t.sessionId)n.session_id=t.sessionId;return{event_type:Up,event_payload:n}}function Jn(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return Mp(process.env.HOME||Pp(),".config","slack-cli","sent.sqlite")}function Kp(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=bn("bun:sqlite");return new n(e,{create:!0})}let t=process.getBuiltinModule?.("node:sqlite");if(t?.DatabaseSync)return new t.DatabaseSync(e)}catch{}return}var Jp=`
248
+ `).replace(/^\*/,"").replace(/\*$/,""),a=[],l=[];if(s){let u=t.length-2;if(Kp(t[u]))u--;if(t[u]!=="")return{kind:"other"};if(u--,t[u]==="_11 番目以降はリアクションがないので、返信で答えてください。_"){u--;while(u>=0&&/^\(\d+\) /.test(t[u]))l.unshift(t[u].replace(/^\(\d+\) /,"")),u--;if(t[u]!=="")return{kind:"other"};u--}let d=[];while(u>=0){let f=t[u];if(!Hp(f))break;d.unshift(f),u--}if(!d.length||d.length>zs)return{kind:"other"};for(let f=0;f<d.length;f++){let h=gl(d[f],f);if(h===null)return{kind:"other"};a.push(h)}if(t[u]!=="")return{kind:"other"};if(u<i+1)return{kind:"other"};for(let f=0;f<l.length;f++)if(!t.includes(`(${f+11}) ${l[f]}`))return{kind:"other"}}return{kind:"open",question:c,reactable:a,overflow:l,threadOnly:o}}function Mr(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function bl(e,t){let n=Mr(e);if(!n)return{kind:"none"};let o=t.map(Mr),s=new Set;o.forEach((l,u)=>{if(l&&l===n)s.add(u+1)}),He.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)s.add(u+1)});let r=0,i="",c=n.match(/^(\d{1,2})$/);if(c)r=Number(c[1]);else if(c=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(c[1]),i=Mr(c[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(r>=1&&r<=t.length&&(i===""||i===o[r-1]))s.add(r);let a=[...s].sort((l,u)=>l-u);if(!a.length)return{kind:"none"};if(a.length>1)return{kind:"ambiguous",indexes:a};return{kind:"chosen",index:a[0]}}var Wr=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],Tw=Wr.length;function Ur(e){let t=e.split(`
249
+ `),n=t[t.length-2];if(n===void 0||!n.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")||!n.endsWith("_"))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function kl(e,t){let n=e.split(`
250
+ `);if(n.length<2)return e;if(Ur(e).length)n.splice(n.length-2,1);if(t.length)n.splice(n.length-1,0,`${"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: "}${t.map((s)=>`<@${s}>`).join(", ")}_`);let o=n.join(`
251
+ `);return o===e?e:o}function xl(e){return e!==void 0&&e.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")&&e.endsWith("_")}var zp="white_check_mark",Iw=`:${zp}: `;var tt=Wr,pn=tt.length,Jn="ballot_box_with_ballot",Jr=`:${Jn}: `,El="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",Sl="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",Gs="_締切: ",Xs="_",Hr="bar_chart",Kr=`:${Hr}: `;function Ys(e){return`:${tt[e].name}:`}function Cl(e,t){for(let n of[Ys(t),tt[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function qp(e){return tt.some((t,n)=>e.startsWith(`${Ys(n)} `)||e.startsWith(`${t.glyph} `))}function Un(e){return e.replace(/\s*\n\s*/g," ")}function Fl(e,t,n,o={}){let s=!!o.multi,r=o.deadline??"",i=o.invalid??[];if(!n.length||n.length>pn)throw Error(`poll needs 1..${pn} choices, got ${n.length}`);let c=[`${Jr}*${e}*`];if(t)c.push("",t);if(c.push(""),c.push(...n.map((a,l)=>`${Ys(l)} ${Un(a)}`)),c.push(""),r)c.push(`${Gs}${Un(r)}${Xs}`);return c.push(s?Sl:El),kl(c.join(`
252
+ `),s?[]:i)}function _l(e,t){let n=t.reduce((s,r)=>s+r.count,0),o=[`${Kr}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return o.push(...t.map((s,r)=>`${Ys(r)} ×${s.count} ${Un(s.choice)}`)),o.join(`
253
+ `)}function $l(e){let t=e.split(`
254
+ `);if(e.startsWith(Kr)){let f=t[0].slice(Kr.length).replace(/^\*/,"").replace(/\*$/,""),h=[];for(let m=0;m<tt.length;m++){let p=t.map((x)=>Cl(x,m)).find((x)=>x!==null&&x.startsWith("×"));if(p===void 0)break;let D=/^×(\d+) (.*)$/.exec(p);if(!D)return{kind:"other"};h.push({choice:D[2],count:Number(D[1])})}if(!h.length)return{kind:"other"};return{kind:"closed",question:f,tallies:h}}let n=t[t.length-1]??"",o;if(n===El)o=!1;else if(n===Sl)o=!0;else return{kind:"other"};if(t[0].startsWith(Jr))t[0]=t[0].slice(Jr.length);if(!t[0].startsWith("*"))return{kind:"other"};let s=0;while(s<t.length&&!(t[s].endsWith("*")&&(s>0||t[0].length>1)))s++;if(s>=t.length)return{kind:"other"};let r=t.slice(0,s+1).join(`
255
+ `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,c=Ur(e);if(xl(t[i]))i--;let a="",l=t[i];if(l!==void 0&&l.startsWith(Gs)&&l.endsWith(Xs)&&l.length>Gs.length+Xs.length)a=l.slice(Gs.length,-Xs.length),i--;if(t[i]!=="")return{kind:"other"};i--;let u=[];while(i>=0){let f=t[i];if(!qp(f))break;u.unshift(f),i--}if(!u.length||u.length>pn)return{kind:"other"};let d=[];for(let f=0;f<u.length;f++){let h=Cl(u[f],f);if(h===null)return{kind:"other"};d.push(h)}if(t[i]!=="")return{kind:"other"};if(i<s+1)return{kind:"other"};return{kind:"open",question:r,choices:d,multi:o,deadline:a,invalid:c}}function Al(e,t,n,o){let s=new Map(t.map((l)=>[l.name,l.users])),r=e.map((l,u)=>(s.get(tt[u].name)??[]).filter((d)=>!n.has(d))),i=[];if(!o){let l=new Map;for(let u of r)for(let d of u)l.set(d,(l.get(d)??0)+1);for(let[u,d]of l)if(d>1)i.push(u)}let c=new Set(i),a=r.map((l)=>l.filter((u)=>!c.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:a[u].length})),voters:a,ambiguous:i}}function Gp(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var Tl={isTestEnv:()=>Gp(),sleep:(e)=>Tl.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Xp(e=process.env){let t=e.SLACK_REACTION_SEED_GAP_MS;if(t===void 0||t==="")return 1100;let n=Number(t);if(!Number.isFinite(n)||n<0)return 1100;return n}async function zr(e,t,n,o=Xp()){for(let s=0;s<e.length;s++){let r=!0;try{await t(e[s])}catch(i){r=!1,n(e[s],i)}if(r&&o>0&&s<e.length-1)await Tl.sleep(o)}}var Il=["text","select","user","link","date","number","checkbox"];function Pl(e){let t=e.split(":"),n=(t[0]??"").trim(),o=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!Il.includes(o))throw Error(`--col ${e}: unknown type "${o}" (expected one of ${Il.join(", ")})`);if(o==="select"){let s=(t.slice(2).join(":")||"").split(",").map((r)=>r.trim()).filter(Boolean);if(!s.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:o,choices:s}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:o}}var Ol=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function Rl(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let o={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)o.is_primary_column=!0;if(t.type==="select")o.options={format:"single_select",choices:t.choices.map((s,r)=>({value:s,label:s,color:Ol[r%Ol.length]}))};if(t.type==="user")o.options={format:"single_entity"};return o})}function Nl(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((o)=>{let s=o??{},i=((s.options??{}).choices??[]).map((c)=>{let a=c??{};return{value:String(a.value??""),label:String(a.label??a.value??"")}});return{id:String(s.id??""),key:String(s.key??""),name:String(s.name??""),type:String(s.type??""),choices:i}})}function qr(e,t){let n=e.find((o)=>o.name===t)??e.find((o)=>o.key===t)??e.find((o)=>o.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((o)=>o.name||o.key).join(", ")})`);return n}function Gr(e,t){switch(e.type){case"text":return{rich_text:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:t}]}]}]};case"select":{let n=e.choices.find((o)=>o.value===t||o.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((o)=>o.label).join(", ")})`);return{select:[n.value]}}case"user":return{user:[t]};case"link":return{link:[{original_url:t,display_as_url:!0}]};case"date":return{date:[t]};case"number":{let n=Number(t);if(!Number.isFinite(n))throw Error(`${e.name}: "${t}" is not a number`);return{number:[n]}}case"checkbox":case"todo_completed":if(!["true","false"].includes(t))throw Error(`${e.name}: expected true or false, got "${t}"`);return{checkbox:t==="true"};default:throw Error(`writing a ${e.type} column (${e.name}) from the CLI is not supported`)}}function Xr(e){return e.map((t)=>{let n=t.indexOf("=");if(n<=0)throw Error(`--set expects name=value, got: ${t}`);return{col:t.slice(0,n),value:t.slice(n+1)}})}function Bl(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as vl}from"node:child_process";import{chmodSync as Yp,mkdirSync as Vp}from"node:fs";import{homedir as Zp,hostname as Qp}from"node:os";import{basename as eh,dirname as th,join as nh}from"node:path";function Vr(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var Ll={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function sh(e){try{let n=(vl("ps",["-o","ppid=,comm=","-p",String(e)],{encoding:"utf8",timeout:2000}).stdout??"").trim().match(/^(\d+)\s+(.+)$/);if(!n)return;return{pid:e,ppid:Number(n[1]),comm:eh(n[2].trim())}}catch{return}}function oh(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=sh(e);if(!n)return;if(Ll[n.comm])return n;e=n.ppid}return}function Ml(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function jl(e=process.env){let t={pid:process.pid,host:rh(),cwd:process.cwd()},n=e.SLACK_TERM_AGENT_CLI||void 0;if(!n&&e.AI_AGENT)n=e.AI_AGENT.split("_")[0]||void 0;if(!n&&e.CLAUDECODE==="1")n="claude-code";let o=Ml(e.SLACK_TERM_AGENT_PID)??Ml(e.CLAUDE_PID);if(!o||!n){let i=oh();if(i)o??=i.pid,n??=Ll[i.comm]}if(n)t.cli=n;if(o)t.agentPid=o;let s=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(s)t.sessionId=s;let r=ih(t.cwd);if(r)t.gitBranch=r;return t}function rh(){try{return Qp()}catch{return""}}function ih(e){try{let t=vl("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var ah="slack_term_sent";function Wl(e,t){let n={kind:e,pid:t.pid,host:t.host,cwd:t.cwd};if(t.agentPid)n.agent_pid=t.agentPid;if(t.gitBranch)n.git_branch=t.gitBranch;if(t.cli)n.cli=t.cli;if(t.sessionId)n.session_id=t.sessionId;return{event_type:ah,event_payload:n}}function Kn(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return nh(process.env.HOME||Zp(),".config","slack-cli","sent.sqlite")}function ch(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=bn("bun:sqlite");return new n(e,{create:!0})}let t=process.getBuiltinModule?.("node:sqlite");if(t?.DatabaseSync)return new t.DatabaseSync(e)}catch{}return}var lh=`
256
256
  CREATE TABLE IF NOT EXISTS sent (
257
257
  id INTEGER PRIMARY KEY AUTOINCREMENT,
258
258
  kind TEXT NOT NULL,
@@ -279,121 +279,123 @@ CREATE TABLE IF NOT EXISTS sent (
279
279
  );
280
280
  CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
281
281
  CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
282
- `;function _l(){let e=Jn();try{Ip(Bp(e),{recursive:!0})}catch{}let t=Kp(e);if(!t)return;try{Op(e,384)}catch{}try{return t.exec(Jp),t}catch{try{t.close()}catch{}return}}function $l(e){if(!Jr())return!1;let t=_l();if(!t)return console.error(` (送信ログに記録できませんでした: ${Hr} — ${Jn()})`),!1;try{let n=e.attribution;return t.prepare(`INSERT INTO sent (kind, team, channel, target, ts, thread_ts, permalink, text, sent_at, pid, agent_pid, host, cwd, git_branch, cli, session_id, as_bot)
283
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0),!0}catch(n){return console.error(` (送信ログに記録できませんでした: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var Hr="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function Al(e){let t=_l();if(!t)return;try{let n=[],o=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),o.push(`%${Kr(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),o.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),o.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),o.push(`${Kr(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),o.push(`${Kr(e.cwd)}%`);if(e.kind)n.push("kind = ?"),o.push(e.kind);let s=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return o.push(e.limit??50),t.prepare(s).all(...o)}finally{try{t.close()}catch{}}}function Kr(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function Tl(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let s={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*s}let o=Date.parse(e);return Number.isNaN(o)?void 0:o}class ct extends Error{retryAfter;constructor(e){super(`Slack rate limited — retry after ${e}s`);this.name="RateLimitError",this.retryAfter=e}}function Gr(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function Pl(e,t,n,o){o=e.startsWith("xoxc-")?o??bt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Gr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new ct(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new ct(60);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
282
+ `;function Ul(){let e=Kn();try{Vp(th(e),{recursive:!0})}catch{}let t=ch(e);if(!t)return;try{Yp(e,384)}catch{}try{return t.exec(lh),t}catch{try{t.close()}catch{}return}}function Jl(e){if(!Vr())return!1;let t=Ul();if(!t)return console.error(` (送信ログに記録できませんでした: ${Zr} — ${Kn()})`),!1;try{let n=e.attribution;return t.prepare(`INSERT INTO sent (kind, team, channel, target, ts, thread_ts, permalink, text, sent_at, pid, agent_pid, host, cwd, git_branch, cli, session_id, as_bot)
283
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0),!0}catch(n){return console.error(` (送信ログに記録できませんでした: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var Zr="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function Kl(e){let t=Ul();if(!t)return;try{let n=[],o=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),o.push(`%${Yr(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),o.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),o.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),o.push(`${Yr(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),o.push(`${Yr(e.cwd)}%`);if(e.kind)n.push("kind = ?"),o.push(e.kind);let s=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return o.push(e.limit??50),t.prepare(s).all(...o)}finally{try{t.close()}catch{}}}function Yr(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function Hl(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let s={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*s}let o=Date.parse(e);return Number.isNaN(o)?void 0:o}class ut extends Error{retryAfter;constructor(e){super(`Slack rate limited — retry after ${e}s`);this.name="RateLimitError",this.retryAfter=e}}function ti(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function Gl(e,t,n,o){o=e.startsWith("xoxc-")?o??kt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ti()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new ut(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new ut(60);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
284
284
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
285
285
  Or replace the token with an xoxp- user token:
286
286
  slack auth login`);if((c==="missing_scope"||c==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${c}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${c} — ${c==="cannot_dm_bot"?`you're authenticated as a bot, so "@you" is the bot itself and it can't DM itself`:"this bot token lacks the user scope this action needs"}.
287
287
  Tailing/DMing people and listing users need a user session, not a bot token.
288
288
  Switch workspace: slack auth ls then slack auth use <name>
289
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}`)}return i}async function Hp(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Gr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new ct(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new ct(60);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`The draft API requires a desktop app session token (xoxc-).
289
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}`)}return i}async function uh(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ti()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new ut(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new ut(60);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`The draft API requires a desktop app session token (xoxc-).
290
290
  Import from Slack desktop: slack auth login`);if((c==="invalid_auth"||c==="not_authed")&&!o)throw Error(`drafts.list also requires the xoxd session cookie.
291
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}`)}return i}function qt(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return Hp(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function ie(e,t,n,o){let s=new URLSearchParams(n).toString();return Pl(e,`${t}?${s}`,{method:"GET"},o)}function Be(e,t,n,o){return Pl(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function Rl(e,t){let n=await ie(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Xs(e,t){t=e.startsWith("xoxc-")?t??bt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${Gr()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new ct(isNaN(i)?60:i)}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function nt(e,t,n=20,o,s,r,i){let c={channel:t,limit:String(n)};if(o!==void 0)c.oldest=o;if(s!==void 0)c.cursor=s;if(i)c.inclusive="true";return ie(e,"conversations.history",c,r)}async function ze(e,t,n,o=50,s){return ie(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Nl(e,t,n){return ie(e,"files.info",{file:t},n)}async function Bl(e,t={},n){let o={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)o.types=t.types;if(t.channel)o.channel=t.channel;if(t.user)o.user=t.user;return ie(e,"files.list",o,n)}async function Ml(e,t,n={},o){let s={list_id:t};if(n.limit)s.limit=String(n.limit);if(n.cursor)s.cursor=n.cursor;return qt(e,"lists.records.list",s,o)}async function vl(e,t,n,o,s){return ie(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(o,1))},s)}async function Ll(e,t,n){return vl(e,t,100,1,n)}async function Xr(e,t,n,o){let r=1,i=[],c={ok:!0,messages:{}};while(!0){let l=await vl(e,t,100,r,o),u=Hn(l,["messages","matches"]),d=Array.isArray(u)?u:[];i.push(...d);let f=Number(Hn(l,["messages","paging","pages"])??1);if(c=l,d.length===0||r>=f||i.length>=n)break;r+=1}let a=c;if(!a.messages)a.messages={};return a.messages.matches=i.slice(0,n),a}async function Gt(e,t,n,o,s,r,i,c){let a=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(o!==void 0)a.thread_ts=o;if(s&&o!==void 0)a.reply_broadcast=!0;return(await jl(e,"chat.postMessage",a,c,r)).ts??""}function zp(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function jl(e,t,n,o,s){if(!o)return Be(e,t,n,s);try{return await Be(e,t,{...n,metadata:o},s)}catch(r){if(!zp(r))throw r;return Be(e,t,n,s)}}async function Wl(e,t,n,o,s,r){let i={channel:t,text:n,post_at:o,blocks:[{type:"markdown",text:n}]};if(s!==void 0)i.thread_ts=s;return(await Be(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function Ul(e,t,n){let o={};if(t)o.channel=t;return ie(e,"chat.scheduledMessages.list",o,n)}async function Kl(e,t,n,o){await Be(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},o)}async function zn(e,t,n,o){return(await ie(e,"chat.getPermalink",{channel:t,message_ts:n},o)).permalink??""}async function Xt(e,t,n,o,s,r,i){return(await jl(e,"chat.update",r?{channel:t,ts:n,text:o}:{channel:t,ts:n,text:o,blocks:[{type:"markdown",text:o}]},i,s)).ts??n}async function Jl(e,t,n,o){await Be(e,"chat.delete",{channel:t,ts:n},o)}async function Hl(e,t,n,o,s=200,r){let i={channel:t,ts:n,limit:String(s)};if(o!==void 0)i.cursor=o;return ie(e,"conversations.replies",i,r)}async function Yr(e,t,n,o){await Be(e,"pins.add",{channel:t,timestamp:n},o)}async function pn(e,t,n,o,s){await Be(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function zl(e,t,n,o){return((await ie(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function qn(e,t,n,o,s){await Be(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function ql(e,t,n=!1,o){let s=await Be(e,"conversations.create",{name:t,is_private:n},o);return{id:s.channel?.id??"",name:s.channel?.name??t}}async function Gl(e,t,n,o){await Be(e,"conversations.invite",{channel:t,users:n.join(",")},o)}async function Gn(e,t){let n=[],o="";while(!0){let s={limit:"200",types:"public_channel,private_channel,im,mpim"};if(o)s.cursor=o;let r=await ie(e,"conversations.list",s,t);if(n.push(...r.channels??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{channels:n}}async function lt(e,t,n){let s=(await Be(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Xl(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await ie(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function zr(e,t,n,o){let s=await Xl(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function zt(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Ol(e,t){let n=zt(e.name??""),o=zt(e.real_name??e.profile?.real_name??""),s=zt(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Yl=200;async function Vl(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await ie(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(Ol(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,c=0,a=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await ie(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Yl){a=!0;break}s.add(h),i++;let m;try{m=(await ie(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof ct)throw p;c++;continue}if(m&&Ol(m,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:c,capped:a}}if(a)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:c,capped:a}}function Zl(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
291
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}`)}return i}function Gt(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return uh(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function ie(e,t,n,o){let s=new URLSearchParams(n).toString();return Gl(e,`${t}?${s}`,{method:"GET"},o)}function xe(e,t,n,o){return Gl(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function ni(e,t){let n=await ie(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function zn(e,t){t=e.startsWith("xoxc-")?t??kt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${ti()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new ut(isNaN(i)?60:i)}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function nt(e,t,n=20,o,s,r,i){let c={channel:t,limit:String(n)};if(o!==void 0)c.oldest=o;if(s!==void 0)c.cursor=s;if(i)c.inclusive="true";return ie(e,"conversations.history",c,r)}async function ze(e,t,n,o=50,s){return ie(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Xl(e,t,n){return ie(e,"files.info",{file:t},n)}async function Yl(e,t={},n){let o={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)o.types=t.types;if(t.channel)o.channel=t.channel;if(t.user)o.user=t.user;return ie(e,"files.list",o,n)}async function Vl(e,t,n,o){let s={name:t,schema:n};if(o)s.todo_mode=!0;return await xe(e,"slackLists.create",s)}async function si(e,t,n={}){let o={list_id:t};if(n.limit)o.limit=n.limit;if(n.cursor)o.cursor=n.cursor;if(n.includeList)o.include_list=!0;return await xe(e,"slackLists.items.list",o)}async function Zl(e,t,n){return await xe(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function Ql(e,t,n,o){let s={list_id:t,access_level:n};if(o.userIds?.length)s.user_ids=o.userIds;if(o.channelIds?.length)s.channel_ids=o.channelIds;return await xe(e,"slackLists.access.set",s)}async function eu(e,t,n){return await xe(e,"slackLists.items.update",{list_id:t,cells:n})}async function tu(e,t,n={},o){let s={list_id:t};if(n.limit)s.limit=String(n.limit);if(n.cursor)s.cursor=n.cursor;return Gt(e,"lists.records.list",s,o)}async function nu(e,t,n,o,s){return ie(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(o,1))},s)}async function su(e,t,n){return nu(e,t,100,1,n)}async function oi(e,t,n,o){let r=1,i=[],c={ok:!0,messages:{}};while(!0){let l=await nu(e,t,100,r,o),u=Hn(l,["messages","matches"]),d=Array.isArray(u)?u:[];i.push(...d);let f=Number(Hn(l,["messages","paging","pages"])??1);if(c=l,d.length===0||r>=f||i.length>=n)break;r+=1}let a=c;if(!a.messages)a.messages={};return a.messages.matches=i.slice(0,n),a}async function Xt(e,t,n,o,s,r,i,c){let a=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(o!==void 0)a.thread_ts=o;if(s&&o!==void 0)a.reply_broadcast=!0;return(await ou(e,"chat.postMessage",a,c,r)).ts??""}function dh(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function ou(e,t,n,o,s){if(!o)return xe(e,t,n,s);try{return await xe(e,t,{...n,metadata:o},s)}catch(r){if(!dh(r))throw r;return xe(e,t,n,s)}}async function ru(e,t,n,o,s,r){let i={channel:t,text:n,post_at:o,blocks:[{type:"markdown",text:n}]};if(s!==void 0)i.thread_ts=s;return(await xe(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function iu(e,t,n){let o={};if(t)o.channel=t;return ie(e,"chat.scheduledMessages.list",o,n)}async function au(e,t,n,o){await xe(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},o)}async function qn(e,t,n,o){return(await ie(e,"chat.getPermalink",{channel:t,message_ts:n},o)).permalink??""}async function Yt(e,t,n,o,s,r,i){return(await ou(e,"chat.update",r?{channel:t,ts:n,text:o}:{channel:t,ts:n,text:o,blocks:[{type:"markdown",text:o}]},i,s)).ts??n}async function cu(e,t,n,o){await xe(e,"chat.delete",{channel:t,ts:n},o)}async function lu(e,t,n,o,s=200,r){let i={channel:t,ts:n,limit:String(s)};if(o!==void 0)i.cursor=o;return ie(e,"conversations.replies",i,r)}async function ri(e,t,n,o){await xe(e,"pins.add",{channel:t,timestamp:n},o)}async function hn(e,t,n,o,s){await xe(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function uu(e,t,n,o){return((await ie(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Gn(e,t,n,o,s){await xe(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function du(e,t,n=!1,o){let s=await xe(e,"conversations.create",{name:t,is_private:n},o);return{id:s.channel?.id??"",name:s.channel?.name??t}}async function fu(e,t,n,o){await xe(e,"conversations.invite",{channel:t,users:n.join(",")},o)}async function Xn(e,t){let n=[],o="";while(!0){let s={limit:"200",types:"public_channel,private_channel,im,mpim"};if(o)s.cursor=o;let r=await ie(e,"conversations.list",s,t);if(n.push(...r.channels??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{channels:n}}async function dt(e,t,n){let s=(await xe(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function pu(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await ie(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function Qr(e,t,n,o){let s=await pu(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function qt(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function zl(e,t){let n=qt(e.name??""),o=qt(e.real_name??e.profile?.real_name??""),s=qt(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var hu=200;async function gu(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await ie(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(zl(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,c=0,a=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await ie(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=hu){a=!0;break}s.add(h),i++;let m;try{m=(await ie(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof ut)throw p;c++;continue}if(m&&zl(m,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:c,capped:a}}if(a)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:c,capped:a}}function mu(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
292
292
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
293
- Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${Yl} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
293
+ Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${hu} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
294
294
  `+(o.length?`This search was incomplete: ${o.join("; ")}.
295
295
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
296
296
  DMed you they cannot be found by name at all. Look them up and use their ID:
297
- slack user ls --external`)}async function ut(e,t,n){let o=t.startsWith("@")?t.slice(1):t;if(qr(o))return o;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let s=zt(o),r=await ie(e,"auth.test",{},n);if(s==="you"||s==="me"||zt(r.user??"")===s){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await Vl(e,s,n);if(i.id)return i.id;throw Zl(t,i)}function Yt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function qp(e){return Yt(e)?.channel}function Il(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function qr(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function pe(e,t,n){let o=qp(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Il(t))return t;if(qr(t))return zr(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Il(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=zt(r);if(s){if(qr(r))return zr(e,r,n);let l=await ie(e,"auth.test",{},n);if(i==="you"||i==="me"||zt(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Xl(e,f,n)||lt(e,f,n)}let d=await Vl(e,i,n);if(!d.id)throw Zl(t,d);if(d.dm)return d.dm;return zr(e,d.id,n,t)}let c=r.toLowerCase(),a="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(a)l.cursor=a;let u=await ie(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===c)return String(d.id??"");if(a=u.response_metadata?.next_cursor??"",!a)break}throw Error(`channel not found: ${t}`)}async function Xn(e,t,n){try{let o=await ie(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Ae(e,t,n){try{let o=await ie(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function Ql(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await ie(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function eu(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await ie(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function Yn(e,t){return qt(e,"drafts.list",{},t)}async function tu(e,t,n,o){let{randomUUID:s}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:n}]}]}]);return qt(e,"drafts.create",{client_msg_id:s(),destinations:JSON.stringify([{channel_id:t}]),blocks:r,file_ids:JSON.stringify([]),is_from_composer:"true"},o)}async function nu(e,t,n,o,s){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:o}]}]}]),i=(Date.now()/1000).toFixed(6);return qt(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:r,file_ids:JSON.stringify([])},s)}async function su(e,t,n){return qt(e,"conversations.info",{channel:t},n)}async function Vn(e,t,n){return ie(e,"users.info",{user:t},n)}async function Zn(e,t,n){return ie(e,"conversations.info",{channel:t},n)}async function ou(e,t,n){let o=(Date.now()/1000).toFixed(6);return qt(e,"drafts.delete",{draft_id:t,client_last_updated_ts:o},n)}async function Vr(e,t){let n=await qt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function ru(e,t,n,o={},s){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:c}=await import("node:path"),a=r(n),l=c(n),u=await ie(e,"files.getUploadURLExternal",{filename:l,length:String(a.size)},s),{upload_url:d,file_id:f}=u;if(!d||!f)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let h=i(n),m=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:h});if(!m.ok)throw Error(`Upload PUT failed: ${m.status} ${m.statusText}`);let p={files:[{id:f,title:o.title??l}],channel_id:t};if(o.threadTs)p.thread_ts=o.threadTs;if(o.initialComment)p.initial_comment=o.initialComment;let D=await Be(e,"files.completeUploadExternal",p,s),C={fileId:f},b=D.files?.[0]?.permalink;if(b)C.permalink=b;return C}function Hn(e,t){let n=e;for(let o of t){if(n===void 0||n===null)return;if(typeof o==="number"){if(!Array.isArray(n))return;n=n[o]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[o]}}return n}import{existsSync as sh,readFileSync as oh}from"node:fs";import{homedir as rh}from"node:os";import{join as ih}from"node:path";import{existsSync as Gp,mkdirSync as Xp,readFileSync as Yp,writeFileSync as Vp}from"node:fs";import{homedir as Zp}from"node:os";import{dirname as Qp,join as eh}from"node:path";var th=3600000,Ys={now:()=>Date.now(),path:()=>eh(process.env.HOME||Zp(),".config","slack-cli","cache.json")},Vs=!0,Ct;function iu(){return{channels:{},users:{}}}function Zr(){if(Ct)return Ct;if(Ct=iu(),!Vs)return Ct;try{let e=Ys.path();if(!Gp(e))return Ct;let t=JSON.parse(Yp(e,"utf8"));for(let n of["channels","users"]){let o=t?.[n];if(!o||typeof o!=="object"||Array.isArray(o))continue;for(let[s,r]of Object.entries(o))if(r&&typeof r==="object"&&typeof r.value==="string"&&typeof r.expires==="number")Ct[n][s]={value:r.value,expires:r.expires}}}catch{Ct=iu()}return Ct}function nh(e){if(!Vs)return;try{let t=Ys.path();Xp(Qp(t),{recursive:!0}),Vp(t,JSON.stringify(e,null,2)+`
298
- `)}catch{}}function au(e,t){return e?`${e} ${t}`:void 0}function Zs(e,t,n){if(!Vs)return;let o=au(t,n);if(!o)return;let s=Zr()[e][o];if(!s)return;if(s.expires<=Ys.now()){delete Zr()[e][o];return}return s.value}function Qs(e,t,n,o,s=th){if(!Vs)return;let r=au(t,n);if(!r)return;let i=Zr();i[e][r]={value:o,expires:Ys.now()+s},nh(i)}var Qr={marker:"pushpin",progress:{done:"white_check_mark",dropped:"no_entry_sign",doing:"eyes",pending:"hourglass_flowing_sand"},flags:{alert:"exclamation","needs-discussion":"thinking_face",waiting:"speech_balloon",blocked:"lock"}},hn=["done","dropped","doing","pending"],du=["alert","needs-discussion","waiting","blocked"];function ah(){return ih(process.env.HOME||rh(),".config","slack-cli","todo.json")}function eo(e){return e.replace(/^:+|:+$/g,"")}function Qn(e=ah()){let t={marker:Qr.marker,progress:{...Qr.progress},flags:{...Qr.flags}};try{if(!sh(e))return t;let n=JSON.parse(oh(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=eo(n.marker.trim());for(let o of hn){let s=n.progress?.[o];if(typeof s==="string"&&s.trim())t.progress[o]=eo(s.trim())}for(let o of du){let s=n.flags?.[o];if(typeof s==="string"&&s.trim())t.flags[o]=eo(s.trim())}}catch{}return t}function cu(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${eo(e)}:`}function fu(e,t,n={}){let o=n.shared===!0,s=(c)=>cu(c,o),r=(c)=>cu(c,o,!0),i=[];if(e==="untriaged")i.push(s(t.marker),...hn.map((c)=>r(t.progress[c])));else if(e==="stuck")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped),`(${du.map((c)=>s(t.flags[c])).join(" OR ")})`);else if(e==="open")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped));else{let c=hn.indexOf(e);i.push(s(t.progress[e]));for(let a of hn.slice(0,c))i.push(r(t.progress[a]))}if(n.in){let c=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${c}`)}if(n.from){let c=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${c}`)}return i.join(" ")}var ch=3,lh={sleep:(e)=>uh()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function uh(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Te(e,t,n=ch){for(let o=0;;o++)try{return await t()}catch(s){if(!(s instanceof Ze))throw s;if(o>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${s.retryAfter}s`),await lh.sleep(s.retryAfter*1000)}}var lu=new Map;async function pu(e,t){let n=lu.get(e);if(n)return n;let o=await Te("auth.test",()=>un(e,t)),s={userId:o.userId,teamId:o.teamId};return lu.set(e,s),s}async function hu(e,t){return(await pu(e,t)).userId}async function ei(e,t){try{return(await pu(e,t)).teamId}catch{return""}}async function ti(e,t,n,o){if(!t.startsWith("#"))return n(e,t,o);let s=await ei(e,o),r=Zs("channels",s,t);if(r)return r;let i=await Te("resolveChannel",()=>n(e,t,o));return Qs("channels",s,t,i),i}async function gu(e,t,n,o){let s=await ei(e,o),r=Zs("users",s,t);if(r)return r;let i=await Te("users.info",()=>n(e,t,o));if(i&&i!==t)Qs("users",s,t,i);return i}async function mu(e,t,n,o){let s=await ei(e,o),r=Zs("users",s,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let c=await Te("users.info",()=>n(e,t,o));if(c?.user?.is_bot===!0||t==="USLACKBOT")return uu(s,t,null);let a=c?.user?.tz;i=typeof a==="string"&&a?a:null}catch{return null}return uu(s,t,i)}function uu(e,t,n){return Qs("users",e,`tz:${t}`,n??"?"),n}async function Du(e,t,n,o,s,r){let i=s.progress[o],c=await hu(e,r),a=await Te("reactions.get",()=>Ec(e,t,n,r)),l=new Set(a.filter((h)=>h.users.includes(c)).map((h)=>h.name)),u=hn.map((h)=>s.progress[h]).filter((h)=>l.has(h));if(u.length===1&&u[0]===i)return{noop:!0,removed:[],leftover:[]};if(!l.has(i))await Te("reactions.add",()=>$s(e,t,n,i,r));let d=[],f=[];for(let h of u){if(h===i)continue;try{await Te("reactions.remove",()=>As(e,t,n,h,r)),d.push(h)}catch{f.push(h)}}return{noop:!1,added:o,removed:d,leftover:f}}async function yu(e,t,n,o,s,r,i){let c=s.flags[o];if(r)await Te("reactions.remove",()=>As(e,t,n,c,i));else await Te("reactions.add",()=>$s(e,t,n,c,i));return c}var ni=1000;async function wu(e,t,n,o={}){let s=o.limit??ni,r=o.cookie,i=await hu(e,r),c=hn.map((f)=>n.progress[f]),a=[],l=0,u,d=!1;while(l<s){let f=Math.min(200,s-l),h=await Te("conversations.history",()=>Rn(e,t,f,void 0,u,r)),m=h.messages??[];l+=m.length;for(let p of m){let D=String(p.ts??"");if(!D)continue;let C=new Set((p.reactions??[]).filter((_)=>(_.users??[]).map(String).includes(i)).map((_)=>String(_.name??""))),b=c.filter((_)=>C.has(_));if(b.length<2)continue;a.push({ts:D,text:String(p.text??"").split(`
299
- `)[0]??"",emoji:b,keep:b[0]})}if(u=h.response_metadata?.next_cursor||void 0,!u||m.length===0)break;if(l>=s){d=!0;break}}if(o.fix)for(let f of a)try{try{await Te("reactions.add",()=>$s(e,t,f.ts,f.keep,r))}catch(h){if(!(h instanceof Error)||!/already_reacted/.test(h.message))throw h}for(let h of f.emoji){if(h===f.keep)continue;await Te("reactions.remove",()=>As(e,t,f.ts,h,r))}f.fixed=!0}catch(h){f.fixed=!1,f.error=h instanceof Error?h.message:String(h)}return{scanned:l,findings:a,truncated:d}}var dh=!0,fh;function si(e){if(dh=e,!e)fh=void 0}function qe(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
300
- `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function oi(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function Vt(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Et(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function ph(e,t){let n=Vt(t),o=Et(e.profile);for(let r of[e.name,e.real_name,o.display_name,o.real_name])if(typeof r==="string"&&r&&Vt(r)===n)return!0;let s=typeof o.email==="string"?o.email.toLowerCase():"";return s!==""&&s===t.toLowerCase()}function hh(e){let t=Et(e.profile),n=new Set;for(let o of[t.display_name,e.real_name,e.name,t.real_name])if(typeof o==="string"&&o){let s=Vt(o);if(s.length>=2)n.add(s)}return[...n]}function gh(e,t){let n=Vt(e),o,s=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let c of hh(r)){let a=-1;if(n===c)a=e.length;else for(let l of ku)if(e.length>l.length&&e.endsWith(l)&&Vt(e.slice(0,e.length-l.length))===c){a=e.length-l.length;break}if(a<0)continue;if(!o||c.length>o.formLen)o={userId:i,matchLen:a,formLen:c.length,display:ai(r)},s=!1;else if(c.length===o.formLen&&o.userId!==i)s=!0}}if(!o)return;return s?"ambiguous":{userId:o.userId,matchLen:o.matchLen,display:o.display}}async function Zt(e,t,n,o){let s=`[${Cu}ー]+`,r=`${s}(?:[._-]+${s})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),c=new Set;for(let b of t.matchAll(i))c.add(b[1]);if(c.size===0)return{text:t,resolved:[],unresolved:[]};let a=new Map;for(let b of c)a.set(b,{status:"pending"});let l=(b)=>{for(let _ of c){if(a.get(_).status!=="pending")continue;if(ii(_)){let A=gh(_,b);if(A==="ambiguous")a.set(_,{status:"ambiguous"});else if(A)a.set(_,{status:"resolved",userId:A.userId,matchLen:A.matchLen,display:A.display})}else{let A=b.filter((j)=>ph(j,_)),N=new Set(A.map((j)=>typeof j.id==="string"?j.id:"").filter(Boolean));if(N.size===1){let j=A.find((I)=>typeof I.id==="string");a.set(_,{status:"resolved",userId:j.id,matchLen:_.length,display:ai(j)})}else if(N.size>1)a.set(_,{status:"ambiguous"})}}},u=!1;try{let b=await Ps(e,o);l((b.members??[]).map(Et)),u=!0}catch{u=!1}let d=[...c].some((b)=>a.get(b).status==="pending"),f=!1,h=!0;if(d&&n){f=!0;try{let b=await hr(e,n,o),_=[];for(let A of b){let N=Et(await gr(e,A,o)),j=Et(N.user);if(typeof j.id!=="string")j.id=A;_.push(j)}l(_)}catch{h=!1}}let m=u&&(n?f&&h:!0),p=[],D=[];for(let b of c){let _=a.get(b);if(_.status==="resolved")p.push({surface:`@${b.slice(0,_.matchLen)}`,display:_.display,userId:_.userId});else if(_.status==="ambiguous")D.push({surface:`@${b}`,reason:"ambiguous"});else D.push({surface:`@${b}`,reason:m?"no-match":"unavailable"})}return{text:t.replace(i,(b,_)=>{let A=a.get(_);if(A&&A.status==="resolved")return`<@${A.userId}>${_.slice(A.matchLen)}`;return b}),resolved:p,unresolved:D}}function es(e){let t=[],n=!1;for(let o of e)if(o.reason==="ambiguous")t.push(`${o.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(o.reason==="unavailable"){if(n)continue;t.push("could not fetch the user list (users:read missing or an API/connection error) — @mentions not tagged, sent as plain text"),n=!0}else t.push(`${o.surface} matched no one — not tagged, sent as plain text`);return t}async function bu(e,t,n,o={}){let s=o.warn??((i)=>process.stderr.write(`${i}
301
- `)),r=await Zt(e,t,n,o.cookie);for(let i of es(r.unresolved))s(`warn: ${i}`);return r.text}var ku=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],Cu="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function ii(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function mh(e){let t=[],n=new RegExp(`([${Cu}]{1,12})(${ku.join("|")})`,"gu");for(let o of e.matchAll(n))t.push({ref:o[1],honorific:o[2]});for(let o of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:o[1],honorific:""});for(let o of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:o[1],honorific:""});return t}function Dh(e){let t=Et(e.profile),n=new Set;for(let o of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof o!=="string"||!o)continue;for(let s of[o,...o.split(/\s+/)]){let r=Vt(s);if(r.length>=2)n.add(r)}}return[...n]}function yh(e,t){let n=Vt(e);if(n.length<2)return;for(let o of t)if(n===o)return o;if(ii(e)){for(let o of t)if(n.includes(o)||o.includes(n))return o}return}function ai(e){return[Et(e.profile).display_name,e.real_name,e.name].filter((o)=>typeof o==="string"&&o!=="")[0]??String(e.id??"?")}async function Eu(e,t,n){let o=mh(t);if(o.length===0)return[];let s=new Set;for(let l of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))s.add(l[1]);let i=((await Ps(e,n)).members??[]).map(Et).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:Dh(l),display:ai(l)})).filter((l)=>l.id!==""),c=[],a=new Set;for(let{ref:l,honorific:u}of o)for(let d of i){let f=yh(l,d.forms);if(!f)continue;if(s.has(d.id)||a.has(d.id))break;a.add(d.id),c.push({surface:ii(l)?`${f}${u}`:l,display:d.display,userId:d.id});break}return c}async function gn(e,t,n,o){let s=t,r=[],i=s,c=0;while(!0){let a=i.indexOf("<@U",c);if(a===-1)break;let l=i.slice(a+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);c=a+1}for(let a of r){if(!n.has(a))n.set(a,await Is(e,a,o));let l=n.get(a)??a;s=s.replaceAll(`<@${a}>`,`@${l}`),s=s.replace(new RegExp(`<@${a}\\|[^>]*>`,"g"),`@${l}`)}return s}function ts(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=i[r.getUTCDay()]??"",l=c[r.getUTCMonth()]??"";return`${a}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function xu(e,t=new Date){let n=new Date(e*1000),o=ri(t),s=ri(new Date(t.getTime()-86400000)),r=ri(n);if(r===o)return"Today";if(r===s)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),c=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${c} ${String(n.getDate()).padStart(2,"0")}`}function ri(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function ci(e){let t=new Date(e*1000),n=t.getFullYear(),o=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}`}function li(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",o=!!t&&wh(t),s=o?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),c,a;try{let h=new Intl.DateTimeFormat("en-GB",{timeZone:s,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});a=h.format(e),c=Number(h.formatToParts(e).find((m)=>m.type==="hour")?.value??"12")}catch{return null}let l=r>i?c>=r||c<i:c>=r&&c<i,u=o?`${s}, recipient`:`${s}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${a} (${u})`;if(!l)return d;return`${d}
302
- ⚠ QUIET HOURS (${r}:00-${i}:00) — this will buzz a phone.${o?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function wh(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{closeSync as Fu,mkdirSync as bh,openSync as Su,readFileSync as mn,statSync as _u,unlinkSync as to,writeFileSync as $u}from"node:fs";import{homedir as kh}from"node:os";import{join as Au}from"node:path";var ss="Pinlog · 最終更新";function ui(e){let t=new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Tokyo",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=(s)=>t.find((r)=>r.type===s)?.value??"??",o=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${o}:${n("minute")} JST`}function Ch(e){return`_${ss} ${ui(e)} · 更新はスレッドに_`}var di=new RegExp(`(^|\\n+)_?${ss} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function Dn(e){return di.test(e)}function os(e){return e.replace(di,"")}function fi(e,t){return`${os(e).trimEnd()}
297
+ slack user ls --external`)}async function ft(e,t,n){let o=t.startsWith("@")?t.slice(1):t;if(ei(o))return o;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let s=qt(o),r=await ie(e,"auth.test",{},n);if(s==="you"||s==="me"||qt(r.user??"")===s){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await gu(e,s,n);if(i.id)return i.id;throw mu(t,i)}function Vt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function fh(e){return Vt(e)?.channel}function ql(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function ei(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function he(e,t,n){let o=fh(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(ql(t))return t;if(ei(t))return Qr(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&ql(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=qt(r);if(s){if(ei(r))return Qr(e,r,n);let l=await ie(e,"auth.test",{},n);if(i==="you"||i==="me"||qt(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await pu(e,f,n)||dt(e,f,n)}let d=await gu(e,i,n);if(!d.id)throw mu(t,d);if(d.dm)return d.dm;return Qr(e,d.id,n,t)}let c=r.toLowerCase(),a="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(a)l.cursor=a;let u=await ie(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===c)return String(d.id??"");if(a=u.response_metadata?.next_cursor??"",!a)break}throw Error(`channel not found: ${t}`)}async function Yn(e,t,n){try{let o=await ie(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Te(e,t,n){try{let o=await ie(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function Du(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await ie(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function yu(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await ie(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function Vn(e,t){return Gt(e,"drafts.list",{},t)}async function wu(e,t,n,o){let{randomUUID:s}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:n}]}]}]);return Gt(e,"drafts.create",{client_msg_id:s(),destinations:JSON.stringify([{channel_id:t}]),blocks:r,file_ids:JSON.stringify([]),is_from_composer:"true"},o)}async function bu(e,t,n,o,s){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:o}]}]}]),i=(Date.now()/1000).toFixed(6);return Gt(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:r,file_ids:JSON.stringify([])},s)}async function ku(e,t,n){return Gt(e,"conversations.info",{channel:t},n)}async function Zn(e,t,n){return ie(e,"users.info",{user:t},n)}async function Qn(e,t,n){return ie(e,"conversations.info",{channel:t},n)}async function xu(e,t,n){let o=(Date.now()/1000).toFixed(6);return Gt(e,"drafts.delete",{draft_id:t,client_last_updated_ts:o},n)}async function ii(e,t){let n=await Gt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function Cu(e,t,n,o={},s){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:c}=await import("node:path"),a=r(n),l=c(n),u=await ie(e,"files.getUploadURLExternal",{filename:l,length:String(a.size)},s),{upload_url:d,file_id:f}=u;if(!d||!f)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let h=i(n),m=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:h});if(!m.ok)throw Error(`Upload PUT failed: ${m.status} ${m.statusText}`);let p={files:[{id:f,title:o.title??l}],channel_id:t};if(o.threadTs)p.thread_ts=o.threadTs;if(o.initialComment)p.initial_comment=o.initialComment;let D=await xe(e,"files.completeUploadExternal",p,s),x={fileId:f},b=D.files?.[0]?.permalink;if(b)x.permalink=b;return x}function Hn(e,t){let n=e;for(let o of t){if(n===void 0||n===null)return;if(typeof o==="number"){if(!Array.isArray(n))return;n=n[o]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[o]}}return n}import{existsSync as xh,readFileSync as Ch}from"node:fs";import{homedir as Eh}from"node:os";import{join as Sh}from"node:path";import{existsSync as ph,mkdirSync as hh,readFileSync as gh,writeFileSync as mh}from"node:fs";import{homedir as Dh}from"node:os";import{dirname as yh,join as wh}from"node:path";var bh=3600000,Vs={now:()=>Date.now(),path:()=>wh(process.env.HOME||Dh(),".config","slack-cli","cache.json")},Zs=!0,Ct;function Eu(){return{channels:{},users:{}}}function ai(){if(Ct)return Ct;if(Ct=Eu(),!Zs)return Ct;try{let e=Vs.path();if(!ph(e))return Ct;let t=JSON.parse(gh(e,"utf8"));for(let n of["channels","users"]){let o=t?.[n];if(!o||typeof o!=="object"||Array.isArray(o))continue;for(let[s,r]of Object.entries(o))if(r&&typeof r==="object"&&typeof r.value==="string"&&typeof r.expires==="number")Ct[n][s]={value:r.value,expires:r.expires}}}catch{Ct=Eu()}return Ct}function kh(e){if(!Zs)return;try{let t=Vs.path();hh(yh(t),{recursive:!0}),mh(t,JSON.stringify(e,null,2)+`
298
+ `)}catch{}}function Su(e,t){return e?`${e} ${t}`:void 0}function Qs(e,t,n){if(!Zs)return;let o=Su(t,n);if(!o)return;let s=ai()[e][o];if(!s)return;if(s.expires<=Vs.now()){delete ai()[e][o];return}return s.value}function eo(e,t,n,o,s=bh){if(!Zs)return;let r=Su(t,n);if(!r)return;let i=ai();i[e][r]={value:o,expires:Vs.now()+s},kh(i)}var ci={marker:"pushpin",progress:{done:"white_check_mark",dropped:"no_entry_sign",doing:"eyes",pending:"hourglass_flowing_sand"},flags:{alert:"exclamation","needs-discussion":"thinking_face",waiting:"speech_balloon",blocked:"lock"}},gn=["done","dropped","doing","pending"],Au=["alert","needs-discussion","waiting","blocked"];function Fh(){return Sh(process.env.HOME||Eh(),".config","slack-cli","todo.json")}function to(e){return e.replace(/^:+|:+$/g,"")}function es(e=Fh()){let t={marker:ci.marker,progress:{...ci.progress},flags:{...ci.flags}};try{if(!xh(e))return t;let n=JSON.parse(Ch(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=to(n.marker.trim());for(let o of gn){let s=n.progress?.[o];if(typeof s==="string"&&s.trim())t.progress[o]=to(s.trim())}for(let o of Au){let s=n.flags?.[o];if(typeof s==="string"&&s.trim())t.flags[o]=to(s.trim())}}catch{}return t}function Fu(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${to(e)}:`}function Tu(e,t,n={}){let o=n.shared===!0,s=(c)=>Fu(c,o),r=(c)=>Fu(c,o,!0),i=[];if(e==="untriaged")i.push(s(t.marker),...gn.map((c)=>r(t.progress[c])));else if(e==="stuck")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped),`(${Au.map((c)=>s(t.flags[c])).join(" OR ")})`);else if(e==="open")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped));else{let c=gn.indexOf(e);i.push(s(t.progress[e]));for(let a of gn.slice(0,c))i.push(r(t.progress[a]))}if(n.in){let c=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${c}`)}if(n.from){let c=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${c}`)}return i.join(" ")}var _h=3,$h={sleep:(e)=>Ah()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Ah(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ie(e,t,n=_h){for(let o=0;;o++)try{return await t()}catch(s){if(!(s instanceof Ze))throw s;if(o>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${s.retryAfter}s`),await $h.sleep(s.retryAfter*1000)}}var _u=new Map;async function Iu(e,t){let n=_u.get(e);if(n)return n;let o=await Ie("auth.test",()=>dn(e,t)),s={userId:o.userId,teamId:o.teamId};return _u.set(e,s),s}async function Ou(e,t){return(await Iu(e,t)).userId}async function li(e,t){try{return(await Iu(e,t)).teamId}catch{return""}}async function ui(e,t,n,o){if(!t.startsWith("#"))return n(e,t,o);let s=await li(e,o),r=Qs("channels",s,t);if(r)return r;let i=await Ie("resolveChannel",()=>n(e,t,o));return eo("channels",s,t,i),i}async function Pu(e,t,n,o){let s=await li(e,o),r=Qs("users",s,t);if(r)return r;let i=await Ie("users.info",()=>n(e,t,o));if(i&&i!==t)eo("users",s,t,i);return i}async function Ru(e,t,n,o){let s=await li(e,o),r=Qs("users",s,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let c=await Ie("users.info",()=>n(e,t,o));if(c?.user?.is_bot===!0||t==="USLACKBOT")return $u(s,t,null);let a=c?.user?.tz;i=typeof a==="string"&&a?a:null}catch{return null}return $u(s,t,i)}function $u(e,t,n){return eo("users",e,`tz:${t}`,n??"?"),n}async function Nu(e,t,n,o,s,r){let i=s.progress[o],c=await Ou(e,r),a=await Ie("reactions.get",()=>Oc(e,t,n,r)),l=new Set(a.filter((h)=>h.users.includes(c)).map((h)=>h.name)),u=gn.map((h)=>s.progress[h]).filter((h)=>l.has(h));if(u.length===1&&u[0]===i)return{noop:!0,removed:[],leftover:[]};if(!l.has(i))await Ie("reactions.add",()=>Ts(e,t,n,i,r));let d=[],f=[];for(let h of u){if(h===i)continue;try{await Ie("reactions.remove",()=>Is(e,t,n,h,r)),d.push(h)}catch{f.push(h)}}return{noop:!1,added:o,removed:d,leftover:f}}async function Bu(e,t,n,o,s,r,i){let c=s.flags[o];if(r)await Ie("reactions.remove",()=>Is(e,t,n,c,i));else await Ie("reactions.add",()=>Ts(e,t,n,c,i));return c}var di=1000;async function Mu(e,t,n,o={}){let s=o.limit??di,r=o.cookie,i=await Ou(e,r),c=gn.map((f)=>n.progress[f]),a=[],l=0,u,d=!1;while(l<s){let f=Math.min(200,s-l),h=await Ie("conversations.history",()=>Rn(e,t,f,void 0,u,r)),m=h.messages??[];l+=m.length;for(let p of m){let D=String(p.ts??"");if(!D)continue;let x=new Set((p.reactions??[]).filter((_)=>(_.users??[]).map(String).includes(i)).map((_)=>String(_.name??""))),b=c.filter((_)=>x.has(_));if(b.length<2)continue;a.push({ts:D,text:String(p.text??"").split(`
299
+ `)[0]??"",emoji:b,keep:b[0]})}if(u=h.response_metadata?.next_cursor||void 0,!u||m.length===0)break;if(l>=s){d=!0;break}}if(o.fix)for(let f of a)try{try{await Ie("reactions.add",()=>Ts(e,t,f.ts,f.keep,r))}catch(h){if(!(h instanceof Error)||!/already_reacted/.test(h.message))throw h}for(let h of f.emoji){if(h===f.keep)continue;await Ie("reactions.remove",()=>Is(e,t,f.ts,h,r))}f.fixed=!0}catch(h){f.fixed=!1,f.error=h instanceof Error?h.message:String(h)}return{scanned:l,findings:a,truncated:d}}var Th=!0,Ih;function fi(e){if(Th=e,!e)Ih=void 0}function qe(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
300
+ `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function pi(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function Zt(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Et(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Oh(e,t){let n=Zt(t),o=Et(e.profile);for(let r of[e.name,e.real_name,o.display_name,o.real_name])if(typeof r==="string"&&r&&Zt(r)===n)return!0;let s=typeof o.email==="string"?o.email.toLowerCase():"";return s!==""&&s===t.toLowerCase()}function Ph(e){let t=Et(e.profile),n=new Set;for(let o of[t.display_name,e.real_name,e.name,t.real_name])if(typeof o==="string"&&o){let s=Zt(o);if(s.length>=2)n.add(s)}return[...n]}function Rh(e,t){let n=Zt(e),o,s=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let c of Ph(r)){let a=-1;if(n===c)a=e.length;else for(let l of Lu)if(e.length>l.length&&e.endsWith(l)&&Zt(e.slice(0,e.length-l.length))===c){a=e.length-l.length;break}if(a<0)continue;if(!o||c.length>o.formLen)o={userId:i,matchLen:a,formLen:c.length,display:mi(r)},s=!1;else if(c.length===o.formLen&&o.userId!==i)s=!0}}if(!o)return;return s?"ambiguous":{userId:o.userId,matchLen:o.matchLen,display:o.display}}async function Qt(e,t,n,o){let s=`[${ju}ー]+`,r=`${s}(?:[._-]+${s})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),c=new Set;for(let b of t.matchAll(i))c.add(b[1]);if(c.size===0)return{text:t,resolved:[],unresolved:[]};let a=new Map;for(let b of c)a.set(b,{status:"pending"});let l=(b)=>{for(let _ of c){if(a.get(_).status!=="pending")continue;if(gi(_)){let A=Rh(_,b);if(A==="ambiguous")a.set(_,{status:"ambiguous"});else if(A)a.set(_,{status:"resolved",userId:A.userId,matchLen:A.matchLen,display:A.display})}else{let A=b.filter((j)=>Oh(j,_)),N=new Set(A.map((j)=>typeof j.id==="string"?j.id:"").filter(Boolean));if(N.size===1){let j=A.find((O)=>typeof O.id==="string");a.set(_,{status:"resolved",userId:j.id,matchLen:_.length,display:mi(j)})}else if(N.size>1)a.set(_,{status:"ambiguous"})}}},u=!1;try{let b=await Ns(e,o);l((b.members??[]).map(Et)),u=!0}catch{u=!1}let d=[...c].some((b)=>a.get(b).status==="pending"),f=!1,h=!0;if(d&&n){f=!0;try{let b=await yr(e,n,o),_=[];for(let A of b){let N=Et(await wr(e,A,o)),j=Et(N.user);if(typeof j.id!=="string")j.id=A;_.push(j)}l(_)}catch{h=!1}}let m=u&&(n?f&&h:!0),p=[],D=[];for(let b of c){let _=a.get(b);if(_.status==="resolved")p.push({surface:`@${b.slice(0,_.matchLen)}`,display:_.display,userId:_.userId});else if(_.status==="ambiguous")D.push({surface:`@${b}`,reason:"ambiguous"});else D.push({surface:`@${b}`,reason:m?"no-match":"unavailable"})}return{text:t.replace(i,(b,_)=>{let A=a.get(_);if(A&&A.status==="resolved")return`<@${A.userId}>${_.slice(A.matchLen)}`;return b}),resolved:p,unresolved:D}}function ts(e){let t=[],n=!1;for(let o of e)if(o.reason==="ambiguous")t.push(`${o.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(o.reason==="unavailable"){if(n)continue;t.push("could not fetch the user list (users:read missing or an API/connection error) — @mentions not tagged, sent as plain text"),n=!0}else t.push(`${o.surface} matched no one — not tagged, sent as plain text`);return t}async function vu(e,t,n,o={}){let s=o.warn??((i)=>process.stderr.write(`${i}
301
+ `)),r=await Qt(e,t,n,o.cookie);for(let i of ts(r.unresolved))s(`warn: ${i}`);return r.text}var Lu=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],ju="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function gi(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function Nh(e){let t=[],n=new RegExp(`([${ju}]{1,12})(${Lu.join("|")})`,"gu");for(let o of e.matchAll(n))t.push({ref:o[1],honorific:o[2]});for(let o of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:o[1],honorific:""});for(let o of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:o[1],honorific:""});return t}function Bh(e){let t=Et(e.profile),n=new Set;for(let o of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof o!=="string"||!o)continue;for(let s of[o,...o.split(/\s+/)]){let r=Zt(s);if(r.length>=2)n.add(r)}}return[...n]}function Mh(e,t){let n=Zt(e);if(n.length<2)return;for(let o of t)if(n===o)return o;if(gi(e)){for(let o of t)if(n.includes(o)||o.includes(n))return o}return}function mi(e){return[Et(e.profile).display_name,e.real_name,e.name].filter((o)=>typeof o==="string"&&o!=="")[0]??String(e.id??"?")}async function Wu(e,t,n){let o=Nh(t);if(o.length===0)return[];let s=new Set;for(let l of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))s.add(l[1]);let i=((await Ns(e,n)).members??[]).map(Et).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:Bh(l),display:mi(l)})).filter((l)=>l.id!==""),c=[],a=new Set;for(let{ref:l,honorific:u}of o)for(let d of i){let f=Mh(l,d.forms);if(!f)continue;if(s.has(d.id)||a.has(d.id))break;a.add(d.id),c.push({surface:gi(l)?`${f}${u}`:l,display:d.display,userId:d.id});break}return c}async function mn(e,t,n,o){let s=t,r=[],i=s,c=0;while(!0){let a=i.indexOf("<@U",c);if(a===-1)break;let l=i.slice(a+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);c=a+1}for(let a of r){if(!n.has(a))n.set(a,await Rs(e,a,o));let l=n.get(a)??a;s=s.replaceAll(`<@${a}>`,`@${l}`),s=s.replace(new RegExp(`<@${a}\\|[^>]*>`,"g"),`@${l}`)}return s}function ns(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=i[r.getUTCDay()]??"",l=c[r.getUTCMonth()]??"";return`${a}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Uu(e,t=new Date){let n=new Date(e*1000),o=hi(t),s=hi(new Date(t.getTime()-86400000)),r=hi(n);if(r===o)return"Today";if(r===s)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),c=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${c} ${String(n.getDate()).padStart(2,"0")}`}function hi(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Di(e){let t=new Date(e*1000),n=t.getFullYear(),o=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}`}function yi(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",o=!!t&&vh(t),s=o?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),c,a;try{let h=new Intl.DateTimeFormat("en-GB",{timeZone:s,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});a=h.format(e),c=Number(h.formatToParts(e).find((m)=>m.type==="hour")?.value??"12")}catch{return null}let l=r>i?c>=r||c<i:c>=r&&c<i,u=o?`${s}, recipient`:`${s}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${a} (${u})`;if(!l)return d;return`${d}
302
+ ⚠ QUIET HOURS (${r}:00-${i}:00) — this will buzz a phone.${o?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function vh(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{closeSync as Ju,mkdirSync as Lh,openSync as Ku,readFileSync as Dn,statSync as Hu,unlinkSync as no,writeFileSync as zu}from"node:fs";import{homedir as jh}from"node:os";import{join as qu}from"node:path";var os="Pinlog · 最終更新";function wi(e){let t=new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Tokyo",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=(s)=>t.find((r)=>r.type===s)?.value??"??",o=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${o}:${n("minute")} JST`}function Wh(e){return`_${os} ${wi(e)} · 更新はスレッドに_`}var bi=new RegExp(`(^|\\n+)_?${os} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function yn(e){return bi.test(e)}function rs(e){return e.replace(bi,"")}function ki(e,t){return`${rs(e).trimEnd()}
303
303
 
304
- ${Ch(t)}`}function pi(e){let n=e.match(di)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class ns extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function Eh(){return Au(process.env.HOME||kh(),".config","slack-cli","locks")}function Tu(e){let t=e.match(/^pid=(\d+)/);if(!t)return!0;try{return process.kill(Number(t[1]),0),!0}catch(n){return n.code==="EPERM"}}function xh(e,t){let n=`${e}.break`,o=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
305
- `,s;try{s=Su(n,"wx"),$u(s,o)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=mn(n,"utf8");if((/^pid=\d+/.test(i)?!Tu(i):Date.now()-_u(n).mtimeMs>1e4)&&mn(n,"utf8")===i)to(n)}catch{}return}try{if(mn(e,"utf8")===t)to(e)}catch{}finally{Fu(s);try{if(mn(n,"utf8")===o)to(n)}catch{}}}function Ou(e,t={}){let n=t.dir??Eh(),o=t.staleMs??120000;bh(n,{recursive:!0});let s=Au(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),r=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
306
- `;for(let i=0;i<3;i++)try{let c=Su(s,"wx");$u(c,r),Fu(c);let a=!0,l=()=>{if(!a)return;a=!1;try{if(mn(s,"utf8")===r)to(s)}catch{}};return process.once("exit",l),l}catch(c){if(c.code!=="EEXIST")throw c;let a,l;try{a=mn(s,"utf8"),l=Date.now()-_u(s).mtimeMs}catch{continue}if(/^pid=\d+/.test(a)?!Tu(a):l>o){xh(s,a);continue}throw new ns(a.trim().replace(/ nonce=\S+/,"")||"another process")}throw new ns("another process")}function Ge(e,t){return`${e}:${t}`}function no(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}function rs(e){if(!Ju(e))return;let t=Hu(e,"utf8");for(let n of t.split(`
307
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(!(r in process.env))process.env[r]=i}}function Ah(e){Sh(e,{recursive:!0});let t=xt(e,".gitignore");if(!Ju(t))zu(t,`*
308
- `)}function Th(){rs(xt(Iu(),".slack-cli",".env.local")),rs(xt(Iu(),".config/slack-cli",".env")),rs(xt(process.cwd(),".slack-cli",".env.local")),rs(xt(process.cwd(),".env.local")),rs(xt(process.cwd(),".env"))}function Oh(e){return Fh("sha256").update(e).digest("hex")}function O(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Y(e){return Array.isArray(e)?e:[]}function io(e){return Number(e.ts??0)}async function qu(e,t,n){let o=t.user;if(typeof o==="string"){if(!n.has(o))n.set(o,await Ae(e,o));return n.get(o)??o}return typeof t.username==="string"?t.username:"bot"}function hi(e){let t=new Date(e*1000),n=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),c=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}:${c}`}function mi(e){let[t,n="000000"]=e.split("."),o=Number(t),s=new Date(o*1000),r=s.getUTCFullYear(),i=String(s.getUTCMonth()+1).padStart(2,"0"),c=String(s.getUTCDate()).padStart(2,"0"),a=String(s.getUTCHours()).padStart(2,"0"),l=String(s.getUTCMinutes()).padStart(2,"0"),u=String(s.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${r}-${i}-${c}T${a}:${l}:${u}.${d}`}function Di(e){let t=e.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\.(\d{6})$/);if(!t)throw Error(`Invalid message timestamp "${e}" \u2014 expected 2026-05-11T06:01:04.000100`);let n=Date.parse(t[1]+"Z");if(isNaN(n))throw Error(`Cannot parse date in "${e}"`);return`${Math.floor(n/1000)}.${t[2]}`}function Ih(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Di(e):e}async function fo(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:`${io(t)}.000000`,i=mi(r),c="?";if(typeof t.user==="string"){let b=t.user,_="@"+b;if(!n.has(_)){let A=await gu(e,b,async(N,j,I)=>(await Xn(N,j,I))[1],s);n.set(_,A)}c=n.get(_)??b}else if(typeof t.username==="string")c=t.username;let a=typeof t.text==="string"?t.text:"",u=ts(await gn(e,a,n,s)).split(`
304
+ ${Wh(t)}`}function xi(e){let n=e.match(bi)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class ss extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function Uh(){return qu(process.env.HOME||jh(),".config","slack-cli","locks")}function Gu(e){let t=e.match(/^pid=(\d+)/);if(!t)return!0;try{return process.kill(Number(t[1]),0),!0}catch(n){return n.code==="EPERM"}}function Jh(e,t){let n=`${e}.break`,o=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
305
+ `,s;try{s=Ku(n,"wx"),zu(s,o)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=Dn(n,"utf8");if((/^pid=\d+/.test(i)?!Gu(i):Date.now()-Hu(n).mtimeMs>1e4)&&Dn(n,"utf8")===i)no(n)}catch{}return}try{if(Dn(e,"utf8")===t)no(e)}catch{}finally{Ju(s);try{if(Dn(n,"utf8")===o)no(n)}catch{}}}function Xu(e,t={}){let n=t.dir??Uh(),o=t.staleMs??120000;Lh(n,{recursive:!0});let s=qu(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),r=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
306
+ `;for(let i=0;i<3;i++)try{let c=Ku(s,"wx");zu(c,r),Ju(c);let a=!0,l=()=>{if(!a)return;a=!1;try{if(Dn(s,"utf8")===r)no(s)}catch{}};return process.once("exit",l),l}catch(c){if(c.code!=="EEXIST")throw c;let a,l;try{a=Dn(s,"utf8"),l=Date.now()-Hu(s).mtimeMs}catch{continue}if(/^pid=\d+/.test(a)?!Gu(a):l>o){Jh(s,a);continue}throw new ss(a.trim().replace(/ nonce=\S+/,"")||"another process")}throw new ss("another process")}function Ge(e,t){return`${e}:${t}`}function so(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}function is(e){if(!cd(e))return;let t=ld(e,"utf8");for(let n of t.split(`
307
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(!(r in process.env))process.env[r]=i}}function Gh(e){Hh(e,{recursive:!0});let t=St(e,".gitignore");if(!cd(t))ud(t,`*
308
+ `)}function Xh(){is(St(Yu(),".slack-cli",".env.local")),is(St(Yu(),".config/slack-cli",".env")),is(St(process.cwd(),".slack-cli",".env.local")),is(St(process.cwd(),".env.local")),is(St(process.cwd(),".env"))}function Yh(e){return Kh("sha256").update(e).digest("hex")}function I(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Y(e){return Array.isArray(e)?e:[]}function ao(e){return Number(e.ts??0)}async function dd(e,t,n){let o=t.user;if(typeof o==="string"){if(!n.has(o))n.set(o,await Te(e,o));return n.get(o)??o}return typeof t.username==="string"?t.username:"bot"}function Ci(e){let t=new Date(e*1000),n=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),c=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}:${c}`}function Si(e){let[t,n="000000"]=e.split("."),o=Number(t),s=new Date(o*1000),r=s.getUTCFullYear(),i=String(s.getUTCMonth()+1).padStart(2,"0"),c=String(s.getUTCDate()).padStart(2,"0"),a=String(s.getUTCHours()).padStart(2,"0"),l=String(s.getUTCMinutes()).padStart(2,"0"),u=String(s.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${r}-${i}-${c}T${a}:${l}:${u}.${d}`}function Fi(e){let t=e.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\.(\d{6})$/);if(!t)throw Error(`Invalid message timestamp "${e}" \u2014 expected 2026-05-11T06:01:04.000100`);let n=Date.parse(t[1]+"Z");if(isNaN(n))throw Error(`Cannot parse date in "${e}"`);return`${Math.floor(n/1000)}.${t[2]}`}function Vh(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Fi(e):e}async function po(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:`${ao(t)}.000000`,i=Si(r),c="?";if(typeof t.user==="string"){let b=t.user,_="@"+b;if(!n.has(_)){let A=await Pu(e,b,async(N,j,O)=>(await Yn(N,j,O))[1],s);n.set(_,A)}c=n.get(_)??b}else if(typeof t.username==="string")c=t.username;let a=typeof t.text==="string"?t.text:"",u=ns(await mn(e,a,n,s)).split(`
309
309
  `),d=u[0]+(u.length>1?`
310
310
  `+u.slice(1).map((b)=>` ${b}`).join(`
311
- `):""),f=o?`${o} @${c}`:`@${c}`,h=Y(t.reactions).map(O).map((b)=>{let _=typeof b.name==="string"?b.name:"",A=Number(b.count??Y(b.users).length??0);return _?`:${_}:\xD7${A}`:""}).filter(Boolean).join(" "),m=Y(t.files).map(O).map((b)=>{let _=typeof b.name==="string"?b.name:typeof b.title==="string"?b.title:"(file)",A=typeof b.size==="number"?` (${po(b.size)})`:"",N=typeof b.id==="string"?` [${b.id}]`:"";return`
312
- \uD83D\uDCCE ${_}${A}${N}`}).join(""),p=Number(t.reply_count??0),D=p>0?` [+${p} ${p===1?"reply":"replies"}]`:"",C=(h?`
313
- ${h}`:"")+m;return`${i} ${f}: ${d}${D}${C}`}function po(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function Ph(e){return Y(e.files).map(O).map((t)=>({id:t.id??null,name:t.name??t.title??null,mimetype:t.mimetype??null,size:t.size??null,url_private_download:t.url_private_download??t.url_private??null,permalink:t.permalink??null}))}function Gu(e){let t=Ph(e);return{ts:e.ts??null,user:e.user??null,username:e.username??null,bot_id:e.bot_id??null,thread_ts:e.thread_ts??null,text:typeof e.text==="string"?e.text:"",...Array.isArray(e.reactions)&&e.reactions.length?{reactions:Y(e.reactions).map(O).map((n)=>({name:n.name??null,count:n.count??null,users:Array.isArray(n.users)?n.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{}}}async function Rh(e,t,n,o,s){let r=[];for(let i of n){let c=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let a=await ze(e,t,i.ts,200,s),l=Y(a.messages).map(O);c=l[l.length-1]??i}if(c.user!==o)r.push(i)}return r}async function Nh(e,t,n,o="text",s=!1,r){let i=Yt(t),c=await pe(e,t,r),a=new Map,u=await(async()=>{if(i?.threadTs){let f=await ze(e,c,i.threadTs,n,r);return Y(f.messages).map(O)}let d=await nt(e,c,n,void 0,void 0,r);return Y(d.messages).map(O).reverse()})();if(s){let{userId:d}=await Rl(e,r);u=await Rh(e,c,u,d,r)}if(o==="jsonl"){for(let d of u)console.log(JSON.stringify(Gu(d)));return}for(let d of u)console.log(await fo(e,d,a,void 0,r))}async function Bh(e,t,n,o,s="text",r){let i=await pe(e,t,r),c=await ze(e,i,Ih(n),o,r),a=Y(c.messages).map(O);if(s==="jsonl"){for(let u of a)console.log(JSON.stringify(Gu(u)));return}let l=new Map;for(let u of a)console.log(await fo(e,u,l,void 0,r))}async function Mh(e){let t=await Gn(e),n=Y(t.channels).map(O).filter((s)=>s.is_member===!0).sort((s,r)=>Number(r.updated??0)-Number(s.updated??0)).slice(0,10),o=new Map;for(let s of n){let r=String(s.id??""),i=typeof s.name==="string"?s.name:typeof s.user==="string"?s.user:r,c=await nt(e,r,5),a=Y(c.messages).map(O).filter((l)=>l.subtype===void 0||l.subtype===null).filter((l)=>{let u=typeof l.text==="string"?l.text:"";return u.length>0&&!u.startsWith("<@")}).slice(0,3).reverse();if(a.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let l of a){let u=await qu(e,l,o),d=(typeof l.text==="string"?l.text:"").split(`
314
- `)[0]??"",f=await gn(e,d,o);console.log(` ${u}: ${f}`)}}}async function vh(e,t){let n=await Ll(e,"to:me"),o=Y(Hn(n,["messages","matches"])).map(O).slice(0,t),s=new Map,r=[];for(let i of o){let c=xu(io(i)),a=r[r.length-1];if(a?.label===c)a.msgs.push(i);else r.push({label:c,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:c,msgs:a}=r[i];if(i>0)console.log("");console.log(` ${c}`),console.log(" ----------------------------");for(let l of[...a].reverse()){let u=O(l.channel),d=u.is_im===!0,f=typeof u.name==="string"?u.name:"dm",h;if(d&&f.startsWith("U")){let m="@"+f;if(!s.has(m)){let[,p]=await Xn(e,f);s.set(m,p)}h=`@${s.get(m)??f}`}else if(d)h=`@${f}`;else h=`#${f}`;console.log(await fo(e,l,s,h))}}}async function Lh(e,t,n,o,s="text",r){let i=await Gn(e,r),c=Y(i.channels).map(O).filter((a)=>o||a.is_member===!0).filter((a)=>{if(!n)return!0;return(typeof a.name==="string"?a.name:"").toLowerCase().includes(n.toLowerCase())}).sort((a,l)=>Number(l.updated??0)-Number(a.updated??0)).slice(0,t);if(s==="jsonl"){for(let a of c)console.log(JSON.stringify(a));return}for(let a of c){let l=String(a.id??""),u=typeof a.name==="string"?a.name:typeof a.user==="string"?a.user:l,d=a.is_im===!0,f=a.is_mpim===!0,h=d||f?"@":"#",m=a.is_member===!0?"":" (not joined)",p=typeof O(a.purpose).value==="string"?String(O(a.purpose).value):"",D=p?` ${p.split(`
315
- `)[0]?.slice(0,60)}`:"";console.log(`${h}${u} ${l}${m}${D}`)}}function jh(e){let t=(s)=>s.startsWith("xoxp-")||s.startsWith("xoxc-"),n=Zo(),o=n.find((s)=>s.profile.token===e);if(!o)return;return n.find((s)=>t(s.profile.token)&&s.profile.teamId===o.profile.teamId)}async function Xu(e,t,n,o,s){let r=e,i=s,c;try{c=await Xr(r,t,n,i)}catch(u){let d=u instanceof Error?u.message:String(u);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=jh(e);if(f)console.error(`Note: search.messages needs a user token \u2014 the active profile is a bot token (xoxb-); falling back to profile "${f.name}".`),r=f.profile.token,i=f.profile.cookie,c=await Xr(r,t,n,i);else console.error(`Error: search requires a user token (xoxp-/xoxc-) \u2014 the active profile is a bot token (xoxb-), which Slack rejects for search.messages.
311
+ `):""),f=o?`${o} @${c}`:`@${c}`,h=Y(t.reactions).map(I).map((b)=>{let _=typeof b.name==="string"?b.name:"",A=Number(b.count??Y(b.users).length??0);return _?`:${_}:\xD7${A}`:""}).filter(Boolean).join(" "),m=Y(t.files).map(I).map((b)=>{let _=typeof b.name==="string"?b.name:typeof b.title==="string"?b.title:"(file)",A=typeof b.size==="number"?` (${ho(b.size)})`:"",N=typeof b.id==="string"?` [${b.id}]`:"";return`
312
+ \uD83D\uDCCE ${_}${A}${N}`}).join(""),p=Number(t.reply_count??0),D=p>0?` [+${p} ${p===1?"reply":"replies"}]`:"",x=(h?`
313
+ ${h}`:"")+m;return`${i} ${f}: ${d}${D}${x}`}function ho(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function Zh(e){return Y(e.files).map(I).map((t)=>({id:t.id??null,name:t.name??t.title??null,mimetype:t.mimetype??null,size:t.size??null,url_private_download:t.url_private_download??t.url_private??null,permalink:t.permalink??null}))}function fd(e){let t=Zh(e);return{ts:e.ts??null,user:e.user??null,username:e.username??null,bot_id:e.bot_id??null,thread_ts:e.thread_ts??null,text:typeof e.text==="string"?e.text:"",...Array.isArray(e.reactions)&&e.reactions.length?{reactions:Y(e.reactions).map(I).map((n)=>({name:n.name??null,count:n.count??null,users:Array.isArray(n.users)?n.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{}}}async function Qh(e,t,n,o,s){let r=[];for(let i of n){let c=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let a=await ze(e,t,i.ts,200,s),l=Y(a.messages).map(I);c=l[l.length-1]??i}if(c.user!==o)r.push(i)}return r}async function eg(e,t,n,o="text",s=!1,r){let i=Vt(t),c=await he(e,t,r),a=new Map,u=await(async()=>{if(i?.threadTs){let f=await ze(e,c,i.threadTs,n,r);return Y(f.messages).map(I)}let d=await nt(e,c,n,void 0,void 0,r);return Y(d.messages).map(I).reverse()})();if(s){let{userId:d}=await ni(e,r);u=await Qh(e,c,u,d,r)}if(o==="jsonl"){for(let d of u)console.log(JSON.stringify(fd(d)));return}for(let d of u)console.log(await po(e,d,a,void 0,r))}async function tg(e,t,n,o,s="text",r){let i=await he(e,t,r),c=await ze(e,i,Vh(n),o,r),a=Y(c.messages).map(I);if(s==="jsonl"){for(let u of a)console.log(JSON.stringify(fd(u)));return}let l=new Map;for(let u of a)console.log(await po(e,u,l,void 0,r))}async function ng(e){let t=await Xn(e),n=Y(t.channels).map(I).filter((s)=>s.is_member===!0).sort((s,r)=>Number(r.updated??0)-Number(s.updated??0)).slice(0,10),o=new Map;for(let s of n){let r=String(s.id??""),i=typeof s.name==="string"?s.name:typeof s.user==="string"?s.user:r,c=await nt(e,r,5),a=Y(c.messages).map(I).filter((l)=>l.subtype===void 0||l.subtype===null).filter((l)=>{let u=typeof l.text==="string"?l.text:"";return u.length>0&&!u.startsWith("<@")}).slice(0,3).reverse();if(a.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let l of a){let u=await dd(e,l,o),d=(typeof l.text==="string"?l.text:"").split(`
314
+ `)[0]??"",f=await mn(e,d,o);console.log(` ${u}: ${f}`)}}}async function sg(e,t){let n=await su(e,"to:me"),o=Y(Hn(n,["messages","matches"])).map(I).slice(0,t),s=new Map,r=[];for(let i of o){let c=Uu(ao(i)),a=r[r.length-1];if(a?.label===c)a.msgs.push(i);else r.push({label:c,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:c,msgs:a}=r[i];if(i>0)console.log("");console.log(` ${c}`),console.log(" ----------------------------");for(let l of[...a].reverse()){let u=I(l.channel),d=u.is_im===!0,f=typeof u.name==="string"?u.name:"dm",h;if(d&&f.startsWith("U")){let m="@"+f;if(!s.has(m)){let[,p]=await Yn(e,f);s.set(m,p)}h=`@${s.get(m)??f}`}else if(d)h=`@${f}`;else h=`#${f}`;console.log(await po(e,l,s,h))}}}async function og(e,t,n,o,s="text",r){let i=await Xn(e,r),c=Y(i.channels).map(I).filter((a)=>o||a.is_member===!0).filter((a)=>{if(!n)return!0;return(typeof a.name==="string"?a.name:"").toLowerCase().includes(n.toLowerCase())}).sort((a,l)=>Number(l.updated??0)-Number(a.updated??0)).slice(0,t);if(s==="jsonl"){for(let a of c)console.log(JSON.stringify(a));return}for(let a of c){let l=String(a.id??""),u=typeof a.name==="string"?a.name:typeof a.user==="string"?a.user:l,d=a.is_im===!0,f=a.is_mpim===!0,h=d||f?"@":"#",m=a.is_member===!0?"":" (not joined)",p=typeof I(a.purpose).value==="string"?String(I(a.purpose).value):"",D=p?` ${p.split(`
315
+ `)[0]?.slice(0,60)}`:"";console.log(`${h}${u} ${l}${m}${D}`)}}function rg(e){let t=(s)=>s.startsWith("xoxp-")||s.startsWith("xoxc-"),n=nr(),o=n.find((s)=>s.profile.token===e);if(!o)return;return n.find((s)=>t(s.profile.token)&&s.profile.teamId===o.profile.teamId)}async function pd(e,t,n,o,s){let r=e,i=s,c;try{c=await oi(r,t,n,i)}catch(u){let d=u instanceof Error?u.message:String(u);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=rg(e);if(f)console.error(`Note: search.messages needs a user token \u2014 the active profile is a bot token (xoxb-); falling back to profile "${f.name}".`),r=f.profile.token,i=f.profile.cookie,c=await oi(r,t,n,i);else console.error(`Error: search requires a user token (xoxp-/xoxc-) \u2014 the active profile is a bot token (xoxb-), which Slack rejects for search.messages.
316
316
  `+` Add a user-token profile: slack auth login (or slack auth login --token <token>)
317
- Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(o){console.log(JSON.stringify(c,null,2));return}let a=Y(Hn(c,["messages","matches"])).map(O),l=new Map;for(let u of a){let d=O(u.channel),f=d.is_im===!0,h=typeof d.name==="string"?d.name:"dm",m;if(f&&h.startsWith("U")){let p="@"+h;if(!l.has(p)){let[,D]=await Xn(r,h,i);l.set(p,D)}m=`@${l.get(p)??h}`}else if(f)m=`@${h}`;else m=`#${h}`;console.log(await fo(r,u,l,m,i))}}async function Yu(e,t,n,o){let{ref:s,ts:r}=_t(t);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:1700000000.000100 or a Slack permalink URL)"),process.exit(2);return{channelId:n??await ti(e,s,pe,o),ts:r}}async function Wh(e,t){let n=Qn(),o={};if(!t.mine)o.shared=!0;if(t.in)o.in=t.in;if(t.from)o.from=t.from;let s=fu(t.state,n,o);if(!t.json){let r=await yn(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${Zu(r)} \xB7 matching ${i})`),console.error(`(query: ${s})`)}await Te("search.messages",()=>Xu(e,s,t.count,t.json,t.cookie))}async function Uh(e,t){let n=Qn(),{channelId:o,ts:s}=await Yu(e,t.target,t.channelId,t.cookie),r=await Du(e,o,s,t.state,n,t.cookie);if(r.noop){console.log(`= Already ${t.state} (ts: ${s})`);return}let i=r.removed.length?`, removed ${r.removed.map((c)=>`:${c}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${s})${i}`),r.leftover.length)console.error(`\u26A0 ${r.leftover.map((c)=>`:${c}:`).join(" ")} could not be removed \u2014 this message now carries more than one `+"progress reaction. Readers collapse by priority so nothing is lost; repair with: slack todo doctor --in <#chan> --fix")}async function Kh(e,t){let n=Qn(),{channelId:o,ts:s}=await Yu(e,t.target,t.channelId,t.cookie),r=await yu(e,o,s,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${r}: (ts: ${s})`)}async function Jh(e,t){let n=Qn(),o=t.channelId??await ti(e,t.channel,pe,t.cookie),s={limit:t.limit};if(t.fix)s.fix=!0;if(t.cookie)s.cookie=t.cookie;let r=await wu(e,o,n,s);if(r.findings.length===0)console.log(`\u2713 No multi-state tasks in ${r.scanned} message(s).`);else{for(let i of r.findings){let c=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((a)=>`:${a}:`).join(" ")} \u2192 keep :${i.keep}: [${c}] ${q(i.text).slice(0,60)}`)}console.log(`${r.findings.length} multi-state task(s) in ${r.scanned} message(s).`)}if(r.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function Hh(e,t,n,o){let s=Math.floor(Date.now()/1000)-t*86400,r=await Gn(e),i=Y(r.channels).map(O).filter((u)=>u.is_member===!0&&u.is_im!==!0&&u.is_mpim!==!0).filter((u)=>{if(!o)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(o.toLowerCase())}).sort((u,d)=>Number(d.updated??0)-Number(u.updated??0)),c=new Map,a=0,l=0;for(let u of i){let d=String(u.id??""),f=typeof u.name==="string"?u.name:d,h;try{h=await nt(e,d,n)}catch(p){console.error(` SKIP #${f}: ${p.message}`);continue}let m=Y(h.messages).map(O).filter((p)=>(p.subtype===void 0||p.subtype===null)&&io(p)>=s);if(m.length===0)continue;l+=1,a+=m.length,console.log(`## #${f} (${m.length} msgs)
318
- `);for(let p of[...m].reverse()){let D=await qu(e,p,c),C=typeof p.text==="string"?p.text:"",_=ts(await gn(e,C,c)).split(`
319
- `).join(" \u21B5 ");console.log(`[${ci(io(p))}] ${D}: ${_}`)}console.log("")}console.error(`Dumped ${a} messages across ${l} channels (cutoff: ${t}d)`)}function zh(e){let t=[];function n(o){if(typeof o==="string"){t.push(o);return}if(Array.isArray(o)){for(let s of o)n(s);return}if(o&&typeof o==="object"){let s=o;if(typeof s.text==="string"){t.push(s.text);return}if(Array.isArray(s.elements))n(s.elements);else if(Array.isArray(s.content))n(s.content)}}for(let o of e)n(o);return t.join("").trim()}async function Vu(e,t,n){let o=new Map;return async(s)=>{if(!s)return"(unknown)";if(o.has(s))return o.get(s);try{let r=await su(e,s,t),i=O(r.channel),c;if(i.is_im===!0){let a=typeof i.user==="string"?i.user:"";if(!a||a===n)c="@self";else{let[l]=await Xn(e,a);c=`@${l}`}}else c=`#${typeof i.name==="string"?i.name:s}`;return o.set(s,c),c}catch{return s}}}function yi(e){let t=O(Y(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function ao(e){return zh(Y(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function qh(e,t,n=!1){let o=await Yn(e,t),s=Y(o.drafts??o.messages??[]).map(O).filter((l)=>l.is_deleted!==!0),r=n?s:s.filter((l)=>l.is_sent!==!0);if(r.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await Vr(e,t))}catch{}let c=await Vu(e,t,i),a=new Map;for(let l of r){let u=yi(l),d=ao(l),f=Number(l.date_created??l.date_create??0),h=f?hi(f):"?",m=await c(u),p=typeof l.id==="string"?l.id:"",D=l.is_sent===!0?" [SENT]":"",C=ts(await gn(e,d,a));console.log(`-- ${p} ${m} [${h}]${D}`);for(let b of C.split(`
320
- `))console.log(` ${b}`)}}async function Gh(e,t,n){let o=await Yn(e,t),s=Y(o.drafts).map(O).find((m)=>String(m.id)===n);if(!s)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await Vr(e,t))}catch{}let i=await Vu(e,t,r),c=yi(s),a=ao(s),l=Number(s.date_created??0),u=String(s.last_updated_ts??"?"),d=await i(c),h=ts(await gn(e,a,new Map));console.log(`id: ${s.id}`),console.log(`channel: ${d} (${c})`),console.log(`created: ${l?hi(l):"?"}`),console.log(`updated: ${hi(Number(u.split(".")[0]))}`),console.log(`status: ${s.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(h)}function xe(...e){return Oh(e.join(`
321
- `)).slice(0,4)}function q(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var Xh={"reactions.add":"reactions:write","reactions.remove":"reactions:write","chat.postMessage":"chat:write","chat.update":"chat:write","chat.delete":"chat:write","pins.add":"pins:write","conversations.replies":"channels:history (or groups:history)","conversations.history":"channels:history (or groups:history)"};function me(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,o,s]=n;switch(s){case"missing_scope":return`Error: token lacks the ${Xh[o]??"the required"} scope (needed for ${o}). Add it to your Slack App's User Token Scopes (or Bot Token Scopes if you use a bot token / --as-bot) \u2014 it must be on the token type the CLI actually uses \u2014 then reinstall to the workspace.`;case"invalid_name":return"Error: not a valid emoji shortcode \u2014 use the name without colons (e.g. white_check_mark), and make sure it exists in the workspace.";case"already_reacted":return"Error: you've already added that reaction to the message.";case"no_reaction":return"Error: that reaction isn't on the message \u2014 nothing to remove.";case"message_not_found":return"Error: no message found at that timestamp in the channel \u2014 check the target ts/permalink.";case"channel_not_found":return"Error: channel not found \u2014 check the target.";default:return t}}async function ho(e,t,n){if(!t.startsWith("D"))return null;try{let o=await go(e,t,n);if(!o)return null;return await mu(e,o,Vn,n)}catch{return null}}function Fe(e,t,n,o,s=new Date){for(let i of n)console.log(i);let r=li(s,o);if(r)console.log(r);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function _t(e){let t=Yt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let o=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,n),ts:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,n),ts:Di(o)}}}return{ref:e}}function wn(e,t=!0){let n=Yt(e);if(n){if(!t)return{ref:n.channel};let s=n.threadTs??n.ts;return s?{ref:n.channel,threadTs:s}:{ref:n.channel}}let o=e.indexOf(":");if(o>0){let s=e.slice(o+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,o),threadTs:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,o),threadTs:Di(s)}}return{ref:e}}async function St(e,t,n,o){let s=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=O(await Zn(e,t,o)),c=O(i.channel);if(c.is_im===!0){let a=typeof c.user==="string"?c.user:"";s=a?`@${await Ae(e,a,o)}`:t}else s=typeof c.name==="string"?`#${c.name}`:t}catch{s=t}return s===t?t:`${s} (${t})`}async function yn(e,t){try{return await Xs(e,t)}catch{return null}}function dt(e,t){let n;return async()=>{if(n===void 0)n=await yn(e,t);return n}}function Qt(e){if(!Jr())return{record:()=>{}};let t=Fl();return{metadata:Sl(e,t),record:(n)=>{$l({...n,kind:e,attribution:t})}}}function Yh(e){let t=q(e.text.split(`
322
- `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,o=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${ci(e.sent_at/1000)} ${e.kind.padEnd(4)} ${q(e.target??e.channel)} ${n}
317
+ Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(o){console.log(JSON.stringify(c,null,2));return}let a=Y(Hn(c,["messages","matches"])).map(I),l=new Map;for(let u of a){let d=I(u.channel),f=d.is_im===!0,h=typeof d.name==="string"?d.name:"dm",m;if(f&&h.startsWith("U")){let p="@"+h;if(!l.has(p)){let[,D]=await Yn(r,h,i);l.set(p,D)}m=`@${l.get(p)??h}`}else if(f)m=`@${h}`;else m=`#${h}`;console.log(await po(r,u,l,m,i))}}async function hd(e,t,n,o){let{ref:s,ts:r}=$t(t);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:1700000000.000100 or a Slack permalink URL)"),process.exit(2);return{channelId:n??await ui(e,s,he,o),ts:r}}async function ig(e,t){let n=es(),o={};if(!t.mine)o.shared=!0;if(t.in)o.in=t.in;if(t.from)o.from=t.from;let s=Tu(t.state,n,o);if(!t.json){let r=await rt(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${md(r)} \xB7 matching ${i})`),console.error(`(query: ${s})`)}await Ie("search.messages",()=>pd(e,s,t.count,t.json,t.cookie))}async function ag(e,t){let n=es(),{channelId:o,ts:s}=await hd(e,t.target,t.channelId,t.cookie),r=await Nu(e,o,s,t.state,n,t.cookie);if(r.noop){console.log(`= Already ${t.state} (ts: ${s})`);return}let i=r.removed.length?`, removed ${r.removed.map((c)=>`:${c}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${s})${i}`),r.leftover.length)console.error(`\u26A0 ${r.leftover.map((c)=>`:${c}:`).join(" ")} could not be removed \u2014 this message now carries more than one `+"progress reaction. Readers collapse by priority so nothing is lost; repair with: slack todo doctor --in <#chan> --fix")}async function cg(e,t){let n=es(),{channelId:o,ts:s}=await hd(e,t.target,t.channelId,t.cookie),r=await Bu(e,o,s,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${r}: (ts: ${s})`)}async function lg(e,t){let n=es(),o=t.channelId??await ui(e,t.channel,he,t.cookie),s={limit:t.limit};if(t.fix)s.fix=!0;if(t.cookie)s.cookie=t.cookie;let r=await Mu(e,o,n,s);if(r.findings.length===0)console.log(`\u2713 No multi-state tasks in ${r.scanned} message(s).`);else{for(let i of r.findings){let c=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((a)=>`:${a}:`).join(" ")} \u2192 keep :${i.keep}: [${c}] ${q(i.text).slice(0,60)}`)}console.log(`${r.findings.length} multi-state task(s) in ${r.scanned} message(s).`)}if(r.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function ug(e,t,n,o){let s=Math.floor(Date.now()/1000)-t*86400,r=await Xn(e),i=Y(r.channels).map(I).filter((u)=>u.is_member===!0&&u.is_im!==!0&&u.is_mpim!==!0).filter((u)=>{if(!o)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(o.toLowerCase())}).sort((u,d)=>Number(d.updated??0)-Number(u.updated??0)),c=new Map,a=0,l=0;for(let u of i){let d=String(u.id??""),f=typeof u.name==="string"?u.name:d,h;try{h=await nt(e,d,n)}catch(p){console.error(` SKIP #${f}: ${p.message}`);continue}let m=Y(h.messages).map(I).filter((p)=>(p.subtype===void 0||p.subtype===null)&&ao(p)>=s);if(m.length===0)continue;l+=1,a+=m.length,console.log(`## #${f} (${m.length} msgs)
318
+ `);for(let p of[...m].reverse()){let D=await dd(e,p,c),x=typeof p.text==="string"?p.text:"",_=ns(await mn(e,x,c)).split(`
319
+ `).join(" \u21B5 ");console.log(`[${Di(ao(p))}] ${D}: ${_}`)}console.log("")}console.error(`Dumped ${a} messages across ${l} channels (cutoff: ${t}d)`)}function dg(e){let t=[];function n(o){if(typeof o==="string"){t.push(o);return}if(Array.isArray(o)){for(let s of o)n(s);return}if(o&&typeof o==="object"){let s=o;if(typeof s.text==="string"){t.push(s.text);return}if(Array.isArray(s.elements))n(s.elements);else if(Array.isArray(s.content))n(s.content)}}for(let o of e)n(o);return t.join("").trim()}async function gd(e,t,n){let o=new Map;return async(s)=>{if(!s)return"(unknown)";if(o.has(s))return o.get(s);try{let r=await ku(e,s,t),i=I(r.channel),c;if(i.is_im===!0){let a=typeof i.user==="string"?i.user:"";if(!a||a===n)c="@self";else{let[l]=await Yn(e,a);c=`@${l}`}}else c=`#${typeof i.name==="string"?i.name:s}`;return o.set(s,c),c}catch{return s}}}function _i(e){let t=I(Y(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function co(e){return dg(Y(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function fg(e,t,n=!1){let o=await Vn(e,t),s=Y(o.drafts??o.messages??[]).map(I).filter((l)=>l.is_deleted!==!0),r=n?s:s.filter((l)=>l.is_sent!==!0);if(r.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await ii(e,t))}catch{}let c=await gd(e,t,i),a=new Map;for(let l of r){let u=_i(l),d=co(l),f=Number(l.date_created??l.date_create??0),h=f?Ci(f):"?",m=await c(u),p=typeof l.id==="string"?l.id:"",D=l.is_sent===!0?" [SENT]":"",x=ns(await mn(e,d,a));console.log(`-- ${p} ${m} [${h}]${D}`);for(let b of x.split(`
320
+ `))console.log(` ${b}`)}}async function pg(e,t,n){let o=await Vn(e,t),s=Y(o.drafts).map(I).find((m)=>String(m.id)===n);if(!s)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await ii(e,t))}catch{}let i=await gd(e,t,r),c=_i(s),a=co(s),l=Number(s.date_created??0),u=String(s.last_updated_ts??"?"),d=await i(c),h=ns(await mn(e,a,new Map));console.log(`id: ${s.id}`),console.log(`channel: ${d} (${c})`),console.log(`created: ${l?Ci(l):"?"}`),console.log(`updated: ${Ci(Number(u.split(".")[0]))}`),console.log(`status: ${s.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(h)}function De(...e){return Yh(e.join(`
321
+ `)).slice(0,4)}function q(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var hg={"reactions.add":"reactions:write","reactions.remove":"reactions:write","chat.postMessage":"chat:write","chat.update":"chat:write","chat.delete":"chat:write","pins.add":"pins:write","slackLists.create":"lists:write","slackLists.items.create":"lists:write","slackLists.items.update":"lists:write","slackLists.items.list":"lists:read","slackLists.access.set":"lists:write","conversations.replies":"channels:history (or groups:history)","conversations.history":"channels:history (or groups:history)"};function ce(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,o,s]=n;switch(s){case"missing_scope":return`Error: token lacks the ${hg[o]??"the required"} scope (needed for ${o}). Add it to your Slack App's User Token Scopes (or Bot Token Scopes if you use a bot token / --as-bot) \u2014 it must be on the token type the CLI actually uses \u2014 then reinstall to the workspace.`;case"invalid_name":return"Error: not a valid emoji shortcode \u2014 use the name without colons (e.g. white_check_mark), and make sure it exists in the workspace.";case"already_reacted":return"Error: you've already added that reaction to the message.";case"no_reaction":return"Error: that reaction isn't on the message \u2014 nothing to remove.";case"message_not_found":return"Error: no message found at that timestamp in the channel \u2014 check the target ts/permalink.";case"channel_not_found":return"Error: channel not found \u2014 check the target.";default:return t}}async function go(e,t,n){if(!t.startsWith("D"))return null;try{let o=await mo(e,t,n);if(!o)return null;return await Ru(e,o,Zn,n)}catch{return null}}function ye(e,t,n,o,s=new Date){for(let i of n)console.log(i);let r=yi(s,o);if(r)console.log(r);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function $t(e){let t=Vt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let o=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,n),ts:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,n),ts:Fi(o)}}}return{ref:e}}function wn(e,t=!0){let n=Vt(e);if(n){if(!t)return{ref:n.channel};let s=n.threadTs??n.ts;return s?{ref:n.channel,threadTs:s}:{ref:n.channel}}let o=e.indexOf(":");if(o>0){let s=e.slice(o+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,o),threadTs:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,o),threadTs:Fi(s)}}return{ref:e}}async function _t(e,t,n,o){let s=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=I(await Qn(e,t,o)),c=I(i.channel);if(c.is_im===!0){let a=typeof c.user==="string"?c.user:"";s=a?`@${await Te(e,a,o)}`:t}else s=typeof c.name==="string"?`#${c.name}`:t}catch{s=t}return s===t?t:`${s} (${t})`}async function rt(e,t){try{return await zn(e,t)}catch{return null}}function pt(e,t){let n;return async()=>{if(n===void 0)n=await rt(e,t);return n}}function en(e){if(!Vr())return{record:()=>{}};let t=jl();return{metadata:Wl(e,t),record:(n)=>{Jl({...n,kind:e,attribution:t})}}}function gg(e){let t=q(e.text.split(`
322
+ `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,o=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${Di(e.sent_at/1000)} ${e.kind.padEnd(4)} ${q(e.target??e.channel)} ${n}
323
323
  ${t}
324
- ${q(o)}`}function Zu(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let o=q(e.user||e.userId||"?"),s=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${q(e.team)}`:"";return`@${o}${s}${r}${n}`}function Se(e,t={}){return` ${"From:".padEnd(t.pad??6)}${Zu(e,t.asBot)}`}async function gi(e,t,n=60,o){let s=typeof t.user==="string"?await Ae(e,t.user,o):typeof t.username==="string"?t.username:"?",r=(typeof t.text==="string"?t.text:"").split(`
325
- `)[0]??"",i=r.length>n?`${r.slice(0,n)}\u2026`:r,c=typeof t.ts==="string"?t.ts:"";return`${c?mi(c).slice(0,16).replace("T"," "):""} @${s}${i?`: ${i}`:""}`}async function Vh(e,t,n,o){let s=n.find((r)=>String(r.ts)===t)??n[0];if(!s)return t;return gi(e,s,40,o)}function Pu(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Zh(e,t){let n=Pu(e),o=Pu(t);if(!n||!o)return 0;if(n===o)return 1;let s=(l)=>{let u=new Map;for(let d=0;d<l.length-1;d++){let f=l.slice(d,d+2);u.set(f,(u.get(f)??0)+1)}return u},r=s(n),i=s(o);if(r.size===0||i.size===0)return 0;let c=0;for(let[l,u]of r){let d=i.get(l);if(d)c+=Math.min(u,d)}let a=Ru(r)+Ru(i);return a===0?0:2*c/a}function Ru(e){let t=0;for(let n of e.values())t+=n;return t}async function Nu(e,t,n,o){let s=wt();if(!s)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
326
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(o)return{botToken:s};let{ref:r}=_t(e);if(!r.startsWith("@"))return{botToken:s};try{let i=await ut(t,r,n);return{botToken:s,channelId:await lt(s,i)}}catch(i){console.error(`Error: could not resolve ${q(r)} to the bot's DM.
324
+ ${q(o)}`}function md(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let o=q(e.user||e.userId||"?"),s=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${q(e.team)}`:"";return`@${o}${s}${r}${n}`}function we(e,t={}){return` ${"From:".padEnd(t.pad??6)}${md(e,t.asBot)}`}async function Ei(e,t,n=60,o){let s=typeof t.user==="string"?await Te(e,t.user,o):typeof t.username==="string"?t.username:"?",r=(typeof t.text==="string"?t.text:"").split(`
325
+ `)[0]??"",i=r.length>n?`${r.slice(0,n)}\u2026`:r,c=typeof t.ts==="string"?t.ts:"";return`${c?Si(c).slice(0,16).replace("T"," "):""} @${s}${i?`: ${i}`:""}`}async function mg(e,t,n,o){let s=n.find((r)=>String(r.ts)===t)??n[0];if(!s)return t;return Ei(e,s,40,o)}function Vu(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Dg(e,t){let n=Vu(e),o=Vu(t);if(!n||!o)return 0;if(n===o)return 1;let s=(l)=>{let u=new Map;for(let d=0;d<l.length-1;d++){let f=l.slice(d,d+2);u.set(f,(u.get(f)??0)+1)}return u},r=s(n),i=s(o);if(r.size===0||i.size===0)return 0;let c=0;for(let[l,u]of r){let d=i.get(l);if(d)c+=Math.min(u,d)}let a=Zu(r)+Zu(i);return a===0?0:2*c/a}function Zu(e){let t=0;for(let n of e.values())t+=n;return t}async function Qu(e,t,n,o){let s=ct();if(!s)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
326
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(o)return{botToken:s};let{ref:r}=$t(e);if(!r.startsWith("@"))return{botToken:s};try{let i=await ft(t,r,n);return{botToken:s,channelId:await dt(s,i)}}catch(i){console.error(`Error: could not resolve ${q(r)} to the bot's DM.
327
327
  ${i instanceof Error?i.message:String(i)}
328
- `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function Qh(e,t){let n=dt(e,t.cookie),{ref:o,ts:s}=_t(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await pe(e,o,t.cookie);let i=await ze(e,r,s,1,t.cookie),a=Y(i.messages).map(O).find((D)=>String(D.ts)===s);if(!a)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof a.text==="string"?a.text:"",u=t.mentionCookie??t.cookie,d=t.mentions?await bu(t.mentionToken??e,t.newText,r,u?{cookie:u}:{}):t.newText;yt(d,t.allowUrlAdjacent);let f=await n(),h=xe(l,d,f?.userId??"");if(t.code!==h)Fe(t.code,h,["--- Editing as -------------------------------",Se(f,{asBot:t.asBot}),"--- Original message -------------------------",...l.split(`
328
+ `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function yg(e,t){let n=pt(e,t.cookie),{ref:o,ts:s}=$t(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await he(e,o,t.cookie);let i=await ze(e,r,s,1,t.cookie),a=Y(i.messages).map(I).find((D)=>String(D.ts)===s);if(!a)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof a.text==="string"?a.text:"",u=t.mentionCookie??t.cookie,d=t.mentions?await vu(t.mentionToken??e,t.newText,r,u?{cookie:u}:{}):t.newText;bt(d,t.allowUrlAdjacent);let f=await n(),h=De(l,d,f?.userId??"");if(t.code!==h)ye(t.code,h,["--- Editing as -------------------------------",we(f,{asBot:t.asBot}),"--- Original message -------------------------",...l.split(`
329
329
  `).map((D)=>` ${D}`),"--- Replacing with ---------------------------",...d.split(`
330
- `).map((D)=>` ${D}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m=Qt("edit"),p=await Xt(e,r,s,d,t.cookie,void 0,m.metadata);console.log(`\u2713 Edited (ts: ${p})`),m.record({team:f?.team,channel:r,target:t.target,ts:s,text:d,asBot:t.asBot})}async function eg(e,t){let n=dt(e,t.cookie),{ref:o,ts:s}=_t(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await pe(e,o,t.cookie);let i=await ze(e,r,s,1,t.cookie),a=Y(i.messages).map(O).find((f)=>String(f.ts)===s);if(!a)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof a.text==="string"?a.text:"",u=await n(),d=xe(r,s,l,u?.userId??"");if(t.code!==d){let f=await St(e,r,o,t.cookie);Fe(t.code,d,["--- Deleting message -------------------------",Se(u,{asBot:t.asBot}),` \u2192 ${f} at ${mi(s)}`,...l.split(`
331
- `).map((h)=>` ${h}`),"---------------------------------------------"])}await Jl(e,r,s,t.cookie),console.log(`\u2713 Deleted (ts: ${s})`)}function Ft(e){return`'${e.replace(/'/g,"'\\''")}'`}async function wi(e,t,n){let o=no(t);if(o)return{...o,ref:o.channel};let{ref:s,ts:r}=_t(t);if(!r)console.error(`Error: ${q(t)} is a channel, not a board \u2014 pass the board's permalink, `+`#chan:ts, or the id \`new\` printed (C\u2026:ts). Boards in a channel: slack pinlog ls ${Ft(t)}`),process.exit(2);return{channel:await pe(e,s,n),ts:r,ref:s}}async function tg(e,t,n,o){let s=O(await ze(e,t,n,1,o)),r=Y(s.messages).map(O).find((i)=>String(i.ts)===n);if(!r)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return r}function so(e,t){if(t!==void 0)try{return Hu(t==="-"?0:t,"utf8").replace(/\n+$/,"")}catch(n){console.error(`Error: cannot read --file ${t}: ${n instanceof Error?n.message:String(n)}`),process.exit(2)}return e===void 0?void 0:qe(e)}var Bu=40000;function co(e,t){if(t.length>Bu)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${Bu}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function lo(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof ct)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function Qu(e,t){let n=li(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function ng(e,t){let{ref:n,ts:o}=_t(t.target);if(o||no(t.target))console.error("Error: `pinlog new` posts a NEW board \u2014 pass a channel (#chan or C\u2026), not a message.\n"+` To change an existing board: slack pinlog set ${Ft(t.target)} '<new state>' '<reason>'`),process.exit(2);if(!t.state.trim())console.error("Error: the initial state is empty \u2014 a board has to say something."),process.exit(2);if(yt(t.state,t.allowUrlAdjacent),t.log!==void 0)yt(t.log,t.allowUrlAdjacent),co("reason",t.log);let s=`${t.workspace?` -w ${Ft(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=dt(e,t.cookie),i=await pe(e,n,t.cookie),c=await r(),a=xe("pinlog-create",i,t.state,t.log??"",c?.userId??""),l=new Date,u=fi(t.state,l);if(co("HEAD (state + footer)",u),t.code!==a){let p=await St(e,i,n,t.cookie),D=(await ed(e,i,200,t.cookie)).found;Fe(t.code,a,["--- New pinlog -------------------------------",Se(c,{asBot:t.asBot}),` \u2192 ${p} \u2014 NEW top-level message, then pinned`,...D.length?[`\u26A0 ${D.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...D.slice(0,5).map((C)=>` ${Ge(i,String(C.ts))} ${td(String(C.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
332
- `).map((C)=>` ${q(C)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
333
- `).map((C)=>` ${q(C)}`)]:[],"---------------------------------------------"])}let d=Qt("send"),f;try{f=await Gt(e,i,u,void 0,!1,t.cookie,!0,d.metadata)}catch(p){if(lo(p))console.error(`\u2717 HEAD was NOT posted: ${me(p)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${me(p)}
334
- Check before retrying, or you will have two boards: slack pinlog ls ${Ft(t.target)}${s}`);process.exit(1)}if(!f)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);d.record({team:c?.team,channel:i,target:t.target,ts:f,text:u,asBot:t.asBot});let h=Ge(i,f);console.log(`\u2713 Posted HEAD: ${h}`);let m=Qu(l,"this new top-level post notified everyone who follows the channel");if(m)console.error(m);try{await Yr(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(p){let D=p instanceof Error?p.message:String(p),C=/missing_scope/.test(D)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:me(p);console.error(`\u26A0 NOT pinned: ${C}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${h}${s}`)}if(t.log)try{let p=await Gt(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${p})`)}catch(p){let D=xe("pinlog-log",i,f,t.log,c?.userId??"");console.error(`${lo(p)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${me(p)}
330
+ `).map((D)=>` ${D}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m=en("edit"),p=await Yt(e,r,s,d,t.cookie,void 0,m.metadata);console.log(`\u2713 Edited (ts: ${p})`),m.record({team:f?.team,channel:r,target:t.target,ts:s,text:d,asBot:t.asBot})}async function wg(e,t){let n=pt(e,t.cookie),{ref:o,ts:s}=$t(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await he(e,o,t.cookie);let i=await ze(e,r,s,1,t.cookie),a=Y(i.messages).map(I).find((f)=>String(f.ts)===s);if(!a)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof a.text==="string"?a.text:"",u=await n(),d=De(r,s,l,u?.userId??"");if(t.code!==d){let f=await _t(e,r,o,t.cookie);ye(t.code,d,["--- Deleting message -------------------------",we(u,{asBot:t.asBot}),` \u2192 ${f} at ${Si(s)}`,...l.split(`
331
+ `).map((h)=>` ${h}`),"---------------------------------------------"])}await cu(e,r,s,t.cookie),console.log(`\u2713 Deleted (ts: ${s})`)}function Ft(e){return`'${e.replace(/'/g,"'\\''")}'`}async function $i(e,t,n){let o=so(t);if(o)return{...o,ref:o.channel};let{ref:s,ts:r}=$t(t);if(!r)console.error(`Error: ${q(t)} is a channel, not a board \u2014 pass the board's permalink, `+`#chan:ts, or the id \`new\` printed (C\u2026:ts). Boards in a channel: slack pinlog ls ${Ft(t)}`),process.exit(2);return{channel:await he(e,s,n),ts:r,ref:s}}async function bg(e,t,n,o){let s=I(await ze(e,t,n,1,o)),r=Y(s.messages).map(I).find((i)=>String(i.ts)===n);if(!r)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return r}function oo(e,t){if(t!==void 0)try{return ld(t==="-"?0:t,"utf8").replace(/\n+$/,"")}catch(n){console.error(`Error: cannot read --file ${t}: ${n instanceof Error?n.message:String(n)}`),process.exit(2)}return e===void 0?void 0:qe(e)}var ed=40000;function lo(e,t){if(t.length>ed)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${ed}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function uo(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof ut)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function Dd(e,t){let n=yi(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function kg(e,t){let{ref:n,ts:o}=$t(t.target);if(o||so(t.target))console.error("Error: `pinlog new` posts a NEW board \u2014 pass a channel (#chan or C\u2026), not a message.\n"+` To change an existing board: slack pinlog set ${Ft(t.target)} '<new state>' '<reason>'`),process.exit(2);if(!t.state.trim())console.error("Error: the initial state is empty \u2014 a board has to say something."),process.exit(2);if(bt(t.state,t.allowUrlAdjacent),t.log!==void 0)bt(t.log,t.allowUrlAdjacent),lo("reason",t.log);let s=`${t.workspace?` -w ${Ft(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=pt(e,t.cookie),i=await he(e,n,t.cookie),c=await r(),a=De("pinlog-create",i,t.state,t.log??"",c?.userId??""),l=new Date,u=ki(t.state,l);if(lo("HEAD (state + footer)",u),t.code!==a){let p=await _t(e,i,n,t.cookie),D=(await yd(e,i,200,t.cookie)).found;ye(t.code,a,["--- New pinlog -------------------------------",we(c,{asBot:t.asBot}),` \u2192 ${p} \u2014 NEW top-level message, then pinned`,...D.length?[`\u26A0 ${D.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...D.slice(0,5).map((x)=>` ${Ge(i,String(x.ts))} ${wd(String(x.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
332
+ `).map((x)=>` ${q(x)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
333
+ `).map((x)=>` ${q(x)}`)]:[],"---------------------------------------------"])}let d=en("send"),f;try{f=await Xt(e,i,u,void 0,!1,t.cookie,!0,d.metadata)}catch(p){if(uo(p))console.error(`\u2717 HEAD was NOT posted: ${ce(p)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ce(p)}
334
+ Check before retrying, or you will have two boards: slack pinlog ls ${Ft(t.target)}${s}`);process.exit(1)}if(!f)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);d.record({team:c?.team,channel:i,target:t.target,ts:f,text:u,asBot:t.asBot});let h=Ge(i,f);console.log(`\u2713 Posted HEAD: ${h}`);let m=Dd(l,"this new top-level post notified everyone who follows the channel");if(m)console.error(m);try{await ri(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(p){let D=p instanceof Error?p.message:String(p),x=/missing_scope/.test(D)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:ce(p);console.error(`\u26A0 NOT pinned: ${x}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${h}${s}`)}if(t.log)try{let p=await Xt(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${p})`)}catch(p){let D=De("pinlog-log",i,f,t.log,c?.userId??"");console.error(`${uo(p)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ce(p)}
335
335
  The board IS posted. Retry just the reason (check the thread first):
336
- slack pinlog note ${h} ${Ft(oi(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${s} --code=${D}`),process.exit(1)}}async function Mu(e,t){if(!t.log.trim())console.error("Error: the reason is required \u2014 one short line saying what changed. The thread log is the point of a pinlog."),process.exit(2);if(!t.logOnly&&(t.state===void 0||!t.state.trim()))console.error("Error: the new state is required (positional or --file). To post only a reason: slack pinlog note <board> <reason>"),process.exit(2);if(yt(t.log,t.allowUrlAdjacent),t.state!==void 0)yt(t.state,t.allowUrlAdjacent);co("log line",t.log);let n=dt(e,t.cookie),{channel:o,ts:s,ref:r}=await wi(e,t.target,t.cookie);try{Ou(`pinlog-${o}-${s}`)}catch(C){if(!(C instanceof ns))throw C;console.error(`Error: another update of ${Ge(o,s)} is running (${C.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await tg(e,o,s,t.cookie),c=typeof i.text==="string"?i.text:"";if(t.adopt&&t.logOnly)console.error("Error: --adopt rewrites the state with a footer \u2014 it does not apply to note."),process.exit(2);if(!Dn(c)&&!t.adopt)console.error(`Error: the message at ${Ge(o,s)} is not a pinlog HEAD (no "${ss}" footer).
337
- `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let a=await n(),l=Ge(o,s),u=new Date,d=`${t.workspace?` -w ${Ft(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=xe("pinlog-log",o,s,t.log,a?.userId??""),h=`slack pinlog note ${l} ${Ft(oi(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,m=Qu(u,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==f){let C=await St(e,o,r,t.cookie);Fe(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",Se(a,{asBot:t.asBot}),` \u2192 ${C}, thread of ${l}`,...t.log.split(`
338
- `).map((b)=>` ${q(b)}`),"---------------------------------------------"])}}else{let C=fi(t.state,u);co("new HEAD (state + footer)",C);let b=!Dn(c),_=xe("pinlog-update",o,s,c,t.state,t.log,a?.userId??"");if(t.code!==_){let N=await St(e,o,r,t.cookie),j=os(c).trim()===os(t.state).trim();Fe(t.code,_,["--- Updating pinlog --------------------------",Se(a,{asBot:t.asBot}),` \u2192 ${N}, ${l}`,"--- Current HEAD -----------------------------",...c.split(`
339
- `).map((I)=>` ${q(I)}`),"--- New HEAD (edited in place \u2014 silent) ------",...C.split(`
340
- `).map((I)=>` ${q(I)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
341
- `).map((I)=>` ${q(I)}`),"---------------------------------------------",...j?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...b?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let A=Qt("edit");try{await Xt(e,o,s,C,t.cookie,!0,A.metadata)}catch(N){let j=N instanceof Error?N.message:String(N),I=/cant_update_message/.test(j)?`
342
- Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",J=lo(N)?`\u2717 HEAD was NOT updated: ${me(N)}${I}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${me(N)}
343
- Check it first: slack pinlog get ${l}${d}`;console.error(`${J}
344
- The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}A.record({team:a?.team,channel:o,target:t.target,ts:s,text:C,asBot:t.asBot}),console.log(`\u2713 HEAD updated: ${l}`)}let p=Qt("send"),D;try{D=await Gt(e,o,t.log,s,!1,t.cookie,!0,p.metadata)}catch(C){let b=lo(C);console.error((b?`\u2717 Log reply was NOT posted: ${me(C)}
345
- `:`\u26A0 UNKNOWN whether the log reply was posted: ${me(C)}
336
+ slack pinlog note ${h} ${Ft(pi(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${s} --code=${D}`),process.exit(1)}}async function td(e,t){if(!t.log.trim())console.error("Error: the reason is required \u2014 one short line saying what changed. The thread log is the point of a pinlog."),process.exit(2);if(!t.logOnly&&(t.state===void 0||!t.state.trim()))console.error("Error: the new state is required (positional or --file). To post only a reason: slack pinlog note <board> <reason>"),process.exit(2);if(bt(t.log,t.allowUrlAdjacent),t.state!==void 0)bt(t.state,t.allowUrlAdjacent);lo("log line",t.log);let n=pt(e,t.cookie),{channel:o,ts:s,ref:r}=await $i(e,t.target,t.cookie);try{Xu(`pinlog-${o}-${s}`)}catch(x){if(!(x instanceof ss))throw x;console.error(`Error: another update of ${Ge(o,s)} is running (${x.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await bg(e,o,s,t.cookie),c=typeof i.text==="string"?i.text:"";if(t.adopt&&t.logOnly)console.error("Error: --adopt rewrites the state with a footer \u2014 it does not apply to note."),process.exit(2);if(!yn(c)&&!t.adopt)console.error(`Error: the message at ${Ge(o,s)} is not a pinlog HEAD (no "${os}" footer).
337
+ `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let a=await n(),l=Ge(o,s),u=new Date,d=`${t.workspace?` -w ${Ft(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=De("pinlog-log",o,s,t.log,a?.userId??""),h=`slack pinlog note ${l} ${Ft(pi(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,m=Dd(u,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==f){let x=await _t(e,o,r,t.cookie);ye(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",we(a,{asBot:t.asBot}),` \u2192 ${x}, thread of ${l}`,...t.log.split(`
338
+ `).map((b)=>` ${q(b)}`),"---------------------------------------------"])}}else{let x=ki(t.state,u);lo("new HEAD (state + footer)",x);let b=!yn(c),_=De("pinlog-update",o,s,c,t.state,t.log,a?.userId??"");if(t.code!==_){let N=await _t(e,o,r,t.cookie),j=rs(c).trim()===rs(t.state).trim();ye(t.code,_,["--- Updating pinlog --------------------------",we(a,{asBot:t.asBot}),` \u2192 ${N}, ${l}`,"--- Current HEAD -----------------------------",...c.split(`
339
+ `).map((O)=>` ${q(O)}`),"--- New HEAD (edited in place \u2014 silent) ------",...x.split(`
340
+ `).map((O)=>` ${q(O)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
341
+ `).map((O)=>` ${q(O)}`),"---------------------------------------------",...j?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...b?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let A=en("edit");try{await Yt(e,o,s,x,t.cookie,!0,A.metadata)}catch(N){let j=N instanceof Error?N.message:String(N),O=/cant_update_message/.test(j)?`
342
+ Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",K=uo(N)?`\u2717 HEAD was NOT updated: ${ce(N)}${O}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ce(N)}
343
+ Check it first: slack pinlog get ${l}${d}`;console.error(`${K}
344
+ The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}A.record({team:a?.team,channel:o,target:t.target,ts:s,text:x,asBot:t.asBot}),console.log(`\u2713 HEAD updated: ${l}`)}let p=en("send"),D;try{D=await Xt(e,o,t.log,s,!1,t.cookie,!0,p.metadata)}catch(x){let b=uo(x);console.error((b?`\u2717 Log reply was NOT posted: ${ce(x)}
345
+ `:`\u26A0 UNKNOWN whether the log reply was posted: ${ce(x)}
346
346
  `)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${b?"is":"may be"} missing.
347
347
  `)+(b?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${l}${d}
348
348
  `)+` Retry just the log line${b?"":" (only if it is not there)"}:
349
- ${h}`),process.exit(1)}if(p.record({team:a?.team,channel:o,target:t.target,ts:D,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${D})`),m)console.error(m)}function vu(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function sg(e){return ui(new Date(Number(e.split(".")[0])*1000))}async function og(e,t,n,o){if(typeof t.user==="string"){let r=n.get(t.user);if(r!==void 0)return r;let i;try{i=await Ae(e,t.user,o)}catch{i=t.user}return n.set(t.user,i),i}let s=O(t.bot_profile);if(typeof s.name==="string")return s.name;return typeof t.username==="string"?t.username:"bot"}async function rg(e,t,n,o){let{channel:s,ts:r}=await wi(e,t,n),i=[],c,a=0;do{let p=O(await Hl(e,s,r,c,200,n));for(let C of Y(p.messages).map(O)){if(String(C.ts)===r&&i.some((b)=>String(b.ts)===r))continue;i.push(C)}let D=O(p.response_metadata).next_cursor;c=typeof D==="string"&&D?D:void 0,a++}while(c&&a<50);let l=c===void 0,u=i.find((p)=>String(p.ts)===r);if(!u)console.error(`Error: no message at ts=${r} in ${s}.`),process.exit(1);let d=typeof u.text==="string"?u.text:"",f=i.filter((p)=>String(p.ts)!==r);if(o){console.log(JSON.stringify({id:Ge(s,r),isPinlog:Dn(d),updated:pi(d),complete:l,head:d,log:f.map((p)=>({ts:String(p.ts),user:p.user??null,text:typeof p.text==="string"?p.text:""}))}));return}if(!Dn(d))console.error(`\u26A0 ${Ge(s,r)} has no "${ss}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${Ge(s,r)} ===`);for(let p of vu(d).split(`
350
- `))console.log(q(p));let h=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${h}) ===`);let m=new Map;for(let p of f){let D=typeof p.text==="string"?p.text:"",C=q(await og(e,p,m,n)),b=vu(D).split(`
351
- `).map((_)=>q(_));console.log(`${sg(String(p.ts))} @${C}: ${b[0]??""}`);for(let _ of b.slice(1))console.log(` ${_}`)}}async function ed(e,t,n,o){let s=0,r,i=[];do{let c=O(await nt(e,t,Math.min(200,n-s),void 0,r,o)),a=Y(c.messages).map(O);s+=a.length;for(let u of a)if(typeof u.text==="string"&&Dn(u.text))i.push(u);let l=O(c.response_metadata).next_cursor;r=typeof l==="string"&&l?l:void 0}while(r&&s<n);return{found:i,scanned:s}}function td(e){return q(os(e).split(`
352
- `).find((t)=>t.trim())??"").slice(0,80)}async function ig(e,t,n,o){let{ref:s,ts:r}=_t(t);if(r||no(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${Ft(t)}`),process.exit(2);let i=await pe(e,s,o),{found:c,scanned:a}=await ed(e,i,n,o),l=await St(e,i,s,o);if(c.length===0){console.log(`No pinlogs in the last ${a} messages of ${l}.${a>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of c){let d=String(u.ts),f=Ge(i,d),h=String(u.text),m=Y(u.pinned_to).some((C)=>C===i)?"\uD83D\uDCCC":" ",p=td(h),D=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${m} ${f} updated ${pi(h)??"?"} log ${D}`),console.log(` ${p}`)}}async function ag(e,t,n){let{channel:o,ts:s}=await wi(e,t,n);try{await Yr(e,o,s,n),console.log(`\u2713 Pinned ${Ge(o,s)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${Ge(o,s)}`);return}console.error(`\u2717 NOT pinned: ${me(r)}`),process.exit(1)}}async function cg(e,t){let{ref:n,ts:o}=_t(t.target);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let s=t.emoji.replace(/^:|:$/g,""),r;if(t.channelId)r=t.channelId;else r=await pe(e,n,t.cookie);if(t.remove)await qn(e,r,o,s,t.cookie),console.log(`\u2713 Removed :${s}: (ts: ${o})`);else await pn(e,r,o,s,t.cookie),console.log(`\u2713 Reacted :${s}: (ts: ${o})`)}async function bi(e,t,n,o){if(!n||!t.startsWith("D"))return!1;try{let s=O(await Zn(e,t,o)),r=O(s.channel);return r.is_im===!0&&r.user===n}catch{return!1}}async function lg(e,t){let{ref:n,threadTs:o}=wn(t.target),s=t.cookie,r=dt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await lt(e,t.userId,s);else i=await pe(e,n,s);if(!t.asBot&&await bi(e,i,(await r())?.userId,s))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
353
- `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let c=qe(t.message);yt(c,t.allowUrlAdjacent);let a=c,l=null;if(t.mentions){l=await Zt(t.mentionToken??e,c,i,t.mentionCookie),a=l.text;for(let I of es(l.unresolved))console.error(`\u26A0 ${q(I)}`)}try{for(let I of await Eu(t.mentionToken??e,a,t.mentionCookie))console.error(`\u26A0 possible untagged mention: ${q(I.surface)} \u2014 @${q(I.display)} won't be notified (did you mean <@${I.userId}>?)`)}catch{}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let I of l.resolved)u.push(` \u2713 ${q(I.surface)} \u2192 @${q(I.display)} (${I.userId}) \u2014 will notify`);for(let I of l.unresolved){let J=I.reason==="ambiguous"?"ambiguous":I.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${q(I.surface)} \u2014 plain text, NOT notified (${J})`)}}let d="",f="?",h=[],m,p,D;if(o)try{let I=await ze(e,i,o,100,s);h=Y(I.messages).map(O);let J=h[h.length-1];d=typeof J?.text==="string"?J.text:"",m=typeof J?.user==="string"?J.user:void 0,p=typeof J?.bot_id==="string"?J.bot_id:void 0,D=typeof J?.ts==="string"?J.ts:void 0}catch{}else try{let I=await nt(e,i,1,void 0,void 0,s),J=Y(I.messages).map(O),U=J.filter((F)=>F.subtype===void 0||F.subtype===null)[0];d=typeof U?.text==="string"?U.text:"",f=typeof U?.user==="string"?await Ae(e,U.user,s):typeof U?.username==="string"?U.username:"?";let Q=J[0];m=typeof Q?.user==="string"?Q.user:void 0,p=typeof Q?.bot_id==="string"?Q.bot_id:void 0,D=typeof Q?.ts==="string"?Q.ts:void 0}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&D&&(m||p))try{let I=await r();if(!!I&&(!!m&&!!I.userId&&I.userId===m||!!p&&!!I.botId&&I.botId===p)){let U=`slack edit "#${i}:${D}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${i}`;try{let Q=await zn(e,i,D,s);if(Q)U=`slack edit "${Q}" "<\u65B0\u3057\u3044\u672C\u6587>"`}catch{}console.error("\u26A0 \u76F8\u624B\u306F\u307E\u3060\u8FD4\u4FE1\u3057\u3066\u3044\u307E\u305B\u3093(\u6700\u5F8C\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u3042\u306A\u305F\u306E\u3082\u306E\u3067\u3059)\u3002"),console.error(" \u9023\u6295\u3092\u907F\u3051\u308B\u305F\u3081\u3001\u65B0\u898F\u9001\u4FE1\u3067\u306A\u304F\u76F4\u524D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306E edit \u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044:"),console.error(` ${U}`),console.error(" \u3053\u306E\u307E\u307E\u9001\u4FE1\u3059\u308B\u5834\u5408\u306F --code=XXXX \u3067\u78BA\u5B9A\u3002")}}catch{}if(o&&h.length){let I={sim:0,msg:null};for(let J of h){let U=typeof J.text==="string"?J.text:"";if(!U)continue;let Q=Zh(a,U);if(Q>I.sim)I={sim:Q,msg:J}}if(I.msg&&I.sim>=0.82){let J=Math.round(I.sim*100);console.error(`\u26A0 possible duplicate: ${J}% similar to an existing thread message \u2014 ${await gi(e,I.msg,60,s)}`)}}let C=await r(),b=await ho(e,i,s),_=xe(i,o??"",d,a,C?.userId??"");if(t.code!==_){let I=await St(e,i,n,s),J=Se(C,{asBot:t.asBot});if(o){let U=await Vh(e,o,h,s),Q=h.slice(-3),F=Q.length?await Promise.all(Q.map(async(E)=>` ${await gi(e,E,60,s)}`)):[" (thread context unavailable)"];Fe(t.code,_,["--- Recent messages in thread ----------------",...F,...u,"--- Sending ----------------------------------",J,` \u2192 ${I} thread of ${U} \u2014 THREAD REPLY`,` Message: ${a}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],b)}else Fe(t.code,_,["--- Last message in channel ------------------",` ${f}: ${d.split(`
354
- `)[0]?.slice(0,100)??"(empty)"}`,...u,"--- Sending ----------------------------------",J,` \u2192 ${I} \u2014 NEW top-level message`,` Message: ${a}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],b)}let A=Qt("send"),N=await Gt(e,i,a,o,t.broadcast,s,void 0,A.metadata),j="";try{j=await zn(e,i,N,s)}catch{}if(A.record({team:(await r())?.team,channel:i,target:t.target,ts:N,threadTs:o,permalink:j,text:a,asBot:t.asBot}),j)console.log(`\u2713 Sent: ${j}`);else console.log(`\u2713 Sent (ts: ${N})`);if(t.asBot&&i.startsWith("D"))try{let I=await Rs(e);if(!I.ok)for(let J of Ns(I,!0))console.error(J);else{let J=I.appId?`https://api.slack.com/apps/${I.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${J} \u2192 App Home.`)}}catch{}}var ug=2,ke=3,dg=4,fg=5,pg=1.618033988749895,hg=1000,gg=5000,Lu=8,mg=(e)=>new Promise((t)=>setTimeout(t,e)),Dg=new Set(["thread_broadcast"]),yg=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function uo(e){let t=new Set;return{text:e.replace(yg,(o,s)=>{let r=s.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function go(e,t,n){if(!t.startsWith("D"))return;try{let o=O(await Zn(e,t,n)),s=O(o.channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function nd(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,audience:c,broadcast:a,cookie:l,timeout:u,shown:d}=t,{askerUserId:f,askerBotId:h}=t,m=(F)=>typeof F==="string"&&!!F&&F!==f&&(a||c.has(F)),p,D="";function C(F){let E=Y(F.reactions).map(O),T=[];for(let S=0;S<r.length;S++){let B=E.find((X)=>X.name===He[S].name),Z=B?Y(B.users).filter(m):[];if(Z.length)T.push({index:S,users:Z})}return T}async function b(F,E){let T=typeof F.text==="string"?F.text:"";if(!T)return;let S=Nr(T,E);if(S===T)return;try{await Xt(e,n,o,S,l,!0)}catch(B){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B instanceof Error?B.message:String(B)})`)}}async function _(F){let E=C(F);if(E.length<=1&&Rr(typeof F.text==="string"?F.text:"").length)await b(F,[]);if(!E.length)return null;if(E.length===1){let{index:B,users:Z}=E[0];return{answer:r[B],how:`\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${He[B].glyph}`,who:Z[0]}}let T=E.map((B)=>He[B.index].glyph).join(" / ");console.error(` (${T} \u304C\u540C\u6642\u306B\u9078\u3070\u308C\u3066\u3044\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let S=[...new Set(E.flatMap((B)=>B.users))].sort();return await b(F,S),null}let A=[...r,...t.overflow];function N(F,E=1/0){let T=[...F].sort((S,B)=>Number(S.ts)-Number(B.ts));for(let S of T){if(!(Number(S.ts)>Number(o)))continue;if(t.after&&!(Number(S.ts)>Number(t.after)))continue;if(!m(S.user))continue;if(typeof S.subtype==="string"&&!Dg.has(S.subtype))continue;if(Number(S.ts)>=E)break;let B=typeof S.text==="string"?S.text.trim():"";if(!B)continue;if(!A.length)return{answer:B,how:"\u8FD4\u4FE1",who:S.user};let Z=dl(B,A);if(Z.kind==="chosen")return{answer:A[Z.index-1],how:`\u8FD4\u4FE1 (${Z.index})`,who:S.user};let X=Z.kind==="ambiguous";if(!p||p.ambiguous&&!X||p.ambiguous===X&&Number(S.ts)<Number(p.ts))p={text:B,who:typeof S.user==="string"?S.user:"",ts:String(S.ts),ambiguous:X}}return null}async function j(){if(p=void 0,t.threadParentTs){let S=O(await ze(e,n,t.threadParentTs,100,l)),B=Y(S.messages).map(O),Z=B.find((X)=>X.ts===o);if(Z){let X=await _(Z);if(X)return X}return N(B)}let F=O(await nt(e,n,30,o,void 0,l,!0)),E=Y(F.messages).map(O),T=E.find((S)=>S.ts===o);if(T){let S=await _(T);if(S)return S}if(!i){let S=E.filter((Z)=>Number(Z.ts)>Number(o)&&(h&&Z.bot_id===h||f&&Z.user===f)).reduce((Z,X)=>Math.min(Z,Number(X.ts)),1/0),B=N(E,S);if(B)return B}if(T&&Number(T.reply_count)>0){let S=O(await ze(e,n,o,30,l)),B=N(Y(S.messages).map(O));if(B)return B}return null}async function I(F){for(let T=0;T<r.length;T++)try{await qn(e,n,o,He[T].name,l)}catch{}let E="";if(F.who)try{E=await Ae(e,F.who,l)}catch{E=F.who}if(E)console.error(` \u56DE\u7B54\u8005: ${q(E)}`);try{await Xt(e,n,o,cl(s,F,E),l,!0);try{await pn(e,n,o,Br,l),await qn(e,n,o,Hs,l)}catch{}}catch(T){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${T instanceof Error?T.message:String(T)})`)}}let J=Date.now()+u*1000,U=0,Q=hg;for(;;){let F=null;try{F=await j(),U=0}catch(E){if(U++,U>=Lu)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${U} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${E instanceof Error?E.message:String(E)}`),process.exit(ke);console.error(` (Slack \u30A8\u30E9\u30FC ${U}/${Lu}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${E instanceof Error?E.message:String(E)})`)}if(F)await I(F),console.log(F.answer),process.exit(0);if(p&&!p.ambiguous){let E=p.who;try{if(E)E=await Ae(e,E,l)}catch{}console.error(` (${q(E)} \u304C\u9078\u629E\u80A2\u5916\u306E\u8FD4\u4FE1\u3092\u3057\u307E\u3057\u305F \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u672C\u6587\u3092 stdout \u306B\u51FA\u3057\u307E\u3059)`),console.error(` \u9078\u629E\u80A2: ${A.map((T,S)=>`${S+1}. ${q(Ht(T))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${ro(d,t.asBot,p.ts)}`),console.log(p.text),process.exit(fg)}if(p&&p.ts!==D){D=p.ts;let E=p.who;try{if(E)E=await Ae(e,E,l)}catch{}console.error(` (${q(E)} \u306E\u8FD4\u4FE1\u306F\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3057\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`),console.error(` \u300C${q(p.text)}\u300D`)}if(Date.now()>=J)break;await mg(Math.min(Q,Math.max(0,J-Date.now()))),Q=Math.min(Q*pg,gg)}if(p)console.error("Error: \u8FD4\u4FE1\u306F\u3042\u308A\u307E\u3057\u305F\u304C\u3001\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3059\u308B\u305F\u3081\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093 (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)"),console.error(` \u8FD4\u4FE1: \u300C${q(p.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${A.map((F,E)=>`${E+1}. ${q(Ht(F))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${ro(d,t.asBot,t.after)}`),process.exit(dg);if(u===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${d}`);else console.error(`Error: ${u}s \u4EE5\u5185\u306B\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)`),console.error(` ${d}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${ro(d,t.asBot,t.after)}`);process.exit(ug)}function ro(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function wg(e,t){let{ref:n,threadTs:o}=wn(t.target,!1),s=t.cookie,r=dt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await lt(e,t.userId,s);else i=await pe(e,n,s);let c=(await r())?.userId??"",a=await go(e,i,s);if(!t.asBot&&!!c&&a===c)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
355
- `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=uo(qe(t.question)),u=uo(qe(t.body??"")),d=new Set([...l.kinds,...u.kinds]),f=t.mentionToken??e,h=await Zt(f,l.text,i,t.mentionCookie),m=u.text?await Zt(f,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},p=h.text,D=m.text,C=[...h.resolved,...m.resolved],b=[...h.unresolved,...m.unresolved];for(let R of es(b))console.error(`\u26A0 ${q(R)}`);let _=d.size>0,A=new Set(C.map((R)=>R.userId).filter((R)=>R!==c)),N=new Map(C.map((R)=>[R.userId,R.display])),j;if(_)j=`anyone in ${n} (${[...d].map((R)=>`@${R}`).join(", ")})`;else{if(!A.size&&a&&a!==c)A.add(a),N.set(a,await Ae(e,a,s));if(!A.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+(b.length?` (${b.map((R)=>q(R.surface)).join(", ")} matched no one, so it names nobody.)
349
+ ${h}`),process.exit(1)}if(p.record({team:a?.team,channel:o,target:t.target,ts:D,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${D})`),m)console.error(m)}function nd(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function xg(e){return wi(new Date(Number(e.split(".")[0])*1000))}async function Cg(e,t,n,o){if(typeof t.user==="string"){let r=n.get(t.user);if(r!==void 0)return r;let i;try{i=await Te(e,t.user,o)}catch{i=t.user}return n.set(t.user,i),i}let s=I(t.bot_profile);if(typeof s.name==="string")return s.name;return typeof t.username==="string"?t.username:"bot"}async function Eg(e,t,n,o){let{channel:s,ts:r}=await $i(e,t,n),i=[],c,a=0;do{let p=I(await lu(e,s,r,c,200,n));for(let x of Y(p.messages).map(I)){if(String(x.ts)===r&&i.some((b)=>String(b.ts)===r))continue;i.push(x)}let D=I(p.response_metadata).next_cursor;c=typeof D==="string"&&D?D:void 0,a++}while(c&&a<50);let l=c===void 0,u=i.find((p)=>String(p.ts)===r);if(!u)console.error(`Error: no message at ts=${r} in ${s}.`),process.exit(1);let d=typeof u.text==="string"?u.text:"",f=i.filter((p)=>String(p.ts)!==r);if(o){console.log(JSON.stringify({id:Ge(s,r),isPinlog:yn(d),updated:xi(d),complete:l,head:d,log:f.map((p)=>({ts:String(p.ts),user:p.user??null,text:typeof p.text==="string"?p.text:""}))}));return}if(!yn(d))console.error(`\u26A0 ${Ge(s,r)} has no "${os}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${Ge(s,r)} ===`);for(let p of nd(d).split(`
350
+ `))console.log(q(p));let h=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${h}) ===`);let m=new Map;for(let p of f){let D=typeof p.text==="string"?p.text:"",x=q(await Cg(e,p,m,n)),b=nd(D).split(`
351
+ `).map((_)=>q(_));console.log(`${xg(String(p.ts))} @${x}: ${b[0]??""}`);for(let _ of b.slice(1))console.log(` ${_}`)}}async function yd(e,t,n,o){let s=0,r,i=[];do{let c=I(await nt(e,t,Math.min(200,n-s),void 0,r,o)),a=Y(c.messages).map(I);s+=a.length;for(let u of a)if(typeof u.text==="string"&&yn(u.text))i.push(u);let l=I(c.response_metadata).next_cursor;r=typeof l==="string"&&l?l:void 0}while(r&&s<n);return{found:i,scanned:s}}function wd(e){return q(rs(e).split(`
352
+ `).find((t)=>t.trim())??"").slice(0,80)}async function Sg(e,t,n,o){let{ref:s,ts:r}=$t(t);if(r||so(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${Ft(t)}`),process.exit(2);let i=await he(e,s,o),{found:c,scanned:a}=await yd(e,i,n,o),l=await _t(e,i,s,o);if(c.length===0){console.log(`No pinlogs in the last ${a} messages of ${l}.${a>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of c){let d=String(u.ts),f=Ge(i,d),h=String(u.text),m=Y(u.pinned_to).some((x)=>x===i)?"\uD83D\uDCCC":" ",p=wd(h),D=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${m} ${f} updated ${xi(h)??"?"} log ${D}`),console.log(` ${p}`)}}async function Fg(e,t,n){let{channel:o,ts:s}=await $i(e,t,n);try{await ri(e,o,s,n),console.log(`\u2713 Pinned ${Ge(o,s)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${Ge(o,s)}`);return}console.error(`\u2717 NOT pinned: ${ce(r)}`),process.exit(1)}}async function _g(e,t){let{ref:n,ts:o}=$t(t.target);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let s=t.emoji.replace(/^:|:$/g,""),r;if(t.channelId)r=t.channelId;else r=await he(e,n,t.cookie);if(t.remove)await Gn(e,r,o,s,t.cookie),console.log(`\u2713 Removed :${s}: (ts: ${o})`);else await hn(e,r,o,s,t.cookie),console.log(`\u2713 Reacted :${s}: (ts: ${o})`)}async function Ai(e,t,n,o){if(!n||!t.startsWith("D"))return!1;try{let s=I(await Qn(e,t,o)),r=I(s.channel);return r.is_im===!0&&r.user===n}catch{return!1}}async function $g(e,t){let{ref:n,threadTs:o}=wn(t.target),s=t.cookie,r=pt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await dt(e,t.userId,s);else i=await he(e,n,s);if(!t.asBot&&await Ai(e,i,(await r())?.userId,s))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
353
+ `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let c=qe(t.message);bt(c,t.allowUrlAdjacent);let a=c,l=null;if(t.mentions){l=await Qt(t.mentionToken??e,c,i,t.mentionCookie),a=l.text;for(let O of ts(l.unresolved))console.error(`\u26A0 ${q(O)}`)}try{for(let O of await Wu(t.mentionToken??e,a,t.mentionCookie))console.error(`\u26A0 possible untagged mention: ${q(O.surface)} \u2014 @${q(O.display)} won't be notified (did you mean <@${O.userId}>?)`)}catch{}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let O of l.resolved)u.push(` \u2713 ${q(O.surface)} \u2192 @${q(O.display)} (${O.userId}) \u2014 will notify`);for(let O of l.unresolved){let K=O.reason==="ambiguous"?"ambiguous":O.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${q(O.surface)} \u2014 plain text, NOT notified (${K})`)}}let d="",f="?",h=[],m,p,D;if(o)try{let O=await ze(e,i,o,100,s);h=Y(O.messages).map(I);let K=h[h.length-1];d=typeof K?.text==="string"?K.text:"",m=typeof K?.user==="string"?K.user:void 0,p=typeof K?.bot_id==="string"?K.bot_id:void 0,D=typeof K?.ts==="string"?K.ts:void 0}catch{}else try{let O=await nt(e,i,1,void 0,void 0,s),K=Y(O.messages).map(I),U=K.filter((S)=>S.subtype===void 0||S.subtype===null)[0];d=typeof U?.text==="string"?U.text:"",f=typeof U?.user==="string"?await Te(e,U.user,s):typeof U?.username==="string"?U.username:"?";let Q=K[0];m=typeof Q?.user==="string"?Q.user:void 0,p=typeof Q?.bot_id==="string"?Q.bot_id:void 0,D=typeof Q?.ts==="string"?Q.ts:void 0}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&D&&(m||p))try{let O=await r();if(!!O&&(!!m&&!!O.userId&&O.userId===m||!!p&&!!O.botId&&O.botId===p)){let U=`slack edit "#${i}:${D}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${i}`;try{let Q=await qn(e,i,D,s);if(Q)U=`slack edit "${Q}" "<\u65B0\u3057\u3044\u672C\u6587>"`}catch{}console.error("\u26A0 \u76F8\u624B\u306F\u307E\u3060\u8FD4\u4FE1\u3057\u3066\u3044\u307E\u305B\u3093(\u6700\u5F8C\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u3042\u306A\u305F\u306E\u3082\u306E\u3067\u3059)\u3002"),console.error(" \u9023\u6295\u3092\u907F\u3051\u308B\u305F\u3081\u3001\u65B0\u898F\u9001\u4FE1\u3067\u306A\u304F\u76F4\u524D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306E edit \u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044:"),console.error(` ${U}`),console.error(" \u3053\u306E\u307E\u307E\u9001\u4FE1\u3059\u308B\u5834\u5408\u306F --code=XXXX \u3067\u78BA\u5B9A\u3002")}}catch{}if(o&&h.length){let O={sim:0,msg:null};for(let K of h){let U=typeof K.text==="string"?K.text:"";if(!U)continue;let Q=Dg(a,U);if(Q>O.sim)O={sim:Q,msg:K}}if(O.msg&&O.sim>=0.82){let K=Math.round(O.sim*100);console.error(`\u26A0 possible duplicate: ${K}% similar to an existing thread message \u2014 ${await Ei(e,O.msg,60,s)}`)}}let x=await r(),b=await go(e,i,s),_=De(i,o??"",d,a,x?.userId??"");if(t.code!==_){let O=await _t(e,i,n,s),K=we(x,{asBot:t.asBot});if(o){let U=await mg(e,o,h,s),Q=h.slice(-3),S=Q.length?await Promise.all(Q.map(async(C)=>` ${await Ei(e,C,60,s)}`)):[" (thread context unavailable)"];ye(t.code,_,["--- Recent messages in thread ----------------",...S,...u,"--- Sending ----------------------------------",K,` \u2192 ${O} thread of ${U} \u2014 THREAD REPLY`,` Message: ${a}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],b)}else ye(t.code,_,["--- Last message in channel ------------------",` ${f}: ${d.split(`
354
+ `)[0]?.slice(0,100)??"(empty)"}`,...u,"--- Sending ----------------------------------",K,` \u2192 ${O} \u2014 NEW top-level message`,` Message: ${a}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],b)}let A=en("send"),N=await Xt(e,i,a,o,t.broadcast,s,void 0,A.metadata),j="";try{j=await qn(e,i,N,s)}catch{}if(A.record({team:(await r())?.team,channel:i,target:t.target,ts:N,threadTs:o,permalink:j,text:a,asBot:t.asBot}),j)console.log(`\u2713 Sent: ${j}`);else console.log(`\u2713 Sent (ts: ${N})`);if(t.asBot&&i.startsWith("D"))try{let O=await Bs(e);if(!O.ok)for(let K of Ms(O,!0))console.error(K);else{let K=O.appId?`https://api.slack.com/apps/${O.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${K} \u2192 App Home.`)}}catch{}}var Ag=2,Se=3,Tg=4,Ig=5,Og=1.618033988749895,Pg=1000,Rg=5000,sd=8,Ng=(e)=>new Promise((t)=>setTimeout(t,e)),Bg=new Set(["thread_broadcast"]),Mg=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function fo(e){let t=new Set;return{text:e.replace(Mg,(o,s)=>{let r=s.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function mo(e,t,n){if(!t.startsWith("D"))return;try{let o=I(await Qn(e,t,n)),s=I(o.channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function bd(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,audience:c,broadcast:a,cookie:l,timeout:u,shown:d}=t,{askerUserId:f,askerBotId:h}=t,m=(S)=>typeof S==="string"&&!!S&&S!==f&&(a||c.has(S)),p,D="";function x(S){let C=Y(S.reactions).map(I),T=[];for(let F=0;F<r.length;F++){let B=C.find((X)=>X.name===He[F].name),Z=B?Y(B.users).filter(m):[];if(Z.length)T.push({index:F,users:Z})}return T}async function b(S,C){let T=typeof S.text==="string"?S.text:"";if(!T)return;let F=Lr(T,C);if(F===T)return;try{await Yt(e,n,o,F,l,!0)}catch(B){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B instanceof Error?B.message:String(B)})`)}}async function _(S){let C=x(S);if(C.length<=1&&vr(typeof S.text==="string"?S.text:"").length)await b(S,[]);if(!C.length)return null;if(C.length===1){let{index:B,users:Z}=C[0];return{answer:r[B],how:`\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${He[B].glyph}`,who:Z[0]}}let T=C.map((B)=>He[B.index].glyph).join(" / ");console.error(` (${T} \u304C\u540C\u6642\u306B\u9078\u3070\u308C\u3066\u3044\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let F=[...new Set(C.flatMap((B)=>B.users))].sort();return await b(S,F),null}let A=[...r,...t.overflow];function N(S,C=1/0){let T=[...S].sort((F,B)=>Number(F.ts)-Number(B.ts));for(let F of T){if(!(Number(F.ts)>Number(o)))continue;if(t.after&&!(Number(F.ts)>Number(t.after)))continue;if(!m(F.user))continue;if(typeof F.subtype==="string"&&!Bg.has(F.subtype))continue;if(Number(F.ts)>=C)break;let B=typeof F.text==="string"?F.text.trim():"";if(!B)continue;if(!A.length)return{answer:B,how:"\u8FD4\u4FE1",who:F.user};let Z=bl(B,A);if(Z.kind==="chosen")return{answer:A[Z.index-1],how:`\u8FD4\u4FE1 (${Z.index})`,who:F.user};let X=Z.kind==="ambiguous";if(!p||p.ambiguous&&!X||p.ambiguous===X&&Number(F.ts)<Number(p.ts))p={text:B,who:typeof F.user==="string"?F.user:"",ts:String(F.ts),ambiguous:X}}return null}async function j(){if(p=void 0,t.threadParentTs){let F=I(await ze(e,n,t.threadParentTs,100,l)),B=Y(F.messages).map(I),Z=B.find((X)=>X.ts===o);if(Z){let X=await _(Z);if(X)return X}return N(B)}let S=I(await nt(e,n,30,o,void 0,l,!0)),C=Y(S.messages).map(I),T=C.find((F)=>F.ts===o);if(T){let F=await _(T);if(F)return F}if(!i){let F=C.filter((Z)=>Number(Z.ts)>Number(o)&&(h&&Z.bot_id===h||f&&Z.user===f)).reduce((Z,X)=>Math.min(Z,Number(X.ts)),1/0),B=N(C,F);if(B)return B}if(T&&Number(T.reply_count)>0){let F=I(await ze(e,n,o,30,l)),B=N(Y(F.messages).map(I));if(B)return B}return null}async function O(S){for(let T=0;T<r.length;T++)try{await Gn(e,n,o,He[T].name,l)}catch{}let C="";if(S.who)try{C=await Te(e,S.who,l)}catch{C=S.who}if(C)console.error(` \u56DE\u7B54\u8005: ${q(C)}`);try{await Yt(e,n,o,Dl(s,S,C),l,!0);try{await hn(e,n,o,jr,l),await Gn(e,n,o,qs,l)}catch{}}catch(T){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${T instanceof Error?T.message:String(T)})`)}}let K=Date.now()+u*1000,U=0,Q=Pg;for(;;){let S=null;try{S=await j(),U=0}catch(C){if(U++,U>=sd)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${U} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${C instanceof Error?C.message:String(C)}`),process.exit(Se);console.error(` (Slack \u30A8\u30E9\u30FC ${U}/${sd}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${C instanceof Error?C.message:String(C)})`)}if(S)await O(S),console.log(S.answer),process.exit(0);if(p&&!p.ambiguous){let C=p.who;try{if(C)C=await Te(e,C,l)}catch{}console.error(` (${q(C)} \u304C\u9078\u629E\u80A2\u5916\u306E\u8FD4\u4FE1\u3092\u3057\u307E\u3057\u305F \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u672C\u6587\u3092 stdout \u306B\u51FA\u3057\u307E\u3059)`),console.error(` \u9078\u629E\u80A2: ${A.map((T,F)=>`${F+1}. ${q(zt(T))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${io(d,t.asBot,p.ts)}`),console.log(p.text),process.exit(Ig)}if(p&&p.ts!==D){D=p.ts;let C=p.who;try{if(C)C=await Te(e,C,l)}catch{}console.error(` (${q(C)} \u306E\u8FD4\u4FE1\u306F\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3057\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`),console.error(` \u300C${q(p.text)}\u300D`)}if(Date.now()>=K)break;await Ng(Math.min(Q,Math.max(0,K-Date.now()))),Q=Math.min(Q*Og,Rg)}if(p)console.error("Error: \u8FD4\u4FE1\u306F\u3042\u308A\u307E\u3057\u305F\u304C\u3001\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3059\u308B\u305F\u3081\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093 (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)"),console.error(` \u8FD4\u4FE1: \u300C${q(p.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${A.map((S,C)=>`${C+1}. ${q(zt(S))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${io(d,t.asBot,t.after)}`),process.exit(Tg);if(u===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${d}`);else console.error(`Error: ${u}s \u4EE5\u5185\u306B\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)`),console.error(` ${d}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${io(d,t.asBot,t.after)}`);process.exit(Ag)}function io(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function vg(e,t){let{ref:n,threadTs:o}=wn(t.target,!1),s=t.cookie,r=pt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await dt(e,t.userId,s);else i=await he(e,n,s);let c=(await r())?.userId??"",a=await mo(e,i,s);if(!t.asBot&&!!c&&a===c)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
355
+ `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=fo(qe(t.question)),u=fo(qe(t.body??"")),d=new Set([...l.kinds,...u.kinds]),f=t.mentionToken??e,h=await Qt(f,l.text,i,t.mentionCookie),m=u.text?await Qt(f,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},p=h.text,D=m.text,x=[...h.resolved,...m.resolved],b=[...h.unresolved,...m.unresolved];for(let R of ts(b))console.error(`\u26A0 ${q(R)}`);let _=d.size>0,A=new Set(x.map((R)=>R.userId).filter((R)=>R!==c)),N=new Map(x.map((R)=>[R.userId,R.display])),j;if(_)j=`anyone in ${n} (${[...d].map((R)=>`@${R}`).join(", ")})`;else{if(!A.size&&a&&a!==c)A.add(a),N.set(a,await Te(e,a,s));if(!A.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+(b.length?` (${b.map((R)=>q(R.surface)).join(", ")} matched no one, so it names nobody.)
356
356
  `:"")+` Tag the person who should answer: slack ask '${t.target}' '@alice ${t.question}' ...
357
357
  Or open it to the whole channel: slack ask '${t.target}' '@here ${t.question}' ...
358
- (In a 1:1 DM the other person counts automatically.)`),process.exit(ke);j=[...A].map((R)=>`@${q(N.get(R)??R)} (${R})`).join(", ")}let I=t.choices.map(qe),J=I.slice(0,Js),U=I.slice(Js),Q=!i.startsWith("D")||!!o,F=al(p,D,J,U,Q);yt(F,t.allowUrlAdjacent);let E="",T="?";try{let R=await nt(e,i,1,void 0,void 0,s),le=Y(R.messages).map(O).filter((Le)=>Le.subtype===void 0||Le.subtype===null)[0];E=typeof le?.text==="string"?le.text:"",T=typeof le?.user==="string"?await Ae(e,le.user,s):typeof le?.username==="string"?le.username:"?"}catch{}let S=await r(),B=await ho(e,i,s),Z=xe(i,o??"",E,F,S?.userId??"");if(t.code!==Z){let R=await St(e,i,n,s),le=J.length?["--- Choices (seeded as reactions) ------------",...J.map((Le,z)=>` ${He[z].glyph} ${Ht(Le)}`),...U.map((Le,z)=>` (${z+11}) ${Ht(Le)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];Fe(t.code,Z,["--- Last message in channel ------------------",` ${T}: ${E.split(`
359
- `)[0]?.slice(0,100)??"(empty)"}`,...le,"--- Asking -----------------------------------",Se(S,{asBot:t.asBot}),` \u2192 ${R}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${p}`,` Answerable by: ${j}`,` Via: ${Q?"reactions or thread replies":"reactions or replies in this DM"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],B)}let X=Qt("ask"),oe=await Gt(e,i,F,o,!1,s,!0,X.metadata);await Ur([Hs,...J.map((R,le)=>He[le].name)],(R)=>pn(e,i,oe,R,s),(R,le)=>{let Le=le instanceof Error?le.message:String(le);if(R===Hs)console.error(` (marker ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${Le})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${Le})`)});let Me="";try{Me=await zn(e,i,oe,s)}catch{}let ne=Me||`${i}:${oe}`;if(console.error(`\u2713 Asked: ${ne}`),X.record({team:S?.team,channel:i,target:t.target,ts:oe,threadTs:o,permalink:Me,text:F,asBot:t.asBot}),!t.wait){console.log(ro(ne,!!t.asBot));return}let ve=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${ve}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let rt={channelId:i,ts:oe,question:p,reactable:J,overflow:U,threadOnly:Q,audience:A,broadcast:_,askerUserId:S?.userId??"",askerBotId:S?.botId??"",timeout:ve,shown:ne,asBot:!!t.asBot};if(o)rt.threadParentTs=o;if(s)rt.cookie=s;await nd(e,rt)}async function bg(e,t){let n=Yt(t.link),o,s,r;if(n?.ts)o=n.channel,s=n.ts,r=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let m=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!m)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
360
- `+` Got: ${q(t.link)}`),process.exit(ke);o=m[1],s=m[2]}let i;if(r){let m=O(await ze(e,o,r,100,t.cookie));i=Y(m.messages).map(O).find((p)=>p.ts===s)}else{let m=O(await nt(e,o,1,s,void 0,t.cookie,!0));i=Y(m.messages).map(O).find((p)=>p.ts===s)}if(!i)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${q(t.link)}`),process.exit(ke);let c=typeof i.text==="string"?i.text:"",a=ul(c);if(a.kind==="other")console.error("Error: \u3053\u308C\u306F `slack ask` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093\u3002\n"+` \u7406\u7531: ${ll(c)}
358
+ (In a 1:1 DM the other person counts automatically.)`),process.exit(Se);j=[...A].map((R)=>`@${q(N.get(R)??R)} (${R})`).join(", ")}let O=t.choices.map(qe),K=O.slice(0,zs),U=O.slice(zs),Q=!i.startsWith("D")||!!o,S=ml(p,D,K,U,Q);bt(S,t.allowUrlAdjacent);let C="",T="?";try{let R=await nt(e,i,1,void 0,void 0,s),ue=Y(R.messages).map(I).filter((Le)=>Le.subtype===void 0||Le.subtype===null)[0];C=typeof ue?.text==="string"?ue.text:"",T=typeof ue?.user==="string"?await Te(e,ue.user,s):typeof ue?.username==="string"?ue.username:"?"}catch{}let F=await r(),B=await go(e,i,s),Z=De(i,o??"",C,S,F?.userId??"");if(t.code!==Z){let R=await _t(e,i,n,s),ue=K.length?["--- Choices (seeded as reactions) ------------",...K.map((Le,z)=>` ${He[z].glyph} ${zt(Le)}`),...U.map((Le,z)=>` (${z+11}) ${zt(Le)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];ye(t.code,Z,["--- Last message in channel ------------------",` ${T}: ${C.split(`
359
+ `)[0]?.slice(0,100)??"(empty)"}`,...ue,"--- Asking -----------------------------------",we(F,{asBot:t.asBot}),` \u2192 ${R}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${p}`,` Answerable by: ${j}`,` Via: ${Q?"reactions or thread replies":"reactions or replies in this DM"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],B)}let X=en("ask"),oe=await Xt(e,i,S,o,!1,s,!0,X.metadata);await zr([qs,...K.map((R,ue)=>He[ue].name)],(R)=>hn(e,i,oe,R,s),(R,ue)=>{let Le=ue instanceof Error?ue.message:String(ue);if(R===qs)console.error(` (marker ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${Le})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${Le})`)});let Me="";try{Me=await qn(e,i,oe,s)}catch{}let ne=Me||`${i}:${oe}`;if(console.error(`\u2713 Asked: ${ne}`),X.record({team:F?.team,channel:i,target:t.target,ts:oe,threadTs:o,permalink:Me,text:S,asBot:t.asBot}),!t.wait){console.log(io(ne,!!t.asBot));return}let ve=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${ve}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let it={channelId:i,ts:oe,question:p,reactable:K,overflow:U,threadOnly:Q,audience:A,broadcast:_,askerUserId:F?.userId??"",askerBotId:F?.botId??"",timeout:ve,shown:ne,asBot:!!t.asBot};if(o)it.threadParentTs=o;if(s)it.cookie=s;await bd(e,it)}async function Lg(e,t){let n=Vt(t.link),o,s,r;if(n?.ts)o=n.channel,s=n.ts,r=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let m=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!m)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
360
+ `+` Got: ${q(t.link)}`),process.exit(Se);o=m[1],s=m[2]}let i;if(r){let m=I(await ze(e,o,r,100,t.cookie));i=Y(m.messages).map(I).find((p)=>p.ts===s)}else{let m=I(await nt(e,o,1,s,void 0,t.cookie,!0));i=Y(m.messages).map(I).find((p)=>p.ts===s)}if(!i)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${q(t.link)}`),process.exit(Se);let c=typeof i.text==="string"?i.text:"",a=wl(c);if(a.kind==="other")console.error("Error: \u3053\u308C\u306F `slack ask` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093\u3002\n"+` \u7406\u7531: ${yl(c)}
361
361
  ${q(t.link)}
362
- `+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${q(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(ke);if(a.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${q(a.question)}`),console.log(a.answer);return}let l=typeof i.user==="string"?i.user:"",u=typeof i.bot_id==="string"?i.bot_id:"",d=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(c),f=new Set;for(let m of c.matchAll(/<@([UW][A-Z0-9]+)>/g))if(m[1]!==l)f.add(m[1]);if(!f.size&&!d){let m=await go(e,o,t.cookie);if(m&&m!==l)f.add(m)}if(!f.size&&!d)console.error(`Error: \u3053\u306E\u8CEA\u554F\u306F\u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u6709\u52B9\u306A\u56DE\u7B54\u8005\u3092\u5224\u5B9A\u3067\u304D\u307E\u305B\u3093: ${q(t.link)}`),process.exit(ke);if(t.timeout>0)console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${t.timeout}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let h={channelId:o,ts:s,question:a.question,reactable:a.reactable,overflow:a.overflow,threadOnly:a.threadOnly,audience:f,broadcast:d,askerUserId:l,askerBotId:u,timeout:t.timeout,shown:t.link,asBot:t.asBot};if(r)h.threadParentTs=r;if(t.cookie)h.cookie=t.cookie;if(t.after)h.after=t.after;await nd(e,h)}var Xe=3;function kg(e){return`slack poll --results='${e}'`}async function Cg(e,t){let{ref:n,threadTs:o}=wn(t.target,!1),s=t.cookie,r=dt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await lt(e,t.userId,s);else i=await pe(e,n,s);let c=(await r())?.userId??"",a=await go(e,i,s);if(!t.asBot&&!!c&&a===c)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
363
- `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=uo(qe(t.question)),u=uo(qe(t.body??"")),d=t.mentionToken??e,f=await Zt(d,l.text,i,t.mentionCookie),h=u.text?await Zt(d,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},m=f.text,p=h.text;for(let T of es([...f.unresolved,...h.unresolved]))console.error(`\u26A0 ${q(T)}`);let D=t.choices.map(qe),C=!!t.multi,b=t.until??"",_=Dl(m,p,D,{multi:C,deadline:b}),A="",N="?";try{let T=await nt(e,i,1,void 0,void 0,s),S=Y(T.messages).map(O).filter((B)=>B.subtype===void 0||B.subtype===null)[0];A=typeof S?.text==="string"?S.text:"",N=typeof S?.user==="string"?await Ae(e,S.user,s):typeof S?.username==="string"?S.username:"?"}catch{}let j=await r(),I=await ho(e,i,s),J=xe(i,o??"",A,_,j?.userId??"");if(t.code!==J){let T=await St(e,i,n,s);Fe(t.code,J,["--- Last message in channel ------------------",` ${N}: ${A.split(`
364
- `)[0]?.slice(0,100)??"(empty)"}`,"--- Ballot (seeded as reactions) -------------",...D.map((S,B)=>` ${tt[B].glyph} ${Un(S)}`),"--- Posting ----------------------------------",Se(j,{asBot:t.asBot}),` \u2192 ${T}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${m}`,` Rule: ${C?"1 \u4EBA \u4F55\u7968\u3067\u3082 (--multi)":"1 \u4EBA 1 \u7968"}${b?` \u2014 \u7DE0\u5207 ${b}`:""}`," Note: \u3042\u306A\u305F\u81EA\u8EAB\u306E\u7968\u306F\u6570\u3048\u307E\u305B\u3093 (\u30D4\u30EB\u306F\u3042\u306A\u305F\u304C\u4ED8\u3051\u305F\u7A2E\u306A\u306E\u3067\u533A\u5225\u3067\u304D\u307E\u305B\u3093)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],I)}let U=Qt("poll"),Q=await Gt(e,i,_,o,!1,s,!0,U.metadata);await Ur([Kn,...D.map((T,S)=>tt[S].name)],(T)=>pn(e,i,Q,T,s),(T,S)=>{let B=S instanceof Error?S.message:String(S);if(T===Kn)console.error(` (marker ${T} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${T} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B})`)});let F="";try{F=await zn(e,i,Q,s)}catch{}let E=F||`${i}:${Q}`;console.error(`\u2713 Posted: ${E}`),U.record({team:j?.team,channel:i,target:t.target,ts:Q,threadTs:o,permalink:F,text:_,asBot:t.asBot}),console.log(kg(E)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${E}'${t.asBot?" --as-bot":""}`)}async function Eg(e,t,n){let o=Yt(t),s,r,i;if(o?.ts)s=o.channel,r=o.ts,i=o.threadTs&&o.threadTs!==o.ts?o.threadTs:void 0;else{let a=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!a)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
365
- `+` Got: ${q(t)}`),process.exit(Xe);s=a[1],r=a[2]}let c;if(i){let a=O(await ze(e,s,i,100,n));c=Y(a.messages).map(O).find((l)=>l.ts===r)}else{let a=O(await nt(e,s,1,r,void 0,n,!0));c=Y(a.messages).map(O).find((l)=>l.ts===r)}if(!c)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${q(t)}`),process.exit(Xe);return{channelId:s,ts:r,msg:c}}function ju(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,o)=>`${tt[o].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function xg(e,t){let{channelId:n,ts:o,msg:s}=await Eg(e,t.link,t.cookie),r=typeof s.text==="string"?s.text:"",i=wl(r);if(i.kind==="other")console.error("Error: \u3053\u308C\u306F `slack poll` \u306E\u6295\u7968\u3067\u306F\u3042\u308A\u307E\u305B\u3093 (\u7968\u306E\u6570\u3048\u65B9\u304C\u5206\u304B\u308A\u307E\u305B\u3093)\u3002\n"+` ${q(t.link)}`),process.exit(Xe);if(i.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${q(i.question)}`);for(let h of ju(i.tallies))console.log(h);return}let c=new Set;if(typeof s.user==="string"&&s.user)c.add(s.user);let a=await zl(e,n,o,t.cookie),l=bl(i.choices,a,c,i.multi);console.error(`${q(i.question)}${i.deadline?` (\u7DE0\u5207 ${i.deadline})`:""}`);for(let h of ju(l.tallies))console.log(h);let u=l.tallies.reduce((h,m)=>h+m.count,0);if(console.error(` \u8A08 ${u} \u7968${i.multi?" (\u8907\u6570\u9078\u629E\u53EF)":""}`),t.names)for(let h=0;h<l.voters.length;h++){if(!l.voters[h].length)continue;let m=await Promise.all(l.voters[h].map((p)=>Ae(e,p,t.cookie)));console.error(` ${tt[h].glyph} ${m.map((p)=>`@${q(p)}`).join(", ")}`)}let d=i.multi?[]:l.ambiguous,f=Nr(r,d);if(f!==r&&!t.noNotify)try{await Xt(t.writeToken??e,n,o,f,t.writeToken?t.writeCookie:t.cookie,!0)}catch(h){console.error(` (\u6295\u7968\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${h instanceof Error?h.message:String(h)})
366
- `+" \u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u66F8\u304D\u63DB\u3048\u3089\u308C\u308B\u306E\u306F\u6295\u7A3F\u8005\u3060\u3051\u3067\u3059 \u2014 bot \u304C\u6295\u7A3F\u3057\u305F\u6295\u7968\u306A\u3089 --as-bot \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}if(l.ambiguous.length){let h=await Promise.all(l.ambiguous.map((m)=>Ae(e,m,t.cookie)));console.error(`\u26A0 1 \u4EBA 1 \u7968\u306A\u306E\u306B\u8907\u6570\u62BC\u3057\u3066\u3044\u308B\u4EBA\u304C\u3044\u307E\u3059 (\u7121\u52B9\u7968): ${h.map((m)=>`@${q(m)}`).join(", ")}`)}if(!t.close)return;await Xt(t.writeToken??e,n,o,yl(i.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await pn(t.writeToken??e,n,o,Wr,t.writeToken?t.writeCookie:t.cookie),await qn(t.writeToken??e,n,o,Kn,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${q(t.link)}`)}async function Fg(e){let t=await Rs(e);for(let n of Ns(t,!1))console.log(n);if(!t.ok)process.exit(1)}function oo(){let e=wt();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
367
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function Wu(e,t,n,o){let s=await ut(n,e,o);return lt(t,s)}function Sg(e){if(/^\d{10,}$/.test(e))return parseInt(e,10);let t=new Date(e.replace(" ","T"));if(isNaN(t.getTime()))throw Error(`Cannot parse time: ${e}`);return Math.floor(t.getTime()/1000)}function _g(e){let t=new Date(e*1000);return`${new Intl.DateTimeFormat("sv-SE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).format(t).replace(/\u2212/g,"-")} (local) / ${t.toISOString()} (Unix: ${e})`}async function $g(e,t){let n=dt(e,t.cookie),{ref:o,threadTs:s}=wn(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await lt(e,t.userId,t.cookie);else r=await pe(e,o,t.cookie);let i=Sg(t.at),c=new Date(i*1000).toISOString(),a=await n();if(!t.asBot&&await bi(e,r,a?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
368
- `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let l=xe(r,t.message,String(i),a?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==l){let f=await ho(e,r,t.cookie);Fe(t.code,l,["--- Scheduling message -----------------------",Se(a,{asBot:t.asBot,pad:9}),` To: ${o}${s?` (thread ${s})`:""}${u}`,` At: ${_g(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await Wl(e,r,t.message,i,s,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${c})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
362
+ `+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${q(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(Se);if(a.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${q(a.question)}`),console.log(a.answer);return}let l=typeof i.user==="string"?i.user:"",u=typeof i.bot_id==="string"?i.bot_id:"",d=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(c),f=new Set;for(let m of c.matchAll(/<@([UW][A-Z0-9]+)>/g))if(m[1]!==l)f.add(m[1]);if(!f.size&&!d){let m=await mo(e,o,t.cookie);if(m&&m!==l)f.add(m)}if(!f.size&&!d)console.error(`Error: \u3053\u306E\u8CEA\u554F\u306F\u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u6709\u52B9\u306A\u56DE\u7B54\u8005\u3092\u5224\u5B9A\u3067\u304D\u307E\u305B\u3093: ${q(t.link)}`),process.exit(Se);if(t.timeout>0)console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${t.timeout}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let h={channelId:o,ts:s,question:a.question,reactable:a.reactable,overflow:a.overflow,threadOnly:a.threadOnly,audience:f,broadcast:d,askerUserId:l,askerBotId:u,timeout:t.timeout,shown:t.link,asBot:t.asBot};if(r)h.threadParentTs=r;if(t.cookie)h.cookie=t.cookie;if(t.after)h.after=t.after;await bd(e,h)}var Xe=3;function jg(e){return`slack poll --results='${e}'`}async function Wg(e,t){let{ref:n,threadTs:o}=wn(t.target,!1),s=t.cookie,r=pt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await dt(e,t.userId,s);else i=await he(e,n,s);let c=(await r())?.userId??"",a=await mo(e,i,s);if(!t.asBot&&!!c&&a===c)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
363
+ `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=fo(qe(t.question)),u=fo(qe(t.body??"")),d=t.mentionToken??e,f=await Qt(d,l.text,i,t.mentionCookie),h=u.text?await Qt(d,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},m=f.text,p=h.text;for(let T of ts([...f.unresolved,...h.unresolved]))console.error(`\u26A0 ${q(T)}`);let D=t.choices.map(qe),x=!!t.multi,b=t.until??"",_=Fl(m,p,D,{multi:x,deadline:b}),A="",N="?";try{let T=await nt(e,i,1,void 0,void 0,s),F=Y(T.messages).map(I).filter((B)=>B.subtype===void 0||B.subtype===null)[0];A=typeof F?.text==="string"?F.text:"",N=typeof F?.user==="string"?await Te(e,F.user,s):typeof F?.username==="string"?F.username:"?"}catch{}let j=await r(),O=await go(e,i,s),K=De(i,o??"",A,_,j?.userId??"");if(t.code!==K){let T=await _t(e,i,n,s);ye(t.code,K,["--- Last message in channel ------------------",` ${N}: ${A.split(`
364
+ `)[0]?.slice(0,100)??"(empty)"}`,"--- Ballot (seeded as reactions) -------------",...D.map((F,B)=>` ${tt[B].glyph} ${Un(F)}`),"--- Posting ----------------------------------",we(j,{asBot:t.asBot}),` \u2192 ${T}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${m}`,` Rule: ${x?"1 \u4EBA \u4F55\u7968\u3067\u3082 (--multi)":"1 \u4EBA 1 \u7968"}${b?` \u2014 \u7DE0\u5207 ${b}`:""}`," Note: \u3042\u306A\u305F\u81EA\u8EAB\u306E\u7968\u306F\u6570\u3048\u307E\u305B\u3093 (\u30D4\u30EB\u306F\u3042\u306A\u305F\u304C\u4ED8\u3051\u305F\u7A2E\u306A\u306E\u3067\u533A\u5225\u3067\u304D\u307E\u305B\u3093)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],O)}let U=en("poll"),Q=await Xt(e,i,_,o,!1,s,!0,U.metadata);await zr([Jn,...D.map((T,F)=>tt[F].name)],(T)=>hn(e,i,Q,T,s),(T,F)=>{let B=F instanceof Error?F.message:String(F);if(T===Jn)console.error(` (marker ${T} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${T} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B})`)});let S="";try{S=await qn(e,i,Q,s)}catch{}let C=S||`${i}:${Q}`;console.error(`\u2713 Posted: ${C}`),U.record({team:j?.team,channel:i,target:t.target,ts:Q,threadTs:o,permalink:S,text:_,asBot:t.asBot}),console.log(jg(C)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${C}'${t.asBot?" --as-bot":""}`)}async function Ug(e,t,n){let o=Vt(t),s,r,i;if(o?.ts)s=o.channel,r=o.ts,i=o.threadTs&&o.threadTs!==o.ts?o.threadTs:void 0;else{let a=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!a)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
365
+ `+` Got: ${q(t)}`),process.exit(Xe);s=a[1],r=a[2]}let c;if(i){let a=I(await ze(e,s,i,100,n));c=Y(a.messages).map(I).find((l)=>l.ts===r)}else{let a=I(await nt(e,s,1,r,void 0,n,!0));c=Y(a.messages).map(I).find((l)=>l.ts===r)}if(!c)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${q(t)}`),process.exit(Xe);return{channelId:s,ts:r,msg:c}}function od(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,o)=>`${tt[o].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function Jg(e,t){let{channelId:n,ts:o,msg:s}=await Ug(e,t.link,t.cookie),r=typeof s.text==="string"?s.text:"",i=$l(r);if(i.kind==="other")console.error("Error: \u3053\u308C\u306F `slack poll` \u306E\u6295\u7968\u3067\u306F\u3042\u308A\u307E\u305B\u3093 (\u7968\u306E\u6570\u3048\u65B9\u304C\u5206\u304B\u308A\u307E\u305B\u3093)\u3002\n"+` ${q(t.link)}`),process.exit(Xe);if(i.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${q(i.question)}`);for(let h of od(i.tallies))console.log(h);return}let c=new Set;if(typeof s.user==="string"&&s.user)c.add(s.user);let a=await uu(e,n,o,t.cookie),l=Al(i.choices,a,c,i.multi);console.error(`${q(i.question)}${i.deadline?` (\u7DE0\u5207 ${i.deadline})`:""}`);for(let h of od(l.tallies))console.log(h);let u=l.tallies.reduce((h,m)=>h+m.count,0);if(console.error(` \u8A08 ${u} \u7968${i.multi?" (\u8907\u6570\u9078\u629E\u53EF)":""}`),t.names)for(let h=0;h<l.voters.length;h++){if(!l.voters[h].length)continue;let m=await Promise.all(l.voters[h].map((p)=>Te(e,p,t.cookie)));console.error(` ${tt[h].glyph} ${m.map((p)=>`@${q(p)}`).join(", ")}`)}let d=i.multi?[]:l.ambiguous,f=Lr(r,d);if(f!==r&&!t.noNotify)try{await Yt(t.writeToken??e,n,o,f,t.writeToken?t.writeCookie:t.cookie,!0)}catch(h){console.error(` (\u6295\u7968\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${h instanceof Error?h.message:String(h)})
366
+ `+" \u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u66F8\u304D\u63DB\u3048\u3089\u308C\u308B\u306E\u306F\u6295\u7A3F\u8005\u3060\u3051\u3067\u3059 \u2014 bot \u304C\u6295\u7A3F\u3057\u305F\u6295\u7968\u306A\u3089 --as-bot \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}if(l.ambiguous.length){let h=await Promise.all(l.ambiguous.map((m)=>Te(e,m,t.cookie)));console.error(`\u26A0 1 \u4EBA 1 \u7968\u306A\u306E\u306B\u8907\u6570\u62BC\u3057\u3066\u3044\u308B\u4EBA\u304C\u3044\u307E\u3059 (\u7121\u52B9\u7968): ${h.map((m)=>`@${q(m)}`).join(", ")}`)}if(!t.close)return;await Yt(t.writeToken??e,n,o,_l(i.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await hn(t.writeToken??e,n,o,Hr,t.writeToken?t.writeCookie:t.cookie),await Gn(t.writeToken??e,n,o,Jn,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${q(t.link)}`)}async function Kg(e){let t=await Bs(e);for(let n of Ms(t,!1))console.log(n);if(!t.ok)process.exit(1)}function ro(){let e=ct();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
367
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function rd(e,t,n,o){let s=await ft(n,e,o);return dt(t,s)}function Hg(e){if(/^\d{10,}$/.test(e))return parseInt(e,10);let t=new Date(e.replace(" ","T"));if(isNaN(t.getTime()))throw Error(`Cannot parse time: ${e}`);return Math.floor(t.getTime()/1000)}function zg(e){let t=new Date(e*1000);return`${new Intl.DateTimeFormat("sv-SE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).format(t).replace(/\u2212/g,"-")} (local) / ${t.toISOString()} (Unix: ${e})`}async function qg(e,t){let n=pt(e,t.cookie),{ref:o,threadTs:s}=wn(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await dt(e,t.userId,t.cookie);else r=await he(e,o,t.cookie);let i=Hg(t.at),c=new Date(i*1000).toISOString(),a=await n();if(!t.asBot&&await Ai(e,r,a?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
368
+ `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let l=De(r,t.message,String(i),a?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==l){let f=await go(e,r,t.cookie);ye(t.code,l,["--- Scheduling message -----------------------",we(a,{asBot:t.asBot,pad:9}),` To: ${o}${s?` (thread ${s})`:""}${u}`,` At: ${zg(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await ru(e,r,t.message,i,s,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${c})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
369
369
  `+` slack schedule ls --as-bot
370
- slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await Rs(e);if(!f.ok)for(let h of Ns(f,!0))console.error(h);else{let h=f.appId?`https://api.slack.com/apps/${f.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${h} \u2192 App Home.`)}}catch{}}}async function Uu(e,t,n,o){let s;if(n)s=n;else if(t)s=await pe(e,t,o);let i=(await Ul(e,s,o)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let c of i){let a=new Date(c.post_at*1000).toISOString();console.log(`${c.id} ${a} [${c.channel_id}] ${c.text.split(`
371
- `)[0]?.slice(0,80)??""}`)}}async function Ku(e,t){let n;if(t.channelId)n=t.channelId;else n=await pe(e,t.target,t.cookie);let o=await yn(e,t.cookie),s=xe(n,t.id,o?.userId??"");if(t.code!==s)Fe(t.code,s,["--- Deleting scheduled message ---------------",Se(o,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await Kl(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function Ag(e,t){let n=dt(e,t.cookie),{statSync:o,existsSync:s}=await import("fs"),{basename:r}=await import("path");for(let m of t.filePaths)if(!s(m))console.error(`Error: file not found: ${m}`),process.exit(1);let{ref:i,threadTs:c}=wn(t.target),a;if(t.channelId)a=t.channelId;else if(t.userId)a=await lt(e,t.userId,t.cookie);else a=await pe(e,i,t.cookie);if(await bi(e,a,(await n())?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own upload.`);let l=t.filePaths.length>1,u=t.filePaths.map((m)=>{let p=r(m),D=l?p:t.title??p;return{fp:m,filename:p,title:D,sizeFmt:po(o(m).size)}}),d=await n(),f=xe(a,...u.flatMap((m)=>[m.fp,m.title]),d?.userId??"");if(t.code!==f){let m=` To: ${i}${c?` (thread ${c})`:""}`,p=l?[`--- Uploading ${u.length} files ------------------------`,Se(d,{pad:7}),m,...u.map((D)=>` ${D.filename} (${D.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",Se(d,{pad:7}),m,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];Fe(t.code,f,p)}let h=u.length;for(let m=0;m<h;m++){let p=u[m],D={title:p.title};if(c!==void 0)D.threadTs=c;if(t.comment!==void 0&&m===0)D.initialComment=t.comment;let{fileId:C,permalink:b}=await ru(e,a,p.fp,D,t.cookie),_=h>1?`[${m+1}/${h}] `:"";console.log(`${_}\u2713 Uploaded (file_id: ${C}${b?`, url: ${b}`:""})`)}}async function Tg(e,t,n){let o=n.channel?await pe(e,n.channel,t):void 0,s=[],r=1,i=1;do{let a={page:r,count:200};if(n.types)a.types=n.types;if(o)a.channel=o;if(n.user)a.user=n.user;let l=O(await Bl(e,a,t));for(let u of Y(l.files))s.push(O(u));i=Number(O(l.paging).pages??1),r++}while(s.length<n.limit&&r<=i);let c=s.slice(0,n.limit);if(n.format==="jsonl"){for(let a of c)console.log(JSON.stringify({id:a.id??null,name:a.name??a.title??null,filetype:a.filetype??null,size:a.size??null,user:a.user??null,created:a.created??null,permalink:a.permalink??null}));return}for(let a of c){let l=String(a.id??""),u=typeof a.name==="string"?a.name:typeof a.title==="string"?a.title:l,d=typeof a.filetype==="string"?a.filetype:"?",f=typeof a.size==="number"?po(a.size):"";console.log(`${l} ${d.padEnd(7)} ${f.padStart(9)} ${u}`)}}function Og(e){if(/^F[A-Z0-9]+$/i.test(e))return e;return e.match(/\/lists\/[A-Za-z0-9]+\/(F[A-Za-z0-9]+)/i)?.[1]??e.match(/\/lists\/(F[A-Za-z0-9]+)/i)?.[1]}function Ig(e){if(typeof e.text==="string"&&e.text)return e.text;let t=e.value;if(typeof t==="string"||typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map((n)=>typeof n==="string"?n:String(O(n).text??O(n).name??O(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let o=e[n];if(o!=null)return typeof o==="object"?JSON.stringify(o):String(o)}return""}async function Pg(e,t,n,o){let s=Og(n);if(!s)throw Error(`Not a list ID or list URL: ${n}
372
- `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let a={limit:200};if(i)a.cursor=i;let l=O(await Ml(e,s,a,t));for(let d of Y(l.items??l.records))r.push(O(d));let u=O(l.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i&&r.length<o.limit);let c=r.slice(0,o.limit);if(o.format==="jsonl"){for(let a of c)console.log(JSON.stringify(a));return}for(let a of c){let l=String(a.id??""),u=Y(a.fields).map(O).map((d)=>{let f=String(d.key??d.column_id??"?"),h=Ig(d);return h?`${f}=${h}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function Rg(e){if(/^F[A-Z0-9]+$/i.test(e))return e;return e.match(/\/files\/[A-Za-z0-9]+\/(F[A-Za-z0-9]+)/)?.[1]}async function Ng(e,t,n,o){let s=Rg(n);if(!s)throw Error(`Not a file ID or file permalink: ${n}
373
- `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=O(await Nl(e,s,t)),i=O(r.file),c=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:s,a=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!a)throw Error(`files.info returned no download URL for ${s}`);let l={Authorization:`Bearer ${e}`};if(t)l.Cookie=`d=${t}`;let u=await fetch(a,{headers:l});if(!u.ok)throw Error(`Download failed: HTTP ${u.status} ${u.statusText}`);let d=Buffer.from(await u.arrayBuffer()),{statSync:f,existsSync:h}=await import("fs"),{basename:m}=await import("path"),p=o??c;if(o&&h(o)&&f(o).isDirectory())p=xt(o,m(c));zu(p,d),console.log(`\u2713 Downloaded ${c} (${po(d.length)}) \u2192 ${p}`)}async function Bg(){Th();let e=(s)=>An(s.workspace),t=(s)=>Qo(s.workspace),n={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},o=async(s,r)=>{let i={state:s.state??"open",mine:r||s.mine===!0,count:s.n??50,json:s.json===!0};if(s.in)i.in=s.in;if(s.from)i.from=s.from;let c=t(s);if(c)i.cookie=c;await Wh(e(s),i)};await nc(To(process.argv)).scriptName("slack").showHelpOnFail(!1).fail((s,r,i)=>{if(r)console.error(r.message),process.exit(1);console.error(s),console.error(""),i.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).middleware(async(s)=>{let r=String((s._??[])[0]??"");if(!r||r==="auth"||r==="login"||r==="agent"||r==="sent")return;try{An(s.workspace)}catch(i){if((i instanceof Error?i.message:String(i)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
374
- `),await Wn(),process.exit(0);throw i}},!0).command("agent","Bot agent session status and command heartbeat",(s)=>sl(s,wn)).command(["read [target]","msgs [target]"],"Browse messages",(s)=>s.positional("target",{type:"string",describe:"#channel, @user, or URL"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(s)=>{let r=e(s),i=s.json?"jsonl":s.format;if(s.target)await Nh(r,s.target,s.limit,i,s.unreplied,t(s));else await Mh(r)}).command("thread <target> <ts>","Show thread messages",(s)=>s.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(s)=>{let r=s.json?"jsonl":s.format;await Bh(e(s),s.target,s.ts,s.limit,r,t(s))}).command(["channel","channels","ch"],"Channel commands",(s)=>s.command(["ls","list"],"List channels",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("all",{type:"boolean",default:!1}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{await Lh(e(r),r.limit,r.filter,r.all,r.json?"jsonl":r.format,t(r))}).command("get <channel>","Show channel details",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(r)=>{let i=e(r),c=t(r),a=r.channel,l=a.startsWith("#")||a.startsWith("@")||a.startsWith("C")||a.startsWith("G")||a.startsWith("D")?a:`#${a}`,u=await pe(i,l,c),d=O(await Zn(i,u,c)),f=O(d.channel),h=typeof f.name==="string"?f.name:u,p=f.is_im===!0?"@":"#",D=String(O(f.purpose).value??""),C=String(O(f.topic).value??""),b=f.num_members??f.member_count??"";if(console.log(`${p}${h} ${u}`),C)console.log(`topic: ${C}`);if(D)console.log(`purpose: ${D}`);if(b)console.log(`members: ${b}`);console.log(`private: ${f.is_private===!0}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"Channel name (Slack lowercases it; no spaces)"}).option("private",{type:"boolean",default:!1,describe:"Create a private channel"}).option("invite",{type:"string",array:!0,default:[],describe:"Users to invite after creating (@handle or Uxxxx, repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{let i=e(r),c=t(r),a=r.name.replace(/^#/,"").toLowerCase(),l=r.private===!0,u=r.invite.filter(Boolean),d=await yn(i,c),f=xe(a,String(l),u.join(","),d?.userId??"");if(r.code!==f)Fe(r.code,f,["--- Creating channel -------------------------",Se(d,{pad:9}),` name: ${l?"\uD83D\uDD12 ":"#"}${a}`,` private: ${l}`,...u.length?[` invite: ${u.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await ql(i,a,l,c)}catch(m){console.error(m instanceof Error?m.message:String(m)),process.exit(1)}if(console.log(`\u2713 Created ${l?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),u.length){let m=[];for(let p of u)try{m.push(p.startsWith("U")||p.startsWith("W")?p:await ut(i,p,c))}catch(D){console.error(` ! could not resolve ${p}: ${D instanceof Error?D.message:String(D)}`)}for(let p of m)try{let D=O(await Vn(i,p,c)),C=O(D.user);if(C.is_ultra_restricted===!0)console.error(`\u26A0 ${p} is a single-channel guest \u2014 Slack restricts them to their one existing channel; this invite will likely report success but not actually add them.`);else if(C.is_restricted===!0)console.error(`\u26A0 ${p} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(m.length)try{await Gl(i,h.id,m,c),console.log(`\u2713 Invited ${m.length} member${m.length===1?"":"s"}`)}catch(p){console.error(` ! invite failed: ${p instanceof Error?p.message:String(p)}`)}}}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(s)=>s.command(["ls","list"],"List workspace members",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("format",{type:"string",choices:["text","jsonl","yaml"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("external",{type:"boolean",default:!1,describe:"Also include people reachable only through Slack Connect shared channels \u2014 they are in ANOTHER workspace, so users.list never returns them (costs one API call per shared channel)"}),async(r)=>{let i=r.json?"jsonl":r.format,c=e(r),a=t(r),l=await Ql(c,a),u=r.filter?.toLowerCase(),d=Y(l.members).map(O);if(r.external){let p=new Set(d.map((_)=>String(_.id))),D=O(await Gn(c,a)),C=Y(D.channels).map(O).filter((_)=>_.is_ext_shared===!0&&!!_.name),b=new Set;for(let _ of C)try{for(let A of await eu(c,String(_.id),a))if(!p.has(A))b.add(A)}catch{}for(let _ of b)try{let A=O(await Vn(c,_,a)),N=O(A.user);if(N.id)d.push(N)}catch{}}let f=d.filter((p)=>p.deleted!==!0&&p.is_bot!==!0&&String(p.id)!=="USLACKBOT").filter((p)=>{if(!u)return!0;let D=String(p.name??"").toLowerCase(),C=String(O(p.profile).real_name??"").toLowerCase(),b=String(O(p.profile).email??"").toLowerCase();return D.includes(u)||C.includes(u)||b.includes(u)}).slice(0,r.limit);if(i==="jsonl"){for(let p of f)console.log(JSON.stringify(p));return}if(i==="yaml"){for(let p of f){let D=function(C,b=""){if(C===null)return"null";if(typeof C==="string")return C.includes(`
370
+ slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await Bs(e);if(!f.ok)for(let h of Ms(f,!0))console.error(h);else{let h=f.appId?`https://api.slack.com/apps/${f.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${h} \u2192 App Home.`)}}catch{}}}async function id(e,t,n,o){let s;if(n)s=n;else if(t)s=await he(e,t,o);let i=(await iu(e,s,o)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let c of i){let a=new Date(c.post_at*1000).toISOString();console.log(`${c.id} ${a} [${c.channel_id}] ${c.text.split(`
371
+ `)[0]?.slice(0,80)??""}`)}}async function ad(e,t){let n;if(t.channelId)n=t.channelId;else n=await he(e,t.target,t.cookie);let o=await rt(e,t.cookie),s=De(n,t.id,o?.userId??"");if(t.code!==s)ye(t.code,s,["--- Deleting scheduled message ---------------",we(o,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await au(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function Gg(e,t){let n=pt(e,t.cookie),{statSync:o,existsSync:s}=await import("fs"),{basename:r}=await import("path");for(let m of t.filePaths)if(!s(m))console.error(`Error: file not found: ${m}`),process.exit(1);let{ref:i,threadTs:c}=wn(t.target),a;if(t.channelId)a=t.channelId;else if(t.userId)a=await dt(e,t.userId,t.cookie);else a=await he(e,i,t.cookie);if(await Ai(e,a,(await n())?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own upload.`);let l=t.filePaths.length>1,u=t.filePaths.map((m)=>{let p=r(m),D=l?p:t.title??p;return{fp:m,filename:p,title:D,sizeFmt:ho(o(m).size)}}),d=await n(),f=De(a,...u.flatMap((m)=>[m.fp,m.title]),d?.userId??"");if(t.code!==f){let m=` To: ${i}${c?` (thread ${c})`:""}`,p=l?[`--- Uploading ${u.length} files ------------------------`,we(d,{pad:7}),m,...u.map((D)=>` ${D.filename} (${D.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",we(d,{pad:7}),m,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];ye(t.code,f,p)}let h=u.length;for(let m=0;m<h;m++){let p=u[m],D={title:p.title};if(c!==void 0)D.threadTs=c;if(t.comment!==void 0&&m===0)D.initialComment=t.comment;let{fileId:x,permalink:b}=await Cu(e,a,p.fp,D,t.cookie),_=h>1?`[${m+1}/${h}] `:"";console.log(`${_}\u2713 Uploaded (file_id: ${x}${b?`, url: ${b}`:""})`)}}async function Xg(e,t,n){let o=n.channel?await he(e,n.channel,t):void 0,s=[],r=1,i=1;do{let a={page:r,count:200};if(n.types)a.types=n.types;if(o)a.channel=o;if(n.user)a.user=n.user;let l=I(await Yl(e,a,t));for(let u of Y(l.files))s.push(I(u));i=Number(I(l.paging).pages??1),r++}while(s.length<n.limit&&r<=i);let c=s.slice(0,n.limit);if(n.format==="jsonl"){for(let a of c)console.log(JSON.stringify({id:a.id??null,name:a.name??a.title??null,filetype:a.filetype??null,size:a.size??null,user:a.user??null,created:a.created??null,permalink:a.permalink??null}));return}for(let a of c){let l=String(a.id??""),u=typeof a.name==="string"?a.name:typeof a.title==="string"?a.title:l,d=typeof a.filetype==="string"?a.filetype:"?",f=typeof a.size==="number"?ho(a.size):"";console.log(`${l} ${d.padEnd(7)} ${f.padStart(9)} ${u}`)}}function Do(e){if(/^F[A-Z0-9]+$/i.test(e))return e;return e.match(/\/lists\/[A-Za-z0-9]+\/(F[A-Za-z0-9]+)/i)?.[1]??e.match(/\/lists\/(F[A-Za-z0-9]+)/i)?.[1]}function Yg(e){if(typeof e.text==="string"&&e.text)return e.text;let t=e.value;if(typeof t==="string"||typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map((n)=>typeof n==="string"?n:String(I(n).text??I(n).name??I(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let o=e[n];if(o!=null)return typeof o==="object"?JSON.stringify(o):String(o)}return""}async function Vg(e,t,n,o){let s=Do(n);if(!s)throw Error(`Not a list ID or list URL: ${n}
372
+ `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let a={limit:200};if(i)a.cursor=i;let l=o.asBot?await si(as(),s,a):I(await tu(e,s,a,t));for(let d of Y(l.items??l.records))r.push(I(d));let u=I(l.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i&&r.length<o.limit);let c=r.slice(0,o.limit);if(o.format==="jsonl"){for(let a of c)console.log(JSON.stringify(a));return}for(let a of c){let l=String(a.id??""),u=Y(a.fields).map(I).map((d)=>{let f=String(d.key??d.column_id??"?"),h=Yg(d);return h?`${f}=${h}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function as(){let e=ct();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
373
+ `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function yo(e){let t=[];try{t=(await zn(e)).scopes}catch{return}if(t.length&&!t.includes("lists:write"))console.error(`Error: the bot token lacks the lists:write scope (needed for slackLists.* writes).
374
+ `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function Zg(e,t){try{let n=await ni(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function kd(e,t){let n=await si(e,t,{limit:1,includeList:!0}),o=Nl(I(n.list));if(!o.length)throw Error(`could not read the column schema of list ${t}`);return o}function wo(e){console.error(ce(e)),process.exit(1)}async function Qg(e){let t=e.cols.map(Pl),n=Rl(t),o=as();await yo(o);let s=await rt(o),r=De("lists-create",e.name,JSON.stringify(n),String(e.todo),s?.userId??"");if(e.code!==r)ye(e.code,r,["--- Creating Slack List ----------------------",we(s,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((a,l)=>` column: ${a.name} (${a.type}${a.choices?`: ${a.choices.join("/")}`:""})${l===0?" [primary]":""}`),` todo: ${e.todo?"on (adds Completed / Assignee / Due date)":"off"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let i;try{i=await Vl(o,e.name,n,e.todo)}catch(a){wo(a)}let c=String(i.list_id??I(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${c})`),console.log(await Zg(o,c))}async function em(e){let t=Do(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=as();await yo(n);let o=await kd(n,t),r=[{col:o.find((u)=>u.type==="text")??o[0],value:e.text},...Xr(e.sets).map((u)=>({col:qr(o,u.col),value:u.value}))],i=r.map((u)=>({column_id:u.col.id,...Gr(u.col,u.value)})),c=await rt(n),a=De("lists-add",t,JSON.stringify(i),c?.userId??"");if(e.code!==a)ye(e.code,a,["--- Adding a row to Slack List ---------------",we(c,{asBot:!0,pad:9}),` list: ${t}`,...r.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let l;try{l=await Zl(n,t,i)}catch(u){wo(u)}console.log(`\u2713 Added row ${String(I(l.item).id??"")} ${e.text}`)}async function tm(e){let t=Do(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=as();await yo(n);let o=await kd(n,t),s=Xr(e.sets).map((a)=>({col:qr(o,a.col),value:a.value}));if(e.done!==void 0){let a=Bl(o);if(!a)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);s.push({col:{...a,type:"checkbox"},value:String(e.done)})}if(!s.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let r=s.map((a)=>({row_id:e.row,column_id:a.col.id,...Gr(a.col,a.value)})),i=await rt(n),c=De("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==c)ye(e.code,c,["--- Updating Slack List row -----------------",we(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...s.map((a)=>` ${(a.col.name||a.col.key).padEnd(8)} ${a.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await eu(n,t,r)}catch(a){wo(a)}console.log(`\u2713 Updated row ${e.row}`)}async function nm(e){let t=Do(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);if(!e.users.length===!e.channels.length)throw Error("pass --user or --channel (Slack takes one kind per call, not both)");if(e.level==="owner"&&e.channels.length)throw Error("only a user can be made owner");let n=as();await yo(n);let o=e.users.length?e.users:e.channels,s=await rt(n),r=De("lists-share",t,e.level,o.join(","),s?.userId??"");if(e.code!==r)ye(e.code,r,["--- Sharing Slack List ----------------------",we(s,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${o.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Ql(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){wo(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${o.join(", ")}`)}function sm(e){if(/^F[A-Z0-9]+$/i.test(e))return e;return e.match(/\/files\/[A-Za-z0-9]+\/(F[A-Za-z0-9]+)/)?.[1]}async function om(e,t,n,o){let s=sm(n);if(!s)throw Error(`Not a file ID or file permalink: ${n}
375
+ `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=I(await Xl(e,s,t)),i=I(r.file),c=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:s,a=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!a)throw Error(`files.info returned no download URL for ${s}`);let l={Authorization:`Bearer ${e}`};if(t)l.Cookie=`d=${t}`;let u=await fetch(a,{headers:l});if(!u.ok)throw Error(`Download failed: HTTP ${u.status} ${u.statusText}`);let d=Buffer.from(await u.arrayBuffer()),{statSync:f,existsSync:h}=await import("fs"),{basename:m}=await import("path"),p=o??c;if(o&&h(o)&&f(o).isDirectory())p=St(o,m(c));ud(p,d),console.log(`\u2713 Downloaded ${c} (${ho(d.length)}) \u2192 ${p}`)}async function rm(){Xh();let e=(s)=>An(s.workspace),t=(s)=>sr(s.workspace),n={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},o=async(s,r)=>{let i={state:s.state??"open",mine:r||s.mine===!0,count:s.n??50,json:s.json===!0};if(s.in)i.in=s.in;if(s.from)i.from=s.from;let c=t(s);if(c)i.cookie=c;await ig(e(s),i)};await dc(Ro(process.argv)).scriptName("slack").showHelpOnFail(!1).fail((s,r,i)=>{if(r)console.error(r.message),process.exit(1);console.error(s),console.error(""),i.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).middleware(async(s)=>{let r=String((s._??[])[0]??"");if(!r||r==="auth"||r==="login"||r==="agent"||r==="sent")return;try{An(s.workspace)}catch(i){if((i instanceof Error?i.message:String(i)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
376
+ `),await Wn(),process.exit(0);throw i}},!0).command("agent","Bot agent session status and command heartbeat",(s)=>fl(s,wn)).command(["read [target]","msgs [target]"],"Browse messages",(s)=>s.positional("target",{type:"string",describe:"#channel, @user, or URL"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(s)=>{let r=e(s),i=s.json?"jsonl":s.format;if(s.target)await eg(r,s.target,s.limit,i,s.unreplied,t(s));else await ng(r)}).command("thread <target> <ts>","Show thread messages",(s)=>s.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(s)=>{let r=s.json?"jsonl":s.format;await tg(e(s),s.target,s.ts,s.limit,r,t(s))}).command(["channel","channels","ch"],"Channel commands",(s)=>s.command(["ls","list"],"List channels",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("all",{type:"boolean",default:!1}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{await og(e(r),r.limit,r.filter,r.all,r.json?"jsonl":r.format,t(r))}).command("get <channel>","Show channel details",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(r)=>{let i=e(r),c=t(r),a=r.channel,l=a.startsWith("#")||a.startsWith("@")||a.startsWith("C")||a.startsWith("G")||a.startsWith("D")?a:`#${a}`,u=await he(i,l,c),d=I(await Qn(i,u,c)),f=I(d.channel),h=typeof f.name==="string"?f.name:u,p=f.is_im===!0?"@":"#",D=String(I(f.purpose).value??""),x=String(I(f.topic).value??""),b=f.num_members??f.member_count??"";if(console.log(`${p}${h} ${u}`),x)console.log(`topic: ${x}`);if(D)console.log(`purpose: ${D}`);if(b)console.log(`members: ${b}`);console.log(`private: ${f.is_private===!0}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"Channel name (Slack lowercases it; no spaces)"}).option("private",{type:"boolean",default:!1,describe:"Create a private channel"}).option("invite",{type:"string",array:!0,default:[],describe:"Users to invite after creating (@handle or Uxxxx, repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{let i=e(r),c=t(r),a=r.name.replace(/^#/,"").toLowerCase(),l=r.private===!0,u=r.invite.filter(Boolean),d=await rt(i,c),f=De(a,String(l),u.join(","),d?.userId??"");if(r.code!==f)ye(r.code,f,["--- Creating channel -------------------------",we(d,{pad:9}),` name: ${l?"\uD83D\uDD12 ":"#"}${a}`,` private: ${l}`,...u.length?[` invite: ${u.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await du(i,a,l,c)}catch(m){console.error(m instanceof Error?m.message:String(m)),process.exit(1)}if(console.log(`\u2713 Created ${l?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),u.length){let m=[];for(let p of u)try{m.push(p.startsWith("U")||p.startsWith("W")?p:await ft(i,p,c))}catch(D){console.error(` ! could not resolve ${p}: ${D instanceof Error?D.message:String(D)}`)}for(let p of m)try{let D=I(await Zn(i,p,c)),x=I(D.user);if(x.is_ultra_restricted===!0)console.error(`\u26A0 ${p} is a single-channel guest \u2014 Slack restricts them to their one existing channel; this invite will likely report success but not actually add them.`);else if(x.is_restricted===!0)console.error(`\u26A0 ${p} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(m.length)try{await fu(i,h.id,m,c),console.log(`\u2713 Invited ${m.length} member${m.length===1?"":"s"}`)}catch(p){console.error(` ! invite failed: ${p instanceof Error?p.message:String(p)}`)}}}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(s)=>s.command(["ls","list"],"List workspace members",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("format",{type:"string",choices:["text","jsonl","yaml"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("external",{type:"boolean",default:!1,describe:"Also include people reachable only through Slack Connect shared channels \u2014 they are in ANOTHER workspace, so users.list never returns them (costs one API call per shared channel)"}),async(r)=>{let i=r.json?"jsonl":r.format,c=e(r),a=t(r),l=await Du(c,a),u=r.filter?.toLowerCase(),d=Y(l.members).map(I);if(r.external){let p=new Set(d.map((_)=>String(_.id))),D=I(await Xn(c,a)),x=Y(D.channels).map(I).filter((_)=>_.is_ext_shared===!0&&!!_.name),b=new Set;for(let _ of x)try{for(let A of await yu(c,String(_.id),a))if(!p.has(A))b.add(A)}catch{}for(let _ of b)try{let A=I(await Zn(c,_,a)),N=I(A.user);if(N.id)d.push(N)}catch{}}let f=d.filter((p)=>p.deleted!==!0&&p.is_bot!==!0&&String(p.id)!=="USLACKBOT").filter((p)=>{if(!u)return!0;let D=String(p.name??"").toLowerCase(),x=String(I(p.profile).real_name??"").toLowerCase(),b=String(I(p.profile).email??"").toLowerCase();return D.includes(u)||x.includes(u)||b.includes(u)}).slice(0,r.limit);if(i==="jsonl"){for(let p of f)console.log(JSON.stringify(p));return}if(i==="yaml"){for(let p of f){let D=function(x,b=""){if(x===null)return"null";if(typeof x==="string")return x.includes(`
375
377
  `)?`|
376
- ${C.split(`
378
+ ${x.split(`
377
379
  `).join(`
378
- `)}`:C;if(typeof C!=="object")return String(C);if(Array.isArray(C))return C.map((_)=>`
379
- ${b} - ${D(_,b+" ")}`).join("");return Object.entries(C).map(([_,A])=>`
380
- ${b} ${_}: ${D(A,b+" ")}`).join("")};console.log("---");for(let[C,b]of Object.entries(p))console.log(`${C}: ${D(b)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,m=f.length?String(O(Y(l.members).map(O)[0]??{}).team_id??""):"";for(let p of f){let D=O(p.profile),C=String(p.name??p.id),b=String(p.id??""),_=String(D.display_name||""),A=String(D.real_name||""),N=String(D.email||""),j=String(p.tz??""),J=[...new Set([_,A].filter((T)=>T&&T!==C))].join(" / "),U=j&&j!==h?j:"",Q=String(p.team_id??""),F=p.is_stranger===!0||m&&Q&&Q!==m?`external:${Q||"?"}`:p.is_ultra_restricted===!0?"single-channel guest":p.is_restricted===!0?"guest":"",E=[N,U].filter(Boolean).join(" ");console.log(`@${C} ${b} ${J}${E?" "+E:""}${F?` [${F}]`:""}`)}}).command("get <user>","Show user details",(r)=>r.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(r)=>{let i=e(r),c=t(r),a=r.user.startsWith("@")?r.user:`@${r.user}`,l="";try{l=await ut(i,a,c)}catch(I){console.error(I instanceof Error?I.message:String(I)),process.exit(1)}let u=O(await Vn(i,l,c)),d=O(u.user),f=O(d.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,m=String(d.name??l),p=String(d.id??l),D=String(f.display_name||""),C=String(f.real_name||""),b=String(f.email||""),_=String(d.tz??""),A=String(f.phone||""),N=String(f.title||"");console.log(`@${m} ${p}`);let j=[...new Set([D,C].filter((I)=>I&&I!==m))];if(j.length)console.log(`name: ${j.join(" / ")}`);if(b)console.log(`email: ${b}`);if(A)console.log(`phone: ${A}`);if(N)console.log(`title: ${N}`);if(_&&_!==h)console.log(`tz: ${_}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(s)=>s.option("limit",{alias:"l",type:"number",default:20}),async(s)=>{await vh(e(s),s.limit)}).command("search <query>","Full-text search",(s)=>s.positional("query",{type:"string",demandOption:!0}).option("count",{alias:"n",type:"number",default:100}).option("json",{type:"boolean",default:!1,describe:"Output raw JSON"}),async(s)=>{await Xu(e(s),s.query,s.count,s.json,t(s))}).command("send <target> <message>","Send a message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Send via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient and can be two-way"}).option("broadcast",{type:"boolean",default:!1,describe:`Also send to channel: broadcast a threaded reply back to the channel (Slack's "Also send to #channel" checkbox). Only effective with a thread target.`}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real <@USERID> mentions (on by default; resolves via users.list, then channel members for Slack Connect guests). Unresolved handles stay as plain text. The confirm preview shows the converted message before sending. Disable with --no-mentions for literal @text."}),async(s)=>{let r={target:s.target,message:s.message,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];if(s.broadcast)r.broadcast=!0;if(s.mentions!==!1){r.mentions=!0,r.mentionToken=e(s);let c=t(s);if(c)r.mentionCookie=c}let i;if(s["as-bot"]){let c=wt();if(!c)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
381
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!r.channelId&&!r.userId&&r.target.startsWith("@"))try{r.userId=await ut(e(s),r.target,t(s))}catch(a){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
380
+ `)}`:x;if(typeof x!=="object")return String(x);if(Array.isArray(x))return x.map((_)=>`
381
+ ${b} - ${D(_,b+" ")}`).join("");return Object.entries(x).map(([_,A])=>`
382
+ ${b} ${_}: ${D(A,b+" ")}`).join("")};console.log("---");for(let[x,b]of Object.entries(p))console.log(`${x}: ${D(b)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,m=f.length?String(I(Y(l.members).map(I)[0]??{}).team_id??""):"";for(let p of f){let D=I(p.profile),x=String(p.name??p.id),b=String(p.id??""),_=String(D.display_name||""),A=String(D.real_name||""),N=String(D.email||""),j=String(p.tz??""),K=[...new Set([_,A].filter((T)=>T&&T!==x))].join(" / "),U=j&&j!==h?j:"",Q=String(p.team_id??""),S=p.is_stranger===!0||m&&Q&&Q!==m?`external:${Q||"?"}`:p.is_ultra_restricted===!0?"single-channel guest":p.is_restricted===!0?"guest":"",C=[N,U].filter(Boolean).join(" ");console.log(`@${x} ${b} ${K}${C?" "+C:""}${S?` [${S}]`:""}`)}}).command("get <user>","Show user details",(r)=>r.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(r)=>{let i=e(r),c=t(r),a=r.user.startsWith("@")?r.user:`@${r.user}`,l="";try{l=await ft(i,a,c)}catch(O){console.error(O instanceof Error?O.message:String(O)),process.exit(1)}let u=I(await Zn(i,l,c)),d=I(u.user),f=I(d.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,m=String(d.name??l),p=String(d.id??l),D=String(f.display_name||""),x=String(f.real_name||""),b=String(f.email||""),_=String(d.tz??""),A=String(f.phone||""),N=String(f.title||"");console.log(`@${m} ${p}`);let j=[...new Set([D,x].filter((O)=>O&&O!==m))];if(j.length)console.log(`name: ${j.join(" / ")}`);if(b)console.log(`email: ${b}`);if(A)console.log(`phone: ${A}`);if(N)console.log(`title: ${N}`);if(_&&_!==h)console.log(`tz: ${_}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(s)=>s.option("limit",{alias:"l",type:"number",default:20}),async(s)=>{await sg(e(s),s.limit)}).command("search <query>","Full-text search",(s)=>s.positional("query",{type:"string",demandOption:!0}).option("count",{alias:"n",type:"number",default:100}).option("json",{type:"boolean",default:!1,describe:"Output raw JSON"}),async(s)=>{await pd(e(s),s.query,s.count,s.json,t(s))}).command("send <target> <message>","Send a message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Send via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient and can be two-way"}).option("broadcast",{type:"boolean",default:!1,describe:`Also send to channel: broadcast a threaded reply back to the channel (Slack's "Also send to #channel" checkbox). Only effective with a thread target.`}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real <@USERID> mentions (on by default; resolves via users.list, then channel members for Slack Connect guests). Unresolved handles stay as plain text. The confirm preview shows the converted message before sending. Disable with --no-mentions for literal @text."}),async(s)=>{let r={target:s.target,message:s.message,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];if(s.broadcast)r.broadcast=!0;if(s.mentions!==!1){r.mentions=!0,r.mentionToken=e(s);let c=t(s);if(c)r.mentionCookie=c}let i;if(s["as-bot"]){let c=ct();if(!c)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
383
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!r.channelId&&!r.userId&&r.target.startsWith("@"))try{r.userId=await ft(e(s),r.target,t(s))}catch(a){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
382
384
  ${a instanceof Error?a.message:String(a)}
383
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}i=c,r.asBot=!0}else{i=e(s);let c=t(s);if(c)r.cookie=c}try{await lg(i,r)}catch(c){console.error(me(c)),process.exit(1)}}).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("wait",{type:"boolean",default:!1,describe:"Block until answered; print ONLY the answer on stdout. Exit 0 = answered, 2 = nobody replied, 3 = transport failure, 4 = a reply matched several choices (stdout empty), 5 = a free-text reply that picked none of the choices (the reply is on stdout; NOT a decision \u2014 the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted. Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: ignore text replies at or before this ts (the reply an exit 5 already delivered). Reactions still count."}).option("timeout",{type:"number",default:3600,describe:"Overall limit for --wait / --waitFor, in seconds (0 with --waitFor = check once)"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Ask via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient"}),async(s)=>{let r=s.waitFor?String(s.waitFor):"",i=Number(s.timeout);if(!Number.isFinite(i)||i<0||i===0&&!r)console.error("Error: --timeout must be a positive number of seconds"),process.exit(ke);if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(ke);let d,f;if(s["as-bot"]){let h=wt();if(!h)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
384
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ke);d=h}else d=e(s),f=t(s);try{let h={link:r,timeout:i,asBot:!!s["as-bot"]};if(f)h.cookie=f;if(s.after){let m=String(s.after);if(!/^\d{10}\.\d{6}$/.test(m))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${q(m)})`),process.exit(ke);h.after=m}await bg(d,h)}catch(h){console.error(me(h)),process.exit(ke)}return}if(!s.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(ke);let c=String(s.question??"").trim();if(!c)console.error("Error: question is empty"),process.exit(ke);let a={allowUrlAdjacent:s["allow-url-adjacent"],target:s.target,question:c,choices:(s.choices??[]).map((d)=>String(d).trim()).filter(Boolean),timeout:i};if(s.code)a.code=s.code;if(s.body)a.body=s.body;if(s.wait)a.wait=!0;if(s["channel-id"])a.channelId=s["channel-id"];if(s["user-id"])a.userId=s["user-id"];a.mentionToken=e(s);let l=t(s);if(l)a.mentionCookie=l;let u;if(s["as-bot"]){let d=wt();if(!d)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
385
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ke);if(!a.channelId&&!a.userId&&a.target.startsWith("@"))try{a.userId=await ut(e(s),a.target,t(s))}catch(f){console.error(`Error: could not resolve ${a.target} to a user for the bot DM.
385
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}i=c,r.asBot=!0}else{i=e(s);let c=t(s);if(c)r.cookie=c}try{await $g(i,r)}catch(c){console.error(ce(c)),process.exit(1)}}).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("wait",{type:"boolean",default:!1,describe:"Block until answered; print ONLY the answer on stdout. Exit 0 = answered, 2 = nobody replied, 3 = transport failure, 4 = a reply matched several choices (stdout empty), 5 = a free-text reply that picked none of the choices (the reply is on stdout; NOT a decision \u2014 the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted. Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: ignore text replies at or before this ts (the reply an exit 5 already delivered). Reactions still count."}).option("timeout",{type:"number",default:3600,describe:"Overall limit for --wait / --waitFor, in seconds (0 with --waitFor = check once)"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Ask via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient"}),async(s)=>{let r=s.waitFor?String(s.waitFor):"",i=Number(s.timeout);if(!Number.isFinite(i)||i<0||i===0&&!r)console.error("Error: --timeout must be a positive number of seconds"),process.exit(Se);if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(Se);let d,f;if(s["as-bot"]){let h=ct();if(!h)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
386
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Se);d=h}else d=e(s),f=t(s);try{let h={link:r,timeout:i,asBot:!!s["as-bot"]};if(f)h.cookie=f;if(s.after){let m=String(s.after);if(!/^\d{10}\.\d{6}$/.test(m))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${q(m)})`),process.exit(Se);h.after=m}await Lg(d,h)}catch(h){console.error(ce(h)),process.exit(Se)}return}if(!s.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(Se);let c=String(s.question??"").trim();if(!c)console.error("Error: question is empty"),process.exit(Se);let a={allowUrlAdjacent:s["allow-url-adjacent"],target:s.target,question:c,choices:(s.choices??[]).map((d)=>String(d).trim()).filter(Boolean),timeout:i};if(s.code)a.code=s.code;if(s.body)a.body=s.body;if(s.wait)a.wait=!0;if(s["channel-id"])a.channelId=s["channel-id"];if(s["user-id"])a.userId=s["user-id"];a.mentionToken=e(s);let l=t(s);if(l)a.mentionCookie=l;let u;if(s["as-bot"]){let d=ct();if(!d)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
387
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Se);if(!a.channelId&&!a.userId&&a.target.startsWith("@"))try{a.userId=await ft(e(s),a.target,t(s))}catch(f){console.error(`Error: could not resolve ${a.target} to a user for the bot DM.
386
388
  ${f instanceof Error?f.message:String(f)}
387
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(ke)}u=d,a.asBot=!0}else{u=e(s);let d=t(s);if(d)a.cookie=d}try{await wg(u,a)}catch(d){console.error(me(d)),process.exit(ke)}}).command(["poll [target] [question] [choices..]","vote [target] [question] [choices..]"],"Post a poll with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions, then count them (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: 1 \u4EBA 1 \u7968)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's"}),async(s)=>{let r=s.close?String(s.close):s.results?String(s.results):"";if(s.results&&s.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(Xe);let i=()=>{let f=wt();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
388
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Xe);return f};if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(Xe);let f=e(s),h=t(s);try{let m={link:r};if(s.close)m.close=!0;if(s.names)m.names=!0;if(s["no-notify"])m.noNotify=!0;if(h)m.cookie=h;if(s["as-bot"])m.writeToken=i();await xg(f,m)}catch(m){console.error(me(m)),process.exit(Xe)}return}if(!s.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(Xe);let c=String(s.question??"").trim();if(!c)console.error("Error: question is empty"),process.exit(Xe);let a=(s.choices??[]).map((f)=>String(f).trim()).filter(Boolean);if(a.length<2||a.length>fn)console.error(`Error: poll needs 2..${fn} choices (got ${a.length}). For a free-text question use \`slack ask\`.`),process.exit(Xe);let l={target:s.target,question:c,choices:a};if(s.multi)l.multi=!0;if(s.until)l.until=String(s.until);if(s.code)l.code=s.code;if(s.body)l.body=s.body;if(s["channel-id"])l.channelId=s["channel-id"];if(s["user-id"])l.userId=s["user-id"];l.mentionToken=e(s);let u=t(s);if(u)l.mentionCookie=u;let d;if(s["as-bot"]){let f=i();if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await ut(e(s),l.target,t(s))}catch(h){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
389
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(Se)}u=d,a.asBot=!0}else{u=e(s);let d=t(s);if(d)a.cookie=d}try{await vg(u,a)}catch(d){console.error(ce(d)),process.exit(Se)}}).command(["poll [target] [question] [choices..]","vote [target] [question] [choices..]"],"Post a poll with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions, then count them (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: 1 \u4EBA 1 \u7968)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's"}),async(s)=>{let r=s.close?String(s.close):s.results?String(s.results):"";if(s.results&&s.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(Xe);let i=()=>{let f=ct();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
390
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Xe);return f};if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(Xe);let f=e(s),h=t(s);try{let m={link:r};if(s.close)m.close=!0;if(s.names)m.names=!0;if(s["no-notify"])m.noNotify=!0;if(h)m.cookie=h;if(s["as-bot"])m.writeToken=i();await Jg(f,m)}catch(m){console.error(ce(m)),process.exit(Xe)}return}if(!s.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(Xe);let c=String(s.question??"").trim();if(!c)console.error("Error: question is empty"),process.exit(Xe);let a=(s.choices??[]).map((f)=>String(f).trim()).filter(Boolean);if(a.length<2||a.length>pn)console.error(`Error: poll needs 2..${pn} choices (got ${a.length}). For a free-text question use \`slack ask\`.`),process.exit(Xe);let l={target:s.target,question:c,choices:a};if(s.multi)l.multi=!0;if(s.until)l.until=String(s.until);if(s.code)l.code=s.code;if(s.body)l.body=s.body;if(s["channel-id"])l.channelId=s["channel-id"];if(s["user-id"])l.userId=s["user-id"];l.mentionToken=e(s);let u=t(s);if(u)l.mentionCookie=u;let d;if(s["as-bot"]){let f=i();if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await ft(e(s),l.target,t(s))}catch(h){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
389
391
  ${h instanceof Error?h.message:String(h)}
390
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(Xe)}d=f,l.asBot=!0}else{d=e(s);let f=t(s);if(f)l.cookie=f}try{await Cg(d,l)}catch(f){console.error(me(f)),process.exit(Xe)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(s)=>s.positional("query",{type:"string",describe:"Substring of the message text (case-insensitive)"}).option("channel",{type:"string",describe:"Channel/DM id (C\u2026/D\u2026) or the target as typed (#eng, @bob)"}).option("since",{type:"string",describe:"Only newer than this: 30m, 2h, 7d, 1w, or an ISO date"}).option("session",{type:"string",describe:"Agent session id (prefix match)"}).option("cwd",{type:"string",describe:"Working directory the sender ran in (prefix match)"}).option("kind",{type:"string",choices:["send","ask","poll","edit"],describe:"Only this kind of write"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per line (every recorded field)"}).option("count",{alias:"n",type:"number",default:50,describe:"Max rows (newest first)"}),(s)=>{let r;if(s.since!==void 0){if(r=Tl(String(s.since)),r===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${q(String(s.since))})`),process.exit(1)}let i={limit:Number(s.count)||50};if(s.query)i.text=String(s.query);if(s.channel)i.channel=String(s.channel);if(r!==void 0)i.sinceMs=r;if(s.session)i.session=String(s.session);if(s.cwd){let a=$h(String(s.cwd));try{i.cwd=_h(a)}catch{i.cwd=a}}if(s.kind)i.kind=s.kind;let c=Al(i);if(!c)console.error(`Error: ${Hr}
391
- (${Jn()})`),process.exit(1);if(s.json){for(let a of c)console.log(JSON.stringify(a));return}if(!c.length){console.error(`No sent messages match (log: ${Jn()}).`);return}for(let a of c)console.log(Yh(a))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(s)=>s,async()=>{let s=wt();if(!s)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
392
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await Fg(s)}).command("schedule","Manage scheduled messages",(s)=>s.command("send <target> <message>","Schedule a message for later delivery",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("at",{type:"string",demandOption:!0,describe:"Delivery time (ISO datetime or Unix ts)"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Schedule via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. Without it a scheduled DM to yourself is posted by you, and Slack never notifies you of your own message \u2014 it fires into silence."}),async(r)=>{let i={target:r.target,message:r.message,at:r.at};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["user-id"])i.userId=r["user-id"],i.targetOverride=`--user-id ${r["user-id"]}`;let c;if(r["as-bot"]){let a=oo();if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await ut(e(r),i.target,t(r))}catch(l){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
392
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(Xe)}d=f,l.asBot=!0}else{d=e(s);let f=t(s);if(f)l.cookie=f}try{await Wg(d,l)}catch(f){console.error(ce(f)),process.exit(Xe)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(s)=>s.positional("query",{type:"string",describe:"Substring of the message text (case-insensitive)"}).option("channel",{type:"string",describe:"Channel/DM id (C\u2026/D\u2026) or the target as typed (#eng, @bob)"}).option("since",{type:"string",describe:"Only newer than this: 30m, 2h, 7d, 1w, or an ISO date"}).option("session",{type:"string",describe:"Agent session id (prefix match)"}).option("cwd",{type:"string",describe:"Working directory the sender ran in (prefix match)"}).option("kind",{type:"string",choices:["send","ask","poll","edit"],describe:"Only this kind of write"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per line (every recorded field)"}).option("count",{alias:"n",type:"number",default:50,describe:"Max rows (newest first)"}),(s)=>{let r;if(s.since!==void 0){if(r=Hl(String(s.since)),r===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${q(String(s.since))})`),process.exit(1)}let i={limit:Number(s.count)||50};if(s.query)i.text=String(s.query);if(s.channel)i.channel=String(s.channel);if(r!==void 0)i.sinceMs=r;if(s.session)i.session=String(s.session);if(s.cwd){let a=qh(String(s.cwd));try{i.cwd=zh(a)}catch{i.cwd=a}}if(s.kind)i.kind=s.kind;let c=Kl(i);if(!c)console.error(`Error: ${Zr}
393
+ (${Kn()})`),process.exit(1);if(s.json){for(let a of c)console.log(JSON.stringify(a));return}if(!c.length){console.error(`No sent messages match (log: ${Kn()}).`);return}for(let a of c)console.log(gg(a))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(s)=>s,async()=>{let s=ct();if(!s)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
394
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await Kg(s)}).command("schedule","Manage scheduled messages",(s)=>s.command("send <target> <message>","Schedule a message for later delivery",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("at",{type:"string",demandOption:!0,describe:"Delivery time (ISO datetime or Unix ts)"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Schedule via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. Without it a scheduled DM to yourself is posted by you, and Slack never notifies you of your own message \u2014 it fires into silence."}),async(r)=>{let i={target:r.target,message:r.message,at:r.at};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["user-id"])i.userId=r["user-id"],i.targetOverride=`--user-id ${r["user-id"]}`;let c;if(r["as-bot"]){let a=ro();if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await ft(e(r),i.target,t(r))}catch(l){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
393
395
  ${l instanceof Error?l.message:String(l)}
394
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}c=a,i.asBot=!0}else{c=e(r);let a=t(r);if(a)i.cookie=a}await $g(c,i)}).command(["ls","list"],"List pending scheduled messages",(r)=>r.positional("target",{type:"string",describe:"#channel to filter by"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"List what the BOT token scheduled. A message from `schedule send --as-bot` belongs to the app, so the user token's listing does not contain it \u2014 and an invisible pending message cannot be cancelled."}),async(r)=>{let i=r.target;if(r["as-bot"]){let c=oo(),a=r["channel-id"];if(!a&&i?.startsWith("@"))a=await Wu(i,c,e(r),t(r));await Uu(c,i,a);return}await Uu(e(r),i,r["channel-id"],t(r))}).command("rm <target> <id>","Delete a scheduled message",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#channel or @user"}).positional("id",{type:"string",demandOption:!0,describe:"Scheduled message ID"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Cancel a message scheduled with `schedule send --as-bot`. It belongs to the bot token, so the user token cannot delete it."}),async(r)=>{let i={target:r.target,id:r.id};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["as-bot"]){let a=oo();if(!i.channelId&&i.target.startsWith("@"))i.channelId=await Wu(i.target,a,e(r),t(r));i.asBot=!0,await Ku(a,i);return}let c=t(r);if(c)i.cookie=c;await Ku(e(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("newText",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm edit"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens in the new text to real <@USERID> mentions (on by default). Unresolved handles stay as plain text. Disable with --no-mentions for literal @text."}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED to correct a message the bot posted: Slack only lets a token edit its OWN messages, so a bot-authored message is uneditable by the user token and chat.update returns cant_update_message. Address it by permalink or --channel-id; an @user target resolves against the BOT's DM list, which is where a bot-authored DM actually lives."}),async(s)=>{let r={target:s.target,newText:s.newText,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s.mentions!==!1)r.mentions=!0;let i;if(s["as-bot"]){let c=await Nu(r.target,e(s),t(s),r.channelId);if(i=c.botToken,c.channelId&&!r.channelId)r.channelId=c.channelId;r.asBot=!0,r.mentionToken=e(s);let a=t(s);if(a)r.mentionCookie=a}else{i=e(s);let c=t(s);if(c)r.cookie=c}await Qh(i,r)}).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).option("code",{type:"string",describe:"Safety hash to confirm delete"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Delete as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED for a message the bot posted: chat.delete refuses another token's message exactly as chat.update does."}),async(s)=>{let r={target:s.target};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];let i;if(s["as-bot"]){let c=await Nu(r.target,e(s),t(s),r.channelId);if(i=c.botToken,c.channelId&&!r.channelId)r.channelId=c.channelId;r.asBot=!0}else{i=e(s);let c=t(s);if(c)r.cookie=c}await eg(i,r)}).command("pinlog","Pinned status board: the pinned top-level message is the current state (edited in place, silent); each change is one thread reply (the log, notifies)",(s)=>{let r={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},i=async(a)=>{if(a["as-bot"]){let u=oo();if(typeof a.workspace==="string"){let d=t(a),[f,h]=await Promise.all([Xs(e(a),d),Xs(u)]);if(f.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${a.workspace} is ${f.url}.
395
- Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(a);return{token:e(a),...l?{cookie:l}:{},asBot:!1}},c=(a)=>{console.error(me(a)),process.exit(1)};return s.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"#chan or channel ID"}).positional("state",{type:"string",describe:"The whole state (\\n for newlines), or use --file"}).positional("reason",{type:"string",describe:"Optional: why the board exists \u2014 its first thread reply"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <channel> is the reason"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(a)=>{let l=a.file!==void 0;if(l&&a.state!==void 0&&a.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let u=l?so(void 0,a.file):so(a.state,void 0),d=l?a.state:a.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let f=await i(a),h={target:a.channel,state:u,asBot:f.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(d!==void 0)h.log=qe(d);if(f.cookie)h.cookie=f.cookie;if(typeof a.workspace==="string")h.workspace=a.workspace;if(a.code)h.code=a.code;await ng(f.token,h).catch(c)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("state",{type:"string",describe:"The WHOLE new state, not a diff (or --file)"}).positional("reason",{type:"string",describe:"One short line: what changed and why (required)"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <board> is the reason"}).option("adopt",{type:"boolean",default:!1,describe:"Allow a message WITHOUT the pinlog footer: turn a hand-run board into one"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(a)=>{let l=a.file!==void 0;if(l&&a.state!==void 0&&a.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let u=l?so(void 0,a.file):so(a.state,void 0),d=l?a.state:a.reason;if(u===void 0||d===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let f=await i(a),h={target:a.board,state:u,log:qe(d),adopt:a.adopt,asBot:f.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(typeof a.workspace==="string")h.workspace=a.workspace;if(f.cookie)h.cookie=f.cookie;if(a.code)h.code=a.code;await Mu(f.token,h).catch(c)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("reason",{type:"string",demandOption:!0,describe:"One short line, e.g. still blocked \u2014 chased X"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r),async(a)=>{let l=await i(a),u={target:a.board,log:qe(a.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(typeof a.workspace==="string")u.workspace=a.workspace;if(l.cookie)u.cookie=l.cookie;if(a.code)u.code=a.code;await Mu(l.token,u).catch(c)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or C\u2026:ts"}).option("json",{type:"boolean",default:!1,describe:"One JSON object: {id, isPinlog, updated, head, log[]}"}).option("as-bot",r),async(a)=>{let l=await i(a);await rg(l.token,a.board,l.cookie,a.json).catch(c)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(a)=>a.positional("channel",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:500,describe:"How many recent channel messages to scan"}).option("as-bot",r),async(a)=>{let l=await i(a);await ig(l.token,a.channel,a.limit,l.cookie).catch(c)}).command("pin <board>",!1,(a)=>a.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(a)=>{let l=await i(a);await ag(l.token,a.board,l.cookie).catch(c)}).demandCommand(1,"Pick one: ls | get | new | set | note")},()=>{}).command("react <target> <emoji>","Add (or --remove) an emoji reaction \u2014 a lightweight ack that doesn't grow the thread",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(s)=>{let r={target:s.target,emoji:s.emoji};if(s.remove)r.remove=!0;if(s["channel-id"])r.channelId=s["channel-id"];let i=t(s);if(i)r.cookie=i;try{await cg(e(s),r)}catch(c){console.error(me(c)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)si(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(r)=>r.options(n).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(r)=>{await o(r,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,state:r.state};if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await Uh(e(r),i)}catch(a){console.error(me(a)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,flag:r.flag};if(r.remove)i.remove=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await Kh(e(r),i)}catch(a){console.error(me(a)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(r)=>r.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:ni,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={channel:r.in,limit:r.limit};if(r.fix)i.fix=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;await Jh(e(r),i)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)si(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(r)=>r.options(n),async(r)=>{await o(r,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}),async(s)=>{let r={target:s.target,filePaths:s.file};if(s.title)r.title=s.title;if(s.comment)r.comment=s.comment;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];let i=t(s);if(i)r.cookie=i;await Ag(e(s),r)}).command("files","File commands",(s)=>s.command(["ls","list"],"List files visible to you (files.list)",(r)=>r.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{let i={limit:r.limit,format:r.json?"jsonl":r.format};if(r.type)i.types=r.type;if(r.channel)i.channel=r.channel;if(r.user)i.user=r.user;await Tg(e(r),t(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(s)=>s.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}),async(s)=>{let r=s.json?"jsonl":s.format;try{await Pg(e(s),t(s),s.ref,{limit:s.limit,format:r})}catch(i){console.error(me(i)),process.exit(1)}}).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(s)=>s.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(s)=>{await Ng(e(s),t(s),s.ref,s.dest)}).command("dump","Bulk export channel history as markdown",(s)=>s.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(s)=>{await Hh(e(s),s.days,s.limit,s.filter)}).command("drafts","Manage message drafts (requires xoxc desktop token)",(s)=>s.command(["$0","ls","list"],"List pending drafts",(r)=>r.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(r)=>{await qh(e(r),t(r),r.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(r)=>r.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}),async(r)=>{let i=e(r),c=t(r),a=r.text.join(" ");if(!a)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);let l=await pe(i,r.channel,c),u=await tu(i,l,a,c);console.log(`\u2713 Draft created (id: ${O(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await Gh(e(r),t(r),r.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}),async(r)=>{let i=e(r),c=t(r),a=r.text.join(" ");if(!a)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);let l=await Yn(i,c),u=Y(l.drafts).map(O).find((p)=>String(p.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=ao(u),f=await yn(i,c),h=xe(d,a,f?.userId??"");if(r.code!==h)Fe(r.code,h,["--- Editing draft as -------------------------",Se(f),"--- Current draft ----------------------------",...d.split(`
396
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}c=a,i.asBot=!0}else{c=e(r);let a=t(r);if(a)i.cookie=a}await qg(c,i)}).command(["ls","list"],"List pending scheduled messages",(r)=>r.positional("target",{type:"string",describe:"#channel to filter by"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"List what the BOT token scheduled. A message from `schedule send --as-bot` belongs to the app, so the user token's listing does not contain it \u2014 and an invisible pending message cannot be cancelled."}),async(r)=>{let i=r.target;if(r["as-bot"]){let c=ro(),a=r["channel-id"];if(!a&&i?.startsWith("@"))a=await rd(i,c,e(r),t(r));await id(c,i,a);return}await id(e(r),i,r["channel-id"],t(r))}).command("rm <target> <id>","Delete a scheduled message",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#channel or @user"}).positional("id",{type:"string",demandOption:!0,describe:"Scheduled message ID"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Cancel a message scheduled with `schedule send --as-bot`. It belongs to the bot token, so the user token cannot delete it."}),async(r)=>{let i={target:r.target,id:r.id};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["as-bot"]){let a=ro();if(!i.channelId&&i.target.startsWith("@"))i.channelId=await rd(i.target,a,e(r),t(r));i.asBot=!0,await ad(a,i);return}let c=t(r);if(c)i.cookie=c;await ad(e(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("newText",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm edit"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens in the new text to real <@USERID> mentions (on by default). Unresolved handles stay as plain text. Disable with --no-mentions for literal @text."}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED to correct a message the bot posted: Slack only lets a token edit its OWN messages, so a bot-authored message is uneditable by the user token and chat.update returns cant_update_message. Address it by permalink or --channel-id; an @user target resolves against the BOT's DM list, which is where a bot-authored DM actually lives."}),async(s)=>{let r={target:s.target,newText:s.newText,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s.mentions!==!1)r.mentions=!0;let i;if(s["as-bot"]){let c=await Qu(r.target,e(s),t(s),r.channelId);if(i=c.botToken,c.channelId&&!r.channelId)r.channelId=c.channelId;r.asBot=!0,r.mentionToken=e(s);let a=t(s);if(a)r.mentionCookie=a}else{i=e(s);let c=t(s);if(c)r.cookie=c}await yg(i,r)}).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).option("code",{type:"string",describe:"Safety hash to confirm delete"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Delete as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED for a message the bot posted: chat.delete refuses another token's message exactly as chat.update does."}),async(s)=>{let r={target:s.target};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];let i;if(s["as-bot"]){let c=await Qu(r.target,e(s),t(s),r.channelId);if(i=c.botToken,c.channelId&&!r.channelId)r.channelId=c.channelId;r.asBot=!0}else{i=e(s);let c=t(s);if(c)r.cookie=c}await wg(i,r)}).command("pinlog","Pinned status board: the pinned top-level message is the current state (edited in place, silent); each change is one thread reply (the log, notifies)",(s)=>{let r={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},i=async(a)=>{if(a["as-bot"]){let u=ro();if(typeof a.workspace==="string"){let d=t(a),[f,h]=await Promise.all([zn(e(a),d),zn(u)]);if(f.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${a.workspace} is ${f.url}.
397
+ Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(a);return{token:e(a),...l?{cookie:l}:{},asBot:!1}},c=(a)=>{console.error(ce(a)),process.exit(1)};return s.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"#chan or channel ID"}).positional("state",{type:"string",describe:"The whole state (\\n for newlines), or use --file"}).positional("reason",{type:"string",describe:"Optional: why the board exists \u2014 its first thread reply"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <channel> is the reason"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(a)=>{let l=a.file!==void 0;if(l&&a.state!==void 0&&a.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let u=l?oo(void 0,a.file):oo(a.state,void 0),d=l?a.state:a.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let f=await i(a),h={target:a.channel,state:u,asBot:f.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(d!==void 0)h.log=qe(d);if(f.cookie)h.cookie=f.cookie;if(typeof a.workspace==="string")h.workspace=a.workspace;if(a.code)h.code=a.code;await kg(f.token,h).catch(c)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("state",{type:"string",describe:"The WHOLE new state, not a diff (or --file)"}).positional("reason",{type:"string",describe:"One short line: what changed and why (required)"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <board> is the reason"}).option("adopt",{type:"boolean",default:!1,describe:"Allow a message WITHOUT the pinlog footer: turn a hand-run board into one"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(a)=>{let l=a.file!==void 0;if(l&&a.state!==void 0&&a.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let u=l?oo(void 0,a.file):oo(a.state,void 0),d=l?a.state:a.reason;if(u===void 0||d===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let f=await i(a),h={target:a.board,state:u,log:qe(d),adopt:a.adopt,asBot:f.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(typeof a.workspace==="string")h.workspace=a.workspace;if(f.cookie)h.cookie=f.cookie;if(a.code)h.code=a.code;await td(f.token,h).catch(c)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("reason",{type:"string",demandOption:!0,describe:"One short line, e.g. still blocked \u2014 chased X"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r),async(a)=>{let l=await i(a),u={target:a.board,log:qe(a.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(typeof a.workspace==="string")u.workspace=a.workspace;if(l.cookie)u.cookie=l.cookie;if(a.code)u.code=a.code;await td(l.token,u).catch(c)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or C\u2026:ts"}).option("json",{type:"boolean",default:!1,describe:"One JSON object: {id, isPinlog, updated, head, log[]}"}).option("as-bot",r),async(a)=>{let l=await i(a);await Eg(l.token,a.board,l.cookie,a.json).catch(c)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(a)=>a.positional("channel",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:500,describe:"How many recent channel messages to scan"}).option("as-bot",r),async(a)=>{let l=await i(a);await Sg(l.token,a.channel,a.limit,l.cookie).catch(c)}).command("pin <board>",!1,(a)=>a.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(a)=>{let l=await i(a);await Fg(l.token,a.board,l.cookie).catch(c)}).demandCommand(1,"Pick one: ls | get | new | set | note")},()=>{}).command("react <target> <emoji>","Add (or --remove) an emoji reaction \u2014 a lightweight ack that doesn't grow the thread",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(s)=>{let r={target:s.target,emoji:s.emoji};if(s.remove)r.remove=!0;if(s["channel-id"])r.channelId=s["channel-id"];let i=t(s);if(i)r.cookie=i;try{await _g(e(s),r)}catch(c){console.error(ce(c)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)fi(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(r)=>r.options(n).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(r)=>{await o(r,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,state:r.state};if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await ag(e(r),i)}catch(a){console.error(ce(a)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,flag:r.flag};if(r.remove)i.remove=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await cg(e(r),i)}catch(a){console.error(ce(a)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(r)=>r.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:di,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={channel:r.in,limit:r.limit};if(r.fix)i.fix=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;await lg(e(r),i)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)fi(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(r)=>r.options(n),async(r)=>{await o(r,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}),async(s)=>{let r={target:s.target,filePaths:s.file};if(s.title)r.title=s.title;if(s.comment)r.comment=s.comment;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];let i=t(s);if(i)r.cookie=i;await Gg(e(s),r)}).command("files","File commands",(s)=>s.command(["ls","list"],"List files visible to you (files.list)",(r)=>r.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{let i={limit:r.limit,format:r.json?"jsonl":r.format};if(r.type)i.types=r.type;if(r.channel)i.channel=r.channel;if(r.user)i.user=r.user;await Xg(e(r),t(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(s)=>s.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"List name"}).option("col",{type:"string",array:!0,default:[],describe:"Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable"}).option("todo",{type:"boolean",default:!1,describe:"Todo mode: adds Completed / Assignee / Due date columns"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{try{let i={name:r.name,cols:r.col,todo:r.todo===!0};if(r.code!==void 0)i.code=r.code;await Qg(i)}catch(i){console.error(ce(i)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("text",{type:"string",demandOption:!0,describe:"Primary (first text) column value"}).option("set",{type:"string",array:!0,default:[],describe:"Other cells: column=value (repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm add"}),async(r)=>{try{let i={list:r.list,text:r.text,sets:r.set};if(r.code!==void 0)i.code=r.code;await em(i)}catch(i){console.error(ce(i)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("row",{type:"string",demandOption:!0,describe:"Row id (Rec\u2026), as printed by lists add / lists <ref>"}).option("set",{type:"string",array:!0,default:[],describe:"column=value (repeatable)"}).option("done",{type:"boolean",describe:"Check the row off (--no-done to uncheck); needs a todo-mode list"}).option("code",{type:"string",describe:"Safety hash to confirm update"}),async(r)=>{try{let i={list:r.list,row:r.row,sets:r.set};if(r.done!==void 0)i.done=r.done;if(r.code!==void 0)i.code=r.code;await tm(i)}catch(i){console.error(ce(i)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).option("user",{type:"string",array:!0,default:[],describe:"User ID (U\u2026), repeatable"}).option("channel",{type:"string",array:!0,default:[],describe:"Channel ID (C\u2026), repeatable"}).option("level",{type:"string",choices:["read","write","owner"],default:"write"}).option("code",{type:"string",describe:"Safety hash to confirm share"}),async(r)=>{try{let i={list:r.list,users:r.user,channels:r.channel,level:r.level};if(r.code!==void 0)i.code=r.code;await nm(i)}catch(i){console.error(ce(i)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(r)=>r.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}).option("as-bot",{type:"boolean",default:!1,describe:"Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session"}),async(r)=>{let i=r.json?"jsonl":r.format;try{let c=r.asBot===!0;await Vg(c?"":e(r),c?void 0:t(r),r.ref,{limit:r.limit,format:i,asBot:c})}catch(c){console.error(ce(c)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(s)=>s.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(s)=>{await om(e(s),t(s),s.ref,s.dest)}).command("dump","Bulk export channel history as markdown",(s)=>s.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(s)=>{await ug(e(s),s.days,s.limit,s.filter)}).command("drafts","Manage message drafts (requires xoxc desktop token)",(s)=>s.command(["$0","ls","list"],"List pending drafts",(r)=>r.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(r)=>{await fg(e(r),t(r),r.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(r)=>r.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}),async(r)=>{let i=e(r),c=t(r),a=r.text.join(" ");if(!a)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);let l=await he(i,r.channel,c),u=await wu(i,l,a,c);console.log(`\u2713 Draft created (id: ${I(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await pg(e(r),t(r),r.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}),async(r)=>{let i=e(r),c=t(r),a=r.text.join(" ");if(!a)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);let l=await Vn(i,c),u=Y(l.drafts).map(I).find((p)=>String(p.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=co(u),f=await rt(i,c),h=De(d,a,f?.userId??"");if(r.code!==h)ye(r.code,h,["--- Editing draft as -------------------------",we(f),"--- Current draft ----------------------------",...d.split(`
396
398
  `).map((p)=>` ${p}`),"--- Replacing with ---------------------------",...a.split(`
397
- `).map((p)=>` ${p}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m=await nu(i,r.id,yi(u),a,c);console.log(`\u2713 Draft updated (id: ${O(m.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(r)=>{let i=e(r),c=t(r),a=await Yn(i,c),l=Y(a.drafts).map(O).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=ao(l),d=await yn(i,c),f=xe(r.id,u,d?.userId??"");if(r.code!==f)Fe(r.code,f,["\u2500-- Deleting draft \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",Se(d),` id: ${r.id}`,...u.split(`
398
- `).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await ou(i,r.id,c),console.log(`\u2713 Draft deleted (id: ${r.id})`)})).command("auth","Authentication and workspace management",(s)=>s.command("token","Print the active token (or save one with --token)",(r)=>r.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(r)=>{if(r.token===void 0){console.log(An(r.workspace));return}await Uc({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(r)=>{let i=An(r.workspace),c=i.startsWith("xoxc-")?Qo(r.workspace):void 0,a=[["SLACK_TOKEN",i]];if(c)a.push(["SLACK_COOKIE",c]);let l=a.map(([u,d])=>{if(/[\r\n\0']/.test(d))throw Error(`Cannot export ${u}: unsupported characters in credential`);return`${u}='${d}'`});console.log(l.join(`
399
- `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(r)=>r.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(r)=>{await Kc({...r.bot!==void 0?{bot:r.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(r)=>r.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(i)=>i.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(i)=>{await $r({...i.profile!==void 0?{profile:i.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(i)=>i.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(i)=>{await Ar({...i.workspace!==void 0?{workspace:i.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(i)=>{await Wn({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{},yes:i.yes,fromDesktop:i.fromDesktop,fromChrome:i.fromChrome,fromFirefox:i.fromFirefox,fromAll:i.fromAll})}),async(r)=>{await Wn({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{},yes:r.yes,fromDesktop:r.fromDesktop,fromChrome:r.fromChrome,fromFirefox:r.fromFirefox,fromAll:r.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>Jc({...r.workspace!==void 0?{workspace:r.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(r)=>r.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>Hc({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=Zo();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:c,current:a}of r)console.log(`${a?"* ":" "}${i} ${c.team} (${c.user}) ${c.url??""}`)}).command("use <name>","Switch active workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(r)=>{if(!r.g)Ah(xt(process.cwd(),".slack-cli"));lc(r.name,r.g),console.log(`Switched to workspace "${r.name}" ${r.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}),(r)=>{cc(r.name),console.log(`Removed workspace "${r.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await Wc({...r.workspace!==void 0?{workspace:r.workspace}:{},...r.profile!==void 0?{profile:r.profile}:{},yes:r.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await Ar({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("tail [target]","Stream new messages in real time (like tail -f)",(s)=>s.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(s)=>{let r=e(s),i=t(s),c=new AbortController;process.on("SIGINT",()=>{c.abort(),process.exit(0)}),await Zc(r,s.target,{...s.since!==void 0?{since:s.since}:{},...s.thread!==void 0?{thread:s.thread}:{},...s["watch-thread"]!==void 0?{watchThread:s["watch-thread"]}:{},me:s.me,interval:s.interval,...s.timeout!==void 0?{timeout:s.timeout}:{},...s["exit-on-message"]===!0?{exitOnMessage:!0}:{},...i!==void 0?{cookie:i}:{},...s.rtm===!1?{noRtm:!0}:{}},c.signal)}).command("login",!1,(s)=>s.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(s)=>{await Wn({...s.token!==void 0?{token:s.token}:{},...s.name!==void 0?{name:s.name}:{},yes:s.yes,fromDesktop:s.fromDesktop,fromChrome:s.fromChrome,fromFirefox:s.fromFirefox,fromAll:s.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}Bg().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
399
+ `).map((p)=>` ${p}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m=await bu(i,r.id,_i(u),a,c);console.log(`\u2713 Draft updated (id: ${I(m.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(r)=>{let i=e(r),c=t(r),a=await Vn(i,c),l=Y(a.drafts).map(I).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=co(l),d=await rt(i,c),f=De(r.id,u,d?.userId??"");if(r.code!==f)ye(r.code,f,["\u2500-- Deleting draft \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",we(d),` id: ${r.id}`,...u.split(`
400
+ `).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await xu(i,r.id,c),console.log(`\u2713 Draft deleted (id: ${r.id})`)})).command("auth","Authentication and workspace management",(s)=>s.command("token","Print the active token (or save one with --token)",(r)=>r.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(r)=>{if(r.token===void 0){console.log(An(r.workspace));return}await Vc({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(r)=>{let i=An(r.workspace),c=i.startsWith("xoxc-")?sr(r.workspace):void 0,a=[["SLACK_TOKEN",i]];if(c)a.push(["SLACK_COOKIE",c]);let l=a.map(([u,d])=>{if(/[\r\n\0']/.test(d))throw Error(`Cannot export ${u}: unsupported characters in credential`);return`${u}='${d}'`});console.log(l.join(`
401
+ `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(r)=>r.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(r)=>{await Zc({...r.bot!==void 0?{bot:r.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(r)=>r.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(i)=>i.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(i)=>{await Or({...i.profile!==void 0?{profile:i.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(i)=>i.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(i)=>{await Pr({...i.workspace!==void 0?{workspace:i.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(i)=>{await Wn({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{},yes:i.yes,fromDesktop:i.fromDesktop,fromChrome:i.fromChrome,fromFirefox:i.fromFirefox,fromAll:i.fromAll})}),async(r)=>{await Wn({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{},yes:r.yes,fromDesktop:r.fromDesktop,fromChrome:r.fromChrome,fromFirefox:r.fromFirefox,fromAll:r.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>Qc({...r.workspace!==void 0?{workspace:r.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(r)=>r.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>el({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=nr();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:c,current:a}of r)console.log(`${a?"* ":" "}${i} ${c.team} (${c.user}) ${c.url??""}`)}).command("use <name>","Switch active workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(r)=>{if(!r.g)Gh(St(process.cwd(),".slack-cli"));yc(r.name,r.g),console.log(`Switched to workspace "${r.name}" ${r.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}),(r)=>{Dc(r.name),console.log(`Removed workspace "${r.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await Yc({...r.workspace!==void 0?{workspace:r.workspace}:{},...r.profile!==void 0?{profile:r.profile}:{},yes:r.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await Pr({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("tail [target]","Stream new messages in real time (like tail -f)",(s)=>s.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(s)=>{let r=e(s),i=t(s),c=new AbortController;process.on("SIGINT",()=>{c.abort(),process.exit(0)}),await al(r,s.target,{...s.since!==void 0?{since:s.since}:{},...s.thread!==void 0?{thread:s.thread}:{},...s["watch-thread"]!==void 0?{watchThread:s["watch-thread"]}:{},me:s.me,interval:s.interval,...s.timeout!==void 0?{timeout:s.timeout}:{},...s["exit-on-message"]===!0?{exitOnMessage:!0}:{},...i!==void 0?{cookie:i}:{},...s.rtm===!1?{noRtm:!0}:{}},c.signal)}).command("login",!1,(s)=>s.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(s)=>{await Wn({...s.token!==void 0?{token:s.token}:{},...s.name!==void 0?{name:s.name}:{},yes:s.yes,fromDesktop:s.fromDesktop,fromChrome:s.fromChrome,fromFirefox:s.fromFirefox,fromAll:s.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}rm().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});