slack-term 1.45.0 → 1.47.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 Tp}from"node:module";var Ep=Object.create;var{getPrototypeOf:_p,defineProperty:Ma,getOwnPropertyNames:Cp}=Object;var Na=Object.prototype.hasOwnProperty;function $p(e){return this[e]}var Ap,Fp,Ba=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?Ap??=new WeakMap:Fp??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?Ep(_p(e)):{};let i=t||!e||!e.__esModule||!Na.call(e,"default")?Ma(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Cp(e))if(!Na.call(i,a))Ma(i,a,{get:$p.bind(e,a),enumerable:!0})}if(o)s.set(e,i);return i};var ja=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Yn=Tp(import.meta.url);var oc=ja(function(_b,sc){sc.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 Tc=ja(function(pD,Fc){Fc.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 ep}from"crypto";import{existsSync as tp,readFileSync as np,mkdirSync as Oy,realpathSync as vy,writeFileSync as sp}from"fs";import{homedir as Ca}from"os";import{join as Dt,resolve as Ly}from"path";import{notStrictEqual as gh,strictEqual as mh}from"assert";var Rp={right:Op,center:vp};class Ua{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 Up}from"node:module";var Lp=Object.create;var{getPrototypeOf:Mp,defineProperty:Ha,getOwnPropertyNames:Np}=Object;var za=Object.prototype.hasOwnProperty;function Bp(e){return this[e]}var jp,Wp,Xa=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?jp??=new WeakMap:Wp??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?Lp(Mp(e)):{};let i=t||!e||!e.__esModule||!za.call(e,"default")?Ha(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Np(e))if(!za.call(i,a))Ha(i,a,{get:Bp.bind(e,a),enumerable:!0})}if(o)s.set(e,i);return i};var Ga=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Zn=Up(import.meta.url);var pc=Ga(function(Jb,fc){fc.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 Bc=Ga(function(RD,Nc){Nc.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 up}from"crypto";import{existsSync as dp,readFileSync as fp,mkdirSync as Vy,realpathSync as Zy,writeFileSync as pp}from"fs";import{homedir as La}from"os";import{join as kt,resolve as Qy}from"path";import{notStrictEqual as Ch,strictEqual as Ah}from"assert";var Jp={right:Hp,center:zp};class Va{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&&Ye.stringWidth(o[0])>n)n=Math.min(Math.floor(this.width*0.5),Ye.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=Ye.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:a}=e[i],c=this.negatePadding(e[i]),l=r;if(c>Ye.stringWidth(r))l+=" ".repeat(c-Ye.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Rp[e[i].align];if(l=d(l,c),Ye.stringWidth(l)<c)l+=" ".repeat((a||0)-Ye.stringWidth(l)-1)}let u=e[i].padding||[0,0,0,0];if(u[3])s+=" ".repeat(u[3]);if(s+=Wa(e[i],l,"| "),s+=l,s+=Wa(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=Ye.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=Ye.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:a}=e[i],c=this.negatePadding(e[i]),l=r;if(c>Ye.stringWidth(r))l+=" ".repeat(c-Ye.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Jp[e[i].align];if(l=d(l,c),Ye.stringWidth(l)<c)l+=" ".repeat((a||0)-Ye.stringWidth(l)-1)}let u=e[i].padding||[0,0,0,0];if(u[3])s+=" ".repeat(u[3]);if(s+=Ya(e[i],l,"| "),s+=l,s+=Ya(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=Ye.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=Ye.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,a)=>{if(!t[a])t.push([]);let c=t[a];for(let l=0;l<r;l++)if(c[l]===void 0)c.push("");c.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||Ye.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,Ip(e[i]));return r})}}function Wa(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Ip(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Pp(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Op(e,t){e=e.trim();let n=Ye.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function vp(e,t){e=e.trim();let n=Ye.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Ye;function Ka(e,t){return Ye=t,new Ua({width:(e===null||e===void 0?void 0:e.width)||Pp(),wrap:e===null||e===void 0?void 0:e.wrap})}function hr({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 Lp=hr();function tn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(Lp,"")}var Ja=161,qa=1114109,Ha=[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],za=12288,Xa=65510,Ga=[12288,12288,65281,65376,65504,65510];var Ya=4352,Va=262141,gr=[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 Ns=(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 Za=19968,[Mp,Np]=Bp(gr);function Bp(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(Za>=s&&Za<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var Qa=(e)=>{if(e<Ja||e>qa)return!1;return Ns(Ha,e)},ec=(e)=>{if(e<za||e>Xa)return!1;return Ns(Ga,e)};var tc=(e)=>{if(e>=Mp&&e<=Np)return!0;if(e<Ya||e>Va)return!1;return Ns(gr,e)};function jp(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function nc(e,{ambiguousAsWide:t=!1}={}){if(jp(e),ec(e)||tc(e)||t&&Qa(e))return 2;return 1}var rc=Ba(oc(),1),Wp=new Intl.Segmenter,Up=/^\p{Default_Ignorable_Code_Point}$/u;function lt(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=tn(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of Wp.segment(e)){let a=i.codePointAt(0);if(a<=31||a>=127&&a<=159)continue;if(a>=8203&&a<=8207||a===65279)continue;if(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)continue;if(a>=55296&&a<=57343)continue;if(a>=65024&&a<=65039)continue;if(Up.test(i))continue;if(rc.default().test(i)){s+=2;continue}s+=nc(a,r)}return s}var ic=(e=0)=>(t)=>`\x1B[${t+e}m`,ac=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,cc=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,De={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]}},Fb=Object.keys(De.modifier),Kp=Object.keys(De.color),Jp=Object.keys(De.bgColor),Tb=[...Kp,...Jp];function qp(){let e=new Map;for(let[t,n]of Object.entries(De)){for(let[o,s]of Object.entries(n))De[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=De[o],e.set(s[0],s[1]);Object.defineProperty(De,t,{value:n,enumerable:!1})}return Object.defineProperty(De,"codes",{value:e,enumerable:!1}),De.color.close="\x1B[39m",De.bgColor.close="\x1B[49m",De.color.ansi=ic(),De.color.ansi256=ac(),De.color.ansi16m=cc(),De.bgColor.ansi=ic(10),De.bgColor.ansi256=ac(10),De.bgColor.ansi16m=cc(10),Object.defineProperties(De,{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)=>De.rgbToAnsi256(...De.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 a=t%36;n=Math.floor(t/36)/5,o=Math.floor(a/6)/5,s=a%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)=>De.ansi256ToAnsi(De.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>De.ansi256ToAnsi(De.hexToAnsi256(t)),enumerable:!1}}),De}var Hp=qp(),lc=Hp;var js=new Set(["\x1B","›"]),zp=39,yr="\x07",fc="[",Xp="]",pc="m",Bs=`${Xp}8;;`,uc=(e)=>`${js.values().next().value}${fc}${e}${pc}`,dc=(e)=>`${js.values().next().value}${Bs}${e}${yr}`,Gp=(e)=>e.split(" ").map((t)=>lt(t)),mr=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=lt(tn(e.at(-1)));for(let[a,c]of o.entries()){let l=lt(c);if(i+l<=n)e[e.length-1]+=c;else e.push(c),i=0;if(js.has(c))s=!0,r=o.slice(a+1,a+1+Bs.length).join("")===Bs;if(s){if(r){if(c===yr)s=!1,r=!1}else if(c===pc)s=!1;continue}if(i+=l,i===n&&a<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},Yp=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(lt(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Vp=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=Gp(e),a=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)a[a.length-1]=a.at(-1).trimStart();let h=lt(a.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),h=0;if(h>0||n.trim===!1)a[a.length-1]+=" ",h++}if(n.hard&&i[d]>t){let g=t-h,p=1+Math.floor((i[d]-g-1)/t);if(Math.floor((i[d]-1)/t)<p)a.push("");mr(a,f,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){mr(a,f,t);continue}a.push("")}if(h+i[d]>t&&n.wordWrap===!1){mr(a,f,t);continue}a[a.length-1]+=f}if(n.trim!==!1)a=a.map((d)=>Yp(d));let c=a.join(`
8
- `),l=[...c],u=0;for(let[d,f]of l.entries()){if(o+=f,js.has(f)){let{groups:g}=new RegExp(`(?:\\${fc}(?<code>\\d+)m|\\${Bs}(?<uri>.*)${yr})`).exec(c.slice(u))||{groups:{}};if(g.code!==void 0){let p=Number.parseFloat(g.code);s=p===zp?void 0:p}else if(g.uri!==void 0)r=g.uri.length===0?void 0:g.uri}let h=lc.codes.get(Number(s));if(l[d+1]===`
9
- `){if(r)o+=dc("");if(s&&h)o+=uc(h)}else if(f===`
10
- `){if(s&&h)o+=uc(s);if(r)o+=dc(r)}u+=f.length}return o};function wr(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,a)=>{if(!t[a])t.push([]);let c=t[a];for(let l=0;l<r;l++)if(c[l]===void 0)c.push("");c.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||Ye.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,Kp(e[i]));return r})}}function Ya(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Kp(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function qp(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Hp(e,t){e=e.trim();let n=Ye.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function zp(e,t){e=e.trim();let n=Ye.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Ye;function Za(e,t){return Ye=t,new Va({width:(e===null||e===void 0?void 0:e.width)||qp(),wrap:e===null||e===void 0?void 0:e.wrap})}function wr({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 Xp=wr();function tn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(Xp,"")}var Qa=161,ec=1114109,tc=[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],nc=12288,sc=65510,oc=[12288,12288,65281,65376,65504,65510];var rc=4352,ic=262141,br=[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 js=(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 ac=19968,[Gp,Yp]=Vp(br);function Vp(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(ac>=s&&ac<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var cc=(e)=>{if(e<Qa||e>ec)return!1;return js(tc,e)},lc=(e)=>{if(e<nc||e>sc)return!1;return js(oc,e)};var uc=(e)=>{if(e>=Gp&&e<=Yp)return!0;if(e<rc||e>ic)return!1;return js(br,e)};function Zp(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function dc(e,{ambiguousAsWide:t=!1}={}){if(Zp(e),lc(e)||uc(e)||t&&cc(e))return 2;return 1}var hc=Xa(pc(),1),Qp=new Intl.Segmenter,eh=/^\p{Default_Ignorable_Code_Point}$/u;function lt(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=tn(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of Qp.segment(e)){let a=i.codePointAt(0);if(a<=31||a>=127&&a<=159)continue;if(a>=8203&&a<=8207||a===65279)continue;if(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)continue;if(a>=55296&&a<=57343)continue;if(a>=65024&&a<=65039)continue;if(eh.test(i))continue;if(hc.default().test(i)){s+=2;continue}s+=dc(a,r)}return s}var gc=(e=0)=>(t)=>`\x1B[${t+e}m`,mc=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,yc=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,De={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]}},zb=Object.keys(De.modifier),th=Object.keys(De.color),nh=Object.keys(De.bgColor),Xb=[...th,...nh];function sh(){let e=new Map;for(let[t,n]of Object.entries(De)){for(let[o,s]of Object.entries(n))De[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=De[o],e.set(s[0],s[1]);Object.defineProperty(De,t,{value:n,enumerable:!1})}return Object.defineProperty(De,"codes",{value:e,enumerable:!1}),De.color.close="\x1B[39m",De.bgColor.close="\x1B[49m",De.color.ansi=gc(),De.color.ansi256=mc(),De.color.ansi16m=yc(),De.bgColor.ansi=gc(10),De.bgColor.ansi256=mc(10),De.bgColor.ansi16m=yc(10),Object.defineProperties(De,{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)=>De.rgbToAnsi256(...De.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 a=t%36;n=Math.floor(t/36)/5,o=Math.floor(a/6)/5,s=a%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)=>De.ansi256ToAnsi(De.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>De.ansi256ToAnsi(De.hexToAnsi256(t)),enumerable:!1}}),De}var oh=sh(),wc=oh;var Us=new Set(["\x1B","›"]),rh=39,kr="\x07",kc="[",ih="]",xc="m",Ws=`${ih}8;;`,bc=(e)=>`${Us.values().next().value}${kc}${e}${xc}`,Dc=(e)=>`${Us.values().next().value}${Ws}${e}${kr}`,ah=(e)=>e.split(" ").map((t)=>lt(t)),Dr=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=lt(tn(e.at(-1)));for(let[a,c]of o.entries()){let l=lt(c);if(i+l<=n)e[e.length-1]+=c;else e.push(c),i=0;if(Us.has(c))s=!0,r=o.slice(a+1,a+1+Ws.length).join("")===Ws;if(s){if(r){if(c===kr)s=!1,r=!1}else if(c===xc)s=!1;continue}if(i+=l,i===n&&a<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},ch=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(lt(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},lh=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=ah(e),a=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)a[a.length-1]=a.at(-1).trimStart();let h=lt(a.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),h=0;if(h>0||n.trim===!1)a[a.length-1]+=" ",h++}if(n.hard&&i[d]>t){let g=t-h,p=1+Math.floor((i[d]-g-1)/t);if(Math.floor((i[d]-1)/t)<p)a.push("");Dr(a,f,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){Dr(a,f,t);continue}a.push("")}if(h+i[d]>t&&n.wordWrap===!1){Dr(a,f,t);continue}a[a.length-1]+=f}if(n.trim!==!1)a=a.map((d)=>ch(d));let c=a.join(`
8
+ `),l=[...c],u=0;for(let[d,f]of l.entries()){if(o+=f,Us.has(f)){let{groups:g}=new RegExp(`(?:\\${kc}(?<code>\\d+)m|\\${Ws}(?<uri>.*)${kr})`).exec(c.slice(u))||{groups:{}};if(g.code!==void 0){let p=Number.parseFloat(g.code);s=p===rh?void 0:p}else if(g.uri!==void 0)r=g.uri.length===0?void 0:g.uri}let h=wc.codes.get(Number(s));if(l[d+1]===`
9
+ `){if(r)o+=Dc("");if(s&&h)o+=bc(h)}else if(f===`
10
+ `){if(s&&h)o+=bc(s);if(r)o+=Dc(r)}u+=f.length}return o};function xr(e,t,n){return String(e).normalize().replaceAll(`\r
11
11
  `,`
12
12
  `).split(`
13
- `).map((o)=>Vp(o,t,n)).join(`
14
- `)}function br(e){return Ka(e,{stringWidth:lt,stripAnsi:tn,wrap:wr})}import{dirname as hc,resolve as gc}from"path";import{readdirSync as Zp,statSync as Qp}from"fs";function Dr(e,t){let n=gc(".",e),o;if(!Qp(n).isDirectory())n=hc(n);while(!0){if(o=t(n,Zp(n)),o)return gc(n,o);if(n=hc(o=n),o===n)break}}import{inspect as yh}from"util";import{fileURLToPath as Ic}from"url";import{format as nh}from"util";import{normalize as sh,resolve as oh}from"path";function nn(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 Ws(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 mc(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 nt;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(nt||(nt={}));var kt;class xr{constructor(e){kt=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=mc(e),s=typeof e==="string",r=eh(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),a=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",f=Object.create(null),h=Object.create(null),g=n.__||kt.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:[]},m=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,w=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(k){let _=typeof k==="object"?k.key:k,B=Object.keys(k).map(function(R){return{boolean:"bools",string:"strings",number:"numbers"}[R]}).filter(Boolean).pop();if(B)p[B][_]=!0;p.arrays[_]=!0,p.keys.push(_)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(k){p.bools[k]=!0,p.keys.push(k)}),[].concat(n.string||[]).filter(Boolean).forEach(function(k){p.strings[k]=!0,p.keys.push(k)}),[].concat(n.number||[]).filter(Boolean).forEach(function(k){p.numbers[k]=!0,p.keys.push(k)}),[].concat(n.count||[]).filter(Boolean).forEach(function(k){p.counts[k]=!0,p.keys.push(k)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(k){p.normalize[k]=!0,p.keys.push(k)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([k,_])=>{if(typeof _==="number")p.nargs[k]=_,p.keys.push(k)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([k,_])=>{if(typeof _==="function")p.coercions[k]=_,p.keys.push(k)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(k){p.configs[k]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([k,_])=>{if(typeof _==="boolean"||typeof _==="function")p.configs[k]=_})}ae(n.key,r,n.default,p.arrays),Object.keys(a).forEach(function(k){(p.aliases[k]||[]).forEach(function(_){a[_]=a[k]})});let b=null;pr();let D=[],S=Object.assign(Object.create(null),{_:[]}),F={};for(let k=0;k<o.length;k++){let _=o[k],B=_.replace(/^-{3,}/,"---"),R,E,Z,X,te,Ie;if(_!=="--"&&/^-/.test(_)&&oe(_))A(_);else if(B.match(/^---+(=|$)/)){A(_);continue}else if(_.match(/^--.+=/)||!i["short-option-groups"]&&_.match(/^-.+=/)){if(X=_.match(/^--?([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)if(j(X[1],p.arrays))k=x(k,X[1],o,X[2]);else if(j(X[1],p.nargs)!==!1)k=C(k,X[1],o,X[2]);else J(X[1],X[2],!0)}else if(_.match(w)&&i["boolean-negation"]){if(X=_.match(w),X!==null&&Array.isArray(X)&&X.length>=2)E=X[1],J(E,j(E,p.arrays)?[!1]:!1)}else if(_.match(/^--.+/)||!i["short-option-groups"]&&_.match(/^-[^-]+/)){if(X=_.match(/^--?(.+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(E=X[1],j(E,p.arrays))k=x(k,E,o);else if(j(E,p.nargs)!==!1)k=C(k,E,o);else if(te=o[k+1],te!==void 0&&(!te.match(/^-/)||te.match(m))&&!j(E,p.bools)&&!j(E,p.counts))J(E,te),k++;else if(/^(true|false)$/.test(te))J(E,te),k++;else J(E,M(E))}else if(_.match(/^-.\..+=/)){if(X=_.match(/^-([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)J(X[1],X[2])}else if(_.match(/^-.\..+/)&&!_.match(m)){if(te=o[k+1],X=_.match(/^-(.\..+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(E=X[1],te!==void 0&&!te.match(/^-/)&&!j(E,p.bools)&&!j(E,p.counts))J(E,te),k++;else J(E,M(E))}else if(_.match(/^-[^-]+/)&&!_.match(m)){Z=_.slice(1,-1).split(""),R=!1;for(let je=0;je<Z.length;je++){if(te=_.slice(je+2),Z[je+1]&&Z[je+1]==="="){if(Ie=_.slice(je+3),E=Z[je],j(E,p.arrays))k=x(k,E,o,Ie);else if(j(E,p.nargs)!==!1)k=C(k,E,o,Ie);else J(E,Ie);R=!0;break}if(te==="-"){J(Z[je],te);continue}if(/[A-Za-z]/.test(Z[je])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(te)&&j(te,p.bools)===!1){J(Z[je],te),R=!0;break}if(Z[je+1]&&Z[je+1].match(/\W/)){J(Z[je],te),R=!0;break}else J(Z[je],M(Z[je]))}if(E=_.slice(-1)[0],!R&&E!=="-")if(j(E,p.arrays))k=x(k,E,o);else if(j(E,p.nargs)!==!1)k=C(k,E,o);else if(te=o[k+1],te!==void 0&&(!/^(-|--)[^-]/.test(te)||te.match(m))&&!j(E,p.bools)&&!j(E,p.counts))J(E,te),k++;else if(/^(true|false)$/.test(te))J(E,te),k++;else J(E,M(E))}else if(_.match(/^-[0-9]$/)&&_.match(m)&&j(_.slice(1),p.bools))E=_.slice(1),J(E,M(E));else if(_==="--"){D=o.slice(k+1);break}else if(i["halt-at-non-option"]){D=o.slice(k);break}else A(_)}if(q(S,!0),q(S,!1),I(S),N(),le(S,p.aliases,a,!0),H(S),i["set-placeholder-key"])v(S);if(Object.keys(p.counts).forEach(function(k){if(!ee(S,k.split(".")))J(k,0)}),u&&D.length)S[d]=[];if(D.forEach(function(k){S[d].push(k)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(S).filter((k)=>k!=="--"&&k.includes("-")).forEach((k)=>{delete S[k]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((k)=>r[k])).forEach((k)=>{if(i["camel-case-expansion"]&&k.includes("-"))delete S[k.split(".").map((_)=>nn(_)).join(".")];delete S[k]});function A(k){let _=O("_",k);if(typeof _==="string"||typeof _==="number")S._.push(_)}function C(k,_,B,R){let E,Z=j(_,p.nargs);if(Z=typeof Z!=="number"||isNaN(Z)?1:Z,Z===0){if(!Ae(R))b=Error(g("Argument unexpected for: %s",_));return J(_,M(_)),k}let X=Ae(R)?0:1;if(i["nargs-eats-options"]){if(B.length-(k+1)+X<Z)b=Error(g("Not enough arguments following: %s",_));X=Z}else{for(E=k+1;E<B.length;E++)if(!B[E].match(/^-[^0-9]/)||B[E].match(m)||oe(B[E]))X++;else break;if(X<Z)b=Error(g("Not enough arguments following: %s",_))}let te=Math.min(X,Z);if(!Ae(R)&&te>0)J(_,R),te--;for(E=k+1;E<te+k+1;E++)J(_,B[E]);return k+te}function x(k,_,B,R){let E=[],Z=R||B[k+1],X=j(_,p.nargs);if(j(_,p.bools)&&!/^(true|false)$/.test(Z))E.push(!0);else if(Ae(Z)||Ae(R)&&/^-/.test(Z)&&!m.test(Z)&&!oe(Z)){if(a[_]!==void 0){let te=a[_];E=Array.isArray(te)?te:[te]}}else{if(!Ae(R))E.push(L(_,R,!0));for(let te=k+1;te<B.length;te++){if(!i["greedy-arrays"]&&E.length>0||X&&typeof X==="number"&&E.length>=X)break;if(Z=B[te],/^-/.test(Z)&&!m.test(Z)&&!oe(Z))break;k=te,E.push(L(_,Z,s))}}if(typeof X==="number"&&(X&&E.length<X||isNaN(X)&&E.length===0))b=Error(g("Not enough arguments following: %s",_));return J(_,E),k}function J(k,_,B=s){if(/-/.test(k)&&i["camel-case-expansion"]){let Z=k.split(".").map(function(X){return nn(X)}).join(".");ne(k,Z)}let R=L(k,_,B),E=k.split(".");if(K(S,E,R),p.aliases[k])p.aliases[k].forEach(function(Z){let X=Z.split(".");K(S,X,R)});if(E.length>1&&i["dot-notation"])(p.aliases[E[0]]||[]).forEach(function(Z){let X=Z.split("."),te=[].concat(E);if(te.shift(),X=X.concat(te),!(p.aliases[k]||[]).includes(X.join(".")))K(S,X,R)});if(j(k,p.normalize)&&!j(k,p.arrays))[k].concat(p.aliases[k]||[]).forEach(function(X){Object.defineProperty(F,X,{enumerable:!0,get(){return _},set(te){_=typeof te==="string"?kt.normalize(te):te}})})}function ne(k,_){if(!(p.aliases[k]&&p.aliases[k].length))p.aliases[k]=[_],f[_]=!0;if(!(p.aliases[_]&&p.aliases[_].length))ne(_,k)}function L(k,_,B){if(B)_=th(_);if(j(k,p.bools)||j(k,p.counts)){if(typeof _==="string")_=_==="true"}let R=Array.isArray(_)?_.map(function(E){return O(k,E)}):O(k,_);if(j(k,p.counts)&&(Ae(R)||typeof R==="boolean"))R=kr();if(j(k,p.normalize)&&j(k,p.arrays))if(Array.isArray(_))R=_.map((E)=>kt.normalize(E));else R=kt.normalize(_);return R}function O(k,_){if(!i["parse-positional-numbers"]&&k==="_")return _;if(!j(k,p.strings)&&!j(k,p.bools)&&!Array.isArray(_)){if(Us(_)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${_}`)))||!Ae(_)&&j(k,p.numbers))_=Number(_)}return _}function I(k){let _=Object.create(null);le(_,p.aliases,a),Object.keys(p.configs).forEach(function(B){let R=k[B]||_[B];if(R)try{let E=null,Z=kt.resolve(kt.cwd(),R),X=p.configs[B];if(typeof X==="function"){try{E=X(Z)}catch(te){E=te}if(E instanceof Error){b=E;return}}else E=kt.require(Z);W(E)}catch(E){if(E.name==="PermissionDenied")b=E;else if(k[B])b=Error(g("Invalid JSON config file: %s",R))}})}function W(k,_){Object.keys(k).forEach(function(B){let R=k[B],E=_?_+"."+B:B;if(typeof R==="object"&&R!==null&&!Array.isArray(R)&&i["dot-notation"])W(R,E);else if(!ee(S,E.split("."))||j(E,p.arrays)&&i["combine-arrays"])J(E,R)})}function N(){if(typeof c<"u")c.forEach(function(k){W(k)})}function q(k,_){if(typeof l>"u")return;let B=typeof l==="string"?l:"",R=kt.env();Object.keys(R).forEach(function(E){if(B===""||E.lastIndexOf(B,0)===0){let Z=E.split("__").map(function(X,te){if(te===0)X=X.substring(B.length);return nn(X)});if((_&&p.configs[Z.join(".")]||!_)&&!ee(k,Z))J(Z.join("."),R[E])}})}function H(k){let _,B=new Set;Object.keys(k).forEach(function(R){if(!B.has(R)){if(_=j(R,p.coercions),typeof _==="function")try{let E=O(R,_(k[R]));[].concat(p.aliases[R]||[],R).forEach((Z)=>{B.add(Z),k[Z]=E})}catch(E){b=E}}})}function v(k){return p.keys.forEach((_)=>{if(~_.indexOf("."))return;if(typeof k[_]>"u")k[_]=void 0}),k}function le(k,_,B,R=!1){Object.keys(B).forEach(function(E){if(!ee(k,E.split("."))){if(K(k,E.split("."),B[E]),R)h[E]=!0;(_[E]||[]).forEach(function(Z){if(ee(k,Z.split(".")))return;K(k,Z.split("."),B[E])})}})}function ee(k,_){let B=k;if(!i["dot-notation"])_=[_.join(".")];_.slice(0,-1).forEach(function(E){B=B[E]||{}});let R=_[_.length-1];if(typeof B!=="object")return!1;else return R in B}function K(k,_,B){let R=k;if(!i["dot-notation"])_=[_.join(".")];_.slice(0,-1).forEach(function(Ie){if(Ie=yc(Ie),typeof R==="object"&&R[Ie]===void 0)R[Ie]={};if(typeof R[Ie]!=="object"||Array.isArray(R[Ie])){if(Array.isArray(R[Ie]))R[Ie].push({});else R[Ie]=[R[Ie],{}];R=R[Ie][R[Ie].length-1]}else R=R[Ie]});let E=yc(_[_.length-1]),Z=j(_.join("."),p.arrays),X=Array.isArray(B),te=i["duplicate-arguments-array"];if(!te&&j(E,p.nargs)){if(te=!0,!Ae(R[E])&&p.nargs[E]===1||Array.isArray(R[E])&&R[E].length===p.nargs[E])R[E]=void 0}if(B===kr())R[E]=kr(R[E]);else if(Array.isArray(R[E]))if(te&&Z&&X)R[E]=i["flatten-duplicate-arrays"]?R[E].concat(B):(Array.isArray(R[E][0])?R[E]:[R[E]]).concat([B]);else if(!te&&Boolean(Z)===Boolean(X))R[E]=B;else R[E]=R[E].concat([B]);else if(R[E]===void 0&&Z)R[E]=X?B:[B];else if(te&&!(R[E]===void 0||j(E,p.counts)||j(E,p.bools)))R[E]=[R[E],B];else R[E]=B}function ae(...k){k.forEach(function(_){Object.keys(_||{}).forEach(function(B){if(p.aliases[B])return;p.aliases[B]=[].concat(r[B]||[]),p.aliases[B].concat(B).forEach(function(R){if(/-/.test(R)&&i["camel-case-expansion"]){let E=nn(R);if(E!==B&&p.aliases[B].indexOf(E)===-1)p.aliases[B].push(E),f[E]=!0}}),p.aliases[B].concat(B).forEach(function(R){if(R.length>1&&/[A-Z]/.test(R)&&i["camel-case-expansion"]){let E=Ws(R,"-");if(E!==B&&p.aliases[B].indexOf(E)===-1)p.aliases[B].push(E),f[E]=!0}}),p.aliases[B].forEach(function(R){p.aliases[R]=[B].concat(p.aliases[B].filter(function(E){return R!==E}))})})})}function j(k,_){let B=[].concat(p.aliases[k]||[],k),R=Object.keys(_),E=B.find((Z)=>R.includes(Z));return E?_[E]:!1}function de(k){let _=Object.keys(p);return[].concat(_.map((R)=>p[R])).some(function(R){return Array.isArray(R)?R.includes(k):R[k]})}function se(k,..._){return[].concat(..._).some(function(R){let E=k.match(R);return E&&de(E[1])})}function U(k){if(k.match(m)||!k.match(/^-[^-]+/))return!1;let _=!0,B,R=k.slice(1).split("");for(let E=0;E<R.length;E++){if(B=k.slice(E+2),!de(R[E])){_=!1;break}if(R[E+1]&&R[E+1]==="="||B==="-"||/[A-Za-z]/.test(R[E])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(B)||R[E+1]&&R[E+1].match(/\W/))break}return _}function oe(k){return i["unknown-options-as-args"]&&z(k)}function z(k){if(k=k.replace(/^-{3,}/,"--"),k.match(m))return!1;if(U(k))return!1;return!se(k,/^-+([^=]+?)=[\s\S]*$/,w,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function M(k){if(!j(k,p.bools)&&!j(k,p.counts)&&`${k}`in a)return a[k];else return pe(we(k))}function pe(k){return{[nt.BOOLEAN]:!0,[nt.STRING]:"",[nt.NUMBER]:void 0,[nt.ARRAY]:[]}[k]}function we(k){let _=nt.BOOLEAN;if(j(k,p.strings))_=nt.STRING;else if(j(k,p.numbers))_=nt.NUMBER;else if(j(k,p.bools))_=nt.BOOLEAN;else if(j(k,p.arrays))_=nt.ARRAY;return _}function Ae(k){return k===void 0}function pr(){Object.keys(p.counts).find((k)=>{if(j(k,p.arrays))return b=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",k)),!0;else if(j(k,p.nargs))return b=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",k)),!0;return!1})}return{aliases:Object.assign({},p.aliases),argv:Object.assign(F,S),configuration:i,defaulted:Object.assign({},h),error:b,newAliases:Object.assign({},f)}}}function eh(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(a){return t[r].indexOf(a)!==-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,a,c){return c.indexOf(i)===a});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function kr(e){return e!==void 0?e+1:1}function yc(e){if(e==="__proto__")return"___proto___";return e}function th(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 rh}from"fs";import{createRequire as wc}from"node:module";var Sr,Er,_r,bc=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Dc=(Er=(Sr=process===null||process===void 0?void 0:process.versions)===null||Sr===void 0?void 0:Sr.node)!==null&&Er!==void 0?Er:(_r=process===null||process===void 0?void 0:process.version)===null||_r===void 0?void 0:_r.slice(1);if(Dc){if(Number(Dc.match(/^([^.]+)/)[1])<bc)throw Error(`yargs parser supports a minimum Node.js version of ${bc}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var ih=process?process.env:{},kc=wc?wc(import.meta.url):void 0,xc=new xr({cwd:process.cwd,env:()=>ih,format:nh,normalize:sh,resolve:oh,require:(e)=>{if(typeof kc<"u")return kc(e);else if(e.match(/\.json$/))return JSON.parse(rh(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),Vn=function(t,n){return xc.parse(t.slice(),n).argv};Vn.detailed=function(e,t){return xc.parse(e.slice(),t)};Vn.camelCase=nn;Vn.decamelize=Ws;Vn.looksLikeNumber=Us;var Cr=Vn;import{basename as wh,dirname as bh,extname as Dh,relative as kh,resolve as Rc,join as xh}from"path";function Sc(){if(ah())return 0;return 1}function ah(){return ch()&&!process.defaultApp}function ch(){return!!process.versions.electron}function $r(e){return e.slice(Sc()+1)}function Ec(){return process.argv[Sc()]}import{readFileSync as lh,statSync as uh,writeFile as dh}from"fs";import{format as fh}from"util";import{resolve as ph}from"path";var _c={fs:{readFileSync:lh,writeFile:dh},format:fh,resolve:ph,exists:(e)=>{try{return uh(e).isFile()}catch(t){return!1}}};var ut;class Cc{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 ut.format.apply(ut.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 ut.format.apply(ut.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);ut.fs.writeFile(r,i,"utf-8",function(a){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(a)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(ut.fs.readFileSync)e=JSON.parse(ut.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=ut.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=ut.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return ut.exists(e)}}function $c(e,t){ut=t;let n=new Cc(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 hh=(e)=>$c(e,_c),Ac=hh;var Pc=Ba(Tc(),1);import{createRequire as Sh}from"node:module";import{readFileSync as Eh,readdirSync as _h}from"node:fs";var Ar=Ic(import.meta.url),Ch=Ar.substring(0,Ar.lastIndexOf("node_modules")),$h=Sh(import.meta.url),Fr={assert:{notStrictEqual:gh,strictEqual:mh},cliui:br,findUp:Dr,getEnv:(e)=>process.env[e],inspect:yh,getProcessArgvBin:Ec,mainFilename:Ch||process.cwd(),Parser:Cr,path:{basename:wh,dirname:bh,extname:Dh,relative:kh,resolve:Rc,join:xh},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:Eh,readdirSync:_h,require:$h,getCallerFile:()=>{let e=Pc.default(3);return e.match(/^file:\/\//)?Ic(e):e},stringWidth:lt,y18n:Ac({directory:Rc(Ar,"../../../locales"),updateFiles:!1})};function We(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function Tr(e,t){t.assert.strictEqual(typeof e,"string")}function $n(e){return Object.keys(e)}function be(e){return!!e&&!!e.then&&typeof e.then==="function"}class Ce extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,Ce)}}function Pt(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,a)=>{let c=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&a===n.length-1)c=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:c});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:c})}),r}var Ah=["first","second","third","fourth","fifth","sixth"];function Y(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[Pt(`cmd ${e}`),t,n]}try{let s=0,[r,i,a]=o(),c=[].slice.call(i);while(c.length&&c[c.length-1]===void 0)c.pop();let l=a||c.length;if(l<r.demanded.length)throw new Ce(`Not enough arguments provided. Expected ${r.demanded.length} but received ${c.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new Ce(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let f=c.shift(),h=Oc(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)vc(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(c.length===0)return;let f=c.shift(),h=Oc(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)vc(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function Oc(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function vc(e,t,n){throw new Ce(`Invalid ${Ah[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class Rr{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(Y("<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 Lc(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function sn(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(be(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,a])=>Object.assign(i,a));else{let i=r(s,t);return be(i)?i.then((a)=>Object.assign(s,a)):Object.assign(s,i)}},e)}function on(e,t,n=(o)=>{throw o}){try{let o=Fh(e)?e():e;return be(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function Fh(e){return typeof e==="function"}var An=/(^\*)|(^\$0)/;class Nc{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:(a)=>a;for(let a of r){let c=a.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(c);else u=o.exclude.test(c);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(c);else u=o.include.test(c);if(!u)continue}let l=!1;for(let u of o.extensions)if(c.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,c),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,u,c)){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=[],a=Lc(s);if(o=o||(()=>{}),Array.isArray(e))if(Th(e))[e,...i]=e;else for(let c of e)this.addHandler(c);else if(Ih(e)){let c=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(c===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)c=[].concat(c).concat(e.aliases);this.addHandler(c,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(Mc(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let c=Pt(e);i=i.map((d)=>Pt(d).cmd);let l=!1,u=[c.cmd].concat(i).filter((d)=>{if(An.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)c.cmd=u[0],i=u.slice(1),e=e.replace(An,c.cmd);if(i.forEach((d)=>{this.aliasMap[d]=c.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[c.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:a,deprecated:r,demanded:c.demanded,optional:c.optional},l)this.defaultCommand=this.handlers[c.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,a=t.getInternalMethods().getContext(),c=a.commands.slice(),l=!e;if(e)a.commands.push(e),a.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,c,o,s,r);return be(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,a,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,a,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,a){let c=t.builder,l=n;if(Ks(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(o),a);if(be(u))return u.then((d)=>(l=jc(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(Rh(c))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,c[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 be(i)?i.then((a)=>({aliases:n.parsed.aliases,innerArgv:a})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=An.test(t.original)?t.original.replace(An,"").trim():t.original,o=e.filter((s)=>!An.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,a){if(!r.getInternalMethods().getHasOutput()){let c=r.getInternalMethods().runValidation(s,a,r.parsed.error,e);n=on(n,(l)=>(c(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let c=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,c,!1,!1),n=sn(n,r,i,!1),n=on(n,(l)=>{let u=t.handler(l);return be(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(be(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 a={};if(s)return n;if(!i.getInternalMethods().getHasOutput())a=this.populatePositionals(t,n,o,i);let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=sn(n,i,c,!0);return be(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,c,a)):this.handleValidationAndGetResult(e,t,l,o,r,i,c,a)}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 a=s.shift();this.populatePositional(a,t,i)}while(r.length){let a=r.shift();this.populatePositional(a,t,i)}return t._=n.commands.concat(t._.map((a)=>""+a)),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=Pt(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 c of Object.keys(n.alias))s.alias[c]=(s.alias[c]||[]).concat(n.alias[c]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((c)=>{t[c].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[c]=!0;r.push(`--${c}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(a.error)o.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{let c=Object.keys(t);Object.keys(t).forEach((l)=>{c.push(...a.aliases[l])}),Object.keys(a.argv).forEach((l)=>{if(c.includes(l)){if(!t[l])t[l]=a.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(a.argv,l)&&(Array.isArray(e[l])||Array.isArray(a.argv[l])))e[l]=[].concat(e[l],a.argv[l]);else e[l]=a.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=An.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(Ks(t))return t(e,!0);else if(!Mc(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;We(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();We(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 Bc(e,t,n,o){return new Nc(e,t,n,o)}function Mc(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Th(e){return e.every((t)=>typeof t==="string")}function Ks(e){return typeof e==="function"}function Rh(e){return typeof e==="object"}function Ih(e){return typeof e==="object"&&!Array.isArray(e)}function Ot(e={},t=()=>!0){let n={};return $n(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function vt(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 Ph(e){return typeof e==="boolean"}function Uc(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(O){s.push(O)};let r=null,i=null,a=!0;o.showHelpOnFail=function(O=!0,I){let[W,N]=typeof O==="string"?[!0,O]:[O,I];if(e.getInternalMethods().isGlobalContext())i=N;return r=N,a=W,o};let c=!1;o.fail=function(O,I){let W=e.getInternalMethods().getLoggerInstance();if(s.length)for(let N=s.length-1;N>=0;--N){let q=s[N];if(Ph(q)){if(I)throw I;else if(O)throw Error(O)}else q(O,I,o)}else{if(e.getExitProcess())vt(!0);if(!c){if(c=!0,a)e.showHelp("error"),W.error();if(O||I)W.error(O||I);let N=r||i;if(N){if(O||I)W.error("");W.error(N)}}if(I=I||new Ce(O),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,I);else throw I}};let l=[],u=!1;o.usage=(L,O)=>{if(L===null)return u=!0,l=[],o;return u=!1,l.push([L,O||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(L,O)=>{d.push([L,O||""])};let f=[];o.command=function(O,I,W,N,q=!1){if(W)f=f.map((H)=>(H[2]=!1,H));f.push([O,I||"",W,N,q])},o.getCommands=()=>f;let h={};o.describe=function(O,I){if(Array.isArray(O))O.forEach((W)=>{o.describe(W,I)});else if(typeof O==="object")Object.keys(O).forEach((W)=>{o.describe(W,O[W])});else h[O]=I},o.getDescriptions=()=>h;let g=[];o.epilog=(L)=>{g.push(L)};let p=!1,m;o.wrap=(L)=>{p=!0,m=L},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!p)m=x(),p=!0;return m};let w="__yargsString__:";o.deferY18nLookup=(L)=>w+L,o.help=function(){if(S)return S;D();let O=e.customScriptName?e.$0:t.path.basename(e.$0),I=e.getDemandedOptions(),W=e.getDemandedCommands(),N=e.getDeprecatedOptions(),q=e.getGroups(),H=e.getOptions(),v=[];v=v.concat(Object.keys(h)),v=v.concat(Object.keys(I)),v=v.concat(Object.keys(W)),v=v.concat(Object.keys(H.default)),v=v.filter(A),v=Object.keys(v.reduce((U,oe)=>{if(oe!=="_")U[oe]=!0;return U},{}));let le=o.getWrap(),ee=t.cliui({width:le,wrap:!!le});if(!u){if(l.length)l.forEach((U)=>{if(ee.div({text:`${U[0].replace(/\$0/g,O)}`}),U[1])ee.div({text:`${U[1]}`,padding:[1,0,0,0]})}),ee.div();else if(f.length){let U=null;if(W._)U=`${O} <${n("command")}>
15
- `;else U=`${O} [${n("command")}]
16
- `;ee.div(`${U}`)}}if(f.length>1||f.length===1&&!f[0][2]){ee.div(n("Commands:"));let U=e.getInternalMethods().getContext(),oe=U.commands.length?`${U.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((M,pe)=>M[0].localeCompare(pe[0]));let z=O?`${O} `:"";f.forEach((M)=>{let pe=`${z}${oe}${M[0].replace(/^\$0 ?/,"")}`;ee.span({text:pe,padding:[0,2,0,2],width:b(f,le,`${O}${oe}`)+4},{text:M[1]});let we=[];if(M[2])we.push(`[${n("default")}]`);if(M[3]&&M[3].length)we.push(`[${n("aliases:")} ${M[3].join(", ")}]`);if(M[4])if(typeof M[4]==="string")we.push(`[${n("deprecated: %s",M[4])}]`);else we.push(`[${n("deprecated")}]`);if(we.length)ee.div({text:we.join(" "),padding:[0,0,0,2],align:"right"});else ee.div()}),ee.div()}let K=(Object.keys(H.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);v=v.filter((U)=>!e.parsed.newAliases[U]&&K.every((oe)=>(H.alias[oe]||[]).indexOf(U)===-1));let ae=n("Options:");if(!q[ae])q[ae]=[];F(v,H.alias,q,ae);let j=(U)=>/^--/.test(Js(U)),de=Object.keys(q).filter((U)=>q[U].length>0).map((U)=>{let oe=q[U].filter(A).map((z)=>{if(K.includes(z))return z;for(let M=0,pe;(pe=K[M])!==void 0;M++)if((H.alias[pe]||[]).includes(z))return pe;return z});return{groupName:U,normalizedKeys:oe}}).filter(({normalizedKeys:U})=>U.length>0).map(({groupName:U,normalizedKeys:oe})=>{let z=oe.reduce((M,pe)=>(M[pe]=[pe].concat(H.alias[pe]||[]).map((we)=>{if(U===o.getPositionalGroupName())return we;else return(/^[0-9]$/.test(we)?H.boolean.includes(pe)?"-":"--":we.length>1?"--":"-")+we}).sort((we,Ae)=>j(we)===j(Ae)?0:j(we)?1:-1).join(", "),M),{});return{groupName:U,normalizedKeys:oe,switches:z}});if(de.filter(({groupName:U})=>U!==o.getPositionalGroupName()).some(({normalizedKeys:U,switches:oe})=>!U.every((z)=>j(oe[z]))))de.filter(({groupName:U})=>U!==o.getPositionalGroupName()).forEach(({normalizedKeys:U,switches:oe})=>{U.forEach((z)=>{if(j(oe[z]))oe[z]=Oh(oe[z],4)})});if(de.forEach(({groupName:U,normalizedKeys:oe,switches:z})=>{ee.div(U),oe.forEach((M)=>{let pe=z[M],we=h[M]||"",Ae=null;if(we.includes(w))we=n(we.substring(w.length));if(H.boolean.includes(M))Ae=`[${n("boolean")}]`;if(H.count.includes(M))Ae=`[${n("count")}]`;if(H.string.includes(M))Ae=`[${n("string")}]`;if(H.normalize.includes(M))Ae=`[${n("string")}]`;if(H.array.includes(M))Ae=`[${n("array")}]`;if(H.number.includes(M))Ae=`[${n("number")}]`;let pr=(B)=>typeof B==="string"?`[${n("deprecated: %s",B)}]`:`[${n("deprecated")}]`,k=[M in N?pr(N[M]):null,Ae,M in I?`[${n("required")}]`:null,H.choices&&H.choices[M]?`[${n("choices:")} ${o.stringifiedValues(H.choices[M])}]`:null,C(H.default[M],H.defaultDescription[M])].filter(Boolean).join(" ");ee.span({text:Js(pe),padding:[0,2,0,2+Wc(pe)],width:b(z,le)+4},we);let _=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(k&&!_)ee.div({text:k,padding:[0,0,0,2],align:"right"});else ee.div()}),ee.div()}),d.length)ee.div(n("Examples:")),d.forEach((U)=>{U[0]=U[0].replace(/\$0/g,O)}),d.forEach((U)=>{if(U[1]==="")ee.div({text:U[0],padding:[0,2,0,2]});else ee.div({text:U[0],padding:[0,2,0,2],width:b(d,le)+4},{text:U[1]})}),ee.div();if(g.length>0){let U=g.map((oe)=>oe.replace(/\$0/g,O)).join(`
17
- `);ee.div(`${U}
18
- `)}return ee.toString().replace(/\s*$/,"")};function b(L,O,I){let W=0;if(!Array.isArray(L))L=Object.values(L).map((N)=>[N]);if(L.forEach((N)=>{W=Math.max(t.stringWidth(I?`${I} ${Js(N[0])}`:Js(N[0]))+Wc(N[0]),W)}),O)W=Math.min(W,parseInt((O*0.5).toString(),10));return W}function D(){let L=e.getDemandedOptions(),O=e.getOptions();(Object.keys(O.alias)||[]).forEach((I)=>{O.alias[I].forEach((W)=>{if(h[W])o.describe(I,h[W]);if(W in L)e.demandOption(I,L[W]);if(O.boolean.includes(W))e.boolean(I);if(O.count.includes(W))e.count(I);if(O.string.includes(W))e.string(I);if(O.normalize.includes(W))e.normalize(I);if(O.array.includes(W))e.array(I);if(O.number.includes(W))e.number(I)})})}let S;o.cacheHelpMessage=function(){S=this.help()},o.clearCachedHelpMessage=function(){S=void 0},o.hasCachedHelpMessage=function(){return!!S};function F(L,O,I,W){let N=[],q=null;return Object.keys(I).forEach((H)=>{N=N.concat(I[H])}),L.forEach((H)=>{if(q=[H].concat(O[H]),!q.some((v)=>N.indexOf(v)!==-1))I[W].push(H)}),N}function A(L){return e.getOptions().hiddenOptions.indexOf(L)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}o.showHelp=(L)=>{let O=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:O[L])(o.help())},o.functionDescription=(L)=>["(",L.name?t.Parser.decamelize(L.name,"-"):n("generated-value"),")"].join(""),o.stringifiedValues=function(O,I){let W="",N=I||", ",q=[].concat(O);if(!O||!q.length)return W;return q.forEach((H)=>{if(W.length)W+=N;W+=JSON.stringify(H)}),W};function C(L,O){let I=`[${n("default:")} `;if(L===void 0&&!O)return null;if(O)I+=O;else switch(typeof L){case"string":I+=`"${L}"`;break;case"object":I+=JSON.stringify(L);break;default:I+=L}return`${I}]`}function x(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let J=null;o.version=(L)=>{J=L},o.showVersion=(L)=>{let O=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:O[L])(J)},o.reset=function(O){return r=null,c=!1,l=[],u=!1,g=[],d=[],f=[],h=Ot(h,(I)=>!O[I]),o};let ne=[];return o.freeze=function(){ne.push({failMessage:r,failureOutput:c,usages:l,usageDisabled:u,epilogs:g,examples:d,commands:f,descriptions:h})},o.unfreeze=function(O=!1){let I=ne.pop();if(!I)return;if(O)h={...I.descriptions,...h},f=[...I.commands,...f],l=[...I.usages,...l],d=[...I.examples,...d],g=[...I.epilogs,...g];else({failMessage:r,failureOutput:c,usages:l,usageDisabled:u,epilogs:g,examples:d,commands:f,descriptions:h}=I)},o}function Ir(e){return typeof e==="object"}function Oh(e,t){return Ir(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Wc(e){return Ir(e)?e.indentation:0}function Js(e){return Ir(e)?e.text:e}var Kc=`###-begin-{{app_name}}-completions-###
13
+ `).map((o)=>lh(o,t,n)).join(`
14
+ `)}function Sr(e){return Za(e,{stringWidth:lt,stripAnsi:tn,wrap:xr})}import{dirname as Sc,resolve as Ec}from"path";import{readdirSync as uh,statSync as dh}from"fs";function Er(e,t){let n=Ec(".",e),o;if(!dh(n).isDirectory())n=Sc(n);while(!0){if(o=t(n,uh(n)),o)return Ec(n,o);if(n=Sc(o=n),o===n)break}}import{inspect as Fh}from"util";import{fileURLToPath as Wc}from"url";import{format as hh}from"util";import{normalize as gh,resolve as mh}from"path";function nn(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 Js(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 Ks(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 _c(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 nt;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(nt||(nt={}));var xt;class $r{constructor(e){xt=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=_c(e),s=typeof e==="string",r=fh(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),a=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",f=Object.create(null),h=Object.create(null),g=n.__||xt.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:[]},m=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,w=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(k){let C=typeof k==="object"?k.key:k,B=Object.keys(k).map(function(R){return{boolean:"bools",string:"strings",number:"numbers"}[R]}).filter(Boolean).pop();if(B)p[B][C]=!0;p.arrays[C]=!0,p.keys.push(C)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(k){p.bools[k]=!0,p.keys.push(k)}),[].concat(n.string||[]).filter(Boolean).forEach(function(k){p.strings[k]=!0,p.keys.push(k)}),[].concat(n.number||[]).filter(Boolean).forEach(function(k){p.numbers[k]=!0,p.keys.push(k)}),[].concat(n.count||[]).filter(Boolean).forEach(function(k){p.counts[k]=!0,p.keys.push(k)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(k){p.normalize[k]=!0,p.keys.push(k)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([k,C])=>{if(typeof C==="number")p.nargs[k]=C,p.keys.push(k)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([k,C])=>{if(typeof C==="function")p.coercions[k]=C,p.keys.push(k)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(k){p.configs[k]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([k,C])=>{if(typeof C==="boolean"||typeof C==="function")p.configs[k]=C})}re(n.key,r,n.default,p.arrays),Object.keys(a).forEach(function(k){(p.aliases[k]||[]).forEach(function(C){a[C]=a[k]})});let b=null;yr();let D=[],S=Object.assign(Object.create(null),{_:[]}),A={};for(let k=0;k<o.length;k++){let C=o[k],B=C.replace(/^-{3,}/,"---"),R,_,Z,X,ne,Oe;if(C!=="--"&&/^-/.test(C)&&oe(C))F(C);else if(B.match(/^---+(=|$)/)){F(C);continue}else if(C.match(/^--.+=/)||!i["short-option-groups"]&&C.match(/^-.+=/)){if(X=C.match(/^--?([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)if(j(X[1],p.arrays))k=x(k,X[1],o,X[2]);else if(j(X[1],p.nargs)!==!1)k=E(k,X[1],o,X[2]);else W(X[1],X[2],!0)}else if(C.match(w)&&i["boolean-negation"]){if(X=C.match(w),X!==null&&Array.isArray(X)&&X.length>=2)_=X[1],W(_,j(_,p.arrays)?[!1]:!1)}else if(C.match(/^--.+/)||!i["short-option-groups"]&&C.match(/^-[^-]+/)){if(X=C.match(/^--?(.+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(_=X[1],j(_,p.arrays))k=x(k,_,o);else if(j(_,p.nargs)!==!1)k=E(k,_,o);else if(ne=o[k+1],ne!==void 0&&(!ne.match(/^-/)||ne.match(m))&&!j(_,p.bools)&&!j(_,p.counts))W(_,ne),k++;else if(/^(true|false)$/.test(ne))W(_,ne),k++;else W(_,L(_))}else if(C.match(/^-.\..+=/)){if(X=C.match(/^-([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)W(X[1],X[2])}else if(C.match(/^-.\..+/)&&!C.match(m)){if(ne=o[k+1],X=C.match(/^-(.\..+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(_=X[1],ne!==void 0&&!ne.match(/^-/)&&!j(_,p.bools)&&!j(_,p.counts))W(_,ne),k++;else W(_,L(_))}else if(C.match(/^-[^-]+/)&&!C.match(m)){Z=C.slice(1,-1).split(""),R=!1;for(let We=0;We<Z.length;We++){if(ne=C.slice(We+2),Z[We+1]&&Z[We+1]==="="){if(Oe=C.slice(We+3),_=Z[We],j(_,p.arrays))k=x(k,_,o,Oe);else if(j(_,p.nargs)!==!1)k=E(k,_,o,Oe);else W(_,Oe);R=!0;break}if(ne==="-"){W(Z[We],ne);continue}if(/[A-Za-z]/.test(Z[We])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(ne)&&j(ne,p.bools)===!1){W(Z[We],ne),R=!0;break}if(Z[We+1]&&Z[We+1].match(/\W/)){W(Z[We],ne),R=!0;break}else W(Z[We],L(Z[We]))}if(_=C.slice(-1)[0],!R&&_!=="-")if(j(_,p.arrays))k=x(k,_,o);else if(j(_,p.nargs)!==!1)k=E(k,_,o);else if(ne=o[k+1],ne!==void 0&&(!/^(-|--)[^-]/.test(ne)||ne.match(m))&&!j(_,p.bools)&&!j(_,p.counts))W(_,ne),k++;else if(/^(true|false)$/.test(ne))W(_,ne),k++;else W(_,L(_))}else if(C.match(/^-[0-9]$/)&&C.match(m)&&j(C.slice(1),p.bools))_=C.slice(1),W(_,L(_));else if(C==="--"){D=o.slice(k+1);break}else if(i["halt-at-non-option"]){D=o.slice(k);break}else F(C)}if(q(S,!0),q(S,!1),I(S),N(),le(S,p.aliases,a,!0),H(S),i["set-placeholder-key"])v(S);if(Object.keys(p.counts).forEach(function(k){if(!te(S,k.split(".")))W(k,0)}),u&&D.length)S[d]=[];if(D.forEach(function(k){S[d].push(k)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(S).filter((k)=>k!=="--"&&k.includes("-")).forEach((k)=>{delete S[k]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((k)=>r[k])).forEach((k)=>{if(i["camel-case-expansion"]&&k.includes("-"))delete S[k.split(".").map((C)=>nn(C)).join(".")];delete S[k]});function F(k){let C=P("_",k);if(typeof C==="string"||typeof C==="number")S._.push(C)}function E(k,C,B,R){let _,Z=j(C,p.nargs);if(Z=typeof Z!=="number"||isNaN(Z)?1:Z,Z===0){if(!Ae(R))b=Error(g("Argument unexpected for: %s",C));return W(C,L(C)),k}let X=Ae(R)?0:1;if(i["nargs-eats-options"]){if(B.length-(k+1)+X<Z)b=Error(g("Not enough arguments following: %s",C));X=Z}else{for(_=k+1;_<B.length;_++)if(!B[_].match(/^-[^0-9]/)||B[_].match(m)||oe(B[_]))X++;else break;if(X<Z)b=Error(g("Not enough arguments following: %s",C))}let ne=Math.min(X,Z);if(!Ae(R)&&ne>0)W(C,R),ne--;for(_=k+1;_<ne+k+1;_++)W(C,B[_]);return k+ne}function x(k,C,B,R){let _=[],Z=R||B[k+1],X=j(C,p.nargs);if(j(C,p.bools)&&!/^(true|false)$/.test(Z))_.push(!0);else if(Ae(Z)||Ae(R)&&/^-/.test(Z)&&!m.test(Z)&&!oe(Z)){if(a[C]!==void 0){let ne=a[C];_=Array.isArray(ne)?ne:[ne]}}else{if(!Ae(R))_.push(M(C,R,!0));for(let ne=k+1;ne<B.length;ne++){if(!i["greedy-arrays"]&&_.length>0||X&&typeof X==="number"&&_.length>=X)break;if(Z=B[ne],/^-/.test(Z)&&!m.test(Z)&&!oe(Z))break;k=ne,_.push(M(C,Z,s))}}if(typeof X==="number"&&(X&&_.length<X||isNaN(X)&&_.length===0))b=Error(g("Not enough arguments following: %s",C));return W(C,_),k}function W(k,C,B=s){if(/-/.test(k)&&i["camel-case-expansion"]){let Z=k.split(".").map(function(X){return nn(X)}).join(".");Q(k,Z)}let R=M(k,C,B),_=k.split(".");if(K(S,_,R),p.aliases[k])p.aliases[k].forEach(function(Z){let X=Z.split(".");K(S,X,R)});if(_.length>1&&i["dot-notation"])(p.aliases[_[0]]||[]).forEach(function(Z){let X=Z.split("."),ne=[].concat(_);if(ne.shift(),X=X.concat(ne),!(p.aliases[k]||[]).includes(X.join(".")))K(S,X,R)});if(j(k,p.normalize)&&!j(k,p.arrays))[k].concat(p.aliases[k]||[]).forEach(function(X){Object.defineProperty(A,X,{enumerable:!0,get(){return C},set(ne){C=typeof ne==="string"?xt.normalize(ne):ne}})})}function Q(k,C){if(!(p.aliases[k]&&p.aliases[k].length))p.aliases[k]=[C],f[C]=!0;if(!(p.aliases[C]&&p.aliases[C].length))Q(C,k)}function M(k,C,B){if(B)C=ph(C);if(j(k,p.bools)||j(k,p.counts)){if(typeof C==="string")C=C==="true"}let R=Array.isArray(C)?C.map(function(_){return P(k,_)}):P(k,C);if(j(k,p.counts)&&(Ae(R)||typeof R==="boolean"))R=_r();if(j(k,p.normalize)&&j(k,p.arrays))if(Array.isArray(C))R=C.map((_)=>xt.normalize(_));else R=xt.normalize(C);return R}function P(k,C){if(!i["parse-positional-numbers"]&&k==="_")return C;if(!j(k,p.strings)&&!j(k,p.bools)&&!Array.isArray(C)){if(Ks(C)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${C}`)))||!Ae(C)&&j(k,p.numbers))C=Number(C)}return C}function I(k){let C=Object.create(null);le(C,p.aliases,a),Object.keys(p.configs).forEach(function(B){let R=k[B]||C[B];if(R)try{let _=null,Z=xt.resolve(xt.cwd(),R),X=p.configs[B];if(typeof X==="function"){try{_=X(Z)}catch(ne){_=ne}if(_ instanceof Error){b=_;return}}else _=xt.require(Z);U(_)}catch(_){if(_.name==="PermissionDenied")b=_;else if(k[B])b=Error(g("Invalid JSON config file: %s",R))}})}function U(k,C){Object.keys(k).forEach(function(B){let R=k[B],_=C?C+"."+B:B;if(typeof R==="object"&&R!==null&&!Array.isArray(R)&&i["dot-notation"])U(R,_);else if(!te(S,_.split("."))||j(_,p.arrays)&&i["combine-arrays"])W(_,R)})}function N(){if(typeof c<"u")c.forEach(function(k){U(k)})}function q(k,C){if(typeof l>"u")return;let B=typeof l==="string"?l:"",R=xt.env();Object.keys(R).forEach(function(_){if(B===""||_.lastIndexOf(B,0)===0){let Z=_.split("__").map(function(X,ne){if(ne===0)X=X.substring(B.length);return nn(X)});if((C&&p.configs[Z.join(".")]||!C)&&!te(k,Z))W(Z.join("."),R[_])}})}function H(k){let C,B=new Set;Object.keys(k).forEach(function(R){if(!B.has(R)){if(C=j(R,p.coercions),typeof C==="function")try{let _=P(R,C(k[R]));[].concat(p.aliases[R]||[],R).forEach((Z)=>{B.add(Z),k[Z]=_})}catch(_){b=_}}})}function v(k){return p.keys.forEach((C)=>{if(~C.indexOf("."))return;if(typeof k[C]>"u")k[C]=void 0}),k}function le(k,C,B,R=!1){Object.keys(B).forEach(function(_){if(!te(k,_.split("."))){if(K(k,_.split("."),B[_]),R)h[_]=!0;(C[_]||[]).forEach(function(Z){if(te(k,Z.split(".")))return;K(k,Z.split("."),B[_])})}})}function te(k,C){let B=k;if(!i["dot-notation"])C=[C.join(".")];C.slice(0,-1).forEach(function(_){B=B[_]||{}});let R=C[C.length-1];if(typeof B!=="object")return!1;else return R in B}function K(k,C,B){let R=k;if(!i["dot-notation"])C=[C.join(".")];C.slice(0,-1).forEach(function(Oe){if(Oe=$c(Oe),typeof R==="object"&&R[Oe]===void 0)R[Oe]={};if(typeof R[Oe]!=="object"||Array.isArray(R[Oe])){if(Array.isArray(R[Oe]))R[Oe].push({});else R[Oe]=[R[Oe],{}];R=R[Oe][R[Oe].length-1]}else R=R[Oe]});let _=$c(C[C.length-1]),Z=j(C.join("."),p.arrays),X=Array.isArray(B),ne=i["duplicate-arguments-array"];if(!ne&&j(_,p.nargs)){if(ne=!0,!Ae(R[_])&&p.nargs[_]===1||Array.isArray(R[_])&&R[_].length===p.nargs[_])R[_]=void 0}if(B===_r())R[_]=_r(R[_]);else if(Array.isArray(R[_]))if(ne&&Z&&X)R[_]=i["flatten-duplicate-arrays"]?R[_].concat(B):(Array.isArray(R[_][0])?R[_]:[R[_]]).concat([B]);else if(!ne&&Boolean(Z)===Boolean(X))R[_]=B;else R[_]=R[_].concat([B]);else if(R[_]===void 0&&Z)R[_]=X?B:[B];else if(ne&&!(R[_]===void 0||j(_,p.counts)||j(_,p.bools)))R[_]=[R[_],B];else R[_]=B}function re(...k){k.forEach(function(C){Object.keys(C||{}).forEach(function(B){if(p.aliases[B])return;p.aliases[B]=[].concat(r[B]||[]),p.aliases[B].concat(B).forEach(function(R){if(/-/.test(R)&&i["camel-case-expansion"]){let _=nn(R);if(_!==B&&p.aliases[B].indexOf(_)===-1)p.aliases[B].push(_),f[_]=!0}}),p.aliases[B].concat(B).forEach(function(R){if(R.length>1&&/[A-Z]/.test(R)&&i["camel-case-expansion"]){let _=Js(R,"-");if(_!==B&&p.aliases[B].indexOf(_)===-1)p.aliases[B].push(_),f[_]=!0}}),p.aliases[B].forEach(function(R){p.aliases[R]=[B].concat(p.aliases[B].filter(function(_){return R!==_}))})})})}function j(k,C){let B=[].concat(p.aliases[k]||[],k),R=Object.keys(C),_=B.find((Z)=>R.includes(Z));return _?C[_]:!1}function de(k){let C=Object.keys(p);return[].concat(C.map((R)=>p[R])).some(function(R){return Array.isArray(R)?R.includes(k):R[k]})}function se(k,...C){return[].concat(...C).some(function(R){let _=k.match(R);return _&&de(_[1])})}function J(k){if(k.match(m)||!k.match(/^-[^-]+/))return!1;let C=!0,B,R=k.slice(1).split("");for(let _=0;_<R.length;_++){if(B=k.slice(_+2),!de(R[_])){C=!1;break}if(R[_+1]&&R[_+1]==="="||B==="-"||/[A-Za-z]/.test(R[_])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(B)||R[_+1]&&R[_+1].match(/\W/))break}return C}function oe(k){return i["unknown-options-as-args"]&&z(k)}function z(k){if(k=k.replace(/^-{3,}/,"--"),k.match(m))return!1;if(J(k))return!1;return!se(k,/^-+([^=]+?)=[\s\S]*$/,w,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function L(k){if(!j(k,p.bools)&&!j(k,p.counts)&&`${k}`in a)return a[k];else return pe(we(k))}function pe(k){return{[nt.BOOLEAN]:!0,[nt.STRING]:"",[nt.NUMBER]:void 0,[nt.ARRAY]:[]}[k]}function we(k){let C=nt.BOOLEAN;if(j(k,p.strings))C=nt.STRING;else if(j(k,p.numbers))C=nt.NUMBER;else if(j(k,p.bools))C=nt.BOOLEAN;else if(j(k,p.arrays))C=nt.ARRAY;return C}function Ae(k){return k===void 0}function yr(){Object.keys(p.counts).find((k)=>{if(j(k,p.arrays))return b=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",k)),!0;else if(j(k,p.nargs))return b=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",k)),!0;return!1})}return{aliases:Object.assign({},p.aliases),argv:Object.assign(A,S),configuration:i,defaulted:Object.assign({},h),error:b,newAliases:Object.assign({},f)}}}function fh(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(a){return t[r].indexOf(a)!==-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,a,c){return c.indexOf(i)===a});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function _r(e){return e!==void 0?e+1:1}function $c(e){if(e==="__proto__")return"___proto___";return e}function ph(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 yh}from"fs";import{createRequire as Cc}from"node:module";var Cr,Ar,Fr,Ac=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Fc=(Ar=(Cr=process===null||process===void 0?void 0:process.versions)===null||Cr===void 0?void 0:Cr.node)!==null&&Ar!==void 0?Ar:(Fr=process===null||process===void 0?void 0:process.version)===null||Fr===void 0?void 0:Fr.slice(1);if(Fc){if(Number(Fc.match(/^([^.]+)/)[1])<Ac)throw Error(`yargs parser supports a minimum Node.js version of ${Ac}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var wh=process?process.env:{},Tc=Cc?Cc(import.meta.url):void 0,Rc=new $r({cwd:process.cwd,env:()=>wh,format:hh,normalize:gh,resolve:mh,require:(e)=>{if(typeof Tc<"u")return Tc(e);else if(e.match(/\.json$/))return JSON.parse(yh(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),Qn=function(t,n){return Rc.parse(t.slice(),n).argv};Qn.detailed=function(e,t){return Rc.parse(e.slice(),t)};Qn.camelCase=nn;Qn.decamelize=Js;Qn.looksLikeNumber=Ks;var Tr=Qn;import{basename as Th,dirname as Rh,extname as Ih,relative as Oh,resolve as jc,join as Ph}from"path";function Ic(){if(bh())return 0;return 1}function bh(){return Dh()&&!process.defaultApp}function Dh(){return!!process.versions.electron}function Rr(e){return e.slice(Ic()+1)}function Oc(){return process.argv[Ic()]}import{readFileSync as kh,statSync as xh,writeFile as Sh}from"fs";import{format as Eh}from"util";import{resolve as _h}from"path";var Pc={fs:{readFileSync:kh,writeFile:Sh},format:Eh,resolve:_h,exists:(e)=>{try{return xh(e).isFile()}catch(t){return!1}}};var ut;class vc{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 ut.format.apply(ut.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 ut.format.apply(ut.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);ut.fs.writeFile(r,i,"utf-8",function(a){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(a)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(ut.fs.readFileSync)e=JSON.parse(ut.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=ut.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=ut.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return ut.exists(e)}}function Lc(e,t){ut=t;let n=new vc(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 $h=(e)=>Lc(e,Pc),Mc=$h;var Uc=Xa(Bc(),1);import{createRequire as vh}from"node:module";import{readFileSync as Lh,readdirSync as Mh}from"node:fs";var Ir=Wc(import.meta.url),Nh=Ir.substring(0,Ir.lastIndexOf("node_modules")),Bh=vh(import.meta.url),Or={assert:{notStrictEqual:Ch,strictEqual:Ah},cliui:Sr,findUp:Er,getEnv:(e)=>process.env[e],inspect:Fh,getProcessArgvBin:Oc,mainFilename:Nh||process.cwd(),Parser:Tr,path:{basename:Th,dirname:Rh,extname:Ih,relative:Oh,resolve:jc,join:Ph},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:Lh,readdirSync:Mh,require:Bh,getCallerFile:()=>{let e=Uc.default(3);return e.match(/^file:\/\//)?Wc(e):e},stringWidth:lt,y18n:Mc({directory:jc(Ir,"../../../locales"),updateFiles:!1})};function Ue(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function Pr(e,t){t.assert.strictEqual(typeof e,"string")}function An(e){return Object.keys(e)}function be(e){return!!e&&!!e.then&&typeof e.then==="function"}class $e extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,$e)}}function Lt(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,a)=>{let c=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&a===n.length-1)c=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:c});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:c})}),r}var jh=["first","second","third","fourth","fifth","sixth"];function Y(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[Lt(`cmd ${e}`),t,n]}try{let s=0,[r,i,a]=o(),c=[].slice.call(i);while(c.length&&c[c.length-1]===void 0)c.pop();let l=a||c.length;if(l<r.demanded.length)throw new $e(`Not enough arguments provided. Expected ${r.demanded.length} but received ${c.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new $e(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let f=c.shift(),h=Jc(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)Kc(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(c.length===0)return;let f=c.shift(),h=Jc(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)Kc(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function Jc(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function Kc(e,t,n){throw new $e(`Invalid ${jh[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class vr{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(Y("<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 qc(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function sn(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(be(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,a])=>Object.assign(i,a));else{let i=r(s,t);return be(i)?i.then((a)=>Object.assign(s,a)):Object.assign(s,i)}},e)}function on(e,t,n=(o)=>{throw o}){try{let o=Wh(e)?e():e;return be(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function Wh(e){return typeof e==="function"}var Fn=/(^\*)|(^\$0)/;class zc{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:(a)=>a;for(let a of r){let c=a.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(c);else u=o.exclude.test(c);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(c);else u=o.include.test(c);if(!u)continue}let l=!1;for(let u of o.extensions)if(c.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,c),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,u,c)){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=[],a=qc(s);if(o=o||(()=>{}),Array.isArray(e))if(Uh(e))[e,...i]=e;else for(let c of e)this.addHandler(c);else if(Kh(e)){let c=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(c===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)c=[].concat(c).concat(e.aliases);this.addHandler(c,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(Hc(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let c=Lt(e);i=i.map((d)=>Lt(d).cmd);let l=!1,u=[c.cmd].concat(i).filter((d)=>{if(Fn.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)c.cmd=u[0],i=u.slice(1),e=e.replace(Fn,c.cmd);if(i.forEach((d)=>{this.aliasMap[d]=c.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[c.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:a,deprecated:r,demanded:c.demanded,optional:c.optional},l)this.defaultCommand=this.handlers[c.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,a=t.getInternalMethods().getContext(),c=a.commands.slice(),l=!e;if(e)a.commands.push(e),a.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,c,o,s,r);return be(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,a,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,a,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,a){let c=t.builder,l=n;if(qs(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(o),a);if(be(u))return u.then((d)=>(l=Gc(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(Jh(c))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,c[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 be(i)?i.then((a)=>({aliases:n.parsed.aliases,innerArgv:a})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=Fn.test(t.original)?t.original.replace(Fn,"").trim():t.original,o=e.filter((s)=>!Fn.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,a){if(!r.getInternalMethods().getHasOutput()){let c=r.getInternalMethods().runValidation(s,a,r.parsed.error,e);n=on(n,(l)=>(c(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let c=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,c,!1,!1),n=sn(n,r,i,!1),n=on(n,(l)=>{let u=t.handler(l);return be(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(be(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 a={};if(s)return n;if(!i.getInternalMethods().getHasOutput())a=this.populatePositionals(t,n,o,i);let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=sn(n,i,c,!0);return be(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,c,a)):this.handleValidationAndGetResult(e,t,l,o,r,i,c,a)}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 a=s.shift();this.populatePositional(a,t,i)}while(r.length){let a=r.shift();this.populatePositional(a,t,i)}return t._=n.commands.concat(t._.map((a)=>""+a)),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=Lt(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 c of Object.keys(n.alias))s.alias[c]=(s.alias[c]||[]).concat(n.alias[c]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((c)=>{t[c].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[c]=!0;r.push(`--${c}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(a.error)o.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{let c=Object.keys(t);Object.keys(t).forEach((l)=>{c.push(...a.aliases[l])}),Object.keys(a.argv).forEach((l)=>{if(c.includes(l)){if(!t[l])t[l]=a.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(a.argv,l)&&(Array.isArray(e[l])||Array.isArray(a.argv[l])))e[l]=[].concat(e[l],a.argv[l]);else e[l]=a.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=Fn.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(qs(t))return t(e,!0);else if(!Hc(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;Ue(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();Ue(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 Xc(e,t,n,o){return new zc(e,t,n,o)}function Hc(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Uh(e){return e.every((t)=>typeof t==="string")}function qs(e){return typeof e==="function"}function Jh(e){return typeof e==="object"}function Kh(e){return typeof e==="object"&&!Array.isArray(e)}function Mt(e={},t=()=>!0){let n={};return An(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function Nt(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 qh(e){return typeof e==="boolean"}function Vc(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(P){s.push(P)};let r=null,i=null,a=!0;o.showHelpOnFail=function(P=!0,I){let[U,N]=typeof P==="string"?[!0,P]:[P,I];if(e.getInternalMethods().isGlobalContext())i=N;return r=N,a=U,o};let c=!1;o.fail=function(P,I){let U=e.getInternalMethods().getLoggerInstance();if(s.length)for(let N=s.length-1;N>=0;--N){let q=s[N];if(qh(q)){if(I)throw I;else if(P)throw Error(P)}else q(P,I,o)}else{if(e.getExitProcess())Nt(!0);if(!c){if(c=!0,a)e.showHelp("error"),U.error();if(P||I)U.error(P||I);let N=r||i;if(N){if(P||I)U.error("");U.error(N)}}if(I=I||new $e(P),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,I);else throw I}};let l=[],u=!1;o.usage=(M,P)=>{if(M===null)return u=!0,l=[],o;return u=!1,l.push([M,P||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(M,P)=>{d.push([M,P||""])};let f=[];o.command=function(P,I,U,N,q=!1){if(U)f=f.map((H)=>(H[2]=!1,H));f.push([P,I||"",U,N,q])},o.getCommands=()=>f;let h={};o.describe=function(P,I){if(Array.isArray(P))P.forEach((U)=>{o.describe(U,I)});else if(typeof P==="object")Object.keys(P).forEach((U)=>{o.describe(U,P[U])});else h[P]=I},o.getDescriptions=()=>h;let g=[];o.epilog=(M)=>{g.push(M)};let p=!1,m;o.wrap=(M)=>{p=!0,m=M},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!p)m=x(),p=!0;return m};let w="__yargsString__:";o.deferY18nLookup=(M)=>w+M,o.help=function(){if(S)return S;D();let P=e.customScriptName?e.$0:t.path.basename(e.$0),I=e.getDemandedOptions(),U=e.getDemandedCommands(),N=e.getDeprecatedOptions(),q=e.getGroups(),H=e.getOptions(),v=[];v=v.concat(Object.keys(h)),v=v.concat(Object.keys(I)),v=v.concat(Object.keys(U)),v=v.concat(Object.keys(H.default)),v=v.filter(F),v=Object.keys(v.reduce((J,oe)=>{if(oe!=="_")J[oe]=!0;return J},{}));let le=o.getWrap(),te=t.cliui({width:le,wrap:!!le});if(!u){if(l.length)l.forEach((J)=>{if(te.div({text:`${J[0].replace(/\$0/g,P)}`}),J[1])te.div({text:`${J[1]}`,padding:[1,0,0,0]})}),te.div();else if(f.length){let J=null;if(U._)J=`${P} <${n("command")}>
15
+ `;else J=`${P} [${n("command")}]
16
+ `;te.div(`${J}`)}}if(f.length>1||f.length===1&&!f[0][2]){te.div(n("Commands:"));let J=e.getInternalMethods().getContext(),oe=J.commands.length?`${J.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((L,pe)=>L[0].localeCompare(pe[0]));let z=P?`${P} `:"";f.forEach((L)=>{let pe=`${z}${oe}${L[0].replace(/^\$0 ?/,"")}`;te.span({text:pe,padding:[0,2,0,2],width:b(f,le,`${P}${oe}`)+4},{text:L[1]});let we=[];if(L[2])we.push(`[${n("default")}]`);if(L[3]&&L[3].length)we.push(`[${n("aliases:")} ${L[3].join(", ")}]`);if(L[4])if(typeof L[4]==="string")we.push(`[${n("deprecated: %s",L[4])}]`);else we.push(`[${n("deprecated")}]`);if(we.length)te.div({text:we.join(" "),padding:[0,0,0,2],align:"right"});else te.div()}),te.div()}let K=(Object.keys(H.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);v=v.filter((J)=>!e.parsed.newAliases[J]&&K.every((oe)=>(H.alias[oe]||[]).indexOf(J)===-1));let re=n("Options:");if(!q[re])q[re]=[];A(v,H.alias,q,re);let j=(J)=>/^--/.test(Hs(J)),de=Object.keys(q).filter((J)=>q[J].length>0).map((J)=>{let oe=q[J].filter(F).map((z)=>{if(K.includes(z))return z;for(let L=0,pe;(pe=K[L])!==void 0;L++)if((H.alias[pe]||[]).includes(z))return pe;return z});return{groupName:J,normalizedKeys:oe}}).filter(({normalizedKeys:J})=>J.length>0).map(({groupName:J,normalizedKeys:oe})=>{let z=oe.reduce((L,pe)=>(L[pe]=[pe].concat(H.alias[pe]||[]).map((we)=>{if(J===o.getPositionalGroupName())return we;else return(/^[0-9]$/.test(we)?H.boolean.includes(pe)?"-":"--":we.length>1?"--":"-")+we}).sort((we,Ae)=>j(we)===j(Ae)?0:j(we)?1:-1).join(", "),L),{});return{groupName:J,normalizedKeys:oe,switches:z}});if(de.filter(({groupName:J})=>J!==o.getPositionalGroupName()).some(({normalizedKeys:J,switches:oe})=>!J.every((z)=>j(oe[z]))))de.filter(({groupName:J})=>J!==o.getPositionalGroupName()).forEach(({normalizedKeys:J,switches:oe})=>{J.forEach((z)=>{if(j(oe[z]))oe[z]=Hh(oe[z],4)})});if(de.forEach(({groupName:J,normalizedKeys:oe,switches:z})=>{te.div(J),oe.forEach((L)=>{let pe=z[L],we=h[L]||"",Ae=null;if(we.includes(w))we=n(we.substring(w.length));if(H.boolean.includes(L))Ae=`[${n("boolean")}]`;if(H.count.includes(L))Ae=`[${n("count")}]`;if(H.string.includes(L))Ae=`[${n("string")}]`;if(H.normalize.includes(L))Ae=`[${n("string")}]`;if(H.array.includes(L))Ae=`[${n("array")}]`;if(H.number.includes(L))Ae=`[${n("number")}]`;let yr=(B)=>typeof B==="string"?`[${n("deprecated: %s",B)}]`:`[${n("deprecated")}]`,k=[L in N?yr(N[L]):null,Ae,L in I?`[${n("required")}]`:null,H.choices&&H.choices[L]?`[${n("choices:")} ${o.stringifiedValues(H.choices[L])}]`:null,E(H.default[L],H.defaultDescription[L])].filter(Boolean).join(" ");te.span({text:Hs(pe),padding:[0,2,0,2+Yc(pe)],width:b(z,le)+4},we);let C=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(k&&!C)te.div({text:k,padding:[0,0,0,2],align:"right"});else te.div()}),te.div()}),d.length)te.div(n("Examples:")),d.forEach((J)=>{J[0]=J[0].replace(/\$0/g,P)}),d.forEach((J)=>{if(J[1]==="")te.div({text:J[0],padding:[0,2,0,2]});else te.div({text:J[0],padding:[0,2,0,2],width:b(d,le)+4},{text:J[1]})}),te.div();if(g.length>0){let J=g.map((oe)=>oe.replace(/\$0/g,P)).join(`
17
+ `);te.div(`${J}
18
+ `)}return te.toString().replace(/\s*$/,"")};function b(M,P,I){let U=0;if(!Array.isArray(M))M=Object.values(M).map((N)=>[N]);if(M.forEach((N)=>{U=Math.max(t.stringWidth(I?`${I} ${Hs(N[0])}`:Hs(N[0]))+Yc(N[0]),U)}),P)U=Math.min(U,parseInt((P*0.5).toString(),10));return U}function D(){let M=e.getDemandedOptions(),P=e.getOptions();(Object.keys(P.alias)||[]).forEach((I)=>{P.alias[I].forEach((U)=>{if(h[U])o.describe(I,h[U]);if(U in M)e.demandOption(I,M[U]);if(P.boolean.includes(U))e.boolean(I);if(P.count.includes(U))e.count(I);if(P.string.includes(U))e.string(I);if(P.normalize.includes(U))e.normalize(I);if(P.array.includes(U))e.array(I);if(P.number.includes(U))e.number(I)})})}let S;o.cacheHelpMessage=function(){S=this.help()},o.clearCachedHelpMessage=function(){S=void 0},o.hasCachedHelpMessage=function(){return!!S};function A(M,P,I,U){let N=[],q=null;return Object.keys(I).forEach((H)=>{N=N.concat(I[H])}),M.forEach((H)=>{if(q=[H].concat(P[H]),!q.some((v)=>N.indexOf(v)!==-1))I[U].push(H)}),N}function F(M){return e.getOptions().hiddenOptions.indexOf(M)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}o.showHelp=(M)=>{let P=e.getInternalMethods().getLoggerInstance();if(!M)M="error";(typeof M==="function"?M:P[M])(o.help())},o.functionDescription=(M)=>["(",M.name?t.Parser.decamelize(M.name,"-"):n("generated-value"),")"].join(""),o.stringifiedValues=function(P,I){let U="",N=I||", ",q=[].concat(P);if(!P||!q.length)return U;return q.forEach((H)=>{if(U.length)U+=N;U+=JSON.stringify(H)}),U};function E(M,P){let I=`[${n("default:")} `;if(M===void 0&&!P)return null;if(P)I+=P;else switch(typeof M){case"string":I+=`"${M}"`;break;case"object":I+=JSON.stringify(M);break;default:I+=M}return`${I}]`}function x(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let W=null;o.version=(M)=>{W=M},o.showVersion=(M)=>{let P=e.getInternalMethods().getLoggerInstance();if(!M)M="error";(typeof M==="function"?M:P[M])(W)},o.reset=function(P){return r=null,c=!1,l=[],u=!1,g=[],d=[],f=[],h=Mt(h,(I)=>!P[I]),o};let Q=[];return o.freeze=function(){Q.push({failMessage:r,failureOutput:c,usages:l,usageDisabled:u,epilogs:g,examples:d,commands:f,descriptions:h})},o.unfreeze=function(P=!1){let I=Q.pop();if(!I)return;if(P)h={...I.descriptions,...h},f=[...I.commands,...f],l=[...I.usages,...l],d=[...I.examples,...d],g=[...I.epilogs,...g];else({failMessage:r,failureOutput:c,usages:l,usageDisabled:u,epilogs:g,examples:d,commands:f,descriptions:h}=I)},o}function Lr(e){return typeof e==="object"}function Hh(e,t){return Lr(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Yc(e){return Lr(e)?e.indentation:0}function Hs(e){return Lr(e)?e.text:e}var Zc=`###-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
- `,Jc=`#compdef {{app_name}}
47
+ `,Qc=`#compdef {{app_name}}
48
48
  ###-begin-{{app_name}}-completions-###
49
49
  #
50
50
  # yargs command completion script
@@ -71,24 +71,24 @@ else
71
71
  compdef _{{app_name}}_yargs_completions {{app_name}}
72
72
  fi
73
73
  ###-end-{{app_name}}-completions-###
74
- `;class qc{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,a=e.length;i<a;++i)if(s[e[i]]&&s[e[i]].builder){let c=s[e[i]].builder;if(Ks(c)){this.indexAfterLastReset=i+1;let l=this.yargs.getInternalMethods().reset();return c(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=Pt(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 a=!!s.configuration["boolean-negation"]&&s.boolean.includes(i);if(!r.includes(i)&&!s.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,a))this.completeOptionKey(i,e,o,a&&!!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 a=this.yargs.getOptions().choices[i]||[];for(let c of a)if(c.startsWith(o))e.push(c.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 a of r)if(Object.prototype.hasOwnProperty.call(s.key,a)&&Array.isArray(s.choices[a])){i=s.choices[a];break}if(i)return i.filter((a)=>!n||a.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,a;let c=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((m)=>{let w=f[m];return typeof w==="string"&&w.length>0}),g=h?f[h]:void 0,p=(a=(i=f[e])!==null&&i!==void 0?i:g)!==null&&a!==void 0?a:"";c=`${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+c),o)t.push(d+"no-"+c)}customCompletion(e,t,n,o){if(We(this.customCompletionFunction,null,this.shim),Lh(this.customCompletionFunction)){let s=this.customCompletionFunction(n,t);if(be(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(Mh(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 be(o)?o.then(s):s(o)}generateCompletionScript(e,t){let n=this.zshShell?Jc:Kc,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 Hc(e,t,n,o){return new qc(e,t,n,o)}function Lh(e){return e.length<3}function Mh(e){return e.length>3}function zc(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 Xc=["$0","--","_"];function Gc(e,t,n){let o=n.y18n.__,s=n.y18n.__n,r={};r.nonOptionCount=function(d){let f=e.getDemandedCommands(),g=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(f._&&(g<f._.min||g>f._.max)){if(g<f._.min)if(f._.minMsg!==void 0)t.fail(f._.minMsg?f._.minMsg.replace(/\$0/g,g.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",g,g.toString(),f._.min.toString()));else if(g>f._.max)if(f._.maxMsg!==void 0)t.fail(f._.maxMsg?f._.maxMsg.replace(/\$0/g,g.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",g,g.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 g of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,g)||typeof d[g]>"u")h=h||{},h[g]=f[g];if(h){let g=[];for(let m of Object.keys(h)){let w=h[m];if(w&&g.indexOf(w)<0)g.push(w)}let p=g.length?`
74
+ `;class el{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,a=e.length;i<a;++i)if(s[e[i]]&&s[e[i]].builder){let c=s[e[i]].builder;if(qs(c)){this.indexAfterLastReset=i+1;let l=this.yargs.getInternalMethods().reset();return c(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=Lt(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 a=!!s.configuration["boolean-negation"]&&s.boolean.includes(i);if(!r.includes(i)&&!s.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,a))this.completeOptionKey(i,e,o,a&&!!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 a=this.yargs.getOptions().choices[i]||[];for(let c of a)if(c.startsWith(o))e.push(c.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 a of r)if(Object.prototype.hasOwnProperty.call(s.key,a)&&Array.isArray(s.choices[a])){i=s.choices[a];break}if(i)return i.filter((a)=>!n||a.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,a;let c=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((m)=>{let w=f[m];return typeof w==="string"&&w.length>0}),g=h?f[h]:void 0,p=(a=(i=f[e])!==null&&i!==void 0?i:g)!==null&&a!==void 0?a:"";c=`${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+c),o)t.push(d+"no-"+c)}customCompletion(e,t,n,o){if(Ue(this.customCompletionFunction,null,this.shim),Xh(this.customCompletionFunction)){let s=this.customCompletionFunction(n,t);if(be(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(Gh(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 be(o)?o.then(s):s(o)}generateCompletionScript(e,t){let n=this.zshShell?Qc:Zc,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 tl(e,t,n,o){return new el(e,t,n,o)}function Xh(e){return e.length<3}function Gh(e){return e.length>3}function nl(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 sl=["$0","--","_"];function ol(e,t,n){let o=n.y18n.__,s=n.y18n.__n,r={};r.nonOptionCount=function(d){let f=e.getDemandedCommands(),g=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(f._&&(g<f._.min||g>f._.max)){if(g<f._.min)if(f._.minMsg!==void 0)t.fail(f._.minMsg?f._.minMsg.replace(/\$0/g,g.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",g,g.toString(),f._.min.toString()));else if(g>f._.max)if(f._.maxMsg!==void 0)t.fail(f._.maxMsg?f._.maxMsg.replace(/\$0/g,g.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",g,g.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 g of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,g)||typeof d[g]>"u")h=h||{},h[g]=f[g];if(h){let g=[];for(let m of Object.keys(h)){let w=h[m];if(w&&g.indexOf(w)<0)g.push(w)}let p=g.length?`
75
75
  ${g.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,g,p=!0){var m;let w=e.getInternalMethods().getCommandInstance().getCommands(),b=[],D=e.getInternalMethods().getContext();if(Object.keys(d).forEach((S)=>{if(!Xc.includes(S)&&!Object.prototype.hasOwnProperty.call(h,S)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),S)&&!r.isValidAndSomeAliasIsNotNew(S,f))b.push(S)}),p&&(D.commands.length>0||w.length>0||g))d._.slice(D.commands.length).forEach((S)=>{if(!w.includes(""+S))b.push(""+S)});if(p){let F=((m=e.getDemandedCommands()._)===null||m===void 0?void 0:m.max)||0,A=D.commands.length+F;if(A<d._.length)d._.slice(A).forEach((C)=>{if(C=String(C),!D.commands.includes(C)&&!b.includes(C))b.push(C)})}if(b.length)t.fail(s("Unknown argument: %s","Unknown arguments: %s",b.length,b.map((S)=>S.trim()?S:`"${S}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),h=[],g=e.getInternalMethods().getContext();if(g.commands.length>0||f.length>0)d._.slice(g.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((g)=>!Object.prototype.hasOwnProperty.call(h,g)||!h[d])},r.limitedChoices=function(d){let f=e.getOptions(),h={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((m)=>{if(Xc.indexOf(m)===-1&&Object.prototype.hasOwnProperty.call(f.choices,m))[].concat(d[m]).forEach((w)=>{if(f.choices[m].indexOf(w)===-1&&w!==void 0)h[m]=(h[m]||[]).concat(w)})});let g=Object.keys(h);if(!g.length)return;let p=o("Invalid values:");g.forEach((m)=>{p+=`
77
- ${o("Argument: %s, Given: %s, Choices: %s",m,t.stringifiedValues(h[m]),t.stringifiedValues(f.choices[m]))}`}),t.fail(p)};let i={};r.implies=function(d,f){if(Y("<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 We(f,void 0,n),i[d].push(f)}},r.getImplied=function(){return i};function a(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 g=h;(i[h]||[]).forEach((p)=>{let m=g,w=p;if(m=a(d,m),p=a(d,p),m&&!p)f.push(` ${g} -> ${w}`)})}),f.length){let h=`${o("Implications failed:")}
78
- `;f.forEach((g)=>{h+=g}),t.fail(h)}};let c={};r.conflicts=function(d,f){if(Y("<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),!c[d])c[d]=[];if(Array.isArray(f))f.forEach((h)=>r.conflicts(d,h));else c[d].push(f)}},r.getConflicting=()=>c,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(c[f])c[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(c).forEach((f)=>{c[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((m,w)=>w.length-m.length);let g=null,p=1/0;for(let m=0,w;(w=f[m])!==void 0;m++){let b=zc(d,w);if(b<=3&&b<p)p=b,g=w}if(g)t.fail(o("Did you mean %s?",g))},r.reset=function(d){return i=Ot(i,(f)=>!d[f]),c=Ot(c,(f)=>!d[f]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:c})},r.unfreeze=function(){let d=l.pop();We(d,void 0,n),{implied:i,conflicting:c}=d},r}var Pr=[],Zn;function Qn(e,t,n,o){Zn=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(a){return e}else i=Bh(t,e.extends);Nh(i),Pr.push(i),s=r?JSON.parse(Zn.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=Qn(s,Zn.path.dirname(i),n,Zn)}return Pr=[],n?Yc(s,e):Object.assign({},s,e)}function Nh(e){if(Pr.indexOf(e)>-1)throw new Ce(`Circular extended configurations: '${e}'.`)}function Bh(e,t){return Zn.path.resolve(e,t)}function Yc(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]=Yc(e[s],t[s]);else n[s]=t[s];return n}var V=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},y=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)},$e,rn,es,Ke,Ve,qs,Lt,an,Hs,st,zs,ot,gt,Ze,rt,Xs,cn,Pe,Q,Gs,Ys,Qe,ln,Fn,un,Mt,Vs,re,dn,fn,pn,ue,Zs,mt,Se;function ml(e){return(t=[],n=e.process.cwd(),o)=>{let s=new yl(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var Vc=Symbol("copyDoubleDash"),Zc=Symbol("copyDoubleDash"),Or=Symbol("deleteFromParserHintObject"),Qc=Symbol("emitWarning"),el=Symbol("freeze"),tl=Symbol("getDollarZero"),hn=Symbol("getParserConfiguration"),nl=Symbol("getUsageConfiguration"),vr=Symbol("guessLocale"),sl=Symbol("guessVersion"),ol=Symbol("parsePositionalNumbers"),Lr=Symbol("pkgUp"),Nt=Symbol("populateParserHintArray"),Tn=Symbol("populateParserHintSingleValueDictionary"),Mr=Symbol("populateParserHintArrayDictionary"),Nr=Symbol("populateParserHintDictionary"),Br=Symbol("sanitizeKey"),jr=Symbol("setKey"),Wr=Symbol("unfreeze"),rl=Symbol("validateAsync"),il=Symbol("getCommandInstance"),al=Symbol("getContext"),cl=Symbol("getHasOutput"),ll=Symbol("getLoggerInstance"),ul=Symbol("getParseContext"),dl=Symbol("getUsageInstance"),fl=Symbol("getValidationInstance"),Qs=Symbol("hasParseCallback"),pl=Symbol("isGlobalContext"),gn=Symbol("postProcess"),hl=Symbol("rebase"),Ur=Symbol("reset"),ts=Symbol("runYargsParserAndExecuteCommands"),Kr=Symbol("runValidation"),gl=Symbol("setHasOutput"),mn=Symbol("kTrackManuallySetKeys"),jh="en_US";class yl{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,$e.set(this,void 0),rn.set(this,void 0),es.set(this,{commands:[],fullCommands:[]}),Ke.set(this,null),Ve.set(this,null),qs.set(this,"show-hidden"),Lt.set(this,null),an.set(this,!0),Hs.set(this,{}),st.set(this,!0),zs.set(this,[]),ot.set(this,void 0),gt.set(this,{}),Ze.set(this,!1),rt.set(this,null),Xs.set(this,!0),cn.set(this,void 0),Pe.set(this,""),Q.set(this,void 0),Gs.set(this,void 0),Ys.set(this,{}),Qe.set(this,null),ln.set(this,null),Fn.set(this,{}),un.set(this,{}),Mt.set(this,void 0),Vs.set(this,!1),re.set(this,void 0),dn.set(this,!1),fn.set(this,!1),pn.set(this,!1),ue.set(this,void 0),Zs.set(this,{}),mt.set(this,null),Se.set(this,void 0),V(this,re,o,"f"),V(this,Mt,e,"f"),V(this,rn,t,"f"),V(this,Gs,n,"f"),V(this,ot,new Rr(this),"f"),this.$0=this[tl](),this[Ur](),V(this,$e,y(this,$e,"f"),"f"),V(this,ue,y(this,ue,"f"),"f"),V(this,Se,y(this,Se,"f"),"f"),V(this,Q,y(this,Q,"f"),"f"),y(this,Q,"f").showHiddenOpt=y(this,qs,"f"),V(this,cn,this[Zc](),"f"),y(this,re,"f").y18n.setLocale(jh)}addHelpOpt(e,t){if(Y("[string|boolean] [string]",[e,t],arguments.length),y(this,rt,"f"))this[Or](y(this,rt,"f")),V(this,rt,null,"f");if(e===!1&&t===void 0)return this;return V(this,rt,typeof e==="string"?e:"help","f"),this.boolean(y(this,rt,"f")),this.describe(y(this,rt,"f"),t||y(this,ue,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(Y("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:y(this,qs,"f");return this.boolean(n),this.describe(n,t||y(this,ue,"f").deferY18nLookup("Show hidden options")),y(this,Q,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return Y("<object|string|array> [string|array]",[e,t],arguments.length),this[Mr](this.alias.bind(this),"alias",e,t),this}array(e){return Y("<array|string>",[e],arguments.length),this[Nt]("array",e),this[mn](e),this}boolean(e){return Y("<array|string>",[e],arguments.length),this[Nt]("boolean",e),this[mn](e),this}check(e,t){return Y("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>on(()=>e(n,o.getOptions()),(s)=>{if(!s)y(this,ue,"f").fail(y(this,re,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)y(this,ue,"f").fail(s.toString(),s);return n},(s)=>(y(this,ue,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return Y("<object|string|array> [string|array]",[e,t],arguments.length),this[Mr](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(Y("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new Ce("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 Ce("coerce callback must be provided");let n=e;return y(this,Q,"f").key[n]=!0,y(this,ot,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],a=[n,...i].filter((c)=>Object.prototype.hasOwnProperty.call(o,c));if(a.length===0)return o;return on(()=>t(o[a[0]]),(c)=>(a.forEach((l)=>{o[l]=c}),o),(c)=>{throw new Ce(c.message)})},n),this}conflicts(e,t){return Y("<string|object> [string|array]",[e,t],arguments.length),y(this,Se,"f").conflicts(e,t),this}config(e="config",t,n){if(Y("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=Qn(e,y(this,rn,"f"),this[hn]()["deep-merge-config"]||!1,y(this,re,"f")),y(this,Q,"f").configObjects=(y(this,Q,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||y(this,ue,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{y(this,Q,"f").config[o]=n||!0}),this}completion(e,t,n){if(Y("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(V(this,Ve,e||y(this,Ve,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(y(this,Ve,"f"),t),n)y(this,Ke,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return Y("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),y(this,$e,"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){Y("<string> [object]",[e,t],arguments.length);let n=y(this,Gs,"f")||y(this,re,"f").require;return y(this,$e,"f").addDirectory(e,n,y(this,re,"f").getCallerFile(),t),this}count(e){return Y("<array|string>",[e],arguments.length),this[Nt]("count",e),this[mn](e),this}default(e,t,n){if(Y("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)Tr(e,y(this,re,"f")),y(this,Q,"f").defaultDescription[e]=n;if(typeof t==="function"){if(Tr(e,y(this,re,"f")),!y(this,Q,"f").defaultDescription[e])y(this,Q,"f").defaultDescription[e]=y(this,ue,"f").functionDescription(t);t=t.call()}return this[Tn](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(Y("[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),y(this,Q,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{We(n,!0,y(this,re,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")We(n,!0,y(this,re,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{We(n,!0,y(this,re,"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 Y("<object|string|array> [string]",[e,t],arguments.length),this[Tn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return Y("<string> [string|boolean]",[e,t],arguments.length),y(this,Q,"f").deprecatedOptions[e]=t,this}describe(e,t){return Y("<object|string|array> [string]",[e,t],arguments.length),this[jr](e,!0),y(this,ue,"f").describe(e,t),this}detectLocale(e){return Y("<boolean>",[e],arguments.length),V(this,an,e,"f"),this}env(e){if(Y("[string|boolean]",[e],arguments.length),e===!1)delete y(this,Q,"f").envPrefix;else y(this,Q,"f").envPrefix=e||"";return this}epilogue(e){return Y("<string>",[e],arguments.length),y(this,ue,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(Y("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else y(this,ue,"f").example(e,t);return this}exit(e,t){if(V(this,Ze,!0,"f"),V(this,Lt,t,"f"),y(this,st,"f"))y(this,re,"f").process.exit(e)}exitProcess(e=!0){return Y("[boolean]",[e],arguments.length),V(this,st,e,"f"),this}fail(e){if(Y("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new Ce("Invalid first argument. Expected function or boolean 'false'");return y(this,ue,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(Y("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{y(this,Ke,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return y(this,Ke,"f").getCompletion(e,t)}getDemandedOptions(){return Y([],0),y(this,Q,"f").demandedOptions}getDemandedCommands(){return Y([],0),y(this,Q,"f").demandedCommands}getDeprecatedOptions(){return Y([],0),y(this,Q,"f").deprecatedOptions}getDetectLocale(){return y(this,an,"f")}getExitProcess(){return y(this,st,"f")}getGroups(){return Object.assign({},y(this,gt,"f"),y(this,un,"f"))}getHelp(){if(V(this,Ze,!0,"f"),!y(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[ts](y(this,Mt,"f"),void 0,void 0,0,!0);if(be(t))return t.then(()=>y(this,ue,"f").help())}let e=y(this,$e,"f").runDefaultBuilderOn(this);if(be(e))return e.then(()=>y(this,ue,"f").help())}return Promise.resolve(y(this,ue,"f").help())}getOptions(){return y(this,Q,"f")}getStrict(){return y(this,dn,"f")}getStrictCommands(){return y(this,fn,"f")}getStrictOptions(){return y(this,pn,"f")}global(e,t){if(Y("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)y(this,Q,"f").local=y(this,Q,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!y(this,Q,"f").local.includes(n))y(this,Q,"f").local.push(n)});return this}group(e,t){Y("<string|array> <string>",[e,t],arguments.length);let n=y(this,un,"f")[t]||y(this,gt,"f")[t];if(y(this,un,"f")[t])delete y(this,un,"f")[t];let o={};return y(this,gt,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return Y("<string>",[e],arguments.length),y(this,Q,"f").hiddenOptions.push(e),this}implies(e,t){return Y("<string|object> [number|string|array]",[e,t],arguments.length),y(this,Se,"f").implies(e,t),this}locale(e){if(Y("[string]",[e],arguments.length),e===void 0)return this[vr](),y(this,re,"f").y18n.getLocale();return V(this,an,!1,"f"),y(this,re,"f").y18n.setLocale(e),this}middleware(e,t,n){return y(this,ot,"f").addMiddleware(e,!!t,n)}nargs(e,t){return Y("<string|object|array> [number]",[e,t],arguments.length),this[Tn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return Y("<array|string>",[e],arguments.length),this[Nt]("normalize",e),this}number(e){return Y("<array|string>",[e],arguments.length),this[Nt]("number",e),this[mn](e),this}option(e,t){if(Y("<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[mn](e),y(this,mt,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[Qc](['"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(y(this,Q,"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)y(this,Q,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let s=t.describe||t.description||t.desc,r=y(this,ue,"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(Y("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[el](),typeof e>"u")e=y(this,Mt,"f");if(typeof t==="object")V(this,ln,t,"f"),t=n;if(typeof t==="function")V(this,Qe,t,"f"),t=!1;if(!t)V(this,Mt,e,"f");if(y(this,Qe,"f"))V(this,st,!1,"f");let o=this[ts](e,!!t),s=this.parsed;if(y(this,Ke,"f").setParsed(this.parsed),be(o))return o.then((r)=>{if(y(this,Qe,"f"))y(this,Qe,"f").call(this,y(this,Lt,"f"),r,y(this,Pe,"f"));return r}).catch((r)=>{if(y(this,Qe,"f"))y(this,Qe,"f")(r,this.parsed.argv,y(this,Pe,"f"));throw r}).finally(()=>{this[Wr](),this.parsed=s});else{if(y(this,Qe,"f"))y(this,Qe,"f").call(this,y(this,Lt,"f"),o,y(this,Pe,"f"));this[Wr](),this.parsed=s}return o}parseAsync(e,t,n){let o=this.parse(e,t,n);return!be(o)?Promise.resolve(o):o}parseSync(e,t,n){let o=this.parse(e,t,n);if(be(o))throw new Ce(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return o}parserConfiguration(e){return Y("<object>",[e],arguments.length),V(this,Ys,e,"f"),this}pkgConf(e,t){Y("<string> [string]",[e,t],arguments.length);let n=null,o=this[Lr](t||y(this,rn,"f"));if(o[e]&&typeof o[e]==="object")n=Qn(o[e],t||y(this,rn,"f"),this[hn]()["deep-merge-config"]||!1,y(this,re,"f")),y(this,Q,"f").configObjects=(y(this,Q,"f").configObjects||[]).concat(n);return this}positional(e,t){Y("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=Ot(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let o=y(this,es,"f").fullCommands[y(this,es,"f").fullCommands.length-1],s=o?y(this,$e,"f").cmdToParseOptions(o):{array:[],alias:{},default:{},demand:{}};return $n(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,y(this,ue,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return Y("[boolean]",[e],arguments.length),V(this,Vs,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(Y("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&y(this,Q,"f").narg[e])return this;else this[Tn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return Y("[string] [string]",[e,t],arguments.length),e=e||this.$0,y(this,cn,"f").log(y(this,Ke,"f").generateCompletionScript(e,t||y(this,Ve,"f")||"completion")),this}showHelp(e){if(Y("[string|function]",[e],arguments.length),V(this,Ze,!0,"f"),!y(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[ts](y(this,Mt,"f"),void 0,void 0,0,!0);if(be(n))return n.then(()=>{y(this,ue,"f").showHelp(e)}),this}let t=y(this,$e,"f").runDefaultBuilderOn(this);if(be(t))return t.then(()=>{y(this,ue,"f").showHelp(e)}),this}return y(this,ue,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return Y("[boolean|string] [string]",[e,t],arguments.length),y(this,ue,"f").showHelpOnFail(e,t),this}showVersion(e){return Y("[string|function]",[e],arguments.length),y(this,ue,"f").showVersion(e),this}skipValidation(e){return Y("<array|string>",[e],arguments.length),this[Nt]("skipValidation",e),this}strict(e){return Y("[boolean]",[e],arguments.length),V(this,dn,e!==!1,"f"),this}strictCommands(e){return Y("[boolean]",[e],arguments.length),V(this,fn,e!==!1,"f"),this}strictOptions(e){return Y("[boolean]",[e],arguments.length),V(this,pn,e!==!1,"f"),this}string(e){return Y("<array|string>",[e],arguments.length),this[Nt]("string",e),this[mn](e),this}terminalWidth(){return Y([],0),y(this,re,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return Y("<object>",[e],arguments.length),V(this,an,!1,"f"),y(this,re,"f").y18n.updateLocale(e),this}usage(e,t,n,o){if(Y("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,o],arguments.length),t!==void 0)if(We(e,null,y(this,re,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,o);else throw new Ce(".usage() description must start with $0 if being used as alias for .command()");else return y(this,ue,"f").usage(e),this}usageConfiguration(e){return Y("<object>",[e],arguments.length),V(this,Zs,e,"f"),this}version(e,t,n){if(Y("[boolean|string] [string] [string]",[e,t,n],arguments.length),y(this,mt,"f"))this[Or](y(this,mt,"f")),y(this,ue,"f").version(void 0),V(this,mt,null,"f");if(arguments.length===0)n=this[sl](),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 V(this,mt,typeof e==="string"?e:"version","f"),t=t||y(this,ue,"f").deferY18nLookup("Show version number"),y(this,ue,"f").version(n||void 0),this.boolean(y(this,mt,"f")),this.describe(y(this,mt,"f"),t),this}wrap(e){return Y("<number|null|undefined>",[e],arguments.length),y(this,ue,"f").wrap(e),this}[($e=new WeakMap,rn=new WeakMap,es=new WeakMap,Ke=new WeakMap,Ve=new WeakMap,qs=new WeakMap,Lt=new WeakMap,an=new WeakMap,Hs=new WeakMap,st=new WeakMap,zs=new WeakMap,ot=new WeakMap,gt=new WeakMap,Ze=new WeakMap,rt=new WeakMap,Xs=new WeakMap,cn=new WeakMap,Pe=new WeakMap,Q=new WeakMap,Gs=new WeakMap,Ys=new WeakMap,Qe=new WeakMap,ln=new WeakMap,Fn=new WeakMap,un=new WeakMap,Mt=new WeakMap,Vs=new WeakMap,re=new WeakMap,dn=new WeakMap,fn=new WeakMap,pn=new WeakMap,ue=new WeakMap,Zs=new WeakMap,mt=new WeakMap,Se=new WeakMap,Vc)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[Zc](){return{log:(...e)=>{if(!this[Qs]())console.log(...e);if(V(this,Ze,!0,"f"),y(this,Pe,"f").length)V(this,Pe,y(this,Pe,"f")+`
80
- `,"f");V(this,Pe,y(this,Pe,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[Qs]())console.error(...e);if(V(this,Ze,!0,"f"),y(this,Pe,"f").length)V(this,Pe,y(this,Pe,"f")+`
81
- `,"f");V(this,Pe,y(this,Pe,"f")+e.join(" "),"f")}}}[Or](e){$n(y(this,Q,"f")).forEach((t)=>{if(((o)=>o==="configObjects")(t))return;let n=y(this,Q,"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 y(this,ue,"f").getDescriptions()[e]}[Qc](e,t,n){if(!y(this,Hs,"f")[n])y(this,re,"f").process.emitWarning(e,t),y(this,Hs,"f")[n]=!0}[el](){y(this,zs,"f").push({options:y(this,Q,"f"),configObjects:y(this,Q,"f").configObjects.slice(0),exitProcess:y(this,st,"f"),groups:y(this,gt,"f"),strict:y(this,dn,"f"),strictCommands:y(this,fn,"f"),strictOptions:y(this,pn,"f"),completionCommand:y(this,Ve,"f"),output:y(this,Pe,"f"),exitError:y(this,Lt,"f"),hasOutput:y(this,Ze,"f"),parsed:this.parsed,parseFn:y(this,Qe,"f"),parseContext:y(this,ln,"f")}),y(this,ue,"f").freeze(),y(this,Se,"f").freeze(),y(this,$e,"f").freeze(),y(this,ot,"f").freeze()}[tl](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(y(this,re,"f").process.argv()[0]))t=y(this,re,"f").process.argv().slice(1,2);else t=y(this,re,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let o=this[hl](y(this,rn,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&o.length<n.length?o:n}).join(" ").trim(),y(this,re,"f").getEnv("_")&&y(this,re,"f").getProcessArgvBin()===y(this,re,"f").getEnv("_"))e=y(this,re,"f").getEnv("_").replace(`${y(this,re,"f").path.dirname(y(this,re,"f").process.execPath())}/`,"");return e}[hn](){return y(this,Ys,"f")}[nl](){return y(this,Zs,"f")}[vr](){if(!y(this,an,"f"))return;let e=y(this,re,"f").getEnv("LC_ALL")||y(this,re,"f").getEnv("LC_MESSAGES")||y(this,re,"f").getEnv("LANG")||y(this,re,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[sl](){return this[Lr]().version||"unknown"}[ol](e){let t=e["--"]?e["--"]:e._;for(let n=0,o;(o=t[n])!==void 0;n++)if(y(this,re,"f").Parser.looksLikeNumber(o)&&Number.isSafeInteger(Math.floor(parseFloat(`${o}`))))t[n]=Number(o);return e}[Lr](e){let t=e||"*";if(y(this,Fn,"f")[t])return y(this,Fn,"f")[t];let n={};try{let o=e||y(this,re,"f").mainFilename;if(y(this,re,"f").path.extname(o))o=y(this,re,"f").path.dirname(o);let s=y(this,re,"f").findUp(o,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});We(s,void 0,y(this,re,"f")),n=JSON.parse(y(this,re,"f").readFileSync(s,"utf8"))}catch(o){}return y(this,Fn,"f")[t]=n||{},y(this,Fn,"f")[t]}[Nt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[Br](n),y(this,Q,"f")[e].push(n)})}[Tn](e,t,n,o){this[Nr](e,t,n,o,(s,r,i)=>{y(this,Q,"f")[s][r]=i})}[Mr](e,t,n,o){this[Nr](e,t,n,o,(s,r,i)=>{y(this,Q,"f")[s][r]=(y(this,Q,"f")[s][r]||[]).concat(i)})}[Nr](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 $n(n))e(r,n[r]);else s(t,this[Br](n),o)}[Br](e){if(e==="__proto__")return"___proto___";return e}[jr](e,t){return this[Tn](this[jr].bind(this),"key",e,t),this}[Wr](){var e,t,n,o,s,r,i,a,c,l,u,d;let f=y(this,zs,"f").pop();We(f,void 0,y(this,re,"f"));let h;e=this,t=this,n=this,o=this,s=this,r=this,i=this,a=this,c=this,l=this,u=this,d=this,{options:{set value(g){V(e,Q,g,"f")}}.value,configObjects:h,exitProcess:{set value(g){V(t,st,g,"f")}}.value,groups:{set value(g){V(n,gt,g,"f")}}.value,output:{set value(g){V(o,Pe,g,"f")}}.value,exitError:{set value(g){V(s,Lt,g,"f")}}.value,hasOutput:{set value(g){V(r,Ze,g,"f")}}.value,parsed:this.parsed,strict:{set value(g){V(i,dn,g,"f")}}.value,strictCommands:{set value(g){V(a,fn,g,"f")}}.value,strictOptions:{set value(g){V(c,pn,g,"f")}}.value,completionCommand:{set value(g){V(l,Ve,g,"f")}}.value,parseFn:{set value(g){V(u,Qe,g,"f")}}.value,parseContext:{set value(g){V(d,ln,g,"f")}}.value}=f,y(this,Q,"f").configObjects=h,y(this,ue,"f").unfreeze(),y(this,Se,"f").unfreeze(),y(this,$e,"f").unfreeze(),y(this,ot,"f").unfreeze()}[rl](e,t){return on(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[il].bind(this),getContext:this[al].bind(this),getHasOutput:this[cl].bind(this),getLoggerInstance:this[ll].bind(this),getParseContext:this[ul].bind(this),getParserConfiguration:this[hn].bind(this),getUsageConfiguration:this[nl].bind(this),getUsageInstance:this[dl].bind(this),getValidationInstance:this[fl].bind(this),hasParseCallback:this[Qs].bind(this),isGlobalContext:this[pl].bind(this),postProcess:this[gn].bind(this),reset:this[Ur].bind(this),runValidation:this[Kr].bind(this),runYargsParserAndExecuteCommands:this[ts].bind(this),setHasOutput:this[gl].bind(this)}}[il](){return y(this,$e,"f")}[al](){return y(this,es,"f")}[cl](){return y(this,Ze,"f")}[ll](){return y(this,cn,"f")}[ul](){return y(this,ln,"f")||{}}[dl](){return y(this,ue,"f")}[fl](){return y(this,Se,"f")}[Qs](){return!!y(this,Qe,"f")}[pl](){return y(this,Xs,"f")}[gn](e,t,n,o){if(n)return e;if(be(e))return e;if(!t)e=this[Vc](e);if(this[hn]()["parse-positional-numbers"]||this[hn]()["parse-positional-numbers"]===void 0)e=this[ol](e);if(o)e=sn(e,this,y(this,ot,"f").getMiddleware(),!1);return e}[Ur](e={}){V(this,Q,y(this,Q,"f")||{},"f");let t={};t.local=y(this,Q,"f").local||[],t.configObjects=y(this,Q,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(y(this,un,"f"),Object.keys(y(this,gt,"f")).reduce((r,i)=>{let a=y(this,gt,"f")[i].filter((c)=>!(c in n));if(a.length>0)r[i]=a;return r},{})),V(this,gt,{},"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]=(y(this,Q,"f")[r]||[]).filter((i)=>!n[i])}),s.forEach((r)=>{t[r]=Ot(y(this,Q,"f")[r],(i)=>!n[i])}),t.envPrefix=y(this,Q,"f").envPrefix,V(this,Q,t,"f"),V(this,ue,y(this,ue,"f")?y(this,ue,"f").reset(n):Uc(this,y(this,re,"f")),"f"),V(this,Se,y(this,Se,"f")?y(this,Se,"f").reset(n):Gc(this,y(this,ue,"f"),y(this,re,"f")),"f"),V(this,$e,y(this,$e,"f")?y(this,$e,"f").reset():Bc(y(this,ue,"f"),y(this,Se,"f"),y(this,ot,"f"),y(this,re,"f")),"f"),!y(this,Ke,"f"))V(this,Ke,Hc(this,y(this,ue,"f"),y(this,$e,"f"),y(this,re,"f")),"f");return y(this,ot,"f").reset(),V(this,Ve,null,"f"),V(this,Pe,"","f"),V(this,Lt,null,"f"),V(this,Ze,!1,"f"),this.parsed=!1,this}[hl](e,t){return y(this,re,"f").path.relative(e,t)}[ts](e,t,n,o=0,s=!1){var r,i,a,c;let l=!!n||s;e=e||y(this,Mt,"f"),y(this,Q,"f").__=y(this,re,"f").y18n.__,y(this,Q,"f").configuration=this[hn]();let u=!!y(this,Q,"f").configuration["populate--"],d=Object.assign({},y(this,Q,"f").configuration,{"populate--":!0}),f=y(this,re,"f").Parser.detailed(e,Object.assign({},y(this,Q,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),h=Object.assign(f.argv,y(this,ln,"f")),g=void 0,p=f.aliases,m=!1,w=!1;if(Object.keys(h).forEach((b)=>{if(b===y(this,rt,"f")&&h[b])m=!0;else if(b===y(this,mt,"f")&&h[b])w=!0}),h.$0=this.$0,this.parsed=f,o===0)y(this,ue,"f").clearCachedHelpMessage();try{if(this[vr](),t)return this[gn](h,u,!!n,!1);if(y(this,rt,"f")){if([y(this,rt,"f")].concat(p[y(this,rt,"f")]||[]).filter((A)=>A.length>1).includes(""+h._[h._.length-1]))h._.pop(),m=!0}V(this,Xs,!1,"f");let b=y(this,$e,"f").getCommands(),D=((r=y(this,Ke,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=y(this,Ke,"f"))===null||i===void 0?void 0:i.completionKey,...(c=this.getAliases()[(a=y(this,Ke,"f"))===null||a===void 0?void 0:a.completionKey])!==null&&c!==void 0?c:[]].some((F)=>Object.prototype.hasOwnProperty.call(h,F)):!1,S=m||D||s;if(h._.length){if(b.length){let F;for(let A=o||0,C;h._[A]!==void 0;A++)if(C=String(h._[A]),b.includes(C)&&C!==y(this,Ve,"f")){let x=y(this,$e,"f").runCommand(C,this,f,A+1,s,m||w||s);return this[gn](x,u,!!n,!1)}else if(!F&&C!==y(this,Ve,"f")){F=C;break}if(!y(this,$e,"f").hasDefaultCommand()&&y(this,Vs,"f")&&F&&!S)y(this,Se,"f").recommendCommands(F,b)}if(y(this,Ve,"f")&&h._.includes(y(this,Ve,"f"))&&!D){if(y(this,st,"f"))vt(!0);this.showCompletionScript(),this.exit(0)}}if(y(this,$e,"f").hasDefaultCommand()&&!S){let F=y(this,$e,"f").runCommand(null,this,f,0,s,m||w||s);return this[gn](F,u,!!n,!1)}if(D){if(y(this,st,"f"))vt(!0);e=[].concat(e);let F=e.slice(e.indexOf(`--${y(this,Ke,"f").completionKey}`)+1);return y(this,Ke,"f").getCompletion(F,(A,C)=>{if(A)throw new Ce(A.message);(C||[]).forEach((x)=>{y(this,cn,"f").log(x)}),this.exit(0)}),this[gn](h,!u,!!n,!1)}if(!y(this,Ze,"f")){if(m){if(y(this,st,"f"))vt(!0);l=!0,this.showHelp((F)=>{y(this,cn,"f").log(F),this.exit(0)})}else if(w){if(y(this,st,"f"))vt(!0);l=!0,y(this,ue,"f").showVersion("log"),this.exit(0)}}if(!l&&y(this,Q,"f").skipValidation.length>0)l=Object.keys(h).some((F)=>y(this,Q,"f").skipValidation.indexOf(F)>=0&&h[F]===!0);if(!l){if(f.error)throw new Ce(f.error.message);if(!D){let F=this[Kr](p,{},f.error);if(!n)g=sn(h,this,y(this,ot,"f").getMiddleware(),!0);if(g=this[rl](F,g!==null&&g!==void 0?g:h),be(g)&&!n)g=g.then(()=>sn(h,this,y(this,ot,"f").getMiddleware(),!1))}}}catch(b){if(b instanceof Ce)y(this,ue,"f").fail(b.message,b);else throw b}return this[gn](g!==null&&g!==void 0?g:h,u,!!n,!0)}[Kr](e,t,n,o){let s={...this.getDemandedOptions()};return(r)=>{if(n)throw new Ce(n.message);y(this,Se,"f").nonOptionCount(r),y(this,Se,"f").requiredArguments(r,s);let i=!1;if(y(this,fn,"f"))i=y(this,Se,"f").unknownCommands(r);if(y(this,dn,"f")&&!i)y(this,Se,"f").unknownArguments(r,e,t,!!o);else if(y(this,pn,"f"))y(this,Se,"f").unknownArguments(r,e,{},!1,!1);y(this,Se,"f").limitedChoices(r),y(this,Se,"f").implications(r),y(this,Se,"f").conflicting(r)}}[gl](){V(this,Ze,!0,"f")}[mn](e){if(typeof e==="string")y(this,Q,"f").key[e]=!0;else for(let t of e)y(this,Q,"f").key[t]=!0}}function jc(e){return!!e&&typeof e.getInternalMethods==="function"}var Wh=ml(Fr),wl=Wh;var Uh=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,Kh=/[\t\n\v\f\r (*_~]/;function Jh(e){let t=e.split(""),n=(s,r)=>{for(let i=s;i<r;i++)if(t[i]!==`
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,g,p=!0){var m;let w=e.getInternalMethods().getCommandInstance().getCommands(),b=[],D=e.getInternalMethods().getContext();if(Object.keys(d).forEach((S)=>{if(!sl.includes(S)&&!Object.prototype.hasOwnProperty.call(h,S)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),S)&&!r.isValidAndSomeAliasIsNotNew(S,f))b.push(S)}),p&&(D.commands.length>0||w.length>0||g))d._.slice(D.commands.length).forEach((S)=>{if(!w.includes(""+S))b.push(""+S)});if(p){let A=((m=e.getDemandedCommands()._)===null||m===void 0?void 0:m.max)||0,F=D.commands.length+A;if(F<d._.length)d._.slice(F).forEach((E)=>{if(E=String(E),!D.commands.includes(E)&&!b.includes(E))b.push(E)})}if(b.length)t.fail(s("Unknown argument: %s","Unknown arguments: %s",b.length,b.map((S)=>S.trim()?S:`"${S}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),h=[],g=e.getInternalMethods().getContext();if(g.commands.length>0||f.length>0)d._.slice(g.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((g)=>!Object.prototype.hasOwnProperty.call(h,g)||!h[d])},r.limitedChoices=function(d){let f=e.getOptions(),h={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((m)=>{if(sl.indexOf(m)===-1&&Object.prototype.hasOwnProperty.call(f.choices,m))[].concat(d[m]).forEach((w)=>{if(f.choices[m].indexOf(w)===-1&&w!==void 0)h[m]=(h[m]||[]).concat(w)})});let g=Object.keys(h);if(!g.length)return;let p=o("Invalid values:");g.forEach((m)=>{p+=`
77
+ ${o("Argument: %s, Given: %s, Choices: %s",m,t.stringifiedValues(h[m]),t.stringifiedValues(f.choices[m]))}`}),t.fail(p)};let i={};r.implies=function(d,f){if(Y("<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 Ue(f,void 0,n),i[d].push(f)}},r.getImplied=function(){return i};function a(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 g=h;(i[h]||[]).forEach((p)=>{let m=g,w=p;if(m=a(d,m),p=a(d,p),m&&!p)f.push(` ${g} -> ${w}`)})}),f.length){let h=`${o("Implications failed:")}
78
+ `;f.forEach((g)=>{h+=g}),t.fail(h)}};let c={};r.conflicts=function(d,f){if(Y("<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),!c[d])c[d]=[];if(Array.isArray(f))f.forEach((h)=>r.conflicts(d,h));else c[d].push(f)}},r.getConflicting=()=>c,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(c[f])c[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(c).forEach((f)=>{c[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((m,w)=>w.length-m.length);let g=null,p=1/0;for(let m=0,w;(w=f[m])!==void 0;m++){let b=nl(d,w);if(b<=3&&b<p)p=b,g=w}if(g)t.fail(o("Did you mean %s?",g))},r.reset=function(d){return i=Mt(i,(f)=>!d[f]),c=Mt(c,(f)=>!d[f]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:c})},r.unfreeze=function(){let d=l.pop();Ue(d,void 0,n),{implied:i,conflicting:c}=d},r}var Mr=[],es;function ts(e,t,n,o){es=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(a){return e}else i=Vh(t,e.extends);Yh(i),Mr.push(i),s=r?JSON.parse(es.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=ts(s,es.path.dirname(i),n,es)}return Mr=[],n?rl(s,e):Object.assign({},s,e)}function Yh(e){if(Mr.indexOf(e)>-1)throw new $e(`Circular extended configurations: '${e}'.`)}function Vh(e,t){return es.path.resolve(e,t)}function rl(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]=rl(e[s],t[s]);else n[s]=t[s];return n}var V=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},y=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)},Ce,rn,ns,Je,Ve,zs,Bt,an,Xs,st,Gs,ot,mt,Ze,rt,Ys,cn,Pe,ee,Vs,Zs,Qe,ln,Tn,un,jt,Qs,ie,dn,fn,pn,ue,eo,yt,Ee;function _l(e){return(t=[],n=e.process.cwd(),o)=>{let s=new $l(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var il=Symbol("copyDoubleDash"),al=Symbol("copyDoubleDash"),Nr=Symbol("deleteFromParserHintObject"),cl=Symbol("emitWarning"),ll=Symbol("freeze"),ul=Symbol("getDollarZero"),hn=Symbol("getParserConfiguration"),dl=Symbol("getUsageConfiguration"),Br=Symbol("guessLocale"),fl=Symbol("guessVersion"),pl=Symbol("parsePositionalNumbers"),jr=Symbol("pkgUp"),Wt=Symbol("populateParserHintArray"),Rn=Symbol("populateParserHintSingleValueDictionary"),Wr=Symbol("populateParserHintArrayDictionary"),Ur=Symbol("populateParserHintDictionary"),Jr=Symbol("sanitizeKey"),Kr=Symbol("setKey"),qr=Symbol("unfreeze"),hl=Symbol("validateAsync"),gl=Symbol("getCommandInstance"),ml=Symbol("getContext"),yl=Symbol("getHasOutput"),wl=Symbol("getLoggerInstance"),bl=Symbol("getParseContext"),Dl=Symbol("getUsageInstance"),kl=Symbol("getValidationInstance"),to=Symbol("hasParseCallback"),xl=Symbol("isGlobalContext"),gn=Symbol("postProcess"),Sl=Symbol("rebase"),Hr=Symbol("reset"),ss=Symbol("runYargsParserAndExecuteCommands"),zr=Symbol("runValidation"),El=Symbol("setHasOutput"),mn=Symbol("kTrackManuallySetKeys"),Zh="en_US";class $l{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,Ce.set(this,void 0),rn.set(this,void 0),ns.set(this,{commands:[],fullCommands:[]}),Je.set(this,null),Ve.set(this,null),zs.set(this,"show-hidden"),Bt.set(this,null),an.set(this,!0),Xs.set(this,{}),st.set(this,!0),Gs.set(this,[]),ot.set(this,void 0),mt.set(this,{}),Ze.set(this,!1),rt.set(this,null),Ys.set(this,!0),cn.set(this,void 0),Pe.set(this,""),ee.set(this,void 0),Vs.set(this,void 0),Zs.set(this,{}),Qe.set(this,null),ln.set(this,null),Tn.set(this,{}),un.set(this,{}),jt.set(this,void 0),Qs.set(this,!1),ie.set(this,void 0),dn.set(this,!1),fn.set(this,!1),pn.set(this,!1),ue.set(this,void 0),eo.set(this,{}),yt.set(this,null),Ee.set(this,void 0),V(this,ie,o,"f"),V(this,jt,e,"f"),V(this,rn,t,"f"),V(this,Vs,n,"f"),V(this,ot,new vr(this),"f"),this.$0=this[ul](),this[Hr](),V(this,Ce,y(this,Ce,"f"),"f"),V(this,ue,y(this,ue,"f"),"f"),V(this,Ee,y(this,Ee,"f"),"f"),V(this,ee,y(this,ee,"f"),"f"),y(this,ee,"f").showHiddenOpt=y(this,zs,"f"),V(this,cn,this[al](),"f"),y(this,ie,"f").y18n.setLocale(Zh)}addHelpOpt(e,t){if(Y("[string|boolean] [string]",[e,t],arguments.length),y(this,rt,"f"))this[Nr](y(this,rt,"f")),V(this,rt,null,"f");if(e===!1&&t===void 0)return this;return V(this,rt,typeof e==="string"?e:"help","f"),this.boolean(y(this,rt,"f")),this.describe(y(this,rt,"f"),t||y(this,ue,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(Y("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:y(this,zs,"f");return this.boolean(n),this.describe(n,t||y(this,ue,"f").deferY18nLookup("Show hidden options")),y(this,ee,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return Y("<object|string|array> [string|array]",[e,t],arguments.length),this[Wr](this.alias.bind(this),"alias",e,t),this}array(e){return Y("<array|string>",[e],arguments.length),this[Wt]("array",e),this[mn](e),this}boolean(e){return Y("<array|string>",[e],arguments.length),this[Wt]("boolean",e),this[mn](e),this}check(e,t){return Y("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>on(()=>e(n,o.getOptions()),(s)=>{if(!s)y(this,ue,"f").fail(y(this,ie,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)y(this,ue,"f").fail(s.toString(),s);return n},(s)=>(y(this,ue,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return Y("<object|string|array> [string|array]",[e,t],arguments.length),this[Wr](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(Y("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new $e("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 $e("coerce callback must be provided");let n=e;return y(this,ee,"f").key[n]=!0,y(this,ot,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],a=[n,...i].filter((c)=>Object.prototype.hasOwnProperty.call(o,c));if(a.length===0)return o;return on(()=>t(o[a[0]]),(c)=>(a.forEach((l)=>{o[l]=c}),o),(c)=>{throw new $e(c.message)})},n),this}conflicts(e,t){return Y("<string|object> [string|array]",[e,t],arguments.length),y(this,Ee,"f").conflicts(e,t),this}config(e="config",t,n){if(Y("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=ts(e,y(this,rn,"f"),this[hn]()["deep-merge-config"]||!1,y(this,ie,"f")),y(this,ee,"f").configObjects=(y(this,ee,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||y(this,ue,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{y(this,ee,"f").config[o]=n||!0}),this}completion(e,t,n){if(Y("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(V(this,Ve,e||y(this,Ve,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(y(this,Ve,"f"),t),n)y(this,Je,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return Y("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),y(this,Ce,"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){Y("<string> [object]",[e,t],arguments.length);let n=y(this,Vs,"f")||y(this,ie,"f").require;return y(this,Ce,"f").addDirectory(e,n,y(this,ie,"f").getCallerFile(),t),this}count(e){return Y("<array|string>",[e],arguments.length),this[Wt]("count",e),this[mn](e),this}default(e,t,n){if(Y("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)Pr(e,y(this,ie,"f")),y(this,ee,"f").defaultDescription[e]=n;if(typeof t==="function"){if(Pr(e,y(this,ie,"f")),!y(this,ee,"f").defaultDescription[e])y(this,ee,"f").defaultDescription[e]=y(this,ue,"f").functionDescription(t);t=t.call()}return this[Rn](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(Y("[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),y(this,ee,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{Ue(n,!0,y(this,ie,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")Ue(n,!0,y(this,ie,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{Ue(n,!0,y(this,ie,"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 Y("<object|string|array> [string]",[e,t],arguments.length),this[Rn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return Y("<string> [string|boolean]",[e,t],arguments.length),y(this,ee,"f").deprecatedOptions[e]=t,this}describe(e,t){return Y("<object|string|array> [string]",[e,t],arguments.length),this[Kr](e,!0),y(this,ue,"f").describe(e,t),this}detectLocale(e){return Y("<boolean>",[e],arguments.length),V(this,an,e,"f"),this}env(e){if(Y("[string|boolean]",[e],arguments.length),e===!1)delete y(this,ee,"f").envPrefix;else y(this,ee,"f").envPrefix=e||"";return this}epilogue(e){return Y("<string>",[e],arguments.length),y(this,ue,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(Y("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else y(this,ue,"f").example(e,t);return this}exit(e,t){if(V(this,Ze,!0,"f"),V(this,Bt,t,"f"),y(this,st,"f"))y(this,ie,"f").process.exit(e)}exitProcess(e=!0){return Y("[boolean]",[e],arguments.length),V(this,st,e,"f"),this}fail(e){if(Y("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new $e("Invalid first argument. Expected function or boolean 'false'");return y(this,ue,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(Y("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{y(this,Je,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return y(this,Je,"f").getCompletion(e,t)}getDemandedOptions(){return Y([],0),y(this,ee,"f").demandedOptions}getDemandedCommands(){return Y([],0),y(this,ee,"f").demandedCommands}getDeprecatedOptions(){return Y([],0),y(this,ee,"f").deprecatedOptions}getDetectLocale(){return y(this,an,"f")}getExitProcess(){return y(this,st,"f")}getGroups(){return Object.assign({},y(this,mt,"f"),y(this,un,"f"))}getHelp(){if(V(this,Ze,!0,"f"),!y(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[ss](y(this,jt,"f"),void 0,void 0,0,!0);if(be(t))return t.then(()=>y(this,ue,"f").help())}let e=y(this,Ce,"f").runDefaultBuilderOn(this);if(be(e))return e.then(()=>y(this,ue,"f").help())}return Promise.resolve(y(this,ue,"f").help())}getOptions(){return y(this,ee,"f")}getStrict(){return y(this,dn,"f")}getStrictCommands(){return y(this,fn,"f")}getStrictOptions(){return y(this,pn,"f")}global(e,t){if(Y("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)y(this,ee,"f").local=y(this,ee,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!y(this,ee,"f").local.includes(n))y(this,ee,"f").local.push(n)});return this}group(e,t){Y("<string|array> <string>",[e,t],arguments.length);let n=y(this,un,"f")[t]||y(this,mt,"f")[t];if(y(this,un,"f")[t])delete y(this,un,"f")[t];let o={};return y(this,mt,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return Y("<string>",[e],arguments.length),y(this,ee,"f").hiddenOptions.push(e),this}implies(e,t){return Y("<string|object> [number|string|array]",[e,t],arguments.length),y(this,Ee,"f").implies(e,t),this}locale(e){if(Y("[string]",[e],arguments.length),e===void 0)return this[Br](),y(this,ie,"f").y18n.getLocale();return V(this,an,!1,"f"),y(this,ie,"f").y18n.setLocale(e),this}middleware(e,t,n){return y(this,ot,"f").addMiddleware(e,!!t,n)}nargs(e,t){return Y("<string|object|array> [number]",[e,t],arguments.length),this[Rn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return Y("<array|string>",[e],arguments.length),this[Wt]("normalize",e),this}number(e){return Y("<array|string>",[e],arguments.length),this[Wt]("number",e),this[mn](e),this}option(e,t){if(Y("<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[mn](e),y(this,yt,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[cl](['"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(y(this,ee,"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)y(this,ee,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let s=t.describe||t.description||t.desc,r=y(this,ue,"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(Y("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[ll](),typeof e>"u")e=y(this,jt,"f");if(typeof t==="object")V(this,ln,t,"f"),t=n;if(typeof t==="function")V(this,Qe,t,"f"),t=!1;if(!t)V(this,jt,e,"f");if(y(this,Qe,"f"))V(this,st,!1,"f");let o=this[ss](e,!!t),s=this.parsed;if(y(this,Je,"f").setParsed(this.parsed),be(o))return o.then((r)=>{if(y(this,Qe,"f"))y(this,Qe,"f").call(this,y(this,Bt,"f"),r,y(this,Pe,"f"));return r}).catch((r)=>{if(y(this,Qe,"f"))y(this,Qe,"f")(r,this.parsed.argv,y(this,Pe,"f"));throw r}).finally(()=>{this[qr](),this.parsed=s});else{if(y(this,Qe,"f"))y(this,Qe,"f").call(this,y(this,Bt,"f"),o,y(this,Pe,"f"));this[qr](),this.parsed=s}return o}parseAsync(e,t,n){let o=this.parse(e,t,n);return!be(o)?Promise.resolve(o):o}parseSync(e,t,n){let o=this.parse(e,t,n);if(be(o))throw new $e(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return o}parserConfiguration(e){return Y("<object>",[e],arguments.length),V(this,Zs,e,"f"),this}pkgConf(e,t){Y("<string> [string]",[e,t],arguments.length);let n=null,o=this[jr](t||y(this,rn,"f"));if(o[e]&&typeof o[e]==="object")n=ts(o[e],t||y(this,rn,"f"),this[hn]()["deep-merge-config"]||!1,y(this,ie,"f")),y(this,ee,"f").configObjects=(y(this,ee,"f").configObjects||[]).concat(n);return this}positional(e,t){Y("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=Mt(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let o=y(this,ns,"f").fullCommands[y(this,ns,"f").fullCommands.length-1],s=o?y(this,Ce,"f").cmdToParseOptions(o):{array:[],alias:{},default:{},demand:{}};return An(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,y(this,ue,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return Y("[boolean]",[e],arguments.length),V(this,Qs,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(Y("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&y(this,ee,"f").narg[e])return this;else this[Rn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return Y("[string] [string]",[e,t],arguments.length),e=e||this.$0,y(this,cn,"f").log(y(this,Je,"f").generateCompletionScript(e,t||y(this,Ve,"f")||"completion")),this}showHelp(e){if(Y("[string|function]",[e],arguments.length),V(this,Ze,!0,"f"),!y(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[ss](y(this,jt,"f"),void 0,void 0,0,!0);if(be(n))return n.then(()=>{y(this,ue,"f").showHelp(e)}),this}let t=y(this,Ce,"f").runDefaultBuilderOn(this);if(be(t))return t.then(()=>{y(this,ue,"f").showHelp(e)}),this}return y(this,ue,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return Y("[boolean|string] [string]",[e,t],arguments.length),y(this,ue,"f").showHelpOnFail(e,t),this}showVersion(e){return Y("[string|function]",[e],arguments.length),y(this,ue,"f").showVersion(e),this}skipValidation(e){return Y("<array|string>",[e],arguments.length),this[Wt]("skipValidation",e),this}strict(e){return Y("[boolean]",[e],arguments.length),V(this,dn,e!==!1,"f"),this}strictCommands(e){return Y("[boolean]",[e],arguments.length),V(this,fn,e!==!1,"f"),this}strictOptions(e){return Y("[boolean]",[e],arguments.length),V(this,pn,e!==!1,"f"),this}string(e){return Y("<array|string>",[e],arguments.length),this[Wt]("string",e),this[mn](e),this}terminalWidth(){return Y([],0),y(this,ie,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return Y("<object>",[e],arguments.length),V(this,an,!1,"f"),y(this,ie,"f").y18n.updateLocale(e),this}usage(e,t,n,o){if(Y("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,o],arguments.length),t!==void 0)if(Ue(e,null,y(this,ie,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,o);else throw new $e(".usage() description must start with $0 if being used as alias for .command()");else return y(this,ue,"f").usage(e),this}usageConfiguration(e){return Y("<object>",[e],arguments.length),V(this,eo,e,"f"),this}version(e,t,n){if(Y("[boolean|string] [string] [string]",[e,t,n],arguments.length),y(this,yt,"f"))this[Nr](y(this,yt,"f")),y(this,ue,"f").version(void 0),V(this,yt,null,"f");if(arguments.length===0)n=this[fl](),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 V(this,yt,typeof e==="string"?e:"version","f"),t=t||y(this,ue,"f").deferY18nLookup("Show version number"),y(this,ue,"f").version(n||void 0),this.boolean(y(this,yt,"f")),this.describe(y(this,yt,"f"),t),this}wrap(e){return Y("<number|null|undefined>",[e],arguments.length),y(this,ue,"f").wrap(e),this}[(Ce=new WeakMap,rn=new WeakMap,ns=new WeakMap,Je=new WeakMap,Ve=new WeakMap,zs=new WeakMap,Bt=new WeakMap,an=new WeakMap,Xs=new WeakMap,st=new WeakMap,Gs=new WeakMap,ot=new WeakMap,mt=new WeakMap,Ze=new WeakMap,rt=new WeakMap,Ys=new WeakMap,cn=new WeakMap,Pe=new WeakMap,ee=new WeakMap,Vs=new WeakMap,Zs=new WeakMap,Qe=new WeakMap,ln=new WeakMap,Tn=new WeakMap,un=new WeakMap,jt=new WeakMap,Qs=new WeakMap,ie=new WeakMap,dn=new WeakMap,fn=new WeakMap,pn=new WeakMap,ue=new WeakMap,eo=new WeakMap,yt=new WeakMap,Ee=new WeakMap,il)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[al](){return{log:(...e)=>{if(!this[to]())console.log(...e);if(V(this,Ze,!0,"f"),y(this,Pe,"f").length)V(this,Pe,y(this,Pe,"f")+`
80
+ `,"f");V(this,Pe,y(this,Pe,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[to]())console.error(...e);if(V(this,Ze,!0,"f"),y(this,Pe,"f").length)V(this,Pe,y(this,Pe,"f")+`
81
+ `,"f");V(this,Pe,y(this,Pe,"f")+e.join(" "),"f")}}}[Nr](e){An(y(this,ee,"f")).forEach((t)=>{if(((o)=>o==="configObjects")(t))return;let n=y(this,ee,"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 y(this,ue,"f").getDescriptions()[e]}[cl](e,t,n){if(!y(this,Xs,"f")[n])y(this,ie,"f").process.emitWarning(e,t),y(this,Xs,"f")[n]=!0}[ll](){y(this,Gs,"f").push({options:y(this,ee,"f"),configObjects:y(this,ee,"f").configObjects.slice(0),exitProcess:y(this,st,"f"),groups:y(this,mt,"f"),strict:y(this,dn,"f"),strictCommands:y(this,fn,"f"),strictOptions:y(this,pn,"f"),completionCommand:y(this,Ve,"f"),output:y(this,Pe,"f"),exitError:y(this,Bt,"f"),hasOutput:y(this,Ze,"f"),parsed:this.parsed,parseFn:y(this,Qe,"f"),parseContext:y(this,ln,"f")}),y(this,ue,"f").freeze(),y(this,Ee,"f").freeze(),y(this,Ce,"f").freeze(),y(this,ot,"f").freeze()}[ul](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(y(this,ie,"f").process.argv()[0]))t=y(this,ie,"f").process.argv().slice(1,2);else t=y(this,ie,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let o=this[Sl](y(this,rn,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&o.length<n.length?o:n}).join(" ").trim(),y(this,ie,"f").getEnv("_")&&y(this,ie,"f").getProcessArgvBin()===y(this,ie,"f").getEnv("_"))e=y(this,ie,"f").getEnv("_").replace(`${y(this,ie,"f").path.dirname(y(this,ie,"f").process.execPath())}/`,"");return e}[hn](){return y(this,Zs,"f")}[dl](){return y(this,eo,"f")}[Br](){if(!y(this,an,"f"))return;let e=y(this,ie,"f").getEnv("LC_ALL")||y(this,ie,"f").getEnv("LC_MESSAGES")||y(this,ie,"f").getEnv("LANG")||y(this,ie,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[fl](){return this[jr]().version||"unknown"}[pl](e){let t=e["--"]?e["--"]:e._;for(let n=0,o;(o=t[n])!==void 0;n++)if(y(this,ie,"f").Parser.looksLikeNumber(o)&&Number.isSafeInteger(Math.floor(parseFloat(`${o}`))))t[n]=Number(o);return e}[jr](e){let t=e||"*";if(y(this,Tn,"f")[t])return y(this,Tn,"f")[t];let n={};try{let o=e||y(this,ie,"f").mainFilename;if(y(this,ie,"f").path.extname(o))o=y(this,ie,"f").path.dirname(o);let s=y(this,ie,"f").findUp(o,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});Ue(s,void 0,y(this,ie,"f")),n=JSON.parse(y(this,ie,"f").readFileSync(s,"utf8"))}catch(o){}return y(this,Tn,"f")[t]=n||{},y(this,Tn,"f")[t]}[Wt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[Jr](n),y(this,ee,"f")[e].push(n)})}[Rn](e,t,n,o){this[Ur](e,t,n,o,(s,r,i)=>{y(this,ee,"f")[s][r]=i})}[Wr](e,t,n,o){this[Ur](e,t,n,o,(s,r,i)=>{y(this,ee,"f")[s][r]=(y(this,ee,"f")[s][r]||[]).concat(i)})}[Ur](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 An(n))e(r,n[r]);else s(t,this[Jr](n),o)}[Jr](e){if(e==="__proto__")return"___proto___";return e}[Kr](e,t){return this[Rn](this[Kr].bind(this),"key",e,t),this}[qr](){var e,t,n,o,s,r,i,a,c,l,u,d;let f=y(this,Gs,"f").pop();Ue(f,void 0,y(this,ie,"f"));let h;e=this,t=this,n=this,o=this,s=this,r=this,i=this,a=this,c=this,l=this,u=this,d=this,{options:{set value(g){V(e,ee,g,"f")}}.value,configObjects:h,exitProcess:{set value(g){V(t,st,g,"f")}}.value,groups:{set value(g){V(n,mt,g,"f")}}.value,output:{set value(g){V(o,Pe,g,"f")}}.value,exitError:{set value(g){V(s,Bt,g,"f")}}.value,hasOutput:{set value(g){V(r,Ze,g,"f")}}.value,parsed:this.parsed,strict:{set value(g){V(i,dn,g,"f")}}.value,strictCommands:{set value(g){V(a,fn,g,"f")}}.value,strictOptions:{set value(g){V(c,pn,g,"f")}}.value,completionCommand:{set value(g){V(l,Ve,g,"f")}}.value,parseFn:{set value(g){V(u,Qe,g,"f")}}.value,parseContext:{set value(g){V(d,ln,g,"f")}}.value}=f,y(this,ee,"f").configObjects=h,y(this,ue,"f").unfreeze(),y(this,Ee,"f").unfreeze(),y(this,Ce,"f").unfreeze(),y(this,ot,"f").unfreeze()}[hl](e,t){return on(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[gl].bind(this),getContext:this[ml].bind(this),getHasOutput:this[yl].bind(this),getLoggerInstance:this[wl].bind(this),getParseContext:this[bl].bind(this),getParserConfiguration:this[hn].bind(this),getUsageConfiguration:this[dl].bind(this),getUsageInstance:this[Dl].bind(this),getValidationInstance:this[kl].bind(this),hasParseCallback:this[to].bind(this),isGlobalContext:this[xl].bind(this),postProcess:this[gn].bind(this),reset:this[Hr].bind(this),runValidation:this[zr].bind(this),runYargsParserAndExecuteCommands:this[ss].bind(this),setHasOutput:this[El].bind(this)}}[gl](){return y(this,Ce,"f")}[ml](){return y(this,ns,"f")}[yl](){return y(this,Ze,"f")}[wl](){return y(this,cn,"f")}[bl](){return y(this,ln,"f")||{}}[Dl](){return y(this,ue,"f")}[kl](){return y(this,Ee,"f")}[to](){return!!y(this,Qe,"f")}[xl](){return y(this,Ys,"f")}[gn](e,t,n,o){if(n)return e;if(be(e))return e;if(!t)e=this[il](e);if(this[hn]()["parse-positional-numbers"]||this[hn]()["parse-positional-numbers"]===void 0)e=this[pl](e);if(o)e=sn(e,this,y(this,ot,"f").getMiddleware(),!1);return e}[Hr](e={}){V(this,ee,y(this,ee,"f")||{},"f");let t={};t.local=y(this,ee,"f").local||[],t.configObjects=y(this,ee,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(y(this,un,"f"),Object.keys(y(this,mt,"f")).reduce((r,i)=>{let a=y(this,mt,"f")[i].filter((c)=>!(c in n));if(a.length>0)r[i]=a;return r},{})),V(this,mt,{},"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]=(y(this,ee,"f")[r]||[]).filter((i)=>!n[i])}),s.forEach((r)=>{t[r]=Mt(y(this,ee,"f")[r],(i)=>!n[i])}),t.envPrefix=y(this,ee,"f").envPrefix,V(this,ee,t,"f"),V(this,ue,y(this,ue,"f")?y(this,ue,"f").reset(n):Vc(this,y(this,ie,"f")),"f"),V(this,Ee,y(this,Ee,"f")?y(this,Ee,"f").reset(n):ol(this,y(this,ue,"f"),y(this,ie,"f")),"f"),V(this,Ce,y(this,Ce,"f")?y(this,Ce,"f").reset():Xc(y(this,ue,"f"),y(this,Ee,"f"),y(this,ot,"f"),y(this,ie,"f")),"f"),!y(this,Je,"f"))V(this,Je,tl(this,y(this,ue,"f"),y(this,Ce,"f"),y(this,ie,"f")),"f");return y(this,ot,"f").reset(),V(this,Ve,null,"f"),V(this,Pe,"","f"),V(this,Bt,null,"f"),V(this,Ze,!1,"f"),this.parsed=!1,this}[Sl](e,t){return y(this,ie,"f").path.relative(e,t)}[ss](e,t,n,o=0,s=!1){var r,i,a,c;let l=!!n||s;e=e||y(this,jt,"f"),y(this,ee,"f").__=y(this,ie,"f").y18n.__,y(this,ee,"f").configuration=this[hn]();let u=!!y(this,ee,"f").configuration["populate--"],d=Object.assign({},y(this,ee,"f").configuration,{"populate--":!0}),f=y(this,ie,"f").Parser.detailed(e,Object.assign({},y(this,ee,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),h=Object.assign(f.argv,y(this,ln,"f")),g=void 0,p=f.aliases,m=!1,w=!1;if(Object.keys(h).forEach((b)=>{if(b===y(this,rt,"f")&&h[b])m=!0;else if(b===y(this,yt,"f")&&h[b])w=!0}),h.$0=this.$0,this.parsed=f,o===0)y(this,ue,"f").clearCachedHelpMessage();try{if(this[Br](),t)return this[gn](h,u,!!n,!1);if(y(this,rt,"f")){if([y(this,rt,"f")].concat(p[y(this,rt,"f")]||[]).filter((F)=>F.length>1).includes(""+h._[h._.length-1]))h._.pop(),m=!0}V(this,Ys,!1,"f");let b=y(this,Ce,"f").getCommands(),D=((r=y(this,Je,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=y(this,Je,"f"))===null||i===void 0?void 0:i.completionKey,...(c=this.getAliases()[(a=y(this,Je,"f"))===null||a===void 0?void 0:a.completionKey])!==null&&c!==void 0?c:[]].some((A)=>Object.prototype.hasOwnProperty.call(h,A)):!1,S=m||D||s;if(h._.length){if(b.length){let A;for(let F=o||0,E;h._[F]!==void 0;F++)if(E=String(h._[F]),b.includes(E)&&E!==y(this,Ve,"f")){let x=y(this,Ce,"f").runCommand(E,this,f,F+1,s,m||w||s);return this[gn](x,u,!!n,!1)}else if(!A&&E!==y(this,Ve,"f")){A=E;break}if(!y(this,Ce,"f").hasDefaultCommand()&&y(this,Qs,"f")&&A&&!S)y(this,Ee,"f").recommendCommands(A,b)}if(y(this,Ve,"f")&&h._.includes(y(this,Ve,"f"))&&!D){if(y(this,st,"f"))Nt(!0);this.showCompletionScript(),this.exit(0)}}if(y(this,Ce,"f").hasDefaultCommand()&&!S){let A=y(this,Ce,"f").runCommand(null,this,f,0,s,m||w||s);return this[gn](A,u,!!n,!1)}if(D){if(y(this,st,"f"))Nt(!0);e=[].concat(e);let A=e.slice(e.indexOf(`--${y(this,Je,"f").completionKey}`)+1);return y(this,Je,"f").getCompletion(A,(F,E)=>{if(F)throw new $e(F.message);(E||[]).forEach((x)=>{y(this,cn,"f").log(x)}),this.exit(0)}),this[gn](h,!u,!!n,!1)}if(!y(this,Ze,"f")){if(m){if(y(this,st,"f"))Nt(!0);l=!0,this.showHelp((A)=>{y(this,cn,"f").log(A),this.exit(0)})}else if(w){if(y(this,st,"f"))Nt(!0);l=!0,y(this,ue,"f").showVersion("log"),this.exit(0)}}if(!l&&y(this,ee,"f").skipValidation.length>0)l=Object.keys(h).some((A)=>y(this,ee,"f").skipValidation.indexOf(A)>=0&&h[A]===!0);if(!l){if(f.error)throw new $e(f.error.message);if(!D){let A=this[zr](p,{},f.error);if(!n)g=sn(h,this,y(this,ot,"f").getMiddleware(),!0);if(g=this[hl](A,g!==null&&g!==void 0?g:h),be(g)&&!n)g=g.then(()=>sn(h,this,y(this,ot,"f").getMiddleware(),!1))}}}catch(b){if(b instanceof $e)y(this,ue,"f").fail(b.message,b);else throw b}return this[gn](g!==null&&g!==void 0?g:h,u,!!n,!0)}[zr](e,t,n,o){let s={...this.getDemandedOptions()};return(r)=>{if(n)throw new $e(n.message);y(this,Ee,"f").nonOptionCount(r),y(this,Ee,"f").requiredArguments(r,s);let i=!1;if(y(this,fn,"f"))i=y(this,Ee,"f").unknownCommands(r);if(y(this,dn,"f")&&!i)y(this,Ee,"f").unknownArguments(r,e,t,!!o);else if(y(this,pn,"f"))y(this,Ee,"f").unknownArguments(r,e,{},!1,!1);y(this,Ee,"f").limitedChoices(r),y(this,Ee,"f").implications(r),y(this,Ee,"f").conflicting(r)}}[El](){V(this,Ze,!0,"f")}[mn](e){if(typeof e==="string")y(this,ee,"f").key[e]=!0;else for(let t of e)y(this,ee,"f").key[t]=!0}}function Gc(e){return!!e&&typeof e.getInternalMethods==="function"}var Qh=_l(Or),Cl=Qh;var eg=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,tg=/[\t\n\v\f\r (*_~]/;function ng(e){let t=e.split(""),n=(s,r)=>{for(let i=s;i<r;i++)if(t[i]!==`
82
82
  `)t[i]="\x00"},o=0;while(o<e.length){let r=o===0||e[o-1]===`
83
83
  `?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(o)):null;if(r){let a=r[1]??r[2],c=new RegExp(`
84
84
  {0,3}${a[0]==="`"?"`":"~"}{${a.length},}[ ]*\r?(?=
85
85
  |$)`,"g");c.lastIndex=o+r[0].length;let l=c.exec(e),u=l?l.index+l[0].length:e.length;n(o,u),o=u;continue}let i=e[o];if(i==="\\"){o+=2;continue}if(i==="`"){let a=0;while(e[o+a]==="`")a++;let c=o+a,l=-1;while(c<e.length){if(e[c]===`
86
- `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(c)))break;if(e[c]!=="`"){c++;continue}let u=0;while(e[c+u]==="`")u++;if(u===a){l=c+u;break}c+=u}if(l<0){o+=a;continue}n(o,l),o=l;continue}if(i==="["){let a=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(o));if(a){n(o,o+a[0].length),o+=a[0].length;continue}}o++}return t.join("")}function qh(e,{markdown:t=!0}={}){let n=t?Jh(e):e,o=[];for(let s of n.matchAll(Uh)){let r=s[0];if(r.startsWith("<"))continue;let i=s.index??0,a=i>0?n[i-1]:"";if(a&&!Kh.test(a))o.push({url:r,side:"before",char:e[i-1]});let c=r.match(/[^\x00-\x7f]|>/);if(c)o.push({url:r,side:"after",char:c[0]})}return o}function Je(e,t=!1,n=console.error,{sides:o=["before","after"],markdown:s=!0}={}){let r=qh(e,{markdown:s}).filter((l)=>o.includes(l.side));if(!r.length)return;let i=r.map((l)=>l.side==="before"?`${JSON.stringify(l.url)} (glued to ${JSON.stringify(l.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(l.url)} (runs into ${JSON.stringify(l.char)} after it)`),a=r.some((l)=>l.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",c=`Ambiguous URL boundary: ${i.join(", ")}. ${a}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(c);n(`Warning: ${c}`)}import{existsSync as ss,readFileSync as Hr,writeFileSync as Jr,mkdirSync as xl,chmodSync as bl}from"node:fs";import{homedir as Hh}from"node:os";import{join as yn,dirname as zr}from"node:path";function Xr(){return process.env.HOME||Hh()}function Sl(){return yn(Xr(),".config","slack-cli","profiles.json")}function eo(){return yn(process.cwd(),".slack-cli","workspace")}function to(){return yn(Xr(),".slack-cli","workspace")}function os(){let e=Sl();if(!ss(e))return{profiles:{}};return JSON.parse(Hr(e,"utf8"))}function zh(e){let t=Sl();if(xl(zr(t),{recursive:!0}),process.platform!=="win32"&&ss(t))bl(t,384);if(Jr(t,JSON.stringify(e,null,2)+`
87
- `,{mode:384}),process.platform!=="win32")bl(t,384)}function Rn(e){if(!ss(e))return;return Hr(e,"utf8").trim()||void 0}function Dl(e,t){let n=zr(e);xl(n,{recursive:!0});let o=yn(n,".gitignore");if(!ss(o))Jr(o,`*
88
- `);Jr(e,t+`
89
- `)}function Xh(e){let t={};for(let n of e.split(`
90
- `)){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 kl(e){if(!ss(e))return{};try{return Xh(Hr(e,"utf8"))}catch{return{}}}function qr(e,t){let n=Xr(),o=e;while(!0){for(let i of[yn(o,".slack-term",".env.local"),yn(o,".env.local")]){let a=kl(i);for(let c of t)if(a[c])return a[c]}if(o===n)break;let r=zr(o);if(r===o)break;o=r}let s=kl(yn(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function Gr(){let e=os(),t=Rn(eo()),n=Rn(to()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=ns(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function ns(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 El(e){let t=os();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],zh(t)}function _l(e,t=!1){let n=os();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)Dl(to(),e);else Dl(eo(),e)}function rs(e){let n=os().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=qr(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.
91
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=qr(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let a=process.env.SLACK_WORKSPACE;if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let c=Rn(eo());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=Rn(to());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).
86
+ `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(c)))break;if(e[c]!=="`"){c++;continue}let u=0;while(e[c+u]==="`")u++;if(u===a){l=c+u;break}c+=u}if(l<0){o+=a;continue}n(o,l),o=l;continue}if(i==="["){let a=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(o));if(a){n(o,o+a[0].length),o+=a[0].length;continue}}o++}return t.join("")}function sg(e,{markdown:t=!0}={}){let n=t?ng(e):e,o=[];for(let s of n.matchAll(eg)){let r=s[0];if(r.startsWith("<"))continue;let i=s.index??0,a=i>0?n[i-1]:"";if(a&&!tg.test(a))o.push({url:r,side:"before",char:e[i-1]});let c=r.match(/[^\x00-\x7f]|>/);if(c)o.push({url:r,side:"after",char:c[0]})}return o}function Ke(e,t=!1,n=console.error,{sides:o=["before","after"],markdown:s=!0}={}){let r=sg(e,{markdown:s}).filter((l)=>o.includes(l.side));if(!r.length)return;let i=r.map((l)=>l.side==="before"?`${JSON.stringify(l.url)} (glued to ${JSON.stringify(l.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(l.url)} (runs into ${JSON.stringify(l.char)} after it)`),a=r.some((l)=>l.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",c=`Ambiguous URL boundary: ${i.join(", ")}. ${a}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(c);n(`Warning: ${c}`)}import{existsSync as rs,readFileSync as Yr,writeFileSync as Xr,mkdirSync as Rl,chmodSync as Al}from"node:fs";import{homedir as og}from"node:os";import{join as yn,dirname as Vr}from"node:path";function Zr(){return process.env.HOME||og()}function Il(){return yn(Zr(),".config","slack-cli","profiles.json")}function no(){return yn(process.cwd(),".slack-cli","workspace")}function so(){return yn(Zr(),".slack-cli","workspace")}function is(){let e=Il();if(!rs(e))return{profiles:{}};return JSON.parse(Yr(e,"utf8"))}function rg(e){let t=Il();if(Rl(Vr(t),{recursive:!0}),process.platform!=="win32"&&rs(t))Al(t,384);if(Xr(t,JSON.stringify(e,null,2)+`
87
+ `,{mode:384}),process.platform!=="win32")Al(t,384)}function In(e){if(!rs(e))return;return Yr(e,"utf8").trim()||void 0}function Fl(e,t){let n=Vr(e);Rl(n,{recursive:!0});let o=yn(n,".gitignore");if(!rs(o))Xr(o,`*
88
+ `);Xr(e,t+`
89
+ `)}function ig(e){let t={};for(let n of e.split(`
90
+ `)){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 Tl(e){if(!rs(e))return{};try{return ig(Yr(e,"utf8"))}catch{return{}}}function Gr(e,t){let n=Zr(),o=e;while(!0){for(let i of[yn(o,".slack-term",".env.local"),yn(o,".env.local")]){let a=Tl(i);for(let c of t)if(a[c])return a[c]}if(o===n)break;let r=Vr(o);if(r===o)break;o=r}let s=Tl(yn(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function Qr(){let e=is(),t=In(no()),n=In(so()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=os(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function os(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 Ol(e){let t=is();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],rg(t)}function Pl(e,t=!1){let n=is();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)Fl(so(),e);else Fl(no(),e)}function as(e){let n=is().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=Gr(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.
91
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Gr(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let a=process.env.SLACK_WORKSPACE;if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let c=In(no());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=In(so());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).
92
92
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
93
93
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
94
94
  Run one of:
@@ -97,13 +97,13 @@ ${g.join(`
97
97
  `+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
98
98
  `+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
99
99
  `+` slack auth token --token xoxp-... — paste an existing token
100
- `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function qe(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Yr(e){let t=os(),n=t.profiles;if(e)return ns(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=qr(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return ns(t,r);let i=Rn(eo());if(i)return ns(t,i);let a=Rn(to());if(a)return ns(t,a);return}import{existsSync as Pn,readFileSync as so,writeFileSync as $l,mkdirSync as Al,chmodSync as no}from"node:fs";import{homedir as Gh}from"node:os";import{join as In,dirname as Zr}from"node:path";function Qr(){return process.env.HOME||Gh()}function Fl(){return In(Qr(),".config","slack-cli","profiles.json")}function ei(){return In(process.cwd(),".slack-cli","workspace")}function ti(){return In(Qr(),".slack-cli","workspace")}function vn(){let e=Fl();if(!Pn(e))return{profiles:{}};return JSON.parse(so(e,"utf8"))}function ni(e){let t=Fl();if(Al(Zr(t),{recursive:!0}),process.platform!=="win32"&&Pn(t))no(t,384);if($l(t,JSON.stringify(e,null,2)+`
101
- `,{mode:384}),process.platform!=="win32")no(t,384)}function On(e){if(!Pn(e))return;return so(e,"utf8").trim()||void 0}function Yh(e){let t={};for(let n of e.split(`
102
- `)){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 Cl(e){if(!Pn(e))return{};try{return Yh(so(e,"utf8"))}catch{return{}}}function Vr(e,t){let n=Qr(),o=e;while(!0){for(let i of[In(o,".slack-term",".env.local"),In(o,".env.local")]){let a=Cl(i);for(let c of t)if(a[c])return a[c]}if(o===n)break;let r=Zr(o);if(r===o)break;o=r}let s=Cl(In(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function si(e,t){Al(Zr(e),{recursive:!0});let n=Pn(e)?so(e,"utf8"):"",o=n?n.split(`
103
- `):[];for(let[s,r]of Object.entries(t)){let i=o.findIndex((c)=>{let l=c.trim();return l.startsWith(s+"=")||l.startsWith(s+" =")}),a=`${s}=${r}`;if(i!==-1)o[i]=a;else o.push(a)}if(process.platform!=="win32"&&Pn(e))no(e,384);if($l(e,o.join(`
100
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function qe(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function ei(e){let t=is(),n=t.profiles;if(e)return os(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=Gr(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return os(t,r);let i=In(no());if(i)return os(t,i);let a=In(so());if(a)return os(t,a);return}import{existsSync as Pn,readFileSync as ro,writeFileSync as Ll,mkdirSync as Ml,chmodSync as oo}from"node:fs";import{homedir as ag}from"node:os";import{join as On,dirname as ni}from"node:path";function si(){return process.env.HOME||ag()}function Nl(){return On(si(),".config","slack-cli","profiles.json")}function oi(){return On(process.cwd(),".slack-cli","workspace")}function ri(){return On(si(),".slack-cli","workspace")}function Ln(){let e=Nl();if(!Pn(e))return{profiles:{}};return JSON.parse(ro(e,"utf8"))}function ii(e){let t=Nl();if(Ml(ni(t),{recursive:!0}),process.platform!=="win32"&&Pn(t))oo(t,384);if(Ll(t,JSON.stringify(e,null,2)+`
101
+ `,{mode:384}),process.platform!=="win32")oo(t,384)}function vn(e){if(!Pn(e))return;return ro(e,"utf8").trim()||void 0}function cg(e){let t={};for(let n of e.split(`
102
+ `)){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 vl(e){if(!Pn(e))return{};try{return cg(ro(e,"utf8"))}catch{return{}}}function ti(e,t){let n=si(),o=e;while(!0){for(let i of[On(o,".slack-term",".env.local"),On(o,".env.local")]){let a=vl(i);for(let c of t)if(a[c])return a[c]}if(o===n)break;let r=ni(o);if(r===o)break;o=r}let s=vl(On(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function ai(e,t){Ml(ni(e),{recursive:!0});let n=Pn(e)?ro(e,"utf8"):"",o=n?n.split(`
103
+ `):[];for(let[s,r]of Object.entries(t)){let i=o.findIndex((c)=>{let l=c.trim();return l.startsWith(s+"=")||l.startsWith(s+" =")}),a=`${s}=${r}`;if(i!==-1)o[i]=a;else o.push(a)}if(process.platform!=="win32"&&Pn(e))oo(e,384);if(Ll(e,o.join(`
104
104
  `).trimEnd()+`
105
- `,{mode:384}),process.platform!=="win32")no(e,384)}function as(){let e=vn(),t=On(ei()),n=On(ti()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=is(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function oo(e,t){let n=vn();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;ni(n)}function oi(e,t){let n=vn(),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;ni(n)}function Tl(e,t,n){let o=vn();o.users??={},o.users[e]={...o.users[e]??{},cookie:t,...n?{source:n}:{}},ni(o)}function is(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 Rl(e){let n=vn().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=Vr(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.
106
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Vr(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let a=process.env.SLACK_WORKSPACE;if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let c=On(ei());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=On(ti());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).
105
+ `,{mode:384}),process.platform!=="win32")oo(e,384)}function ls(){let e=Ln(),t=vn(oi()),n=vn(ri()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=cs(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function io(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;ii(n)}function ci(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;ii(n)}function Bl(e,t,n){let o=Ln();o.users??={},o.users[e]={...o.users[e]??{},cookie:t,...n?{source:n}:{}},ii(o)}function cs(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 jl(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=ti(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.
106
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=ti(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let a=process.env.SLACK_WORKSPACE;if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let c=vn(oi());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=vn(ri());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).
107
107
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
108
108
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
109
109
  Run one of:
@@ -112,34 +112,34 @@ ${g.join(`
112
112
  `+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
113
113
  `+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
114
114
  `+` slack auth token --token xoxp-... — paste an existing token
115
- `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function ro(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Bt(e){let t=vn(),n=t.profiles;if(e)return is(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=Vr(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return is(t,r);let i=On(ei());if(i)return is(t,i);let a=On(ti());if(a)return is(t,a);return}function io(e){let t=[],n=(r)=>{if(!r)return;let i=t[t.length-1];if(i?.type==="text")i.text+=r;else t.push({type:"text",text:r})},o=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,s=0;for(let r of e.matchAll(o)){let i=r.index??0;if(n(e.slice(s,i)),r[1]){t.push(r[2]?{type:"link",url:r[1],text:r[2]}:{type:"link",url:r[1]}),s=i+r[0].length;continue}let a=r[0];while(/[.,:;!?'"*_~]$/.test(a)||a.endsWith(")")&&Il(a,"(")<Il(a,")"))a=a.slice(0,-1);t.push({type:"link",url:a}),s=i+a.length}return n(e.slice(s)),t}function Il(e,t){return e.split(t).length-1}var Vh={"&":"&amp;","<":"&lt;",">":"&gt;"};function Zh(e){if(typeof e!=="string"||!/^[0-9a-f]+(-[0-9a-f]+)*$/i.test(e))return[];let t=e.split("-").map((s)=>parseInt(s,16)),n=String.fromCodePoint(...t),o=String.fromCodePoint(...t.filter((s)=>s!==65039));return n===o?[n]:[n,o]}function Qh(e){let t=[],n=(r)=>{for(let i of r)if(i===`
116
- `)t.push(null);else if(!/\s/u.test(i))t.push(...Vh[i]??i)},o=(r)=>{switch(r.type){case"text":n(String(r.text??""));break;case"link":case"message_mention":n(String(r.url??""));break;case"user":n(String(r.user_id??""));break;case"channel":n(String(r.channel_id??""));break;case"usergroup":n(String(r.usergroup_id??""));break;case"broadcast":n(String(r.range??""));break;case"emoji":t.push([`:${String(r.name??"")}:`,...Zh(r.unicode)].filter((i)=>i!=="::"));break;default:break}},s=(r)=>{let i=Array.isArray(r.elements)?r.elements:[];if(r.type==="rich_text_list"||r.type==="rich_text")i.forEach((a,c)=>{if(c>0)t.push(null);s(a)});else i.forEach(o)};return e.forEach((r,i)=>{if(i>0)t.push(null);let a=r;if(a.type==="rich_text")s(a)}),t}function eg(e,t,n){if(typeof t==="string"){let s=n;while(s<e.length&&e[s]!==t)s++;return s<e.length?[s,1]:[-1,0]}let o=[-1,0];for(let s of t){let r=[...s];for(let i=n;i+r.length<=e.length&&(o[0]<0||i<o[0]);i++)if(r.every((a,c)=>e[i+c]===a)){o=[i,r.length];break}}return o}function tg(e,t){if(e.includes(`
117
- `)||!Array.isArray(t)||!t.some((g)=>g?.type==="rich_text"))return e;let n=Qh(t);if(!n.includes(null))return e;let o=[...e],s=t[0].elements,i=t[t.length-1].elements,a=Array.isArray(s)&&s[0]?.type==="rich_text_preformatted",c=Array.isArray(i)&&i[i.length-1]?.type==="rich_text_preformatted",l=0,u=-1,d=a,f=[];for(let g of n){if(g===null){d=!0;continue}let[p,m]=eg(o,g,l);if(p<0)return e;if(d)f.push([u+1,p]),d=!1;u=p+m-1,l=p+m}if((d||c)&&u>=0)f.push([u+1,o.length]);let h=/^(?:[-*+•]|\d{1,9}[.)]|&gt;|>)$/;for(let[g,p]of f){let m=g;if(o.lastIndexOf("<",g-1)>o.lastIndexOf(">",g-1)){let D=o.indexOf(">",g);if(D!==-1&&D<p)m=D+1}let w="",b=g===0;while(m<p)if(o[m]===" "){let D=m;while(D<p&&o[D]===" ")D++;if(b&&h.test(w))b=!1;else{let S=D-m<=2?D-m:1;for(let F=m;F<m+S;F++)o[F]=`
118
- `;b=!0}w="",m=D}else w+=o[m],m++}return o.join("")}function ao(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.text==="string")t.text=tg(t.text,t.blocks)}class He extends Error{retryAfter;method;constructor(e,t){super(t?`Slack rate limited on ${t} — retry after ${e}s`:`Slack rate limited — retry after ${e}s`);if(this.name="RateLimitError",this.retryAfter=e,t)this.method=t}}function ii(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function ai(e,t,n,o){o=e.startsWith("xoxc-")?o??Bt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ii()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new He(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new He(60,t);if(a==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
115
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function ao(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Ut(e){let t=Ln(),n=t.profiles;if(e)return cs(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=ti(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return cs(t,r);let i=vn(oi());if(i)return cs(t,i);let a=vn(ri());if(a)return cs(t,a);return}function co(e){let t=[],n=(r)=>{if(!r)return;let i=t[t.length-1];if(i?.type==="text")i.text+=r;else t.push({type:"text",text:r})},o=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,s=0;for(let r of e.matchAll(o)){let i=r.index??0;if(n(e.slice(s,i)),r[1]){t.push(r[2]?{type:"link",url:r[1],text:r[2]}:{type:"link",url:r[1]}),s=i+r[0].length;continue}let a=r[0];while(/[.,:;!?'"*_~]$/.test(a)||a.endsWith(")")&&Wl(a,"(")<Wl(a,")"))a=a.slice(0,-1);t.push({type:"link",url:a}),s=i+a.length}return n(e.slice(s)),t}function Wl(e,t){return e.split(t).length-1}var lg={"&":"&amp;","<":"&lt;",">":"&gt;"};function ug(e){if(typeof e!=="string"||!/^[0-9a-f]+(-[0-9a-f]+)*$/i.test(e))return[];let t=e.split("-").map((s)=>parseInt(s,16)),n=String.fromCodePoint(...t),o=String.fromCodePoint(...t.filter((s)=>s!==65039));return n===o?[n]:[n,o]}function dg(e){let t=[],n=(r)=>{for(let i of r)if(i===`
116
+ `)t.push(null);else if(!/\s/u.test(i))t.push(...lg[i]??i)},o=(r)=>{switch(r.type){case"text":n(String(r.text??""));break;case"link":case"message_mention":n(String(r.url??""));break;case"user":n(String(r.user_id??""));break;case"channel":n(String(r.channel_id??""));break;case"usergroup":n(String(r.usergroup_id??""));break;case"broadcast":n(String(r.range??""));break;case"emoji":t.push([`:${String(r.name??"")}:`,...ug(r.unicode)].filter((i)=>i!=="::"));break;default:break}},s=(r)=>{let i=Array.isArray(r.elements)?r.elements:[];if(r.type==="rich_text_list"||r.type==="rich_text")i.forEach((a,c)=>{if(c>0)t.push(null);s(a)});else i.forEach(o)};return e.forEach((r,i)=>{if(i>0)t.push(null);let a=r;if(a.type==="rich_text")s(a)}),t}function fg(e,t,n){if(typeof t==="string"){let s=n;while(s<e.length&&e[s]!==t)s++;return s<e.length?[s,1]:[-1,0]}let o=[-1,0];for(let s of t){let r=[...s];for(let i=n;i+r.length<=e.length&&(o[0]<0||i<o[0]);i++)if(r.every((a,c)=>e[i+c]===a)){o=[i,r.length];break}}return o}function pg(e,t){if(e.includes(`
117
+ `)||!Array.isArray(t)||!t.some((g)=>g?.type==="rich_text"))return e;let n=dg(t);if(!n.includes(null))return e;let o=[...e],s=t[0].elements,i=t[t.length-1].elements,a=Array.isArray(s)&&s[0]?.type==="rich_text_preformatted",c=Array.isArray(i)&&i[i.length-1]?.type==="rich_text_preformatted",l=0,u=-1,d=a,f=[];for(let g of n){if(g===null){d=!0;continue}let[p,m]=fg(o,g,l);if(p<0)return e;if(d)f.push([u+1,p]),d=!1;u=p+m-1,l=p+m}if((d||c)&&u>=0)f.push([u+1,o.length]);let h=/^(?:[-*+•]|\d{1,9}[.)]|&gt;|>)$/;for(let[g,p]of f){let m=g;if(o.lastIndexOf("<",g-1)>o.lastIndexOf(">",g-1)){let D=o.indexOf(">",g);if(D!==-1&&D<p)m=D+1}let w="",b=g===0;while(m<p)if(o[m]===" "){let D=m;while(D<p&&o[D]===" ")D++;if(b&&h.test(w))b=!1;else{let S=D-m<=2?D-m:1;for(let A=m;A<m+S;A++)o[A]=`
118
+ `;b=!0}w="",m=D}else w+=o[m],m++}return o.join("")}function lo(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.text==="string")t.text=pg(t.text,t.blocks)}class He extends Error{retryAfter;method;constructor(e,t){super(t?`Slack rate limited on ${t} — retry after ${e}s`:`Slack rate limited — retry after ${e}s`);if(this.name="RateLimitError",this.retryAfter=e,t)this.method=t}}function ui(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function di(e,t,n,o){o=e.startsWith("xoxc-")?o??Ut():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ui()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new He(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new He(60,t);if(a==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
119
119
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
120
120
  Or replace the token with an xoxp- user token:
121
121
  slack auth login`);if((a==="missing_scope"||a==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${a}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${a} — ${a==="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"}.
122
122
  Tailing/DMing people and listing users need a user session, not a bot token.
123
123
  Switch workspace: slack auth ls then slack auth use <name>
124
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${a}`)}return i}async function ng(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ii()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new He(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new He(60,t);if((a==="invalid_auth"||a==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
124
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${a}`)}return i}async function hg(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ui()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new He(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new He(60,t);if((a==="invalid_auth"||a==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
125
125
  Import from Slack desktop: slack auth login`);if((a==="invalid_auth"||a==="not_authed")&&!o)throw Error(`${t} also requires the xoxd session cookie.
126
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${a}`)}return i}function sg(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return ng(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function Fe(e,t,n,o){let s=new URLSearchParams(n).toString();return ai(e,`${t}?${s}`,{method:"GET"},o)}function ci(e,t,n,o){return ai(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function Ll(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return ai(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function ls(e,t,n){return Ll(e,"agents.sessions.setStatus",{...t,status:n})}function li(e,t,n){return Ll(e,"agents.sessions.rename",{...t,title:n})}async function Ln(e,t){let n=await Fe(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Ml(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(`${ii()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new He(isNaN(i)?60:i,"auth.test")}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 Nl(e,t,n){let o=await Fe(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function wn(e,t,n=20,o,s,r,i){let a={channel:t,limit:String(n)};if(o!==void 0)a.oldest=o;if(s!==void 0)a.cursor=s;if(i)a.inclusive="true";return ui(await Fe(e,"conversations.history",a,r))}function ui(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let o of n)ao(o);return e}async function Bl(e,t,n,o=50,s){return ui(await Fe(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s))}async function jl(e,t,n,o={},s){let r={channel:t,ts:n,limit:String(o.limit??200)};if(o.oldest!==void 0)r.oldest=o.oldest;if(o.cursor!==void 0)r.cursor=o.cursor;return ui(await Fe(e,"conversations.replies",r,s))}async function Wl(e,t,n){let o=[],s="";do{let r={limit:"200",types:t,exclude_archived:"true"};if(s)r.cursor=s;let i=await Fe(e,"users.conversations",r,n);o.push(...i.channels??[]),s=i.response_metadata?.next_cursor??""}while(s);return o}async function co(e,t,n,o,s){await ci(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Ul(e,t,n,o){return((await Fe(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 lo(e,t,n,o,s){await ci(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function og(e,t,n){let s=(await ci(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Kl(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await Fe(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 ri(e,t,n,o){let s=await Kl(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 cs(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Pl(e,t){let n=cs(e.name??""),o=cs(e.real_name??e.profile?.real_name??""),s=cs(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Jl=200;async function rg(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await Fe(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(Pl(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,a=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await Fe(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Jl){c=!0;break}s.add(h),i++;let g;try{g=(await Fe(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof He)throw p;a++;continue}if(g&&Pl(g,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:a,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:a,capped:c}}function ig(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
126
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${a}`)}return i}function gg(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return hg(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function Fe(e,t,n,o){let s=new URLSearchParams(n).toString();return di(e,`${t}?${s}`,{method:"GET"},o)}function fi(e,t,n,o){return di(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function ql(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return di(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function ds(e,t,n){return ql(e,"agents.sessions.setStatus",{...t,status:n})}function pi(e,t,n){return ql(e,"agents.sessions.rename",{...t,title:n})}async function Mn(e,t){let n=await Fe(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Hl(e,t){t=e.startsWith("xoxc-")?t??Ut():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${ui()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new He(isNaN(i)?60:i,"auth.test")}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 zl(e,t,n){let o=await Fe(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function wn(e,t,n=20,o,s,r,i){let a={channel:t,limit:String(n)};if(o!==void 0)a.oldest=o;if(s!==void 0)a.cursor=s;if(i)a.inclusive="true";return hi(await Fe(e,"conversations.history",a,r))}function hi(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let o of n)lo(o);return e}async function Xl(e,t,n,o=50,s){return hi(await Fe(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s))}async function Gl(e,t,n,o={},s){let r={channel:t,ts:n,limit:String(o.limit??200)};if(o.oldest!==void 0)r.oldest=o.oldest;if(o.cursor!==void 0)r.cursor=o.cursor;return hi(await Fe(e,"conversations.replies",r,s))}async function Yl(e,t,n){let o=[],s="";do{let r={limit:"200",types:t,exclude_archived:"true"};if(s)r.cursor=s;let i=await Fe(e,"users.conversations",r,n);o.push(...i.channels??[]),s=i.response_metadata?.next_cursor??""}while(s);return o}async function uo(e,t,n,o,s){await fi(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Vl(e,t,n,o){return((await Fe(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 fo(e,t,n,o,s){await fi(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function mg(e,t,n){let s=(await fi(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Zl(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await Fe(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 li(e,t,n,o){let s=await Zl(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 us(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Ul(e,t){let n=us(e.name??""),o=us(e.real_name??e.profile?.real_name??""),s=us(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Ql=200;async function yg(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await Fe(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(Ul(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,a=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await Fe(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Ql){c=!0;break}s.add(h),i++;let g;try{g=(await Fe(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof He)throw p;a++;continue}if(g&&Ul(g,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:a,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:a,capped:c}}function wg(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
127
127
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
128
- 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 ${Jl} 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.
128
+ 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 ${Ql} 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.
129
129
  `+(o.length?`This search was incomplete: ${o.join("; ")}.
130
130
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
131
131
  DMed you they cannot be found by name at all. Look them up and use their ID:
132
- slack user ls --external`)}function di(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 ag(e){return di(e)?.channel}function Ol(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function vl(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function uo(e,t,n){let o=ag(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Ol(t))return t;if(vl(t))return ri(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Ol(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=cs(r);if(s){if(vl(r))return ri(e,r,n);let l=await Fe(e,"auth.test",{},n);if(i==="you"||i==="me"||cs(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Kl(e,f,n)||og(e,f,n)}let d=await rg(e,i,n);if(!d.id)throw ig(t,d);if(d.dm)return d.dm;return ri(e,d.id,n,t)}let a=r.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await Fe(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===a)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function fo(e,t,n){try{let o=await Fe(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 Mn(e,t,n){try{let o=await Fe(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 po(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await Fe(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function fi(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await Fe(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function pi(e,t,n){return Fe(e,"users.info",{user:t},n)}async function ql(e,t,n){return Fe(e,"conversations.info",{channel:t},n)}async function Hl(e,t){let n=await sg(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 cg=["chat:write","im:write"],lg=["im:history","im:read"];async function ho(e){let{userId:t,botId:n,team:o,scopes:s}=await Ml(e),r="";if(n)try{r=(await Nl(e,n)).appId}catch{r=""}let i=(l)=>s.includes(l),a=cg.filter((l)=>!i(l)),c=lg.filter((l)=>!i(l));return{canSend:a.length===0,canReceiveReplies:c.length===0,ok:a.length===0&&c.length===0,botUserId:t,appId:r,team:o,grantedScopes:s,missingSendScopes:a,missingReplyScopes:c}}function zl(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function go(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,...zl(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,...zl(e)]}import{createInterface as ze}from"node:readline/promises";import{join as Si,resolve as vg}from"node:path";import{homedir as Lg}from"node:os";import{readdirSync as fs,readFileSync as ds,existsSync as et,copyFileSync as mi,mkdtempSync as Vl,rmSync as Zl}from"node:fs";import{homedir as yo,tmpdir as Ql}from"node:os";import{join as ge,dirname as fg}from"node:path";import{pbkdf2Sync as mo,createDecipheriv as eu,createHash as pg,timingSafeEqual as hg}from"node:crypto";import{execSync as tu,execFileSync as gg}from"node:child_process";function us(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 ug(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++],a=i&3;if(a===0){let c=i>>2;if(c>=60){let l=c-59;c=0;for(let u=0;u<l;u++)c+=e[t++]*2**(8*u)}c+=1,e.copy(s,r,t,t+c),t+=c,r+=c}else{let c,l;if(a===1)c=4+(i>>2&7),l=(i>>5&7)*256+e[t++];else if(a===2)c=1+(i>>2),l=e[t]+e[t+1]*256,t+=2;else c=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<c&&r<n;d++)s[r++]=s[u++]}}return r===n?s:s.subarray(0,r)}function hi(e,t){let n=us(e,t),o=us(e,n.pos);return{handle:{offset:n.value,size:o.value},pos:o.pos}}function Xl(e,t){let{offset:n,size:o}=t,s=e.subarray(n,n+o);return e[n+o]===1?ug(s):Buffer.from(s)}function dg(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=us(e,s),a=us(e,i.pos),c=us(e,a.pos);s=c.pos;let l=i.value,u=a.value,d=c.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 Gl(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=hi(e,t),o=hi(e,n.pos),s=Xl(e,o.handle),r=[];for(let i of dg(s))try{let{handle:a}=hi(i,0);r.push(Xl(e,a))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function Yl(){let e=process.env.HOME??yo();if(process.platform==="darwin")return[ge(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[ge(e,".config","Slack","Local Storage","leveldb"),ge(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),ge(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??ge(e,"AppData","Roaming");return[ge(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function mg(){let e=process.env.HOME??yo();if(process.platform==="darwin")return ge(e,"Library","Application Support","Slack","Cookies");return""}function yg(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=eu("aes-128-cbc",t,n);return s.setAutoPadding(!0),Buffer.concat([s.update(o),s.final()]).toString("utf8")}function wg(){if(process.platform!=="darwin")return;let e=mg();if(!et(e))return;let t;try{t=tu('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=mo(t,"saltysalt",1003,16,"sha1");try{let{default:o}=Yn("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 yg(Buffer.from(r.encrypted_value),n)}catch{return}}function nu(e){if(!et(e))return[];let t=fs(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,o=(i)=>{let a=n.get(i);if(a!==void 0)return a;let c="";try{let l=ds(ge(e,i));c=i.endsWith(".ldb")?Gl(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{c=""}return n.set(i,c),c},s=new Map;for(let i of t){let a=o(i);for(let c of a.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=c[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,c.index-2000),f=Math.min(a.length,c.index+2000),h=a.slice(d,f),g=h.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),p=h.match(/"(?:team_name|name)":"([^"]{2,60})"/),m=s.get(u);if(!m||l.length>m.token.length){let w={token:l,teamId:u},b=g?.[1]??m?.url,D=p?.[1]??m?.teamName;if(b)w.url=b;if(D)w.teamName=D;s.set(u,w)}}}let r=t.map((i)=>o(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of s.values()){if(i.teamName)continue;let a=r.indexOf(i.teamId);if(a!==-1){let c=Math.max(0,a-500),l=Math.min(r.length,a+500),d=r.slice(c,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let c=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(c){let l=r.indexOf(c);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=c.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...s.values()]}async function yi(e){let t=e??Yl().find(et);if(!t)throw Error(`Slack desktop app LevelDB not found at:
133
- ${Yl().join(`
132
+ slack user ls --external`)}function gi(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 bg(e){return gi(e)?.channel}function Jl(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Kl(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function po(e,t,n){let o=bg(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Jl(t))return t;if(Kl(t))return li(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Jl(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=us(r);if(s){if(Kl(r))return li(e,r,n);let l=await Fe(e,"auth.test",{},n);if(i==="you"||i==="me"||us(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Zl(e,f,n)||mg(e,f,n)}let d=await yg(e,i,n);if(!d.id)throw wg(t,d);if(d.dm)return d.dm;return li(e,d.id,n,t)}let a=r.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await Fe(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===a)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function ho(e,t,n){try{let o=await Fe(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 Nn(e,t,n){try{let o=await Fe(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 go(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await Fe(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function mi(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await Fe(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function yi(e,t,n){return Fe(e,"users.info",{user:t},n)}async function eu(e,t,n){return Fe(e,"conversations.info",{channel:t},n)}async function tu(e,t){let n=await gg(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 Dg=["chat:write","im:write"],kg=["im:history","im:read"];async function mo(e){let{userId:t,botId:n,team:o,scopes:s}=await Hl(e),r="";if(n)try{r=(await zl(e,n)).appId}catch{r=""}let i=(l)=>s.includes(l),a=Dg.filter((l)=>!i(l)),c=kg.filter((l)=>!i(l));return{canSend:a.length===0,canReceiveReplies:c.length===0,ok:a.length===0&&c.length===0,botUserId:t,appId:r,team:o,grantedScopes:s,missingSendScopes:a,missingReplyScopes:c}}function nu(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function yo(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,...nu(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,...nu(e)]}import{createInterface as ze}from"node:readline/promises";import{join as Ci,resolve as zg}from"node:path";import{homedir as Xg}from"node:os";import{readdirSync as hs,readFileSync as ps,existsSync as et,copyFileSync as Di,mkdtempSync as iu,rmSync as au}from"node:fs";import{homedir as bo,tmpdir as cu}from"node:os";import{join as ge,dirname as Eg}from"node:path";import{pbkdf2Sync as wo,createDecipheriv as lu,createHash as _g,timingSafeEqual as $g}from"node:crypto";import{execSync as uu,execFileSync as Cg}from"node:child_process";function fs(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 xg(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++],a=i&3;if(a===0){let c=i>>2;if(c>=60){let l=c-59;c=0;for(let u=0;u<l;u++)c+=e[t++]*2**(8*u)}c+=1,e.copy(s,r,t,t+c),t+=c,r+=c}else{let c,l;if(a===1)c=4+(i>>2&7),l=(i>>5&7)*256+e[t++];else if(a===2)c=1+(i>>2),l=e[t]+e[t+1]*256,t+=2;else c=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<c&&r<n;d++)s[r++]=s[u++]}}return r===n?s:s.subarray(0,r)}function wi(e,t){let n=fs(e,t),o=fs(e,n.pos);return{handle:{offset:n.value,size:o.value},pos:o.pos}}function su(e,t){let{offset:n,size:o}=t,s=e.subarray(n,n+o);return e[n+o]===1?xg(s):Buffer.from(s)}function Sg(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=fs(e,s),a=fs(e,i.pos),c=fs(e,a.pos);s=c.pos;let l=i.value,u=a.value,d=c.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 ou(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=wi(e,t),o=wi(e,n.pos),s=su(e,o.handle),r=[];for(let i of Sg(s))try{let{handle:a}=wi(i,0);r.push(su(e,a))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function ru(){let e=process.env.HOME??bo();if(process.platform==="darwin")return[ge(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[ge(e,".config","Slack","Local Storage","leveldb"),ge(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),ge(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??ge(e,"AppData","Roaming");return[ge(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Ag(){let e=process.env.HOME??bo();if(process.platform==="darwin")return ge(e,"Library","Application Support","Slack","Cookies");return""}function Fg(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=lu("aes-128-cbc",t,n);return s.setAutoPadding(!0),Buffer.concat([s.update(o),s.final()]).toString("utf8")}function Tg(){if(process.platform!=="darwin")return;let e=Ag();if(!et(e))return;let t;try{t=uu('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=wo(t,"saltysalt",1003,16,"sha1");try{let{default:o}=Zn("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 Fg(Buffer.from(r.encrypted_value),n)}catch{return}}function du(e){if(!et(e))return[];let t=hs(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,o=(i)=>{let a=n.get(i);if(a!==void 0)return a;let c="";try{let l=ps(ge(e,i));c=i.endsWith(".ldb")?ou(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{c=""}return n.set(i,c),c},s=new Map;for(let i of t){let a=o(i);for(let c of a.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=c[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,c.index-2000),f=Math.min(a.length,c.index+2000),h=a.slice(d,f),g=h.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),p=h.match(/"(?:team_name|name)":"([^"]{2,60})"/),m=s.get(u);if(!m||l.length>m.token.length){let w={token:l,teamId:u},b=g?.[1]??m?.url,D=p?.[1]??m?.teamName;if(b)w.url=b;if(D)w.teamName=D;s.set(u,w)}}}let r=t.map((i)=>o(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of s.values()){if(i.teamName)continue;let a=r.indexOf(i.teamId);if(a!==-1){let c=Math.max(0,a-500),l=Math.min(r.length,a+500),d=r.slice(c,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let c=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(c){let l=r.indexOf(c);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=c.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...s.values()]}async function ki(e){let t=e??ru().find(et);if(!t)throw Error(`Slack desktop app LevelDB not found at:
133
+ ${ru().join(`
134
134
  `)}
135
- Is Slack installed and opened at least once?`);let n=nu(t),o=e?void 0:wg();if(o)for(let s of n)s.cookie=o;return n}function bg(e,t){try{return JSON.parse(ds(ge(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function wi(){let e=bi();if(!e||!et(e))return[];let t=["Default",...fs(e).filter((o)=>o.startsWith("Profile "))],n=[];for(let o of t){let s=ge(e,o,"Local Storage","leveldb"),r=nu(s);if(r.length===0)continue;let i=bg(e,o);n.push({profileDir:o,...i?{email:i}:{},label:su(e,o),sessions:r})}return n}function gi(e,t,n,o=!1){let s=(r,i)=>{try{let a=eu("aes-128-cbc",t,r);a.setAutoPadding(!0);let c=Buffer.concat([a.update(i),a.final()]);if(c.subarray(0,5).toString()==="xoxd-")return c.toString("utf8");if(c.length>=37){let l=pg("sha256").update(n).digest();if(hg(c.subarray(0,32),l)){let u=c.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 su(e,t){let n=(o,s)=>{if(o&&s)return`${o} (${s})`;return o||s||t};try{let s=JSON.parse(ds(ge(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(ds(ge(e,t,"Preferences"),"utf8")).profile;return n(s?.name??"",s?.user_name??"")}catch{return t}}function bi(){let e=process.env.HOME??yo();if(process.platform==="darwin")return ge(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return ge(process.env.XDG_CONFIG_HOME??ge(e,".config"),"google-chrome");return""}function Dg(){try{return gg("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function ps(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=bi();if(!et(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=tu('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=mo(i,"saltysalt",1003,16,"sha1")}let n=["Default",...fs(e).filter((i)=>i.startsWith("Profile "))],o=[],s,r=!1;for(let i of n){let a=[ge(e,i,"Network","Cookies"),ge(e,i,"Cookies")].find(et);if(!a)continue;let c=Vl(ge(Ql(),"slack-chrome-cookies-")),l=ge(c,"Cookies");try{if(mi(a,l),et(`${a}-wal`))mi(`${a}-wal`,`${l}-wal`);let{default:u}=Yn("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),g=h.subarray(0,3).toString(),p;if(g==="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(g==="v10")p=gi(h,mo("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(g==="v11"){if(!s){let m=Dg();if(m)s=mo(m,"saltysalt",1,16,"sha1")}if(s)p=gi(h,s,f.host_key);else r=!0}}else if(g==="v10"&&t)p=gi(h,t,f.host_key,!0);else if(g!=="v10")throw Error("Unknown cookie encryption prefix.");if(p)o.push({profileDir:i,profileName:su(e,i),cookie:p})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{Zl(c,{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 Di(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=bi();if(!et(e))throw Error("Chrome profile directory was not found.");let t=new Map(ps().candidates.map((s)=>[s.profileDir,s.cookie])),n=new Map,o=["Default",...fs(e).filter((s)=>s.startsWith("Profile "))];for(let s of o){let r=ge(e,s,"Local Storage","leveldb");if(!et(r))continue;let i;try{i=await yi(r)}catch{continue}for(let a of i){if(n.has(a.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let c=t.get(s);if(c)a.cookie=c;n.set(a.teamId,a)}}return[...n.values()]}function kg(){let e=process.env.HOME??yo();if(process.platform==="darwin")return[ge(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[ge(e,".mozilla","firefox"),ge(e,"snap","firefox","common",".mozilla","firefox"),ge(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[ge(process.env.APPDATA??ge(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function xg(e){let t=ge(e,"profiles.ini"),n=et(t)?t:ge(fg(e),"profiles.ini"),o={};if(!et(n))return o;try{let s=ds(n,"utf8"),r="",i="";for(let a of s.split(`
136
- `)){let c=a.trim();if(c.startsWith("[")){r="",i="";continue}let l=c.indexOf("=");if(l===-1)continue;let u=c.slice(0,l).trim().toLowerCase(),d=c.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 wo(){let e=[];for(let t of kg().filter(et)){let n=xg(t),o;try{o=fs(t)}catch{continue}for(let s of o){let r=ge(t,s,"cookies.sqlite");if(!et(r))continue;let i=Vl(ge(Ql(),"slack-firefox-cookies-")),a=ge(i,"cookies.sqlite");try{mi(r,a);let{default:c}=Yn("bun:sqlite"),l=new c(a,{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{Zl(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as ki,writeFileSync as xi,mkdirSync as Sg,existsSync as hs,rmSync as Eg}from"node:fs";import{join as it}from"node:path";import{createDecipheriv as bo}from"node:crypto";import{spawnSync as _g}from"node:child_process";var Cg=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),$g=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Ag=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),dt="C:\\ProgramData\\slack-term-abe";function Fg(){let e=process.env.LOCALAPPDATA??it(process.env.USERPROFILE??"","AppData","Local");return it(e,"Google","Chrome","User Data")}var Tg=String.raw`try {
135
+ Is Slack installed and opened at least once?`);let n=du(t),o=e?void 0:Tg();if(o)for(let s of n)s.cookie=o;return n}function Rg(e,t){try{return JSON.parse(ps(ge(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function xi(){let e=Si();if(!e||!et(e))return[];let t=["Default",...hs(e).filter((o)=>o.startsWith("Profile "))],n=[];for(let o of t){let s=ge(e,o,"Local Storage","leveldb"),r=du(s);if(r.length===0)continue;let i=Rg(e,o);n.push({profileDir:o,...i?{email:i}:{},label:fu(e,o),sessions:r})}return n}function bi(e,t,n,o=!1){let s=(r,i)=>{try{let a=lu("aes-128-cbc",t,r);a.setAutoPadding(!0);let c=Buffer.concat([a.update(i),a.final()]);if(c.subarray(0,5).toString()==="xoxd-")return c.toString("utf8");if(c.length>=37){let l=_g("sha256").update(n).digest();if($g(c.subarray(0,32),l)){let u=c.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 fu(e,t){let n=(o,s)=>{if(o&&s)return`${o} (${s})`;return o||s||t};try{let s=JSON.parse(ps(ge(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(ps(ge(e,t,"Preferences"),"utf8")).profile;return n(s?.name??"",s?.user_name??"")}catch{return t}}function Si(){let e=process.env.HOME??bo();if(process.platform==="darwin")return ge(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return ge(process.env.XDG_CONFIG_HOME??ge(e,".config"),"google-chrome");return""}function Ig(){try{return Cg("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function gs(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=Si();if(!et(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=uu('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=wo(i,"saltysalt",1003,16,"sha1")}let n=["Default",...hs(e).filter((i)=>i.startsWith("Profile "))],o=[],s,r=!1;for(let i of n){let a=[ge(e,i,"Network","Cookies"),ge(e,i,"Cookies")].find(et);if(!a)continue;let c=iu(ge(cu(),"slack-chrome-cookies-")),l=ge(c,"Cookies");try{if(Di(a,l),et(`${a}-wal`))Di(`${a}-wal`,`${l}-wal`);let{default:u}=Zn("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),g=h.subarray(0,3).toString(),p;if(g==="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(g==="v10")p=bi(h,wo("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(g==="v11"){if(!s){let m=Ig();if(m)s=wo(m,"saltysalt",1,16,"sha1")}if(s)p=bi(h,s,f.host_key);else r=!0}}else if(g==="v10"&&t)p=bi(h,t,f.host_key,!0);else if(g!=="v10")throw Error("Unknown cookie encryption prefix.");if(p)o.push({profileDir:i,profileName:fu(e,i),cookie:p})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{au(c,{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 Ei(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Si();if(!et(e))throw Error("Chrome profile directory was not found.");let t=new Map(gs().candidates.map((s)=>[s.profileDir,s.cookie])),n=new Map,o=["Default",...hs(e).filter((s)=>s.startsWith("Profile "))];for(let s of o){let r=ge(e,s,"Local Storage","leveldb");if(!et(r))continue;let i;try{i=await ki(r)}catch{continue}for(let a of i){if(n.has(a.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let c=t.get(s);if(c)a.cookie=c;n.set(a.teamId,a)}}return[...n.values()]}function Og(){let e=process.env.HOME??bo();if(process.platform==="darwin")return[ge(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[ge(e,".mozilla","firefox"),ge(e,"snap","firefox","common",".mozilla","firefox"),ge(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[ge(process.env.APPDATA??ge(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Pg(e){let t=ge(e,"profiles.ini"),n=et(t)?t:ge(Eg(e),"profiles.ini"),o={};if(!et(n))return o;try{let s=ps(n,"utf8"),r="",i="";for(let a of s.split(`
136
+ `)){let c=a.trim();if(c.startsWith("[")){r="",i="";continue}let l=c.indexOf("=");if(l===-1)continue;let u=c.slice(0,l).trim().toLowerCase(),d=c.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 Do(){let e=[];for(let t of Og().filter(et)){let n=Pg(t),o;try{o=hs(t)}catch{continue}for(let s of o){let r=ge(t,s,"cookies.sqlite");if(!et(r))continue;let i=iu(ge(cu(),"slack-firefox-cookies-")),a=ge(i,"cookies.sqlite");try{Di(r,a);let{default:c}=Zn("bun:sqlite"),l=new c(a,{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{au(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as _i,writeFileSync as $i,mkdirSync as vg,existsSync as ms,rmSync as Lg}from"node:fs";import{join as it}from"node:path";import{createDecipheriv as ko}from"node:crypto";import{spawnSync as Mg}from"node:child_process";var Ng=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),Bg=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),jg=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),dt="C:\\ProgramData\\slack-term-abe";function Wg(){let e=process.env.LOCALAPPDATA??it(process.env.USERPROFILE??"","AppData","Local");return it(e,"Google","Chrome","User Data")}var Ug=String.raw`try {
137
137
  Add-Type -AssemblyName System.Security
138
138
  $d = [IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\in.bin')
139
139
  $o = [Security.Cryptography.ProtectedData]::Unprotect($d, $null, 'CurrentUser')
140
140
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\sys.bin', $o)
141
141
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\dpapi.err' ($_.Exception.Message) }
142
- `,Rg=String.raw`try {
142
+ `,Jg=String.raw`try {
143
143
  Add-Type -TypeDefinition @'
144
144
  using System; using System.Runtime.InteropServices;
145
145
  public static class NC {
@@ -155,7 +155,7 @@ public static class NC {
155
155
  '@
156
156
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\cng.bin', [NC]::Dec([IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\eak.bin')))
157
157
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\cng.err' ($_.Exception.Message) }
158
- `;function Ig(e,t){let n=(o)=>`'${o.replace(/'/g,"''")}'`;return String.raw`
158
+ `;function Kg(e,t){let n=(o)=>`'${o.replace(/'/g,"''")}'`;return String.raw`
159
159
  $ErrorActionPreference = 'Stop'
160
160
  Add-Type -AssemblyName System.Security
161
161
  $work = 'C:\ProgramData\slack-term-abe'
@@ -221,71 +221,71 @@ icacls "$work\Cookies" /grant "$($u):(R)" | Out-Null
221
221
  if (Test-Path "$work\cng.bin") { icacls "$work\cng.bin" /grant "$($u):(R)" | Out-Null }
222
222
  Write-Host 'OK'
223
223
  try { Stop-Transcript | Out-Null } catch {}
224
- `}function Pg(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),a=e.subarray(o+45,o+61),c=s===1?bo("aes-256-gcm",Cg,r):bo("chacha20-poly1305",$g,r,{authTagLength:16});return c.setAuthTag(a),Buffer.concat([c.update(i),c.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),a=e.subarray(o+77,o+93),c=Buffer.from(t.map((u,d)=>u^Ag[d])),l=bo("aes-256-gcm",c,r);return l.setAuthTag(a),Buffer.concat([l.update(i),l.final()])}throw Error(`Unsupported app-bound key flag: ${s}`)}function Og(e,t){let n=t.subarray(3,15),o=t.subarray(15,t.length-16),s=t.subarray(t.length-16),r=bo("aes-256-gcm",e,n);return r.setAuthTag(s),Buffer.concat([r.update(o),r.final()]).subarray(32).toString("utf8")}async function ou(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Fg();if(!hs(it(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);Sg(dt,{recursive:!0});let n=it(dt,"extract.ps1");xi(n,Ig(t,e)),xi(it(dt,"inner_dpapi.ps1"),Tg),xi(it(dt,"inner_cng.ps1"),Rg);let o=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,s=_g("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=it(dt,"out.bin"),i=it(dt,"Cookies");if(!hs(r)||!hs(i)){let a=hs(it(dt,"log.txt"))?ki(it(dt,"log.txt"),"utf8").split(`
225
- `).filter((c)=>c.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${a?` (${a.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let a=ki(r),c=hs(it(dt,"cng.bin"))?ki(it(dt,"cng.bin")):void 0,l=Pg(a,c),{Database:u}=Yn("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 g=Og(l,h);if(!g.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return g}finally{if(!process.env.SLACK_KEEP_ABE)Eg(dt,{recursive:!0,force:!0})}}var Mg=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],Ng=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function Nn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Bg(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:Mg}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function jg(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:Ng}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function jt(e,t){return(await e.question(t)).trim()}async function gs(e,t){if(t)return!0;if(!e)return!1;let n=await jt(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function bn(e,t,n,o){console.error("Verifying token...");let s=await Ln(t,o),r=Nn(s.team),i;if(n)i=n;else if(e)i=await jt(e,`Workspace name [${r}]: `)||r;else i=r;let a=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 c=await jt(e,"Choice [1/2/3/4, Enter=1]: ");if(c==="2")a=Si(process.cwd(),".slack-term",".env.local");else if(c==="3")a=Si(Lg(),".slack-term",".env.local");else if(c==="4")a=null;else a=Si(process.cwd(),".env.local")}if(a===null)if(oo(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 c={SLACK_TOKEN:t};if(o)c.SLACK_COOKIE=o;si(a,c),console.log(`Saved token to ${a}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function Ei(e,t=!1,n="auto",o=!1){console.error("Scanning Slack desktop app...");let s=await yi();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 gs(e,t)){let r=[];if(n!=="chrome")for(let i of wo())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 ps().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 _i(s,e,o)}async function _i(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 bn(t,o.token,Nn(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=Nn(s);oo(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=Nn(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 ru(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 jt(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 jt(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 bn(e,r)}async function Do(e,t){let n=t==="user"?Bg():jg(),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 jt(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 bn(e,r)}async function Wg(e,t){let n=wi();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((c,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}]`));let r=ze({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let a=parseInt(i,10)-1;if(isNaN(a)||a<0||a>=n.length)console.error("Invalid choice."),process.exit(1);s=n[a]}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 ou(s.profileDir)}catch(r){console.error(`
226
- 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 iu(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=as();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=ze({input:process.stdin,output:process.stdout}),a=(await i.question("Choice: ")).trim();i.close();let c=parseInt(a,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c].name}}let o=t.find((r)=>r.name===n);if(o.profile.token.startsWith("xoxb-")){console.error(`
224
+ `}function qg(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),a=e.subarray(o+45,o+61),c=s===1?ko("aes-256-gcm",Ng,r):ko("chacha20-poly1305",Bg,r,{authTagLength:16});return c.setAuthTag(a),Buffer.concat([c.update(i),c.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),a=e.subarray(o+77,o+93),c=Buffer.from(t.map((u,d)=>u^jg[d])),l=ko("aes-256-gcm",c,r);return l.setAuthTag(a),Buffer.concat([l.update(i),l.final()])}throw Error(`Unsupported app-bound key flag: ${s}`)}function Hg(e,t){let n=t.subarray(3,15),o=t.subarray(15,t.length-16),s=t.subarray(t.length-16),r=ko("aes-256-gcm",e,n);return r.setAuthTag(s),Buffer.concat([r.update(o),r.final()]).subarray(32).toString("utf8")}async function pu(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Wg();if(!ms(it(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);vg(dt,{recursive:!0});let n=it(dt,"extract.ps1");$i(n,Kg(t,e)),$i(it(dt,"inner_dpapi.ps1"),Ug),$i(it(dt,"inner_cng.ps1"),Jg);let o=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,s=Mg("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=it(dt,"out.bin"),i=it(dt,"Cookies");if(!ms(r)||!ms(i)){let a=ms(it(dt,"log.txt"))?_i(it(dt,"log.txt"),"utf8").split(`
225
+ `).filter((c)=>c.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${a?` (${a.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let a=_i(r),c=ms(it(dt,"cng.bin"))?_i(it(dt,"cng.bin")):void 0,l=qg(a,c),{Database:u}=Zn("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 g=Hg(l,h);if(!g.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return g}finally{if(!process.env.SLACK_KEEP_ABE)Lg(dt,{recursive:!0,force:!0})}}var Gg=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],Yg=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function Bn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Vg(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:Gg}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function Zg(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:Yg}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function Jt(e,t){return(await e.question(t)).trim()}async function ys(e,t){if(t)return!0;if(!e)return!1;let n=await Jt(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function bn(e,t,n,o){console.error("Verifying token...");let s=await Mn(t,o),r=Bn(s.team),i;if(n)i=n;else if(e)i=await Jt(e,`Workspace name [${r}]: `)||r;else i=r;let a=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 c=await Jt(e,"Choice [1/2/3/4, Enter=1]: ");if(c==="2")a=Ci(process.cwd(),".slack-term",".env.local");else if(c==="3")a=Ci(Xg(),".slack-term",".env.local");else if(c==="4")a=null;else a=Ci(process.cwd(),".env.local")}if(a===null)if(io(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 c={SLACK_TOKEN:t};if(o)c.SLACK_COOKIE=o;ai(a,c),console.log(`Saved token to ${a}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function Ai(e,t=!1,n="auto",o=!1){console.error("Scanning Slack desktop app...");let s=await ki();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 ys(e,t)){let r=[];if(n!=="chrome")for(let i of Do())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 gs().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 Fi(s,e,o)}async function Fi(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 bn(t,o.token,Bn(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=Bn(s);io(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=Bn(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 hu(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 Jt(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 Jt(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 bn(e,r)}async function xo(e,t){let n=t==="user"?Vg():Zg(),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 Jt(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 bn(e,r)}async function Qg(e,t){let n=xi();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((c,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}]`));let r=ze({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let a=parseInt(i,10)-1;if(isNaN(a)||a<0||a>=n.length)console.error("Invalid choice."),process.exit(1);s=n[a]}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 pu(s.profileDir)}catch(r){console.error(`
226
+ 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 gu(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=ls();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=ze({input:process.stdin,output:process.stdout}),a=(await i.question("Choice: ")).trim();i.close();let c=parseInt(a,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c].name}}let o=t.find((r)=>r.name===n);if(o.profile.token.startsWith("xoxb-")){console.error(`
227
227
  Workspace "${n}" uses a bot token (xoxb-). A Chrome session cookie only
228
228
  `+`augments a user session token (xoxc-) — it has no effect on a bot token, so user-level
229
- `+"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 Wg(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:ze({input:process.stdin,output:process.stdout});try{if(!await gs(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,a;try{({candidates:i,totalProfiles:a}=ps())}catch(c){console.error(`Failed: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${a} profile${a!==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&&a<=1)s=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let c=i.length===1?`Found 1 Slack session across ${a} Chrome profiles:`:`Found ${i.length} Slack sessions across ${a} Chrome profiles:`;console.log(c),i.forEach((h,g)=>console.log(` ${g+1}) ${h.profileName} [${h.profileDir}]`)),console.log("");let l=ze({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}}oi(n,s),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Ci(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=wi();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((a)=>a.email===r||a.profileDir===r||a.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" has no Slack session. Available:`),t.forEach((a)=>console.error(` - ${a.email??a.label} [${a.profileDir}] (${a.sessions.length} workspace${a.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((c,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`));let r=ze({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.close();let a=parseInt(i,10)-1;if(isNaN(a)||a<0||a>=t.length)console.error("Invalid choice."),process.exit(1);n=t[a]}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}=ps();s=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(s)Tl(o,s,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,a=Nn(i);oo(a,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:o}),console.log(`Added workspace "${a}": ${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 ${Nn(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 $i(e={}){let t=as();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((a)=>a.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((a)=>a.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((a)=>a.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 a=ze({input:process.stdin,output:process.stdout}),c=(await a.question("Choice: ")).trim();a.close();let l=parseInt(c,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:ze({input:process.stdin,output:process.stdout});try{if(!await gs(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}console.log("Scanning Firefox profiles for Slack session...");let s=wo();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=ze({input:process.stdin,output:process.stdout}),a=(await i.question("Choice: ")).trim();i.close();let c=parseInt(a,10)-1;if(isNaN(c)||c<0||c>=s.length)console.error("Invalid choice."),process.exit(1);r=s[c].cookie}oi(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function au(e={}){if(e.token){await bn(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 bn(null,o,e.name);return}let t=ze({input:process.stdin,output:process.stdout});try{await ru(t)}finally{t.close()}}async function cu(e={}){let t=ze({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await Do(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 jt(t,"Choice [1/2, Enter=1]: ");await Do(t,n==="2"?"bot":"user")}finally{t.close()}}function lu(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",Rl(e.workspace))],o=Bt(e.workspace);if(o)n.push(t("SLACK_COOKIE",o));if(!e.workspace){let s=ro();if(s)n.push(t("SLACK_BOT_TOKEN",s))}console.log(n.join(`
230
- `))}function uu(e){let t=as(),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=vg(e.envfile);si(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 ms(e={}){let t=as();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?ze({input:process.stdin,output:process.stdout}):void 0;try{if(!await gs(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let s=await Di();if(s.length===0)throw Error("No Slack session token found in Chrome profiles.");await _i(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?ze({input:process.stdin,output:process.stdout}):void 0;try{try{await Ei(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 gs(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await Di();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=wo();if(i.length===1)for(let a of r)a.cookie=i[0].cookie}await _i(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?ze({input:process.stdin,output:process.stdout}):void 0;try{await Ei(s,e.yes??!1,o,!0)}finally{s?.close()}return}if(e.token){await bn(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 bn(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=ze({input:process.stdin,output:process.stdout});try{let o=await jt(n,"Choice [1/2/3/4/5]: ");if(console.log(""),o==="1")await Ei(n,e.yes??!1);else if(o==="2"){n.close(),await Ci();return}else if(o==="3")await ru(n);else if(o==="4")await Do(n,"user");else if(o==="5")await Do(n,"bot");else console.error(`Invalid choice: "${o}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function ko(e,t,n,o){let s=t,r=[],i=s,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let l=i.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);a=c+1}for(let c of r){if(!n.has(c))n.set(c,await Mn(e,c,o));let l=n.get(c)??c;s=s.replaceAll(`<@${c}>`,`@${l}`),s=s.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return s}function xo(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"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[r.getUTCDay()]??"",l=a[r.getUTCMonth()]??"";return`${c}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function fu(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Ug(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"),a=String(o.getUTCHours()).padStart(2,"0"),c=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${a}:${c}:${l}.${u}`}async function Kg(e,t,n){let o=typeof t.ts==="string"?t.ts:"0.000000",s=Ug(o),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,h]=await fo(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:"",c=xo(await ko(e,i,n)).split(`
229
+ `+"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 Qg(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:ze({input:process.stdin,output:process.stdout});try{if(!await ys(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,a;try{({candidates:i,totalProfiles:a}=gs())}catch(c){console.error(`Failed: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${a} profile${a!==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&&a<=1)s=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let c=i.length===1?`Found 1 Slack session across ${a} Chrome profiles:`:`Found ${i.length} Slack sessions across ${a} Chrome profiles:`;console.log(c),i.forEach((h,g)=>console.log(` ${g+1}) ${h.profileName} [${h.profileDir}]`)),console.log("");let l=ze({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}}ci(n,s),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Ti(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=xi();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((a)=>a.email===r||a.profileDir===r||a.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" has no Slack session. Available:`),t.forEach((a)=>console.error(` - ${a.email??a.label} [${a.profileDir}] (${a.sessions.length} workspace${a.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((c,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`));let r=ze({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.close();let a=parseInt(i,10)-1;if(isNaN(a)||a<0||a>=t.length)console.error("Invalid choice."),process.exit(1);n=t[a]}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}=gs();s=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(s)Bl(o,s,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,a=Bn(i);io(a,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:o}),console.log(`Added workspace "${a}": ${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 ${Bn(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 Ri(e={}){let t=ls();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((a)=>a.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((a)=>a.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((a)=>a.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 a=ze({input:process.stdin,output:process.stdout}),c=(await a.question("Choice: ")).trim();a.close();let l=parseInt(c,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:ze({input:process.stdin,output:process.stdout});try{if(!await ys(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}console.log("Scanning Firefox profiles for Slack session...");let s=Do();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=ze({input:process.stdin,output:process.stdout}),a=(await i.question("Choice: ")).trim();i.close();let c=parseInt(a,10)-1;if(isNaN(c)||c<0||c>=s.length)console.error("Invalid choice."),process.exit(1);r=s[c].cookie}ci(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function mu(e={}){if(e.token){await bn(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 bn(null,o,e.name);return}let t=ze({input:process.stdin,output:process.stdout});try{await hu(t)}finally{t.close()}}async function yu(e={}){let t=ze({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await xo(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 Jt(t,"Choice [1/2, Enter=1]: ");await xo(t,n==="2"?"bot":"user")}finally{t.close()}}function wu(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",jl(e.workspace))],o=Ut(e.workspace);if(o)n.push(t("SLACK_COOKIE",o));if(!e.workspace){let s=ao();if(s)n.push(t("SLACK_BOT_TOKEN",s))}console.log(n.join(`
230
+ `))}function bu(e){let t=ls(),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=zg(e.envfile);ai(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 ws(e={}){let t=ls();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?ze({input:process.stdin,output:process.stdout}):void 0;try{if(!await ys(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let s=await Ei();if(s.length===0)throw Error("No Slack session token found in Chrome profiles.");await Fi(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?ze({input:process.stdin,output:process.stdout}):void 0;try{try{await Ai(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 ys(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await Ei();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=Do();if(i.length===1)for(let a of r)a.cookie=i[0].cookie}await Fi(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?ze({input:process.stdin,output:process.stdout}):void 0;try{await Ai(s,e.yes??!1,o,!0)}finally{s?.close()}return}if(e.token){await bn(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 bn(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=ze({input:process.stdin,output:process.stdout});try{let o=await Jt(n,"Choice [1/2/3/4/5]: ");if(console.log(""),o==="1")await Ai(n,e.yes??!1);else if(o==="2"){n.close(),await Ti();return}else if(o==="3")await hu(n);else if(o==="4")await xo(n,"user");else if(o==="5")await xo(n,"bot");else console.error(`Invalid choice: "${o}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function So(e,t,n,o){let s=t,r=[],i=s,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let l=i.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);a=c+1}for(let c of r){if(!n.has(c))n.set(c,await Nn(e,c,o));let l=n.get(c)??c;s=s.replaceAll(`<@${c}>`,`@${l}`),s=s.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return s}function Eo(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"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[r.getUTCDay()]??"",l=a[r.getUTCMonth()]??"";return`${c}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function ku(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function em(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"),a=String(o.getUTCHours()).padStart(2,"0"),c=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${a}:${c}:${l}.${u}`}async function tm(e,t,n){let o=typeof t.ts==="string"?t.ts:"0.000000",s=em(o),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,h]=await ho(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:"",c=Eo(await So(e,i,n)).split(`
231
231
  `),l=c[0]+(c.length>1?`
232
232
  `+c.slice(1).map((d)=>` ${d}`).join(`
233
- `):""),u=fu(t)?"↳ ":"";return`${s} ${u}@${r}: ${l}`}async function Jg(e,t,n,o,s,r,i,a){if(a?.aborted)return;return new Promise((c)=>{let l=new e(n);a?.addEventListener("abort",()=>{l.close(),c()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
234
- `)}),l.addEventListener("close",()=>c()),l.addEventListener("error",()=>c()),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 g=typeof d.ts==="string"?d.ts:"";if(!g||r.has(g))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:g)!==s.thread&&g!==s.thread)return}if(s.watchThread&&fu(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(g),r.size>1000){let w=r.values().next().value;if(w!==void 0)r.delete(w)}let m=await Kg(t,d,i);process.stdout.write(m+`
233
+ `):""),u=ku(t)?"↳ ":"";return`${s} ${u}@${r}: ${l}`}async function nm(e,t,n,o,s,r,i,a){if(a?.aborted)return;return new Promise((c)=>{let l=new e(n);a?.addEventListener("abort",()=>{l.close(),c()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
234
+ `)}),l.addEventListener("close",()=>c()),l.addEventListener("error",()=>c()),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 g=typeof d.ts==="string"?d.ts:"";if(!g||r.has(g))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:g)!==s.thread&&g!==s.thread)return}if(s.watchThread&&ku(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(g),r.size>1000){let w=r.values().next().value;if(w!==void 0)r.delete(w)}let m=await tm(t,d,i);process.stdout.write(m+`
235
235
  `)}catch(d){process.stderr.write(`RTM message error: ${d instanceof Error?d.message:String(d)}
236
- `)}})()})})}var du=3,qg=2000,Ai={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:Hl,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function pu(e,t,n,o,s,r,i){let a=Ai.getWebSocket();if(!a)return;for(let c=0;c<du;c++){if(i?.aborted)return;try{let{wsUrl:l}=await Ai.clientBoot(e,t);await Jg(a,e,l,n,o,s,r,i)}catch{}if(i?.aborted)return;if(c<du-1)await Ai.sleep(qg)}}function Wt(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 ft={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:pu};function xt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Fi(e){return Array.isArray(e)?e:[]}function hu(e){return Number(e)||0}function gu(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Hg(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"),a=String(o.getUTCHours()).padStart(2,"0"),c=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${a}:${c}:${l}.${u}`}async function zg(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:"0.000000",i=Hg(r),a="?";if(typeof t.user==="string"){let g=t.user,p="@"+g;if(!n.has(p)){let[,m]=await fo(e,g,s);n.set(p,m)}a=n.get(p)??g}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",u=xo(await ko(e,c,n,s)).split(`
236
+ `)}})()})})}var Du=3,sm=2000,Ii={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:tu,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function xu(e,t,n,o,s,r,i){let a=Ii.getWebSocket();if(!a)return;for(let c=0;c<Du;c++){if(i?.aborted)return;try{let{wsUrl:l}=await Ii.clientBoot(e,t);await nm(a,e,l,n,o,s,r,i)}catch{}if(i?.aborted)return;if(c<Du-1)await Ii.sleep(sm)}}function Kt(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 ft={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:xu};function St(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Oi(e){return Array.isArray(e)?e:[]}function Su(e){return Number(e)||0}function Eu(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function om(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"),a=String(o.getUTCHours()).padStart(2,"0"),c=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${a}:${c}:${l}.${u}`}async function rm(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:"0.000000",i=om(r),a="?";if(typeof t.user==="string"){let g=t.user,p="@"+g;if(!n.has(p)){let[,m]=await ho(e,g,s);n.set(p,m)}a=n.get(p)??g}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",u=Eo(await So(e,c,n,s)).split(`
237
237
  `),d=u[0]+(u.length>1?`
238
238
  `+u.slice(1).map((g)=>` ${g}`).join(`
239
- `):""),f=gu(t)?"↳ ":"",h=o?`${o} @${a}`:`@${a}`;return`${i} ${f}${h}: ${d}`}async function Xg(e,t,n,o,s,r,i){let a=xt(await wn(e,t,20,i?void 0:n||void 0,i,o.cookie)),c=Fi(a.messages).map(xt).reverse(),l=xt(a.response_metadata),u=a.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(o.watchThread&&!i){let m=xt(await Bl(e,t,o.watchThread,50,o.cookie));d=Fi(m.messages).map(xt).filter((w)=>(typeof w.ts==="string"?w.ts:"")!==o.watchThread)}let f=[...c.map((m)=>({m,fromHistory:!0})),...d.map((m)=>({m,fromHistory:!1}))].sort((m,w)=>hu(typeof m.m.ts==="string"?m.m.ts:"")-hu(typeof w.m.ts==="string"?w.m.ts:"")),h=[],g=n,p=!1;for(let{m,fromHistory:w}of f){let b=typeof m.ts==="string"?m.ts:"";if(!b||s.has(b))continue;let D=typeof m.subtype==="string"?m.subtype:"";if(D==="message_changed"||D==="message_deleted")continue;if(o.thread){if((typeof m.thread_ts==="string"?m.thread_ts:b)!==o.thread&&b!==o.thread)continue}if(o.watchThread&&gu(m)){if((typeof m.thread_ts==="string"?m.thread_ts:"")!==o.watchThread)continue}if(o.me&&o.myUserId){if(!(typeof m.text==="string"?m.text:"").includes(`<@${o.myUserId}>`))continue}if(s.add(b),s.size>1000){let F=s.values().next().value;if(F!==void 0)s.delete(F)}if(h.push(await zg(e,m,r,void 0,o.cookie)),w)g=b;let S=typeof m.user==="string"?m.user:"";if(!o.myUserId||S!==o.myUserId)p=!0}return{newCursor:g,lines:h,hasMore:a.has_more===!0,nextPageCursor:u,emittedOther:p}}function Gg(e){if(e.includes("slack.com")){let t=di(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 mu(e,t,n={},o){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
239
+ `):""),f=Eu(t)?"↳ ":"",h=o?`${o} @${a}`:`@${a}`;return`${i} ${f}${h}: ${d}`}async function im(e,t,n,o,s,r,i){let a=St(await wn(e,t,20,i?void 0:n||void 0,i,o.cookie)),c=Oi(a.messages).map(St).reverse(),l=St(a.response_metadata),u=a.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(o.watchThread&&!i){let m=St(await Xl(e,t,o.watchThread,50,o.cookie));d=Oi(m.messages).map(St).filter((w)=>(typeof w.ts==="string"?w.ts:"")!==o.watchThread)}let f=[...c.map((m)=>({m,fromHistory:!0})),...d.map((m)=>({m,fromHistory:!1}))].sort((m,w)=>Su(typeof m.m.ts==="string"?m.m.ts:"")-Su(typeof w.m.ts==="string"?w.m.ts:"")),h=[],g=n,p=!1;for(let{m,fromHistory:w}of f){let b=typeof m.ts==="string"?m.ts:"";if(!b||s.has(b))continue;let D=typeof m.subtype==="string"?m.subtype:"";if(D==="message_changed"||D==="message_deleted")continue;if(o.thread){if((typeof m.thread_ts==="string"?m.thread_ts:b)!==o.thread&&b!==o.thread)continue}if(o.watchThread&&Eu(m)){if((typeof m.thread_ts==="string"?m.thread_ts:"")!==o.watchThread)continue}if(o.me&&o.myUserId){if(!(typeof m.text==="string"?m.text:"").includes(`<@${o.myUserId}>`))continue}if(s.add(b),s.size>1000){let A=s.values().next().value;if(A!==void 0)s.delete(A)}if(h.push(await rm(e,m,r,void 0,o.cookie)),w)g=b;let S=typeof m.user==="string"?m.user:"";if(!o.myUserId||S!==o.myUserId)p=!0}return{newCursor:g,lines:h,hasMore:a.has_more===!0,nextPageCursor:u,emittedOther:p}}function am(e){if(e.includes("slack.com")){let t=gi(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 _u(e,t,n={},o){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
240
240
  Cross-channel mention streaming is not yet supported.
241
- 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 uo(e,t,n.cookie),r=n.interval??60000,i=n.timeout?ft.now()+Wt(n.timeout)*1000:1/0,a=new Map,c=new Set;try{let p=xt(await ql(e,s,n.cookie));if(xt(p.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(p){let m=p instanceof Error?p.message:String(p);if(m.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(m.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(m.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: ${m}`)}let l="";if(n.since){let p=Wt(n.since);l=(ft.now()/1000-p).toFixed(6)}else{let p=xt(await wn(e,s,1,void 0,void 0,n.cookie)),m=Fi(p.messages).map(xt);if(m.length>0&&typeof m[0]?.ts==="string")l=m[0].ts,c.add(l);else l=(ft.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await Ln(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=Gg(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 ft.tailRTM(e,n.cookie,s,f,c,a,o),o?.aborted)return;console.error("RTM unavailable — switching to polling.")}let h=!0,g=ft.now();while(!o?.aborted){if(ft.now()>=i)return;let p=!1;try{let b=ft.now()-g,D=r>0&&b>r*5,S,F=!0;do{let{newCursor:A,lines:C,nextPageCursor:x,emittedOther:J}=await Xg(e,s,l,f,c,a,S);if(l=A,h&&F&&n.since&&C.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
242
- `);F=!1;for(let ne of C)process.stdout.write(ne+`
243
- `);if(J)p=!0;S=D?x:void 0}while(S);h=!1}catch(w){if(w instanceof He){console.error(`Warning: Slack rate limit hit — backing off for ${w.retryAfter}s`),await ft.sleep(w.retryAfter*1000);continue}throw w}if(n.exitOnMessage&&p)return;g=ft.now();let m=i-ft.now();if(m<=0)return;await ft.sleep(Math.min(r,m))}}import{existsSync as Yg,mkdirSync as Du,readFileSync as Ii,renameSync as Vg,unlinkSync as yu,writeFileSync as Pi}from"node:fs";import{dirname as ku}from"node:path";class Ti extends Error{}function wu(e){let t=e,n=(Array.isArray(t.messages)?t.messages:[]).filter((s)=>!!s&&typeof s==="object"&&!Array.isArray(s)),o=t.has_more===!0?t.response_metadata?.next_cursor:void 0;return typeof o==="string"&&o?{messages:n,nextCursor:o}:{messages:n}}function xu(e,t){return{async listChannels(){return(await Wl(e,"public_channel,private_channel,im,mpim",t)).flatMap((o)=>{if(!o||typeof o!=="object"||Array.isArray(o)||typeof o.id!=="string")return[];let s=o.is_im===!0;return[{id:o.id,name:ie(o.name)||o.id,isIm:s,...o.is_mpim===!0?{isMpim:!0}:{},...s&&typeof o.user==="string"?{user:o.user}:{}}]})},history:async(n,o,s)=>wu(await wn(e,n,200,o,s,t)),replies:async(n,o,s,r)=>wu(await jl(e,n,o,{oldest:s,...r?{cursor:r}:{}},t)),userName:(n)=>Mn(e,n,t)}}var Zg="https://github.com/snomiao/slack-term/blob/main/worker/README.md",Qg=1.618,em=25,So=2000,tm=8,fe={now:()=>Date.now(),sleep:(e,t)=>new Promise((n)=>{if(t?.aborted)return n();let o=()=>{clearTimeout(s),n()},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})}),out:(e)=>{process.stdout.write(e+`
241
+ 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 po(e,t,n.cookie),r=n.interval??60000,i=n.timeout?ft.now()+Kt(n.timeout)*1000:1/0,a=new Map,c=new Set;try{let p=St(await eu(e,s,n.cookie));if(St(p.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(p){let m=p instanceof Error?p.message:String(p);if(m.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(m.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(m.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: ${m}`)}let l="";if(n.since){let p=Kt(n.since);l=(ft.now()/1000-p).toFixed(6)}else{let p=St(await wn(e,s,1,void 0,void 0,n.cookie)),m=Oi(p.messages).map(St);if(m.length>0&&typeof m[0]?.ts==="string")l=m[0].ts,c.add(l);else l=(ft.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await Mn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=am(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 ft.tailRTM(e,n.cookie,s,f,c,a,o),o?.aborted)return;console.error("RTM unavailable — switching to polling.")}let h=!0,g=ft.now();while(!o?.aborted){if(ft.now()>=i)return;let p=!1;try{let b=ft.now()-g,D=r>0&&b>r*5,S,A=!0;do{let{newCursor:F,lines:E,nextPageCursor:x,emittedOther:W}=await im(e,s,l,f,c,a,S);if(l=F,h&&A&&n.since&&E.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
242
+ `);A=!1;for(let Q of E)process.stdout.write(Q+`
243
+ `);if(W)p=!0;S=D?x:void 0}while(S);h=!1}catch(w){if(w instanceof He){console.error(`Warning: Slack rate limit hit — backing off for ${w.retryAfter}s`),await ft.sleep(w.retryAfter*1000);continue}throw w}if(n.exitOnMessage&&p)return;g=ft.now();let m=i-ft.now();if(m<=0)return;await ft.sleep(Math.min(r,m))}}import{existsSync as cm,mkdirSync as Fu,readFileSync as Li,renameSync as lm,unlinkSync as $u,writeFileSync as Mi}from"node:fs";import{dirname as Tu}from"node:path";class Pi extends Error{}function Cu(e){let t=e,n=(Array.isArray(t.messages)?t.messages:[]).filter((s)=>!!s&&typeof s==="object"&&!Array.isArray(s)),o=t.has_more===!0?t.response_metadata?.next_cursor:void 0;return typeof o==="string"&&o?{messages:n,nextCursor:o}:{messages:n}}function Ru(e,t){return{async listChannels(){return(await Yl(e,"public_channel,private_channel,im,mpim",t)).flatMap((o)=>{if(!o||typeof o!=="object"||Array.isArray(o)||typeof o.id!=="string")return[];let s=o.is_im===!0;return[{id:o.id,name:ae(o.name)||o.id,isIm:s,...o.is_mpim===!0?{isMpim:!0}:{},...s&&typeof o.user==="string"?{user:o.user}:{}}]})},history:async(n,o,s)=>Cu(await wn(e,n,200,o,s,t)),replies:async(n,o,s,r)=>Cu(await Gl(e,n,o,{oldest:s,...r?{cursor:r}:{}},t)),userName:(n)=>Nn(e,n,t)}}var um="https://github.com/snomiao/slack-term/blob/main/worker/README.md",dm=1.618,fm=25,_o=2000,pm=8,fe={now:()=>Date.now(),sleep:(e,t)=>new Promise((n)=>{if(t?.aborted)return n();let o=()=>{clearTimeout(s),n()},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})}),out:(e)=>{process.stdout.write(e+`
244
244
  `)},err:(e)=>{process.stderr.write(e+`
245
- `)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function Eo(e,t,n){return Math.min(n,Math.round(t*Math.pow(Qg,Math.max(0,e-1))))}var nm=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive","no_permission"],sm=["channel_not_found","not_in_channel","missing_scope","is_archived"];class Ut extends Error{}function Xe(e){return e instanceof Error?e.message:String(e)}function Ri(e){let t=Xe(e);if(nm.some((n)=>t.includes(n)))return"fatal";if(sm.some((n)=>t.includes(n)))return"channel";return"transient"}var ie=(e)=>typeof e==="string"?e:"",he=(e)=>Number(e)||0,pt=(e)=>e.toFixed(6),om=new Set(["message_changed","message_deleted","channel_join","channel_leave","group_join","group_leave"]);function rm(e){let t=[ie(e.text)];if(Array.isArray(e.attachments)){for(let n of e.attachments)if(n&&typeof n==="object"&&!Array.isArray(n))t.push(ie(n.pretext),ie(n.text),ie(n.fallback))}return t.filter(Boolean).join(`
246
- `)}function im(e,t,n,o){let r=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return o&&o!==n?`${r}?thread_ts=${o}&cid=${t}`:r}function am(e,t){if(!Yg(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(Ii(e,"utf8"))}catch(s){throw new Ut(`state file ${e} is unreadable (${Xe(s)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((s)=>s&&typeof s.since==="string"&&typeof s.cursor==="string"&&s.threads&&typeof s.threads==="object")))throw new Ut(`state file ${e} is not a slack stream state; move it aside to start fresh`);if(n.identity!==t)throw new Ut(`state file ${e} belongs to identity ${n.identity}, not ${t}; pass a different --state`);return n}function St(e,t){Du(ku(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;Pi(n,JSON.stringify(t)),Vg(n,e)}function cm(e){let t=`${e}.lock`;Du(ku(t),{recursive:!0});let n=()=>{try{if(Ii(t,"utf8").trim()===String(process.pid))yu(t)}catch{}};try{Pi(t,String(process.pid),{flag:"wx"})}catch{let o=Number(Ii(t,"utf8").trim());if(o&&fe.pidAlive(o))throw new Ut(`another slack stream (pid ${o}) already uses ${e}`);yu(t),Pi(t,String(process.pid),{flag:"wx"})}return n}async function bu(e,t){let n=e.names.get(t);if(n===void 0)n=await e.client.userName(t),e.names.set(t,n);return n}async function Oi(e,t,n,o,s){if(om.has(ie(n.subtype)))return!1;let r=ie(n.user),i=ie(n.bot_id),a=e.opts.repliesTo,c=ie(n.thread_ts);if(o&&a&&c&&(a.has(r)||a.has(i))){let w=e.state.joined??={};w[`${t.id}:${c}`]=Math.max(w[`${t.id}:${c}`]??0,he(ie(n.ts)))}if(r&&e.opts.selfUsers.has(r)||i&&e.opts.selfBots.has(i))return!1;e.opts.grep.lastIndex=0;let l=e.opts.grep.test(rm(n))?"grep":o&&a&&await lm(e,t,a,n,s)?"replies-to":void 0;if(!l)return!1;let u=ie(n.ts),d=`${t.id}:${u}`;if(e.state.seen?.[d]!==void 0)return!1;if(e.opts.relay&&!e.opts.once)(e.state.seen??={})[d]=he(u);let f=ie(n.thread_ts)||null,h=r||i,g=r?await bu(e,r):ie(n.username)||ie(n.bot_profile?.name)||i,p=t.isIm?`@${t.user?await bu(e,t.user):t.id}`:t.isMpim?t.name:`#${t.name}`,m={type:o?"reply":"message",channel:{id:t.id,name:p},ts:u,thread_ts:f,user:{id:h,name:g},text:ie(n.text).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),permalink:im(e.opts.teamUrl,t.id,u,f??void 0),match:l};return e.opts.json?fe.out(JSON.stringify(m)):fe.out(um(m)),e.matches++,!0}async function lm(e,t,n,o,s){if(n.has(ie(o.parent_user_id)))return!0;let r=ie(o.thread_ts),i=Su(e,t,n,r,s);if(i!==void 0)return i;let a=`${t.id}:${r}`,c=e.notJoined?.get(a);if(c!==void 0&&c>=he(ie(o.ts)))return!1;let l=c!==void 0?pt(c):"0";return vi(e,t,n,r,await _o((u)=>e.client.replies(t.id,r,l,u))),e.state.joined?.[a]!==void 0}function Su(e,t,n,o,s){if(e.state.joined?.[`${t.id}:${o}`]!==void 0)return!0;if(!s)return;if(n.has(ie(s.user))||n.has(ie(s.bot_id)))return!0;let r=Array.isArray(s.reply_users)?s.reply_users.map((a)=>ie(a)):void 0;if(r?.some((a)=>n.has(a)))return!0;let i=typeof s.reply_users_count==="number"?s.reply_users_count:void 0;if(r&&(i!==void 0?i<=r.length:r.length<5))return!1;return}function vi(e,t,n,o,s){let r=`${t.id}:${o}`,i=s.filter((c)=>n.has(ie(c.user))||n.has(ie(c.bot_id))).map((c)=>he(ie(c.ts)));if(i.length){let c=e.state.joined??={};c[r]=Math.max(c[r]??0,...i),e.notJoined?.delete(r);return}let a=Math.max(e.notJoined?.get(r)??0,...s.map((c)=>he(ie(c.ts))));(e.notJoined??=new Map).set(r,a)}function um(e){let t=new Date(he(e.ts)*1000).toISOString().replace(/\.\d+Z$/,"Z"),n=e.type==="reply"?"↳ ":"",o=e.text.split(`
245
+ `)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function $o(e,t,n){return Math.min(n,Math.round(t*Math.pow(dm,Math.max(0,e-1))))}var hm=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive","no_permission"],gm=["channel_not_found","not_in_channel","missing_scope","is_archived"];class qt extends Error{}function Xe(e){return e instanceof Error?e.message:String(e)}function vi(e){let t=Xe(e);if(hm.some((n)=>t.includes(n)))return"fatal";if(gm.some((n)=>t.includes(n)))return"channel";return"transient"}var ae=(e)=>typeof e==="string"?e:"",he=(e)=>Number(e)||0,pt=(e)=>e.toFixed(6),mm=new Set(["message_changed","message_deleted","channel_join","channel_leave","group_join","group_leave"]);function ym(e){let t=[ae(e.text)];if(Array.isArray(e.attachments)){for(let n of e.attachments)if(n&&typeof n==="object"&&!Array.isArray(n))t.push(ae(n.pretext),ae(n.text),ae(n.fallback))}return t.filter(Boolean).join(`
246
+ `)}function wm(e,t,n,o){let r=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return o&&o!==n?`${r}?thread_ts=${o}&cid=${t}`:r}function bm(e,t){if(!cm(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(Li(e,"utf8"))}catch(s){throw new qt(`state file ${e} is unreadable (${Xe(s)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((s)=>s&&typeof s.since==="string"&&typeof s.cursor==="string"&&s.threads&&typeof s.threads==="object")))throw new qt(`state file ${e} is not a slack stream state; move it aside to start fresh`);if(n.identity!==t)throw new qt(`state file ${e} belongs to identity ${n.identity}, not ${t}; pass a different --state`);return n}function Et(e,t){Fu(Tu(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;Mi(n,JSON.stringify(t)),lm(n,e)}function Dm(e){let t=`${e}.lock`;Fu(Tu(t),{recursive:!0});let n=()=>{try{if(Li(t,"utf8").trim()===String(process.pid))$u(t)}catch{}};try{Mi(t,String(process.pid),{flag:"wx"})}catch{let o=Number(Li(t,"utf8").trim());if(o&&fe.pidAlive(o))throw new qt(`another slack stream (pid ${o}) already uses ${e}`);$u(t),Mi(t,String(process.pid),{flag:"wx"})}return n}async function Au(e,t){let n=e.names.get(t);if(n===void 0)n=await e.client.userName(t),e.names.set(t,n);return n}async function Ni(e,t,n,o,s){if(mm.has(ae(n.subtype)))return!1;let r=ae(n.user),i=ae(n.bot_id),a=e.opts.repliesTo,c=ae(n.thread_ts);if(o&&a&&c&&(a.has(r)||a.has(i))){let w=e.state.joined??={};w[`${t.id}:${c}`]=Math.max(w[`${t.id}:${c}`]??0,he(ae(n.ts)))}if(r&&e.opts.selfUsers.has(r)||i&&e.opts.selfBots.has(i))return!1;e.opts.grep.lastIndex=0;let l=e.opts.grep.test(ym(n))?"grep":o&&a&&await km(e,t,a,n,s)?"replies-to":void 0;if(!l)return!1;let u=ae(n.ts),d=`${t.id}:${u}`;if(e.state.seen?.[d]!==void 0)return!1;if(e.opts.relay&&!e.opts.once)(e.state.seen??={})[d]=he(u);let f=ae(n.thread_ts)||null,h=r||i,g=r?await Au(e,r):ae(n.username)||ae(n.bot_profile?.name)||i,p=t.isIm?`@${t.user?await Au(e,t.user):t.id}`:t.isMpim?t.name:`#${t.name}`,m={type:o?"reply":"message",channel:{id:t.id,name:p},ts:u,thread_ts:f,user:{id:h,name:g},text:ae(n.text).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),permalink:wm(e.opts.teamUrl,t.id,u,f??void 0),match:l};return e.opts.json?fe.out(JSON.stringify(m)):fe.out(xm(m)),e.matches++,!0}async function km(e,t,n,o,s){if(n.has(ae(o.parent_user_id)))return!0;let r=ae(o.thread_ts),i=Iu(e,t,n,r,s);if(i!==void 0)return i;let a=`${t.id}:${r}`,c=e.notJoined?.get(a);if(c!==void 0&&c>=he(ae(o.ts)))return!1;let l=c!==void 0?pt(c):"0";return Bi(e,t,n,r,await Co((u)=>e.client.replies(t.id,r,l,u))),e.state.joined?.[a]!==void 0}function Iu(e,t,n,o,s){if(e.state.joined?.[`${t.id}:${o}`]!==void 0)return!0;if(!s)return;if(n.has(ae(s.user))||n.has(ae(s.bot_id)))return!0;let r=Array.isArray(s.reply_users)?s.reply_users.map((a)=>ae(a)):void 0;if(r?.some((a)=>n.has(a)))return!0;let i=typeof s.reply_users_count==="number"?s.reply_users_count:void 0;if(r&&(i!==void 0?i<=r.length:r.length<5))return!1;return}function Bi(e,t,n,o,s){let r=`${t.id}:${o}`,i=s.filter((c)=>n.has(ae(c.user))||n.has(ae(c.bot_id))).map((c)=>he(ae(c.ts)));if(i.length){let c=e.state.joined??={};c[r]=Math.max(c[r]??0,...i),e.notJoined?.delete(r);return}let a=Math.max(e.notJoined?.get(r)??0,...s.map((c)=>he(ae(c.ts))));(e.notJoined??=new Map).set(r,a)}function xm(e){let t=new Date(he(e.ts)*1000).toISOString().replace(/\.\d+Z$/,"Z"),n=e.type==="reply"?"↳ ":"",o=e.text.split(`
247
247
  `).join(`
248
248
  `);return`${t} ${e.channel.name} ${n}@${e.user.name}: ${o}
249
- ${e.permalink}`}async function _o(e){let t=[],n;do{let o=await e(n);t.push(...o.messages),n=o.nextCursor}while(n);return t}async function dm(e,t,n,o=!0){let s=e.state.channels[t.id],r=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,a=he(s.cursor),c=o?Math.min(a,i):a,l=(await _o((f)=>e.client.history(t.id,pt(c),f))).sort((f,h)=>he(ie(f.ts))-he(ie(h.ts))),u=e.opts.repliesTo?new Map(l.map((f)=>[ie(f.ts),f])):void 0,d=l.at(-1);if(d&&he(ie(d.ts))>he(s.latest??"0"))s.latest=ie(d.ts);if(o)s.scanned=pt(n);for(let f of l){let h=he(ie(f.ts));if(h<=a||h>r)continue;let g=ie(f.thread_ts),p=await Oi(e,t,f,g!==""&&g!==ie(f.ts),g?u?.get(g):void 0);if(s.cursor=ie(f.ts),p)St(e.opts.statePath,e.state)}if(he(s.cursor)<r)s.cursor=pt(r);for(let f of l){let h=ie(f.ts),g=he(ie(f.latest_reply));if(!g||ie(f.thread_ts)!==h)continue;let p=he(s.threads[h]??s.since);if(g<=p)continue;let m=e.opts.repliesTo,w=m!==void 0&&Su(e,t,m,h,f)===void 0,b=w?Math.min(p,e.notJoined?.get(`${t.id}:${h}`)??0):p,D=(await _o((S)=>e.client.replies(t.id,h,pt(b),S))).sort((S,F)=>he(ie(S.ts))-he(ie(F.ts)));if(w)vi(e,t,m,h,D);for(let S of D){let F=he(ie(S.ts));if(ie(S.ts)===h||F<=p||F>r)continue;let A=ie(S.subtype)!=="thread_broadcast"&&await Oi(e,t,S,!0,f);if(s.threads[h]=ie(S.ts),A)St(e.opts.statePath,e.state)}s.threads[h]=pt(Math.max(he(s.threads[h]??"0"),Math.min(g,r)))}for(let f of Object.keys(s.threads))if(he(f)<i)delete s.threads[f];St(e.opts.statePath,e.state)}async function fm(e,t,n){let o,s,r,i=e.opts.repliesTo,a=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[a]===void 0){let g=Math.min(e.notJoined?.get(a)??0,he(n.ts)-1),p=await _o((m)=>e.client.replies(t.id,n.thread_ts,pt(g),m));if(o=p.find((m)=>ie(m.ts)===n.ts),s=p.find((m)=>ie(m.ts)===n.thread_ts),o)vi(e,t,i,n.thread_ts,p)}for(let g=0;g<5&&!o;g++){let p=await e.client.replies(t.id,n.thread_ts??n.ts,pt(he(n.ts)-1),r);if(o=p.messages.find((m)=>ie(m.ts)===n.ts),s??=n.thread_ts?p.messages.find((m)=>ie(m.ts)===n.thread_ts):void 0,r=p.nextCursor,!r)break}if(!o)return!1;let c=ie(o.thread_ts),l=e.state.channels[t.id],d=c!==""&&c!==n.ts&&ie(o.subtype)!=="thread_broadcast"?l?.threads[c]:l?.cursor;if(d!==void 0&&he(n.ts)<=he(d))return!0;let f=Object.keys(e.state.joined??{}).length;if(await Oi(e,t,o,c!==""&&c!==n.ts,s)||Object.keys(e.state.joined??{}).length!==f)St(e.opts.statePath,e.state);return!0}var pm=2592000;function hm(e,t){if(!e.joined)return;for(let[n,o]of Object.entries(e.joined))if(o<t)delete e.joined[n];if(!Object.keys(e.joined).length)delete e.joined}function gm(e,t){if(!e.seen)return;for(let[n,o]of Object.entries(e.seen))if(o<t)delete e.seen[n];if(!Object.keys(e.seen).length)delete e.seen}var mm=10;function ym(e,t,n){if(!(t>0))return e;let o=60000/t,s=-1/0,r=async()=>{let i=fe.now();s=Math.max(s,i);let a=s-i-(mm-1)*o;if(s+=o,a>0)await fe.sleep(a,n)};return{listChannels:()=>e.listChannels(),userName:(i)=>e.userName(i),history:async(i,a,c)=>(await r(),e.history(i,a,c)),replies:async(i,a,c,l)=>(await r(),e.replies(i,a,c,l))}}function wm(e,t,n,o){let s=n-o.windowSec,r=(f)=>t.channels[f.id],i=(f)=>r(f)?.scanned!==void 0&&he(r(f).latest??"0")<s,a=(f)=>o.once||r(f)?.scanned===void 0||n-he(r(f).scanned)>=o.periodSec,c=new Map,l=e.filter((f)=>!i(f)),u=o.once||o.periodSec<=o.intervalSec?1/0:Math.max(1,Math.ceil(l.length*o.intervalSec/o.periodSec)),d=l.filter(a).sort((f,h)=>he(r(f)?.scanned??"0")-he(r(h)?.scanned??"0")).slice(0,u);for(let f of d)c.set(f.id,"full");for(let f of e){if(c.has(f.id))continue;c.set(f.id,i(f)&&(f.isIm||f.isMpim)&&!a(f)?"skip":"cursor")}return c}async function Eu(e,t){let n=t.maxFailures??(t.once?3:12),o=t.backoffBaseMs??2000,s=t.backoffCapMs??300000,r=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)fe.err(`slack stream: WARNING: polling mode (${t.pollReason??"no relay configured"}) — this is the fallback, `+`not the intended setup: matches arrive up to ${Math.round(t.intervalMs/1000)}s late (replies under older parents up to ${Math.round(Math.max(t.threadScanSec??180,t.intervalMs/1000))}s) and every cycle spends Slack API calls. For real time, deploy the relay and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${Zg}`);e=ym(e,t.callsPerMin??40,t.signal);let a,c=new AbortController,l=()=>c.abort();t.signal?.addEventListener("abort",l,{once:!0});try{a=cm(t.statePath);let u=am(t.statePath,t.identity),d=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(u.joinedBy!==d)delete u.joined;if(d)u.joinedBy=d;else delete u.joinedBy;let f={opts:t,client:e,state:u,names:new Map,matches:0},h=new Set,g=[],p=fe.now()/1000,m=p,w="",b=0,D=0,S=-1/0,F=0,A=(K)=>{fe.err(`slack stream: rate limited — waiting ${K.retryAfter}s`),F=Math.max(F,fe.now()+K.retryAfter*1000)},C=async(K)=>{if(g=(await e.listChannels()).filter((de)=>!t.channels||t.channels.includes(de.id)),t.channels){for(let de of t.channels)if(!g.some((se)=>se.id===de))throw new Ut(`--channel ${de}: the identity is not a member of it`)}let j=Object.keys(u.channels).length===0;for(let de of g){if(u.channels[de.id])continue;let U=Math.min(j||D===0?K:m,t.sinceSec!==void 0?p-t.sinceSec:1/0);u.channels[de.id]={since:pt(U),cursor:pt(U),threads:{}}}m=K,St(t.statePath,u)};if(t.sinceSec!==void 0)u.channels={},delete u.seen,delete u.relay;let x={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},J=new AbortController,ne=()=>J.abort(),L=(K,ae="")=>{if(x.live===K)return;x.live=K,fe.err(K?`slack stream: relay connected — polling every ${Math.round(Math.max(t.intervalMs,i.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${ae?` (${ae})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),ne()},O=async(K)=>{let ae=t.sinceSec===void 0&&u.relay?.url===K.url?{seq:u.relay.seq,...u.relay.epoch?{epoch:u.relay.epoch}:{}}:{seq:0},j=0,de=()=>x.queue.length+x.retry.length+(x.inflight?1:0);while(!c.signal.aborted){while(de()>=So/2&&!c.signal.aborted)await new Promise((M)=>{let pe=()=>M();x.onDrain=()=>{c.signal.removeEventListener("abort",pe),M()},c.signal.addEventListener("abort",pe,{once:!0})});if(c.signal.aborted)return;let se=new AbortController,U=()=>se.abort();c.signal.addEventListener("abort",U,{once:!0});let oe=!1,z="stream closed";try{await K.subscribe(ae,se.signal,{hello:(M)=>{if(j=0,M.gap)x.full=!0;if(M.gap||u.relay?.url!==K.url||u.relay.epoch!==M.epoch){u.relay={url:K.url,seq:M.seq,...M.epoch?{epoch:M.epoch}:{}},x.handled=Math.min(x.handled,M.seq);for(let pe of[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]])pe.seq=Math.min(pe.seq,M.seq)}ae={seq:M.seq,...M.epoch?{epoch:M.epoch}:{}},L(!0)},bell:(M,pe)=>{if(oe)return;if(de()>=So){fe.err(`slack stream: relay backlog over ${So} — pausing the relay until it drains`),oe=!0,se.abort(),L(!1,"paused while its backlog drains");return}ae={...ae,seq:M},x.queue.push({seq:M,bell:pe,tries:0,dueMs:0}),ne()}})}catch(M){if(M instanceof Ti){if(x.live)L(!1,Xe(M));x.live=!1,fe.err(`slack stream: relay disabled for this run: ${Xe(M)} — check SLACK_RELAY_TOKEN`);return}z=Xe(M)}finally{c.signal.removeEventListener("abort",U)}if(c.signal.aborted)return;if(oe)continue;L(!1,z),j++,await fe.sleep(Eo(j,2000,60000),c.signal)}};if(i)O(i);let I=async(K)=>{if(t.channels&&!t.channels.includes(K.channel))return!0;let ae=g.find((de)=>de.id===K.channel);if(!ae){if(fe.now()/1000-m<60)return!1;await C(fe.now()/1000),ae=g.find((de)=>de.id===K.channel)}let j=ae&&u.channels[ae.id];if(!ae||!j||h.has(ae.id))return!0;if(he(K.ts)<he(j.since))return!0;if(K.self&&t.selfUsers.has(K.self)){if(t.repliesTo?.has(K.self)&&K.thread_ts){let de=u.joined??={},se=`${ae.id}:${K.thread_ts}`;de[se]=Math.max(de[se]??0,he(K.ts)),f.notJoined?.delete(se),St(t.statePath,u)}return!0}return fm(f,ae,K)},W=()=>{if(!u.relay||u.relay.url!==i?.url)return;let K=[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]].map((ae)=>ae.seq);u.relay.seq=Math.max(0,K.length?Math.min(...K)-1:Math.max(u.relay.seq,x.handled))},N=async()=>{let K=fe.now(),ae=x.retry.filter((se)=>se.dueMs<=K);if(ae.length)x.retry=x.retry.filter((se)=>se.dueMs>K),x.queue=[...ae,...x.queue].sort((se,U)=>se.seq-U.seq);let j=0;while(x.queue.length&&j<em&&!t.signal?.aborted&&fe.now()>=F){let se=x.queue.shift();x.inflight=se,j++;let U,oe;try{U=await I(se.bell)}catch(z){if(z instanceof He){A(z),se.dueMs=F,x.retry.push(se),x.inflight=void 0;break}U=!1,oe=z}if(x.inflight=void 0,oe!==void 0&&/thread_not_found|message_not_found/.test(Xe(oe)))oe=void 0;if(oe!==void 0&&Ri(oe)==="channel")fe.err(`slack stream: relay bell for ${se.bell.channel} dropped: ${Xe(oe)}`),U=!0;if(oe===void 0&&ee)fe.err("slack stream: relay bell reads recovered"),ee=!1;if(U)x.handled=Math.max(x.handled,se.seq);else if(oe!==void 0){if(se.fails=(se.fails??0)+1,!ee)fe.err(`slack stream: relay bell for ${se.bell.channel} failed (${Xe(oe)}) — retrying`);ee=!0,se.dueMs=fe.now()+Eo(se.fails,1500,60000),x.retry.push(se)}else if(++se.tries>=tm)fe.err(`slack stream: relay bell for ${se.bell.channel} abandoned after ${se.tries} tries (not visible) — only the poll can find it now`),x.handled=Math.max(x.handled,se.seq);else se.dueMs=fe.now()+Eo(se.tries,1500,60000),x.retry.push(se)}if(x.onDrain&&x.queue.length+x.retry.length<So/2)x.onDrain(),x.onDrain=void 0;let de=u.relay?.seq;if(W(),j||u.relay?.seq!==de)St(t.statePath,u)},q=()=>x.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,H=()=>{let K=fe.now();return(K>=S+q()||x.full)&&K>=F},v=()=>x.queue.length>0||x.retry.some((K)=>K.dueMs<=fe.now()),le=!1,ee=!1;while(!t.signal?.aborted){if(H()&&!(le&&v())){x.full=!1;let j=fe.now()/1000;try{if(D%r===0)await C(j);let de=Math.max(0,t.threadScanSec??180),se=wm(g.filter((U)=>!h.has(U.id)),u,j,{windowSec:t.threadWindowSec,periodSec:de,intervalSec:q()/1000,once:t.once});for(let U of g){if(t.signal?.aborted)break;if(h.has(U.id))continue;let oe=se.get(U.id)??"full";if(oe==="skip")continue;for(;;)try{let z=u.channels[U.id],M=oe==="cursor"&&z.scanned!==void 0&&he(z.latest??"0")<j-t.threadWindowSec&&j-he(z.scanned)>=de;if(await dm(f,U,j,oe==="full"),M)z.scanned=pt(j),St(t.statePath,u);break}catch(z){if(z instanceof He){if(A(z),await fe.sleep(F-fe.now(),t.signal),t.signal?.aborted)break;continue}if(Ri(z)==="channel"){h.add(U.id),w=Xe(z),fe.err(`slack stream: skipping ${U.isIm?U.id:"#"+U.name} (${U.id}): ${Xe(z)}`);break}throw z}}if(g.length>0&&g.every((U)=>h.has(U.id)))throw new Ut(`every channel failed — nothing left to watch (last: ${w})`);if(b>0)fe.err(`slack stream: recovered after ${b} failed attempt(s)`);b=0}catch(de){if(de instanceof Ut||Ri(de)==="fatal")return fe.err(`slack stream: fatal: ${Xe(de)}`),3;if(b++,b>=n)return fe.err(`slack stream: giving up after ${b} consecutive failures: ${Xe(de)}`),3;let se=Eo(b,o,s);fe.err(`slack stream: ${Xe(de)} — reconnecting in ${(se/1000).toFixed(1)}s (attempt ${b}/${n})`),await fe.sleep(se,t.signal),x.full=!0;continue}if(D++,gm(u,j-t.threadWindowSec-86400),hm(u,j-pm),t.once){if(St(t.statePath,u),f.matches===0)fe.err(`slack stream: no matches in ${g.length-h.size} channel(s)`);return f.matches>0?0:2}S=j*1000,le=!0}if(t.signal?.aborted)break;let K=fe.now(),ae=Math.max(F,x.queue.length||x.full?K:Math.min(S+q(),...x.retry.map((j)=>j.dueMs)));if(ae>K){J=new AbortController;let j=J,de=()=>j.abort();t.signal?.addEventListener("abort",de,{once:!0}),await fe.sleep(ae-K,j.signal),t.signal?.removeEventListener("abort",de)}if(H()&&!(le&&v()))continue;await N(),le=!1}return 0}catch(u){return fe.err(`slack stream: fatal: ${Xe(u)}`),3}finally{c.abort(),t.signal?.removeEventListener("abort",l),a?.()}}class _u extends Error{}function bm(e,t){let n;while((n=e.indexOf(`
249
+ ${e.permalink}`}async function Co(e){let t=[],n;do{let o=await e(n);t.push(...o.messages),n=o.nextCursor}while(n);return t}async function Sm(e,t,n,o=!0){let s=e.state.channels[t.id],r=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,a=he(s.cursor),c=o?Math.min(a,i):a,l=(await Co((f)=>e.client.history(t.id,pt(c),f))).sort((f,h)=>he(ae(f.ts))-he(ae(h.ts))),u=e.opts.repliesTo?new Map(l.map((f)=>[ae(f.ts),f])):void 0,d=l.at(-1);if(d&&he(ae(d.ts))>he(s.latest??"0"))s.latest=ae(d.ts);if(o)s.scanned=pt(n);for(let f of l){let h=he(ae(f.ts));if(h<=a||h>r)continue;let g=ae(f.thread_ts),p=await Ni(e,t,f,g!==""&&g!==ae(f.ts),g?u?.get(g):void 0);if(s.cursor=ae(f.ts),p)Et(e.opts.statePath,e.state)}if(he(s.cursor)<r)s.cursor=pt(r);for(let f of l){let h=ae(f.ts),g=he(ae(f.latest_reply));if(!g||ae(f.thread_ts)!==h)continue;let p=he(s.threads[h]??s.since);if(g<=p)continue;let m=e.opts.repliesTo,w=m!==void 0&&Iu(e,t,m,h,f)===void 0,b=w?Math.min(p,e.notJoined?.get(`${t.id}:${h}`)??0):p,D=(await Co((S)=>e.client.replies(t.id,h,pt(b),S))).sort((S,A)=>he(ae(S.ts))-he(ae(A.ts)));if(w)Bi(e,t,m,h,D);for(let S of D){let A=he(ae(S.ts));if(ae(S.ts)===h||A<=p||A>r)continue;let F=ae(S.subtype)!=="thread_broadcast"&&await Ni(e,t,S,!0,f);if(s.threads[h]=ae(S.ts),F)Et(e.opts.statePath,e.state)}s.threads[h]=pt(Math.max(he(s.threads[h]??"0"),Math.min(g,r)))}for(let f of Object.keys(s.threads))if(he(f)<i)delete s.threads[f];Et(e.opts.statePath,e.state)}async function Em(e,t,n){let o,s,r,i=e.opts.repliesTo,a=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[a]===void 0){let g=Math.min(e.notJoined?.get(a)??0,he(n.ts)-1),p=await Co((m)=>e.client.replies(t.id,n.thread_ts,pt(g),m));if(o=p.find((m)=>ae(m.ts)===n.ts),s=p.find((m)=>ae(m.ts)===n.thread_ts),o)Bi(e,t,i,n.thread_ts,p)}for(let g=0;g<5&&!o;g++){let p=await e.client.replies(t.id,n.thread_ts??n.ts,pt(he(n.ts)-1),r);if(o=p.messages.find((m)=>ae(m.ts)===n.ts),s??=n.thread_ts?p.messages.find((m)=>ae(m.ts)===n.thread_ts):void 0,r=p.nextCursor,!r)break}if(!o)return!1;let c=ae(o.thread_ts),l=e.state.channels[t.id],d=c!==""&&c!==n.ts&&ae(o.subtype)!=="thread_broadcast"?l?.threads[c]:l?.cursor;if(d!==void 0&&he(n.ts)<=he(d))return!0;let f=Object.keys(e.state.joined??{}).length;if(await Ni(e,t,o,c!==""&&c!==n.ts,s)||Object.keys(e.state.joined??{}).length!==f)Et(e.opts.statePath,e.state);return!0}var _m=2592000;function $m(e,t){if(!e.joined)return;for(let[n,o]of Object.entries(e.joined))if(o<t)delete e.joined[n];if(!Object.keys(e.joined).length)delete e.joined}function Cm(e,t){if(!e.seen)return;for(let[n,o]of Object.entries(e.seen))if(o<t)delete e.seen[n];if(!Object.keys(e.seen).length)delete e.seen}var Am=10;function Fm(e,t,n){if(!(t>0))return e;let o=60000/t,s=-1/0,r=async()=>{let i=fe.now();s=Math.max(s,i);let a=s-i-(Am-1)*o;if(s+=o,a>0)await fe.sleep(a,n)};return{listChannels:()=>e.listChannels(),userName:(i)=>e.userName(i),history:async(i,a,c)=>(await r(),e.history(i,a,c)),replies:async(i,a,c,l)=>(await r(),e.replies(i,a,c,l))}}function Tm(e,t,n,o){let s=n-o.windowSec,r=(f)=>t.channels[f.id],i=(f)=>r(f)?.scanned!==void 0&&he(r(f).latest??"0")<s,a=(f)=>o.once||r(f)?.scanned===void 0||n-he(r(f).scanned)>=o.periodSec,c=new Map,l=e.filter((f)=>!i(f)),u=o.once||o.periodSec<=o.intervalSec?1/0:Math.max(1,Math.ceil(l.length*o.intervalSec/o.periodSec)),d=l.filter(a).sort((f,h)=>he(r(f)?.scanned??"0")-he(r(h)?.scanned??"0")).slice(0,u);for(let f of d)c.set(f.id,"full");for(let f of e){if(c.has(f.id))continue;c.set(f.id,i(f)&&(f.isIm||f.isMpim)&&!a(f)?"skip":"cursor")}return c}async function Ou(e,t){let n=t.maxFailures??(t.once?3:12),o=t.backoffBaseMs??2000,s=t.backoffCapMs??300000,r=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)fe.err(`slack stream: WARNING: polling mode (${t.pollReason??"no relay configured"}) — this is the fallback, `+`not the intended setup: matches arrive up to ${Math.round(t.intervalMs/1000)}s late (replies under older parents up to ${Math.round(Math.max(t.threadScanSec??180,t.intervalMs/1000))}s) and every cycle spends Slack API calls. For real time, deploy the relay and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${um}`);e=Fm(e,t.callsPerMin??40,t.signal);let a,c=new AbortController,l=()=>c.abort();t.signal?.addEventListener("abort",l,{once:!0});try{a=Dm(t.statePath);let u=bm(t.statePath,t.identity),d=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(u.joinedBy!==d)delete u.joined;if(d)u.joinedBy=d;else delete u.joinedBy;let f={opts:t,client:e,state:u,names:new Map,matches:0},h=new Set,g=[],p=fe.now()/1000,m=p,w="",b=0,D=0,S=-1/0,A=0,F=(K)=>{fe.err(`slack stream: rate limited — waiting ${K.retryAfter}s`),A=Math.max(A,fe.now()+K.retryAfter*1000)},E=async(K)=>{if(g=(await e.listChannels()).filter((de)=>!t.channels||t.channels.includes(de.id)),t.channels){for(let de of t.channels)if(!g.some((se)=>se.id===de))throw new qt(`--channel ${de}: the identity is not a member of it`)}let j=Object.keys(u.channels).length===0;for(let de of g){if(u.channels[de.id])continue;let J=Math.min(j||D===0?K:m,t.sinceSec!==void 0?p-t.sinceSec:1/0);u.channels[de.id]={since:pt(J),cursor:pt(J),threads:{}}}m=K,Et(t.statePath,u)};if(t.sinceSec!==void 0)u.channels={},delete u.seen,delete u.relay;let x={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},W=new AbortController,Q=()=>W.abort(),M=(K,re="")=>{if(x.live===K)return;x.live=K,fe.err(K?`slack stream: relay connected${re?` (${re})`:""} — polling every ${Math.round(Math.max(t.intervalMs,i.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${re?` (${re})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),Q()},P=async(K)=>{let re=t.sinceSec===void 0&&u.relay?.url===K.url?{seq:u.relay.seq,...u.relay.epoch?{epoch:u.relay.epoch}:{}}:{seq:0},j=0,de=()=>x.queue.length+x.retry.length+(x.inflight?1:0);while(!c.signal.aborted){while(de()>=_o/2&&!c.signal.aborted)await new Promise((L)=>{let pe=()=>L();x.onDrain=()=>{c.signal.removeEventListener("abort",pe),L()},c.signal.addEventListener("abort",pe,{once:!0})});if(c.signal.aborted)return;let se=new AbortController,J=()=>se.abort();c.signal.addEventListener("abort",J,{once:!0});let oe=!1,z="stream closed";try{await K.subscribe(re,se.signal,{hello:(L)=>{if(j=0,L.gap)x.full=!0;if(L.gap||u.relay?.url!==K.url||u.relay.epoch!==L.epoch){u.relay={url:K.url,seq:L.seq,...L.epoch?{epoch:L.epoch}:{}},x.handled=Math.min(x.handled,L.seq);for(let pe of[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]])pe.seq=Math.min(pe.seq,L.seq)}re={seq:L.seq,...L.epoch?{epoch:L.epoch}:{}},M(!0,L.via)},bell:(L,pe)=>{if(oe)return;if(de()>=_o){fe.err(`slack stream: relay backlog over ${_o} — pausing the relay until it drains`),oe=!0,se.abort(),M(!1,"paused while its backlog drains");return}re={...re,seq:L},x.queue.push({seq:L,bell:pe,tries:0,dueMs:0}),Q()}})}catch(L){if(L instanceof Pi){if(x.live)M(!1,Xe(L));x.live=!1,fe.err(`slack stream: relay disabled for this run: ${Xe(L)} — check SLACK_RELAY_TOKEN`);return}z=Xe(L)}finally{c.signal.removeEventListener("abort",J)}if(c.signal.aborted)return;if(oe)continue;M(!1,z),j++,await fe.sleep($o(j,2000,60000),c.signal)}};if(i)P(i);let I=async(K)=>{if(t.channels&&!t.channels.includes(K.channel))return!0;let re=g.find((de)=>de.id===K.channel);if(!re){if(fe.now()/1000-m<60)return!1;await E(fe.now()/1000),re=g.find((de)=>de.id===K.channel)}let j=re&&u.channels[re.id];if(!re||!j||h.has(re.id))return!0;if(he(K.ts)<he(j.since))return!0;if(K.self&&t.selfUsers.has(K.self)){if(t.repliesTo?.has(K.self)&&K.thread_ts){let de=u.joined??={},se=`${re.id}:${K.thread_ts}`;de[se]=Math.max(de[se]??0,he(K.ts)),f.notJoined?.delete(se),Et(t.statePath,u)}return!0}return Em(f,re,K)},U=()=>{if(!u.relay||u.relay.url!==i?.url)return;let K=[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]].map((re)=>re.seq);u.relay.seq=Math.max(0,K.length?Math.min(...K)-1:Math.max(u.relay.seq,x.handled))},N=async()=>{let K=fe.now(),re=x.retry.filter((se)=>se.dueMs<=K);if(re.length)x.retry=x.retry.filter((se)=>se.dueMs>K),x.queue=[...re,...x.queue].sort((se,J)=>se.seq-J.seq);let j=0;while(x.queue.length&&j<fm&&!t.signal?.aborted&&fe.now()>=A){let se=x.queue.shift();x.inflight=se,j++;let J,oe;try{J=await I(se.bell)}catch(z){if(z instanceof He){F(z),se.dueMs=A,x.retry.push(se),x.inflight=void 0;break}J=!1,oe=z}if(x.inflight=void 0,oe!==void 0&&/thread_not_found|message_not_found/.test(Xe(oe)))oe=void 0;if(oe!==void 0&&vi(oe)==="channel")fe.err(`slack stream: relay bell for ${se.bell.channel} dropped: ${Xe(oe)}`),J=!0;if(oe===void 0&&te)fe.err("slack stream: relay bell reads recovered"),te=!1;if(J)x.handled=Math.max(x.handled,se.seq);else if(oe!==void 0){if(se.fails=(se.fails??0)+1,!te)fe.err(`slack stream: relay bell for ${se.bell.channel} failed (${Xe(oe)}) — retrying`);te=!0,se.dueMs=fe.now()+$o(se.fails,1500,60000),x.retry.push(se)}else if(++se.tries>=pm)fe.err(`slack stream: relay bell for ${se.bell.channel} abandoned after ${se.tries} tries (not visible) — only the poll can find it now`),x.handled=Math.max(x.handled,se.seq);else se.dueMs=fe.now()+$o(se.tries,1500,60000),x.retry.push(se)}if(x.onDrain&&x.queue.length+x.retry.length<_o/2)x.onDrain(),x.onDrain=void 0;let de=u.relay?.seq;if(U(),j||u.relay?.seq!==de)Et(t.statePath,u)},q=()=>x.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,H=()=>{let K=fe.now();return(K>=S+q()||x.full)&&K>=A},v=()=>x.queue.length>0||x.retry.some((K)=>K.dueMs<=fe.now()),le=!1,te=!1;while(!t.signal?.aborted){if(H()&&!(le&&v())){x.full=!1;let j=fe.now()/1000;try{if(D%r===0)await E(j);let de=Math.max(0,t.threadScanSec??180),se=Tm(g.filter((J)=>!h.has(J.id)),u,j,{windowSec:t.threadWindowSec,periodSec:de,intervalSec:q()/1000,once:t.once});for(let J of g){if(t.signal?.aborted)break;if(h.has(J.id))continue;let oe=se.get(J.id)??"full";if(oe==="skip")continue;for(;;)try{let z=u.channels[J.id],L=oe==="cursor"&&z.scanned!==void 0&&he(z.latest??"0")<j-t.threadWindowSec&&j-he(z.scanned)>=de;if(await Sm(f,J,j,oe==="full"),L)z.scanned=pt(j),Et(t.statePath,u);break}catch(z){if(z instanceof He){if(F(z),await fe.sleep(A-fe.now(),t.signal),t.signal?.aborted)break;continue}if(vi(z)==="channel"){h.add(J.id),w=Xe(z),fe.err(`slack stream: skipping ${J.isIm?J.id:"#"+J.name} (${J.id}): ${Xe(z)}`);break}throw z}}if(g.length>0&&g.every((J)=>h.has(J.id)))throw new qt(`every channel failed — nothing left to watch (last: ${w})`);if(b>0)fe.err(`slack stream: recovered after ${b} failed attempt(s)`);b=0}catch(de){if(de instanceof qt||vi(de)==="fatal")return fe.err(`slack stream: fatal: ${Xe(de)}`),3;if(b++,b>=n)return fe.err(`slack stream: giving up after ${b} consecutive failures: ${Xe(de)}`),3;let se=$o(b,o,s);fe.err(`slack stream: ${Xe(de)} — reconnecting in ${(se/1000).toFixed(1)}s (attempt ${b}/${n})`),await fe.sleep(se,t.signal),x.full=!0;continue}if(D++,Cm(u,j-t.threadWindowSec-86400),$m(u,j-_m),t.once){if(Et(t.statePath,u),f.matches===0)fe.err(`slack stream: no matches in ${g.length-h.size} channel(s)`);return f.matches>0?0:2}S=j*1000,le=!0}if(t.signal?.aborted)break;let K=fe.now(),re=Math.max(A,x.queue.length||x.full?K:Math.min(S+q(),...x.retry.map((j)=>j.dueMs)));if(re>K){W=new AbortController;let j=W,de=()=>j.abort();t.signal?.addEventListener("abort",de,{once:!0}),await fe.sleep(re-K,j.signal),t.signal?.removeEventListener("abort",de)}if(H()&&!(le&&v()))continue;await N(),le=!1}return 0}catch(u){return fe.err(`slack stream: fatal: ${Xe(u)}`),3}finally{c.abort(),t.signal?.removeEventListener("abort",l),a?.()}}class Pu extends Error{}function Rm(e,t){let n;while((n=e.indexOf(`
250
250
 
251
251
  `))>=0){let o=e.slice(0,n);e=e.slice(n+2);let s="message",r,i=[];for(let a of o.split(`
252
252
  `)){if(!a||a.startsWith(":"))continue;let c=a.indexOf(":"),l=c<0?a:a.slice(0,c),u=c<0?"":a.slice(c+1).replace(/^ /,"");if(l==="event")s=u;else if(l==="data")i.push(u);else if(l==="id")r=u}if(i.length)t(s,i.join(`
253
- `),r)}return e}function Cu(e,t,n=70000){let o=e.replace(/\/+$/,"");return async(s,r,i)=>{let a=new AbortController,c=()=>a.abort();r.addEventListener("abort",c,{once:!0});let l,u=!1,d=()=>{clearTimeout(l),l=setTimeout(()=>{u=!0,a.abort()},n)};try{d();let f=s===void 0?"":`?after=${s.seq}${s.epoch?`&epoch=${encodeURIComponent(s.epoch)}`:""}`,h=await fetch(`${o}/stream${f}`,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:a.signal});if(h.status===401)throw new _u("relay rejected the token (401)");if(!h.ok||!h.body)throw Error(`relay: HTTP ${h.status}`);let g=h.body.getReader(),p=new TextDecoder,m="";for(;;){let{done:w,value:b}=await g.read();if(w)return;d(),m=bm((m+p.decode(b,{stream:!0})).replace(/\r\n/g,`
254
- `),(D,S,F)=>{let A=JSON.parse(S);if(D==="hello")i.hello(A);else if(D==="bell"&&F!==void 0)i.bell(Number(F),A)})}}catch(f){if(r.aborted)return;if(u)throw Error(`relay: no data for ${Math.round(n/1000)}s`);throw f}finally{clearTimeout(l),r.removeEventListener("abort",c)}}}import{spawn as Dm}from"node:child_process";import{constants as $u}from"node:os";var km=["processing","active","suspended","closed"];function Au(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?ro():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 Fu(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function Tu(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 uo(e,o),thread_ts:s}}function Li(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function xm(e,t,n,o){let s,r,i,a,c,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"),g=()=>f("SIGTERM");process.on("SIGINT",h),process.on("SIGTERM",g);try{if(u=!0,await ls(e,t,"processing"),!l&&o.title!==void 0)await li(e,t,o.title);if(!l){s=Dm(n[0],n.slice(1),{stdio:"inherit"});let p=new Promise((m)=>{s.once("error",()=>{console.error("agent: could not start command"),m(127)}),s.once("exit",(w,b)=>{m(w??(b?128+$u.signals[b]:1))})});a=setInterval(()=>{if(l||c)return;c=ls(e,t,"processing").then(()=>{}).catch((m)=>Li("heartbeat failed; retrying on next tick",m)).finally(()=>{c=void 0})},o.every*1000),d=await p}}catch(p){Li("could not start agent session",p)}finally{if(l=!0,clearInterval(a),clearTimeout(i),await c,u)try{await ls(e,t,o.close?"closed":"active")}catch(p){if(Li("final status clear failed",p),d===0)d=1}process.removeListener("SIGINT",h),process.removeListener("SIGTERM",g)}return r?128+$u.signals[r]:d}function Ru(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:km,demandOption:!0}),async(o)=>{Fu(o.title);let s=Au(o["bot-token-env"]),r=await Tu(s,o.target,t);if(await ls(s,r,o.status),o.title!==void 0)await li(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(Fu(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=Au(o["bot-token-env"]),a=await Tu(i,o.target,t);process.exitCode=await xm(i,a,r,{every:o.every,close:o.close,...o.title!==void 0?{title:o.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}var Te=[{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"}],Et=Te.length,Kt="question";var Bn="heavy_plus_sign";var Ou=["heavy_plus_sign","question"],Dn="information_source";var yt=["ja","en"];function Bi(e,t=process.env){for(let[r,i]of[[e.flag,"flag"],[t.SLACK_TERM_LANG,"env"]]){if(r===void 0||r.trim()==="")continue;let a=r.trim().toLowerCase();return yt.includes(a)?{lang:a,source:i}:null}let n=(e.readerLocales??[]).map(Iu);if(n.length&&n[0]&&n.every((r)=>r===n[0]))return{lang:n[0],source:"readers"};let o=ji((e.content??[]).join(`
255
- `));if(o)return{lang:o,source:"content"};let s=Iu(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(s)return{lang:s,source:"system"};return{lang:"ja",source:"default"}}function Iu(e){let t=(e??"").toLowerCase();return yt.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function ji(e){let t=e.replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ").replace(/:[a-z0-9_+-]+:/g," ");if(/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(t))return"ja";if(/\p{Script=Latin}/u.test(t))return"en";return null}var Le={ja:{instructionReactionThread:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_",instructionReactionHere:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_",instructionTextThread:"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_",instructionTextHere:"_このメッセージに返信してください。本文がそのまま回答になります。_",overflowNote:"_11 番目以降はリアクションがないので、返信で答えてください。_",otherThread:`${":heavy_plus_sign: "}その他 — スレッドで返信してください`,otherHere:`${":heavy_plus_sign: "}その他 — このメッセージに返信してください`,explainLine:`${":information_source: "}説明して — 押すと質問者に説明を頼みます (回答にはなりません)`,explainNote:`${":information_source: "}説明のリクエストを受け付けました — このスレッドで説明します。質問はまだ開いているので、回答はそのあとで大丈夫です。`,invalidPrefix:"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ",answeredVia:(e,t)=>`_${e}で回答済み${t?` (${t})`:""}_`,howReaction:(e)=>`リアクション ${e}`,howReply:"返信",howReplyN:(e)=>`返信 (${e})`,voidStamp:(e)=>`_無効${e?`: ${e}`:""} — この質問への回答は受け付けません。_`,supersededBy:(e)=>`↪ 新しい質問: ${e}`},en:{instructionReactionThread:"_Press one of the reactions below to answer. If none fits, reply in this message's *thread* (ordinary channel posts are not picked up as answers)._",instructionReactionHere:"_Press one of the reactions below to answer. If none fits, reply to this message._",instructionTextThread:"_Reply in this message's *thread* — your reply is the answer (ordinary channel posts are not picked up as answers)._",instructionTextHere:"_Reply to this message — your reply is the answer._",overflowNote:"_Choices 11 and up have no reaction — answer them with a reply._",otherThread:`${":heavy_plus_sign: "}Other — reply in the thread`,otherHere:`${":heavy_plus_sign: "}Other — reply to this message`,explainLine:`${":information_source: "}Explain — press to ask the asker for more detail (not an answer)`,explainNote:`${":information_source: "}Explanation requested — it will follow in this thread. The question stays open; answer it after that.`,invalidPrefix:"_:warning: Several choices are selected, so this is not counted as an answer — keep only one: ",answeredVia:(e,t)=>`_Answered by ${e}${t?` (${t})`:""}_`,howReaction:(e)=>`reaction ${e}`,howReply:"reply",howReplyN:(e)=>`reply (${e})`,voidStamp:(e)=>`_Void${e?`: ${e}`:""} — this question no longer takes answers._`,supersededBy:(e)=>`↪ Replaced by: ${e}`}},Sm=yt.flatMap((e)=>[Le[e].otherThread,Le[e].otherHere].map((t)=>":question: "+t.slice(18)));function vu(e){if(e===void 0)return null;if(e.startsWith(":heavy_plus_sign: ")||e.startsWith("➕ "))return"heavy_plus_sign";if(e.startsWith(":question: ")||e.startsWith("❓ "))return"question";return null}function Em(e){return e!==void 0&&(e.startsWith(":information_source: ")||e.startsWith("ℹ️ "))}function _m(e,t){if(e===void 0)return!1;return(e.startsWith("ℹ️ ")?":information_source: "+e.slice(3):e)===t.explainLine}var Co="_";function Lu(e){if(e===void 0||!e.endsWith(Co))return null;return yt.find((t)=>e.startsWith(Le[t].invalidPrefix))??null}function $o(e){let t=e.split(`
256
- `),n=t[t.length-2];if(!Lu(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function Ao(e,t,n="ja"){let o=e.split(`
257
- `);if(o.length<2)return e;if($o(e).length)o.splice(o.length-2,1);if(t.length)o.splice(o.length-1,0,`${Le[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${Co}`);let s=o.join(`
258
- `);return s===e?e:s}function Fo(e){return typeof e==="string"&&yt.some((t)=>Le[t].explainNote===e.trim())}function Pu(e){return Lu(e)!==null}var Wi="white_check_mark",ws=`:${Wi}: `,Ui="no_entry_sign",Ni=`:${Ui}: `,Cm=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function To(e){return`:${Te[e].name}:`}function Mu(e,t){let n=Te[t];for(let o of[To(t),n.glyph]){if(e.startsWith(`${o} `))return e.slice(o.length+1);if(e===o)return""}return null}function $m(e){return Te.some((t,n)=>Mu(e,n)!==null)}function Oe(e){return e.replace(/\s*\n\s*/g," ")}function Ki(e,t,n,o,s,r="ja",i=!1){let a=Le[r],c=[`:question: *${e}*`];if(t)c.push("",t);if(n.length){if(c.push(""),c.push(...n.map((l,u)=>`${To(u)} ${Oe(l)}`)),c.push(s?a.otherThread:a.otherHere),i)c.push(a.explainLine);if(o.length)c.push(""),c.push(...o.map((l,u)=>`(${u+11}) ${Oe(l)}`)),c.push(a.overflowNote);c.push(""),c.push(s?a.instructionReactionThread:a.instructionReactionHere)}else{if(c.push(""),i)c.push(a.explainLine,"");c.push(s?a.instructionTextThread:a.instructionTextHere)}return c.join(`
259
- `)}function Nu(e,t,n,o="ja",s){let r=t.answer.split(`
253
+ `),r)}return e}var Im="slack-term-relay.v1";function Om(e){return`bearer.${Buffer.from(e,"utf8").toString("base64url")}`}function vu(e){return e==="websocket"||e==="sse"?e:"auto"}var Pm=32;function Lu(e){return e===void 0?"":`?after=${e.seq}${e.epoch?`&epoch=${encodeURIComponent(e.epoch)}`:""}`}function Mu(e,t,n=70000,o={}){let s=e.replace(/\/+$/,""),r=o.transport??"auto",i=Lm(s,t,n);return async(a,c,l)=>{let u=o.WebSocket===void 0?globalThis.WebSocket:o.WebSocket;if(r!=="sse")if(!u){if(r==="websocket")throw Error("relay: this runtime has no WebSocket")}else{if(await vm(u,s,t,n,o.pingMs??25000,o.ackDelayMs??100,a,c,l)||c.aborted)return;if(r==="websocket")throw Error("relay: WebSocket connection failed")}return i(a,c,l)}}function vm(e,t,n,o,s,r,i,a,c){return new Promise((l,u)=>{if(a.aborted)return l(!0);let d;try{d=new e(`${t.replace(/^http/i,"ws")}/ws${Lu(i)}`,[Im,Om(n)])}catch{return l(!1)}let f=!1,h=!1,g,p,m,w=0,b=0,D=(E)=>{if(h)return;h=!0,clearTimeout(g),clearTimeout(p),clearInterval(m),a.removeEventListener("abort",S),d.onopen=d.onmessage=d.onerror=d.onclose=null;try{d.close(1000)}catch{}if(E)u(E);else l(f||a.aborted)},S=()=>D();a.addEventListener("abort",S,{once:!0});let A=()=>{clearTimeout(g),g=setTimeout(()=>D(f?Error(`relay: no data for ${Math.round(o/1000)}s`):void 0),o)},F=()=>{if(clearTimeout(p),p=void 0,w<=b)return;b=w;try{d.send(JSON.stringify({type:"ack",seq:w}))}catch{}};A(),d.onopen=()=>{f=!0,A(),m=setInterval(()=>{try{d.send("ping")}catch{}},s)},d.onmessage=(E)=>{if(A(),typeof E.data!=="string"||E.data==="pong")return;let x;try{x=JSON.parse(E.data)}catch(W){return D(W)}if(x.type==="hello"){let{type:W,...Q}=x;w=b=Q.seq,c.hello({...Q,via:"websocket"})}else if(x.type==="bell"&&typeof x.seq==="number"){if(c.bell(x.seq,x.bell),h)return;if(w=Math.max(w,x.seq),w-b>=Pm)F();else p??=setTimeout(F,r)}},d.onerror=()=>{},d.onclose=(E)=>{if(!f||E.code===1000)return D();D(Error(`relay: WebSocket closed (${E.code}${E.reason?` ${E.reason}`:""})`))}})}function Lm(e,t,n){return async(o,s,r)=>{let i=new AbortController,a=()=>i.abort();s.addEventListener("abort",a,{once:!0});let c,l=!1,u=()=>{clearTimeout(c),c=setTimeout(()=>{l=!0,i.abort()},n)};try{u();let d=await fetch(`${e}/stream${Lu(o)}`,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(d.status===401)throw new Pu("relay rejected the token (401)");if(!d.ok||!d.body)throw Error(`relay: HTTP ${d.status}`);let f=d.body.getReader(),h=new TextDecoder,g="";for(;;){let{done:p,value:m}=await f.read();if(p)return;u(),g=Rm((g+h.decode(m,{stream:!0})).replace(/\r\n/g,`
254
+ `),(w,b,D)=>{let S=JSON.parse(b);if(w==="hello")r.hello({...S,via:"sse"});else if(w==="bell"&&D!==void 0)r.bell(Number(D),S)})}}catch(d){if(s.aborted)return;if(l)throw Error(`relay: no data for ${Math.round(n/1000)}s`);throw d}finally{clearTimeout(c),s.removeEventListener("abort",a)}}}import{spawn as Mm}from"node:child_process";import{constants as Nu}from"node:os";var Nm=["processing","active","suspended","closed"];function Bu(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?ao():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 ju(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function Wu(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 po(e,o),thread_ts:s}}function ji(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function Bm(e,t,n,o){let s,r,i,a,c,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"),g=()=>f("SIGTERM");process.on("SIGINT",h),process.on("SIGTERM",g);try{if(u=!0,await ds(e,t,"processing"),!l&&o.title!==void 0)await pi(e,t,o.title);if(!l){s=Mm(n[0],n.slice(1),{stdio:"inherit"});let p=new Promise((m)=>{s.once("error",()=>{console.error("agent: could not start command"),m(127)}),s.once("exit",(w,b)=>{m(w??(b?128+Nu.signals[b]:1))})});a=setInterval(()=>{if(l||c)return;c=ds(e,t,"processing").then(()=>{}).catch((m)=>ji("heartbeat failed; retrying on next tick",m)).finally(()=>{c=void 0})},o.every*1000),d=await p}}catch(p){ji("could not start agent session",p)}finally{if(l=!0,clearInterval(a),clearTimeout(i),await c,u)try{await ds(e,t,o.close?"closed":"active")}catch(p){if(ji("final status clear failed",p),d===0)d=1}process.removeListener("SIGINT",h),process.removeListener("SIGTERM",g)}return r?128+Nu.signals[r]:d}function Uu(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:Nm,demandOption:!0}),async(o)=>{ju(o.title);let s=Bu(o["bot-token-env"]),r=await Wu(s,o.target,t);if(await ds(s,r,o.status),o.title!==void 0)await pi(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(ju(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=Bu(o["bot-token-env"]),a=await Wu(i,o.target,t);process.exitCode=await Bm(i,a,r,{every:o.every,close:o.close,...o.title!==void 0?{title:o.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}var Te=[{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"}],_t=Te.length,Ht="question";var jn="heavy_plus_sign";var qu=["heavy_plus_sign","question"],Dn="information_source";var wt=["ja","en"];function Ji(e,t=process.env){for(let[r,i]of[[e.flag,"flag"],[t.SLACK_TERM_LANG,"env"]]){if(r===void 0||r.trim()==="")continue;let a=r.trim().toLowerCase();return wt.includes(a)?{lang:a,source:i}:null}let n=(e.readerLocales??[]).map(Ju);if(n.length&&n[0]&&n.every((r)=>r===n[0]))return{lang:n[0],source:"readers"};let o=Ki((e.content??[]).join(`
255
+ `));if(o)return{lang:o,source:"content"};let s=Ju(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(s)return{lang:s,source:"system"};return{lang:"ja",source:"default"}}function Ju(e){let t=(e??"").toLowerCase();return wt.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function Ki(e){let t=e.replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ").replace(/:[a-z0-9_+-]+:/g," ");if(/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(t))return"ja";if(/\p{Script=Latin}/u.test(t))return"en";return null}var Le={ja:{instructionReactionThread:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_",instructionReactionHere:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_",instructionTextThread:"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_",instructionTextHere:"_このメッセージに返信してください。本文がそのまま回答になります。_",overflowNote:"_11 番目以降はリアクションがないので、返信で答えてください。_",otherThread:`${":heavy_plus_sign: "}その他 — スレッドで返信してください`,otherHere:`${":heavy_plus_sign: "}その他 — このメッセージに返信してください`,explainLine:`${":information_source: "}説明して — 押すと質問者に説明を頼みます (回答にはなりません)`,explainNote:`${":information_source: "}説明のリクエストを受け付けました — このスレッドで説明します。質問はまだ開いているので、回答はそのあとで大丈夫です。`,invalidPrefix:"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ",answeredVia:(e,t)=>`_${e}で回答済み${t?` (${t})`:""}_`,howReaction:(e)=>`リアクション ${e}`,howReply:"返信",howReplyN:(e)=>`返信 (${e})`,voidStamp:(e)=>`_無効${e?`: ${e}`:""} — この質問への回答は受け付けません。_`,supersededBy:(e)=>`↪ 新しい質問: ${e}`},en:{instructionReactionThread:"_Press one of the reactions below to answer. If none fits, reply in this message's *thread* (ordinary channel posts are not picked up as answers)._",instructionReactionHere:"_Press one of the reactions below to answer. If none fits, reply to this message._",instructionTextThread:"_Reply in this message's *thread* — your reply is the answer (ordinary channel posts are not picked up as answers)._",instructionTextHere:"_Reply to this message — your reply is the answer._",overflowNote:"_Choices 11 and up have no reaction — answer them with a reply._",otherThread:`${":heavy_plus_sign: "}Other — reply in the thread`,otherHere:`${":heavy_plus_sign: "}Other — reply to this message`,explainLine:`${":information_source: "}Explain — press to ask the asker for more detail (not an answer)`,explainNote:`${":information_source: "}Explanation requested — it will follow in this thread. The question stays open; answer it after that.`,invalidPrefix:"_:warning: Several choices are selected, so this is not counted as an answer — keep only one: ",answeredVia:(e,t)=>`_Answered by ${e}${t?` (${t})`:""}_`,howReaction:(e)=>`reaction ${e}`,howReply:"reply",howReplyN:(e)=>`reply (${e})`,voidStamp:(e)=>`_Void${e?`: ${e}`:""} — this question no longer takes answers._`,supersededBy:(e)=>`↪ Replaced by: ${e}`}},jm=wt.flatMap((e)=>[Le[e].otherThread,Le[e].otherHere].map((t)=>":question: "+t.slice(18)));function Hu(e){if(e===void 0)return null;if(e.startsWith(":heavy_plus_sign: ")||e.startsWith("➕ "))return"heavy_plus_sign";if(e.startsWith(":question: ")||e.startsWith("❓ "))return"question";return null}function Wm(e){return e!==void 0&&(e.startsWith(":information_source: ")||e.startsWith("ℹ️ "))}function Um(e,t){if(e===void 0)return!1;return(e.startsWith("ℹ️ ")?":information_source: "+e.slice(3):e)===t.explainLine}var Ao="_";function zu(e){if(e===void 0||!e.endsWith(Ao))return null;return wt.find((t)=>e.startsWith(Le[t].invalidPrefix))??null}function Fo(e){let t=e.split(`
256
+ `),n=t[t.length-2];if(!zu(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function To(e,t,n="ja"){let o=e.split(`
257
+ `);if(o.length<2)return e;if(Fo(e).length)o.splice(o.length-2,1);if(t.length)o.splice(o.length-1,0,`${Le[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${Ao}`);let s=o.join(`
258
+ `);return s===e?e:s}function Ro(e){return typeof e==="string"&&wt.some((t)=>Le[t].explainNote===e.trim())}function Ku(e){return zu(e)!==null}var qi="white_check_mark",Ds=`:${qi}: `,Hi="no_entry_sign",Ui=`:${Hi}: `,Jm=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function Io(e){return`:${Te[e].name}:`}function Xu(e,t){let n=Te[t];for(let o of[Io(t),n.glyph]){if(e.startsWith(`${o} `))return e.slice(o.length+1);if(e===o)return""}return null}function Km(e){return Te.some((t,n)=>Xu(e,n)!==null)}function ve(e){return e.replace(/\s*\n\s*/g," ")}function zi(e,t,n,o,s,r="ja",i=!1){let a=Le[r],c=[`:question: *${e}*`];if(t)c.push("",t);if(n.length){if(c.push(""),c.push(...n.map((l,u)=>`${Io(u)} ${ve(l)}`)),c.push(s?a.otherThread:a.otherHere),i)c.push(a.explainLine);if(o.length)c.push(""),c.push(...o.map((l,u)=>`(${u+11}) ${ve(l)}`)),c.push(a.overflowNote);c.push(""),c.push(s?a.instructionReactionThread:a.instructionReactionHere)}else{if(c.push(""),i)c.push(a.explainLine,"");c.push(s?a.instructionTextThread:a.instructionTextHere)}return c.join(`
259
+ `)}function Gu(e,t,n,o="ja",s){let r=t.answer.split(`
260
260
  `).map((a)=>`> ${a}`).join(`
261
- `),i=`${ws}*${e}*
261
+ `),i=`${Ds}*${e}*
262
262
  ${Le[o].answeredVia(t.how,n)}
263
263
 
264
264
  ${r}`;if(s?.body)i+=`
265
265
 
266
266
  ${s.body}`;if(s?.chosenLine)i+=`
267
267
 
268
- ${s.chosenLine}`;return i}function Bu(e,t){let n=wt(e);if(n.kind!=="open")return;let o={};if(n.body)o.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)o.chosenLine=`${To(t-1)} ${Oe(n.reactable[t-1])}`;else if(t-Et<=n.overflow.length&&t>Et)o.chosenLine=`(${t}) ${Oe(n.overflow[t-Et-1])}`}return o.body||o.chosenLine?o:void 0}function ju(e,t,n="ja",o,s){let r=Le[n],i=`${Ni}*${e}*
269
- ${r.voidStamp(Oe(t.trim()))}`;if(s)i+=`
268
+ ${s.chosenLine}`;return i}function Yu(e,t){let n=bt(e);if(n.kind!=="open")return;let o={};if(n.body)o.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)o.chosenLine=`${Io(t-1)} ${ve(n.reactable[t-1])}`;else if(t-_t<=n.overflow.length&&t>_t)o.chosenLine=`(${t}) ${ve(n.overflow[t-_t-1])}`}return o.body||o.chosenLine?o:void 0}function Vu(e,t,n="ja",o,s){let r=Le[n],i=`${Ui}*${e}*
269
+ ${r.voidStamp(ve(t.trim()))}`;if(s)i+=`
270
270
  ${r.supersededBy(s)}`;if(o)i+=`
271
271
 
272
- ${o}`;return i}function Wu(e){if(!e.startsWith(":question: "))return null;let t=e.slice(11),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let o=t.slice(n[0].length),s=!1;for(let r of yt){let i=Le[r];for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(o.includes(c))s=!0;for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere,...Sm,i.explainLine])o=o.split(c).join(" ");let a=o.indexOf(i.invalidPrefix);if(a>=0){let c=o.indexOf(Co,a+i.invalidPrefix.length);o=o.slice(0,a)+" "+(c>=0?o.slice(c+Co.length):"")}}if(!s)return null;return{question:n[1],body:o.replace(/[ \t]{3,}/g," ").trim()}}function Uu(e){if(!e[0]?.startsWith(ws))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("&gt; "));for(let n=1;n+2<e.length;n++){let o=e[n];if(o.length>1&&o.startsWith("_")&&o.endsWith("_")&&e[n+1]===""&&t(e[n+2]))return n}return-1}function Ku(e){let t=e.split(`
273
- `),n=Uu(t),s=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!s)return{byReply:!1};return s[1]?{byReply:!0,n:Number(s[1])}:{byReply:!0}}function ys(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function bs(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
274
- `),n=t[t.length-1]??"";if(e.startsWith(ws))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(":question: ")&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function wt(e){let t=e.split(`
275
- `),n=(w)=>e.startsWith(`${w}*`)&&t.some((b,D)=>D>0&&b.length>1&&b.startsWith("_")&&b.endsWith("_"));if(n(Ni)){let w=t.findIndex((F,A)=>A>0&&F.startsWith("_")&&F.endsWith("_")),b=ys(t.slice(0,w>0?w:1).join(`
276
- `).slice(Ni.length).replace(/^\*/,"").replace(/\*$/,"")),D=w>0?t[w].replace(/^_|_$/g,""):"",S=w>0?t[w+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return S?{kind:"void",question:b,reason:D,supersededBy:S}:{kind:"void",question:b,reason:D}}let o=t[0].match(Cm)?e.match(/:question: \*([^\n]*?)\*/):null;if(o)return{kind:"void",question:ys(o[1]),reason:ys(t[0])};if(n(ws)){let w=(A)=>A.startsWith("> ")?A.slice(2):A.startsWith("&gt; ")?A.slice(5):null,b=Uu(t),D;if(b>0){D=[];for(let A=b+2;A<t.length;A++){let C=w(t[A]);if(C===null)break;D.push(C)}}else D=t.map(w).filter((A)=>A!==null);let S=ys(t.slice(0,b>0?b:1).join(`
277
- `).slice(ws.length).replace(/^\*/,"").replace(/\*$/,"")),F=D.map(ys).join(`
278
- `);if(!F)return{kind:"other"};return{kind:"resolved",question:S,answer:F}}let s=t[t.length-1]??"",r,i,a=yt.find((w)=>[Le[w].instructionReactionThread,Le[w].instructionReactionHere,Le[w].instructionTextThread,Le[w].instructionTextHere].includes(s));if(!a)return{kind:"other"};let c=Le[a];r=s===c.instructionReactionThread||s===c.instructionTextThread,i=s===c.instructionReactionThread||s===c.instructionReactionHere;let l=t[0].startsWith(":question: ")?t[0].slice(11):t[0];if(t[0]=l,!t[0].startsWith("*"))return{kind:"other"};let u=0;while(u<t.length&&!(t[u].endsWith("*")&&(u>0||t[0].length>1)))u++;if(u>=t.length)return{kind:"other"};let d=t.slice(0,u+1).join(`
279
- `).replace(/^\*/,"").replace(/\*$/,""),f=[],h=[],g=t.length-1;if(Pu(t[g-1]))g--;let p=!1;if(i){let w=t.length-2;if(Pu(t[w]))w--;if(t[w]!=="")return{kind:"other"};if(w--,t[w]===c.overflowNote){w--;while(w>=0&&/^\(\d+\) /.test(t[w]))h.unshift(t[w].replace(/^\(\d+\) /,"")),w--;if(t[w]!=="")return{kind:"other"};w--}if(Em(t[w]))p=!0,w--;if(vu(t[w]))w--;let b=[];while(w>=0){let D=t[w];if(!$m(D))break;b.unshift(D),w--}if(!b.length||b.length>Et)return{kind:"other"};for(let D=0;D<b.length;D++){let S=Mu(b[D],D);if(S===null)return{kind:"other"};f.push(S)}if(t[w]!=="")return{kind:"other"};if(w<u+1)return{kind:"other"};g=w;for(let D=0;D<h.length;D++)if(!t.includes(`(${D+11}) ${h[D]}`))return{kind:"other"}}else if(t[g-1]===""&&_m(t[g-2],c)&&t[g-3]===""&&g-3>=u)p=!0,g-=2;let m=t.slice(u+1,g).join(`
280
- `).replace(/^\n+|\n+$/g,"");return{kind:"open",question:d,body:m,reactable:f,overflow:h,threadOnly:r,lang:a,explain:p}}function Ds(e){let t=wt(e);if(t.kind!=="open")return null;if(!t.reactable.length)return"question";let n=e.split(`
281
- `),o=To(t.reactable.length-1),s=Te[t.reactable.length-1].glyph,r=-1;for(let i=n.length-1;i>=0;i--)if(n[i].startsWith(`${o} `)||n[i]===o||n[i].startsWith(`${s} `)||n[i]===s){r=i;break}return(r>=0?vu(n[r+1]):null)??"question"}function Mi(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Ju(e,t,n){let o=Array.from({length:n},(r,i)=>i===n-1?t:""),s=Ji(e,o);return s.kind==="chosen"&&s.index===n}function Ji(e,t){let n=Mi(e);if(!n)return{kind:"none"};let o=t.map(Mi),s=new Set;o.forEach((l,u)=>{if(l&&l===n)s.add(u+1)}),Te.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)s.add(u+1)});let r=0,i="",a=n.match(/^(\d{1,2})$/);if(a)r=Number(a[1]);else if(a=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(a[1]),i=Mi(a[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 c=[...s].sort((l,u)=>l-u);if(!c.length)return{kind:"none"};if(c.length>1)return{kind:"ambiguous",indexes:c};return{kind:"chosen",index:c[0]}}var qi=[{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"}],jk=qi.length;var qu=["ja","en"];var Ro={ja:{instructionReactionThread:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_",instructionReactionHere:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_",instructionTextThread:"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_",instructionTextHere:"_このメッセージに返信してください。本文がそのまま回答になります。_",overflowNote:"_11 番目以降はリアクションがないので、返信で答えてください。_",otherThread:`${":heavy_plus_sign: "}その他 — スレッドで返信してください`,otherHere:`${":heavy_plus_sign: "}その他 — このメッセージに返信してください`,explainLine:`${":information_source: "}説明して — 押すと質問者に説明を頼みます (回答にはなりません)`,explainNote:`${":information_source: "}説明のリクエストを受け付けました — このスレッドで説明します。質問はまだ開いているので、回答はそのあとで大丈夫です。`,invalidPrefix:"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ",answeredVia:(e,t)=>`_${e}で回答済み${t?` (${t})`:""}_`,howReaction:(e)=>`リアクション ${e}`,howReply:"返信",howReplyN:(e)=>`返信 (${e})`,voidStamp:(e)=>`_無効${e?`: ${e}`:""} — この質問への回答は受け付けません。_`,supersededBy:(e)=>`↪ 新しい質問: ${e}`},en:{instructionReactionThread:"_Press one of the reactions below to answer. If none fits, reply in this message's *thread* (ordinary channel posts are not picked up as answers)._",instructionReactionHere:"_Press one of the reactions below to answer. If none fits, reply to this message._",instructionTextThread:"_Reply in this message's *thread* — your reply is the answer (ordinary channel posts are not picked up as answers)._",instructionTextHere:"_Reply to this message — your reply is the answer._",overflowNote:"_Choices 11 and up have no reaction — answer them with a reply._",otherThread:`${":heavy_plus_sign: "}Other — reply in the thread`,otherHere:`${":heavy_plus_sign: "}Other — reply to this message`,explainLine:`${":information_source: "}Explain — press to ask the asker for more detail (not an answer)`,explainNote:`${":information_source: "}Explanation requested — it will follow in this thread. The question stays open; answer it after that.`,invalidPrefix:"_:warning: Several choices are selected, so this is not counted as an answer — keep only one: ",answeredVia:(e,t)=>`_Answered by ${e}${t?` (${t})`:""}_`,howReaction:(e)=>`reaction ${e}`,howReply:"reply",howReplyN:(e)=>`reply (${e})`,voidStamp:(e)=>`_Void${e?`: ${e}`:""} — this question no longer takes answers._`,supersededBy:(e)=>`↪ Replaced by: ${e}`}},Wk=qu.flatMap((e)=>[Ro[e].otherThread,Ro[e].otherHere].map((t)=>":question: "+t.slice(18)));var Hu="_";function zu(e){if(e===void 0||!e.endsWith(Hu))return null;return qu.find((t)=>e.startsWith(Ro[t].invalidPrefix))??null}function Hi(e){let t=e.split(`
282
- `),n=t[t.length-2];if(!zu(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function Xu(e,t,n="ja"){let o=e.split(`
283
- `);if(o.length<2)return e;if(Hi(e).length)o.splice(o.length-2,1);if(t.length)o.splice(o.length-1,0,`${Ro[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${Hu}`);let s=o.join(`
284
- `);return s===e?e:s}function Gu(e){return zu(e)!==null}var Am="white_check_mark",Uk=`:${Am}: `,Fm="no_entry_sign",Kk=`:${Fm}: `;var ht=qi,jn=ht.length,xs="ballot_box_with_ballot",zi=`:${xs}: `,Vu="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",Zu="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",Io="_締切: ",Po="_",Gi="bar_chart",Xi=`:${Gi}: `;function Oo(e){return`:${ht[e].name}:`}function Yu(e,t){for(let n of[Oo(t),ht[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function Tm(e){return ht.some((t,n)=>e.startsWith(`${Oo(n)} `)||e.startsWith(`${t.glyph} `))}function ks(e){return e.replace(/\s*\n\s*/g," ")}function Qu(e,t,n,o={}){let s=!!o.multi,r=o.deadline??"",i=o.invalid??[];if(!n.length||n.length>jn)throw Error(`poll needs 1..${jn} choices, got ${n.length}`);let a=[`${zi}*${e}*`];if(t)a.push("",t);if(a.push(""),a.push(...n.map((c,l)=>`${Oo(l)} ${ks(c)}`)),a.push(""),r)a.push(`${Io}${ks(r)}${Po}`);return a.push(s?Zu:Vu),Xu(a.join(`
285
- `),s?[]:i)}function ed(e,t){let n=t.reduce((s,r)=>s+r.count,0),o=[`${Xi}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return o.push(...t.map((s,r)=>`${Oo(r)} ×${s.count} ${ks(s.choice)}`)),o.join(`
286
- `)}function Ss(e){let t=e.split(`
287
- `);if(e.startsWith(Xi)){let f=t[0].slice(Xi.length).replace(/^\*/,"").replace(/\*$/,""),h=[];for(let g=0;g<ht.length;g++){let p=t.map((w)=>Yu(w,g)).find((w)=>w!==null&&w.startsWith("×"));if(p===void 0)break;let m=/^×(\d+) (.*)$/.exec(p);if(!m)return{kind:"other"};h.push({choice:m[2],count:Number(m[1])})}if(!h.length)return{kind:"other"};return{kind:"closed",question:f,tallies:h}}let n=t[t.length-1]??"",o;if(n===Vu)o=!1;else if(n===Zu)o=!0;else return{kind:"other"};if(t[0].startsWith(zi))t[0]=t[0].slice(zi.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(`
288
- `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,a=Hi(e);if(Gu(t[i]))i--;let c="",l=t[i];if(l!==void 0&&l.startsWith(Io)&&l.endsWith(Po)&&l.length>Io.length+Po.length)c=l.slice(Io.length,-Po.length),i--;if(t[i]!=="")return{kind:"other"};i--;let u=[];while(i>=0){let f=t[i];if(!Tm(f))break;u.unshift(f),i--}if(!u.length||u.length>jn)return{kind:"other"};let d=[];for(let f=0;f<u.length;f++){let h=Yu(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:c,invalid:a}}function td(e,t,n,o){let s=new Map(t.map((l)=>[l.name,l.users])),r=e.map((l,u)=>(s.get(ht[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 a=new Set(i),c=r.map((l)=>l.filter((u)=>!a.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:c[u].length})),voters:c,ambiguous:i}}function Rm(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var nd={isTestEnv:()=>Rm(),sleep:(e)=>nd.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Im(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 vo(e,t,n,o=Im()){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 nd.sleep(o)}}var sd=["text","select","user","link","date","number","checkbox"];function rd(e){let t=e.split(":"),n=(t[0]??"").trim(),o=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!sd.includes(o))throw Error(`--col ${e}: unknown type "${o}" (expected one of ${sd.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 od=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function id(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:od[r%od.length]}))};if(t.type==="user")o.options={format:"single_entity"};return o})}function ad(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((o)=>{let s=o??{},i=((s.options??{}).choices??[]).map((a)=>{let c=a??{};return{value:String(c.value??""),label:String(c.label??c.value??"")}});return{id:String(s.id??""),key:String(s.key??""),name:String(s.name??""),type:String(s.type??""),choices:i}})}function Yi(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 Vi(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 Zi(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 cd(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as ea}from"node:child_process";import{chmodSync as Pm,existsSync as ud,mkdirSync as Om}from"node:fs";import{homedir as vm,hostname as Lm}from"node:os";import{basename as dd,dirname as Mm,join as Nm}from"node:path";function Mo(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var Lo={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function Bm(e){try{let n=(ea("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:dd(n[2].trim())}}catch{return}}function jm(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=Bm(e);if(!n)return;if(Lo[n.comm])return n;e=n.ppid}return}function ld(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function fd(e=process.env){let t={pid:process.pid,host:Wm(),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=ld(e.SLACK_TERM_AGENT_PID)??ld(e.CLAUDE_PID);if(!o||!n){let i=jm();if(i)o??=i.pid,n??=Lo[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=Um(t.cwd);if(r)t.gitBranch=r;return t}function Wm(){try{return Lm()}catch{return""}}function Um(e){try{let t=ea("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var Km="slack_term_sent";function pd(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:Km,event_payload:n}}function bt(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return Nm(process.env.HOME||vm(),".config","slack-cli","sent.sqlite")}function Jm(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=Yn("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 qm=`
272
+ ${o}`;return i}function Zu(e){if(!e.startsWith(":question: "))return null;let t=e.slice(11),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let o=t.slice(n[0].length),s=!1;for(let r of wt){let i=Le[r];for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(o.includes(c))s=!0;for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere,...jm,i.explainLine])o=o.split(c).join(" ");let a=o.indexOf(i.invalidPrefix);if(a>=0){let c=o.indexOf(Ao,a+i.invalidPrefix.length);o=o.slice(0,a)+" "+(c>=0?o.slice(c+Ao.length):"")}}if(!s)return null;return{question:n[1],body:o.replace(/[ \t]{3,}/g," ").trim()}}function Qu(e){if(!e[0]?.startsWith(Ds))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("&gt; "));for(let n=1;n+2<e.length;n++){let o=e[n];if(o.length>1&&o.startsWith("_")&&o.endsWith("_")&&e[n+1]===""&&t(e[n+2]))return n}return-1}function ed(e){let t=e.split(`
273
+ `),n=Qu(t),s=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!s)return{byReply:!1};return s[1]?{byReply:!0,n:Number(s[1])}:{byReply:!0}}function bs(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function ks(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
274
+ `),n=t[t.length-1]??"";if(e.startsWith(Ds))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(":question: ")&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function bt(e){let t=e.split(`
275
+ `),n=(w)=>e.startsWith(`${w}*`)&&t.some((b,D)=>D>0&&b.length>1&&b.startsWith("_")&&b.endsWith("_"));if(n(Ui)){let w=t.findIndex((A,F)=>F>0&&A.startsWith("_")&&A.endsWith("_")),b=bs(t.slice(0,w>0?w:1).join(`
276
+ `).slice(Ui.length).replace(/^\*/,"").replace(/\*$/,"")),D=w>0?t[w].replace(/^_|_$/g,""):"",S=w>0?t[w+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return S?{kind:"void",question:b,reason:D,supersededBy:S}:{kind:"void",question:b,reason:D}}let o=t[0].match(Jm)?e.match(/:question: \*([^\n]*?)\*/):null;if(o)return{kind:"void",question:bs(o[1]),reason:bs(t[0])};if(n(Ds)){let w=(F)=>F.startsWith("> ")?F.slice(2):F.startsWith("&gt; ")?F.slice(5):null,b=Qu(t),D;if(b>0){D=[];for(let F=b+2;F<t.length;F++){let E=w(t[F]);if(E===null)break;D.push(E)}}else D=t.map(w).filter((F)=>F!==null);let S=bs(t.slice(0,b>0?b:1).join(`
277
+ `).slice(Ds.length).replace(/^\*/,"").replace(/\*$/,"")),A=D.map(bs).join(`
278
+ `);if(!A)return{kind:"other"};return{kind:"resolved",question:S,answer:A}}let s=t[t.length-1]??"",r,i,a=wt.find((w)=>[Le[w].instructionReactionThread,Le[w].instructionReactionHere,Le[w].instructionTextThread,Le[w].instructionTextHere].includes(s));if(!a)return{kind:"other"};let c=Le[a];r=s===c.instructionReactionThread||s===c.instructionTextThread,i=s===c.instructionReactionThread||s===c.instructionReactionHere;let l=t[0].startsWith(":question: ")?t[0].slice(11):t[0];if(t[0]=l,!t[0].startsWith("*"))return{kind:"other"};let u=0;while(u<t.length&&!(t[u].endsWith("*")&&(u>0||t[0].length>1)))u++;if(u>=t.length)return{kind:"other"};let d=t.slice(0,u+1).join(`
279
+ `).replace(/^\*/,"").replace(/\*$/,""),f=[],h=[],g=t.length-1;if(Ku(t[g-1]))g--;let p=!1;if(i){let w=t.length-2;if(Ku(t[w]))w--;if(t[w]!=="")return{kind:"other"};if(w--,t[w]===c.overflowNote){w--;while(w>=0&&/^\(\d+\) /.test(t[w]))h.unshift(t[w].replace(/^\(\d+\) /,"")),w--;if(t[w]!=="")return{kind:"other"};w--}if(Wm(t[w]))p=!0,w--;if(Hu(t[w]))w--;let b=[];while(w>=0){let D=t[w];if(!Km(D))break;b.unshift(D),w--}if(!b.length||b.length>_t)return{kind:"other"};for(let D=0;D<b.length;D++){let S=Xu(b[D],D);if(S===null)return{kind:"other"};f.push(S)}if(t[w]!=="")return{kind:"other"};if(w<u+1)return{kind:"other"};g=w;for(let D=0;D<h.length;D++)if(!t.includes(`(${D+11}) ${h[D]}`))return{kind:"other"}}else if(t[g-1]===""&&Um(t[g-2],c)&&t[g-3]===""&&g-3>=u)p=!0,g-=2;let m=t.slice(u+1,g).join(`
280
+ `).replace(/^\n+|\n+$/g,"");return{kind:"open",question:d,body:m,reactable:f,overflow:h,threadOnly:r,lang:a,explain:p}}function xs(e){let t=bt(e);if(t.kind!=="open")return null;if(!t.reactable.length)return"question";let n=e.split(`
281
+ `),o=Io(t.reactable.length-1),s=Te[t.reactable.length-1].glyph,r=-1;for(let i=n.length-1;i>=0;i--)if(n[i].startsWith(`${o} `)||n[i]===o||n[i].startsWith(`${s} `)||n[i]===s){r=i;break}return(r>=0?Hu(n[r+1]):null)??"question"}function Wi(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function td(e,t,n){let o=Array.from({length:n},(r,i)=>i===n-1?t:""),s=Xi(e,o);return s.kind==="chosen"&&s.index===n}function Xi(e,t){let n=Wi(e);if(!n)return{kind:"none"};let o=t.map(Wi),s=new Set;o.forEach((l,u)=>{if(l&&l===n)s.add(u+1)}),Te.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)s.add(u+1)});let r=0,i="",a=n.match(/^(\d{1,2})$/);if(a)r=Number(a[1]);else if(a=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(a[1]),i=Wi(a[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 c=[...s].sort((l,u)=>l-u);if(!c.length)return{kind:"none"};if(c.length>1)return{kind:"ambiguous",indexes:c};return{kind:"chosen",index:c[0]}}var Gi=[{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"}],ox=Gi.length;var nd=["ja","en"];var Oo={ja:{instructionReactionThread:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_",instructionReactionHere:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_",instructionTextThread:"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_",instructionTextHere:"_このメッセージに返信してください。本文がそのまま回答になります。_",overflowNote:"_11 番目以降はリアクションがないので、返信で答えてください。_",otherThread:`${":heavy_plus_sign: "}その他 — スレッドで返信してください`,otherHere:`${":heavy_plus_sign: "}その他 — このメッセージに返信してください`,explainLine:`${":information_source: "}説明して — 押すと質問者に説明を頼みます (回答にはなりません)`,explainNote:`${":information_source: "}説明のリクエストを受け付けました — このスレッドで説明します。質問はまだ開いているので、回答はそのあとで大丈夫です。`,invalidPrefix:"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ",answeredVia:(e,t)=>`_${e}で回答済み${t?` (${t})`:""}_`,howReaction:(e)=>`リアクション ${e}`,howReply:"返信",howReplyN:(e)=>`返信 (${e})`,voidStamp:(e)=>`_無効${e?`: ${e}`:""} — この質問への回答は受け付けません。_`,supersededBy:(e)=>`↪ 新しい質問: ${e}`},en:{instructionReactionThread:"_Press one of the reactions below to answer. If none fits, reply in this message's *thread* (ordinary channel posts are not picked up as answers)._",instructionReactionHere:"_Press one of the reactions below to answer. If none fits, reply to this message._",instructionTextThread:"_Reply in this message's *thread* — your reply is the answer (ordinary channel posts are not picked up as answers)._",instructionTextHere:"_Reply to this message — your reply is the answer._",overflowNote:"_Choices 11 and up have no reaction — answer them with a reply._",otherThread:`${":heavy_plus_sign: "}Other — reply in the thread`,otherHere:`${":heavy_plus_sign: "}Other — reply to this message`,explainLine:`${":information_source: "}Explain — press to ask the asker for more detail (not an answer)`,explainNote:`${":information_source: "}Explanation requested — it will follow in this thread. The question stays open; answer it after that.`,invalidPrefix:"_:warning: Several choices are selected, so this is not counted as an answer — keep only one: ",answeredVia:(e,t)=>`_Answered by ${e}${t?` (${t})`:""}_`,howReaction:(e)=>`reaction ${e}`,howReply:"reply",howReplyN:(e)=>`reply (${e})`,voidStamp:(e)=>`_Void${e?`: ${e}`:""} — this question no longer takes answers._`,supersededBy:(e)=>`↪ Replaced by: ${e}`}},rx=nd.flatMap((e)=>[Oo[e].otherThread,Oo[e].otherHere].map((t)=>":question: "+t.slice(18)));var sd="_";function od(e){if(e===void 0||!e.endsWith(sd))return null;return nd.find((t)=>e.startsWith(Oo[t].invalidPrefix))??null}function Yi(e){let t=e.split(`
282
+ `),n=t[t.length-2];if(!od(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function rd(e,t,n="ja"){let o=e.split(`
283
+ `);if(o.length<2)return e;if(Yi(e).length)o.splice(o.length-2,1);if(t.length)o.splice(o.length-1,0,`${Oo[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${sd}`);let s=o.join(`
284
+ `);return s===e?e:s}function id(e){return od(e)!==null}var qm="white_check_mark",ix=`:${qm}: `,Hm="no_entry_sign",ax=`:${Hm}: `;var ht=Gi,Wn=ht.length,Es="ballot_box_with_ballot",Vi=`:${Es}: `,cd="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",ld="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",Po="_締切: ",vo="_",Qi="bar_chart",Zi=`:${Qi}: `;function Lo(e){return`:${ht[e].name}:`}function ad(e,t){for(let n of[Lo(t),ht[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function zm(e){return ht.some((t,n)=>e.startsWith(`${Lo(n)} `)||e.startsWith(`${t.glyph} `))}function Ss(e){return e.replace(/\s*\n\s*/g," ")}function ud(e,t,n,o={}){let s=!!o.multi,r=o.deadline??"",i=o.invalid??[];if(!n.length||n.length>Wn)throw Error(`poll needs 1..${Wn} choices, got ${n.length}`);let a=[`${Vi}*${e}*`];if(t)a.push("",t);if(a.push(""),a.push(...n.map((c,l)=>`${Lo(l)} ${Ss(c)}`)),a.push(""),r)a.push(`${Po}${Ss(r)}${vo}`);return a.push(s?ld:cd),rd(a.join(`
285
+ `),s?[]:i)}function dd(e,t){let n=t.reduce((s,r)=>s+r.count,0),o=[`${Zi}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return o.push(...t.map((s,r)=>`${Lo(r)} ×${s.count} ${Ss(s.choice)}`)),o.join(`
286
+ `)}function _s(e){let t=e.split(`
287
+ `);if(e.startsWith(Zi)){let f=t[0].slice(Zi.length).replace(/^\*/,"").replace(/\*$/,""),h=[];for(let g=0;g<ht.length;g++){let p=t.map((w)=>ad(w,g)).find((w)=>w!==null&&w.startsWith("×"));if(p===void 0)break;let m=/^×(\d+) (.*)$/.exec(p);if(!m)return{kind:"other"};h.push({choice:m[2],count:Number(m[1])})}if(!h.length)return{kind:"other"};return{kind:"closed",question:f,tallies:h}}let n=t[t.length-1]??"",o;if(n===cd)o=!1;else if(n===ld)o=!0;else return{kind:"other"};if(t[0].startsWith(Vi))t[0]=t[0].slice(Vi.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(`
288
+ `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,a=Yi(e);if(id(t[i]))i--;let c="",l=t[i];if(l!==void 0&&l.startsWith(Po)&&l.endsWith(vo)&&l.length>Po.length+vo.length)c=l.slice(Po.length,-vo.length),i--;if(t[i]!=="")return{kind:"other"};i--;let u=[];while(i>=0){let f=t[i];if(!zm(f))break;u.unshift(f),i--}if(!u.length||u.length>Wn)return{kind:"other"};let d=[];for(let f=0;f<u.length;f++){let h=ad(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:c,invalid:a}}function fd(e,t,n,o){let s=new Map(t.map((l)=>[l.name,l.users])),r=e.map((l,u)=>(s.get(ht[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 a=new Set(i),c=r.map((l)=>l.filter((u)=>!a.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:c[u].length})),voters:c,ambiguous:i}}function Xm(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var pd={isTestEnv:()=>Xm(),sleep:(e)=>pd.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Gm(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 Mo(e,t,n,o=Gm()){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 pd.sleep(o)}}var hd=["text","select","user","link","date","number","checkbox"];function md(e){let t=e.split(":"),n=(t[0]??"").trim(),o=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!hd.includes(o))throw Error(`--col ${e}: unknown type "${o}" (expected one of ${hd.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 gd=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function yd(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:gd[r%gd.length]}))};if(t.type==="user")o.options={format:"single_entity"};return o})}function wd(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((o)=>{let s=o??{},i=((s.options??{}).choices??[]).map((a)=>{let c=a??{};return{value:String(c.value??""),label:String(c.label??c.value??"")}});return{id:String(s.id??""),key:String(s.key??""),name:String(s.name??""),type:String(s.type??""),choices:i}})}function ea(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 ta(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 na(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 bd(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as oa}from"node:child_process";import{chmodSync as Ym,existsSync as kd,mkdirSync as Vm}from"node:fs";import{homedir as Zm,hostname as Qm}from"node:os";import{basename as xd,dirname as ey,join as ty}from"node:path";function Bo(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var No={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function ny(e){try{let n=(oa("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:xd(n[2].trim())}}catch{return}}function sy(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=ny(e);if(!n)return;if(No[n.comm])return n;e=n.ppid}return}function Dd(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Sd(e=process.env){let t={pid:process.pid,host:oy(),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=Dd(e.SLACK_TERM_AGENT_PID)??Dd(e.CLAUDE_PID);if(!o||!n){let i=sy();if(i)o??=i.pid,n??=No[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=ry(t.cwd);if(r)t.gitBranch=r;return t}function oy(){try{return Qm()}catch{return""}}function ry(e){try{let t=oa("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var iy="slack_term_sent";function Ed(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:iy,event_payload:n}}function Dt(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return ty(process.env.HOME||Zm(),".config","slack-cli","sent.sqlite")}function ay(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=Zn("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 cy=`
289
289
  CREATE TABLE IF NOT EXISTS sent (
290
290
  id INTEGER PRIMARY KEY AUTOINCREMENT,
291
291
  kind TEXT NOT NULL,
@@ -314,161 +314,162 @@ CREATE TABLE IF NOT EXISTS sent (
314
314
  );
315
315
  CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
316
316
  CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
317
- `;function No(){let e=bt();try{Om(Mm(e),{recursive:!0})}catch{}let t=Jm(e);if(!t)return;try{Pm(e,384)}catch{}try{t.exec(qm);for(let n of["delivered_answer TEXT","delivered_cursor TEXT"])try{t.exec(`ALTER TABLE sent ADD COLUMN ${n}`)}catch{}return t}catch{try{t.close()}catch{}return}}function hd(e){if(!Mo())return!1;let t=No();if(!t)return console.error(` (送信ログに記録できませんでした: ${Es} — ${bt()})`),!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)
318
- 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 Es="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function ta(e){let t=No();if(!t)return;try{let n=[],o=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),o.push(`%${Qi(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(`${Qi(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),o.push(`${Qi(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 Qi(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function Bo(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}function gd(e,...t){if(!Mo()||!ud(bt()))return;let n=No();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function na(e,t,n,o){let s=Date.now();gd(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
317
+ `;function jo(){let e=Dt();try{Vm(ey(e),{recursive:!0})}catch{}let t=ay(e);if(!t)return;try{Ym(e,384)}catch{}try{t.exec(cy);for(let n of["delivered_answer TEXT","delivered_cursor TEXT"])try{t.exec(`ALTER TABLE sent ADD COLUMN ${n}`)}catch{}return t}catch{try{t.close()}catch{}return}}function _d(e){if(!Bo())return!1;let t=jo();if(!t)return console.error(` (送信ログに記録できませんでした: ${$s} — ${Dt()})`),!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)
318
+ 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 $s="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function ra(e){let t=jo();if(!t)return;try{let n=[],o=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),o.push(`%${sa(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(`${sa(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),o.push(`${sa(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 sa(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function Wo(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}function $d(e,...t){if(!Bo()||!kd(Dt()))return;let n=jo();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function ia(e,t,n,o){let s=Date.now();$d(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
319
319
  delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
320
- WHERE kind = 'ask' AND channel = ? AND ts = ?`,s,n,s,n,o,e,t)}function md(e,t,n,o){gd(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
321
- WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,o,e,t)}function yd(e){if(!ud(bt()))return[];let t=No();if(!t)return;try{return t.prepare("SELECT * FROM sent WHERE kind = 'ask' AND collected_at IS NULL AND sent_at >= ? ORDER BY sent_at ASC, id ASC").all(e)}finally{try{t.close()}catch{}}}function wd(e){let t=e.agent_pid??e.pid;if(!Hm(t))return!1;try{let o=(ea("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),s=Date.parse(o.slice(0,24));if(!Number.isNaN(s)&&s>e.sent_at+1000)return!1;let r=dd(o.slice(24).trim()),i=new Set(Object.values(Lo));if(e.cli&&i.has(e.cli)&&r&&Lo[r]!==e.cli)return!1}catch{}return!0}function Hm(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class _t extends Error{retryAfter;method;constructor(e,t){super(t?`Slack rate limited on ${t} — retry after ${e}s`:`Slack rate limited — retry after ${e}s`);if(this.name="RateLimitError",this.retryAfter=e,t)this.method=t}}function ra(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function kd(e,t,n,o){o=e.startsWith("xoxc-")?o??Bt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ra()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new _t(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new _t(60,t);if(a==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
320
+ WHERE kind = 'ask' AND channel = ? AND ts = ?`,s,n,s,n,o,e,t)}function Cd(e,t,n,o){$d(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
321
+ WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,o,e,t)}function Ad(e){if(!kd(Dt()))return[];let t=jo();if(!t)return;try{return t.prepare("SELECT * FROM sent WHERE kind = 'ask' AND collected_at IS NULL AND sent_at >= ? ORDER BY sent_at ASC, id ASC").all(e)}finally{try{t.close()}catch{}}}function Fd(e){let t=e.agent_pid??e.pid;if(!ly(t))return!1;try{let o=(oa("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),s=Date.parse(o.slice(0,24));if(!Number.isNaN(s)&&s>e.sent_at+1000)return!1;let r=xd(o.slice(24).trim()),i=new Set(Object.values(No));if(e.cli&&i.has(e.cli)&&r&&No[r]!==e.cli)return!1}catch{}return!0}function ly(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class $t extends Error{retryAfter;method;constructor(e,t){super(t?`Slack rate limited on ${t} — retry after ${e}s`:`Slack rate limited — retry after ${e}s`);if(this.name="RateLimitError",this.retryAfter=e,t)this.method=t}}function la(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function Id(e,t,n,o){o=e.startsWith("xoxc-")?o??Ut():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${la()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new $t(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new $t(60,t);if(a==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
322
322
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
323
323
  Or replace the token with an xoxp- user token:
324
324
  slack auth login`);if((a==="missing_scope"||a==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${a}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${a} — ${a==="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"}.
325
325
  Tailing/DMing people and listing users need a user session, not a bot token.
326
326
  Switch workspace: slack auth ls then slack auth use <name>
327
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${a}`)}return i}async function zm(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ra()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new _t(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new _t(60,t);if((a==="invalid_auth"||a==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
327
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${a}`)}return i}async function uy(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${la()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new $t(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new $t(60,t);if((a==="invalid_auth"||a==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
328
328
  Import from Slack desktop: slack auth login`);if((a==="invalid_auth"||a==="not_authed")&&!o)throw Error(`${t} also requires the xoxd session cookie.
329
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${a}`)}return i}function Jt(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return zm(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function me(e,t,n,o){let s=new URLSearchParams(n).toString();return kd(e,`${t}?${s}`,{method:"GET"},o)}function Re(e,t,n,o){return kd(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function ia(e,t){let n=await me(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function qt(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(`${ra()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new _t(isNaN(i)?60:i,"auth.test")}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 xd(e,t,n){let o=await me(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function tt(e,t,n=20,o,s,r,i){let a={channel:t,limit:String(n)};if(o!==void 0)a.oldest=o;if(s!==void 0)a.cursor=s;if(i)a.inclusive="true";return jo(await me(e,"conversations.history",a,r))}function jo(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let o of n)ao(o);return e}async function Ue(e,t,n,o=50,s){return jo(await me(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s))}async function Sd(e,t,n,o={},s){let r={channel:t,ts:n,limit:String(o.limit??200)};if(o.oldest!==void 0)r.oldest=o.oldest;if(o.cursor!==void 0)r.cursor=o.cursor;return jo(await me(e,"conversations.replies",r,s))}async function Ed(e,t,n){return me(e,"files.info",{file:t},n)}async function _d(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 me(e,"files.list",o,n)}async function Cd(e,t,n,o){let s={name:t,schema:n};if(o)s.todo_mode=!0;return await Re(e,"slackLists.create",s)}async function aa(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 Re(e,"slackLists.items.list",o)}async function $d(e,t,n){return await Re(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function Ad(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 Re(e,"slackLists.access.set",s)}async function Fd(e,t,n){return await Re(e,"slackLists.items.update",{list_id:t,cells:n})}async function Td(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 Jt(e,"lists.records.list",s,o)}async function Rd(e,t,n,o,s){return jo(await me(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 Id(e,t,n){return Rd(e,t,100,1,n)}async function ca(e,t,n,o){let r=1,i=[],a={ok:!0,messages:{}};while(!0){let l=await Rd(e,t,100,r,o),u=_s(l,["messages","matches"]),d=Array.isArray(u)?u:[];i.push(...d);let f=Number(_s(l,["messages","paging","pages"])??1);if(a=l,d.length===0||r>=f||i.length>=n)break;r+=1}let c=a;if(!c.messages)c.messages={};return c.messages.matches=i.slice(0,n),c}async function Ht(e,t,n,o,s,r,i,a){let c=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(o!==void 0)c.thread_ts=o;if(s&&o!==void 0)c.reply_broadcast=!0;return(await Pd(e,"chat.postMessage",c,a,r)).ts??""}function Xm(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function Pd(e,t,n,o,s){if(!o)return Re(e,t,n,s);try{return await Re(e,t,{...n,metadata:o},s)}catch(r){if(!Xm(r))throw r;return Re(e,t,n,s)}}async function Od(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 Re(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function vd(e,t,n){let o={};if(t)o.channel=t;return me(e,"chat.scheduledMessages.list",o,n)}async function Ld(e,t,n,o){await Re(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},o)}async function Wn(e,t,n,o){return(await me(e,"chat.getPermalink",{channel:t,message_ts:n},o)).permalink??""}async function Ct(e,t,n,o,s,r,i){return(await Pd(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 Md(e,t,n,o){await Re(e,"chat.delete",{channel:t,ts:n},o)}async function Nd(e,t,n,o,s=200,r){let i={channel:t,ts:n,limit:String(s)};if(o!==void 0)i.cursor=o;return me(e,"conversations.replies",i,r)}async function la(e,t,n,o){await Re(e,"pins.add",{channel:t,timestamp:n},o)}async function $t(e,t,n,o,s){await Re(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Bd(e,t,n,o){return((await me(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 At(e,t,n,o,s){await Re(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function jd(e,t,n=!1,o){let s=await Re(e,"conversations.create",{name:t,is_private:n},o);return{id:s.channel?.id??"",name:s.channel?.name??t}}async function Wd(e,t,n,o){let s=await Re(e,"conversations.rename",{channel:t,name:n},o);return{id:s.channel?.id??t,name:s.channel?.name??n}}async function Ud(e,t,n,o){await Re(e,"conversations.invite",{channel:t,users:n.join(",")},o)}async function Cs(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 me(e,"conversations.list",s,t);if(n.push(...r.channels??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{channels:n}}async function Ft(e,t,n){let s=(await Re(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Kd(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await me(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 sa(e,t,n,o){let s=await Kd(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 kn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function bd(e,t){let n=kn(e.name??""),o=kn(e.real_name??e.profile?.real_name??""),s=kn(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Jd=200;async function qd(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await me(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(bd(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,a=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await me(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Jd){c=!0;break}s.add(h),i++;let g;try{g=(await me(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof _t)throw p;a++;continue}if(g&&bd(g,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:a,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:a,capped:c}}function Hd(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
329
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${a}`)}return i}function gt(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return uy(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function me(e,t,n,o){let s=new URLSearchParams(n).toString();return Id(e,`${t}?${s}`,{method:"GET"},o)}function Re(e,t,n,o){return Id(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function ua(e,t){let n=await me(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Ct(e,t){t=e.startsWith("xoxc-")?t??Ut():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${la()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new $t(isNaN(i)?60:i,"auth.test")}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 Od(e,t,n){let o=await me(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function tt(e,t,n=20,o,s,r,i){let a={channel:t,limit:String(n)};if(o!==void 0)a.oldest=o;if(s!==void 0)a.cursor=s;if(i)a.inclusive="true";return Uo(await me(e,"conversations.history",a,r))}function Uo(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let o of n)lo(o);return e}async function Me(e,t,n,o=50,s){return Uo(await me(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s))}async function Pd(e,t,n,o={},s){let r={channel:t,ts:n,limit:String(o.limit??200)};if(o.oldest!==void 0)r.oldest=o.oldest;if(o.cursor!==void 0)r.cursor=o.cursor;return Uo(await me(e,"conversations.replies",r,s))}async function vd(e,t,n){return me(e,"files.info",{file:t},n)}async function Ld(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 me(e,"files.list",o,n)}async function Md(e,t,n,o){let s={name:t,schema:n};if(o)s.todo_mode=!0;return await Re(e,"slackLists.create",s)}async function da(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 Re(e,"slackLists.items.list",o)}async function Nd(e,t,n){return await Re(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function Bd(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 Re(e,"slackLists.access.set",s)}async function jd(e,t,n){return await Re(e,"slackLists.items.update",{list_id:t,cells:n})}async function Wd(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 Ud(e,t,n,o,s){return Uo(await me(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 Jd(e,t,n){return Ud(e,t,100,1,n)}async function fa(e,t,n,o){let r=1,i=[],a={ok:!0,messages:{}};while(!0){let l=await Ud(e,t,100,r,o),u=Cs(l,["messages","matches"]),d=Array.isArray(u)?u:[];i.push(...d);let f=Number(Cs(l,["messages","paging","pages"])??1);if(a=l,d.length===0||r>=f||i.length>=n)break;r+=1}let c=a;if(!c.messages)c.messages={};return c.messages.matches=i.slice(0,n),c}async function zt(e,t,n,o,s,r,i,a){let c=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(o!==void 0)c.thread_ts=o;if(s&&o!==void 0)c.reply_broadcast=!0;return(await Kd(e,"chat.postMessage",c,a,r)).ts??""}function dy(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function Kd(e,t,n,o,s){if(!o)return Re(e,t,n,s);try{return await Re(e,t,{...n,metadata:o},s)}catch(r){if(!dy(r))throw r;return Re(e,t,n,s)}}async function qd(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 Re(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function Hd(e,t,n){let o={};if(t)o.channel=t;return me(e,"chat.scheduledMessages.list",o,n)}async function zd(e,t,n,o){await Re(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},o)}async function Un(e,t,n,o){return(await me(e,"chat.getPermalink",{channel:t,message_ts:n},o)).permalink??""}async function At(e,t,n,o,s,r,i){return(await Kd(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 Xd(e,t,n,o){await Re(e,"chat.delete",{channel:t,ts:n},o)}async function Gd(e,t,n,o,s=200,r){let i={channel:t,ts:n,limit:String(s)};if(o!==void 0)i.cursor=o;return me(e,"conversations.replies",i,r)}async function pa(e,t,n,o){await Re(e,"pins.add",{channel:t,timestamp:n},o)}async function Ft(e,t,n,o,s){await Re(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Yd(e,t,n,o){return((await me(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 Tt(e,t,n,o,s){await Re(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function Vd(e,t,n=!1,o){let s=await Re(e,"conversations.create",{name:t,is_private:n},o);return{id:s.channel?.id??"",name:s.channel?.name??t}}async function Zd(e,t,n,o){let s=await Re(e,"conversations.rename",{channel:t,name:n},o);return{id:s.channel?.id??t,name:s.channel?.name??n}}async function Qd(e,t,n,o){await Re(e,"conversations.invite",{channel:t,users:n.join(",")},o)}async function As(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 me(e,"conversations.list",s,t);if(n.push(...r.channels??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{channels:n}}async function Rt(e,t,n){let s=(await Re(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function ef(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await me(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 aa(e,t,n,o){let s=await ef(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 kn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Td(e,t){let n=kn(e.name??""),o=kn(e.real_name??e.profile?.real_name??""),s=kn(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var tf=200;async function nf(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await me(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(Td(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,a=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await me(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=tf){c=!0;break}s.add(h),i++;let g;try{g=(await me(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof $t)throw p;a++;continue}if(g&&Td(g,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:a,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:a,capped:c}}function sf(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
330
330
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
331
- 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 ${Jd} 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.
331
+ 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 ${tf} 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.
332
332
  `+(o.length?`This search was incomplete: ${o.join("; ")}.
333
333
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
334
334
  DMed you they cannot be found by name at all. Look them up and use their ID:
335
- slack user ls --external`)}async function Tt(e,t,n){let o=t.startsWith("@")?t.slice(1):t;if(oa(o))return o;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let s=kn(o),r=await me(e,"auth.test",{},n);if(s==="you"||s==="me"||kn(r.user??"")===s){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await qd(e,s,n);if(i.id)return i.id;throw Hd(t,i)}function zt(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 Gm(e){return zt(e)?.channel}function Dd(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function oa(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function ke(e,t,n){let o=Gm(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Dd(t))return t;if(oa(t))return sa(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Dd(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=kn(r);if(s){if(oa(r))return sa(e,r,n);let l=await me(e,"auth.test",{},n);if(i==="you"||i==="me"||kn(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Kd(e,f,n)||Ft(e,f,n)}let d=await qd(e,i,n);if(!d.id)throw Hd(t,d);if(d.dm)return d.dm;return sa(e,d.id,n,t)}let a=r.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await me(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===a)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function $s(e,t,n){try{let o=await me(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 ve(e,t,n){try{let o=await me(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 zd(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await me(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function Xd(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await me(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function Gd(e,t={},n){let o={limit:String(t.limit??50)};if(t.filter)o.filter=t.filter;if(t.cursor)o.cursor=t.cursor;return Jt(e,"saved.list",o,n)}async function As(e,t){return Jt(e,"drafts.list",{},t)}async function Yd(e,t,n,o){let{randomUUID:s}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:io(n)}]}]);return Jt(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 Vd(e,t,n,o,s){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:io(o)}]}]),i=(Date.now()/1000).toFixed(6);return Jt(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 Zd(e,t,n){return Jt(e,"conversations.info",{channel:t},n)}async function Un(e,t,n){return me(e,"users.info",{user:t},n)}async function Qd(e,t,n){try{let o=await me(e,"users.info",{user:t,include_locale:"true"},n);return typeof o.user?.locale==="string"?o.user.locale:void 0}catch{return}}async function xn(e,t,n){return me(e,"conversations.info",{channel:t},n)}async function ef(e,t,n){let o=(Date.now()/1000).toFixed(6);return Jt(e,"drafts.delete",{draft_id:t,client_last_updated_ts:o},n)}async function ua(e,t){let n=await Jt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function tf(e,t,n,o={},s){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:a}=await import("node:path"),c=r(n),l=a(n),u=await me(e,"files.getUploadURLExternal",{filename:l,length:String(c.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),g=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:h});if(!g.ok)throw Error(`Upload PUT failed: ${g.status} ${g.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 m=await Re(e,"files.completeUploadExternal",p,s),w={fileId:f},b=m.files?.[0]?.permalink;if(b)w.permalink=b;return w}function _s(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}var sf=["todo","saved","completed","archived"],Fs=(e)=>typeof e==="string"?e:"",nf=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function of(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((o)=>!!o&&typeof o==="object"&&!Array.isArray(o)).map((o)=>({channel:Fs(o.item_id),ts:Fs(o.ts),due:nf(o.date_due),completed:nf(o.date_completed),todoState:Fs(o.todo_state),state:Fs(o.state),archived:o.is_archived===!0,itemType:Fs(o.item_type)}))}function rf(e){return[...e].sort((t,n)=>{if(t.due&&n.due)return t.due-n.due;if(t.due!==n.due)return t.due?-1:1;return Number(n.ts)-Number(t.ts)})}function Wo(e){return e.completed>0||e.state==="completed"}function af(e,t,n){let o=Wo(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${o} no due date`;let s=!Wo(e)&&e.due<t?" OVERDUE":"";return`${o} due ${n(e.due)}${s}`}function cf(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as ry,readFileSync as iy}from"node:fs";import{homedir as ay}from"node:os";import{join as cy}from"node:path";import{existsSync as Ym,mkdirSync as Vm,readFileSync as Zm,writeFileSync as Qm}from"node:fs";import{homedir as ey}from"node:os";import{dirname as ty,join as ny}from"node:path";var sy=3600000,Uo={now:()=>Date.now(),path:()=>ny(process.env.HOME||ey(),".config","slack-cli","cache.json")},Ko=!0,Xt;function lf(){return{channels:{},users:{}}}function da(){if(Xt)return Xt;if(Xt=lf(),!Ko)return Xt;try{let e=Uo.path();if(!Ym(e))return Xt;let t=JSON.parse(Zm(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")Xt[n][s]={value:r.value,expires:r.expires}}}catch{Xt=lf()}return Xt}function oy(e){if(!Ko)return;try{let t=Uo.path();Vm(ty(t),{recursive:!0}),Qm(t,JSON.stringify(e,null,2)+`
336
- `)}catch{}}function uf(e,t){return e?`${e} ${t}`:void 0}function Jo(e,t,n){if(!Ko)return;let o=uf(t,n);if(!o)return;let s=da()[e][o];if(!s)return;if(s.expires<=Uo.now()){delete da()[e][o];return}return s.value}function qo(e,t,n,o,s=sy){if(!Ko)return;let r=uf(t,n);if(!r)return;let i=da();i[e][r]={value:o,expires:Uo.now()+s},oy(i)}var fa={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"}},Kn=["done","dropped","doing","pending"],hf=["alert","needs-discussion","waiting","blocked"];function ly(){return cy(process.env.HOME||ay(),".config","slack-cli","todo.json")}function Ho(e){return e.replace(/^:+|:+$/g,"")}function Ts(e=ly()){let t={marker:fa.marker,progress:{...fa.progress},flags:{...fa.flags}};try{if(!ry(e))return t;let n=JSON.parse(iy(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=Ho(n.marker.trim());for(let o of Kn){let s=n.progress?.[o];if(typeof s==="string"&&s.trim())t.progress[o]=Ho(s.trim())}for(let o of hf){let s=n.flags?.[o];if(typeof s==="string"&&s.trim())t.flags[o]=Ho(s.trim())}}catch{}return t}function df(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${Ho(e)}:`}function gf(e,t,n={}){let o=n.shared===!0,s=(a)=>df(a,o),r=(a)=>df(a,o,!0),i=[];if(e==="untriaged")i.push(s(t.marker),...Kn.map((a)=>r(t.progress[a])));else if(e==="stuck")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped),`(${hf.map((a)=>s(t.flags[a])).join(" OR ")})`);else if(e==="open")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped));else{let a=Kn.indexOf(e);i.push(s(t.progress[e]));for(let c of Kn.slice(0,a))i.push(r(t.progress[c]))}if(n.in){let a=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${a}`)}if(n.from){let a=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${a}`)}return i.join(" ")}var uy=3,dy={sleep:(e)=>fy()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function fy(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ge(e,t,n=uy){for(let o=0;;o++)try{return await t()}catch(s){if(!(s instanceof He))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 dy.sleep(s.retryAfter*1000)}}var ff=new Map;async function mf(e,t){let n=ff.get(e);if(n)return n;let o=await Ge("auth.test",()=>Ln(e,t)),s={userId:o.userId,teamId:o.teamId};return ff.set(e,s),s}async function yf(e,t){return(await mf(e,t)).userId}async function pa(e,t){try{return(await mf(e,t)).teamId}catch{return""}}async function ha(e,t,n,o){if(!t.startsWith("#"))return n(e,t,o);let s=await pa(e,o),r=Jo("channels",s,t);if(r)return r;let i=await Ge("resolveChannel",()=>n(e,t,o));return qo("channels",s,t,i),i}async function wf(e,t,n,o){let s=await pa(e,o),r=Jo("users",s,t);if(r)return r;let i=await Ge("users.info",()=>n(e,t,o));if(i&&i!==t)qo("users",s,t,i);return i}async function bf(e,t,n,o){let s=await pa(e,o),r=Jo("users",s,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let a=await Ge("users.info",()=>n(e,t,o));if(a?.user?.is_bot===!0||t==="USLACKBOT")return pf(s,t,null);let c=a?.user?.tz;i=typeof c==="string"&&c?c:null}catch{return null}return pf(s,t,i)}function pf(e,t,n){return qo("users",e,`tz:${t}`,n??"?"),n}async function Df(e,t,n,o,s,r){let i=s.progress[o],a=await yf(e,r),c=await Ge("reactions.get",()=>Ul(e,t,n,r)),l=new Set(c.filter((h)=>h.users.includes(a)).map((h)=>h.name)),u=Kn.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 Ge("reactions.add",()=>co(e,t,n,i,r));let d=[],f=[];for(let h of u){if(h===i)continue;try{await Ge("reactions.remove",()=>lo(e,t,n,h,r)),d.push(h)}catch{f.push(h)}}return{noop:!1,added:o,removed:d,leftover:f}}async function kf(e,t,n,o,s,r,i){let a=s.flags[o];if(r)await Ge("reactions.remove",()=>lo(e,t,n,a,i));else await Ge("reactions.add",()=>co(e,t,n,a,i));return a}var ga=1000;async function xf(e,t,n,o={}){let s=o.limit??ga,r=o.cookie,i=await yf(e,r),a=Kn.map((f)=>n.progress[f]),c=[],l=0,u,d=!1;while(l<s){let f=Math.min(200,s-l),h=await Ge("conversations.history",()=>wn(e,t,f,void 0,u,r)),g=h.messages??[];l+=g.length;for(let p of g){let m=String(p.ts??"");if(!m)continue;let w=new Set((p.reactions??[]).filter((D)=>(D.users??[]).map(String).includes(i)).map((D)=>String(D.name??""))),b=a.filter((D)=>w.has(D));if(b.length<2)continue;c.push({ts:m,text:String(p.text??"").split(`
337
- `)[0]??"",emoji:b,keep:b[0]})}if(u=h.response_metadata?.next_cursor||void 0,!u||g.length===0)break;if(l>=s){d=!0;break}}if(o.fix)for(let f of c)try{try{await Ge("reactions.add",()=>co(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 Ge("reactions.remove",()=>lo(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:c,truncated:d}}var py=!0,hy;function ma(e){if(py=e,!e)hy=void 0}function Me(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
338
- `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function Jn(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var qn=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Ne=(e)=>typeof e==="string"?e:"";function gy(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Ne(qn(qn(n).message).text)).filter(Boolean).join(`
339
- `)}function ya(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(qn).map((n)=>{let o=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),s=qn(qn((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:o,unfurl:!o&&!!Ne(n.original_url),author_id:Ne(n.author_id)||Ne(qn(s.message).user)||null,author_name:Ne(n.author_name)||null,channel_id:Ne(n.channel_id)||Ne(s.channel)||null,ts:Ne(n.ts)||Ne(s.ts)||null,title:Ne(n.title)||null,text:Ne(n.text)||gy(n)||Ne(n.pretext)||Ne(n.fallback),permalink:Ne(n.from_url)||Ne(n.title_link)||Ne(n.original_url)||null}})}function Sf(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let o=n.author_name??n.author_id,s=n.shared?`↪ shared message${o?` from @${o}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,r=n.text?n.text.replace(/\n+$/,"").split(`
335
+ slack user ls --external`)}async function It(e,t,n){let o=t.startsWith("@")?t.slice(1):t;if(ca(o))return o;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let s=kn(o),r=await me(e,"auth.test",{},n);if(s==="you"||s==="me"||kn(r.user??"")===s){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await nf(e,s,n);if(i.id)return i.id;throw sf(t,i)}function Xt(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 fy(e){return Xt(e)?.channel}function Rd(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function ca(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function ke(e,t,n){let o=fy(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Rd(t))return t;if(ca(t))return aa(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Rd(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=kn(r);if(s){if(ca(r))return aa(e,r,n);let l=await me(e,"auth.test",{},n);if(i==="you"||i==="me"||kn(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await ef(e,f,n)||Rt(e,f,n)}let d=await nf(e,i,n);if(!d.id)throw sf(t,d);if(d.dm)return d.dm;return aa(e,d.id,n,t)}let a=r.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await me(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===a)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function Fs(e,t,n){try{let o=await me(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 Ie(e,t,n){try{let o=await me(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 of(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await me(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function rf(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await me(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function ha(e,t={},n){let o={limit:String(t.limit??50)};if(t.filter)o.filter=t.filter;if(t.cursor)o.cursor=t.cursor;return gt(e,"saved.list",o,n)}var ga=(e)=>({item_type:"message",item_id:e.channel,ts:e.ts});async function af(e,t,n={},o){let s={...ga(t),todo_state:n.todo===!1?"saved":"to_do"};if(n.due)s.date_due=String(n.due);return gt(e,"saved.add",s,o)}async function ma(e,t,n,o){let s=ga(t);if(n.mark)s.mark=n.mark;if(n.todo!==void 0)s.todo_state=n.todo?"to_do":"saved";if(n.due!==void 0)s.date_due=String(n.due);return gt(e,"saved.update",s,o)}async function cf(e,t,n){return gt(e,"saved.delete",ga(t),n)}async function Ts(e,t){return gt(e,"drafts.list",{},t)}async function lf(e,t,n,o){let{randomUUID:s}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:co(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 uf(e,t,n,o,s){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:co(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 df(e,t,n){return gt(e,"conversations.info",{channel:t},n)}async function Jn(e,t,n){return me(e,"users.info",{user:t},n)}async function ff(e,t,n){try{let o=await me(e,"users.info",{user:t,include_locale:"true"},n);return typeof o.user?.locale==="string"?o.user.locale:void 0}catch{return}}async function xn(e,t,n){return me(e,"conversations.info",{channel:t},n)}async function pf(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 ya(e,t){let n=await gt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function hf(e,t,n,o={},s){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:a}=await import("node:path"),c=r(n),l=a(n),u=await me(e,"files.getUploadURLExternal",{filename:l,length:String(c.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),g=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:h});if(!g.ok)throw Error(`Upload PUT failed: ${g.status} ${g.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 m=await Re(e,"files.completeUploadExternal",p,s),w={fileId:f},b=m.files?.[0]?.permalink;if(b)w.permalink=b;return w}function Cs(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}var mf=["todo","saved","completed","archived"],Rs=(e)=>typeof e==="string"?e:"",gf=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function wa(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((o)=>!!o&&typeof o==="object"&&!Array.isArray(o)).map((o)=>({channel:Rs(o.item_id),ts:Rs(o.ts),due:gf(o.date_due),completed:gf(o.date_completed),todoState:Rs(o.todo_state),state:Rs(o.state),archived:o.is_archived===!0,itemType:Rs(o.item_type)}))}function yf(e){return[...e].sort((t,n)=>{if(t.due&&n.due)return t.due-n.due;if(t.due!==n.due)return t.due?-1:1;return Number(n.ts)-Number(t.ts)})}function Is(e){return e.completed>0||e.state==="completed"||e.todoState==="completed"}function ba(e,t,n){let o=Is(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${o} no due date`;let s=!Is(e)&&e.due<t?" OVERDUE":"";return`${o} due ${n(e.due)}${s}`}function Da(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as xy,readFileSync as Sy}from"node:fs";import{homedir as Ey}from"node:os";import{join as _y}from"node:path";import{existsSync as py,mkdirSync as hy,readFileSync as gy,writeFileSync as my}from"node:fs";import{homedir as yy}from"node:os";import{dirname as wy,join as by}from"node:path";var Dy=3600000,Jo={now:()=>Date.now(),path:()=>by(process.env.HOME||yy(),".config","slack-cli","cache.json")},Ko=!0,Gt;function wf(){return{channels:{},users:{}}}function ka(){if(Gt)return Gt;if(Gt=wf(),!Ko)return Gt;try{let e=Jo.path();if(!py(e))return Gt;let t=JSON.parse(gy(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")Gt[n][s]={value:r.value,expires:r.expires}}}catch{Gt=wf()}return Gt}function ky(e){if(!Ko)return;try{let t=Jo.path();hy(wy(t),{recursive:!0}),my(t,JSON.stringify(e,null,2)+`
336
+ `)}catch{}}function bf(e,t){return e?`${e} ${t}`:void 0}function qo(e,t,n){if(!Ko)return;let o=bf(t,n);if(!o)return;let s=ka()[e][o];if(!s)return;if(s.expires<=Jo.now()){delete ka()[e][o];return}return s.value}function Ho(e,t,n,o,s=Dy){if(!Ko)return;let r=bf(t,n);if(!r)return;let i=ka();i[e][r]={value:o,expires:Jo.now()+s},ky(i)}var xa={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"}},Kn=["done","dropped","doing","pending"],Sf=["alert","needs-discussion","waiting","blocked"];function $y(){return _y(process.env.HOME||Ey(),".config","slack-cli","todo.json")}function zo(e){return e.replace(/^:+|:+$/g,"")}function Os(e=$y()){let t={marker:xa.marker,progress:{...xa.progress},flags:{...xa.flags}};try{if(!xy(e))return t;let n=JSON.parse(Sy(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=zo(n.marker.trim());for(let o of Kn){let s=n.progress?.[o];if(typeof s==="string"&&s.trim())t.progress[o]=zo(s.trim())}for(let o of Sf){let s=n.flags?.[o];if(typeof s==="string"&&s.trim())t.flags[o]=zo(s.trim())}}catch{}return t}function Df(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${zo(e)}:`}function Ef(e,t,n={}){let o=n.shared===!0,s=(a)=>Df(a,o),r=(a)=>Df(a,o,!0),i=[];if(e==="untriaged")i.push(s(t.marker),...Kn.map((a)=>r(t.progress[a])));else if(e==="stuck")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped),`(${Sf.map((a)=>s(t.flags[a])).join(" OR ")})`);else if(e==="open")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped));else{let a=Kn.indexOf(e);i.push(s(t.progress[e]));for(let c of Kn.slice(0,a))i.push(r(t.progress[c]))}if(n.in){let a=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${a}`)}if(n.from){let a=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${a}`)}return i.join(" ")}var Cy=3,Ay={sleep:(e)=>Fy()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Fy(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ge(e,t,n=Cy){for(let o=0;;o++)try{return await t()}catch(s){if(!(s instanceof He))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 Ay.sleep(s.retryAfter*1000)}}var kf=new Map;async function _f(e,t){let n=kf.get(e);if(n)return n;let o=await Ge("auth.test",()=>Mn(e,t)),s={userId:o.userId,teamId:o.teamId};return kf.set(e,s),s}async function $f(e,t){return(await _f(e,t)).userId}async function Sa(e,t){try{return(await _f(e,t)).teamId}catch{return""}}async function Ea(e,t,n,o){if(!t.startsWith("#"))return n(e,t,o);let s=await Sa(e,o),r=qo("channels",s,t);if(r)return r;let i=await Ge("resolveChannel",()=>n(e,t,o));return Ho("channels",s,t,i),i}async function Cf(e,t,n,o){let s=await Sa(e,o),r=qo("users",s,t);if(r)return r;let i=await Ge("users.info",()=>n(e,t,o));if(i&&i!==t)Ho("users",s,t,i);return i}async function Af(e,t,n,o){let s=await Sa(e,o),r=qo("users",s,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let a=await Ge("users.info",()=>n(e,t,o));if(a?.user?.is_bot===!0||t==="USLACKBOT")return xf(s,t,null);let c=a?.user?.tz;i=typeof c==="string"&&c?c:null}catch{return null}return xf(s,t,i)}function xf(e,t,n){return Ho("users",e,`tz:${t}`,n??"?"),n}async function Ff(e,t,n,o,s,r){let i=s.progress[o],a=await $f(e,r),c=await Ge("reactions.get",()=>Vl(e,t,n,r)),l=new Set(c.filter((h)=>h.users.includes(a)).map((h)=>h.name)),u=Kn.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 Ge("reactions.add",()=>uo(e,t,n,i,r));let d=[],f=[];for(let h of u){if(h===i)continue;try{await Ge("reactions.remove",()=>fo(e,t,n,h,r)),d.push(h)}catch{f.push(h)}}return{noop:!1,added:o,removed:d,leftover:f}}async function Tf(e,t,n,o,s,r,i){let a=s.flags[o];if(r)await Ge("reactions.remove",()=>fo(e,t,n,a,i));else await Ge("reactions.add",()=>uo(e,t,n,a,i));return a}var _a=1000;async function Rf(e,t,n,o={}){let s=o.limit??_a,r=o.cookie,i=await $f(e,r),a=Kn.map((f)=>n.progress[f]),c=[],l=0,u,d=!1;while(l<s){let f=Math.min(200,s-l),h=await Ge("conversations.history",()=>wn(e,t,f,void 0,u,r)),g=h.messages??[];l+=g.length;for(let p of g){let m=String(p.ts??"");if(!m)continue;let w=new Set((p.reactions??[]).filter((D)=>(D.users??[]).map(String).includes(i)).map((D)=>String(D.name??""))),b=a.filter((D)=>w.has(D));if(b.length<2)continue;c.push({ts:m,text:String(p.text??"").split(`
337
+ `)[0]??"",emoji:b,keep:b[0]})}if(u=h.response_metadata?.next_cursor||void 0,!u||g.length===0)break;if(l>=s){d=!0;break}}if(o.fix)for(let f of c)try{try{await Ge("reactions.add",()=>uo(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 Ge("reactions.remove",()=>fo(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:c,truncated:d}}var Ty=!0,Ry;function $a(e){if(Ty=e,!e)Ry=void 0}function Ne(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
338
+ `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function qn(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var Hn=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Be=(e)=>typeof e==="string"?e:"";function Iy(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Be(Hn(Hn(n).message).text)).filter(Boolean).join(`
339
+ `)}function Ca(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(Hn).map((n)=>{let o=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),s=Hn(Hn((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:o,unfurl:!o&&!!Be(n.original_url),author_id:Be(n.author_id)||Be(Hn(s.message).user)||null,author_name:Be(n.author_name)||null,channel_id:Be(n.channel_id)||Be(s.channel)||null,ts:Be(n.ts)||Be(s.ts)||null,title:Be(n.title)||null,text:Be(n.text)||Iy(n)||Be(n.pretext)||Be(n.fallback),permalink:Be(n.from_url)||Be(n.title_link)||Be(n.original_url)||null}})}function If(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let o=n.author_name??n.author_id,s=n.shared?`↪ shared message${o?` from @${o}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,r=n.text?n.text.replace(/\n+$/,"").split(`
340
340
  `).map((a)=>`
341
341
  │ ${a}`).join(""):"",i=n.permalink?`
342
342
  ${n.permalink}`:"";return`
343
- ${s}${r}${i}`}).join("")}var Ef=new Set(["send","ask","poll","vote","edit","delete","react","upload","schedule send","schedule rm","pinlog new","pinlog set","pinlog note","pinlog pin","todo set","todo flag","lists create","lists add","lists set","lists share","drafts new","drafts save","drafts edit","drafts update","drafts delete","drafts rm","channel create","channel new","channel rename","channel mv"]),my={channels:"channel",ch:"channel"};function yy(e){let[t="",n=""]=e.map(String),o=my[t]??t;return Ef.has(o)||Ef.has(`${o} ${n}`)}function wy(e,t){return String(e[0]??"")==="ask"&&t.ls===!0}function _f(e,t,n){let o=n.botTokenSource;if(!o||n.globalPaths.includes(o))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!yy(e)||wy(e,t)||t["as-bot"]===!0)return null;let s=o==="shell"?"exported in the environment":`set in ${o}`,r="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${s}, but \`${e.slice(0,2).join(" ")}\` would use your user session, not the bot.`,r?" As the app: add --as-bot":" This command has no --as-bot: it can only act as a user."," As yourself: set SLACK_TOKEN, or clear the bot token for this run (SLACK_BOT_TOKEN= slack ...)"].join(`
344
- `)}function Sn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Gt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function by(e,t){let n=Sn(t),o=Gt(e.profile);for(let r of[e.name,e.real_name,o.display_name,o.real_name])if(typeof r==="string"&&r&&Sn(r)===n)return!0;let s=typeof o.email==="string"?o.email.toLowerCase():"";return s!==""&&s===t.toLowerCase()}function Dy(e){let t=Gt(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=Sn(o);if(s.length>=2)n.add(s)}return[...n]}function ky(e,t){let n=Sn(e),o,s=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let a of Dy(r)){let c=-1;if(n===a)c=e.length;else for(let l of $f)if(e.length>l.length&&e.endsWith(l)&&Sn(e.slice(0,e.length-l.length))===a){c=e.length-l.length;break}if(c<0)continue;if(!o||a.length>o.formLen)o={userId:i,matchLen:c,formLen:a.length,display:Da(r)},s=!1;else if(a.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 Yt(e,t,n,o){let s=`[${Af}ー]+`,r=`${s}(?:[._-]+${s})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),a=new Set;for(let b of t.matchAll(i))a.add(b[1]);if(a.size===0)return{text:t,resolved:[],unresolved:[]};let c=new Map;for(let b of a)c.set(b,{status:"pending"});let l=(b)=>{for(let D of a){if(c.get(D).status!=="pending")continue;if(ba(D)){let S=ky(D,b);if(S==="ambiguous")c.set(D,{status:"ambiguous"});else if(S)c.set(D,{status:"resolved",userId:S.userId,matchLen:S.matchLen,display:S.display})}else{let S=b.filter((A)=>by(A,D)),F=new Set(S.map((A)=>typeof A.id==="string"?A.id:"").filter(Boolean));if(F.size===1){let A=S.find((C)=>typeof C.id==="string");c.set(D,{status:"resolved",userId:A.id,matchLen:D.length,display:Da(A)})}else if(F.size>1)c.set(D,{status:"ambiguous"})}}},u=!1;try{let b=await po(e,o);l((b.members??[]).map(Gt)),u=!0}catch{u=!1}let d=[...a].some((b)=>c.get(b).status==="pending"),f=!1,h=!0;if(d&&n){f=!0;try{let b=await fi(e,n,o),D=[];for(let S of b){let F=Gt(await pi(e,S,o)),A=Gt(F.user);if(typeof A.id!=="string")A.id=S;D.push(A)}l(D)}catch{h=!1}}let g=u&&(n?f&&h:!0),p=[],m=[];for(let b of a){let D=c.get(b);if(D.status==="resolved")p.push({surface:`@${b.slice(0,D.matchLen)}`,display:D.display,userId:D.userId});else if(D.status==="ambiguous")m.push({surface:`@${b}`,reason:"ambiguous"});else m.push({surface:`@${b}`,reason:g?"no-match":"unavailable"})}return{text:t.replace(i,(b,D)=>{let S=c.get(D);if(S&&S.status==="resolved")return`<@${S.userId}>${D.slice(S.matchLen)}`;return b}),resolved:p,unresolved:m}}function zo(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 Cf(e,t,n,o={}){let s=o.warn??((i)=>process.stderr.write(`${i}
345
- `)),r=await Yt(e,t,n,o.cookie);for(let i of zo(r.unresolved))s(`warn: ${i}`);return r.text}var $f=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],Af="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function ba(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function xy(e){let t=[],n=new RegExp(`([${Af}]{1,12})(${$f.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 Sy(e){let t=Gt(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=Sn(s);if(r.length>=2)n.add(r)}}return[...n]}function Ey(e,t){let n=Sn(e);if(n.length<2)return;for(let o of t)if(n===o)return o;if(ba(e)){for(let o of t)if(n.includes(o)||o.includes(n))return o}return}function Da(e){return[Gt(e.profile).display_name,e.real_name,e.name].filter((o)=>typeof o==="string"&&o!=="")[0]??String(e.id??"?")}async function Ff(e,t,n){let o=xy(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 po(e,n)).members??[]).map(Gt).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:Sy(l),display:Da(l)})).filter((l)=>l.id!==""),a=[],c=new Set;for(let{ref:l,honorific:u}of o)for(let d of i){let f=Ey(l,d.forms);if(!f)continue;if(s.has(d.id)||c.has(d.id))break;c.add(d.id),a.push({surface:ba(l)?`${f}${u}`:l,display:d.display,userId:d.id});break}return a}async function En(e,t,n,o){let s=t,r=[],i=s,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let l=i.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);a=c+1}for(let c of r){if(!n.has(c))n.set(c,await Mn(e,c,o));let l=n.get(c)??c;s=s.replaceAll(`<@${c}>`,`@${l}`),s=s.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return s}function Hn(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"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[r.getUTCDay()]??"",l=a[r.getUTCMonth()]??"";return`${c}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Tf(e,t=new Date){let n=new Date(e*1000),o=wa(t),s=wa(new Date(t.getTime()-86400000)),r=wa(n);if(r===o)return"Today";if(r===s)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),a=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${a} ${String(n.getDate()).padStart(2,"0")}`}function wa(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Rs(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}`}var _y=/[A-Za-z0-9_-]{32,}/g;function Is(e){return e.replace(_y,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function ka(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",o=!!t&&Cy(t),s=o?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),a,c;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"});c=h.format(e),a=Number(h.formatToParts(e).find((g)=>g.type==="hour")?.value??"12")}catch{return null}let l=r>i?a>=r||a<i:a>=r&&a<i,u=o?`${s}, recipient`:`${s}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${c} (${u})`;if(!l)return d;return`${d}
346
- ⚠ 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 Cy(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as Rf}from"node:fs";import{isatty as If}from"node:tty";import{format as Pf}from"node:util";var $y=new Int32Array(new SharedArrayBuffer(4)),Ay=141;function Of(e,t){let n=Buffer.from(t,"utf8"),o=0;while(o<n.length)try{o+=Rf(e,n,o,n.length-o)}catch(s){let r=s.code;if(r==="EAGAIN"||r==="EWOULDBLOCK"){Atomics.wait($y,0,0,2);continue}if(r==="EPIPE")process.exit(Ay);if(e!==2)try{Rf(2,`slack: cannot write output (${r??String(s)}); output is incomplete
347
- `)}catch{}process.exit(1)}}function vf(){if(!If(1))console.log=(...e)=>Of(1,Pf(...e)+`
348
- `),console.info=console.log;if(!If(2))console.error=(...e)=>Of(2,Pf(...e)+`
349
- `),console.warn=console.error}import{closeSync as Lf,mkdirSync as Fy,openSync as Mf,readFileSync as zn,statSync as Nf,unlinkSync as Xo,writeFileSync as Bf}from"node:fs";import{homedir as Ty}from"node:os";import{join as jf}from"node:path";var Os="Pinlog · 最終更新";function xa(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 Ry(e){return`_${Os} ${xa(e)} · 更新はスレッドに_`}var Sa=new RegExp(`(^|\\n+)_?${Os} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function Xn(e){return Sa.test(e)}function vs(e){return e.replace(Sa,"")}function Ea(e,t){return`${vs(e).trimEnd()}
343
+ ${s}${r}${i}`}).join("")}var Of=new Set(["send","ask","poll","vote","edit","delete","react","upload","schedule send","schedule rm","pinlog new","pinlog set","pinlog note","pinlog pin","todo set","todo flag","todos add","todos done","todos complete","todos edit","todos rm","todos remove","todos delete","lists create","lists add","lists set","lists share","drafts new","drafts save","drafts edit","drafts update","drafts delete","drafts rm","channel create","channel new","channel rename","channel mv"]),Oy={channels:"channel",ch:"channel"};function Py(e){let[t="",n=""]=e.map(String),o=Oy[t]??t;return Of.has(o)||Of.has(`${o} ${n}`)}function vy(e,t){return String(e[0]??"")==="ask"&&t.ls===!0}function Pf(e,t,n){let o=n.botTokenSource;if(!o||n.globalPaths.includes(o))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!Py(e)||vy(e,t)||t["as-bot"]===!0)return null;let s=o==="shell"?"exported in the environment":`set in ${o}`,r="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${s}, but \`${e.slice(0,2).join(" ")}\` would use your user session, not the bot.`,r?" As the app: add --as-bot":" This command has no --as-bot: it can only act as a user."," As yourself: set SLACK_TOKEN, or clear the bot token for this run (SLACK_BOT_TOKEN= slack ...)"].join(`
344
+ `)}function Sn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Yt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Ly(e,t){let n=Sn(t),o=Yt(e.profile);for(let r of[e.name,e.real_name,o.display_name,o.real_name])if(typeof r==="string"&&r&&Sn(r)===n)return!0;let s=typeof o.email==="string"?o.email.toLowerCase():"";return s!==""&&s===t.toLowerCase()}function My(e){let t=Yt(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=Sn(o);if(s.length>=2)n.add(s)}return[...n]}function Ny(e,t){let n=Sn(e),o,s=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let a of My(r)){let c=-1;if(n===a)c=e.length;else for(let l of Lf)if(e.length>l.length&&e.endsWith(l)&&Sn(e.slice(0,e.length-l.length))===a){c=e.length-l.length;break}if(c<0)continue;if(!o||a.length>o.formLen)o={userId:i,matchLen:c,formLen:a.length,display:Ta(r)},s=!1;else if(a.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 Vt(e,t,n,o){let s=`[${Mf}ー]+`,r=`${s}(?:[._-]+${s})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),a=new Set;for(let b of t.matchAll(i))a.add(b[1]);if(a.size===0)return{text:t,resolved:[],unresolved:[]};let c=new Map;for(let b of a)c.set(b,{status:"pending"});let l=(b)=>{for(let D of a){if(c.get(D).status!=="pending")continue;if(Fa(D)){let S=Ny(D,b);if(S==="ambiguous")c.set(D,{status:"ambiguous"});else if(S)c.set(D,{status:"resolved",userId:S.userId,matchLen:S.matchLen,display:S.display})}else{let S=b.filter((F)=>Ly(F,D)),A=new Set(S.map((F)=>typeof F.id==="string"?F.id:"").filter(Boolean));if(A.size===1){let F=S.find((E)=>typeof E.id==="string");c.set(D,{status:"resolved",userId:F.id,matchLen:D.length,display:Ta(F)})}else if(A.size>1)c.set(D,{status:"ambiguous"})}}},u=!1;try{let b=await go(e,o);l((b.members??[]).map(Yt)),u=!0}catch{u=!1}let d=[...a].some((b)=>c.get(b).status==="pending"),f=!1,h=!0;if(d&&n){f=!0;try{let b=await mi(e,n,o),D=[];for(let S of b){let A=Yt(await yi(e,S,o)),F=Yt(A.user);if(typeof F.id!=="string")F.id=S;D.push(F)}l(D)}catch{h=!1}}let g=u&&(n?f&&h:!0),p=[],m=[];for(let b of a){let D=c.get(b);if(D.status==="resolved")p.push({surface:`@${b.slice(0,D.matchLen)}`,display:D.display,userId:D.userId});else if(D.status==="ambiguous")m.push({surface:`@${b}`,reason:"ambiguous"});else m.push({surface:`@${b}`,reason:g?"no-match":"unavailable"})}return{text:t.replace(i,(b,D)=>{let S=c.get(D);if(S&&S.status==="resolved")return`<@${S.userId}>${D.slice(S.matchLen)}`;return b}),resolved:p,unresolved:m}}function Xo(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 vf(e,t,n,o={}){let s=o.warn??((i)=>process.stderr.write(`${i}
345
+ `)),r=await Vt(e,t,n,o.cookie);for(let i of Xo(r.unresolved))s(`warn: ${i}`);return r.text}var Lf=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],Mf="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Fa(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function By(e){let t=[],n=new RegExp(`([${Mf}]{1,12})(${Lf.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 jy(e){let t=Yt(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=Sn(s);if(r.length>=2)n.add(r)}}return[...n]}function Wy(e,t){let n=Sn(e);if(n.length<2)return;for(let o of t)if(n===o)return o;if(Fa(e)){for(let o of t)if(n.includes(o)||o.includes(n))return o}return}function Ta(e){return[Yt(e.profile).display_name,e.real_name,e.name].filter((o)=>typeof o==="string"&&o!=="")[0]??String(e.id??"?")}async function Nf(e,t,n){let o=By(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 go(e,n)).members??[]).map(Yt).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:jy(l),display:Ta(l)})).filter((l)=>l.id!==""),a=[],c=new Set;for(let{ref:l,honorific:u}of o)for(let d of i){let f=Wy(l,d.forms);if(!f)continue;if(s.has(d.id)||c.has(d.id))break;c.add(d.id),a.push({surface:Fa(l)?`${f}${u}`:l,display:d.display,userId:d.id});break}return a}async function En(e,t,n,o){let s=t,r=[],i=s,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let l=i.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);a=c+1}for(let c of r){if(!n.has(c))n.set(c,await Nn(e,c,o));let l=n.get(c)??c;s=s.replaceAll(`<@${c}>`,`@${l}`),s=s.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return s}function zn(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"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[r.getUTCDay()]??"",l=a[r.getUTCMonth()]??"";return`${c}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Bf(e,t=new Date){let n=new Date(e*1000),o=Aa(t),s=Aa(new Date(t.getTime()-86400000)),r=Aa(n);if(r===o)return"Today";if(r===s)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),a=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${a} ${String(n.getDate()).padStart(2,"0")}`}function Aa(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function _n(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}`}var Uy=/[A-Za-z0-9_-]{32,}/g;function Xn(e){return e.replace(Uy,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Ra(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",o=!!t&&Jy(t),s=o?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),a,c;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"});c=h.format(e),a=Number(h.formatToParts(e).find((g)=>g.type==="hour")?.value??"12")}catch{return null}let l=r>i?a>=r||a<i:a>=r&&a<i,u=o?`${s}, recipient`:`${s}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${c} (${u})`;if(!l)return d;return`${d}
346
+ ⚠ 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 Jy(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as jf}from"node:fs";import{isatty as Wf}from"node:tty";import{format as Uf}from"node:util";var Ky=new Int32Array(new SharedArrayBuffer(4)),qy=141;function Jf(e,t){let n=Buffer.from(t,"utf8"),o=0;while(o<n.length)try{o+=jf(e,n,o,n.length-o)}catch(s){let r=s.code;if(r==="EAGAIN"||r==="EWOULDBLOCK"){Atomics.wait(Ky,0,0,2);continue}if(r==="EPIPE")process.exit(qy);if(e!==2)try{jf(2,`slack: cannot write output (${r??String(s)}); output is incomplete
347
+ `)}catch{}process.exit(1)}}function Kf(){if(!Wf(1))console.log=(...e)=>Jf(1,Uf(...e)+`
348
+ `),console.info=console.log;if(!Wf(2))console.error=(...e)=>Jf(2,Uf(...e)+`
349
+ `),console.warn=console.error}import{closeSync as qf,mkdirSync as Hy,openSync as Hf,readFileSync as Gn,statSync as zf,unlinkSync as Go,writeFileSync as Xf}from"node:fs";import{homedir as zy}from"node:os";import{join as Gf}from"node:path";var vs="Pinlog · 最終更新";function Ia(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 Xy(e){return`_${vs} ${Ia(e)} · 更新はスレッドに_`}var Oa=new RegExp(`(^|\\n+)_?${vs} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function Yn(e){return Oa.test(e)}function Ls(e){return e.replace(Oa,"")}function Pa(e,t){return`${Ls(e).trimEnd()}
350
350
 
351
- ${Ry(t)}`}function _a(e){let n=e.match(Sa)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class Ps extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function Iy(){return jf(process.env.HOME||Ty(),".config","slack-cli","locks")}function Wf(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 Py(e,t){let n=`${e}.break`,o=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
352
- `,s;try{s=Mf(n,"wx"),Bf(s,o)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=zn(n,"utf8");if((/^pid=\d+/.test(i)?!Wf(i):Date.now()-Nf(n).mtimeMs>1e4)&&zn(n,"utf8")===i)Xo(n)}catch{}return}try{if(zn(e,"utf8")===t)Xo(e)}catch{}finally{Lf(s);try{if(zn(n,"utf8")===o)Xo(n)}catch{}}}function Uf(e,t={}){let n=t.dir??Iy(),o=t.staleMs??120000;Fy(n,{recursive:!0});let s=jf(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()}
353
- `;for(let i=0;i<3;i++)try{let a=Mf(s,"wx");Bf(a,r),Lf(a);let c=!0,l=()=>{if(!c)return;c=!1;try{if(zn(s,"utf8")===r)Xo(s)}catch{}};return process.once("exit",l),l}catch(a){if(a.code!=="EEXIST")throw a;let c,l;try{c=zn(s,"utf8"),l=Date.now()-Nf(s).mtimeMs}catch{continue}if(/^pid=\d+/.test(c)?!Wf(c):l>o){Py(s,c);continue}throw new Ps(c.trim().replace(/ nonce=\S+/,"")||"another process")}throw new Ps("another process")}function at(e,t){return`${e}:${t}`}function Go(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var op=new Map,$a=new Map,Ra=[Dt(Ca(),".slack-cli",".env.local"),Dt(Ca(),".config/slack-cli",".env")];function Yo(e){if(!tp(e))return;let t=np(e,"utf8");for(let n of t.split(`
354
- `)){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(Ra.includes(e))$a.set(r,[...$a.get(r)??[],{path:e,val:i}]);if(!(r in process.env))process.env[r]=i,op.set(r,e)}}function My(e){Oy(e,{recursive:!0});let t=Dt(e,".gitignore");if(!tp(t))sp(t,`*
355
- `)}function Ny(){for(let e of Ra)Yo(e);Yo(Dt(process.cwd(),".slack-cli",".env.local")),Yo(Dt(process.cwd(),".env.local")),Yo(Dt(process.cwd(),".env"))}function By(e){return ep("sha256").update(e).digest("hex")}function T(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function G(e){return Array.isArray(e)?e:[]}function Qo(e){return Number(e.ts??0)}async function rp(e,t,n){let o=t.user;if(typeof o==="string"){if(!n.has(o))n.set(o,await ve(e,o));return n.get(o)??o}return typeof t.username==="string"?t.username:"bot"}function Aa(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"),a=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}:${a}`}function er(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"),a=String(s.getUTCDate()).padStart(2,"0"),c=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}-${a}T${c}:${l}:${u}.${d}`}function Ia(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 jy(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Ia(e):e}async function or(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:`${Qo(t)}.000000`,i=er(r),a="?";if(typeof t.user==="string"){let D=t.user,S="@"+D;if(!n.has(S)){let F=await wf(e,D,async(A,C,x)=>(await $s(A,C,x))[1],s);n.set(S,F)}a=n.get(S)??D}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",u=Hn(await En(e,c,n,s)).split(`
351
+ ${Xy(t)}`}function va(e){let n=e.match(Oa)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class Ps extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function Gy(){return Gf(process.env.HOME||zy(),".config","slack-cli","locks")}function Yf(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 Yy(e,t){let n=`${e}.break`,o=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
352
+ `,s;try{s=Hf(n,"wx"),Xf(s,o)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=Gn(n,"utf8");if((/^pid=\d+/.test(i)?!Yf(i):Date.now()-zf(n).mtimeMs>1e4)&&Gn(n,"utf8")===i)Go(n)}catch{}return}try{if(Gn(e,"utf8")===t)Go(e)}catch{}finally{qf(s);try{if(Gn(n,"utf8")===o)Go(n)}catch{}}}function Vf(e,t={}){let n=t.dir??Gy(),o=t.staleMs??120000;Hy(n,{recursive:!0});let s=Gf(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()}
353
+ `;for(let i=0;i<3;i++)try{let a=Hf(s,"wx");Xf(a,r),qf(a);let c=!0,l=()=>{if(!c)return;c=!1;try{if(Gn(s,"utf8")===r)Go(s)}catch{}};return process.once("exit",l),l}catch(a){if(a.code!=="EEXIST")throw a;let c,l;try{c=Gn(s,"utf8"),l=Date.now()-zf(s).mtimeMs}catch{continue}if(/^pid=\d+/.test(c)?!Yf(c):l>o){Yy(s,c);continue}throw new Ps(c.trim().replace(/ nonce=\S+/,"")||"another process")}throw new Ps("another process")}function at(e,t){return`${e}:${t}`}function Yo(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var hp=new Map,Ma=new Map,Wa=[kt(La(),".slack-cli",".env.local"),kt(La(),".config/slack-cli",".env")];function Vo(e){if(!dp(e))return;let t=fp(e,"utf8");for(let n of t.split(`
354
+ `)){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(Wa.includes(e))Ma.set(r,[...Ma.get(r)??[],{path:e,val:i}]);if(!(r in process.env))process.env[r]=i,hp.set(r,e)}}function ew(e){Vy(e,{recursive:!0});let t=kt(e,".gitignore");if(!dp(t))pp(t,`*
355
+ `)}function tw(){for(let e of Wa)Vo(e);Vo(kt(process.cwd(),".slack-cli",".env.local")),Vo(kt(process.cwd(),".env.local")),Vo(kt(process.cwd(),".env"))}function nw(e){return up("sha256").update(e).digest("hex")}function T(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function G(e){return Array.isArray(e)?e:[]}function tr(e){return Number(e.ts??0)}async function gp(e,t,n){let o=t.user;if(typeof o==="string"){if(!n.has(o))n.set(o,await Ie(e,o));return n.get(o)??o}return typeof t.username==="string"?t.username:"bot"}function Na(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"),a=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}:${a}`}function nr(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"),a=String(s.getUTCDate()).padStart(2,"0"),c=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}-${a}T${c}:${l}:${u}.${d}`}function Ua(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 sw(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Ua(e):e}async function ar(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:`${tr(t)}.000000`,i=nr(r),a="?";if(typeof t.user==="string"){let D=t.user,S="@"+D;if(!n.has(S)){let A=await Cf(e,D,async(F,E,x)=>(await Fs(F,E,x))[1],s);n.set(S,A)}a=n.get(S)??D}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",u=zn(await En(e,c,n,s)).split(`
356
356
  `),d=u[0]+(u.length>1?`
357
357
  `+u.slice(1).map((D)=>` ${D}`).join(`
358
- `):""),f=o?`${o} @${a}`:`@${a}`,h=G(t.reactions).map(T).map((D)=>{let S=typeof D.name==="string"?D.name:"",F=Number(D.count??G(D.users).length??0);return S?`:${S}:\xD7${F}`:""}).filter(Boolean).join(" "),g=G(t.files).map(T).map((D)=>{let S=typeof D.name==="string"?D.name:typeof D.title==="string"?D.title:"(file)",F=typeof D.size==="number"?` (${rr(D.size)})`:"",A=typeof D.id==="string"?` [${D.id}]`:"";return`
359
- \uD83D\uDCCE ${S}${F}${A}`}).join(""),p=Number(t.reply_count??0),m=p>0?` [+${p} ${p===1?"reply":"replies"}]`:"",w=await Promise.all(ya(t).map(async(D)=>({...D,text:D.text?Hn(await En(e,D.text,n,s)):""}))),b=(h?`
360
- ${h}`:"")+g+Sf(w,er);return`${i} ${f}: ${d}${m}${b}`}function rr(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function Wy(e){return G(e.files).map(T).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 ip(e){let t=Wy(e),n=ya(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:G(e.reactions).map(T).map((o)=>({name:o.name??null,count:o.count??null,users:Array.isArray(o.users)?o.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}:{},...n.length>0?{attachments:n}:{}}}async function Uy(e,t,n,o,s){let r=[];for(let i of n){let a=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let c=await Ue(e,t,i.ts,200,s),l=G(c.messages).map(T);a=l[l.length-1]??i}if(a.user!==o)r.push(i)}return r}async function Ky(e,t,n,o="text",s=!1,r){let i=zt(t),a=await ke(e,t,r),c=new Map,u=await(async()=>{if(i?.threadTs){let f=await Ue(e,a,i.threadTs,n,r);return G(f.messages).map(T)}let d=await tt(e,a,n,void 0,void 0,r);return G(d.messages).map(T).reverse()})();if(s){let{userId:d}=await ia(e,r);u=await Uy(e,a,u,d,r)}if(o==="jsonl"){for(let d of u)console.log(JSON.stringify(ip(d)));return}for(let d of u)console.log(await or(e,d,c,void 0,r))}async function Jy(e,t,n,o,s="text",r){let i=await ke(e,t,r),a=await Ue(e,i,jy(n),o,r),c=G(a.messages).map(T);if(s==="jsonl"){for(let u of c)console.log(JSON.stringify(ip(u)));return}let l=new Map;for(let u of c)console.log(await or(e,u,l,void 0,r))}async function qy(e){let t=await Cs(e),n=G(t.channels).map(T).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,a=await tt(e,r,5),c=G(a.messages).map(T).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(c.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let l of c){let u=await rp(e,l,o),d=(typeof l.text==="string"?l.text:"").split(`
361
- `)[0]??"",f=await En(e,d,o);console.log(` ${u}: ${f}`)}}}async function Hy(e,t){let n=await Id(e,"to:me"),o=G(_s(n,["messages","matches"])).map(T).slice(0,t),s=new Map,r=[];for(let i of o){let a=Tf(Qo(i)),c=r[r.length-1];if(c?.label===a)c.msgs.push(i);else r.push({label:a,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:a,msgs:c}=r[i];if(i>0)console.log("");console.log(` ${a}`),console.log(" ----------------------------");for(let l of[...c].reverse()){let u=T(l.channel),d=u.is_im===!0,f=typeof u.name==="string"?u.name:"dm",h;if(d&&f.startsWith("U")){let g="@"+f;if(!s.has(g)){let[,p]=await $s(e,f);s.set(g,p)}h=`@${s.get(g)??f}`}else if(d)h=`@${f}`;else h=`#${f}`;console.log(await or(e,l,s,h))}}}async function zy(e,t,n,o,s="text",r){let i=await Cs(e,r),a=G(i.channels).map(T).filter((c)=>o||c.is_member===!0).filter((c)=>{if(!n)return!0;return(typeof c.name==="string"?c.name:"").toLowerCase().includes(n.toLowerCase())}).sort((c,l)=>Number(l.updated??0)-Number(c.updated??0)).slice(0,t);if(s==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.user==="string"?c.user:l,d=c.is_im===!0,f=c.is_mpim===!0,h=d||f?"@":"#",g=c.is_member===!0?"":" (not joined)",p=typeof T(c.purpose).value==="string"?String(T(c.purpose).value):"",m=p?` ${p.split(`
362
- `)[0]?.slice(0,60)}`:"";console.log(`${h}${u} ${l}${g}${m}`)}}function Xy(e){let t=(s)=>s.startsWith("xoxp-")||s.startsWith("xoxc-"),n=Gr(),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 ap(e,t,n,o,s){let r=e,i=s,a;try{a=await ca(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=Xy(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,a=await ca(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.
358
+ `):""),f=o?`${o} @${a}`:`@${a}`,h=G(t.reactions).map(T).map((D)=>{let S=typeof D.name==="string"?D.name:"",A=Number(D.count??G(D.users).length??0);return S?`:${S}:\xD7${A}`:""}).filter(Boolean).join(" "),g=G(t.files).map(T).map((D)=>{let S=typeof D.name==="string"?D.name:typeof D.title==="string"?D.title:"(file)",A=typeof D.size==="number"?` (${cr(D.size)})`:"",F=typeof D.id==="string"?` [${D.id}]`:"";return`
359
+ \uD83D\uDCCE ${S}${A}${F}`}).join(""),p=Number(t.reply_count??0),m=p>0?` [+${p} ${p===1?"reply":"replies"}]`:"",w=await Promise.all(Ca(t).map(async(D)=>({...D,text:D.text?zn(await En(e,D.text,n,s)):""}))),b=(h?`
360
+ ${h}`:"")+g+If(w,nr);return`${i} ${f}: ${d}${m}${b}`}function cr(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ow(e){return G(e.files).map(T).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 mp(e){let t=ow(e),n=Ca(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:G(e.reactions).map(T).map((o)=>({name:o.name??null,count:o.count??null,users:Array.isArray(o.users)?o.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}:{},...n.length>0?{attachments:n}:{}}}async function rw(e,t,n,o,s){let r=[];for(let i of n){let a=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let c=await Me(e,t,i.ts,200,s),l=G(c.messages).map(T);a=l[l.length-1]??i}if(a.user!==o)r.push(i)}return r}async function iw(e,t,n,o="text",s=!1,r){let i=Xt(t),a=await ke(e,t,r),c=new Map,u=await(async()=>{if(i?.threadTs){let f=await Me(e,a,i.threadTs,n,r);return G(f.messages).map(T)}let d=await tt(e,a,n,void 0,void 0,r);return G(d.messages).map(T).reverse()})();if(s){let{userId:d}=await ua(e,r);u=await rw(e,a,u,d,r)}if(o==="jsonl"){for(let d of u)console.log(JSON.stringify(mp(d)));return}for(let d of u)console.log(await ar(e,d,c,void 0,r))}async function aw(e,t,n,o,s="text",r){let i=await ke(e,t,r),a=await Me(e,i,sw(n),o,r),c=G(a.messages).map(T);if(s==="jsonl"){for(let u of c)console.log(JSON.stringify(mp(u)));return}let l=new Map;for(let u of c)console.log(await ar(e,u,l,void 0,r))}async function cw(e){let t=await As(e),n=G(t.channels).map(T).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,a=await tt(e,r,5),c=G(a.messages).map(T).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(c.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let l of c){let u=await gp(e,l,o),d=(typeof l.text==="string"?l.text:"").split(`
361
+ `)[0]??"",f=await En(e,d,o);console.log(` ${u}: ${f}`)}}}async function lw(e,t){let n=await Jd(e,"to:me"),o=G(Cs(n,["messages","matches"])).map(T).slice(0,t),s=new Map,r=[];for(let i of o){let a=Bf(tr(i)),c=r[r.length-1];if(c?.label===a)c.msgs.push(i);else r.push({label:a,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:a,msgs:c}=r[i];if(i>0)console.log("");console.log(` ${a}`),console.log(" ----------------------------");for(let l of[...c].reverse()){let u=T(l.channel),d=u.is_im===!0,f=typeof u.name==="string"?u.name:"dm",h;if(d&&f.startsWith("U")){let g="@"+f;if(!s.has(g)){let[,p]=await Fs(e,f);s.set(g,p)}h=`@${s.get(g)??f}`}else if(d)h=`@${f}`;else h=`#${f}`;console.log(await ar(e,l,s,h))}}}async function uw(e,t,n,o,s="text",r){let i=await As(e,r),a=G(i.channels).map(T).filter((c)=>o||c.is_member===!0).filter((c)=>{if(!n)return!0;return(typeof c.name==="string"?c.name:"").toLowerCase().includes(n.toLowerCase())}).sort((c,l)=>Number(l.updated??0)-Number(c.updated??0)).slice(0,t);if(s==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.user==="string"?c.user:l,d=c.is_im===!0,f=c.is_mpim===!0,h=d||f?"@":"#",g=c.is_member===!0?"":" (not joined)",p=typeof T(c.purpose).value==="string"?String(T(c.purpose).value):"",m=p?` ${p.split(`
362
+ `)[0]?.slice(0,60)}`:"";console.log(`${h}${u} ${l}${g}${m}`)}}function dw(e){let t=(s)=>s.startsWith("xoxp-")||s.startsWith("xoxc-"),n=Qr(),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 yp(e,t,n,o,s){let r=e,i=s,a;try{a=await fa(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=dw(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,a=await fa(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.
363
363
  `+` Add a user-token profile: slack auth login (or slack auth login --token <token>)
364
- Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(o){console.log(JSON.stringify(a,null,2));return}let c=G(_s(a,["messages","matches"])).map(T),l=new Map;for(let u of c){let d=T(u.channel),f=d.is_im===!0,h=typeof d.name==="string"?d.name:"dm",g;if(f&&h.startsWith("U")){let p="@"+h;if(!l.has(p)){let[,m]=await $s(r,h,i);l.set(p,m)}g=`@${l.get(p)??h}`}else if(f)g=`@${h}`;else g=`#${h}`;console.log(await or(r,u,l,g,i))}}async function cp(e,t,n,o){let{ref:s,ts:r}=en(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 ha(e,s,ke,o),ts:r}}async function Gy(e,t){let n=Ts(),o={};if(!t.mine)o.shared=!0;if(t.in)o.in=t.in;if(t.from)o.from=t.from;let s=gf(t.state,n,o);if(!t.json){let r=await Be(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${ar(r)} \xB7 matching ${i})`),console.error(`(query: ${s})`)}await Ge("search.messages",()=>ap(e,s,t.count,t.json,t.cookie))}async function Yy(e,t){let n=Ts(),{channelId:o,ts:s}=await cp(e,t.target,t.channelId,t.cookie),r=await Df(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((a)=>`:${a}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${s})${i}`),r.leftover.length)console.error(`\u26A0 ${r.leftover.map((a)=>`:${a}:`).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 Vy(e,t){let n=Ts(),{channelId:o,ts:s}=await cp(e,t.target,t.channelId,t.cookie),r=await kf(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 Zy(e,t){let n=Ts(),o=t.channelId??await ha(e,t.channel,ke,t.cookie),s={limit:t.limit};if(t.fix)s.fix=!0;if(t.cookie)s.cookie=t.cookie;let r=await xf(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 a=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((c)=>`:${c}:`).join(" ")} \u2192 keep :${i.keep}: [${a}] ${P(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 Qy(e,t,n,o){let s=Math.floor(Date.now()/1000)-t*86400,r=await Cs(e),i=G(r.channels).map(T).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)),a=new Map,c=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 tt(e,d,n)}catch(p){console.error(` SKIP #${f}: ${p.message}`);continue}let g=G(h.messages).map(T).filter((p)=>(p.subtype===void 0||p.subtype===null)&&Qo(p)>=s);if(g.length===0)continue;l+=1,c+=g.length,console.log(`## #${f} (${g.length} msgs)
365
- `);for(let p of[...g].reverse()){let m=await rp(e,p,a),w=typeof p.text==="string"?p.text:"",D=Hn(await En(e,w,a)).split(`
366
- `).join(" \u21B5 ");console.log(`[${Rs(Qo(p))}] ${m}: ${D}`)}console.log("")}console.error(`Dumped ${c} messages across ${l} channels (cutoff: ${t}d)`)}function ew(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(s.type==="link"&&typeof s.url==="string"){t.push(s.url);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 Pa(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 Zd(e,s,t),i=T(r.channel),a;if(i.is_im===!0){let c=typeof i.user==="string"?i.user:"";if(!c||c===n)a="@self";else{let[l]=await $s(e,c);a=`@${l}`}}else a=`#${typeof i.name==="string"?i.name:s}`;return o.set(s,a),a}catch{return s}}}function Oa(e){let t=T(G(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function tr(e){return ew(G(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function tw(e,t,n=!1){let o=await As(e,t),s=G(o.drafts??o.messages??[]).map(T).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 ua(e,t))}catch{}let a=await Pa(e,t,i),c=new Map;for(let l of r){let u=Oa(l),d=tr(l),f=Number(l.date_created??l.date_create??0),h=f?Aa(f):"?",g=await a(u),p=typeof l.id==="string"?l.id:"",m=l.is_sent===!0?" [SENT]":"",w=Hn(await En(e,d,c));console.log(`-- ${p} ${g} [${h}]${m}`);for(let b of w.split(`
367
- `))console.log(` ${b}`)}}async function nw(e,t,n){let o=[],s;do{let u=T(await Gd(e,{filter:n.filter,limit:Math.min(n.limit,100),cursor:s},t));o.push(...of(u));let d=T(u.response_metadata).next_cursor;s=typeof d==="string"&&d?d:void 0}while(s&&o.length<n.limit);let r=rf(o).slice(0,n.limit);if(r.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let i="",a="";try{({url:i,userId:a}=await qt(e,t))}catch{}let c=await Pa(e,t,a),l=Date.now()/1000;for(let u of r){let d;if(u.channel&&u.ts)try{let w=T(await Ue(e,u.channel,u.ts,1,t));d=G(w.messages).map(T).find((b)=>b.ts===u.ts)}catch{}let f=u.channel&&u.ts?i?cf(i,u.channel,u.ts):`${u.channel}:${u.ts}`:"";if(n.json){console.log(JSON.stringify({...u,done:Wo(u),permalink:f,user:d?.user??null,text:d?.text??null}));continue}let h=u.channel?await c(u.channel):`(${u.itemType||"item"})`,g=typeof d?.user==="string"?`@${await ve(e,d.user,t)}: `:"",p=typeof d?.text==="string"?d.text.split(`
368
- `)[0]??"":"(message not readable)",m=p.length>100?`${p.slice(0,100)}\u2026`:p;if(console.log(`${af(u,l,Rs)} ${P(h)}`),console.log(` ${P(g+m)}`),f)console.log(` ${f}`)}}async function sw(e,t,n){let o=await As(e,t),s=G(o.drafts).map(T).find((g)=>String(g.id)===n);if(!s)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await ua(e,t))}catch{}let i=await Pa(e,t,r),a=Oa(s),c=tr(s),l=Number(s.date_created??0),u=String(s.last_updated_ts??"?"),d=await i(a),h=Hn(await En(e,c,new Map));console.log(`id: ${s.id}`),console.log(`channel: ${d} (${a})`),console.log(`created: ${l?Aa(l):"?"}`),console.log(`updated: ${Aa(Number(u.split(".")[0]))}`),console.log(`status: ${s.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(h)}function xe(...e){return By(e.join(`
369
- `)).slice(0,4)}function P(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var ow={"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.rename":"channels:manage (or groups:write for a private channel)","conversations.replies":"channels:history (or groups:history)","conversations.history":"channels:history (or groups:history)"};function ye(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 ${ow[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 ir(e,t,n){if(!t.startsWith("D"))return null;try{let o=await cr(e,t,n);if(!o)return null;return await bf(e,o,Un,n)}catch{return null}}function Ee(e,t,n,o,s=new Date){for(let i of n)console.log(i);let r=ka(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 en(e){let t=zt(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:Ia(o)}}}return{ref:e}}function Gn(e,t=!0){let n=zt(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:Ia(s)}}return{ref:e}}async function Qt(e,t,n,o){let s=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=T(await xn(e,t,o)),a=T(i.channel);if(a.is_im===!0){let c=typeof a.user==="string"?a.user:"";s=c?`@${await ve(e,c,o)}`:t}else s=typeof a.name==="string"?`#${a.name}`:t}catch{s=t}return s===t?t:`${s} (${t})`}async function Be(e,t){try{return await qt(e,t)}catch{return null}}function It(e,t){let n;return async()=>{if(n===void 0)n=await Be(e,t);return n}}function Cn(e){if(!Mo())return{record:()=>{}};let t=fd();return{metadata:pd(e,t),record:(n)=>{hd({...n,kind:e,attribution:t})}}}function rw(e){let t=P(e.text.split(`
370
- `)[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`${Rs(e.sent_at/1000)} ${e.kind.padEnd(4)} ${P(e.target??e.channel)} ${n}
364
+ Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(o){console.log(JSON.stringify(a,null,2));return}let c=G(Cs(a,["messages","matches"])).map(T),l=new Map;for(let u of c){let d=T(u.channel),f=d.is_im===!0,h=typeof d.name==="string"?d.name:"dm",g;if(f&&h.startsWith("U")){let p="@"+h;if(!l.has(p)){let[,m]=await Fs(r,h,i);l.set(p,m)}g=`@${l.get(p)??h}`}else if(f)g=`@${h}`;else g=`#${h}`;console.log(await ar(r,u,l,g,i))}}async function wp(e,t,n,o){let{ref:s,ts:r}=Pt(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 Ea(e,s,ke,o),ts:r}}async function fw(e,t){let n=Os(),o={};if(!t.mine)o.shared=!0;if(t.in)o.in=t.in;if(t.from)o.from=t.from;let s=Ef(t.state,n,o);if(!t.json){let r=await je(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${dr(r)} \xB7 matching ${i})`),console.error(`(query: ${s})`)}await Ge("search.messages",()=>yp(e,s,t.count,t.json,t.cookie))}async function pw(e,t){let n=Os(),{channelId:o,ts:s}=await wp(e,t.target,t.channelId,t.cookie),r=await Ff(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((a)=>`:${a}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${s})${i}`),r.leftover.length)console.error(`\u26A0 ${r.leftover.map((a)=>`:${a}:`).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 hw(e,t){let n=Os(),{channelId:o,ts:s}=await wp(e,t.target,t.channelId,t.cookie),r=await Tf(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 gw(e,t){let n=Os(),o=t.channelId??await Ea(e,t.channel,ke,t.cookie),s={limit:t.limit};if(t.fix)s.fix=!0;if(t.cookie)s.cookie=t.cookie;let r=await Rf(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 a=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((c)=>`:${c}:`).join(" ")} \u2192 keep :${i.keep}: [${a}] ${O(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 mw(e,t,n,o){let s=Math.floor(Date.now()/1000)-t*86400,r=await As(e),i=G(r.channels).map(T).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)),a=new Map,c=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 tt(e,d,n)}catch(p){console.error(` SKIP #${f}: ${p.message}`);continue}let g=G(h.messages).map(T).filter((p)=>(p.subtype===void 0||p.subtype===null)&&tr(p)>=s);if(g.length===0)continue;l+=1,c+=g.length,console.log(`## #${f} (${g.length} msgs)
365
+ `);for(let p of[...g].reverse()){let m=await gp(e,p,a),w=typeof p.text==="string"?p.text:"",D=zn(await En(e,w,a)).split(`
366
+ `).join(" \u21B5 ");console.log(`[${_n(tr(p))}] ${m}: ${D}`)}console.log("")}console.error(`Dumped ${c} messages across ${l} channels (cutoff: ${t}d)`)}function yw(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(s.type==="link"&&typeof s.url==="string"){t.push(s.url);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 lr(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 df(e,s,t),i=T(r.channel),a;if(i.is_im===!0){let c=typeof i.user==="string"?i.user:"";if(!c||c===n)a="@self";else{let[l]=await Fs(e,c);a=`@${l}`}}else a=`#${typeof i.name==="string"?i.name:s}`;return o.set(s,a),a}catch{return s}}}function Ja(e){let t=T(G(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function sr(e){return yw(G(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function ww(e,t,n=!1){let o=await Ts(e,t),s=G(o.drafts??o.messages??[]).map(T).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 ya(e,t))}catch{}let a=await lr(e,t,i),c=new Map;for(let l of r){let u=Ja(l),d=sr(l),f=Number(l.date_created??l.date_create??0),h=f?Na(f):"?",g=await a(u),p=typeof l.id==="string"?l.id:"",m=l.is_sent===!0?" [SENT]":"",w=zn(await En(e,d,c));console.log(`-- ${p} ${g} [${h}]${m}`);for(let b of w.split(`
367
+ `))console.log(` ${b}`)}}var or=50,Ms=20;async function bw(e,t,n){let o=[],s,r=0;do{let d=T(await ha(e,{filter:n.filter,limit:or,cursor:s},t));o.push(...wa(d));let f=T(d.response_metadata).next_cursor;s=typeof f==="string"&&f?f:void 0}while(s&&++r<Ms);if(s)console.error(`Note: read the first ${o.length} items only (${Ms} pages); the order covers those.`);let i=yf(o).slice(0,n.limit);if(i.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let a="",c="";try{({url:a,userId:c}=await Ct(e,t))}catch{}let l=await lr(e,t,c),u=Date.now()/1000;for(let d of i){let f;if(d.channel&&d.ts)try{let b=T(await Me(e,d.channel,d.ts,1,t));f=G(b.messages).map(T).find((D)=>D.ts===d.ts)}catch{}let h=d.channel&&d.ts?a?Da(a,d.channel,d.ts):`${d.channel}:${d.ts}`:"";if(n.json){console.log(JSON.stringify({...d,done:Is(d),permalink:h,user:f?.user??null,text:f?.text??null}));continue}let g=d.channel?await l(d.channel):`(${d.itemType||"item"})`,p=typeof f?.user==="string"?`@${await Ie(e,f.user,t)}: `:"",m=typeof f?.text==="string"?f.text.split(`
368
+ `)[0]??"":"(message not readable)",w=m.length>100?`${m.slice(0,100)}\u2026`:m;if(console.log(`${ba(d,u,_n)} ${O(g)}`),console.log(` ${O(p+w)}`),h)console.log(` ${h}`)}}function Dw(e){if(e.kind==="done")return e.undo?["completed","todo","saved","archived"]:["todo","saved","completed","archived"];return["todo","saved","completed","archived"]}async function kw(e,t,n,o,s){let r=0;for(let i of s){let a;do{if(r++>=Ms)return"unknown";let c=T(await ha(e,{filter:i,limit:or,cursor:a},t)),l=wa(c).find((d)=>d.channel===n&&d.ts===o);if(l)return l;let u=T(c.response_metadata).next_cursor;a=typeof u==="string"&&u?u:void 0}while(a)}return}function xw(e,t){let n=(o)=>o===void 0?[]:[` Due: ${o?t(o):"(clear the due date)"}`];switch(e.kind){case"add":return[` Action: add as ${e.saved?"a saved item (no checkbox)":"a to-do"}`,...n(e.due)];case"done":return[` Action: mark ${e.undo?"NOT done (reopen)":"done"}`];case"edit":return[" Action: edit",...e.todo===void 0?[]:[` Kind: ${e.todo?"to-do":"saved item (no checkbox)"}`],...n(e.due)];case"rm":return[" Action: REMOVE from your To-dos (the message itself is untouched)"]}}async function Zo(e,t,n,o,s){let{ref:r,ts:i}=Pt(n);if(!i)console.error("Error: a To-do points at a message \u2014 give its permalink or #chan:<ts> (see `slack todos ls`)."),process.exit(2);if(o.kind==="edit"&&o.due===void 0&&o.todo===void 0)console.error("Error: nothing to edit \u2014 pass --due <time|none>, --todo or --saved."),process.exit(2);let a=await ke(e,r,t),c=await kw(e,t,a,i,Dw(o));if(c==="unknown"&&o.kind!=="add")console.error(`Error: not found in the first ${Ms*or} saved items \u2014 stopped there to stay under Slack's rate limits. Nothing was changed.`),process.exit(1);let l=c==="unknown"?void 0:c;if(o.kind==="add"&&l)console.error(`Error: that message is already in your To-dos (${Is(l)?"done":l.todoState||"saved"}) \u2014 use \`slack todos edit\` or \`done\`.`),process.exit(1);if(o.kind!=="add"&&!l)console.error("Error: that message is not in your To-dos \u2014 nothing to change. `slack todos ls --filter saved` lists everything saved."),process.exit(1);let u="",d="";try{({url:u,userId:d}=await Ct(e,t))}catch{}let f=await(await lr(e,t,d))(a),h;try{let S=T(await Me(e,a,i,1,t));h=G(S.messages).map(T).find((A)=>A.ts===i)}catch{}let g=typeof h?.user==="string"?`@${await Ie(e,h.user,t)}: `:"",p=typeof h?.text==="string"?h.text.split(`
369
+ `)[0]??"":"(message not readable)",m=Xn(p.length>100?`${p.slice(0,100)}\u2026`:p),w=Date.now()/1000,b=xe("todos",JSON.stringify(o),a,i,d);if(s!==b)Se(s,b,["--- To-do ------------------------------------",` For: ${d?`@${await Ie(e,d,t)} (your own To-dos)`:"(your own To-dos)"}`,` Where: ${O(f)}`,` Msg: ${O(g+m)}`,...u?[` Link: ${Da(u,a,i)}`]:[],...l?[` Now: ${ba(l,w,_n)}`]:[],...c==="unknown"?[` Note: not checked beyond the first ${Ms*or} saved items \u2014 it may already be saved`]:[],...xw(o,Pp),"----------------------------------------------"]);let D={channel:a,ts:i};switch(o.kind){case"add":await af(e,D,{todo:!o.saved,...o.due?{due:o.due}:{}},t),console.log(`\u2713 Added to your To-dos${o.due?` (due ${_n(o.due)})`:""}`);break;case"done":await ma(e,D,{mark:o.undo?"uncompleted":"completed"},t),console.log(o.undo?"\u2713 Reopened":"\u2713 Marked done");break;case"edit":await ma(e,D,{...o.todo===void 0?{}:{todo:o.todo},...o.due===void 0?{}:{due:o.due}},t),console.log("\u2713 Updated");break;case"rm":await cf(e,D,t),console.log("\u2713 Removed from your To-dos");break}}async function Sw(e,t,n){let o=await Ts(e,t),s=G(o.drafts).map(T).find((g)=>String(g.id)===n);if(!s)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await ya(e,t))}catch{}let i=await lr(e,t,r),a=Ja(s),c=sr(s),l=Number(s.date_created??0),u=String(s.last_updated_ts??"?"),d=await i(a),h=zn(await En(e,c,new Map));console.log(`id: ${s.id}`),console.log(`channel: ${d} (${a})`),console.log(`created: ${l?Na(l):"?"}`),console.log(`updated: ${Na(Number(u.split(".")[0]))}`),console.log(`status: ${s.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(h)}function xe(...e){return nw(e.join(`
370
+ `)).slice(0,4)}function O(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var Ew={"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.rename":"channels:manage (or groups:write for a private channel)","conversations.replies":"channels:history (or groups:history)","conversations.history":"channels:history (or groups:history)"};function ye(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 ${Ew[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 ur(e,t,n){if(!t.startsWith("D"))return null;try{let o=await fr(e,t,n);if(!o)return null;return await Af(e,o,Jn,n)}catch{return null}}function Se(e,t,n,o,s=new Date){for(let i of n)console.log(i);let r=Ra(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 Pt(e){let t=Xt(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:Ua(o)}}}return{ref:e}}function Vn(e,t=!0){let n=Xt(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:Ua(s)}}return{ref:e}}async function en(e,t,n,o){let s=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=T(await xn(e,t,o)),a=T(i.channel);if(a.is_im===!0){let c=typeof a.user==="string"?a.user:"";s=c?`@${await Ie(e,c,o)}`:t}else s=typeof a.name==="string"?`#${a.name}`:t}catch{s=t}return s===t?t:`${s} (${t})`}async function je(e,t){try{return await Ct(e,t)}catch{return null}}function vt(e,t){let n;return async()=>{if(n===void 0)n=await je(e,t);return n}}function Cn(e){if(!Bo())return{record:()=>{}};let t=Sd();return{metadata:Ed(e,t),record:(n)=>{_d({...n,kind:e,attribution:t})}}}function _w(e){let t=O(e.text.split(`
371
+ `)[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`${_n(e.sent_at/1000)} ${e.kind.padEnd(4)} ${O(e.target??e.channel)} ${n}
371
372
  ${t}
372
- ${P(o)}`}function ar(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let o=P(e.user||e.userId||"?"),s=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${P(e.team)}`:"";return`@${o}${s}${r}${n}`}function _e(e,t={}){return` ${"From:".padEnd(t.pad??6)}${ar(e,t.asBot)}`}async function Fa(e,t,n=60,o){let s=typeof t.user==="string"?await ve(e,t.user,o):typeof t.username==="string"?t.username:"?",r=Is((typeof t.text==="string"?t.text:"").split(`
373
- `)[0]??""),i=r.length>n?`${r.slice(0,n)}\u2026`:r,a=typeof t.ts==="string"?t.ts:"";return`${a?er(a).slice(0,16).replace("T"," "):""} @${s}${i?`: ${i}`:""}`}async function iw(e,t,n,o){let s=n.find((r)=>String(r.ts)===t)??n[0];if(!s)return t;return Fa(e,s,40,o)}function Kf(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function aw(e,t){let n=Kf(e),o=Kf(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 a=0;for(let[l,u]of r){let d=i.get(l);if(d)a+=Math.min(u,d)}let c=Jf(r)+Jf(i);return c===0?0:2*a/c}function Jf(e){let t=0;for(let n of e.values())t+=n;return t}async function qf(e,t,n,o){let s=qe();if(!s)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
374
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(o)return{botToken:s};let{ref:r}=en(e);if(!r.startsWith("@"))return{botToken:s};try{let i=await Tt(t,r,n);return{botToken:s,channelId:await Ft(s,i)}}catch(i){console.error(`Error: could not resolve ${P(r)} to the bot's DM.
373
+ ${O(o)}`}function dr(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let o=O(e.user||e.userId||"?"),s=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${O(e.team)}`:"";return`@${o}${s}${r}${n}`}function _e(e,t={}){return` ${"From:".padEnd(t.pad??6)}${dr(e,t.asBot)}`}async function Ba(e,t,n=60,o){let s=typeof t.user==="string"?await Ie(e,t.user,o):typeof t.username==="string"?t.username:"?",r=Xn((typeof t.text==="string"?t.text:"").split(`
374
+ `)[0]??""),i=r.length>n?`${r.slice(0,n)}\u2026`:r,a=typeof t.ts==="string"?t.ts:"";return`${a?nr(a).slice(0,16).replace("T"," "):""} @${s}${i?`: ${i}`:""}`}async function $w(e,t,n,o){let s=n.find((r)=>String(r.ts)===t)??n[0];if(!s)return t;return Ba(e,s,40,o)}function Zf(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Cw(e,t){let n=Zf(e),o=Zf(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 a=0;for(let[l,u]of r){let d=i.get(l);if(d)a+=Math.min(u,d)}let c=Qf(r)+Qf(i);return c===0?0:2*a/c}function Qf(e){let t=0;for(let n of e.values())t+=n;return t}async function ep(e,t,n,o){let s=qe();if(!s)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
375
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(o)return{botToken:s};let{ref:r}=Pt(e);if(!r.startsWith("@"))return{botToken:s};try{let i=await It(t,r,n);return{botToken:s,channelId:await Rt(s,i)}}catch(i){console.error(`Error: could not resolve ${O(r)} to the bot's DM.
375
376
  ${i instanceof Error?i.message:String(i)}
376
- `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function cw(e,t){let n=It(e,t.cookie),{ref:o,ts:s}=en(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 ke(e,o,t.cookie);let i=await Ue(e,r,s,1,t.cookie),c=G(i.messages).map(T).find((A)=>String(A.ts)===s);if(!c)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=t.mentionCookie??t.cookie,d=t.mentions?await Cf(t.mentionToken??e,t.newText,r,u?{cookie:u}:{}):t.newText;Je(d,t.allowUrlAdjacent);let f=wt(l).kind,h=wt(d).kind,g=Ss(l).kind!=="other",p=g?Ss(d).kind==="other":f!=="other"&&(h==="other"||f!=="open"&&h==="open");if(p&&!t.force)console.error(`Error: this message is ${g?"a `slack poll`":`a \`slack ask\` question (${f==="open"?"open":f==="resolved"?"answered":"void"})`}, and ${g||h==="other"?"the new text would no longer read back as one (collect could not find the question, the pills or the answer)":"the new text would turn it back into an OPEN question"}.
377
+ `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function Aw(e,t){let n=vt(e,t.cookie),{ref:o,ts:s}=Pt(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 ke(e,o,t.cookie);let i=await Me(e,r,s,1,t.cookie),c=G(i.messages).map(T).find((F)=>String(F.ts)===s);if(!c)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=t.mentionCookie??t.cookie,d=t.mentions?await vf(t.mentionToken??e,t.newText,r,u?{cookie:u}:{}):t.newText;Ke(d,t.allowUrlAdjacent);let f=bt(l).kind,h=bt(d).kind,g=_s(l).kind!=="other",p=g?_s(d).kind==="other":f!=="other"&&(h==="other"||f!=="open"&&h==="open");if(p&&!t.force)console.error(`Error: this message is ${g?"a `slack poll`":`a \`slack ask\` question (${f==="open"?"open":f==="resolved"?"answered":"void"})`}, and ${g||h==="other"?"the new text would no longer read back as one (collect could not find the question, the pills or the answer)":"the new text would turn it back into an OPEN question"}.
377
378
  `+(g?" Edit it anyway with --force.":` To retire it: slack ask --void='${t.target}' --reason '\u2026'
378
- Edit it anyway with --force.`)),process.exit(1);let m=p,w=await n(),b=m?xe("force-edit-ask-poll",l,d,w?.userId??""):xe(l,d,w?.userId??"");if(t.code!==b)Ee(t.code,b,[...m?[`\u26A0 --force: rewriting a \`slack ${g?"poll":"ask"}\` message by hand \u2014 collect may no longer read it back`]:[],"--- Editing as -------------------------------",_e(w,{asBot:t.asBot}),"--- Original message -------------------------",...l.split(`
379
- `).map((A)=>` ${A}`),"--- Replacing with ---------------------------",...d.split(`
380
- `).map((A)=>` ${A}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let D=Cn("edit"),S=f!=="other"||h!=="other"||g||Ss(d).kind!=="other",F=await Ct(e,r,s,d,t.cookie,S?!0:void 0,D.metadata);console.log(`\u2713 Edited (ts: ${F})`),D.record({team:w?.team,channel:r,target:t.target,ts:s,text:d,asBot:t.asBot})}async function lw(e,t){let n=It(e,t.cookie),{ref:o,ts:s}=en(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 ke(e,o,t.cookie);let i=await Ue(e,r,s,1,t.cookie),c=G(i.messages).map(T).find((f)=>String(f.ts)===s);if(!c)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=await n(),d=xe(r,s,l,u?.userId??"");if(t.code!==d){let f=await Qt(e,r,o,t.cookie);Ee(t.code,d,["--- Deleting message -------------------------",_e(u,{asBot:t.asBot}),` \u2192 ${f} at ${er(s)}`,...l.split(`
381
- `).map((h)=>` ${h}`),"---------------------------------------------"])}await Md(e,r,s,t.cookie),console.log(`\u2713 Deleted (ts: ${s})`)}function Zt(e){return`'${e.replace(/'/g,"'\\''")}'`}async function va(e,t,n){let o=Go(t);if(o)return{...o,ref:o.channel};let{ref:s,ts:r}=en(t);if(!r)console.error(`Error: ${P(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 ${Zt(t)}`),process.exit(2);return{channel:await ke(e,s,n),ts:r,ref:s}}async function uw(e,t,n,o){let s=T(await Ue(e,t,n,1,o)),r=G(s.messages).map(T).find((i)=>String(i.ts)===n);if(!r)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return r}function Vo(e,t){if(t!==void 0)try{return np(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:Me(e)}var Hf=40000;function nr(e,t){if(t.length>Hf)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${Hf}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function sr(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof _t)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function lp(e,t){let n=ka(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function dw(e,t){let{ref:n,ts:o}=en(t.target);if(o||Go(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 ${Zt(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(Je(t.state,t.allowUrlAdjacent),t.log!==void 0)Je(t.log,t.allowUrlAdjacent),nr("reason",t.log);let s=`${t.workspace?` -w ${Zt(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=It(e,t.cookie),i=await ke(e,n,t.cookie),a=await r(),c=xe("pinlog-create",i,t.state,t.log??"",a?.userId??""),l=new Date,u=Ea(t.state,l);if(nr("HEAD (state + footer)",u),t.code!==c){let p=await Qt(e,i,n,t.cookie),m=(await up(e,i,200,t.cookie)).found;Ee(t.code,c,["--- New pinlog -------------------------------",_e(a,{asBot:t.asBot}),` \u2192 ${p} \u2014 NEW top-level message, then pinned`,...m.length?[`\u26A0 ${m.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...m.slice(0,5).map((w)=>` ${at(i,String(w.ts))} ${dp(String(w.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
382
- `).map((w)=>` ${P(w)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
383
- `).map((w)=>` ${P(w)}`)]:[],"---------------------------------------------"])}let d=Cn("send"),f;try{f=await Ht(e,i,u,void 0,!1,t.cookie,!0,d.metadata)}catch(p){if(sr(p))console.error(`\u2717 HEAD was NOT posted: ${ye(p)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ye(p)}
384
- Check before retrying, or you will have two boards: slack pinlog ls ${Zt(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:a?.team,channel:i,target:t.target,ts:f,text:u,asBot:t.asBot});let h=at(i,f);console.log(`\u2713 Posted HEAD: ${h}`);let g=lp(l,"this new top-level post notified everyone who follows the channel");if(g)console.error(g);try{await la(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(p){let m=p instanceof Error?p.message:String(p),w=/missing_scope/.test(m)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:ye(p);console.error(`\u26A0 NOT pinned: ${w}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${h}${s}`)}if(t.log)try{let p=await Ht(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${p})`)}catch(p){let m=xe("pinlog-log",i,f,t.log,a?.userId??"");console.error(`${sr(p)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ye(p)}
379
+ Edit it anyway with --force.`)),process.exit(1);let m=p,w=await n(),b=m?xe("force-edit-ask-poll",l,d,w?.userId??""):xe(l,d,w?.userId??"");if(t.code!==b)Se(t.code,b,[...m?[`\u26A0 --force: rewriting a \`slack ${g?"poll":"ask"}\` message by hand \u2014 collect may no longer read it back`]:[],"--- Editing as -------------------------------",_e(w,{asBot:t.asBot}),"--- Original message -------------------------",...l.split(`
380
+ `).map((F)=>` ${F}`),"--- Replacing with ---------------------------",...d.split(`
381
+ `).map((F)=>` ${F}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let D=Cn("edit"),S=f!=="other"||h!=="other"||g||_s(d).kind!=="other",A=await At(e,r,s,d,t.cookie,S?!0:void 0,D.metadata);console.log(`\u2713 Edited (ts: ${A})`),D.record({team:w?.team,channel:r,target:t.target,ts:s,text:d,asBot:t.asBot})}async function Fw(e,t){let n=vt(e,t.cookie),{ref:o,ts:s}=Pt(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 ke(e,o,t.cookie);let i=await Me(e,r,s,1,t.cookie),c=G(i.messages).map(T).find((f)=>String(f.ts)===s);if(!c)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=await n(),d=xe(r,s,l,u?.userId??"");if(t.code!==d){let f=await en(e,r,o,t.cookie);Se(t.code,d,["--- Deleting message -------------------------",_e(u,{asBot:t.asBot}),` \u2192 ${f} at ${nr(s)}`,...l.split(`
382
+ `).map((h)=>` ${h}`),"---------------------------------------------"])}await Xd(e,r,s,t.cookie),console.log(`\u2713 Deleted (ts: ${s})`)}function Qt(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Ka(e,t,n){let o=Yo(t);if(o)return{...o,ref:o.channel};let{ref:s,ts:r}=Pt(t);if(!r)console.error(`Error: ${O(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 ${Qt(t)}`),process.exit(2);return{channel:await ke(e,s,n),ts:r,ref:s}}async function Tw(e,t,n,o){let s=T(await Me(e,t,n,1,o)),r=G(s.messages).map(T).find((i)=>String(i.ts)===n);if(!r)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return r}function Qo(e,t){if(t!==void 0)try{return fp(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:Ne(e)}var tp=40000;function rr(e,t){if(t.length>tp)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${tp}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function ir(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof $t)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function bp(e,t){let n=Ra(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function Rw(e,t){let{ref:n,ts:o}=Pt(t.target);if(o||Yo(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 ${Qt(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(Ke(t.state,t.allowUrlAdjacent),t.log!==void 0)Ke(t.log,t.allowUrlAdjacent),rr("reason",t.log);let s=`${t.workspace?` -w ${Qt(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=vt(e,t.cookie),i=await ke(e,n,t.cookie),a=await r(),c=xe("pinlog-create",i,t.state,t.log??"",a?.userId??""),l=new Date,u=Pa(t.state,l);if(rr("HEAD (state + footer)",u),t.code!==c){let p=await en(e,i,n,t.cookie),m=(await Dp(e,i,200,t.cookie)).found;Se(t.code,c,["--- New pinlog -------------------------------",_e(a,{asBot:t.asBot}),` \u2192 ${p} \u2014 NEW top-level message, then pinned`,...m.length?[`\u26A0 ${m.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...m.slice(0,5).map((w)=>` ${at(i,String(w.ts))} ${kp(String(w.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
383
+ `).map((w)=>` ${O(w)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
384
+ `).map((w)=>` ${O(w)}`)]:[],"---------------------------------------------"])}let d=Cn("send"),f;try{f=await zt(e,i,u,void 0,!1,t.cookie,!0,d.metadata)}catch(p){if(ir(p))console.error(`\u2717 HEAD was NOT posted: ${ye(p)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ye(p)}
385
+ Check before retrying, or you will have two boards: slack pinlog ls ${Qt(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:a?.team,channel:i,target:t.target,ts:f,text:u,asBot:t.asBot});let h=at(i,f);console.log(`\u2713 Posted HEAD: ${h}`);let g=bp(l,"this new top-level post notified everyone who follows the channel");if(g)console.error(g);try{await pa(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(p){let m=p instanceof Error?p.message:String(p),w=/missing_scope/.test(m)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:ye(p);console.error(`\u26A0 NOT pinned: ${w}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${h}${s}`)}if(t.log)try{let p=await zt(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${p})`)}catch(p){let m=xe("pinlog-log",i,f,t.log,a?.userId??"");console.error(`${ir(p)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ye(p)}
385
386
  The board IS posted. Retry just the reason (check the thread first):
386
- slack pinlog note ${h} ${Zt(Jn(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${s} --code=${m}`),process.exit(1)}}async function zf(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(Je(t.log,t.allowUrlAdjacent),t.state!==void 0)Je(t.state,t.allowUrlAdjacent);nr("log line",t.log);let n=It(e,t.cookie),{channel:o,ts:s,ref:r}=await va(e,t.target,t.cookie);try{Uf(`pinlog-${o}-${s}`)}catch(w){if(!(w instanceof Ps))throw w;console.error(`Error: another update of ${at(o,s)} is running (${w.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await uw(e,o,s,t.cookie),a=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(!Xn(a)&&!t.adopt)console.error(`Error: the message at ${at(o,s)} is not a pinlog HEAD (no "${Os}" footer).
387
- `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let c=await n(),l=at(o,s),u=new Date,d=`${t.workspace?` -w ${Zt(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=xe("pinlog-log",o,s,t.log,c?.userId??""),h=`slack pinlog note ${l} ${Zt(Jn(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,g=lp(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 w=await Qt(e,o,r,t.cookie);Ee(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",_e(c,{asBot:t.asBot}),` \u2192 ${w}, thread of ${l}`,...t.log.split(`
388
- `).map((b)=>` ${P(b)}`),"---------------------------------------------"])}}else{let w=Ea(t.state,u);nr("new HEAD (state + footer)",w);let b=!Xn(a),D=xe("pinlog-update",o,s,a,t.state,t.log,c?.userId??"");if(t.code!==D){let F=await Qt(e,o,r,t.cookie),A=vs(a).trim()===vs(t.state).trim();Ee(t.code,D,["--- Updating pinlog --------------------------",_e(c,{asBot:t.asBot}),` \u2192 ${F}, ${l}`,"--- Current HEAD -----------------------------",...a.split(`
389
- `).map((C)=>` ${P(C)}`),"--- New HEAD (edited in place \u2014 silent) ------",...w.split(`
390
- `).map((C)=>` ${P(C)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
391
- `).map((C)=>` ${P(C)}`),"---------------------------------------------",...A?["\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 S=Cn("edit");try{await Ct(e,o,s,w,t.cookie,!0,S.metadata)}catch(F){let A=F instanceof Error?F.message:String(F),C=/cant_update_message/.test(A)?`
392
- Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",x=sr(F)?`\u2717 HEAD was NOT updated: ${ye(F)}${C}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ye(F)}
387
+ slack pinlog note ${h} ${Qt(qn(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${s} --code=${m}`),process.exit(1)}}async function np(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(Ke(t.log,t.allowUrlAdjacent),t.state!==void 0)Ke(t.state,t.allowUrlAdjacent);rr("log line",t.log);let n=vt(e,t.cookie),{channel:o,ts:s,ref:r}=await Ka(e,t.target,t.cookie);try{Vf(`pinlog-${o}-${s}`)}catch(w){if(!(w instanceof Ps))throw w;console.error(`Error: another update of ${at(o,s)} is running (${w.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await Tw(e,o,s,t.cookie),a=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(a)&&!t.adopt)console.error(`Error: the message at ${at(o,s)} is not a pinlog HEAD (no "${vs}" footer).
388
+ `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let c=await n(),l=at(o,s),u=new Date,d=`${t.workspace?` -w ${Qt(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=xe("pinlog-log",o,s,t.log,c?.userId??""),h=`slack pinlog note ${l} ${Qt(qn(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,g=bp(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 w=await en(e,o,r,t.cookie);Se(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",_e(c,{asBot:t.asBot}),` \u2192 ${w}, thread of ${l}`,...t.log.split(`
389
+ `).map((b)=>` ${O(b)}`),"---------------------------------------------"])}}else{let w=Pa(t.state,u);rr("new HEAD (state + footer)",w);let b=!Yn(a),D=xe("pinlog-update",o,s,a,t.state,t.log,c?.userId??"");if(t.code!==D){let A=await en(e,o,r,t.cookie),F=Ls(a).trim()===Ls(t.state).trim();Se(t.code,D,["--- Updating pinlog --------------------------",_e(c,{asBot:t.asBot}),` \u2192 ${A}, ${l}`,"--- Current HEAD -----------------------------",...a.split(`
390
+ `).map((E)=>` ${O(E)}`),"--- New HEAD (edited in place \u2014 silent) ------",...w.split(`
391
+ `).map((E)=>` ${O(E)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
392
+ `).map((E)=>` ${O(E)}`),"---------------------------------------------",...F?["\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 S=Cn("edit");try{await At(e,o,s,w,t.cookie,!0,S.metadata)}catch(A){let F=A instanceof Error?A.message:String(A),E=/cant_update_message/.test(F)?`
393
+ Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",x=ir(A)?`\u2717 HEAD was NOT updated: ${ye(A)}${E}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ye(A)}
393
394
  Check it first: slack pinlog get ${l}${d}`;console.error(`${x}
394
- The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}S.record({team:c?.team,channel:o,target:t.target,ts:s,text:w,asBot:t.asBot}),console.log(`\u2713 HEAD updated: ${l}`)}let p=Cn("send"),m;try{m=await Ht(e,o,t.log,s,!1,t.cookie,!0,p.metadata)}catch(w){let b=sr(w);console.error((b?`\u2717 Log reply was NOT posted: ${ye(w)}
395
+ The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}S.record({team:c?.team,channel:o,target:t.target,ts:s,text:w,asBot:t.asBot}),console.log(`\u2713 HEAD updated: ${l}`)}let p=Cn("send"),m;try{m=await zt(e,o,t.log,s,!1,t.cookie,!0,p.metadata)}catch(w){let b=ir(w);console.error((b?`\u2717 Log reply was NOT posted: ${ye(w)}
395
396
  `:`\u26A0 UNKNOWN whether the log reply was posted: ${ye(w)}
396
397
  `)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${b?"is":"may be"} missing.
397
398
  `)+(b?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${l}${d}
398
399
  `)+` Retry just the log line${b?"":" (only if it is not there)"}:
399
- ${h}`),process.exit(1)}if(p.record({team:c?.team,channel:o,target:t.target,ts:m,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${m})`),g)console.error(g)}function Xf(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function fw(e){return xa(new Date(Number(e.split(".")[0])*1000))}async function pw(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 ve(e,t.user,o)}catch{i=t.user}return n.set(t.user,i),i}let s=T(t.bot_profile);if(typeof s.name==="string")return s.name;return typeof t.username==="string"?t.username:"bot"}async function hw(e,t,n,o){let{channel:s,ts:r}=await va(e,t,n),i=[],a,c=0;do{let p=T(await Nd(e,s,r,a,200,n));for(let w of G(p.messages).map(T)){if(String(w.ts)===r&&i.some((b)=>String(b.ts)===r))continue;i.push(w)}let m=T(p.response_metadata).next_cursor;a=typeof m==="string"&&m?m:void 0,c++}while(a&&c<50);let l=a===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:at(s,r),isPinlog:Xn(d),updated:_a(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(!Xn(d))console.error(`\u26A0 ${at(s,r)} has no "${Os}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${at(s,r)} ===`);for(let p of Xf(d).split(`
400
- `))console.log(P(p));let h=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${h}) ===`);let g=new Map;for(let p of f){let m=typeof p.text==="string"?p.text:"",w=P(await pw(e,p,g,n)),b=Xf(m).split(`
401
- `).map((D)=>P(D));console.log(`${fw(String(p.ts))} @${w}: ${b[0]??""}`);for(let D of b.slice(1))console.log(` ${D}`)}}async function up(e,t,n,o){let s=0,r,i=[];do{let a=T(await tt(e,t,Math.min(200,n-s),void 0,r,o)),c=G(a.messages).map(T);s+=c.length;for(let u of c)if(typeof u.text==="string"&&Xn(u.text))i.push(u);let l=T(a.response_metadata).next_cursor;r=typeof l==="string"&&l?l:void 0}while(r&&s<n);return{found:i,scanned:s}}function dp(e){return P(vs(e).split(`
402
- `).find((t)=>t.trim())??"").slice(0,80)}async function gw(e,t,n,o){let{ref:s,ts:r}=en(t);if(r||Go(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${Zt(t)}`),process.exit(2);let i=await ke(e,s,o),{found:a,scanned:c}=await up(e,i,n,o),l=await Qt(e,i,s,o);if(a.length===0){console.log(`No pinlogs in the last ${c} messages of ${l}.${c>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of a){let d=String(u.ts),f=at(i,d),h=String(u.text),g=G(u.pinned_to).some((w)=>w===i)?"\uD83D\uDCCC":" ",p=dp(h),m=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${g} ${f} updated ${_a(h)??"?"} log ${m}`),console.log(` ${p}`)}}async function mw(e,t,n){let{channel:o,ts:s}=await va(e,t,n);try{await la(e,o,s,n),console.log(`\u2713 Pinned ${at(o,s)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${at(o,s)}`);return}console.error(`\u2717 NOT pinned: ${ye(r)}`),process.exit(1)}}async function yw(e,t){let{ref:n,ts:o}=en(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 ke(e,n,t.cookie);if(t.remove)await At(e,r,o,s,t.cookie),console.log(`\u2713 Removed :${s}: (ts: ${o})`);else await $t(e,r,o,s,t.cookie),console.log(`\u2713 Reacted :${s}: (ts: ${o})`)}async function La(e,t,n,o){if(!n||!t.startsWith("D"))return!1;try{let s=T(await xn(e,t,o)),r=T(s.channel);return r.is_im===!0&&r.user===n}catch{return!1}}function ww(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let o of G(n.reply_users))if(typeof o==="string")t.add(o)}return t}async function bw(e,t,n){if(!t.startsWith("D"))return;try{let o=T(T(await xn(e,t,n)).channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function Dw(e,t){let{ref:n,threadTs:o}=Gn(t.target),s=t.cookie,r=It(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ft(e,t.userId,s);else i=await ke(e,n,s);if(!t.asBot&&await La(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.
403
- `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let a=Me(t.message);Je(a,t.allowUrlAdjacent);let c=a,l=null;if(t.mentions){l=await Yt(t.mentionToken??e,a,i,t.mentionCookie),c=l.text;for(let C of zo(l.unresolved))console.error(`\u26A0 ${P(C)}`)}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let C of l.resolved)u.push(` \u2713 ${P(C.surface)} \u2192 @${P(C.display)} (${C.userId}) \u2014 will notify`);for(let C of l.unresolved){let x=C.reason==="ambiguous"?"ambiguous":C.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${P(C.surface)} \u2014 plain text, NOT notified (${x})`)}}let d="",f="?",h=[],g,p,m;if(o)try{let C=await Ue(e,i,o,100,s);h=G(C.messages).map(T);let x=h[h.length-1];d=typeof x?.text==="string"?x.text:"",g=typeof x?.user==="string"?x.user:void 0,p=typeof x?.bot_id==="string"?x.bot_id:void 0,m=typeof x?.ts==="string"?x.ts:void 0}catch{}else try{let C=await tt(e,i,1,void 0,void 0,s),x=G(C.messages).map(T),J=x.filter((L)=>L.subtype===void 0||L.subtype===null)[0];d=typeof J?.text==="string"?J.text:"",f=typeof J?.user==="string"?await ve(e,J.user,s):typeof J?.username==="string"?J.username:"?";let ne=x[0];g=typeof ne?.user==="string"?ne.user:void 0,p=typeof ne?.bot_id==="string"?ne.bot_id:void 0,m=typeof ne?.ts==="string"?ne.ts:void 0}catch{}try{let C=o?ww(h):new Set([await bw(e,i,s)].filter((x)=>!!x));for(let x of await Ff(t.mentionToken??e,c,t.mentionCookie)){if(C.has(x.userId))continue;console.error(`\u26A0 possible untagged mention: ${P(x.surface)} \u2014 @${P(x.display)} won't be notified (did you mean <@${x.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&m&&(g||p))try{let C=await r();if(!!C&&(!!g&&!!C.userId&&C.userId===g||!!p&&!!C.botId&&C.botId===p)){let J=`slack edit "#${i}:${m}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${i}`;try{let ne=await Wn(e,i,m,s);if(ne)J=`slack edit "${ne}" "<\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(` ${J}`),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 C={sim:0,msg:null};for(let x of h){let J=typeof x.text==="string"?x.text:"";if(!J)continue;let ne=aw(c,J);if(ne>C.sim)C={sim:ne,msg:x}}if(C.msg&&C.sim>=0.82){let x=Math.round(C.sim*100);console.error(`\u26A0 possible duplicate: ${x}% similar to an existing thread message \u2014 ${await Fa(e,C.msg,60,s)}`)}}let w=await r(),b=await ir(e,i,s),D=xe(i,o??"",d,c,w?.userId??"");if(t.code!==D){let C=await Qt(e,i,n,s),x=_e(w,{asBot:t.asBot});if(o){let J=await iw(e,o,h,s),ne=h.slice(-3),L=ne.length?await Promise.all(ne.map(async(O)=>` ${await Fa(e,O,60,s)}`)):[" (thread context unavailable)"];Ee(t.code,D,["--- Recent messages in thread ----------------",...L,...u,"--- Sending ----------------------------------",x,` \u2192 ${C} thread of ${J} \u2014 THREAD REPLY`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],b)}else Ee(t.code,D,["--- Last message in channel ------------------",` ${f}: ${Is(d.split(`
404
- `)[0]??"").slice(0,100)}`,...u,"--- Sending ----------------------------------",x,` \u2192 ${C} \u2014 NEW top-level message`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],b)}let S=Cn("send"),F=await Ht(e,i,c,o,t.broadcast,s,void 0,S.metadata),A="";try{A=await Wn(e,i,F,s)}catch{}if(S.record({team:(await r())?.team,channel:i,target:t.target,ts:F,threadTs:o,permalink:A,text:c,asBot:t.asBot}),A)console.log(`\u2713 Sent: ${A}`);else console.log(`\u2713 Sent (ts: ${F})`);if(t.asBot&&i.startsWith("D"))try{let C=await ho(e);if(!C.ok)for(let x of go(C,!0))console.error(x);else{let x=C.appId?`https://api.slack.com/apps/${C.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${x} \u2192 App Home.`)}}catch{}}var kw=2,ce=3,xw=4,Sw=5,fp=6,Ew=7,_w=10;function Cw(){return/^(1|true|yes|on)$/i.test(process.env.SLACK_TERM_ASK_EXPLAIN??"")}var $w=1.618033988749895,Aw=1000,Fw=5000,Gf=8,Tw=(e)=>new Promise((t)=>setTimeout(t,e)),pp=new Set(["thread_broadcast"]),Rw=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function hp(e){if(!e.length)return;let t=e.map((n)=>{let o=P(n.surface);if(n.reason==="unavailable")return`${o}: could not fetch the user list or channel members (users:read missing or an API/connection error)`;if(n.reason==="ambiguous")return`${o}: matches multiple people \u2014 use an explicit <@USERID> tag`;return`${o}: matched no one`});console.error(`Error: \`ask\` will not post with unresolved answerer tags.
400
+ ${h}`),process.exit(1)}if(p.record({team:c?.team,channel:o,target:t.target,ts:m,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${m})`),g)console.error(g)}function sp(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Iw(e){return Ia(new Date(Number(e.split(".")[0])*1000))}async function Ow(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 Ie(e,t.user,o)}catch{i=t.user}return n.set(t.user,i),i}let s=T(t.bot_profile);if(typeof s.name==="string")return s.name;return typeof t.username==="string"?t.username:"bot"}async function Pw(e,t,n,o){let{channel:s,ts:r}=await Ka(e,t,n),i=[],a,c=0;do{let p=T(await Gd(e,s,r,a,200,n));for(let w of G(p.messages).map(T)){if(String(w.ts)===r&&i.some((b)=>String(b.ts)===r))continue;i.push(w)}let m=T(p.response_metadata).next_cursor;a=typeof m==="string"&&m?m:void 0,c++}while(a&&c<50);let l=a===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:at(s,r),isPinlog:Yn(d),updated:va(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 ${at(s,r)} has no "${vs}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${at(s,r)} ===`);for(let p of sp(d).split(`
401
+ `))console.log(O(p));let h=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${h}) ===`);let g=new Map;for(let p of f){let m=typeof p.text==="string"?p.text:"",w=O(await Ow(e,p,g,n)),b=sp(m).split(`
402
+ `).map((D)=>O(D));console.log(`${Iw(String(p.ts))} @${w}: ${b[0]??""}`);for(let D of b.slice(1))console.log(` ${D}`)}}async function Dp(e,t,n,o){let s=0,r,i=[];do{let a=T(await tt(e,t,Math.min(200,n-s),void 0,r,o)),c=G(a.messages).map(T);s+=c.length;for(let u of c)if(typeof u.text==="string"&&Yn(u.text))i.push(u);let l=T(a.response_metadata).next_cursor;r=typeof l==="string"&&l?l:void 0}while(r&&s<n);return{found:i,scanned:s}}function kp(e){return O(Ls(e).split(`
403
+ `).find((t)=>t.trim())??"").slice(0,80)}async function vw(e,t,n,o){let{ref:s,ts:r}=Pt(t);if(r||Yo(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${Qt(t)}`),process.exit(2);let i=await ke(e,s,o),{found:a,scanned:c}=await Dp(e,i,n,o),l=await en(e,i,s,o);if(a.length===0){console.log(`No pinlogs in the last ${c} messages of ${l}.${c>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of a){let d=String(u.ts),f=at(i,d),h=String(u.text),g=G(u.pinned_to).some((w)=>w===i)?"\uD83D\uDCCC":" ",p=kp(h),m=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${g} ${f} updated ${va(h)??"?"} log ${m}`),console.log(` ${p}`)}}async function Lw(e,t,n){let{channel:o,ts:s}=await Ka(e,t,n);try{await pa(e,o,s,n),console.log(`\u2713 Pinned ${at(o,s)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${at(o,s)}`);return}console.error(`\u2717 NOT pinned: ${ye(r)}`),process.exit(1)}}async function Mw(e,t){let{ref:n,ts:o}=Pt(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 ke(e,n,t.cookie);if(t.remove)await Tt(e,r,o,s,t.cookie),console.log(`\u2713 Removed :${s}: (ts: ${o})`);else await Ft(e,r,o,s,t.cookie),console.log(`\u2713 Reacted :${s}: (ts: ${o})`)}async function qa(e,t,n,o){if(!n||!t.startsWith("D"))return!1;try{let s=T(await xn(e,t,o)),r=T(s.channel);return r.is_im===!0&&r.user===n}catch{return!1}}function Nw(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let o of G(n.reply_users))if(typeof o==="string")t.add(o)}return t}async function Bw(e,t,n){if(!t.startsWith("D"))return;try{let o=T(T(await xn(e,t,n)).channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function jw(e,t){let{ref:n,threadTs:o}=Vn(t.target),s=t.cookie,r=vt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Rt(e,t.userId,s);else i=await ke(e,n,s);if(!t.asBot&&await qa(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.
404
+ `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let a=Ne(t.message);Ke(a,t.allowUrlAdjacent);let c=a,l=null;if(t.mentions){l=await Vt(t.mentionToken??e,a,i,t.mentionCookie),c=l.text;for(let E of Xo(l.unresolved))console.error(`\u26A0 ${O(E)}`)}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let E of l.resolved)u.push(` \u2713 ${O(E.surface)} \u2192 @${O(E.display)} (${E.userId}) \u2014 will notify`);for(let E of l.unresolved){let x=E.reason==="ambiguous"?"ambiguous":E.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${O(E.surface)} \u2014 plain text, NOT notified (${x})`)}}let d="",f="?",h=[],g,p,m;if(o)try{let E=await Me(e,i,o,100,s);h=G(E.messages).map(T);let x=h[h.length-1];d=typeof x?.text==="string"?x.text:"",g=typeof x?.user==="string"?x.user:void 0,p=typeof x?.bot_id==="string"?x.bot_id:void 0,m=typeof x?.ts==="string"?x.ts:void 0}catch{}else try{let E=await tt(e,i,1,void 0,void 0,s),x=G(E.messages).map(T),W=x.filter((M)=>M.subtype===void 0||M.subtype===null)[0];d=typeof W?.text==="string"?W.text:"",f=typeof W?.user==="string"?await Ie(e,W.user,s):typeof W?.username==="string"?W.username:"?";let Q=x[0];g=typeof Q?.user==="string"?Q.user:void 0,p=typeof Q?.bot_id==="string"?Q.bot_id:void 0,m=typeof Q?.ts==="string"?Q.ts:void 0}catch{}try{let E=o?Nw(h):new Set([await Bw(e,i,s)].filter((x)=>!!x));for(let x of await Nf(t.mentionToken??e,c,t.mentionCookie)){if(E.has(x.userId))continue;console.error(`\u26A0 possible untagged mention: ${O(x.surface)} \u2014 @${O(x.display)} won't be notified (did you mean <@${x.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&m&&(g||p))try{let E=await r();if(!!E&&(!!g&&!!E.userId&&E.userId===g||!!p&&!!E.botId&&E.botId===p)){let W=`slack edit "#${i}:${m}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${i}`;try{let Q=await Un(e,i,m,s);if(Q)W=`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(` ${W}`),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 E={sim:0,msg:null};for(let x of h){let W=typeof x.text==="string"?x.text:"";if(!W)continue;let Q=Cw(c,W);if(Q>E.sim)E={sim:Q,msg:x}}if(E.msg&&E.sim>=0.82){let x=Math.round(E.sim*100);console.error(`\u26A0 possible duplicate: ${x}% similar to an existing thread message \u2014 ${await Ba(e,E.msg,60,s)}`)}}let w=await r(),b=await ur(e,i,s),D=xe(i,o??"",d,c,w?.userId??"");if(t.code!==D){let E=await en(e,i,n,s),x=_e(w,{asBot:t.asBot});if(o){let W=await $w(e,o,h,s),Q=h.slice(-3),M=Q.length?await Promise.all(Q.map(async(P)=>` ${await Ba(e,P,60,s)}`)):[" (thread context unavailable)"];Se(t.code,D,["--- Recent messages in thread ----------------",...M,...u,"--- Sending ----------------------------------",x,` \u2192 ${E} thread of ${W} \u2014 THREAD REPLY`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],b)}else Se(t.code,D,["--- Last message in channel ------------------",` ${f}: ${Xn(d.split(`
405
+ `)[0]??"").slice(0,100)}`,...u,"--- Sending ----------------------------------",x,` \u2192 ${E} \u2014 NEW top-level message`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],b)}let S=Cn("send"),A=await zt(e,i,c,o,t.broadcast,s,void 0,S.metadata),F="";try{F=await Un(e,i,A,s)}catch{}if(S.record({team:(await r())?.team,channel:i,target:t.target,ts:A,threadTs:o,permalink:F,text:c,asBot:t.asBot}),F)console.log(`\u2713 Sent: ${F}`);else console.log(`\u2713 Sent (ts: ${A})`);if(t.asBot&&i.startsWith("D"))try{let E=await mo(e);if(!E.ok)for(let x of yo(E,!0))console.error(x);else{let x=E.appId?`https://api.slack.com/apps/${E.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${x} \u2192 App Home.`)}}catch{}}var Ww=2,ce=3,Uw=4,Jw=5,xp=6,Kw=7,qw=10;function Hw(){return/^(1|true|yes|on)$/i.test(process.env.SLACK_TERM_ASK_EXPLAIN??"")}var zw=1.618033988749895,Xw=1000,Gw=5000,op=8,Yw=(e)=>new Promise((t)=>setTimeout(t,e)),Sp=new Set(["thread_broadcast"]),Vw=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function Ep(e){if(!e.length)return;let t=e.map((n)=>{let o=O(n.surface);if(n.reason==="unavailable")return`${o}: could not fetch the user list or channel members (users:read missing or an API/connection error)`;if(n.reason==="ambiguous")return`${o}: matches multiple people \u2014 use an explicit <@USERID> tag`;return`${o}: matched no one`});console.error(`Error: \`ask\` will not post with unresolved answerer tags.
405
406
  ${t.join(`
406
- `)}`),process.exit(ce)}function Ls(e){let t=new Set;return{text:e.replace(Rw,(o,s)=>{let r=s.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function cr(e,t,n){if(!t.startsWith("D"))return;try{let o=T(await xn(e,t,n)),s=T(o.channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function gp(e,t,n,o){let s=new Map;if(t.threadParentTs||t.replyCount!==0)try{let a=T(await Ue(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let c of G(a.messages).map(T))s.set(String(c.ts),c)}catch(a){console.error(` (\u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${a instanceof Error?a.message:String(a)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let a=T(await tt(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),c=G(a.messages).map(T),l=c.filter((u)=>Number(u.ts)>Number(t.ts)&&(t.askerBotId&&u.bot_id===t.askerBotId||t.askerUserId&&u.user===t.askerUserId)).reduce((u,d)=>Math.min(u,Number(d.ts)),1/0);for(let u of c)if(Number(u.ts)<l&&!s.has(String(u.ts)))s.set(String(u.ts),u)}catch(a){console.error(` (DM \u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${a instanceof Error?a.message:String(a)})`)}let r=[...s.values()].filter((a)=>Number(a.ts)>Number(t.ts)).filter((a)=>!n||Number(a.ts)>Number(n)).filter((a)=>t.isAnswerer(a.user)&&!a.bot_id).filter((a)=>typeof a.subtype!=="string"||pp.has(a.subtype)).filter((a)=>typeof a.text==="string"&&a.text.trim()!==""&&!Fo(a.text)).sort((a,c)=>Number(a.ts)-Number(c.ts)).filter((a)=>!o(a)),i=[];for(let a of r){let c="";try{c=await Wn(e,t.channelId,String(a.ts),t.cookie)}catch{}i.push({ts:String(a.ts),user:String(a.user),text:a.text.trim(),permalink:c})}return i}function Rt(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function Vt(e,t,n){if(t.json){console.log(JSON.stringify({status:n.status,answer:n.answer,how:n.how??null,who:n.who??null,...n.status==="void"?{reason:n.reason??"",supersededBy:n.supersededBy??null}:{},...n.explain?.length?{explain:n.explain}:{},notes:n.notes,cursor:n.cursor,permalink:t.shown}));return}if(n.notes.length){console.error(` \u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18 ${n.notes.length} \u4EF6 (\u56DE\u7B54\u3068\u306F\u5225):`);for(let o of n.notes){let s=o.user;try{s=await ve(e,o.user,t.cookie)}catch{}for(let[r,i]of o.text.split(`
407
- `).entries())console.error(` ${r?" ".repeat(P(s).length+2):`${P(s)}: `}${P(i)}`)}}if(n.status==="answered")console.error(` \u3053\u306E\u5F8C\u306E\u8FFD\u8A18\u3092\u62FE\u3046: ${_n(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function mp(e,t,n=!1){let{channelId:o,ts:s,reactable:r,threadOnly:i,audience:a,broadcast:c,cookie:l}=t,u=Le[t.lang],d={explainNow:[],explainPosted:!1},{askerUserId:f,askerBotId:h}=t,g=(N)=>typeof N==="string"&&!!N&&N!==f&&(c||a.has(N)),p=(N)=>{if(d.replyCount=Number(N.reply_count)||0,typeof N.text==="string")d.ownText=N.text},m=(N)=>{let q=typeof N.text==="string"?wt(N.text):void 0;if(q?.kind==="void")d.voided=q;return!!d.voided};function w(N){let q=G(N.reactions).map(T),H=[];for(let v=0;v<r.length;v++){let le=q.find((K)=>K.name===Te[v].name),ee=le?G(le.users).filter(g):[];if(ee.length)H.push({index:v,users:ee})}return H}async function b(N,q){if(n)return;let H=typeof N.text==="string"?N.text:"";if(!H)return;let v=Ao(H,q,t.lang);if(v===H)return;try{await Ct(e,o,s,v,l,!0)}catch(le){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${le instanceof Error?le.message:String(le)})`)}}let D=new Set;function S(N){for(let q of G(N.reactions).map(T)){if(typeof q.name!=="string"||!Ou.includes(q.name))continue;let H=q.name===Bn?"\u2795":"\u2753";for(let v of G(q.users).filter(g)){if(D.has(v))continue;if(D.add(v),!n)console.error(` (<@${v}> \u304C ${H} \u305D\u306E\u4ED6 \u3092\u62BC\u3057\u307E\u3057\u305F\u3002\u8FD4\u4FE1\u3092\u5F85\u3061\u307E\u3059)`)}}}let F=new Set,A=new Map,C=!1;async function x(N){if(N==="USLACKBOT")return!0;let q=A.get(N);if(q!==void 0)return q;try{let H=T(T(await Un(e,N,l)).user).is_bot;if(typeof H!=="boolean")return null;return A.set(N,H),H}catch{return null}}async function J(){let N=t.threadParentTs??s;try{let q,H=0;for(;;){let v=T(await Sd(e,o,N,{oldest:s,...q?{cursor:q}:{}},l));if(G(v.messages).map(T).some((le)=>Number(le.ts)>Number(s)&&Fo(le.text)))return"exists";if(q=String(T(v.response_metadata).next_cursor??"")||void 0,!q)break;if(++H>=_w)return"exists"}}catch(q){return console.error(` (\u30B9\u30EC\u30C3\u30C9\u3092\u8AAD\u3081\u306A\u3044\u305F\u3081\u3001\u8AAC\u660E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u6848\u5185\u306F\u307E\u3060\u51FA\u3057\u3066\u3044\u307E\u305B\u3093: ${q instanceof Error?q.message:String(q)})`),"unread"}try{await Ht(e,o,u.explainNote,N,!1,l,!0)}catch(q){return console.error(` (\u8AAC\u660E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u6848\u5185\u3092\u30B9\u30EC\u30C3\u30C9\u306B\u51FA\u305B\u307E\u305B\u3093\u3067\u3057\u305F: ${q instanceof Error?q.message:String(q)})`),"failed"}return"posted"}async function ne(N){let q=G(N.reactions).map(T).find((v)=>v.name===Dn),H=[];for(let v of q?G(q.users).filter(g):[]){if(await x(v)!==!1)continue;if(H.push(v),F.has(v))continue;if(F.add(v),!n)console.error(` (<@${v}> \u304C \u2139\uFE0F \u8AAC\u660E\u3057\u3066 \u3092\u62BC\u3057\u307E\u3057\u305F \u2014 \u56DE\u7B54\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u56DE\u7B54\u306F\u5F85\u3061\u7D9A\u3051\u307E\u3059)`)}if(d.explainNow=H,H.length&&!C&&!n){let v=await J();if(v!=="unread")C=!0,d.explainPosted=v==="posted"}}async function L(N){if(t.explain)await ne(N);if(r.length)S(N);let q=w(N);if(q.length<=1&&$o(typeof N.text==="string"?N.text:"").length)await b(N,[]);if(!q.length)return null;if(q.length===1){let{index:K,users:ae}=q[0];return{answer:r[K],how:u.howReaction(Te[K].glyph),who:ae[0],choice:K+1}}let H=q.map((K)=>Te[K.index].glyph).join(" / "),v=new Map;for(let K of q)for(let ae of K.users)v.set(ae,(v.get(ae)??0)+1);let le=[...v].filter(([,K])=>K>1).map(([K])=>K);if(!n)console.error(le.length?` (${H} \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)`:` (\u56DE\u7B54\u304C\u5206\u304B\u308C\u3066\u3044\u307E\u3059: ${H}\u3002\u3069\u3061\u3089\u304B\u4E00\u65B9\u306B\u305D\u308D\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let ee=le.sort();return await b(N,ee),null}let O=[...r,...t.overflow];function I(N,q=1/0){let H=[...N].sort((v,le)=>Number(v.ts)-Number(le.ts));for(let v of H){if(!(Number(v.ts)>Number(s)))continue;if(t.after&&!(Number(v.ts)>Number(t.after)))continue;if(!g(v.user))continue;if(typeof v.subtype==="string"&&!pp.has(v.subtype))continue;if(Number(v.ts)>=q)break;let le=typeof v.text==="string"?v.text.trim():"";if(!le||t.explain&&Fo(le))continue;if(!O.length)return{answer:le,how:u.howReply,who:v.user,ts:String(v.ts)};let ee=Ji(le,O);if(ee.kind==="chosen")return{answer:O[ee.index-1],how:u.howReplyN(ee.index),who:v.user,ts:String(v.ts),choice:ee.index};let K=ee.kind==="ambiguous",ae=d.unchosen;if(!ae||ae.ambiguous&&!K||ae.ambiguous===K&&Number(v.ts)<Number(ae.ts))d.unchosen={text:le,who:typeof v.user==="string"?v.user:"",ts:String(v.ts),ambiguous:K}}return null}async function W(){if(delete d.unchosen,t.threadParentTs){let v=T(await Ue(e,o,t.threadParentTs,100,l)),le=G(v.messages).map(T),ee=le.find((K)=>K.ts===s);if(ee){if(p(ee),m(ee))return null;let K=await L(ee);if(K)return K}return I(le)}let N=T(await tt(e,o,30,s,void 0,l,!0)),q=G(N.messages).map(T),H=q.find((v)=>v.ts===s);if(H){if(p(H),m(H))return null}if(H){let v=await L(H);if(v)return v}if(!i){let v=q.filter((ee)=>Number(ee.ts)>Number(s)&&(h&&ee.bot_id===h||f&&ee.user===f)).reduce((ee,K)=>Math.min(ee,Number(K.ts)),1/0),le=I(q,v);if(le)return le}if(H&&Number(H.reply_count)>0){let v=T(await Ue(e,o,s,30,l)),le=I(G(v.messages).map(T));if(le)return le}return null}return{poll:W,state:d,isAnswerer:g,candidates:O}}async function yp(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,cookie:a,timeout:c,shown:l}=t,{askerUserId:u,askerBotId:d}=t,{poll:f,state:h,isAnswerer:g,candidates:p}=mp(e,t),m="";async function w(A){for(let x=0;x<r.length;x++)try{await At(e,n,o,Te[x].name,a)}catch{}let C="";if(A.who)try{C=await ve(e,A.who,a)}catch{C=A.who}if(C)console.error(` \u56DE\u7B54\u8005: ${P(C)}`);try{let x=h.ownText?Bu(h.ownText,A.choice):void 0;await Ct(e,n,o,Nu(s,A,C,t.lang,x),a,!0);try{await $t(e,n,o,Wi,a),await At(e,n,o,t.seedMarker,a)}catch{}try{if(t.explain)await At(e,n,o,Dn,a)}catch{}}catch(x){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${x instanceof Error?x.message:String(x)})`)}}let b=Date.now()+c*1000,D=0,S=Aw,F;for(;;){let A=null;try{A=await f(),D=0}catch(x){if(D++,D>=Gf)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${D} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${x instanceof Error?x.message:String(x)}`),process.exit(ce);console.error(` (Slack \u30A8\u30E9\u30FC ${D}/${Gf}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${x instanceof Error?x.message:String(x)})`)}F=h.unchosen;let C=h.voided;if(C){if(wp(C,l),t.json)await Vt(e,t,{status:"void",answer:null,reason:C.reason,...C.supersededBy?{supersededBy:C.supersededBy}:{},notes:[],cursor:Rt(o,t.after)});process.exit(fp)}if(A){let x=await gp(e,{channelId:n,ts:o,threadOnly:i,replyCount:h.replyCount,isAnswerer:g,askerUserId:u,askerBotId:d,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...a?{cookie:a}:{}},t.after,(ne)=>ne.ts===A.ts);await w(A);let J={status:"answered",answer:A.answer,how:A.how,notes:x,cursor:Rt(o,t.after,A.ts,...x.map((ne)=>ne.ts))};if(na(n,o,A.answer,J.cursor),A.who)J.who=A.who;await Vt(e,t,J),process.exit(0)}if(h.explainPosted&&t.explainExit){if(console.error(` \u8AAC\u660E\u3092\u6C42\u3081\u3089\u308C\u3066\u3044\u307E\u3059 (\u8CEA\u554F\u306F\u307E\u3060\u958B\u3044\u3066\u3044\u307E\u3059)\u3002\u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${_n(l,t.asBot,t.after)}`),t.json)await Vt(e,t,{status:"explain",answer:null,notes:[],cursor:Rt(o,t.after),explain:h.explainNow});process.exit(Ew)}if(F&&!F.ambiguous){let x=F.who;try{if(x)x=await ve(e,x,a)}catch{}if(console.error(` (${P(x)} \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: ${p.map((J,ne)=>`${ne+1}. ${P(Oe(J))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${_n(l,t.asBot,F.ts)}`),md(n,o,F.text,Rt(o,t.after,F.ts)),t.json)await Vt(e,t,{status:"freetext",answer:F.text,who:F.who,notes:[],cursor:Rt(o,t.after,F.ts),explain:h.explainNow});else console.log(F.text);process.exit(Sw)}if(F&&F.ts!==m){m=F.ts;let x=F.who;try{if(x)x=await ve(e,x,a)}catch{}console.error(` (${P(x)} \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${P(F.text)}\u300D`)}if(Date.now()>=b)break;await Tw(Math.min(S,Math.max(0,b-Date.now()))),S=Math.min(S*$w,Fw)}if(F){if(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${P(F.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${p.map((A,C)=>`${C+1}. ${P(Oe(A))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${_n(l,t.asBot,t.after)}`),t.json)await Vt(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Rt(o,t.after),explain:h.explainNow});process.exit(xw)}if(c===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${l}`);else console.error(`Error: ${c}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(` ${l}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${_n(l,t.asBot,t.after)}`);if(t.json)await Vt(e,t,{status:"timeout",answer:null,notes:[],cursor:Rt(o,t.after),explain:h.explainNow});process.exit(kw)}function _n(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function Iw(e,t){let{ref:n,threadTs:o}=Gn(t.target,!1),s=t.cookie,r=It(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ft(e,t.userId,s);else i=await ke(e,n,s);let a=(await r())?.userId??"",c=await cr(e,i,s);if(!t.asBot&&!!a&&c===a)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
408
- `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=Ls(Me(t.question)),u=Ls(Me(t.body??"")),d=new Set([...l.kinds,...u.kinds]);for(let z of`${l.text}
409
- ${u.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(z[1]);let f=t.mentionToken??e,h=await Yt(f,l.text,i,t.mentionCookie),g=u.text?await Yt(f,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},p=h.text,m=g.text,w=[...h.resolved,...g.resolved],b=[...h.unresolved,...g.unresolved];hp(b);let D=d.size>0,S=new Set(w.map((z)=>z.userId).filter((z)=>z!==a)),F=new Map(w.map((z)=>[z.userId,z.display]));for(let z of`${p}
410
- ${m}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let M=z[1];if(M===a||S.has(M))continue;S.add(M),F.set(M,await ve(f,M,t.mentionCookie))}let A;if(D)A=`anyone in ${n} (${[...d].map((z)=>`@${z}`).join(", ")})`;else{if(!S.size&&c&&c!==a)S.add(c),F.set(c,await ve(e,c,s));if(!S.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+` Tag the person who should answer: slack ask '${t.target}' '@alice ${t.question}' ...
407
+ `)}`),process.exit(ce)}function Ns(e){let t=new Set;return{text:e.replace(Vw,(o,s)=>{let r=s.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function fr(e,t,n){if(!t.startsWith("D"))return;try{let o=T(await xn(e,t,n)),s=T(o.channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function _p(e,t,n,o){let s=new Map;if(t.threadParentTs||t.replyCount!==0)try{let a=T(await Me(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let c of G(a.messages).map(T))s.set(String(c.ts),c)}catch(a){console.error(` (\u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${a instanceof Error?a.message:String(a)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let a=T(await tt(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),c=G(a.messages).map(T),l=c.filter((u)=>Number(u.ts)>Number(t.ts)&&(t.askerBotId&&u.bot_id===t.askerBotId||t.askerUserId&&u.user===t.askerUserId)).reduce((u,d)=>Math.min(u,Number(d.ts)),1/0);for(let u of c)if(Number(u.ts)<l&&!s.has(String(u.ts)))s.set(String(u.ts),u)}catch(a){console.error(` (DM \u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${a instanceof Error?a.message:String(a)})`)}let r=[...s.values()].filter((a)=>Number(a.ts)>Number(t.ts)).filter((a)=>!n||Number(a.ts)>Number(n)).filter((a)=>t.isAnswerer(a.user)&&!a.bot_id).filter((a)=>typeof a.subtype!=="string"||Sp.has(a.subtype)).filter((a)=>typeof a.text==="string"&&a.text.trim()!==""&&!Ro(a.text)).sort((a,c)=>Number(a.ts)-Number(c.ts)).filter((a)=>!o(a)),i=[];for(let a of r){let c="";try{c=await Un(e,t.channelId,String(a.ts),t.cookie)}catch{}i.push({ts:String(a.ts),user:String(a.user),text:a.text.trim(),permalink:c})}return i}function Ot(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function Zt(e,t,n){if(t.json){console.log(JSON.stringify({status:n.status,answer:n.answer,how:n.how??null,who:n.who??null,...n.status==="void"?{reason:n.reason??"",supersededBy:n.supersededBy??null}:{},...n.explain?.length?{explain:n.explain}:{},notes:n.notes,cursor:n.cursor,permalink:t.shown}));return}if(n.notes.length){console.error(` \u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18 ${n.notes.length} \u4EF6 (\u56DE\u7B54\u3068\u306F\u5225):`);for(let o of n.notes){let s=o.user;try{s=await Ie(e,o.user,t.cookie)}catch{}for(let[r,i]of o.text.split(`
408
+ `).entries())console.error(` ${r?" ".repeat(O(s).length+2):`${O(s)}: `}${O(i)}`)}}if(n.status==="answered")console.error(` \u3053\u306E\u5F8C\u306E\u8FFD\u8A18\u3092\u62FE\u3046: ${$n(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function $p(e,t,n=!1){let{channelId:o,ts:s,reactable:r,threadOnly:i,audience:a,broadcast:c,cookie:l}=t,u=Le[t.lang],d={explainNow:[],explainPosted:!1},{askerUserId:f,askerBotId:h}=t,g=(N)=>typeof N==="string"&&!!N&&N!==f&&(c||a.has(N)),p=(N)=>{if(d.replyCount=Number(N.reply_count)||0,typeof N.text==="string")d.ownText=N.text},m=(N)=>{let q=typeof N.text==="string"?bt(N.text):void 0;if(q?.kind==="void")d.voided=q;return!!d.voided};function w(N){let q=G(N.reactions).map(T),H=[];for(let v=0;v<r.length;v++){let le=q.find((K)=>K.name===Te[v].name),te=le?G(le.users).filter(g):[];if(te.length)H.push({index:v,users:te})}return H}async function b(N,q){if(n)return;let H=typeof N.text==="string"?N.text:"";if(!H)return;let v=To(H,q,t.lang);if(v===H)return;try{await At(e,o,s,v,l,!0)}catch(le){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${le instanceof Error?le.message:String(le)})`)}}let D=new Set;function S(N){for(let q of G(N.reactions).map(T)){if(typeof q.name!=="string"||!qu.includes(q.name))continue;let H=q.name===jn?"\u2795":"\u2753";for(let v of G(q.users).filter(g)){if(D.has(v))continue;if(D.add(v),!n)console.error(` (<@${v}> \u304C ${H} \u305D\u306E\u4ED6 \u3092\u62BC\u3057\u307E\u3057\u305F\u3002\u8FD4\u4FE1\u3092\u5F85\u3061\u307E\u3059)`)}}}let A=new Set,F=new Map,E=!1;async function x(N){if(N==="USLACKBOT")return!0;let q=F.get(N);if(q!==void 0)return q;try{let H=T(T(await Jn(e,N,l)).user).is_bot;if(typeof H!=="boolean")return null;return F.set(N,H),H}catch{return null}}async function W(){let N=t.threadParentTs??s;try{let q,H=0;for(;;){let v=T(await Pd(e,o,N,{oldest:s,...q?{cursor:q}:{}},l));if(G(v.messages).map(T).some((le)=>Number(le.ts)>Number(s)&&Ro(le.text)))return"exists";if(q=String(T(v.response_metadata).next_cursor??"")||void 0,!q)break;if(++H>=qw)return"exists"}}catch(q){return console.error(` (\u30B9\u30EC\u30C3\u30C9\u3092\u8AAD\u3081\u306A\u3044\u305F\u3081\u3001\u8AAC\u660E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u6848\u5185\u306F\u307E\u3060\u51FA\u3057\u3066\u3044\u307E\u305B\u3093: ${q instanceof Error?q.message:String(q)})`),"unread"}try{await zt(e,o,u.explainNote,N,!1,l,!0)}catch(q){return console.error(` (\u8AAC\u660E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u6848\u5185\u3092\u30B9\u30EC\u30C3\u30C9\u306B\u51FA\u305B\u307E\u305B\u3093\u3067\u3057\u305F: ${q instanceof Error?q.message:String(q)})`),"failed"}return"posted"}async function Q(N){let q=G(N.reactions).map(T).find((v)=>v.name===Dn),H=[];for(let v of q?G(q.users).filter(g):[]){if(await x(v)!==!1)continue;if(H.push(v),A.has(v))continue;if(A.add(v),!n)console.error(` (<@${v}> \u304C \u2139\uFE0F \u8AAC\u660E\u3057\u3066 \u3092\u62BC\u3057\u307E\u3057\u305F \u2014 \u56DE\u7B54\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u56DE\u7B54\u306F\u5F85\u3061\u7D9A\u3051\u307E\u3059)`)}if(d.explainNow=H,H.length&&!E&&!n){let v=await W();if(v!=="unread")E=!0,d.explainPosted=v==="posted"}}async function M(N){if(t.explain)await Q(N);if(r.length)S(N);let q=w(N);if(q.length<=1&&Fo(typeof N.text==="string"?N.text:"").length)await b(N,[]);if(!q.length)return null;if(q.length===1){let{index:K,users:re}=q[0];return{answer:r[K],how:u.howReaction(Te[K].glyph),who:re[0],choice:K+1}}let H=q.map((K)=>Te[K.index].glyph).join(" / "),v=new Map;for(let K of q)for(let re of K.users)v.set(re,(v.get(re)??0)+1);let le=[...v].filter(([,K])=>K>1).map(([K])=>K);if(!n)console.error(le.length?` (${H} \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)`:` (\u56DE\u7B54\u304C\u5206\u304B\u308C\u3066\u3044\u307E\u3059: ${H}\u3002\u3069\u3061\u3089\u304B\u4E00\u65B9\u306B\u305D\u308D\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let te=le.sort();return await b(N,te),null}let P=[...r,...t.overflow];function I(N,q=1/0){let H=[...N].sort((v,le)=>Number(v.ts)-Number(le.ts));for(let v of H){if(!(Number(v.ts)>Number(s)))continue;if(t.after&&!(Number(v.ts)>Number(t.after)))continue;if(!g(v.user))continue;if(typeof v.subtype==="string"&&!Sp.has(v.subtype))continue;if(Number(v.ts)>=q)break;let le=typeof v.text==="string"?v.text.trim():"";if(!le||t.explain&&Ro(le))continue;if(!P.length)return{answer:le,how:u.howReply,who:v.user,ts:String(v.ts)};let te=Xi(le,P);if(te.kind==="chosen")return{answer:P[te.index-1],how:u.howReplyN(te.index),who:v.user,ts:String(v.ts),choice:te.index};let K=te.kind==="ambiguous",re=d.unchosen;if(!re||re.ambiguous&&!K||re.ambiguous===K&&Number(v.ts)<Number(re.ts))d.unchosen={text:le,who:typeof v.user==="string"?v.user:"",ts:String(v.ts),ambiguous:K}}return null}async function U(){if(delete d.unchosen,t.threadParentTs){let v=T(await Me(e,o,t.threadParentTs,100,l)),le=G(v.messages).map(T),te=le.find((K)=>K.ts===s);if(te){if(p(te),m(te))return null;let K=await M(te);if(K)return K}return I(le)}let N=T(await tt(e,o,30,s,void 0,l,!0)),q=G(N.messages).map(T),H=q.find((v)=>v.ts===s);if(H){if(p(H),m(H))return null}if(H){let v=await M(H);if(v)return v}if(!i){let v=q.filter((te)=>Number(te.ts)>Number(s)&&(h&&te.bot_id===h||f&&te.user===f)).reduce((te,K)=>Math.min(te,Number(K.ts)),1/0),le=I(q,v);if(le)return le}if(H&&Number(H.reply_count)>0){let v=T(await Me(e,o,s,30,l)),le=I(G(v.messages).map(T));if(le)return le}return null}return{poll:U,state:d,isAnswerer:g,candidates:P}}async function Cp(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,cookie:a,timeout:c,shown:l}=t,{askerUserId:u,askerBotId:d}=t,{poll:f,state:h,isAnswerer:g,candidates:p}=$p(e,t),m="";async function w(F){for(let x=0;x<r.length;x++)try{await Tt(e,n,o,Te[x].name,a)}catch{}let E="";if(F.who)try{E=await Ie(e,F.who,a)}catch{E=F.who}if(E)console.error(` \u56DE\u7B54\u8005: ${O(E)}`);try{let x=h.ownText?Yu(h.ownText,F.choice):void 0;await At(e,n,o,Gu(s,F,E,t.lang,x),a,!0);try{await Ft(e,n,o,qi,a),await Tt(e,n,o,t.seedMarker,a)}catch{}try{if(t.explain)await Tt(e,n,o,Dn,a)}catch{}}catch(x){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${x instanceof Error?x.message:String(x)})`)}}let b=Date.now()+c*1000,D=0,S=Xw,A;for(;;){let F=null;try{F=await f(),D=0}catch(x){if(D++,D>=op)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${D} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${x instanceof Error?x.message:String(x)}`),process.exit(ce);console.error(` (Slack \u30A8\u30E9\u30FC ${D}/${op}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${x instanceof Error?x.message:String(x)})`)}A=h.unchosen;let E=h.voided;if(E){if(Ap(E,l),t.json)await Zt(e,t,{status:"void",answer:null,reason:E.reason,...E.supersededBy?{supersededBy:E.supersededBy}:{},notes:[],cursor:Ot(o,t.after)});process.exit(xp)}if(F){let x=await _p(e,{channelId:n,ts:o,threadOnly:i,replyCount:h.replyCount,isAnswerer:g,askerUserId:u,askerBotId:d,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...a?{cookie:a}:{}},t.after,(Q)=>Q.ts===F.ts);await w(F);let W={status:"answered",answer:F.answer,how:F.how,notes:x,cursor:Ot(o,t.after,F.ts,...x.map((Q)=>Q.ts))};if(ia(n,o,F.answer,W.cursor),F.who)W.who=F.who;await Zt(e,t,W),process.exit(0)}if(h.explainPosted&&t.explainExit){if(console.error(` \u8AAC\u660E\u3092\u6C42\u3081\u3089\u308C\u3066\u3044\u307E\u3059 (\u8CEA\u554F\u306F\u307E\u3060\u958B\u3044\u3066\u3044\u307E\u3059)\u3002\u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${$n(l,t.asBot,t.after)}`),t.json)await Zt(e,t,{status:"explain",answer:null,notes:[],cursor:Ot(o,t.after),explain:h.explainNow});process.exit(Kw)}if(A&&!A.ambiguous){let x=A.who;try{if(x)x=await Ie(e,x,a)}catch{}if(console.error(` (${O(x)} \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: ${p.map((W,Q)=>`${Q+1}. ${O(ve(W))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${$n(l,t.asBot,A.ts)}`),Cd(n,o,A.text,Ot(o,t.after,A.ts)),t.json)await Zt(e,t,{status:"freetext",answer:A.text,who:A.who,notes:[],cursor:Ot(o,t.after,A.ts),explain:h.explainNow});else console.log(A.text);process.exit(Jw)}if(A&&A.ts!==m){m=A.ts;let x=A.who;try{if(x)x=await Ie(e,x,a)}catch{}console.error(` (${O(x)} \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${O(A.text)}\u300D`)}if(Date.now()>=b)break;await Yw(Math.min(S,Math.max(0,b-Date.now()))),S=Math.min(S*zw,Gw)}if(A){if(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${O(A.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${p.map((F,E)=>`${E+1}. ${O(ve(F))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${$n(l,t.asBot,t.after)}`),t.json)await Zt(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Ot(o,t.after),explain:h.explainNow});process.exit(Uw)}if(c===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${l}`);else console.error(`Error: ${c}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(` ${l}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${$n(l,t.asBot,t.after)}`);if(t.json)await Zt(e,t,{status:"timeout",answer:null,notes:[],cursor:Ot(o,t.after),explain:h.explainNow});process.exit(Ww)}function $n(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function Zw(e,t){let{ref:n,threadTs:o}=Vn(t.target,!1),s=t.cookie,r=vt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Rt(e,t.userId,s);else i=await ke(e,n,s);let a=(await r())?.userId??"",c=await fr(e,i,s);if(!t.asBot&&!!a&&c===a)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
409
+ `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=Ns(Ne(t.question)),u=Ns(Ne(t.body??"")),d=new Set([...l.kinds,...u.kinds]);for(let z of`${l.text}
410
+ ${u.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(z[1]);let f=t.mentionToken??e,h=await Vt(f,l.text,i,t.mentionCookie),g=u.text?await Vt(f,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},p=h.text,m=g.text,w=[...h.resolved,...g.resolved],b=[...h.unresolved,...g.unresolved];Ep(b);let D=d.size>0,S=new Set(w.map((z)=>z.userId).filter((z)=>z!==a)),A=new Map(w.map((z)=>[z.userId,z.display]));for(let z of`${p}
411
+ ${m}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let L=z[1];if(L===a||S.has(L))continue;S.add(L),A.set(L,await Ie(f,L,t.mentionCookie))}let F;if(D)F=`anyone in ${n} (${[...d].map((z)=>`@${z}`).join(", ")})`;else{if(!S.size&&c&&c!==a)S.add(c),A.set(c,await Ie(e,c,s));if(!S.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+` Tag the person who should answer: slack ask '${t.target}' '@alice ${t.question}' ...
411
412
  Or open it to the whole channel: slack ask '${t.target}' '@here ${t.question}' ...
412
- (In a 1:1 DM the other person counts automatically.)`),process.exit(ce);A=[...S].map((z)=>`@${P(F.get(z)??z)} (${z})`).join(", ")}let C=t.choices.map(Me),x=C.slice(0,Et),J=C.slice(Et),ne=!i.startsWith("D")||!!o,L=D?[]:await Promise.all([...S].map((z)=>Qd(f,z,t.mentionCookie))),O=Bi({flag:t.lang,readerLocales:L,content:[p,m,...x,...J]});if(!O)console.error(`Error: unsupported language "${P(t.lang??process.env.SLACK_TERM_LANG??"")}" \u2014 use one of: ${yt.join(", ")}`),process.exit(ce);let I=O.lang,W=t.explain??Cw(),N=Ki(p,m,x,J,ne,I,W);Je(N,t.allowUrlAdjacent);let q="",H="?";try{let z=await tt(e,i,1,void 0,void 0,s),M=G(z.messages).map(T).filter((pe)=>pe.subtype===void 0||pe.subtype===null)[0];q=typeof M?.text==="string"?M.text:"",H=typeof M?.user==="string"?await ve(e,M.user,s):typeof M?.username==="string"?M.username:"?"}catch{}let v=await r(),le=await ir(e,i,s),ee=xe(i,o??"",q,N,v?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==ee){let z=await Qt(e,i,n,s),M=x.length?["--- Choices (seeded as reactions) ------------",...x.map((pe,we)=>` ${Te[we].glyph} ${Oe(pe)}`),...J.map((pe,we)=>` (${we+11}) ${Oe(pe)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];Ee(t.code,ee,["--- Last message in channel ------------------",` ${H}: ${Is(q.split(`
413
- `)[0]??"").slice(0,100)}`,...M,"--- Asking -----------------------------------",_e(v,{asBot:t.asBot}),` \u2192 ${z}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${p}`,` Answerable by: ${A}`,` Via: ${ne?"reactions or thread replies":"reactions or replies in this DM"}`,...W?[" Explain: \u2139\uFE0F pill offered \u2014 pressing it asks you to explain; it is never an answer"]:[],...t.voidAfter?[` Then \u7121\u52B9\u5316: ${P(t.voidAfter.link)} (reason: ${P(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${I} (${{flag:"--lang",env:"SLACK_TERM_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[O.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],le)}let K=Cn("ask"),ae=await Ht(e,i,N,o,!1,s,!0,K.metadata),j=x.length?Bn:Kt;await vo([...x.map((z,M)=>Te[M].name),j,...W?[Dn]:[]],(z)=>$t(e,i,ae,z,s),(z,M)=>{let pe=M instanceof Error?M.message:String(M);if(z===j)console.error(` (marker ${z} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${pe})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${z} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${pe})`)});let de="";try{de=await Wn(e,i,ae,s)}catch{}let se=de||`${i}:${ae}`;if(console.error(`\u2713 Asked: ${se}`),K.record({team:v?.team,channel:i,target:t.target,ts:ae,threadTs:o,permalink:de,text:N,asBot:t.asBot}),t.voidAfter){if(!await Dp(e,t.voidAfter,t.voidAfter.reason,se,s))console.error(` \u26A0 \u65B0\u3057\u3044\u8CEA\u554F\u306F\u51FA\u307E\u3057\u305F\u304C\u3001\u53E4\u3044\u8CEA\u554F\u3092\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F \u2014 \u624B\u3067: slack ask --void='${P(t.voidAfter.link)}' --superseded-by='${se}'`)}if(!t.wait){console.log(_n(se,!!t.asBot));return}let U=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${U}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let oe={channelId:i,ts:ae,question:p,reactable:x,overflow:J,threadOnly:ne,seedMarker:j,lang:I,audience:S,broadcast:D,askerUserId:v?.userId??"",askerBotId:v?.botId??"",timeout:U,shown:se,asBot:!!t.asBot,json:!!t.json,explain:W,explainExit:!!t.explainExit};if(o)oe.threadParentTs=o;if(s)oe.cookie=s;await yp(e,oe)}function wp(e,t){if(console.error(`\u3053\u306E\u8CEA\u554F\u306F\u7121\u52B9\u3067\u3059 \u2014 \u56DE\u7B54\u3055\u308C\u308B\u3053\u3068\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u5F85\u3064\u306E\u3092\u3084\u3081\u3066\u304F\u3060\u3055\u3044: ${P(t)}`),e.reason)console.error(` ${P(e.reason)}`);if(e.supersededBy)console.error(` \u65B0\u3057\u3044\u8CEA\u554F: ${P(e.supersededBy)}`)}async function Ta(e,t,n){let o=zt(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)return null;s=a[1],r=a[2]}return lr(e,{channelId:s,ts:r,threadTs:i},n)}async function lr(e,t,n){let{channelId:o,ts:s}=t,r=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,i;if(r){let c=T(await Ue(e,o,r,100,n));i=G(c.messages).map(T).find((l)=>l.ts===s)}else{let c=T(await tt(e,o,1,s,void 0,n,!0));i=G(c.messages).map(T).find((l)=>l.ts===s)}let a={channelId:o,ts:s};if(r)a.threadTs=r;if(i)a.msg=i;return a}async function bp(e,t,n,o,s){let r=P(t),i=await Ta(e,t,s);if(!i)return console.error(`\u2717 ${r}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),null;if(!i.msg)return console.error(`\u2717 ${r}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),null;let a=i.msg;if(!(!!n?.userId&&a.user===n.userId||!!n?.botId&&a.bot_id===n.botId))return console.error(`\u2717 ${r}: \u81EA\u5206\uFF08${ar(n,o)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u3042\u308A\u307E\u305B\u3093`+`${o?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),null;let l=typeof a.text==="string"?a.text:"",u=wt(l);if(u.kind==="void")return"void";if(u.kind==="resolved")return console.error(`\u2717 ${r}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u3067\u3059\uFF08\u56DE\u7B54: ${P(u.answer.split(`
414
- `)[0]??"")}\uFF09\u2014 \u5909\u66F4\u3067\u304D\u307E\u305B\u3093`),null;if(u.kind!=="open")return console.error(`\u2717 ${r}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${bs(l)}`),null;let d={link:t,channelId:i.channelId,ts:i.ts,parsed:u,seedMarker:Ds(l)??Kt,msg:a};if(i.threadTs)d.threadTs=i.threadTs;return d}async function Pw(e,t,n,o){let s=(i)=>typeof i==="string"&&i!==n?.userId;if(G(t.msg.reactions).map(T).some((i)=>Te.some((a)=>a.name===i.name)&&G(i.users).some(s)))return!0;if(Number(t.msg.reply_count)>0){let i=T(await Ue(e,t.channelId,t.ts,100,o));if(G(i.messages).map(T).some((a)=>Number(a.ts)>Number(t.ts)&&s(a.user)&&!a.bot_id))return!0}if(t.channelId.startsWith("D")){let i=T(await tt(e,t.channelId,30,t.ts,void 0,o,!0));if(G(i.messages).map(T).some((a)=>Number(a.ts)>Number(t.ts)&&s(a.user)&&!a.bot_id))return!0}return!1}async function Ow(e,t){let n=await Be(e,t.cookie),o=await bp(e,t.link,n,t.asBot,t.cookie);if(o==="void")console.error(`\u2717 ${P(t.link)}: \u7121\u52B9\u5316\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7DE8\u96C6\u3067\u304D\u307E\u305B\u3093`),process.exit(ce);if(!o)process.exit(ce);let s=o.parsed,r=async(A)=>{let C=Ls(Me(A)),x=await Yt(t.mentionToken,C.text,o.channelId,t.mentionCookie);return hp(x.unresolved),x.text},i=t.question!==void 0?await r(t.question):s.question,a=t.body!==void 0?await r(t.body):s.body,c=[...s.reactable,...s.overflow],l=t.choices?t.choices.map(Me):c,u=JSON.stringify(l.map(Oe))!==JSON.stringify(c.map(Oe));if(u&&await Pw(e,o,n,t.cookie))console.error(`\u2717 \u3053\u306E\u8CEA\u554F\u306B\u306F\u3082\u3046\u56DE\u7B54\uFF08\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u304B\u8FD4\u4FE1\uFF09\u304C\u3042\u308A\u307E\u3059 \u2014 \u9078\u629E\u80A2\u3092\u5909\u3048\u308B\u3068\u3001\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306E\u610F\u5473\u304C\u5909\u308F\u3063\u3066\u3057\u307E\u3044\u307E\u3059\u3002
413
+ (In a 1:1 DM the other person counts automatically.)`),process.exit(ce);F=[...S].map((z)=>`@${O(A.get(z)??z)} (${z})`).join(", ")}let E=t.choices.map(Ne),x=E.slice(0,_t),W=E.slice(_t),Q=!i.startsWith("D")||!!o,M=D?[]:await Promise.all([...S].map((z)=>ff(f,z,t.mentionCookie))),P=Ji({flag:t.lang,readerLocales:M,content:[p,m,...x,...W]});if(!P)console.error(`Error: unsupported language "${O(t.lang??process.env.SLACK_TERM_LANG??"")}" \u2014 use one of: ${wt.join(", ")}`),process.exit(ce);let I=P.lang,U=t.explain??Hw(),N=zi(p,m,x,W,Q,I,U);Ke(N,t.allowUrlAdjacent);let q="",H="?";try{let z=await tt(e,i,1,void 0,void 0,s),L=G(z.messages).map(T).filter((pe)=>pe.subtype===void 0||pe.subtype===null)[0];q=typeof L?.text==="string"?L.text:"",H=typeof L?.user==="string"?await Ie(e,L.user,s):typeof L?.username==="string"?L.username:"?"}catch{}let v=await r(),le=await ur(e,i,s),te=xe(i,o??"",q,N,v?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==te){let z=await en(e,i,n,s),L=x.length?["--- Choices (seeded as reactions) ------------",...x.map((pe,we)=>` ${Te[we].glyph} ${ve(pe)}`),...W.map((pe,we)=>` (${we+11}) ${ve(pe)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];Se(t.code,te,["--- Last message in channel ------------------",` ${H}: ${Xn(q.split(`
414
+ `)[0]??"").slice(0,100)}`,...L,"--- Asking -----------------------------------",_e(v,{asBot:t.asBot}),` \u2192 ${z}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${p}`,` Answerable by: ${F}`,` Via: ${Q?"reactions or thread replies":"reactions or replies in this DM"}`,...U?[" Explain: \u2139\uFE0F pill offered \u2014 pressing it asks you to explain; it is never an answer"]:[],...t.voidAfter?[` Then \u7121\u52B9\u5316: ${O(t.voidAfter.link)} (reason: ${O(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${I} (${{flag:"--lang",env:"SLACK_TERM_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[P.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],le)}let K=Cn("ask"),re=await zt(e,i,N,o,!1,s,!0,K.metadata),j=x.length?jn:Ht;await Mo([...x.map((z,L)=>Te[L].name),j,...U?[Dn]:[]],(z)=>Ft(e,i,re,z,s),(z,L)=>{let pe=L instanceof Error?L.message:String(L);if(z===j)console.error(` (marker ${z} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${pe})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${z} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${pe})`)});let de="";try{de=await Un(e,i,re,s)}catch{}let se=de||`${i}:${re}`;if(console.error(`\u2713 Asked: ${se}`),K.record({team:v?.team,channel:i,target:t.target,ts:re,threadTs:o,permalink:de,text:N,asBot:t.asBot}),t.voidAfter){if(!await Tp(e,t.voidAfter,t.voidAfter.reason,se,s))console.error(` \u26A0 \u65B0\u3057\u3044\u8CEA\u554F\u306F\u51FA\u307E\u3057\u305F\u304C\u3001\u53E4\u3044\u8CEA\u554F\u3092\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F \u2014 \u624B\u3067: slack ask --void='${O(t.voidAfter.link)}' --superseded-by='${se}'`)}if(!t.wait){console.log($n(se,!!t.asBot));return}let J=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${J}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let oe={channelId:i,ts:re,question:p,reactable:x,overflow:W,threadOnly:Q,seedMarker:j,lang:I,audience:S,broadcast:D,askerUserId:v?.userId??"",askerBotId:v?.botId??"",timeout:J,shown:se,asBot:!!t.asBot,json:!!t.json,explain:U,explainExit:!!t.explainExit};if(o)oe.threadParentTs=o;if(s)oe.cookie=s;await Cp(e,oe)}function Ap(e,t){if(console.error(`\u3053\u306E\u8CEA\u554F\u306F\u7121\u52B9\u3067\u3059 \u2014 \u56DE\u7B54\u3055\u308C\u308B\u3053\u3068\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u5F85\u3064\u306E\u3092\u3084\u3081\u3066\u304F\u3060\u3055\u3044: ${O(t)}`),e.reason)console.error(` ${O(e.reason)}`);if(e.supersededBy)console.error(` \u65B0\u3057\u3044\u8CEA\u554F: ${O(e.supersededBy)}`)}async function ja(e,t,n){let o=Xt(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)return null;s=a[1],r=a[2]}return pr(e,{channelId:s,ts:r,threadTs:i},n)}async function pr(e,t,n){let{channelId:o,ts:s}=t,r=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,i;if(r){let c=T(await Me(e,o,r,100,n));i=G(c.messages).map(T).find((l)=>l.ts===s)}else{let c=T(await tt(e,o,1,s,void 0,n,!0));i=G(c.messages).map(T).find((l)=>l.ts===s)}let a={channelId:o,ts:s};if(r)a.threadTs=r;if(i)a.msg=i;return a}async function Fp(e,t,n,o,s){let r=O(t),i=await ja(e,t,s);if(!i)return console.error(`\u2717 ${r}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),null;if(!i.msg)return console.error(`\u2717 ${r}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),null;let a=i.msg;if(!(!!n?.userId&&a.user===n.userId||!!n?.botId&&a.bot_id===n.botId))return console.error(`\u2717 ${r}: \u81EA\u5206\uFF08${dr(n,o)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u3042\u308A\u307E\u305B\u3093`+`${o?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),null;let l=typeof a.text==="string"?a.text:"",u=bt(l);if(u.kind==="void")return"void";if(u.kind==="resolved")return console.error(`\u2717 ${r}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u3067\u3059\uFF08\u56DE\u7B54: ${O(u.answer.split(`
415
+ `)[0]??"")}\uFF09\u2014 \u5909\u66F4\u3067\u304D\u307E\u305B\u3093`),null;if(u.kind!=="open")return console.error(`\u2717 ${r}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${ks(l)}`),null;let d={link:t,channelId:i.channelId,ts:i.ts,parsed:u,seedMarker:xs(l)??Ht,msg:a};if(i.threadTs)d.threadTs=i.threadTs;return d}async function Qw(e,t,n,o){let s=(i)=>typeof i==="string"&&i!==n?.userId;if(G(t.msg.reactions).map(T).some((i)=>Te.some((a)=>a.name===i.name)&&G(i.users).some(s)))return!0;if(Number(t.msg.reply_count)>0){let i=T(await Me(e,t.channelId,t.ts,100,o));if(G(i.messages).map(T).some((a)=>Number(a.ts)>Number(t.ts)&&s(a.user)&&!a.bot_id))return!0}if(t.channelId.startsWith("D")){let i=T(await tt(e,t.channelId,30,t.ts,void 0,o,!0));if(G(i.messages).map(T).some((a)=>Number(a.ts)>Number(t.ts)&&s(a.user)&&!a.bot_id))return!0}return!1}async function eb(e,t){let n=await je(e,t.cookie),o=await Fp(e,t.link,n,t.asBot,t.cookie);if(o==="void")console.error(`\u2717 ${O(t.link)}: \u7121\u52B9\u5316\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7DE8\u96C6\u3067\u304D\u307E\u305B\u3093`),process.exit(ce);if(!o)process.exit(ce);let s=o.parsed,r=async(F)=>{let E=Ns(Ne(F)),x=await Vt(t.mentionToken,E.text,o.channelId,t.mentionCookie);return Ep(x.unresolved),x.text},i=t.question!==void 0?await r(t.question):s.question,a=t.body!==void 0?await r(t.body):s.body,c=[...s.reactable,...s.overflow],l=t.choices?t.choices.map(Ne):c,u=JSON.stringify(l.map(ve))!==JSON.stringify(c.map(ve));if(u&&await Qw(e,o,n,t.cookie))console.error(`\u2717 \u3053\u306E\u8CEA\u554F\u306B\u306F\u3082\u3046\u56DE\u7B54\uFF08\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u304B\u8FD4\u4FE1\uFF09\u304C\u3042\u308A\u307E\u3059 \u2014 \u9078\u629E\u80A2\u3092\u5909\u3048\u308B\u3068\u3001\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306E\u610F\u5473\u304C\u5909\u308F\u3063\u3066\u3057\u307E\u3044\u307E\u3059\u3002
415
416
  `+` \u8CEA\u554F\u6587\u3068\u672C\u6587\u306F\u5909\u3048\u3089\u308C\u307E\u3059\u3002\u9078\u629E\u80A2\u3092\u5909\u3048\u308B\u306A\u3089\u7121\u52B9\u5316\u3057\u3066\u51FA\u3057\u76F4\u3057\u3066\u304F\u3060\u3055\u3044:
416
- `+` slack ask --void='${P(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(ce);if(!([...`${i}
417
- ${a}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((A)=>A[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${i}
418
- ${a}`)||o.channelId.startsWith("D")))console.error("\u2717 \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u306B\u306A\u308A\u307E\u3059 \u2014 \u56DE\u7B54\u3067\u304D\u308B\u4EBA\u3092 @ \u3067\u6B8B\u3057\u3066\u304F\u3060\u3055\u3044"),process.exit(ce);let h=t.lang?Bi({flag:t.lang})?.lang??s.lang:s.lang,g=l.slice(0,Et),p=l.slice(Et),m=typeof o.msg.text==="string"?o.msg.text:"",w=Ki(i,a,g,p,s.threadOnly,h,s.explain),b=$o(m);if(b.length)w=Ao(w,b,h);if(Je(w,t.allowUrlAdjacent),w===m){console.error("\u5909\u66F4\u306F\u3042\u308A\u307E\u305B\u3093\u3002");return}let D=xe("ask-edit",`${o.channelId}:${o.ts}`,w,n?.userId??"");if(t.code!==D){let A=(C,x,J)=>x===J?[` ${C}: (unchanged)`]:[` ${C}:`,...x.split(`
419
- `).map((ne)=>` - ${ne}`),...J.split(`
420
- `).map((ne)=>` + ${ne}`)];Ee(t.code,D,["--- Editing question --------------------------",_e(n,{asBot:t.asBot}),` ${P(t.link)}`,...A("Question",s.question,i),...A("Body",s.body,a),...u?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...c.map((C,x)=>` - ${x+1}. ${Oe(C)}`),...l.map((C,x)=>` + ${x+1}. ${Oe(C)}`)]:[" Choices: (unchanged)"],...h!==s.lang?[` Language: ${s.lang} \u2192 ${h} (the instructions are rewritten)`]:[],"----------------------------------------------"])}await Ct(e,o.channelId,o.ts,w,t.cookie,!0);let S=g.length?Bn:Kt,F=Ds(m)??Kt;if(u){let A=(C)=>s.explain?[C,Dn]:[C];for(let C of[...s.reactable.map((x,J)=>Te[J].name),...A(F)])try{await At(e,o.channelId,o.ts,C,t.cookie)}catch{}await vo([...g.map((C,x)=>Te[x].name),...A(S)],(C)=>$t(e,o.channelId,o.ts,C,t.cookie),(C,x)=>console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${C} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${x instanceof Error?x.message:String(x)})`))}else if(F!==S)try{await $t(e,o.channelId,o.ts,S,t.cookie),await At(e,o.channelId,o.ts,F,t.cookie)}catch(A){console.error(` (marker \u3092 ${S} \u306B\u66FF\u3048\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${A instanceof Error?A.message:String(A)})`)}console.error(`\u2713 \u7DE8\u96C6\u3057\u307E\u3057\u305F: ${P(t.link)}`)}async function vw(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let o=ta(n);if(!o)console.error(`Error: ${Es}
421
- (${bt()})`),process.exit(ce);let s;if(t.stale){if(s=Bo(t.stale),s===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${P(t.stale)})`),process.exit(ce)}let r=[];for(let a of o){if(s!==void 0&&a.sent_at>s)continue;let c=a.as_bot?e.bot:e.user,l=a.permalink||`${a.channel}:${a.ts}`,u="unknown",d=(a.text.split(`
422
- `)[0]??"").replace(/^:question: /,""),f;if(c)try{let g=await lr(c,{channelId:a.channel,ts:a.ts,threadTs:a.thread_ts??void 0},a.as_bot?void 0:e.cookie);if(!g.msg)u="gone";else{let p=wt(typeof g.msg.text==="string"?g.msg.text:"");if(u=p.kind==="resolved"?"answered":p.kind==="other"?"edited":p.kind,p.kind!=="other"&&p.question)d=p.question;if(p.kind==="resolved")f=p.answer}}catch{u="unknown"}if(t.state!=="all"&&u!==t.state)continue;let h={state:u,age_h:Math.round((Date.now()-a.sent_at)/3600000),asBot:!!a.as_bot,channel:a.channel,target:a.target??a.channel,link:l,question:Oe(d)};if(f!==void 0)h.answer=f;r.push(h)}if(t.json)console.log(JSON.stringify(r));else{for(let a of r)console.log(`${a.state.padEnd(8)} ${String(a.age_h).padStart(4)}h ${a.asBot?"bot ":"user"} ${P(a.target)} ${a.link}
423
- ${P(a.question).slice(0,100)}`);console.error(`${r.length} question(s)${t.state==="all"?"":` in state "${t.state}"`}${t.stale?`, older than ${t.stale}`:""}.`)}let i=r.filter((a)=>a.state==="open");if(t.stale&&i.length)for(let a of[!1,!0]){let c=i.filter((l)=>l.asBot===a);if(!c.length)continue;console.error(`\u7121\u52B9\u5316\u3059\u308B\u306A\u3089 (${c.length} \u4EF6, ${a?"bot":"user"}):
424
- slack ask ${c.map((l)=>`--void='${l.link}'`).join(" ")} --reason 'stale'${a?" --as-bot":""}`)}}async function Lw(e,t){let n=yd(t.sinceMs);if(!n)console.error(`Error: ${Es}
425
- (${bt()})`),process.exit(ce);let o=t.channel?n.filter((u)=>u.channel===t.channel||u.target===t.channel):n,s=[],r={unanswered:0,ambiguous:0,resolved:0,void:0,explain:0},i=[],a=[],c=e.user?(await Be(e.user,e.cookie))?.team??"":e.bot?(await Be(e.bot))?.team??"":"",l=new Map;for(let u of o){if(u.team&&c&&u.team!==c){l.set(u.team,(l.get(u.team)??0)+1);continue}let d=u.permalink||`${u.channel}:${u.ts}`,f=!!u.as_bot,h=f?e.bot:e.user;if(!h){a.push(`${d}: ${f?"--as-bot \u3067\u805E\u3044\u305F\u8CEA\u554F\u3067\u3059\u304C bot token \u304C\u3042\u308A\u307E\u305B\u3093":"user token \u304C\u3042\u308A\u307E\u305B\u3093"}`);continue}let g=f?void 0:e.cookie,p=u.delivered_cursor??void 0;try{let m={channelId:u.channel,ts:u.ts,threadTs:u.thread_ts??void 0},w=await lr(h,m,g);if(!w.msg){a.push(`${d}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093 (\u524A\u9664?)`);continue}let b=await kp(h,{channelId:u.channel,ts:u.ts,msg:w.msg},g),D=b.parsed;if(D.kind==="resolved"){r.resolved++;continue}if(D.kind==="void"){r.void++;continue}if(D.kind==="other"){a.push(`${d}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u3081\u307E\u305B\u3093 \u2014 ${bs(b.text)}`);continue}if(!b.audience.size&&!b.broadcast){a.push(`${d}: \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u3067\u3059`);continue}let S=xp(b,D,m,{timeout:0,link:d,asBot:f,json:!1,cookie:g,after:p}),F=mp(h,S,!0),A=await F.poll(),C=F.state.unchosen;if(F.state.voided){r.void++;continue}let x=_n(d,f,p);if(F.state.explainNow.length)r.explain++,i.push(`${d}: \u2139\uFE0F \u8AAC\u660E\u3092\u6C42\u3081\u3089\u308C\u3066\u3044\u307E\u3059 (${F.state.explainNow.map((ne)=>`<@${ne}>`).join(" ")}) \u2014 \u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044`);let J={row:u,link:d,question:D.question,collect:x,alive:wd(u)};if(A)s.push({...J,answer:A.answer,how:A.how,freeText:!1});else if(C&&!C.ambiguous&&C.text!==u.delivered_answer)s.push({...J,answer:C.text,how:"\u8FD4\u4FE1 (\u9078\u629E\u80A2\u5916)",freeText:!0});else if(C?.ambiguous)r.ambiguous++;else r.unanswered++}catch(m){a.push(`${d}: ${m instanceof Error?m.message:String(m)}`)}}if(t.json)for(let u of s){let d=u.row;console.log(JSON.stringify({id:d.id,link:u.link,channel:d.channel,ts:d.ts,asked_at:d.sent_at,question:u.question,answer:u.answer,how:u.how,free_text:u.freeText,sender:{session_id:d.session_id??null,cli:d.cli??null,agent_pid:d.agent_pid??null,pid:d.pid,alive:u.alive,cwd:d.cwd,git_branch:d.git_branch??null,host:d.host??null},delivered_at:d.delivered_at??null,collect:u.collect}))}else{let u=new Map;for(let d of s){let f=d.row.session_id?`session ${d.row.session_id}`:`pid ${d.row.agent_pid??d.row.pid}`;u.set(f,[...u.get(f)??[],d])}for(let[d,f]of u){let h=f[0].row;console.log(`${P(d)} ${P(h.cli??"?")} pid ${h.agent_pid??h.pid} ${f[0].alive?"(alive)":"(gone)"}${h.git_branch?` branch=${P(h.git_branch)}`:""} cwd=${P(h.cwd)}`);for(let g of f)console.log(` ${P(g.link)} (${Rs(g.row.sent_at/1000)})`),console.log(` Q: ${P(Oe(g.question))}`),console.log(` A: ${P(Oe(g.answer))} \u2014 ${P(g.how)}${g.freeText?" \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093":""}`),console.log(` collect: ${P(g.collect)}`)}}for(let u of a)console.error(` (${P(u)})`);for(let u of i)console.error(` (${P(u)})`);for(let[u,d]of l)console.error(` (${d} \u4EF6\u306F\u5225\u306E\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u300C${P(u)}\u300D\u306E\u8CEA\u554F\u3067\u3059 \u2014 slack -w <name> ask --pending \u3067\u78BA\u8A8D)`);console.error(`${s.length} \u4EF6\u304C\u56DE\u7B54\u6E08\u307F\u30FB\u672A\u56DE\u53CE, ${r.unanswered} \u4EF6\u304C\u672A\u56DE\u7B54`+(r.ambiguous?`, ${r.ambiguous} \u4EF6\u306F\u8FD4\u4FE1\u304C\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4 (\u672A\u78BA\u5B9A)`:"")+(r.resolved?`, ${r.resolved} \u4EF6\u306F \u2705 \u56DE\u53CE\u6E08\u307F`:"")+(r.void?`, ${r.void} \u4EF6\u306F\u7121\u52B9\u5316\u6E08\u307F`:"")+(r.explain?`, ${r.explain} \u4EF6\u306F \u2139\uFE0F \u8AAC\u660E\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u3042\u308A`:"")+` \u2014 ${o.length} \u4EF6\u306E\u672A\u56DE\u53CE\u306E\u8CEA\u554F\u3092\u78BA\u8A8D (log: ${bt()})`)}async function Dp(e,t,n,o,s){let r=P(t.link);try{let i=ju(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,o);await Ct(e,t.channelId,t.ts,i,s,!0)}catch(i){return console.error(`\u2717 ${r}: \u66F8\u304D\u63DB\u3048\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((a,c)=>Te[c].name),t.seedMarker,...t.parsed.explain?[Dn]:[]])try{await At(e,t.channelId,t.ts,i,s)}catch{}try{await $t(e,t.channelId,t.ts,Ui,s)}catch(i){console.error(` (${r}: \uD83D\uDEAB \u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 \u7121\u52B9\u5316: ${r}`),!0}async function Mw(e,t){let n=await Be(e,t.cookie);if(t.supersededBy){let a=P(t.supersededBy),c=!1;try{let l=await Ta(e,t.supersededBy,t.cookie);if(c=!!l?.msg,!l)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${a}`),process.exit(ce)}catch(l){console.error(`Error: --superseded-by \u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093: ${a} (${l instanceof Error?l.message:String(l)})`),process.exit(ce)}if(!c)console.error(`Error: --superseded-by \u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${a}`),process.exit(ce)}let o=[],s=0;for(let a of t.links){let c=P(a),l=await Ta(e,a,t.cookie);if(!l){console.error(`\u2717 ${c}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),s++;continue}if(!l.msg){console.error(`\u2717 ${c}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),s++;continue}let u=l.msg;if(!(!!n?.userId&&u.user===n.userId||!!n?.botId&&u.bot_id===n.botId)){console.error(`\u2717 ${c}: \u81EA\u5206\uFF08${ar(n,t.asBot)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u306A\u3044\u306E\u3067\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093`+`${t.asBot?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),s++;continue}let f=typeof u.text==="string"?u.text:"",h=wt(f),g=!1;if(h.kind==="void"){console.error(`- ${c}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059\uFF08\u4F55\u3082\u3057\u307E\u305B\u3093\uFF09`);continue}if(h.kind==="resolved"){console.error(`\u2717 ${c}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\uFF08\u56DE\u7B54: ${P(h.answer.split(`
426
- `)[0]??"")}\uFF09`),s++;continue}if(h.kind!=="open"){let w=Wu(f);if(!w){console.error(`\u2717 ${c}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${bs(f)}`),s++;continue}let b=G(u.reactions).map(T).filter((D)=>G(D.users).includes(n?.userId??"\x00")).map((D)=>Te.findIndex((S)=>S.name===D.name)).filter((D)=>D>=0);h={kind:"open",question:w.question,body:w.body,reactable:Array.from({length:b.length?Math.max(...b)+1:0},()=>""),overflow:[],threadOnly:!0,lang:ji(f)??"ja",explain:G(u.reactions).map(T).some((D)=>D.name===Dn&&G(D.users).includes(n?.userId??"\x00"))},g=!0}let p=g?G(u.reactions).map(T).some((w)=>w.name===Bn&&G(w.users).includes(n?.userId??"\x00"))?Bn:Kt:Ds(f)??Kt,m=G(u.reactions).map(T).filter((w)=>typeof w.name==="string"&&Te.some((b)=>b.name===w.name)).filter((w)=>G(w.users).some((b)=>b!==n?.userId)).map((w)=>`:${String(w.name)}:`);o.push({link:a,channelId:l.channelId,ts:l.ts,text:f,parsed:h,seedMarker:p,pressed:m,...g?{unreadable:g}:{}})}if(!o.length)console.error(s?"\u7121\u52B9\u5316\u3067\u304D\u308B\u8CEA\u554F\u304C\u3042\u308A\u307E\u305B\u3093\u3002":"\u4F55\u3082\u3059\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u305B\u3093\u3002"),process.exit(s?ce:0);let r=xe("ask-void",...o.map((a)=>`${a.channelId}:${a.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==r)Ee(t.code,r,["--- \u7121\u52B9\u5316 (void) -------------------------------",_e(n,{asBot:t.asBot}),` Reason: ${t.reason?P(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${P(t.supersededBy)}`]:[],` ${o.length} question(s):`,...o.map((a)=>` \u2022 ${P(a.link)}
427
- ${P(a.parsed.question.split(`
417
+ `+` slack ask --void='${O(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(ce);if(!([...`${i}
418
+ ${a}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((F)=>F[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${i}
419
+ ${a}`)||o.channelId.startsWith("D")))console.error("\u2717 \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u306B\u306A\u308A\u307E\u3059 \u2014 \u56DE\u7B54\u3067\u304D\u308B\u4EBA\u3092 @ \u3067\u6B8B\u3057\u3066\u304F\u3060\u3055\u3044"),process.exit(ce);let h=t.lang?Ji({flag:t.lang})?.lang??s.lang:s.lang,g=l.slice(0,_t),p=l.slice(_t),m=typeof o.msg.text==="string"?o.msg.text:"",w=zi(i,a,g,p,s.threadOnly,h,s.explain),b=Fo(m);if(b.length)w=To(w,b,h);if(Ke(w,t.allowUrlAdjacent),w===m){console.error("\u5909\u66F4\u306F\u3042\u308A\u307E\u305B\u3093\u3002");return}let D=xe("ask-edit",`${o.channelId}:${o.ts}`,w,n?.userId??"");if(t.code!==D){let F=(E,x,W)=>x===W?[` ${E}: (unchanged)`]:[` ${E}:`,...x.split(`
420
+ `).map((Q)=>` - ${Q}`),...W.split(`
421
+ `).map((Q)=>` + ${Q}`)];Se(t.code,D,["--- Editing question --------------------------",_e(n,{asBot:t.asBot}),` ${O(t.link)}`,...F("Question",s.question,i),...F("Body",s.body,a),...u?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...c.map((E,x)=>` - ${x+1}. ${ve(E)}`),...l.map((E,x)=>` + ${x+1}. ${ve(E)}`)]:[" Choices: (unchanged)"],...h!==s.lang?[` Language: ${s.lang} \u2192 ${h} (the instructions are rewritten)`]:[],"----------------------------------------------"])}await At(e,o.channelId,o.ts,w,t.cookie,!0);let S=g.length?jn:Ht,A=xs(m)??Ht;if(u){let F=(E)=>s.explain?[E,Dn]:[E];for(let E of[...s.reactable.map((x,W)=>Te[W].name),...F(A)])try{await Tt(e,o.channelId,o.ts,E,t.cookie)}catch{}await Mo([...g.map((E,x)=>Te[x].name),...F(S)],(E)=>Ft(e,o.channelId,o.ts,E,t.cookie),(E,x)=>console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${E} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${x instanceof Error?x.message:String(x)})`))}else if(A!==S)try{await Ft(e,o.channelId,o.ts,S,t.cookie),await Tt(e,o.channelId,o.ts,A,t.cookie)}catch(F){console.error(` (marker \u3092 ${S} \u306B\u66FF\u3048\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${F instanceof Error?F.message:String(F)})`)}console.error(`\u2713 \u7DE8\u96C6\u3057\u307E\u3057\u305F: ${O(t.link)}`)}async function tb(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let o=ra(n);if(!o)console.error(`Error: ${$s}
422
+ (${Dt()})`),process.exit(ce);let s;if(t.stale){if(s=Wo(t.stale),s===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${O(t.stale)})`),process.exit(ce)}let r=[];for(let a of o){if(s!==void 0&&a.sent_at>s)continue;let c=a.as_bot?e.bot:e.user,l=a.permalink||`${a.channel}:${a.ts}`,u="unknown",d=(a.text.split(`
423
+ `)[0]??"").replace(/^:question: /,""),f;if(c)try{let g=await pr(c,{channelId:a.channel,ts:a.ts,threadTs:a.thread_ts??void 0},a.as_bot?void 0:e.cookie);if(!g.msg)u="gone";else{let p=bt(typeof g.msg.text==="string"?g.msg.text:"");if(u=p.kind==="resolved"?"answered":p.kind==="other"?"edited":p.kind,p.kind!=="other"&&p.question)d=p.question;if(p.kind==="resolved")f=p.answer}}catch{u="unknown"}if(t.state!=="all"&&u!==t.state)continue;let h={state:u,age_h:Math.round((Date.now()-a.sent_at)/3600000),asBot:!!a.as_bot,channel:a.channel,target:a.target??a.channel,link:l,question:ve(d)};if(f!==void 0)h.answer=f;r.push(h)}if(t.json)console.log(JSON.stringify(r));else{for(let a of r)console.log(`${a.state.padEnd(8)} ${String(a.age_h).padStart(4)}h ${a.asBot?"bot ":"user"} ${O(a.target)} ${a.link}
424
+ ${O(a.question).slice(0,100)}`);console.error(`${r.length} question(s)${t.state==="all"?"":` in state "${t.state}"`}${t.stale?`, older than ${t.stale}`:""}.`)}let i=r.filter((a)=>a.state==="open");if(t.stale&&i.length)for(let a of[!1,!0]){let c=i.filter((l)=>l.asBot===a);if(!c.length)continue;console.error(`\u7121\u52B9\u5316\u3059\u308B\u306A\u3089 (${c.length} \u4EF6, ${a?"bot":"user"}):
425
+ slack ask ${c.map((l)=>`--void='${l.link}'`).join(" ")} --reason 'stale'${a?" --as-bot":""}`)}}async function nb(e,t){let n=Ad(t.sinceMs);if(!n)console.error(`Error: ${$s}
426
+ (${Dt()})`),process.exit(ce);let o=t.channel?n.filter((u)=>u.channel===t.channel||u.target===t.channel):n,s=[],r={unanswered:0,ambiguous:0,resolved:0,void:0,explain:0},i=[],a=[],c=e.user?(await je(e.user,e.cookie))?.team??"":e.bot?(await je(e.bot))?.team??"":"",l=new Map;for(let u of o){if(u.team&&c&&u.team!==c){l.set(u.team,(l.get(u.team)??0)+1);continue}let d=u.permalink||`${u.channel}:${u.ts}`,f=!!u.as_bot,h=f?e.bot:e.user;if(!h){a.push(`${d}: ${f?"--as-bot \u3067\u805E\u3044\u305F\u8CEA\u554F\u3067\u3059\u304C bot token \u304C\u3042\u308A\u307E\u305B\u3093":"user token \u304C\u3042\u308A\u307E\u305B\u3093"}`);continue}let g=f?void 0:e.cookie,p=u.delivered_cursor??void 0;try{let m={channelId:u.channel,ts:u.ts,threadTs:u.thread_ts??void 0},w=await pr(h,m,g);if(!w.msg){a.push(`${d}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093 (\u524A\u9664?)`);continue}let b=await Rp(h,{channelId:u.channel,ts:u.ts,msg:w.msg},g),D=b.parsed;if(D.kind==="resolved"){r.resolved++;continue}if(D.kind==="void"){r.void++;continue}if(D.kind==="other"){a.push(`${d}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u3081\u307E\u305B\u3093 \u2014 ${ks(b.text)}`);continue}if(!b.audience.size&&!b.broadcast){a.push(`${d}: \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u3067\u3059`);continue}let S=Ip(b,D,m,{timeout:0,link:d,asBot:f,json:!1,cookie:g,after:p}),A=$p(h,S,!0),F=await A.poll(),E=A.state.unchosen;if(A.state.voided){r.void++;continue}let x=$n(d,f,p);if(A.state.explainNow.length)r.explain++,i.push(`${d}: \u2139\uFE0F \u8AAC\u660E\u3092\u6C42\u3081\u3089\u308C\u3066\u3044\u307E\u3059 (${A.state.explainNow.map((Q)=>`<@${Q}>`).join(" ")}) \u2014 \u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044`);let W={row:u,link:d,question:D.question,collect:x,alive:Fd(u)};if(F)s.push({...W,answer:F.answer,how:F.how,freeText:!1});else if(E&&!E.ambiguous&&E.text!==u.delivered_answer)s.push({...W,answer:E.text,how:"\u8FD4\u4FE1 (\u9078\u629E\u80A2\u5916)",freeText:!0});else if(E?.ambiguous)r.ambiguous++;else r.unanswered++}catch(m){a.push(`${d}: ${m instanceof Error?m.message:String(m)}`)}}if(t.json)for(let u of s){let d=u.row;console.log(JSON.stringify({id:d.id,link:u.link,channel:d.channel,ts:d.ts,asked_at:d.sent_at,question:u.question,answer:u.answer,how:u.how,free_text:u.freeText,sender:{session_id:d.session_id??null,cli:d.cli??null,agent_pid:d.agent_pid??null,pid:d.pid,alive:u.alive,cwd:d.cwd,git_branch:d.git_branch??null,host:d.host??null},delivered_at:d.delivered_at??null,collect:u.collect}))}else{let u=new Map;for(let d of s){let f=d.row.session_id?`session ${d.row.session_id}`:`pid ${d.row.agent_pid??d.row.pid}`;u.set(f,[...u.get(f)??[],d])}for(let[d,f]of u){let h=f[0].row;console.log(`${O(d)} ${O(h.cli??"?")} pid ${h.agent_pid??h.pid} ${f[0].alive?"(alive)":"(gone)"}${h.git_branch?` branch=${O(h.git_branch)}`:""} cwd=${O(h.cwd)}`);for(let g of f)console.log(` ${O(g.link)} (${_n(g.row.sent_at/1000)})`),console.log(` Q: ${O(ve(g.question))}`),console.log(` A: ${O(ve(g.answer))} \u2014 ${O(g.how)}${g.freeText?" \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093":""}`),console.log(` collect: ${O(g.collect)}`)}}for(let u of a)console.error(` (${O(u)})`);for(let u of i)console.error(` (${O(u)})`);for(let[u,d]of l)console.error(` (${d} \u4EF6\u306F\u5225\u306E\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u300C${O(u)}\u300D\u306E\u8CEA\u554F\u3067\u3059 \u2014 slack -w <name> ask --pending \u3067\u78BA\u8A8D)`);console.error(`${s.length} \u4EF6\u304C\u56DE\u7B54\u6E08\u307F\u30FB\u672A\u56DE\u53CE, ${r.unanswered} \u4EF6\u304C\u672A\u56DE\u7B54`+(r.ambiguous?`, ${r.ambiguous} \u4EF6\u306F\u8FD4\u4FE1\u304C\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4 (\u672A\u78BA\u5B9A)`:"")+(r.resolved?`, ${r.resolved} \u4EF6\u306F \u2705 \u56DE\u53CE\u6E08\u307F`:"")+(r.void?`, ${r.void} \u4EF6\u306F\u7121\u52B9\u5316\u6E08\u307F`:"")+(r.explain?`, ${r.explain} \u4EF6\u306F \u2139\uFE0F \u8AAC\u660E\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u3042\u308A`:"")+` \u2014 ${o.length} \u4EF6\u306E\u672A\u56DE\u53CE\u306E\u8CEA\u554F\u3092\u78BA\u8A8D (log: ${Dt()})`)}async function Tp(e,t,n,o,s){let r=O(t.link);try{let i=Vu(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,o);await At(e,t.channelId,t.ts,i,s,!0)}catch(i){return console.error(`\u2717 ${r}: \u66F8\u304D\u63DB\u3048\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((a,c)=>Te[c].name),t.seedMarker,...t.parsed.explain?[Dn]:[]])try{await Tt(e,t.channelId,t.ts,i,s)}catch{}try{await Ft(e,t.channelId,t.ts,Hi,s)}catch(i){console.error(` (${r}: \uD83D\uDEAB \u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 \u7121\u52B9\u5316: ${r}`),!0}async function sb(e,t){let n=await je(e,t.cookie);if(t.supersededBy){let a=O(t.supersededBy),c=!1;try{let l=await ja(e,t.supersededBy,t.cookie);if(c=!!l?.msg,!l)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${a}`),process.exit(ce)}catch(l){console.error(`Error: --superseded-by \u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093: ${a} (${l instanceof Error?l.message:String(l)})`),process.exit(ce)}if(!c)console.error(`Error: --superseded-by \u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${a}`),process.exit(ce)}let o=[],s=0;for(let a of t.links){let c=O(a),l=await ja(e,a,t.cookie);if(!l){console.error(`\u2717 ${c}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),s++;continue}if(!l.msg){console.error(`\u2717 ${c}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),s++;continue}let u=l.msg;if(!(!!n?.userId&&u.user===n.userId||!!n?.botId&&u.bot_id===n.botId)){console.error(`\u2717 ${c}: \u81EA\u5206\uFF08${dr(n,t.asBot)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u306A\u3044\u306E\u3067\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093`+`${t.asBot?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),s++;continue}let f=typeof u.text==="string"?u.text:"",h=bt(f),g=!1;if(h.kind==="void"){console.error(`- ${c}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059\uFF08\u4F55\u3082\u3057\u307E\u305B\u3093\uFF09`);continue}if(h.kind==="resolved"){console.error(`\u2717 ${c}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\uFF08\u56DE\u7B54: ${O(h.answer.split(`
427
+ `)[0]??"")}\uFF09`),s++;continue}if(h.kind!=="open"){let w=Zu(f);if(!w){console.error(`\u2717 ${c}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${ks(f)}`),s++;continue}let b=G(u.reactions).map(T).filter((D)=>G(D.users).includes(n?.userId??"\x00")).map((D)=>Te.findIndex((S)=>S.name===D.name)).filter((D)=>D>=0);h={kind:"open",question:w.question,body:w.body,reactable:Array.from({length:b.length?Math.max(...b)+1:0},()=>""),overflow:[],threadOnly:!0,lang:Ki(f)??"ja",explain:G(u.reactions).map(T).some((D)=>D.name===Dn&&G(D.users).includes(n?.userId??"\x00"))},g=!0}let p=g?G(u.reactions).map(T).some((w)=>w.name===jn&&G(w.users).includes(n?.userId??"\x00"))?jn:Ht:xs(f)??Ht,m=G(u.reactions).map(T).filter((w)=>typeof w.name==="string"&&Te.some((b)=>b.name===w.name)).filter((w)=>G(w.users).some((b)=>b!==n?.userId)).map((w)=>`:${String(w.name)}:`);o.push({link:a,channelId:l.channelId,ts:l.ts,text:f,parsed:h,seedMarker:p,pressed:m,...g?{unreadable:g}:{}})}if(!o.length)console.error(s?"\u7121\u52B9\u5316\u3067\u304D\u308B\u8CEA\u554F\u304C\u3042\u308A\u307E\u305B\u3093\u3002":"\u4F55\u3082\u3059\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u305B\u3093\u3002"),process.exit(s?ce:0);let r=xe("ask-void",...o.map((a)=>`${a.channelId}:${a.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==r)Se(t.code,r,["--- \u7121\u52B9\u5316 (void) -------------------------------",_e(n,{asBot:t.asBot}),` Reason: ${t.reason?O(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${O(t.supersededBy)}`]:[],` ${o.length} question(s):`,...o.map((a)=>` \u2022 ${O(a.link)}
428
+ ${O(a.parsed.question.split(`
428
429
  `)[0]??"").slice(0,100)}`+(a.pressed.length?`
429
430
  (already pressed: ${a.pressed.join(" ")} \u2014 left in place, never collected)`:"")+(a.unreadable?`
430
- \u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...s?[` (${s} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let a of o)if(!await Dp(e,a,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||s?ce:0)}async function Nw(e,t){let n=zt(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 p=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!p)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
431
- `+` Got: ${P(t.link)}`),process.exit(ce);o=p[1],s=p[2]}let i=await lr(e,{channelId:o,ts:s,threadTs:r},t.cookie);if(!i.msg)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${P(t.link)}`),process.exit(ce);let a=i.msg,c=await kp(e,{channelId:o,ts:s,msg:a},t.cookie),{text:l,parsed:u,audience:d,broadcast:f,askerUserId:h,askerBotId:g}=c;if(u.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: ${bs(l)}
432
- ${P(t.link)}
433
- `+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${P(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(ce);if(u.kind==="void"){if(wp(u,t.link),t.json)await Vt(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:u.reason,...u.supersededBy?{supersededBy:u.supersededBy}:{},notes:[],cursor:Rt(s,t.after)});process.exit(fp)}if(u.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${P(u.question)}`);let p=typeof T(a.edited).ts==="string"?String(T(a.edited).ts):void 0,m=Ku(l),w=!1,b=(A)=>{if(w||!m.byReply)return!1;if(p&&Number(A.ts)>Number(p))return!1;let C=typeof A.text==="string"?A.text.trim():"",x=C===u.answer||m.n!==void 0&&(new RegExp(`^[(\uFF08]?${m.n}(?![0-9])`).test(C)||Ju(C,u.answer,m.n));if(x)w=!0;return x},D=t.after,S=[];if(d.size||f){let A=(C)=>typeof C==="string"&&!!C&&C!==h&&(f||d.has(C));S=await gp(e,{channelId:o,ts:s,threadOnly:!!r||!o.startsWith("D"),replyCount:Number(a.reply_count)||0,isAnswerer:A,askerUserId:h,askerBotId:g,...r?{threadParentTs:r}:{},...t.cookie?{cookie:t.cookie}:{}},D,b)}let F=Rt(s,D,...S.map((A)=>A.ts));await Vt(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:u.answer,notes:S,cursor:F}),na(o,s,u.answer,F);return}if(!d.size&&!f)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: ${P(t.link)}`),process.exit(ce);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`);await yp(e,xp(c,u,{channelId:o,ts:s,threadTs:r},t))}async function kp(e,t,n){let{msg:o}=t,s=typeof o.text==="string"?o.text:"",r=wt(s),i=typeof o.user==="string"?o.user:"",a=typeof o.bot_id==="string"?o.bot_id:"",c=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(s),l=new Set;for(let u of s.matchAll(/<@([UW][A-Z0-9]+)>/g))if(u[1]!==i)l.add(u[1]);if(r.kind!=="other"&&!l.size&&!c){let u=await cr(e,t.channelId,n);if(u&&u!==i)l.add(u)}return{text:s,parsed:r,audience:l,broadcast:c,askerUserId:i,askerBotId:a}}function xp(e,t,n,o){let s={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,seedMarker:Ds(e.text)??Kt,lang:t.lang,audience:e.audience,broadcast:e.broadcast,askerUserId:e.askerUserId,askerBotId:e.askerBotId,timeout:o.timeout,shown:o.link,asBot:o.asBot,json:o.json,explain:t.explain,explainExit:!!o.explainExit};if(n.threadTs)s.threadParentTs=n.threadTs;if(o.cookie)s.cookie=o.cookie;if(o.after)s.after=o.after;return s}var ct=3;function Bw(e){return`slack poll --results='${e}'`}async function jw(e,t){let{ref:n,threadTs:o}=Gn(t.target,!1),s=t.cookie,r=It(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ft(e,t.userId,s);else i=await ke(e,n,s);let a=(await r())?.userId??"",c=await cr(e,i,s);if(!t.asBot&&!!a&&c===a)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
434
- `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=Ls(Me(t.question)),u=Ls(Me(t.body??"")),d=t.mentionToken??e,f=await Yt(d,l.text,i,t.mentionCookie),h=u.text?await Yt(d,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},g=f.text,p=h.text;for(let I of zo([...f.unresolved,...h.unresolved]))console.error(`\u26A0 ${P(I)}`);let m=t.choices.map(Me),w=!!t.multi,b=t.until??"",D=Qu(g,p,m,{multi:w,deadline:b});Je(D,t.allowUrlAdjacent);let S="",F="?";try{let I=await tt(e,i,1,void 0,void 0,s),W=G(I.messages).map(T).filter((N)=>N.subtype===void 0||N.subtype===null)[0];S=typeof W?.text==="string"?W.text:"",F=typeof W?.user==="string"?await ve(e,W.user,s):typeof W?.username==="string"?W.username:"?"}catch{}let A=await r(),C=await ir(e,i,s),x=xe(i,o??"",S,D,A?.userId??"");if(t.code!==x){let I=await Qt(e,i,n,s);Ee(t.code,x,["--- Last message in channel ------------------",` ${F}: ${Is(S.split(`
435
- `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...m.map((W,N)=>` ${ht[N].glyph} ${ks(W)}`),"--- Posting ----------------------------------",_e(A,{asBot:t.asBot}),` \u2192 ${I}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${g}`,` Rule: ${w?"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"],C)}let J=Cn("poll"),ne=await Ht(e,i,D,o,!1,s,!0,J.metadata);await vo([xs,...m.map((I,W)=>ht[W].name)],(I)=>$t(e,i,ne,I,s),(I,W)=>{let N=W instanceof Error?W.message:String(W);if(I===xs)console.error(` (marker ${I} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${N})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${I} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${N})`)});let L="";try{L=await Wn(e,i,ne,s)}catch{}let O=L||`${i}:${ne}`;console.error(`\u2713 Posted: ${O}`),J.record({team:A?.team,channel:i,target:t.target,ts:ne,threadTs:o,permalink:L,text:D,asBot:t.asBot}),console.log(Bw(O)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${O}'${t.asBot?" --as-bot":""}`)}async function Ww(e,t,n){let o=zt(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 c=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!c)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
436
- `+` Got: ${P(t)}`),process.exit(ct);s=c[1],r=c[2]}let a;if(i){let c=T(await Ue(e,s,i,100,n));a=G(c.messages).map(T).find((l)=>l.ts===r)}else{let c=T(await tt(e,s,1,r,void 0,n,!0));a=G(c.messages).map(T).find((l)=>l.ts===r)}if(!a)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${P(t)}`),process.exit(ct);return{channelId:s,ts:r,msg:a}}function Yf(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,o)=>`${ht[o].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function Uw(e,t){let{channelId:n,ts:o,msg:s}=await Ww(e,t.link,t.cookie),r=typeof s.text==="string"?s.text:"",i=Ss(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"+` ${P(t.link)}`),process.exit(ct);if(i.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${P(i.question)}`);for(let h of Yf(i.tallies))console.log(h);return}let a=new Set;if(typeof s.user==="string"&&s.user)a.add(s.user);let c=await Bd(e,n,o,t.cookie),l=td(i.choices,c,a,i.multi);console.error(`${P(i.question)}${i.deadline?` (\u7DE0\u5207 ${i.deadline})`:""}`);for(let h of Yf(l.tallies))console.log(h);let u=l.tallies.reduce((h,g)=>h+g.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 g=await Promise.all(l.voters[h].map((p)=>ve(e,p,t.cookie)));console.error(` ${ht[h].glyph} ${g.map((p)=>`@${P(p)}`).join(", ")}`)}let d=i.multi?[]:l.ambiguous,f=Ao(r,d);if(f!==r&&!t.noNotify)try{await Ct(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)})
437
- `+" \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((g)=>ve(e,g,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((g)=>`@${P(g)}`).join(", ")}`)}if(!t.close)return;await Ct(t.writeToken??e,n,o,ed(i.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await $t(t.writeToken??e,n,o,Gi,t.writeToken?t.writeCookie:t.cookie),await At(t.writeToken??e,n,o,xs,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${P(t.link)}`)}async function Kw(e){let t=await ho(e);for(let n of go(t,!1))console.log(n);if(!t.ok)process.exit(1)}function Zo(){let e=qe();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
438
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function Vf(e,t,n,o){let s=await Tt(n,e,o);return Ft(t,s)}function Jw(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 qw(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 Hw(e,t){Je(t.message,t.allowUrlAdjacent);let n=It(e,t.cookie),{ref:o,threadTs:s}=Gn(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await Ft(e,t.userId,t.cookie);else r=await ke(e,o,t.cookie);let i=Jw(t.at),a=new Date(i*1000).toISOString(),c=await n();if(!t.asBot&&await La(e,r,c?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
439
- `+` 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),c?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==l){let f=await ir(e,r,t.cookie);Ee(t.code,l,["--- Scheduling message -----------------------",_e(c,{asBot:t.asBot,pad:9}),` To: ${o}${s?` (thread ${s})`:""}${u}`,` At: ${qw(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await Od(e,r,t.message,i,s,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${a})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
431
+ \u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...s?[` (${s} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let a of o)if(!await Tp(e,a,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||s?ce:0)}async function ob(e,t){let n=Xt(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 p=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!p)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
432
+ `+` Got: ${O(t.link)}`),process.exit(ce);o=p[1],s=p[2]}let i=await pr(e,{channelId:o,ts:s,threadTs:r},t.cookie);if(!i.msg)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${O(t.link)}`),process.exit(ce);let a=i.msg,c=await Rp(e,{channelId:o,ts:s,msg:a},t.cookie),{text:l,parsed:u,audience:d,broadcast:f,askerUserId:h,askerBotId:g}=c;if(u.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: ${ks(l)}
433
+ ${O(t.link)}
434
+ `+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${O(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(ce);if(u.kind==="void"){if(Ap(u,t.link),t.json)await Zt(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:u.reason,...u.supersededBy?{supersededBy:u.supersededBy}:{},notes:[],cursor:Ot(s,t.after)});process.exit(xp)}if(u.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${O(u.question)}`);let p=typeof T(a.edited).ts==="string"?String(T(a.edited).ts):void 0,m=ed(l),w=!1,b=(F)=>{if(w||!m.byReply)return!1;if(p&&Number(F.ts)>Number(p))return!1;let E=typeof F.text==="string"?F.text.trim():"",x=E===u.answer||m.n!==void 0&&(new RegExp(`^[(\uFF08]?${m.n}(?![0-9])`).test(E)||td(E,u.answer,m.n));if(x)w=!0;return x},D=t.after,S=[];if(d.size||f){let F=(E)=>typeof E==="string"&&!!E&&E!==h&&(f||d.has(E));S=await _p(e,{channelId:o,ts:s,threadOnly:!!r||!o.startsWith("D"),replyCount:Number(a.reply_count)||0,isAnswerer:F,askerUserId:h,askerBotId:g,...r?{threadParentTs:r}:{},...t.cookie?{cookie:t.cookie}:{}},D,b)}let A=Ot(s,D,...S.map((F)=>F.ts));await Zt(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:u.answer,notes:S,cursor:A}),ia(o,s,u.answer,A);return}if(!d.size&&!f)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: ${O(t.link)}`),process.exit(ce);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`);await Cp(e,Ip(c,u,{channelId:o,ts:s,threadTs:r},t))}async function Rp(e,t,n){let{msg:o}=t,s=typeof o.text==="string"?o.text:"",r=bt(s),i=typeof o.user==="string"?o.user:"",a=typeof o.bot_id==="string"?o.bot_id:"",c=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(s),l=new Set;for(let u of s.matchAll(/<@([UW][A-Z0-9]+)>/g))if(u[1]!==i)l.add(u[1]);if(r.kind!=="other"&&!l.size&&!c){let u=await fr(e,t.channelId,n);if(u&&u!==i)l.add(u)}return{text:s,parsed:r,audience:l,broadcast:c,askerUserId:i,askerBotId:a}}function Ip(e,t,n,o){let s={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,seedMarker:xs(e.text)??Ht,lang:t.lang,audience:e.audience,broadcast:e.broadcast,askerUserId:e.askerUserId,askerBotId:e.askerBotId,timeout:o.timeout,shown:o.link,asBot:o.asBot,json:o.json,explain:t.explain,explainExit:!!o.explainExit};if(n.threadTs)s.threadParentTs=n.threadTs;if(o.cookie)s.cookie=o.cookie;if(o.after)s.after=o.after;return s}var ct=3;function rb(e){return`slack poll --results='${e}'`}async function ib(e,t){let{ref:n,threadTs:o}=Vn(t.target,!1),s=t.cookie,r=vt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Rt(e,t.userId,s);else i=await ke(e,n,s);let a=(await r())?.userId??"",c=await fr(e,i,s);if(!t.asBot&&!!a&&c===a)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
435
+ `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=Ns(Ne(t.question)),u=Ns(Ne(t.body??"")),d=t.mentionToken??e,f=await Vt(d,l.text,i,t.mentionCookie),h=u.text?await Vt(d,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},g=f.text,p=h.text;for(let I of Xo([...f.unresolved,...h.unresolved]))console.error(`\u26A0 ${O(I)}`);let m=t.choices.map(Ne),w=!!t.multi,b=t.until??"",D=ud(g,p,m,{multi:w,deadline:b});Ke(D,t.allowUrlAdjacent);let S="",A="?";try{let I=await tt(e,i,1,void 0,void 0,s),U=G(I.messages).map(T).filter((N)=>N.subtype===void 0||N.subtype===null)[0];S=typeof U?.text==="string"?U.text:"",A=typeof U?.user==="string"?await Ie(e,U.user,s):typeof U?.username==="string"?U.username:"?"}catch{}let F=await r(),E=await ur(e,i,s),x=xe(i,o??"",S,D,F?.userId??"");if(t.code!==x){let I=await en(e,i,n,s);Se(t.code,x,["--- Last message in channel ------------------",` ${A}: ${Xn(S.split(`
436
+ `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...m.map((U,N)=>` ${ht[N].glyph} ${Ss(U)}`),"--- Posting ----------------------------------",_e(F,{asBot:t.asBot}),` \u2192 ${I}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${g}`,` Rule: ${w?"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"],E)}let W=Cn("poll"),Q=await zt(e,i,D,o,!1,s,!0,W.metadata);await Mo([Es,...m.map((I,U)=>ht[U].name)],(I)=>Ft(e,i,Q,I,s),(I,U)=>{let N=U instanceof Error?U.message:String(U);if(I===Es)console.error(` (marker ${I} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${N})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${I} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${N})`)});let M="";try{M=await Un(e,i,Q,s)}catch{}let P=M||`${i}:${Q}`;console.error(`\u2713 Posted: ${P}`),W.record({team:F?.team,channel:i,target:t.target,ts:Q,threadTs:o,permalink:M,text:D,asBot:t.asBot}),console.log(rb(P)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${P}'${t.asBot?" --as-bot":""}`)}async function ab(e,t,n){let o=Xt(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 c=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!c)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
437
+ `+` Got: ${O(t)}`),process.exit(ct);s=c[1],r=c[2]}let a;if(i){let c=T(await Me(e,s,i,100,n));a=G(c.messages).map(T).find((l)=>l.ts===r)}else{let c=T(await tt(e,s,1,r,void 0,n,!0));a=G(c.messages).map(T).find((l)=>l.ts===r)}if(!a)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${O(t)}`),process.exit(ct);return{channelId:s,ts:r,msg:a}}function rp(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,o)=>`${ht[o].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function cb(e,t){let{channelId:n,ts:o,msg:s}=await ab(e,t.link,t.cookie),r=typeof s.text==="string"?s.text:"",i=_s(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"+` ${O(t.link)}`),process.exit(ct);if(i.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${O(i.question)}`);for(let h of rp(i.tallies))console.log(h);return}let a=new Set;if(typeof s.user==="string"&&s.user)a.add(s.user);let c=await Yd(e,n,o,t.cookie),l=fd(i.choices,c,a,i.multi);console.error(`${O(i.question)}${i.deadline?` (\u7DE0\u5207 ${i.deadline})`:""}`);for(let h of rp(l.tallies))console.log(h);let u=l.tallies.reduce((h,g)=>h+g.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 g=await Promise.all(l.voters[h].map((p)=>Ie(e,p,t.cookie)));console.error(` ${ht[h].glyph} ${g.map((p)=>`@${O(p)}`).join(", ")}`)}let d=i.multi?[]:l.ambiguous,f=To(r,d);if(f!==r&&!t.noNotify)try{await At(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)})
438
+ `+" \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((g)=>Ie(e,g,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((g)=>`@${O(g)}`).join(", ")}`)}if(!t.close)return;await At(t.writeToken??e,n,o,dd(i.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await Ft(t.writeToken??e,n,o,Qi,t.writeToken?t.writeCookie:t.cookie),await Tt(t.writeToken??e,n,o,Es,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${O(t.link)}`)}async function lb(e){let t=await mo(e);for(let n of yo(t,!1))console.log(n);if(!t.ok)process.exit(1)}function er(){let e=qe();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
439
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function ip(e,t,n,o){let s=await It(n,e,o);return Rt(t,s)}function ap(e){try{return Op(e)}catch{console.error(`Error: cannot parse --due "${e}" \u2014 use an ISO datetime (2026-11-01T18:00) or a Unix ts.`),process.exit(2)}}function Op(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 Pp(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 ub(e,t){Ke(t.message,t.allowUrlAdjacent);let n=vt(e,t.cookie),{ref:o,threadTs:s}=Vn(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await Rt(e,t.userId,t.cookie);else r=await ke(e,o,t.cookie);let i=Op(t.at),a=new Date(i*1000).toISOString(),c=await n();if(!t.asBot&&await qa(e,r,c?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
440
+ `+` 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),c?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==l){let f=await ur(e,r,t.cookie);Se(t.code,l,["--- Scheduling message -----------------------",_e(c,{asBot:t.asBot,pad:9}),` To: ${o}${s?` (thread ${s})`:""}${u}`,` At: ${Pp(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await qd(e,r,t.message,i,s,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${a})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
440
441
  `+` slack schedule ls --as-bot
441
- slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await ho(e);if(!f.ok)for(let h of go(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 Zf(e,t,n,o){let s;if(n)s=n;else if(t)s=await ke(e,t,o);let i=(await vd(e,s,o)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let a of i){let c=new Date(a.post_at*1000).toISOString();console.log(`${a.id} ${c} [${a.channel_id}] ${a.text.split(`
442
- `)[0]?.slice(0,80)??""}`)}}async function Qf(e,t){let n;if(t.channelId)n=t.channelId;else n=await ke(e,t.target,t.cookie);let o=await Be(e,t.cookie),s=xe(n,t.id,o?.userId??"");if(t.code!==s)Ee(t.code,s,["--- Deleting scheduled message ---------------",_e(o,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await Ld(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function zw(e,t){if(t.comment!==void 0)Je(t.comment,t.allowUrlAdjacent);let n=It(e,t.cookie),{statSync:o,existsSync:s}=await import("fs"),{basename:r}=await import("path");for(let g of t.filePaths)if(!s(g))console.error(`Error: file not found: ${g}`),process.exit(1);let{ref:i,threadTs:a}=Gn(t.target),c;if(t.channelId)c=t.channelId;else if(t.userId)c=await Ft(e,t.userId,t.cookie);else c=await ke(e,i,t.cookie);if(await La(e,c,(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((g)=>{let p=r(g),m=l?p:t.title??p;return{fp:g,filename:p,title:m,sizeFmt:rr(o(g).size)}}),d=await n(),f=xe(c,...u.flatMap((g)=>[g.fp,g.title]),d?.userId??"");if(t.code!==f){let g=` To: ${i}${a?` (thread ${a})`:""}`,p=l?[`--- Uploading ${u.length} files ------------------------`,_e(d,{pad:7}),g,...u.map((m)=>` ${m.filename} (${m.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",_e(d,{pad:7}),g,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];Ee(t.code,f,p)}let h=u.length;for(let g=0;g<h;g++){let p=u[g],m={title:p.title};if(a!==void 0)m.threadTs=a;if(t.comment!==void 0&&g===0)m.initialComment=t.comment;let{fileId:w,permalink:b}=await tf(e,c,p.fp,m,t.cookie),D=h>1?`[${g+1}/${h}] `:"";console.log(`${D}\u2713 Uploaded (file_id: ${w}${b?`, url: ${b}`:""})`)}}async function Xw(e,t,n){let o=n.channel?await ke(e,n.channel,t):void 0,s=[],r=1,i=1;do{let c={page:r,count:200};if(n.types)c.types=n.types;if(o)c.channel=o;if(n.user)c.user=n.user;let l=T(await _d(e,c,t));for(let u of G(l.files))s.push(T(u));i=Number(T(l.paging).pages??1),r++}while(s.length<n.limit&&r<=i);let a=s.slice(0,n.limit);if(n.format==="jsonl"){for(let c of a)console.log(JSON.stringify({id:c.id??null,name:c.name??c.title??null,filetype:c.filetype??null,size:c.size??null,user:c.user??null,created:c.created??null,permalink:c.permalink??null}));return}for(let c of a){let l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.title==="string"?c.title:l,d=typeof c.filetype==="string"?c.filetype:"?",f=typeof c.size==="number"?rr(c.size):"";console.log(`${l} ${d.padEnd(7)} ${f.padStart(9)} ${u}`)}}function ur(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 Gw(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(T(n).text??T(n).name??T(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 Yw(e,t,n,o){let s=ur(n);if(!s)throw Error(`Not a list ID or list URL: ${n}
443
- `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let c={limit:200};if(i)c.cursor=i;let l=o.asBot?await aa(Ms(),s,c):T(await Td(e,s,c,t));for(let d of G(l.items??l.records))r.push(T(d));let u=T(l.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i&&r.length<o.limit);let a=r.slice(0,o.limit);if(o.format==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let l=String(c.id??""),u=G(c.fields).map(T).map((d)=>{let f=String(d.key??d.column_id??"?"),h=Gw(d);return h?`${f}=${h}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function Ms(){let e=qe();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
444
- `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function dr(e){let t=[];try{t=(await qt(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).
445
- `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function Vw(e,t){try{let n=await ia(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Sp(e,t){let n=await aa(e,t,{limit:1,includeList:!0}),o=ad(T(n.list));if(!o.length)throw Error(`could not read the column schema of list ${t}`);return o}function fr(e){console.error(ye(e)),process.exit(1)}async function Zw(e){let t=e.cols.map(rd),n=id(t),o=Ms();await dr(o);let s=await Be(o),r=xe("lists-create",e.name,JSON.stringify(n),String(e.todo),s?.userId??"");if(e.code!==r)Ee(e.code,r,["--- Creating Slack List ----------------------",_e(s,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((c,l)=>` column: ${c.name} (${c.type}${c.choices?`: ${c.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 Cd(o,e.name,n,e.todo)}catch(c){fr(c)}let a=String(i.list_id??T(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${a})`),console.log(await Vw(o,a))}async function Qw(e){let t=ur(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=Ms();await dr(n);let o=await Sp(n,t),r=[{col:o.find((u)=>u.type==="text")??o[0],value:e.text},...Zi(e.sets).map((u)=>({col:Yi(o,u.col),value:u.value}))],i=r.map((u)=>({column_id:u.col.id,...Vi(u.col,u.value)})),a=await Be(n),c=xe("lists-add",t,JSON.stringify(i),a?.userId??"");if(e.code!==c)Ee(e.code,c,["--- Adding a row to Slack List ---------------",_e(a,{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 $d(n,t,i)}catch(u){fr(u)}console.log(`\u2713 Added row ${String(T(l.item).id??"")} ${e.text}`)}async function eb(e){let t=ur(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=Ms();await dr(n);let o=await Sp(n,t),s=Zi(e.sets).map((c)=>({col:Yi(o,c.col),value:c.value}));if(e.done!==void 0){let c=cd(o);if(!c)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);s.push({col:{...c,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((c)=>({row_id:e.row,column_id:c.col.id,...Vi(c.col,c.value)})),i=await Be(n),a=xe("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==a)Ee(e.code,a,["--- Updating Slack List row -----------------",_e(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...s.map((c)=>` ${(c.col.name||c.col.key).padEnd(8)} ${c.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Fd(n,t,r)}catch(c){fr(c)}console.log(`\u2713 Updated row ${e.row}`)}async function tb(e){let t=ur(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=Ms();await dr(n);let o=e.users.length?e.users:e.channels,s=await Be(n),r=xe("lists-share",t,e.level,o.join(","),s?.userId??"");if(e.code!==r)Ee(e.code,r,["--- Sharing Slack List ----------------------",_e(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 Ad(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){fr(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${o.join(", ")}`)}function nb(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 sb(e,t,n,o){let s=nb(n);if(!s)throw Error(`Not a file ID or file permalink: ${n}
446
- `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=T(await Ed(e,s,t)),i=T(r.file),a=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:s,c=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!c)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(c,{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:g}=await import("path"),p=o??a;if(o&&h(o)&&f(o).isDirectory())p=Dt(o,g(a));sp(p,d),console.log(`\u2713 Downloaded ${a} (${rr(d.length)}) \u2192 ${p}`)}async function ob(){vf(),Ny();let e=(s)=>rs(s.workspace),t=(s)=>Yr(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 a=t(s);if(a)i.cookie=a;await Gy(e(s),i)};await wl($r(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{let i=rs(s.workspace),a=qe(),c=_f(s._??[],s,{botTokenSource:a?op.get("SLACK_BOT_TOKEN")??$a.get("SLACK_BOT_TOKEN")?.find((l)=>l.val===a)?.path??"shell":void 0,globalPaths:Ra,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!a&&i===a});if(c)console.error(c),process.exit(2)}catch(i){if((i instanceof Error?i.message:String(i)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
447
- `),await ms(),process.exit(0);throw i}},!0).command("agent","Bot agent session status and command heartbeat",(s)=>Ru(s,Gn)).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 Ky(r,s.target,s.limit,i,s.unreplied,t(s));else await qy(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 Jy(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 zy(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),a=t(r),c=r.channel,l=c.startsWith("#")||c.startsWith("@")||c.startsWith("C")||c.startsWith("G")||c.startsWith("D")?c:`#${c}`,u=await ke(i,l,a),d=T(await xn(i,u,a)),f=T(d.channel),h=typeof f.name==="string"?f.name:u,p=f.is_im===!0?"@":"#",m=String(T(f.purpose).value??""),w=String(T(f.topic).value??""),b=f.num_members??f.member_count??"";if(console.log(`${p}${h} ${u}`),w)console.log(`topic: ${w}`);if(m)console.log(`purpose: ${m}`);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),a=t(r),c=r.name.replace(/^#/,"").toLowerCase(),l=r.private===!0,u=r.invite.filter(Boolean),d=await Be(i,a),f=xe(c,String(l),u.join(","),d?.userId??"");if(r.code!==f)Ee(r.code,f,["--- Creating channel -------------------------",_e(d,{pad:9}),` name: ${l?"\uD83D\uDD12 ":"#"}${c}`,` private: ${l}`,...u.length?[` invite: ${u.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await jd(i,c,l,a)}catch(g){console.error(g instanceof Error?g.message:String(g)),process.exit(1)}if(console.log(`\u2713 Created ${l?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),u.length){let g=[];for(let p of u)try{g.push(p.startsWith("U")||p.startsWith("W")?p:await Tt(i,p,a))}catch(m){console.error(` ! could not resolve ${p}: ${m instanceof Error?m.message:String(m)}`)}for(let p of g)try{let m=T(await Un(i,p,a)),w=T(m.user);if(w.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(w.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(g.length)try{await Ud(i,h.id,g,a),console.log(`\u2713 Invited ${g.length} member${g.length===1?"":"s"}`)}catch(p){console.error(` ! invite failed: ${p instanceof Error?p.message:String(p)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name, name, or channel ID (C\u2026/G\u2026)"}).positional("new-name",{type:"string",demandOption:!0,describe:"New channel name (Slack lowercases it; no spaces)"}).option("dry-run",{type:"boolean",default:!1,describe:"Resolve the channel and print old -> new without renaming"}).option("code",{type:"string",describe:"Safety hash to confirm rename"}),async(r)=>{let i=e(r),a=t(r),c=r.channel;if(c.startsWith("@"))console.error(`Error: ${c} is a DM \u2014 only channels can be renamed.`),process.exit(1);let l=c.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(c)?c:`#${c}`,u=r.newName.replace(/^#/,"").toLowerCase(),d,f;try{d=await ke(i,l,a)}catch(m){console.error(`Error: could not resolve channel ${c}: ${m instanceof Error?m.message:String(m)}`),process.exit(1)}try{let m=T(T(await xn(i,d,a)).channel);if(m.is_im===!0||m.is_mpim===!0)console.error(`Error: ${d} is a DM \u2014 only channels can be renamed.`),process.exit(1);f=typeof m.name==="string"?m.name:l.replace(/^#/,"")}catch(m){let w=m instanceof Error?m.message:String(m);if(/channel_not_found/.test(w))console.error(`Error: could not resolve channel ${c}: channel not found (or not visible to this token).`),process.exit(1);f=l.replace(/^#/,"")}if(r.dryRun===!0){console.log(`#${f} -> #${u} (${d})`),console.log("(dry run \u2014 conversations.rename not called)");return}let h=await Be(i,a),g=xe("rename",d,u,h?.userId??"");if(r.code!==g)Ee(r.code,g,["--- Renaming channel -------------------------",_e(h,{pad:9}),` channel: ${d}`,` from: #${f}`,` to: #${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let p;try{p=await Wd(i,d,u,a)}catch(m){let b=(m instanceof Error?m.message:String(m)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],D={name_taken:`Error: a channel named #${u} already exists.`,invalid_name:`Error: "${u}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${u}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${u}" is too long (max 80 chars).`,invalid_name_required:"Error: the new channel name can't be empty.",not_authorized:`Error: this token isn't allowed to rename #${f} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${f} \u2014 join it first.`,is_archived:`Error: #${f} is archived \u2014 unarchive it before renaming.`};console.error((b&&D[b])??ye(m)),process.exit(1)}console.log(`\u2713 Renamed #${f} -> #${p.name} (${p.id})`)}).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,a=e(r),c=t(r),l=await zd(a,c),u=r.filter?.toLowerCase(),d=G(l.members).map(T);if(r.external){let p=new Set(d.map((D)=>String(D.id))),m=T(await Cs(a,c)),w=G(m.channels).map(T).filter((D)=>D.is_ext_shared===!0&&!!D.name),b=new Set;for(let D of w)try{for(let S of await Xd(a,String(D.id),c))if(!p.has(S))b.add(S)}catch{}for(let D of b)try{let S=T(await Un(a,D,c)),F=T(S.user);if(F.id)d.push(F)}catch{}}let f=d.filter((p)=>p.deleted!==!0&&p.is_bot!==!0&&String(p.id)!=="USLACKBOT").filter((p)=>{if(!u)return!0;let m=String(p.name??"").toLowerCase(),w=String(T(p.profile).real_name??"").toLowerCase(),b=String(T(p.profile).email??"").toLowerCase();return m.includes(u)||w.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 m=function(w,b=""){if(w===null)return"null";if(typeof w==="string")return w.includes(`
442
+ slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await mo(e);if(!f.ok)for(let h of yo(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 cp(e,t,n,o){let s;if(n)s=n;else if(t)s=await ke(e,t,o);let i=(await Hd(e,s,o)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let a of i){let c=new Date(a.post_at*1000).toISOString();console.log(`${a.id} ${c} [${a.channel_id}] ${a.text.split(`
443
+ `)[0]?.slice(0,80)??""}`)}}async function lp(e,t){let n;if(t.channelId)n=t.channelId;else n=await ke(e,t.target,t.cookie);let o=await je(e,t.cookie),s=xe(n,t.id,o?.userId??"");if(t.code!==s)Se(t.code,s,["--- Deleting scheduled message ---------------",_e(o,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await zd(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function db(e,t){if(t.comment!==void 0)Ke(t.comment,t.allowUrlAdjacent);let n=vt(e,t.cookie),{statSync:o,existsSync:s}=await import("fs"),{basename:r}=await import("path");for(let g of t.filePaths)if(!s(g))console.error(`Error: file not found: ${g}`),process.exit(1);let{ref:i,threadTs:a}=Vn(t.target),c;if(t.channelId)c=t.channelId;else if(t.userId)c=await Rt(e,t.userId,t.cookie);else c=await ke(e,i,t.cookie);if(await qa(e,c,(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((g)=>{let p=r(g),m=l?p:t.title??p;return{fp:g,filename:p,title:m,sizeFmt:cr(o(g).size)}}),d=await n(),f=xe(c,...u.flatMap((g)=>[g.fp,g.title]),d?.userId??"");if(t.code!==f){let g=` To: ${i}${a?` (thread ${a})`:""}`,p=l?[`--- Uploading ${u.length} files ------------------------`,_e(d,{pad:7}),g,...u.map((m)=>` ${m.filename} (${m.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",_e(d,{pad:7}),g,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];Se(t.code,f,p)}let h=u.length;for(let g=0;g<h;g++){let p=u[g],m={title:p.title};if(a!==void 0)m.threadTs=a;if(t.comment!==void 0&&g===0)m.initialComment=t.comment;let{fileId:w,permalink:b}=await hf(e,c,p.fp,m,t.cookie),D=h>1?`[${g+1}/${h}] `:"";console.log(`${D}\u2713 Uploaded (file_id: ${w}${b?`, url: ${b}`:""})`)}}async function fb(e,t,n){let o=n.channel?await ke(e,n.channel,t):void 0,s=[],r=1,i=1;do{let c={page:r,count:200};if(n.types)c.types=n.types;if(o)c.channel=o;if(n.user)c.user=n.user;let l=T(await Ld(e,c,t));for(let u of G(l.files))s.push(T(u));i=Number(T(l.paging).pages??1),r++}while(s.length<n.limit&&r<=i);let a=s.slice(0,n.limit);if(n.format==="jsonl"){for(let c of a)console.log(JSON.stringify({id:c.id??null,name:c.name??c.title??null,filetype:c.filetype??null,size:c.size??null,user:c.user??null,created:c.created??null,permalink:c.permalink??null}));return}for(let c of a){let l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.title==="string"?c.title:l,d=typeof c.filetype==="string"?c.filetype:"?",f=typeof c.size==="number"?cr(c.size):"";console.log(`${l} ${d.padEnd(7)} ${f.padStart(9)} ${u}`)}}function hr(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 pb(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(T(n).text??T(n).name??T(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 hb(e,t,n,o){let s=hr(n);if(!s)throw Error(`Not a list ID or list URL: ${n}
444
+ `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let c={limit:200};if(i)c.cursor=i;let l=o.asBot?await da(Bs(),s,c):T(await Wd(e,s,c,t));for(let d of G(l.items??l.records))r.push(T(d));let u=T(l.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i&&r.length<o.limit);let a=r.slice(0,o.limit);if(o.format==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let l=String(c.id??""),u=G(c.fields).map(T).map((d)=>{let f=String(d.key??d.column_id??"?"),h=pb(d);return h?`${f}=${h}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function Bs(){let e=qe();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
445
+ `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function gr(e){let t=[];try{t=(await Ct(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).
446
+ `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function gb(e,t){try{let n=await ua(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function vp(e,t){let n=await da(e,t,{limit:1,includeList:!0}),o=wd(T(n.list));if(!o.length)throw Error(`could not read the column schema of list ${t}`);return o}function mr(e){console.error(ye(e)),process.exit(1)}async function mb(e){let t=e.cols.map(md),n=yd(t),o=Bs();await gr(o);let s=await je(o),r=xe("lists-create",e.name,JSON.stringify(n),String(e.todo),s?.userId??"");if(e.code!==r)Se(e.code,r,["--- Creating Slack List ----------------------",_e(s,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((c,l)=>` column: ${c.name} (${c.type}${c.choices?`: ${c.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 Md(o,e.name,n,e.todo)}catch(c){mr(c)}let a=String(i.list_id??T(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${a})`),console.log(await gb(o,a))}async function yb(e){let t=hr(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=Bs();await gr(n);let o=await vp(n,t),r=[{col:o.find((u)=>u.type==="text")??o[0],value:e.text},...na(e.sets).map((u)=>({col:ea(o,u.col),value:u.value}))],i=r.map((u)=>({column_id:u.col.id,...ta(u.col,u.value)})),a=await je(n),c=xe("lists-add",t,JSON.stringify(i),a?.userId??"");if(e.code!==c)Se(e.code,c,["--- Adding a row to Slack List ---------------",_e(a,{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 Nd(n,t,i)}catch(u){mr(u)}console.log(`\u2713 Added row ${String(T(l.item).id??"")} ${e.text}`)}async function wb(e){let t=hr(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=Bs();await gr(n);let o=await vp(n,t),s=na(e.sets).map((c)=>({col:ea(o,c.col),value:c.value}));if(e.done!==void 0){let c=bd(o);if(!c)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);s.push({col:{...c,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((c)=>({row_id:e.row,column_id:c.col.id,...ta(c.col,c.value)})),i=await je(n),a=xe("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==a)Se(e.code,a,["--- Updating Slack List row -----------------",_e(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...s.map((c)=>` ${(c.col.name||c.col.key).padEnd(8)} ${c.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await jd(n,t,r)}catch(c){mr(c)}console.log(`\u2713 Updated row ${e.row}`)}async function bb(e){let t=hr(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=Bs();await gr(n);let o=e.users.length?e.users:e.channels,s=await je(n),r=xe("lists-share",t,e.level,o.join(","),s?.userId??"");if(e.code!==r)Se(e.code,r,["--- Sharing Slack List ----------------------",_e(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 Bd(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){mr(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${o.join(", ")}`)}function Db(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 kb(e,t,n,o){let s=Db(n);if(!s)throw Error(`Not a file ID or file permalink: ${n}
447
+ `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=T(await vd(e,s,t)),i=T(r.file),a=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:s,c=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!c)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(c,{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:g}=await import("path"),p=o??a;if(o&&h(o)&&f(o).isDirectory())p=kt(o,g(a));pp(p,d),console.log(`\u2713 Downloaded ${a} (${cr(d.length)}) \u2192 ${p}`)}async function xb(){Kf(),tw();let e=(s)=>as(s.workspace),t=(s)=>ei(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 a=t(s);if(a)i.cookie=a;await fw(e(s),i)};await Cl(Rr(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{let i=as(s.workspace),a=qe(),c=Pf(s._??[],s,{botTokenSource:a?hp.get("SLACK_BOT_TOKEN")??Ma.get("SLACK_BOT_TOKEN")?.find((l)=>l.val===a)?.path??"shell":void 0,globalPaths:Wa,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!a&&i===a});if(c)console.error(c),process.exit(2)}catch(i){if((i instanceof Error?i.message:String(i)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
448
+ `),await ws(),process.exit(0);throw i}},!0).command("agent","Bot agent session status and command heartbeat",(s)=>Uu(s,Vn)).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 iw(r,s.target,s.limit,i,s.unreplied,t(s));else await cw(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 aw(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 uw(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),a=t(r),c=r.channel,l=c.startsWith("#")||c.startsWith("@")||c.startsWith("C")||c.startsWith("G")||c.startsWith("D")?c:`#${c}`,u=await ke(i,l,a),d=T(await xn(i,u,a)),f=T(d.channel),h=typeof f.name==="string"?f.name:u,p=f.is_im===!0?"@":"#",m=String(T(f.purpose).value??""),w=String(T(f.topic).value??""),b=f.num_members??f.member_count??"";if(console.log(`${p}${h} ${u}`),w)console.log(`topic: ${w}`);if(m)console.log(`purpose: ${m}`);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),a=t(r),c=r.name.replace(/^#/,"").toLowerCase(),l=r.private===!0,u=r.invite.filter(Boolean),d=await je(i,a),f=xe(c,String(l),u.join(","),d?.userId??"");if(r.code!==f)Se(r.code,f,["--- Creating channel -------------------------",_e(d,{pad:9}),` name: ${l?"\uD83D\uDD12 ":"#"}${c}`,` private: ${l}`,...u.length?[` invite: ${u.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await Vd(i,c,l,a)}catch(g){console.error(g instanceof Error?g.message:String(g)),process.exit(1)}if(console.log(`\u2713 Created ${l?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),u.length){let g=[];for(let p of u)try{g.push(p.startsWith("U")||p.startsWith("W")?p:await It(i,p,a))}catch(m){console.error(` ! could not resolve ${p}: ${m instanceof Error?m.message:String(m)}`)}for(let p of g)try{let m=T(await Jn(i,p,a)),w=T(m.user);if(w.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(w.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(g.length)try{await Qd(i,h.id,g,a),console.log(`\u2713 Invited ${g.length} member${g.length===1?"":"s"}`)}catch(p){console.error(` ! invite failed: ${p instanceof Error?p.message:String(p)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name, name, or channel ID (C\u2026/G\u2026)"}).positional("new-name",{type:"string",demandOption:!0,describe:"New channel name (Slack lowercases it; no spaces)"}).option("dry-run",{type:"boolean",default:!1,describe:"Resolve the channel and print old -> new without renaming"}).option("code",{type:"string",describe:"Safety hash to confirm rename"}),async(r)=>{let i=e(r),a=t(r),c=r.channel;if(c.startsWith("@"))console.error(`Error: ${c} is a DM \u2014 only channels can be renamed.`),process.exit(1);let l=c.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(c)?c:`#${c}`,u=r.newName.replace(/^#/,"").toLowerCase(),d,f;try{d=await ke(i,l,a)}catch(m){console.error(`Error: could not resolve channel ${c}: ${m instanceof Error?m.message:String(m)}`),process.exit(1)}try{let m=T(T(await xn(i,d,a)).channel);if(m.is_im===!0||m.is_mpim===!0)console.error(`Error: ${d} is a DM \u2014 only channels can be renamed.`),process.exit(1);f=typeof m.name==="string"?m.name:l.replace(/^#/,"")}catch(m){let w=m instanceof Error?m.message:String(m);if(/channel_not_found/.test(w))console.error(`Error: could not resolve channel ${c}: channel not found (or not visible to this token).`),process.exit(1);f=l.replace(/^#/,"")}if(r.dryRun===!0){console.log(`#${f} -> #${u} (${d})`),console.log("(dry run \u2014 conversations.rename not called)");return}let h=await je(i,a),g=xe("rename",d,u,h?.userId??"");if(r.code!==g)Se(r.code,g,["--- Renaming channel -------------------------",_e(h,{pad:9}),` channel: ${d}`,` from: #${f}`,` to: #${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let p;try{p=await Zd(i,d,u,a)}catch(m){let b=(m instanceof Error?m.message:String(m)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],D={name_taken:`Error: a channel named #${u} already exists.`,invalid_name:`Error: "${u}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${u}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${u}" is too long (max 80 chars).`,invalid_name_required:"Error: the new channel name can't be empty.",not_authorized:`Error: this token isn't allowed to rename #${f} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${f} \u2014 join it first.`,is_archived:`Error: #${f} is archived \u2014 unarchive it before renaming.`};console.error((b&&D[b])??ye(m)),process.exit(1)}console.log(`\u2713 Renamed #${f} -> #${p.name} (${p.id})`)}).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,a=e(r),c=t(r),l=await of(a,c),u=r.filter?.toLowerCase(),d=G(l.members).map(T);if(r.external){let p=new Set(d.map((D)=>String(D.id))),m=T(await As(a,c)),w=G(m.channels).map(T).filter((D)=>D.is_ext_shared===!0&&!!D.name),b=new Set;for(let D of w)try{for(let S of await rf(a,String(D.id),c))if(!p.has(S))b.add(S)}catch{}for(let D of b)try{let S=T(await Jn(a,D,c)),A=T(S.user);if(A.id)d.push(A)}catch{}}let f=d.filter((p)=>p.deleted!==!0&&p.is_bot!==!0&&String(p.id)!=="USLACKBOT").filter((p)=>{if(!u)return!0;let m=String(p.name??"").toLowerCase(),w=String(T(p.profile).real_name??"").toLowerCase(),b=String(T(p.profile).email??"").toLowerCase();return m.includes(u)||w.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 m=function(w,b=""){if(w===null)return"null";if(typeof w==="string")return w.includes(`
448
449
  `)?`|
449
450
  ${w.split(`
450
451
  `).join(`
451
452
  `)}`:w;if(typeof w!=="object")return String(w);if(Array.isArray(w))return w.map((D)=>`
452
453
  ${b} - ${m(D,b+" ")}`).join("");return Object.entries(w).map(([D,S])=>`
453
- ${b} ${D}: ${m(S,b+" ")}`).join("")};console.log("---");for(let[w,b]of Object.entries(p))console.log(`${w}: ${m(b)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,g=f.length?String(T(G(l.members).map(T)[0]??{}).team_id??""):"";for(let p of f){let m=T(p.profile),w=String(p.name??p.id),b=String(p.id??""),D=String(m.display_name||""),S=String(m.real_name||""),F=String(m.email||""),A=String(p.tz??""),x=[...new Set([D,S].filter((I)=>I&&I!==w))].join(" / "),J=A&&A!==h?A:"",ne=String(p.team_id??""),L=p.is_stranger===!0||g&&ne&&ne!==g?`external:${ne||"?"}`:p.is_ultra_restricted===!0?"single-channel guest":p.is_restricted===!0?"guest":"",O=[F,J].filter(Boolean).join(" ");console.log(`@${w} ${b} ${x}${O?" "+O:""}${L?` [${L}]`:""}`)}}).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),a=t(r),c=r.user.startsWith("@")?r.user:`@${r.user}`,l="";try{l=await Tt(i,c,a)}catch(C){console.error(C instanceof Error?C.message:String(C)),process.exit(1)}let u=T(await Un(i,l,a)),d=T(u.user),f=T(d.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,g=String(d.name??l),p=String(d.id??l),m=String(f.display_name||""),w=String(f.real_name||""),b=String(f.email||""),D=String(d.tz??""),S=String(f.phone||""),F=String(f.title||"");console.log(`@${g} ${p}`);let A=[...new Set([m,w].filter((C)=>C&&C!==g))];if(A.length)console.log(`name: ${A.join(" / ")}`);if(b)console.log(`email: ${b}`);if(S)console.log(`phone: ${S}`);if(F)console.log(`title: ${F}`);if(D&&D!==h)console.log(`tz: ${D}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(s)=>s.option("limit",{alias:"l",type:"number",default:20}),async(s)=>{await Hy(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 ap(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)=>{if(!String(s.message??"").trim())console.error("Error: message is empty"),process.exit(1);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 a=t(s);if(a)r.mentionCookie=a}let i;if(s["as-bot"]){let a=qe();if(!a)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
454
- 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 Tt(e(s),r.target,t(s))}catch(c){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
454
+ ${b} ${D}: ${m(S,b+" ")}`).join("")};console.log("---");for(let[w,b]of Object.entries(p))console.log(`${w}: ${m(b)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,g=f.length?String(T(G(l.members).map(T)[0]??{}).team_id??""):"";for(let p of f){let m=T(p.profile),w=String(p.name??p.id),b=String(p.id??""),D=String(m.display_name||""),S=String(m.real_name||""),A=String(m.email||""),F=String(p.tz??""),x=[...new Set([D,S].filter((I)=>I&&I!==w))].join(" / "),W=F&&F!==h?F:"",Q=String(p.team_id??""),M=p.is_stranger===!0||g&&Q&&Q!==g?`external:${Q||"?"}`:p.is_ultra_restricted===!0?"single-channel guest":p.is_restricted===!0?"guest":"",P=[A,W].filter(Boolean).join(" ");console.log(`@${w} ${b} ${x}${P?" "+P:""}${M?` [${M}]`:""}`)}}).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),a=t(r),c=r.user.startsWith("@")?r.user:`@${r.user}`,l="";try{l=await It(i,c,a)}catch(E){console.error(E instanceof Error?E.message:String(E)),process.exit(1)}let u=T(await Jn(i,l,a)),d=T(u.user),f=T(d.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,g=String(d.name??l),p=String(d.id??l),m=String(f.display_name||""),w=String(f.real_name||""),b=String(f.email||""),D=String(d.tz??""),S=String(f.phone||""),A=String(f.title||"");console.log(`@${g} ${p}`);let F=[...new Set([m,w].filter((E)=>E&&E!==g))];if(F.length)console.log(`name: ${F.join(" / ")}`);if(b)console.log(`email: ${b}`);if(S)console.log(`phone: ${S}`);if(A)console.log(`title: ${A}`);if(D&&D!==h)console.log(`tz: ${D}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(s)=>s.option("limit",{alias:"l",type:"number",default:20}),async(s)=>{await lw(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 yp(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)=>{if(!String(s.message??"").trim())console.error("Error: message is empty"),process.exit(1);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 a=t(s);if(a)r.mentionCookie=a}let i;if(s["as-bot"]){let a=qe();if(!a)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
455
+ 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 It(e(s),r.target,t(s))}catch(c){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
455
456
  ${c instanceof Error?c.message:String(c)}
456
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}i=a,r.asBot=!0}else{i=e(s);let a=t(s);if(a)r.cookie=a}try{await Dw(i,r)}catch(a){console.error(ye(a)),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). Lifecycle: --waitFor=<link> collect, --void=<link> \u7121\u52B9\u5316 (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(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("lang",{type:"string",choices:[...yt],describe:"Language of the instructions in the posted body. Default: $SLACK_TERM_LANG, else the answerers' Slack locale, else the question's own language, else the system locale, else ja"}).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), 6 = the question was voided (\u7121\u52B9\u5316, `slack ask void`) \u2014 stop waiting. 7 = only with --explain-exit: \u2139\uFE0F pressed, explain and collect again (the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted (except, on an --explain question someone pressed \u2139\uFE0F on, one thread note per question). Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: the cursor \u2014 everything at or before this ts was already delivered. Text replies there are neither answers nor notes again (pass the `cursor` a previous --json result gave you, or the reply ts an exit 5 printed). Reactions still count."}).option("void",{type:"string",array:!0,describe:"\u7121\u52B9\u5316: void question(s) you posted that expired or stopped meaning anything \u2014 --void=<permalink>, repeatable. The text becomes \uD83D\uDEAB with --reason (body kept, options removed), our pills come off, and --wait/--waitFor on it exits 6. Same --code gate. Only your own questions (--as-bot for the bot's). Alias: `slack ask void <link\u2026>`."}).option("reask",{type:"boolean",default:!1,describe:"With ONE --void: post the question again (same channel/thread, same text and choices unless you give new ones as positionals / --body) and void the old one as replaced by it \u2014 one gate for both. The way to change the options of a question someone already answered."}).option("edit",{type:"string",describe:'Change an open question you posted: --edit=<permalink> ["new question" [choices\u2026]] [--body \u2026]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate.'}).option("ls",{type:"boolean",default:!1,describe:"List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them."}).option("pending",{type:"boolean",default:!1,describe:"List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only: --since 7d, --channel, --json."}).option("since",{type:"string",default:"7d",describe:"With --pending: how far back to look (30m, 2h, 7d, or an ISO date)"}).option("stale",{type:"string",describe:"With --ls: only open questions older than this (24h, 3d)"}).option("state",{type:"string",default:"open",choices:["open","answered","void","edited","gone","unknown","all"],describe:"With --ls: which state to list"}).option("channel",{type:"string",describe:"With --ls / --pending: only this channel (id, or the target as typed)"}).option("limit",{type:"number",default:50,describe:"With --ls: how many recent asks to check"}).option("reason",{type:"string",describe:"With --void: why it is void (written into the message)"}).option("superseded-by",{type:"string",describe:"With --void: permalink of the question that replaces it"}).option("explain",{type:"boolean",describe:"Also offer an \u2139\uFE0F 'explain' pill (seeded after \u2795): pressing it asks YOU to explain the question in its thread and is never an answer \u2014 the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_TERM_ASK_EXPLAIN=1 turns it on; --no-explain turns it off."}).option("explain-exit",{type:"boolean",default:!1,describe:'With --wait / --waitFor: exit 7 (stdout empty; --json status "explain") when someone presses \u2139\uFE0F \u2014 once per question, on the run that posts the thread note. The question stays open: explain, then collect again.'}).option("json",{type:"boolean",default:!1,describe:"With --pending: one JSON object per answered question (sender, answer, collect command). With --wait / --waitFor: print ONE JSON object on stdout \u2014 {status, answer, how, who, notes:[{ts,user,text,permalink}], cursor, permalink} \u2014 instead of the bare answer. `notes` are the audience's replies that are not the answer (thread replies; plain replies too in a 1:1 DM). Exit codes unchanged."}).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. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(s)=>{if(s.ls||s.pending){if(s.ls&&s.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(ce);let p=(()=>{try{return e(s)}catch{return}})(),m={};if(p)m.user=p;let w=qe();if(w)m.bot=w;let b=t(s);if(b)m.cookie=b;if(s.pending){if(s.target||s.question||s.waitFor||s.wait||s.void||s.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(ce);let S=Bo(String(s.since));if(S===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${P(String(s.since))})`),process.exit(ce);let F={sinceMs:S,json:!!s.json};if(s.channel)F.channel=String(s.channel);try{await Lw(m,F)}catch(A){console.error(ye(A)),process.exit(ce)}return}let D={state:String(s.state??"open"),json:!!s.json,limit:Number(s.limit)||50};if(s.stale)D.stale=String(s.stale);if(s.channel)D.channel=String(s.channel);await vw(m,D);return}let r=(p)=>{if(!p){let w=t(s);return w?{token:e(s),cookie:w}:{token:e(s)}}let m=qe();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
457
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ce);return{token:m}},i=s.target!==void 0&&s.target!=="void"&&s.target!=="collect"?String(s.target):void 0,a=[s.question,...s.choices??[]].filter((p)=>p!==void 0).map(String);if(s.edit){if(s.void||s.wait||s.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(ce);let{token:p,cookie:m}=r(!!s["as-bot"]),w={link:String(s.edit),asBot:!!s["as-bot"],mentionToken:p,allowUrlAdjacent:!!s["allow-url-adjacent"]};if(i!==void 0)w.question=i;if(a.length)w.choices=a.map((b)=>b.trim()).filter(Boolean);if(s.body!==void 0)w.body=String(s.body);if(s.lang)w.lang=String(s.lang);if(s.code)w.code=String(s.code);if(m)w.cookie=m,w.mentionCookie=m;try{await Ow(p,w)}catch(b){console.error(ye(b)),process.exit(ce)}return}let c,l=(s.void??[]).map(String).filter(Boolean);if(s.reask){if(l.length!==1||s.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(ce);if(s.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(ce);let{token:p,cookie:m}=r(!!s["as-bot"]),w=await Be(p,m),b=await bp(p,l[0],w,!!s["as-bot"],m);if(b==="void")console.error(`\u2717 ${P(l[0])}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059 \u2014 \u65B0\u3057\u304F\u805E\u304F\u306A\u3089\u666E\u901A\u306B slack ask \u3067`),process.exit(ce);if(!b)process.exit(ce);if(c={...b,reason:Me(String(s.reason??"")).trim()},s.target=b.threadTs?`${b.channelId}:${b.threadTs}`:b.channelId,s["channel-id"]=b.channelId,s.question=i??Jn(b.parsed.question),s.choices=a.length?a:[...b.parsed.reactable,...b.parsed.overflow].map(Jn),s.body===void 0&&b.parsed.body)s.body=Jn(b.parsed.body);if(!s.lang)s.lang=b.parsed.lang;if(s.explain===void 0&&b.parsed.explain)s.explain=!0;s.void=void 0}if(!c&&(s.target==="void"||l.length)){let p=s.target==="void"?[s.question,...s.choices??[]]:[];if(s.target!=="void"&&(s.target||s.question||s.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(ce);let m=[...l,...p.map((S)=>String(S??""))].filter(Boolean);if(!m.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(ce);if(s.wait||s.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(ce);let w,b;if(s["as-bot"]){let S=qe();if(!S)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
458
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ce);w=S}else w=e(s),b=t(s);let D={links:m,reason:Me(String(s.reason??"")).trim(),asBot:!!s["as-bot"]};if(s["superseded-by"])D.supersededBy=String(s["superseded-by"]);if(s.code)D.code=String(s.code);if(b)D.cookie=b;try{await Mw(w,D)}catch(S){console.error(ye(S)),process.exit(ce)}return}if(s.target==="collect"){if(!s.question||s.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(ce);s.waitFor=String(s.question),s.target=void 0,s.question=void 0}let u=s.waitFor?String(s.waitFor):"",d=Number(s.timeout);if(!Number.isFinite(d)||d<0||d===0&&!u)console.error("Error: --timeout must be a positive number of seconds"),process.exit(ce);if(u){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(ce);let p,m;if(s["as-bot"]){let w=qe();if(!w)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
459
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ce);p=w}else p=e(s),m=t(s);try{let w={link:u,timeout:d,asBot:!!s["as-bot"],json:!!s.json};if(s["explain-exit"])w.explainExit=!0;if(m)w.cookie=m;if(s.after){let b=String(s.after);if(!/^\d{10}\.\d{6}$/.test(b))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${P(b)})`),process.exit(ce);w.after=b}await Nw(p,w)}catch(w){console.error(ye(w)),process.exit(ce)}return}if(!s.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(ce);let f=String(s.question??"").trim();if(!f)console.error("Error: question is empty"),process.exit(ce);let h={allowUrlAdjacent:s["allow-url-adjacent"],target:s.target,question:f,choices:(s.choices??[]).map((p)=>String(p).trim()).filter(Boolean),timeout:d};if(s.code)h.code=s.code;if(s.body)h.body=s.body;if(s.lang)h.lang=String(s.lang);if(s.wait)h.wait=!0;if(s.json)h.json=!0;if(typeof s.explain==="boolean")h.explain=s.explain;if(s["explain-exit"])h.explainExit=!0;if(c)h.voidAfter=c;if(s["channel-id"])h.channelId=s["channel-id"];if(s["user-id"])h.userId=s["user-id"];let g;if(s["as-bot"]){let p=qe();if(!p)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
460
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ce);if(!h.channelId&&!h.userId&&h.target.startsWith("@"))try{h.userId=await Tt(p,h.target)}catch(m){console.error(`Error: could not resolve ${h.target} to a user for the bot DM.
457
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}i=a,r.asBot=!0}else{i=e(s);let a=t(s);if(a)r.cookie=a}try{await jw(i,r)}catch(a){console.error(ye(a)),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). Lifecycle: --waitFor=<link> collect, --void=<link> \u7121\u52B9\u5316 (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(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("lang",{type:"string",choices:[...wt],describe:"Language of the instructions in the posted body. Default: $SLACK_TERM_LANG, else the answerers' Slack locale, else the question's own language, else the system locale, else ja"}).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), 6 = the question was voided (\u7121\u52B9\u5316, `slack ask void`) \u2014 stop waiting. 7 = only with --explain-exit: \u2139\uFE0F pressed, explain and collect again (the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted (except, on an --explain question someone pressed \u2139\uFE0F on, one thread note per question). Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: the cursor \u2014 everything at or before this ts was already delivered. Text replies there are neither answers nor notes again (pass the `cursor` a previous --json result gave you, or the reply ts an exit 5 printed). Reactions still count."}).option("void",{type:"string",array:!0,describe:"\u7121\u52B9\u5316: void question(s) you posted that expired or stopped meaning anything \u2014 --void=<permalink>, repeatable. The text becomes \uD83D\uDEAB with --reason (body kept, options removed), our pills come off, and --wait/--waitFor on it exits 6. Same --code gate. Only your own questions (--as-bot for the bot's). Alias: `slack ask void <link\u2026>`."}).option("reask",{type:"boolean",default:!1,describe:"With ONE --void: post the question again (same channel/thread, same text and choices unless you give new ones as positionals / --body) and void the old one as replaced by it \u2014 one gate for both. The way to change the options of a question someone already answered."}).option("edit",{type:"string",describe:'Change an open question you posted: --edit=<permalink> ["new question" [choices\u2026]] [--body \u2026]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate.'}).option("ls",{type:"boolean",default:!1,describe:"List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them."}).option("pending",{type:"boolean",default:!1,describe:"List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only: --since 7d, --channel, --json."}).option("since",{type:"string",default:"7d",describe:"With --pending: how far back to look (30m, 2h, 7d, or an ISO date)"}).option("stale",{type:"string",describe:"With --ls: only open questions older than this (24h, 3d)"}).option("state",{type:"string",default:"open",choices:["open","answered","void","edited","gone","unknown","all"],describe:"With --ls: which state to list"}).option("channel",{type:"string",describe:"With --ls / --pending: only this channel (id, or the target as typed)"}).option("limit",{type:"number",default:50,describe:"With --ls: how many recent asks to check"}).option("reason",{type:"string",describe:"With --void: why it is void (written into the message)"}).option("superseded-by",{type:"string",describe:"With --void: permalink of the question that replaces it"}).option("explain",{type:"boolean",describe:"Also offer an \u2139\uFE0F 'explain' pill (seeded after \u2795): pressing it asks YOU to explain the question in its thread and is never an answer \u2014 the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_TERM_ASK_EXPLAIN=1 turns it on; --no-explain turns it off."}).option("explain-exit",{type:"boolean",default:!1,describe:'With --wait / --waitFor: exit 7 (stdout empty; --json status "explain") when someone presses \u2139\uFE0F \u2014 once per question, on the run that posts the thread note. The question stays open: explain, then collect again.'}).option("json",{type:"boolean",default:!1,describe:"With --pending: one JSON object per answered question (sender, answer, collect command). With --wait / --waitFor: print ONE JSON object on stdout \u2014 {status, answer, how, who, notes:[{ts,user,text,permalink}], cursor, permalink} \u2014 instead of the bare answer. `notes` are the audience's replies that are not the answer (thread replies; plain replies too in a 1:1 DM). Exit codes unchanged."}).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. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(s)=>{if(s.ls||s.pending){if(s.ls&&s.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(ce);let p=(()=>{try{return e(s)}catch{return}})(),m={};if(p)m.user=p;let w=qe();if(w)m.bot=w;let b=t(s);if(b)m.cookie=b;if(s.pending){if(s.target||s.question||s.waitFor||s.wait||s.void||s.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(ce);let S=Wo(String(s.since));if(S===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${O(String(s.since))})`),process.exit(ce);let A={sinceMs:S,json:!!s.json};if(s.channel)A.channel=String(s.channel);try{await nb(m,A)}catch(F){console.error(ye(F)),process.exit(ce)}return}let D={state:String(s.state??"open"),json:!!s.json,limit:Number(s.limit)||50};if(s.stale)D.stale=String(s.stale);if(s.channel)D.channel=String(s.channel);await tb(m,D);return}let r=(p)=>{if(!p){let w=t(s);return w?{token:e(s),cookie:w}:{token:e(s)}}let m=qe();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
458
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ce);return{token:m}},i=s.target!==void 0&&s.target!=="void"&&s.target!=="collect"?String(s.target):void 0,a=[s.question,...s.choices??[]].filter((p)=>p!==void 0).map(String);if(s.edit){if(s.void||s.wait||s.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(ce);let{token:p,cookie:m}=r(!!s["as-bot"]),w={link:String(s.edit),asBot:!!s["as-bot"],mentionToken:p,allowUrlAdjacent:!!s["allow-url-adjacent"]};if(i!==void 0)w.question=i;if(a.length)w.choices=a.map((b)=>b.trim()).filter(Boolean);if(s.body!==void 0)w.body=String(s.body);if(s.lang)w.lang=String(s.lang);if(s.code)w.code=String(s.code);if(m)w.cookie=m,w.mentionCookie=m;try{await eb(p,w)}catch(b){console.error(ye(b)),process.exit(ce)}return}let c,l=(s.void??[]).map(String).filter(Boolean);if(s.reask){if(l.length!==1||s.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(ce);if(s.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(ce);let{token:p,cookie:m}=r(!!s["as-bot"]),w=await je(p,m),b=await Fp(p,l[0],w,!!s["as-bot"],m);if(b==="void")console.error(`\u2717 ${O(l[0])}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059 \u2014 \u65B0\u3057\u304F\u805E\u304F\u306A\u3089\u666E\u901A\u306B slack ask \u3067`),process.exit(ce);if(!b)process.exit(ce);if(c={...b,reason:Ne(String(s.reason??"")).trim()},s.target=b.threadTs?`${b.channelId}:${b.threadTs}`:b.channelId,s["channel-id"]=b.channelId,s.question=i??qn(b.parsed.question),s.choices=a.length?a:[...b.parsed.reactable,...b.parsed.overflow].map(qn),s.body===void 0&&b.parsed.body)s.body=qn(b.parsed.body);if(!s.lang)s.lang=b.parsed.lang;if(s.explain===void 0&&b.parsed.explain)s.explain=!0;s.void=void 0}if(!c&&(s.target==="void"||l.length)){let p=s.target==="void"?[s.question,...s.choices??[]]:[];if(s.target!=="void"&&(s.target||s.question||s.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(ce);let m=[...l,...p.map((S)=>String(S??""))].filter(Boolean);if(!m.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(ce);if(s.wait||s.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(ce);let w,b;if(s["as-bot"]){let S=qe();if(!S)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
459
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ce);w=S}else w=e(s),b=t(s);let D={links:m,reason:Ne(String(s.reason??"")).trim(),asBot:!!s["as-bot"]};if(s["superseded-by"])D.supersededBy=String(s["superseded-by"]);if(s.code)D.code=String(s.code);if(b)D.cookie=b;try{await sb(w,D)}catch(S){console.error(ye(S)),process.exit(ce)}return}if(s.target==="collect"){if(!s.question||s.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(ce);s.waitFor=String(s.question),s.target=void 0,s.question=void 0}let u=s.waitFor?String(s.waitFor):"",d=Number(s.timeout);if(!Number.isFinite(d)||d<0||d===0&&!u)console.error("Error: --timeout must be a positive number of seconds"),process.exit(ce);if(u){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(ce);let p,m;if(s["as-bot"]){let w=qe();if(!w)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
460
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ce);p=w}else p=e(s),m=t(s);try{let w={link:u,timeout:d,asBot:!!s["as-bot"],json:!!s.json};if(s["explain-exit"])w.explainExit=!0;if(m)w.cookie=m;if(s.after){let b=String(s.after);if(!/^\d{10}\.\d{6}$/.test(b))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${O(b)})`),process.exit(ce);w.after=b}await ob(p,w)}catch(w){console.error(ye(w)),process.exit(ce)}return}if(!s.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(ce);let f=String(s.question??"").trim();if(!f)console.error("Error: question is empty"),process.exit(ce);let h={allowUrlAdjacent:s["allow-url-adjacent"],target:s.target,question:f,choices:(s.choices??[]).map((p)=>String(p).trim()).filter(Boolean),timeout:d};if(s.code)h.code=s.code;if(s.body)h.body=s.body;if(s.lang)h.lang=String(s.lang);if(s.wait)h.wait=!0;if(s.json)h.json=!0;if(typeof s.explain==="boolean")h.explain=s.explain;if(s["explain-exit"])h.explainExit=!0;if(c)h.voidAfter=c;if(s["channel-id"])h.channelId=s["channel-id"];if(s["user-id"])h.userId=s["user-id"];let g;if(s["as-bot"]){let p=qe();if(!p)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
461
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ce);if(!h.channelId&&!h.userId&&h.target.startsWith("@"))try{h.userId=await It(p,h.target)}catch(m){console.error(`Error: could not resolve ${h.target} to a user for the bot DM.
461
462
  ${m instanceof Error?m.message:String(m)}
462
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(ce)}g=p,h.mentionToken=p,h.asBot=!0}else{g=e(s),h.mentionToken=g;let p=t(s);if(p)h.cookie=p,h.mentionCookie=p}try{await Iw(g,h)}catch(p){console.error(ye(p)),process.exit(ce)}}).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("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:"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. @tags and an @user target then resolve with the bot token too (needs users:read)."}),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(ct);let i=()=>{let d=qe();if(!d)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
463
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ct);return d};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(ct);let d=e(s),f=t(s);try{let h={link:r};if(s.close)h.close=!0;if(s.names)h.names=!0;if(s["no-notify"])h.noNotify=!0;if(f)h.cookie=f;if(s["as-bot"])h.writeToken=i();await Uw(d,h)}catch(h){console.error(ye(h)),process.exit(ct)}return}if(!s.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(ct);let a=String(s.question??"").trim();if(!a)console.error("Error: question is empty"),process.exit(ct);let c=(s.choices??[]).map((d)=>String(d).trim()).filter(Boolean);if(c.length<2||c.length>jn)console.error(`Error: poll needs 2..${jn} choices (got ${c.length}). For a free-text question use \`slack ask\`.`),process.exit(ct);let l={target:s.target,question:a,choices:c};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["allow-url-adjacent"])l.allowUrlAdjacent=!0;if(s["channel-id"])l.channelId=s["channel-id"];if(s["user-id"])l.userId=s["user-id"];let u;if(s["as-bot"]){let d=i();if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await Tt(d,l.target)}catch(f){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
463
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(ce)}g=p,h.mentionToken=p,h.asBot=!0}else{g=e(s),h.mentionToken=g;let p=t(s);if(p)h.cookie=p,h.mentionCookie=p}try{await Zw(g,h)}catch(p){console.error(ye(p)),process.exit(ce)}}).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("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:"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. @tags and an @user target then resolve with the bot token too (needs users:read)."}),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(ct);let i=()=>{let d=qe();if(!d)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
464
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ct);return d};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(ct);let d=e(s),f=t(s);try{let h={link:r};if(s.close)h.close=!0;if(s.names)h.names=!0;if(s["no-notify"])h.noNotify=!0;if(f)h.cookie=f;if(s["as-bot"])h.writeToken=i();await cb(d,h)}catch(h){console.error(ye(h)),process.exit(ct)}return}if(!s.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(ct);let a=String(s.question??"").trim();if(!a)console.error("Error: question is empty"),process.exit(ct);let c=(s.choices??[]).map((d)=>String(d).trim()).filter(Boolean);if(c.length<2||c.length>Wn)console.error(`Error: poll needs 2..${Wn} choices (got ${c.length}). For a free-text question use \`slack ask\`.`),process.exit(ct);let l={target:s.target,question:a,choices:c};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["allow-url-adjacent"])l.allowUrlAdjacent=!0;if(s["channel-id"])l.channelId=s["channel-id"];if(s["user-id"])l.userId=s["user-id"];let u;if(s["as-bot"]){let d=i();if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await It(d,l.target)}catch(f){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
464
465
  ${f instanceof Error?f.message:String(f)}
465
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(ct)}u=d,l.mentionToken=d,l.asBot=!0}else{u=e(s),l.mentionToken=u;let d=t(s);if(d)l.cookie=d,l.mentionCookie=d}try{await jw(u,l)}catch(d){console.error(ye(d)),process.exit(ct)}}).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=Bo(String(s.since)),r===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${P(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 c=Ly(String(s.cwd));try{i.cwd=vy(c)}catch{i.cwd=c}}if(s.kind)i.kind=s.kind;let a=ta(i);if(!a)console.error(`Error: ${Es}
466
- (${bt()})`),process.exit(1);if(s.json){for(let c of a)console.log(JSON.stringify(c));return}if(!a.length){console.error(`No sent messages match (log: ${bt()}).`);return}for(let c of a)console.log(rw(c))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(s)=>s,async()=>{let s=qe();if(!s)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
467
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await Kw(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("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:"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)=>{if(!String(r.message??"").trim())console.error("Error: message is empty"),process.exit(1);let i={target:r.target,message:r.message,at:r.at};if(r.code)i.code=r.code;if(r["allow-url-adjacent"])i.allowUrlAdjacent=!0;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 a;if(r["as-bot"]){let c=Zo();if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await Tt(e(r),i.target,t(r))}catch(l){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
466
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(ct)}u=d,l.mentionToken=d,l.asBot=!0}else{u=e(s),l.mentionToken=u;let d=t(s);if(d)l.cookie=d,l.mentionCookie=d}try{await ib(u,l)}catch(d){console.error(ye(d)),process.exit(ct)}}).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=Wo(String(s.since)),r===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${O(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 c=Qy(String(s.cwd));try{i.cwd=Zy(c)}catch{i.cwd=c}}if(s.kind)i.kind=s.kind;let a=ra(i);if(!a)console.error(`Error: ${$s}
467
+ (${Dt()})`),process.exit(1);if(s.json){for(let c of a)console.log(JSON.stringify(c));return}if(!a.length){console.error(`No sent messages match (log: ${Dt()}).`);return}for(let c of a)console.log(_w(c))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(s)=>s,async()=>{let s=qe();if(!s)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
468
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await lb(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("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:"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)=>{if(!String(r.message??"").trim())console.error("Error: message is empty"),process.exit(1);let i={target:r.target,message:r.message,at:r.at};if(r.code)i.code=r.code;if(r["allow-url-adjacent"])i.allowUrlAdjacent=!0;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 a;if(r["as-bot"]){let c=er();if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await It(e(r),i.target,t(r))}catch(l){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
468
469
  ${l instanceof Error?l.message:String(l)}
469
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}a=c,i.asBot=!0}else{a=e(r);let c=t(r);if(c)i.cookie=c}await Hw(a,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 a=Zo(),c=r["channel-id"];if(!c&&i?.startsWith("@"))c=await Vf(i,a,e(r),t(r));await Zf(a,i,c);return}await Zf(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 c=Zo();if(!i.channelId&&i.target.startsWith("@"))i.channelId=await Vf(i.target,c,e(r),t(r));i.asBot=!0,await Qf(c,i);return}let a=t(r);if(a)i.cookie=a;await Qf(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("force",{type:"boolean",default:!1,describe:"Apply an edit that BREAKS a `slack ask` / `slack poll` message (new text no longer reads as one, or an answered/void question made open again). Refused by default because collect reads that body back; edits that keep it readable (e.g. writing the \u2705 form) need no flag. Prefer `slack ask --edit=` / `--void=`."}).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.force)r.force=!0;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 a=await qf(r.target,e(s),t(s),r.channelId);if(i=a.botToken,a.channelId&&!r.channelId)r.channelId=a.channelId;r.asBot=!0,r.mentionToken=e(s);let c=t(s);if(c)r.mentionCookie=c}else{i=e(s);let a=t(s);if(a)r.cookie=a}await cw(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 a=await qf(r.target,e(s),t(s),r.channelId);if(i=a.botToken,a.channelId&&!r.channelId)r.channelId=a.channelId;r.asBot=!0}else{i=e(s);let a=t(s);if(a)r.cookie=a}await lw(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(c)=>{if(c["as-bot"]){let u=Zo();if(typeof c.workspace==="string"){let d=t(c),[f,h]=await Promise.all([qt(e(c),d),qt(u)]);if(f.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${c.workspace} is ${f.url}.
470
- Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(c);return{token:e(c),...l?{cookie:l}:{},asBot:!1}},a=(c)=>{console.error(ye(c)),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)",(c)=>c.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(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.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?Vo(void 0,c.file):Vo(c.state,void 0),d=l?c.state:c.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let f=await i(c),h={target:c.channel,state:u,asBot:f.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(d!==void 0)h.log=Me(d);if(f.cookie)h.cookie=f.cookie;if(typeof c.workspace==="string")h.workspace=c.workspace;if(c.code)h.code=c.code;await dw(f.token,h).catch(a)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(c)=>c.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(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.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?Vo(void 0,c.file):Vo(c.state,void 0),d=l?c.state:c.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(c),h={target:c.board,state:u,log:Me(d),adopt:c.adopt,asBot:f.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")h.workspace=c.workspace;if(f.cookie)h.cookie=f.cookie;if(c.code)h.code=c.code;await zf(f.token,h).catch(a)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(c)=>c.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(c)=>{let l=await i(c),u={target:c.board,log:Me(c.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")u.workspace=c.workspace;if(l.cookie)u.cookie=l.cookie;if(c.code)u.code=c.code;await zf(l.token,u).catch(a)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(c)=>c.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(c)=>{let l=await i(c);await hw(l.token,c.board,l.cookie,c.json).catch(a)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(c)=>c.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(c)=>{let l=await i(c);await gw(l.token,c.channel,c.limit,l.cookie).catch(a)}).command("pin <board>",!1,(c)=>c.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(c)=>{let l=await i(c);await mw(l.token,c.board,l.cookie).catch(a)}).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 yw(e(s),r)}catch(a){console.error(ye(a)),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)ma(!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 a=t(r);if(a)i.cookie=a;try{await Yy(e(r),i)}catch(c){console.error(ye(c)),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 a=t(r);if(a)i.cookie=a;try{await Vy(e(r),i)}catch(c){console.error(ye(c)),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:ga,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 a=t(r);if(a)i.cookie=a;await Zy(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)ma(!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("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).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["allow-url-adjacent"])r.allowUrlAdjacent=!0;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 zw(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 Xw(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 Zw(i)}catch(i){console.error(ye(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 Qw(i)}catch(i){console.error(ye(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 eb(i)}catch(i){console.error(ye(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 tb(i)}catch(i){console.error(ye(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 a=r.asBot===!0;await Yw(a?"":e(r),a?void 0:t(r),r.ref,{limit:r.limit,format:i,asBot:a})}catch(a){console.error(ye(a)),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 sb(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 Qy(e(s),s.days,s.limit,s.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (read-only; requires xoxc desktop token). Not `slack todo` (reaction tasks)",(s)=>s.command(["$0","ls","list"],"List your To-dos, soonest due first",(r)=>r.option("filter",{type:"string",choices:[...sf],default:"todo",describe:"todo = open to-dos; saved = everything saved; completed; archived"}).option("limit",{alias:"n",type:"number",default:50,describe:"At most this many items"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per item (raw fields + permalink + message text)"}),async(r)=>{if(!Number.isInteger(r.limit)||r.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${r.limit}).`),process.exit(2);await nw(e(r),t(r),{filter:r.filter,limit:r.limit,json:r.json})})).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 tw(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:[]}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Je(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await ke(i,r.channel,a),u=await Yd(i,l,c,a);console.log(`\u2713 Draft created (id: ${T(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await sw(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"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Je(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await As(i,a),u=G(l.drafts).map(T).find((p)=>String(p.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=tr(u),f=await Be(i,a),h=xe(d,c,f?.userId??"");if(r.code!==h)Ee(r.code,h,["--- Editing draft as -------------------------",_e(f),"--- Current draft ----------------------------",...d.split(`
470
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}a=c,i.asBot=!0}else{a=e(r);let c=t(r);if(c)i.cookie=c}await ub(a,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 a=er(),c=r["channel-id"];if(!c&&i?.startsWith("@"))c=await ip(i,a,e(r),t(r));await cp(a,i,c);return}await cp(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 c=er();if(!i.channelId&&i.target.startsWith("@"))i.channelId=await ip(i.target,c,e(r),t(r));i.asBot=!0,await lp(c,i);return}let a=t(r);if(a)i.cookie=a;await lp(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("force",{type:"boolean",default:!1,describe:"Apply an edit that BREAKS a `slack ask` / `slack poll` message (new text no longer reads as one, or an answered/void question made open again). Refused by default because collect reads that body back; edits that keep it readable (e.g. writing the \u2705 form) need no flag. Prefer `slack ask --edit=` / `--void=`."}).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.force)r.force=!0;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 a=await ep(r.target,e(s),t(s),r.channelId);if(i=a.botToken,a.channelId&&!r.channelId)r.channelId=a.channelId;r.asBot=!0,r.mentionToken=e(s);let c=t(s);if(c)r.mentionCookie=c}else{i=e(s);let a=t(s);if(a)r.cookie=a}await Aw(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 a=await ep(r.target,e(s),t(s),r.channelId);if(i=a.botToken,a.channelId&&!r.channelId)r.channelId=a.channelId;r.asBot=!0}else{i=e(s);let a=t(s);if(a)r.cookie=a}await Fw(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(c)=>{if(c["as-bot"]){let u=er();if(typeof c.workspace==="string"){let d=t(c),[f,h]=await Promise.all([Ct(e(c),d),Ct(u)]);if(f.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${c.workspace} is ${f.url}.
471
+ Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(c);return{token:e(c),...l?{cookie:l}:{},asBot:!1}},a=(c)=>{console.error(ye(c)),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)",(c)=>c.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(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.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?Qo(void 0,c.file):Qo(c.state,void 0),d=l?c.state:c.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let f=await i(c),h={target:c.channel,state:u,asBot:f.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(d!==void 0)h.log=Ne(d);if(f.cookie)h.cookie=f.cookie;if(typeof c.workspace==="string")h.workspace=c.workspace;if(c.code)h.code=c.code;await Rw(f.token,h).catch(a)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(c)=>c.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(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.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?Qo(void 0,c.file):Qo(c.state,void 0),d=l?c.state:c.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(c),h={target:c.board,state:u,log:Ne(d),adopt:c.adopt,asBot:f.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")h.workspace=c.workspace;if(f.cookie)h.cookie=f.cookie;if(c.code)h.code=c.code;await np(f.token,h).catch(a)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(c)=>c.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(c)=>{let l=await i(c),u={target:c.board,log:Ne(c.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")u.workspace=c.workspace;if(l.cookie)u.cookie=l.cookie;if(c.code)u.code=c.code;await np(l.token,u).catch(a)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(c)=>c.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(c)=>{let l=await i(c);await Pw(l.token,c.board,l.cookie,c.json).catch(a)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(c)=>c.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(c)=>{let l=await i(c);await vw(l.token,c.channel,c.limit,l.cookie).catch(a)}).command("pin <board>",!1,(c)=>c.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(c)=>{let l=await i(c);await Lw(l.token,c.board,l.cookie).catch(a)}).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 Mw(e(s),r)}catch(a){console.error(ye(a)),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)$a(!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 a=t(r);if(a)i.cookie=a;try{await pw(e(r),i)}catch(c){console.error(ye(c)),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 a=t(r);if(a)i.cookie=a;try{await hw(e(r),i)}catch(c){console.error(ye(c)),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:_a,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 a=t(r);if(a)i.cookie=a;await gw(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)$a(!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("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).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["allow-url-adjacent"])r.allowUrlAdjacent=!0;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 db(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 fb(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 mb(i)}catch(i){console.error(ye(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 yb(i)}catch(i){console.error(ye(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 wb(i)}catch(i){console.error(ye(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 bb(i)}catch(i){console.error(ye(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 a=r.asBot===!0;await hb(a?"":e(r),a?void 0:t(r),r.ref,{limit:r.limit,format:i,asBot:a})}catch(a){console.error(ye(a)),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 kb(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 mw(e(s),s.days,s.limit,s.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(s)=>s.command(["$0","ls","list"],"List your To-dos, soonest due first",(r)=>r.option("filter",{type:"string",choices:[...mf],default:"todo",describe:"todo = open to-dos; saved = everything saved; completed; archived"}).option("limit",{alias:"n",type:"number",default:50,describe:"At most this many items"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per item (raw fields + permalink + message text)"}),async(r)=>{if(!Number.isInteger(r.limit)||r.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${r.limit}).`),process.exit(2);await bw(e(r),t(r),{filter:r.filter,limit:r.limit,json:r.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"Due time (ISO datetime or Unix ts)"}).option("saved",{type:"boolean",default:!1,describe:"Save it without a checkbox instead of as a to-do"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(r)=>{let i=r.due===void 0?void 0:ap(r.due);await Zo(e(r),t(r),r.target,{kind:"add",...i?{due:i}:{},saved:r.saved},r.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("undo",{type:"boolean",default:!1,describe:"Mark it not done again"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(r)=>{await Zo(e(r),t(r),r.target,{kind:"done",undo:r.undo},r.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"New due time (ISO datetime or Unix ts), or `none` to clear it"}).option("todo",{type:"boolean",describe:"Make it a to-do (with a checkbox)"}).option("saved",{type:"boolean",describe:"Make it a plain saved item (no checkbox)"}).conflicts("todo","saved").option("code",{type:"string",describe:"Confirmation code from the preview"}),async(r)=>{let i=r.due===void 0?void 0:r.due==="none"?0:ap(r.due),a=r.todo?!0:r.saved?!1:void 0;await Zo(e(r),t(r),r.target,{kind:"edit",...i===void 0?{}:{due:i},...a===void 0?{}:{todo:a}},r.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(r)=>{await Zo(e(r),t(r),r.target,{kind:"rm"},r.code)})).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 ww(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:[]}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Ke(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await ke(i,r.channel,a),u=await lf(i,l,c,a);console.log(`\u2713 Draft created (id: ${T(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await Sw(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"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Ke(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await Ts(i,a),u=G(l.drafts).map(T).find((p)=>String(p.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=sr(u),f=await je(i,a),h=xe(d,c,f?.userId??"");if(r.code!==h)Se(r.code,h,["--- Editing draft as -------------------------",_e(f),"--- Current draft ----------------------------",...d.split(`
471
472
  `).map((p)=>` ${p}`),"--- Replacing with ---------------------------",...c.split(`
472
- `).map((p)=>` ${p}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let g=await Vd(i,r.id,Oa(u),c,a);console.log(`\u2713 Draft updated (id: ${T(g.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),a=t(r),c=await As(i,a),l=G(c.drafts).map(T).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=tr(l),d=await Be(i,a),f=xe(r.id,u,d?.userId??"");if(r.code!==f)Ee(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",_e(d),` id: ${r.id}`,...u.split(`
473
- `).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await ef(i,r.id,a),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(rs(r.workspace));return}await au({...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=rs(r.workspace),a=i.startsWith("xoxc-")?Yr(r.workspace):void 0,c=[["SLACK_TOKEN",i]];if(a)c.push(["SLACK_COOKIE",a]);let l=c.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(`
474
- `))}).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 cu({...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 Ci({...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 $i({...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 ms({...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 ms({...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)=>lu({...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)=>uu({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=Gr();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:a,current:c}of r)console.log(`${c?"* ":" "}${i} ${a.team} (${a.user}) ${a.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)My(Dt(process.cwd(),".slack-cli"));_l(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)=>{El(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 iu({...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 $i({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(s)=>s.option("grep",{alias:"e",type:"string",demandOption:!0,describe:"Regex matched against each message's text (raw, e.g. <@U00000001>). Non-matching messages are never printed or logged"}).option("ignore-case",{alias:"i",type:"boolean",default:!1,describe:"Case-insensitive --grep"}).option("channel",{type:"array",string:!0,describe:"Only these channels (#name, id or permalink); repeatable"}).option("replies-to",{type:"array",string:!0,describe:"Also print replies in threads this id started or replied in (user U\u2026/bot B\u2026; `self` = the streaming identity), --grep or not; repeatable"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per match: type, channel{id,name}, ts, thread_ts, user{id,name}, text, permalink, match (grep | replies-to)"}).option("once",{type:"boolean",default:!1,describe:"Scan once from the saved cursor (or --since) and exit: 0 = matches printed, 2 = none, 3 = failure"}).option("since",{type:"string",describe:"Replay from this long ago (e.g. 30m, 2h), ignoring the saved cursor"}).option("interval",{type:"string",default:"45s",describe:"Poll interval (e.g. 30s, 2m)"}).option("thread-window",{type:"string",default:"3d",describe:"Watch replies in threads whose parent is at most this old"}).option("thread-scan",{type:"string",default:"3m",describe:"Polling: re-read each channel's whole --thread-window this often (cycles in between read only what is new)"}).option("calls-per-min",{type:"number",default:40,describe:"Polling: pace conversations.history/replies to this many calls per minute (0 = unpaced)"}).option("state",{type:"string",describe:"Cursor file (default: one per identity+grep+channels under $XDG_STATE_HOME/slack-term/stream/)"}).option("as-user",{type:"boolean",default:!1,describe:"Stream as the user identity (sees the user's DMs) instead of the bot"}).option("relay",{type:"boolean",default:!0,describe:"Use the doorbell relay (worker/) when SLACK_RELAY_URL and SLACK_RELAY_TOKEN are set; --no-relay polls only"}).option("reconcile",{type:"string",default:"5m",describe:"While the relay is connected, poll this rarely as a safety net"}),async(s)=>{let r,i,a,c,l,u;try{r=new RegExp(s.grep,s["ignore-case"]?"i":""),a=Wt(s.interval)*1000,c=Wt(s["thread-window"]),l=Wt(s["thread-scan"]),u=s.since!==void 0?Wt(s.since):void 0,i=Wt(s.reconcile)*1000}catch(I){console.error(`slack stream: ${I instanceof Error?I.message:String(I)}`),process.exit(1)}let d=qe(),f=s["as-user"]===!0||!d,h=f?e(s):d,g=f?t(s):void 0;if(!d&&s["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let p;try{p=await qt(h,g)}catch(I){console.error(`slack stream: fatal: ${I instanceof Error?I.message:String(I)}`),process.exit(3)}let m=new Set([p.userId].filter(Boolean)),w=new Set([p.botId].filter(Boolean));if(f&&d)try{let I=await qt(d);if(I.userId)m.add(I.userId);if(I.botId)w.add(I.botId)}catch{}let b;if(s["replies-to"]?.length){b=new Set;for(let I of s["replies-to"].map(String)){if(I==="self"){for(let W of[p.userId,p.botId])if(W)b.add(W);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(I))console.error(`slack stream: --replies-to: "${I}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(b.add(I),I.startsWith("B"))try{let{userId:W}=await xd(h,I,g);if(W)b.add(W)}catch(W){console.error(`slack stream: --replies-to ${I}: cannot resolve its bot user id (${W instanceof Error?W.message:String(W)}); threads where it shows as a user id are missed`)}}}let D;if(s.channel?.length)try{D=[];for(let I of s.channel)D.push(await ke(h,String(I),g))}catch(I){console.error(`slack stream: --channel: ${I instanceof Error?I.message:String(I)}`),process.exit(1)}let S=ep("sha256").update(JSON.stringify([p.url,p.userId,r.source,r.flags,[...D??[]].sort(),...s["replies-to"]?.length?[[...s["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),F=process.env.XDG_STATE_HOME||Dt(Ca(),".local","state"),A=s.state??Dt(F,"slack-term","stream",`${S}.json`);console.error(`slack stream: as ${f?"user":"bot"} @${p.user} (${p.userId}); state ${A}`);let C=process.env.SLACK_RELAY_URL,x=process.env.SLACK_RELAY_TOKEN,J=s.relay&&!f&&!s.once&&C&&x?{url:C,subscribe:Cu(C,x),reconcileMs:i}:void 0;if(s.relay&&f&&C)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let ne=!s.relay?"--no-relay":f?C?"--as-user: the relay only rings for the bot's channels":"streaming as the user; the relay serves the bot identity":"SLACK_RELAY_URL / SLACK_RELAY_TOKEN not set",L=new AbortController;process.on("SIGINT",()=>L.abort()),process.on("SIGTERM",()=>L.abort());let O=await Eu(xu(h,g),{grep:r,...b?{repliesTo:b}:{},...D?{channels:D}:{},selfUsers:m,selfBots:w,json:s.json,once:s.once,...u!==void 0?{sinceSec:u}:{},intervalMs:a,threadWindowSec:c,threadScanSec:l,callsPerMin:s["calls-per-min"],...J?{}:{pollReason:ne},statePath:A,teamUrl:p.url,identity:p.userId,signal:L.signal,...J?{relay:J}:{}});process.exit(O)}).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),a=new AbortController;process.on("SIGINT",()=>{a.abort(),process.exit(0)}),await mu(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}:{}},a.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 ms({...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()}ob().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
473
+ `).map((p)=>` ${p}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let g=await uf(i,r.id,Ja(u),c,a);console.log(`\u2713 Draft updated (id: ${T(g.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),a=t(r),c=await Ts(i,a),l=G(c.drafts).map(T).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=sr(l),d=await je(i,a),f=xe(r.id,u,d?.userId??"");if(r.code!==f)Se(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",_e(d),` id: ${r.id}`,...u.split(`
474
+ `).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await pf(i,r.id,a),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(as(r.workspace));return}await mu({...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=as(r.workspace),a=i.startsWith("xoxc-")?ei(r.workspace):void 0,c=[["SLACK_TOKEN",i]];if(a)c.push(["SLACK_COOKIE",a]);let l=c.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(`
475
+ `))}).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 yu({...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 Ti({...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 Ri({...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 ws({...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 ws({...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)=>wu({...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)=>bu({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=Qr();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:a,current:c}of r)console.log(`${c?"* ":" "}${i} ${a.team} (${a.user}) ${a.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)ew(kt(process.cwd(),".slack-cli"));Pl(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)=>{Ol(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 gu({...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 Ri({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(s)=>s.option("grep",{alias:"e",type:"string",demandOption:!0,describe:"Regex matched against each message's text (raw, e.g. <@U00000001>). Non-matching messages are never printed or logged"}).option("ignore-case",{alias:"i",type:"boolean",default:!1,describe:"Case-insensitive --grep"}).option("channel",{type:"array",string:!0,describe:"Only these channels (#name, id or permalink); repeatable"}).option("replies-to",{type:"array",string:!0,describe:"Also print replies in threads this id started or replied in (user U\u2026/bot B\u2026; `self` = the streaming identity), --grep or not; repeatable"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per match: type, channel{id,name}, ts, thread_ts, user{id,name}, text, permalink, match (grep | replies-to)"}).option("once",{type:"boolean",default:!1,describe:"Scan once from the saved cursor (or --since) and exit: 0 = matches printed, 2 = none, 3 = failure"}).option("since",{type:"string",describe:"Replay from this long ago (e.g. 30m, 2h), ignoring the saved cursor"}).option("interval",{type:"string",default:"45s",describe:"Poll interval (e.g. 30s, 2m)"}).option("thread-window",{type:"string",default:"3d",describe:"Watch replies in threads whose parent is at most this old"}).option("thread-scan",{type:"string",default:"3m",describe:"Polling: re-read each channel's whole --thread-window this often (cycles in between read only what is new)"}).option("calls-per-min",{type:"number",default:40,describe:"Polling: pace conversations.history/replies to this many calls per minute (0 = unpaced)"}).option("state",{type:"string",describe:"Cursor file (default: one per identity+grep+channels under $XDG_STATE_HOME/slack-term/stream/)"}).option("as-user",{type:"boolean",default:!1,describe:"Stream as the user identity (sees the user's DMs) instead of the bot"}).option("relay",{type:"boolean",default:!0,describe:"Use the doorbell relay (worker/) when SLACK_RELAY_URL and SLACK_RELAY_TOKEN are set; --no-relay polls only"}).option("reconcile",{type:"string",default:"5m",describe:"While the relay is connected, poll this rarely as a safety net"}),async(s)=>{let r,i,a,c,l,u;try{r=new RegExp(s.grep,s["ignore-case"]?"i":""),a=Kt(s.interval)*1000,c=Kt(s["thread-window"]),l=Kt(s["thread-scan"]),u=s.since!==void 0?Kt(s.since):void 0,i=Kt(s.reconcile)*1000}catch(I){console.error(`slack stream: ${I instanceof Error?I.message:String(I)}`),process.exit(1)}let d=qe(),f=s["as-user"]===!0||!d,h=f?e(s):d,g=f?t(s):void 0;if(!d&&s["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let p;try{p=await Ct(h,g)}catch(I){console.error(`slack stream: fatal: ${I instanceof Error?I.message:String(I)}`),process.exit(3)}let m=new Set([p.userId].filter(Boolean)),w=new Set([p.botId].filter(Boolean));if(f&&d)try{let I=await Ct(d);if(I.userId)m.add(I.userId);if(I.botId)w.add(I.botId)}catch{}let b;if(s["replies-to"]?.length){b=new Set;for(let I of s["replies-to"].map(String)){if(I==="self"){for(let U of[p.userId,p.botId])if(U)b.add(U);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(I))console.error(`slack stream: --replies-to: "${I}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(b.add(I),I.startsWith("B"))try{let{userId:U}=await Od(h,I,g);if(U)b.add(U)}catch(U){console.error(`slack stream: --replies-to ${I}: cannot resolve its bot user id (${U instanceof Error?U.message:String(U)}); threads where it shows as a user id are missed`)}}}let D;if(s.channel?.length)try{D=[];for(let I of s.channel)D.push(await ke(h,String(I),g))}catch(I){console.error(`slack stream: --channel: ${I instanceof Error?I.message:String(I)}`),process.exit(1)}let S=up("sha256").update(JSON.stringify([p.url,p.userId,r.source,r.flags,[...D??[]].sort(),...s["replies-to"]?.length?[[...s["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),A=process.env.XDG_STATE_HOME||kt(La(),".local","state"),F=s.state??kt(A,"slack-term","stream",`${S}.json`);console.error(`slack stream: as ${f?"user":"bot"} @${p.user} (${p.userId}); state ${F}`);let E=process.env.SLACK_RELAY_URL,x=process.env.SLACK_RELAY_TOKEN,W=s.relay&&!f&&!s.once&&E&&x?{url:E,subscribe:Mu(E,x,void 0,{transport:vu(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:i}:void 0;if(s.relay&&f&&E)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let Q=!s.relay?"--no-relay":f?E?"--as-user: the relay only rings for the bot's channels":"streaming as the user; the relay serves the bot identity":"SLACK_RELAY_URL / SLACK_RELAY_TOKEN not set",M=new AbortController;process.on("SIGINT",()=>M.abort()),process.on("SIGTERM",()=>M.abort());let P=await Ou(Ru(h,g),{grep:r,...b?{repliesTo:b}:{},...D?{channels:D}:{},selfUsers:m,selfBots:w,json:s.json,once:s.once,...u!==void 0?{sinceSec:u}:{},intervalMs:a,threadWindowSec:c,threadScanSec:l,callsPerMin:s["calls-per-min"],...W?{}:{pollReason:Q},statePath:F,teamUrl:p.url,identity:p.userId,signal:M.signal,...W?{relay:W}:{}});process.exit(P)}).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),a=new AbortController;process.on("SIGINT",()=>{a.abort(),process.exit(0)}),await _u(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}:{}},a.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 ws({...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()}xb().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});