UNPKG

coffee-ahk

Version:
2 lines (1 loc) 38.1 kB
import{at as e,read as t,getDirname as n,glob as s,getName as i,write as r}from"fire-keeper";import{compile as o}from"coffeescript";import{trim as a}from"radash";import c from"cson";import l from"iconv-lite";import u from"kleur";const p=["..","?","?.","bin?","from","func_exist","import"];class f{#e=[];next="";constructor(...e){this.reload(...e)}get first(){return this.at(0)??""}get last(){return this.at(-1)??""}get length(){return this.#e.length}get list(){return[...this.#e]}at(t){return e(this.#e,t)}isEqual(e){const t=e instanceof f?e.list:e;return this.#e.length===t.length&&this.#e.every(((e,n)=>e===t[n]))}pop(){return this.#e.pop()??""}push(...e){return this.#e.push(...e)}reload(e=[]){this.#e=e instanceof f?e.list:e}shift(){return this.#e.shift()??""}slice(...e){return this.#e.slice(...e)}unshift(...e){return this.#e.unshift(...e)}}class d{comment;scope;type;value;constructor(...e){if(e[0]instanceof d){const{scope:t,type:n,value:s}=e[0];return this.type=n,this.value=s,void(this.scope=new f(t))}this.type=e[0]??"void",this.value=(void 0===e[1]?e[0]:e[1])??"",this.scope=new f(e[2])}clone(){const{scope:e,type:t,value:n}=this;return new d(t,n,e)}is(e,t){return e===this.type&&(void 0===t||t===this.value)}}const h=(e,t=e.content.length-1)=>{const{content:n}=e,s=n.at(t);return s?s.is("edge","parameter-start")?t:h(e,t-1):0},g=(e,t)=>{let n=e.substring(1,e.length-1);return n=n.replace(/%/g,"`%").replace(/\\b/g,"`b").replace(/\\n/g,"`n").replace(/\\r/g,"`r").replace(/\\t/g,"`t"),n=`"${n.replace(/"/g,'""')}"`,n=3===t.length?n.replace(/\s*\n\s*/g,""):n.replace(/\s*\n\s*/g," "),n},y={"new-line":e=>{const{content:t,scope:n,type:s,value:i}=e;if("terminator"===s){if("\n"===i)return t.last.is("bracket","}-")&&(t.last.value="}"),["array","call","object","parameter"].includes(n.last)?(t.last.is("sign",",")||(t.last.is("new-line")&&t.pop(),t.push("sign",",")),!0):(t.push("new-line",e.indent.toString()),!0);if(";"===i)return t.last.is("bracket","}-")&&(t.last.value="}"),t.push("new-line",e.indent.toString()),!0}return!1},alias:e=>{const{content:t,type:n}=e;return"@"===n?(t.push("this"),!0):"::"===n&&(t.last.is(".")&&t.pop(),t.push(".").push("prototype"),!0)},array:e=>{const{content:t,scope:n,type:s}=e;return"["===s?(n.push("array"),t.push("edge","array-start"),!0):"]"===s&&(n.pop(),t.push("edge","array-end"),!0)},await:e=>{const{content:t,type:n}=e;return"await"===n&&(t.push("await"),!0)},boolean:e=>{const{content:t,type:n,value:s}=e;return"bool"===n&&(t.push("boolean",s),!0)},bracket:e=>{const{content:t,type:n,value:s}=e;return("("===n||")"===n)&&(t.push("bracket",s),!0)},class:e=>{const{content:t,scope:n,type:s}=e;return"class"===s?(n.next="class",t.push("class"),!0):"super"===s&&(t.push("super"),!0)},comment:e=>{const{content:t,token:n}=e;if(n.comments){const e=[];n.comments.forEach((t=>a(t.content,"\n ").split("\n").forEach((t=>e.push(t)))));const{last:s}=t;return s.comment=e,!0}return!1},do:e=>{const{content:t,type:n}=e;return("do"===n||"do_iife"===n)&&(t.push("native","__mark:do__"),!0)},for:e=>{const{content:t,scope:n,type:s,value:i}=e;if("for"===s)return n.push("for"),t.push("for"),!0;if(["forin","forof"].includes(s)){const e=[],n=t.pop();e.push(n.value);if(t.last.is("sign",",")){t.pop();const n=t.pop();e.unshift(n.value)}return"forin"===s&&e.reverse(),1===e.length&&e.unshift("forin"===s?"__index_for__":"__key_for__"),t.push("identifier",e[0]).push("sign",",").push("identifier",e[1]).push("for-in",i),!0}return!1},forbidden:e=>{const{type:t}=e;if(p.includes(t))throw new Error(`ahk/forbidden: '${t}' is not allowed`);if("post_if"===t)throw new Error("ahk/forbidden: 'post-if' is not allowed");return!1},function:e=>{const{content:t,scope:n,type:s}=e;if(["->","=>"].includes(s))return((e,t)=>{const{content:n,scope:s}=e;if(n.last.is("edge","parameter-end")){if("=>"===t){const t=[...s.list,"parameter"];n.list.splice(h(e)+1,0,new d("this","this",t),new d("sign","=",t),new d("this","this",t),new d("sign",",",t))}}else n.at(-2)?.is("property","constructor")||n.push("identifier","anonymous"),s.push("parameter"),n.push("edge","parameter-start"),"=>"===t&&n.push("this").push("sign","=").push("this"),n.push("edge","parameter-end"),s.pop();return s.push("function"),!0})(e,s);if("call_start"===s){e.flag.isFunctionIncluded=!0;const{next:s}=n;return n.next="",n.push("call"),n.next=s,t.push("edge","call-start"),!0}if("call_end"===s){const e=[t.at(-3),t.at(-2),t.at(-1)];if(e[0]?.is("identifier","Native")&&e[1]?.is("edge","call-start")&&e[2]?.is("string")){e[0].type="void",e[1].type="void",e[2].scope.pop(),e[2].type="native";const{value:s}=e[2];return e[2].value=s.substring(1,s.length-1).replace(/`%/g,"%").replace(/"{2,}/g,'"'),t.push("void","call-end"),n.pop(),!0}return t.push("edge","call-end"),n.pop(),!0}return"param_start"===s?(e=>{const{content:t,scope:n}=e;return t.at(-2)?.is("property","constructor")||t.push("identifier","anonymous"),n.push("parameter"),t.push("edge","parameter-start"),!0})(e):"param_end"===s&&(t.push("edge","parameter-end"),n.pop(),!0)},if:e=>{const{content:t,scope:n,type:s,value:i}=e;return"if"===s?(n.next="if",t.push("if"),"unless"===i&&t.push("logical-operator","!"),t.push("edge","expression-start"),!0):"else"===s&&("switch"===n.last?(n.push("case"),t.push("new-line",e.indent.toString()).push("if","default"),!0):(n.next="else",t.push("if","else"),!0))},indent:e=>{const{content:t,scope:n,type:s}=e;if("indent"===s){if(t.last.is("sign","="))return!0;if(["array","call","object","parameter"].includes(n.last))return!0;e.indent++;const{last:s}=n;if(["case","for","function","switch"].includes(s)&&(["catch","class","else","if","while"].includes(n.next)||("case"===s&&t.push("sign",":"),t.push("edge","block-start"))),["catch","class","else"].includes(n.next)){const e=n.next;n.next="",n.push(e),t.push("edge","block-start")}if(["if","while"].includes(n.next)){t.push("edge","expression-end");const e=n.next;n.next="",n.push(e),t.push("edge","block-start")}return t.push("new-line",e.indent.toString()),!0}return"outdent"===s&&(t.last.is("bracket","}-")?(t.last.value="}",!0):!!["array","call","object","parameter"].includes(n.last)||(e.indent--,!n.length||(t.push("new-line",e.indent.toString()).push("edge","block-end"),n.pop(),!0)))},indentifier:e=>{const{content:t,type:n,value:s}=e;return"identifier"===n&&(t.push("identifier",s),!0)},module:e=>{const{content:t,type:n}=e;return"export"===n&&(t.push("statement","export"),!0)},native:e=>{const{content:t,type:n,value:s}=e;return"js"===n&&(t.push("native",s),!0)},nil:e=>{const{content:t,type:n}=e;return!!["nan","null","undefined"].includes(n)&&(t.push("string",'""'),!0)},number:e=>{const{content:t,type:n,value:s}=e;if("number"===n){let e=s;if(s.includes("n"))throw new Error("ahk/forbidden: 'BigInt' is not allowed");if(s.includes("_")&&(e=e.replace(/_/g,"")),s.includes("e")){const[t,n]=e.split("e");e=`${t}${"0".repeat(parseInt(n,10))}`}return t.push("number",e),!0}return!1},object:e=>{const{content:t,scope:n,token:s,type:i}=e;return"{"===i?"class"===n.last&&!t.last.is("sign","=")||(t.last.is("new-line")&&s.generated&&t.pop(),n.push("object"),t.push("bracket","{"),!0):"}"===i&&("class"===n.last||(s.generated&&"number"==typeof s.origin?.indentSize?t.push("bracket","}-"):t.push("bracket","}"),n.pop()),!0)},operator:e=>{const{content:t,token:n,type:s,value:i}=e;if("+"===s){if(!n.spaced){const{last:e}=t;if("math"===e.type||"negative"===e.type)return"negative"===e.type&&(e.type="math"),t.push("negative","+"),!0}return t.push("math","+"),!0}if("-"===s){if(!n.spaced){const{last:e}=t;if(!["identifier","math"].includes(e.type))return"negative"===e.type&&(e.type="math"),t.push("negative","-"),!0}return t.push("math","-"),!0}return"++"===s?(t.push("++"),!0):"--"===s?(t.push("--"),!0):"**"===s?(t.push("math","**"),!0):"&&"===s||"||"===s?(t.push("logical-operator",i),!0):"unary"===s&&"!"===i||"unary_math"===s?(t.push("logical-operator","!"),!0):"compare"===s?(t.push("compare",i),!0):("compound_assign"===s||"math"===s)&&(t.push("math",i),!0)},property:e=>{const{content:t,type:n,value:s}=e;return"."===n?(t.push("."),!0):"index_start"===n?("."===t.last.type&&t.pop(),t.push("edge","index-start"),!0):"index_end"===n?(t.push("edge","index-end"),!0):"property"===n&&(["prototype","this"].includes(t.last.type)&&t.push("."),t.push("property",s),!0)},sign:e=>{const{content:t,scope:n,type:s}=e;if("..."===s){if(!["call","parameter"].includes(n.last))throw new Error("ahk/forbidden: '...' is not allowed");t.push("sign","...")}return"="===s?(t.push("sign","="),!0):","===s?(t.push("sign",","),!0):":"===s&&("class"===n.last?(t.push("sign","="),!0):(t.push("sign",":"),!0))},statement:e=>{const{content:t,type:n,value:s}=e;return"extends"===n?(t.push("statement","extends"),!0):"return"===n?(t.push("statement","return"),!0):"throw"===n?(t.push("statement","throw"),!0):"statement"!==n||"break"!==s&&"continue"!==s?"unary"===n&&"new"===s&&(t.push("statement","new"),!0):(t.push("statement",s),!0)},string:e=>{const{content:t,token:n,type:s,value:i}=e;return"string"===s?(t.push("string",g(i,n[1].quote??"")),!0):"interpolation_start"===s?(t.push("edge","interpolation-start"),!0):"interpolation_end"===s&&(t.push("edge","interpolation-end"),!0)},switch:e=>{const{content:t,scope:n,type:s}=e;return"switch"===s?(n.push("switch"),t.push("if","switch"),!0):"leading_when"===s&&(n.push("case"),t.push("if","case"),!0)},try:e=>{const{content:t,scope:n,type:s}=e;return"catch"===s?(n.next="catch",t.push("try","catch"),!0):"finally"===s?(t.push("try","finally"),n.push("finally"),t.push("edge","block-start"),!0):"try"===s&&(t.push("try"),n.push("try"),t.push("edge","block-start"),!0)},while:e=>{const{content:t,scope:n,type:s}=e;return"loop"===s?(n.next="while",t.push("while").push("edge","expression-start").push("boolean","true"),!0):"while"===s?(n.next="while",t.push("while").push("edge","expression-start"),!0):"until"===s&&(n.next="while",t.push("while").push("logical-operator","!").push("edge","expression-start"),!0)}},w=e=>{for(const t of Object.keys(y))if("comment"!==t&&y[t](e))break;y.comment(e)};class v{#e=[];scope;constructor(e){this.scope=e}get last(){return this.at(-1)??new d}get length(){return this.#e.length}get list(){return[...this.#e]}at(t){return e(this.#e,t)}pop(){return this.#e.pop()??new d}push(...e){const t=new d(...e);return t.scope.length||t.scope.reload(this.scope),this.#e.push(t),this}reload(e=this.#e){return this.#e=e.filter((e=>!e.is("void"))),this}shift(){return this.#e.shift()??new d}unshift(...e){const t=new d(...e);return t.scope.length||t.scope.reload(this.scope),this.#e.unshift(t),this}}const m=t=>{(e=>{const{content:t}=e,n=`__ci_${e.options.salt}__`;let s=0;const i=(e,n,r=[])=>{const o=t.at(n);return o?(r.push(o),o.is("edge","index-start")&&o.scope.isEqual(e.scope)?(s++,i(e,n+1,r)):o.is("edge","index-end")&&o.scope.isEqual(e.scope)?(s--,0===s?[n,r]:i(e,n+1,r)):i(e,n+1,r)):(s=0,[n,r])},r=(e,n)=>{const s=t.list;s.splice(e[0],e[1]-e[0]+1,...n),t.reload(s)};let o=-1,a=t.length;for(;o<a;){o++,a=t.length;const s=t.at(o);if(!s?.is("edge","index-start"))continue;const c=t.at(o+1);if(!c)continue;if(c.is("identifier",n))continue;if(c.is("edge","index-end"))continue;const[l,u]=i(s,o),p=u.slice(1,u.length-1);let h="number";for(const e of p){if([".","identifier","property","this"].includes(e.type)){h="identifier";break}if("string"===e.type){h="string";break}}if("identifier"!==h)if("number"!==h);else{const e=p[0];r([o+1,l-1],1===p.length?[new d(e.type,(parseFloat(e.value)+1).toString(),e.scope)]:[...p,new d("math","+",e.scope),new d("number","1",e.scope)])}else{e.flag.isChangeIndexUsed=!0;const t=[...p],s=t[0].scope,i=new f([...s.list,"call"]);r([o+1,l-1],[new d("identifier",n,s),new d("edge","call-start",i),...t,new d("edge","call-end",i)])}}})(t),(t=>{const{content:n}=t;let s=[];const i="__array__";let r=[];const o=e=>{const t=n.at(e);return t?"new-line"===t.type?parseInt(t.value,10):o(e-1):0},a=(t,s=[[]])=>{const i=n.at(t);if(!i)return s;const o=e(s,-1);return o?i.is("edge","array-start")?s:(i.is("sign",",")?s.push([]):o.unshift(i),r.pop(),a(t-1,s)):s};n.list.forEach(((e,t)=>{if(s.length&&"new-line"===e.type){const n=o(t-1);return s.forEach(((t,o)=>r=[...r,...[["new-line",n.toString()],...s[s.length-o-1].map((e=>[e.type,e.value])),["sign","="],["identifier",i],["edge","index-start"],["number",(o+1).toString()],["edge","index-end"]].map((t=>new d(t[0],t[1],e.scope)))])),s.length=0,void r.push(e)}e.is("sign","=")&&n.at(t-1)?.is("edge","array-end")?(s=a(t-2),r=r.slice(0,r.length-2),r=[...r,new d("identifier",i,e.scope),new d("sign","=",e.scope)]):r.push(e)})),n.reload(r)})(t)},_=[{type:"native",value:"global ",scope:[]},{type:"identifier",value:"__ci_salt__",scope:[]},{type:"sign",value:"=",scope:[]},{type:"function",value:"anonymous",scope:[]},{type:"edge",value:"parameter-start",scope:["parameter"]},{type:"identifier",value:"__ipt__",scope:["parameter"]},{type:"edge",value:"parameter-end",scope:["parameter"]},{type:"edge",value:"block-start",scope:["function"]},{type:"new-line",value:"1",scope:["function"]},{type:"native",value:"if __ipt__ is Number",scope:["function"]},{type:"new-line",value:"1",scope:["function"]},{type:"native",value:" return __ipt__ + 1",scope:["function"]},{type:"new-line",value:"1",scope:["function"]},{type:"statement",value:"return",scope:["function"]},{type:"identifier",value:"__ipt__",scope:["function"]},{type:"new-line",value:"0",scope:["function"]},{type:"edge",value:"block-end",scope:["function"]},{type:"new-line",value:"0",scope:[]}].map((e=>new d(e.type,e.value,e.scope))),b=[{type:"native",value:"global ",scope:[]},{type:"identifier",value:"__rf_salt__",scope:[]},{type:"sign",value:"=",scope:[]},{type:"function",value:"anonymous",scope:[]},{type:"edge",value:"parameter-start",scope:["parameter"]},{type:"identifier",value:"__fn__",scope:["parameter"]},{type:"sign",value:",",scope:["parameter"]},{type:"identifier",value:"__token__",scope:["parameter"]},{type:"edge",value:"parameter-end",scope:["parameter"]},{type:"edge",value:"block-start",scope:["function"]},{type:"new-line",value:"1",scope:["function"]},{type:"if",value:"if",scope:["function"]},{type:"edge",value:"expression-start",scope:["function"]},{type:"identifier",value:"__fn__",scope:["function"]},{type:"edge",value:"expression-end",scope:["function"]},{type:"edge",value:"block-start",scope:["function","if"]},{type:"new-line",value:"2",scope:["function","if"]},{type:"statement",value:"return",scope:["function","if"]},{type:"identifier",value:"__fn__",scope:["function","if"]},{type:"new-line",value:"1",scope:["function","if"]},{type:"edge",value:"block-end",scope:["function","if"]},{type:"new-line",value:"1",scope:["function"]},{type:"statement",value:"throw",scope:["function"]},{type:"identifier",value:"Exception",scope:["function"]},{type:"edge",value:"call-start",scope:["function","call"]},{type:"string",value:'"invalid function: "',scope:["function","call"]},{type:"edge",value:"interpolation-start",scope:["function","call"]},{type:"identifier",value:"__token__",scope:["function","call"]},{type:"edge",value:"interpolation-end",scope:["function","call"]},{type:"string",value:'""',scope:["function","call"]},{type:"edge",value:"call-end",scope:["function","call"]},{type:"new-line",value:"0",scope:["function"]},{type:"edge",value:"block-end",scope:["function"]},{type:"new-line",value:"0",scope:[]}].map((e=>new d(e.type,e.value,e.scope))),S=(e,t,n)=>{const{content:s}=e;if(e.flag[t]){const t=n.map((e=>new d(e.type,e.value,e.scope)));if(!t.length)return;t[1].value=t[1].value.replace(/_salt_/g,`_${e.options.salt}_`),s.reload([...t,...s.list])}},k=["Class","Function","Native"],E=e=>{const t=(e=>{const{content:t}=e,n=new Set;return t.list.forEach(((e,s)=>{if("class"!==e.type)return;const i=t.at(s+1);if(!i)throw new Error("Unexpected error: picker/class/count/1");"identifier"===i.type&&n.add(i.value)})),n})(e);(e=>{e.forEach((e=>{if(k.includes(e))throw new Error(`ahk/forbidden: class name '${e}' is not allowed`)}))})(t)},x=(e,t=1)=>{const{content:n}=e;n.reload();const s=((e,t)=>{if(!Array.isArray(e))return-1;const n="function"==typeof t?t:"string"==typeof t||"number"==typeof t?e=>Boolean(e[t]):"object"==typeof t?e=>{for(const n in t)if(e[n]!==t[n])return!1;return!0}:null;if(!n)return-1;for(let t=e.length-1;t>=0;t--)if(n(e[t],t,e))return t;return-1})(n.list,{type:"function",value:"anonymous"});if(!~s)return;const i=n.at(s);if(!i)throw new Error("Unexpected error: picker/function/anonymous/1");i.value=`${e.options.salt}_${t}`,C(e,t,s,[...i.scope.list,"function"]).forEach((e=>{"void"!==e.type&&n.push(e)})),x(e,t+1)},C=(e,t,n,s,i=[])=>{const{content:r}=e,o=r.at(n);if(!o)return i;const a=o.clone();for(let e=0;e<s.length-1;e++)a.scope.shift();if(i.push(a),!o.is("edge","block-end")||!o.scope.isEqual(s))return o.type="void",C(e,t,n+1,s,i);o.type="native",o.value=`Func("${e.options.salt}_${t}")`,i.push(new d("new-line","0",s));const c=parseInt(i[((e,t)=>{if(!Array.isArray(e))return-1;const n="function"==typeof t?t:"string"==typeof t||"number"==typeof t?e=>Boolean(e[t]):"object"==typeof t?e=>{for(const n in t)if(e[n]!==t[n])return!1;return!0}:null;if(!n)return-1;for(let t=0;t<e.length;t++)if(n(e[t],t,e))return t;return-1})(i,{type:"new-line"})].value,10)-1;return c>0&&i.forEach((e=>{if("new-line"!==e.type)return;let t=parseInt(e.value,10)-c;t>=0||(t=0),e.value=t.toString()})),i},W=e=>{const{content:t}=e,n=[];t.list.forEach((e=>{if("native"!==e.type||!e.value.startsWith("Func(")||!e.value.endsWith(")"))return void n.push(e);const t=e.scope.list;t.pop(),n.push(new d("identifier","Func",t)),n.push(new d("edge","call-start",[...t,"call"])),n.push(new d("string",e.value.slice(5,e.value.length-1),[...t,"call"])),n.push(new d("edge","call-end",[...t,"call"]))})),t.reload(n)},$=(e,t,n)=>{const{content:s}=e,i=s.at(t);return i?i.is("edge","parameter-start")&&n.scope.isEqual([...i.scope.slice(0,i.scope.length-1),"function"])?t:$(e,t-1,n):0},F=e=>{I(e),(e=>{const{content:t}=e,n=[];t.list.forEach(((s,i)=>{if(n.push(s),!s.is("edge","block-end"))return;if("function"!==s.scope.at(-1))return;if("class"!==s.scope.at(-2))return;const r=$(e,i,s);if(t.at(r-1)?.is("property","constructor"))return;const o=[s.scope.list];o[1]=[...o[0],"call"],n.push(new d(".",".",o[0])),n.push(new d("identifier","Bind",o[0])),n.push(new d("edge","call-start",o[1])),n.push(new d("this","this",o[1])),n.push(new d("edge","call-end",o[1]))})),t.reload(n)})(e),j(e),(e=>{const{content:t}=e,n=[];t.list.forEach(((e,s)=>{if(n.push(e),!e.is("super"))return;const i=t.at(s+1);if(!i?.is("edge","call-start"))return;const r=i.scope.list;n.push(new d(".",".",r),new d("property","__New",r))})),t.reload(n)})(e)},I=t=>{const{content:n}=t,s=[];n.list.forEach(((t,i)=>{if(s.push(t),!t.is("edge","parameter-start"))return;if(e(s,-3)?.is("property","constructor"))return void(s[s.length-2].type="void");if("class"!==t.scope.at(-1)&&("parameter"!==t.scope.at(-1)||"class"!==t.scope.at(-2)))return;const r=t.scope.list;s.push(new d("this","this",r));const o=n.at(i+1);o?.is("edge","parameter-end")||s.push(new d("sign",",",r))})),n.reload(s)},j=e=>{const{content:t}=e;t.list.forEach((e=>{e.is("property","constructor")&&(e.value="__New")}))},A=[],M=[],G=[];let L=0;const R=(e,t,n)=>{const{content:s}=e,i=s.at(n);return i?i.is("edge","block-end")&&i.scope.isEqual(t.scope)?n:R(e,t,n+1):0},O=e=>{const{content:t}=e;L=0,M.length=0,A.length=0,G.length=0,t.list.forEach(((t,n)=>L?(L--,void M.push(new d("void","",[]))):G.length&&t.is("edge","block-start")?(M.push(t),((e,t,n)=>{const s=[t.scope.slice(0,t.scope.length-1)];s[1]=[...s[0],"call"];let i=[];for(const e of G){for(const t of e)t.scope.reload(t.scope.list.join(",").replace(/^.*?parameter/u,s[1].join(",")).split(",")),i.push(t);i.push(new d("sign",",",s[1]))}i.pop(),i=[new d(".",".",s[0]),new d("identifier","Bind",s[0]),new d("edge","call-start",s[1]),...i,new d("edge","call-end",s[1])],A.push([R(e,t,n)+1,i])})(e,t,n),void(G.length=0)):void(T(e,t,n)||M.push(t))));for(const[e,t]of((e,...t)=>{if(!Array.isArray(e))return[];if(0===t.length)return[...e];const n=t.map((e=>"function"==typeof e?e:"string"==typeof e||"number"==typeof e?t=>t[e]:()=>{}));return[...e].sort(((e,t)=>{for(const s of n){const n=s(e),i=s(t);if(null!=n||null!=i){if(null==n)return-1;if(null==i)return 1;if(typeof n==typeof i){if(n<i)return-1;if(n>i)return 1}else{const e=String(n),t=String(i);if(e<t)return-1;if(e>t)return 1}}}return 0}))})(A,(e=>e[0])).reverse())M.splice(e,0,...t);t.reload(M)},T=(e,t,n)=>{const{content:s}=e;if(!t.is("sign","="))return!1;if("parameter"!==t.scope.at(-1))return!1;const i=s.at(n+1);if(!i)return!1;if(!["identifier","this"].includes(i.type))return!1;const r=s.at(n-1);return!!r&&(!!["identifier","this"].includes(r.type)&&(M.push(new d("void")),G.push(B(e,i,n+1)),L=G[G.length-1].length,!0))},B=(e,t,n,s=[])=>{const{content:i}=e,r=i.at(n);return r?r.scope.isEqual(t.scope)&&(r.is("sign",",")||r.is("edge","parameter-end"))?s:(s.push(r),B(e,t,n+1,s)):s},D=e=>{const{content:t}=e,n=new Set;return t.list.forEach((e=>{e.is("function")&&n.add(e.value)})),n},N=new Map,q=new Set,P=(e,t)=>{const{content:n}=e,s=n.at(t);return s?.is("edge","block-start")?t:P(e,t+1)},U=(e,t,n)=>{const{content:s}=e,i=s.at(t);if(!i?.is("edge","block-end")||!i.scope.isEqual([...n.scope.slice(0,n.scope.length-1),"function"])){if(i?.is("identifier")&&!N.get(i.value)){const e=s.at(t-1);if(!e)return;const n=s.at(t+1);if(!n)return;N.set(i.value,e.is("for","for")||n.is("sign","=")||n.is("for-in")||"parameter"===i.scope.at(-1))}U(e,t+1,n)}},H=(e,t,n)=>{const{content:s}=e,i=s.at(t);if(!i?.is("edge","parameter-end")||!i.scope.isEqual(n.scope)){if(i?.is("identifier")){const e=s.at(t+1);if(!e)return;(e.is("sign","=")||e.is("sign",",")||e.is("sign","...")||e.is("edge","parameter-end"))&&q.add(i.value)}H(e,t+1,n)}},K=e=>{const{content:t}=e,n=[];t.list.forEach(((e,s)=>{e.is("sign",",")&&t.at(s+1)?.is("edge","parameter-end")||n.push(e)})),t.reload(n)},V=(e,t)=>{const{content:n}=e,s=n.at(t);return s?.is("edge","block-start")&&"function"===s.scope.at(-1)?[t,s.scope]:V(e,t+1)},z=(e,t)=>{const{content:n}=e,{i:s,list:i,scope:r}=t,o=n.at(s);if(!o)return i;i.push(o);return o.is("edge","block-end")&&o.scope.isEqual(r)?i:z(e,{i:s+1,list:i,scope:r})},J=(e,t)=>{const{content:n}=e;n.list.forEach(((e,s)=>{"identifier"===e.type&&"call"===e.scope.at(-1)&&t.has(e.value)&&(n.at(s+1)?.is("edge","call-start")||(e.type="native",e.value=`Func("${e.value}")`))}))},Q=t=>{const{countBracket:n,hasIdentifier:s,i:i,list:r,result:o,scope:a}=t,c=e(r,i);if(!c)return[i,o];o.unshift(c);const l=c.is("bracket")?"("===c.value?n-1:n+1:n,u=["identifier","super","this"].includes(c.type)||s;return 0===l&&u&&c.scope.isEqual(a)?[i,o]:Q({countBracket:l,hasIdentifier:u,i:i-1,list:r,result:o,scope:a})},X=e=>{(e=>{const{content:t}=e;t.list.forEach((e=>{e.type}))})(e),(e=>{const{content:t}=e;t.list.forEach(((e,n)=>{if(!e.is("edge","parameter-start"))return;const s=t.at(n-1);s?.is("identifier")&&(s.type="function")}))})(e);let t=D(e);F(e),(e=>{const{content:t}=e,n=[];t.list.forEach(((s,i)=>{if(n.push(s),!s.is("edge","parameter-start"))return;if(t.at(i-1)?.is("property","__New"))return;const r=P(e,i);q.clear(),N.clear(),H(e,i,s),U(e,r,s),N.forEach(((t,i)=>{t||q.has(i)||e.cache.global.has(i)||i.startsWith("__")&&i.endsWith("__")||i[0].toLowerCase()===i[0]&&n.push(...[["identifier",i],["sign","="],["identifier",i],["sign",","]].map((e=>new d(e[0],e[1],s.scope))))}))})),t.reload(n),K(e)})(e),(e=>{const{content:t}=e,n={i:-1,scope:new f,isObjectWithoutBrackets:!1},s=[];t.list.forEach(((i,r)=>{if(s.push(i),r===n.i)return n.isObjectWithoutBrackets&&s.push(new d("new-line",n.scope.length.toString(),n.scope)),void s.push(new d("statement","return",n.scope));if(!i.is("edge","parameter-start"))return;if(t.at(r-1)?.is("property","__New"))return;const[o,a]=V(e,r),c=z(e,{i:o,list:[],scope:a}),l=c[1].is("bracket","{");c.filter((e=>e.is("new-line")&&e.scope.isEqual(a))).length>(l?1:2)||(e=>!!(e.is("for")||e.is("if")||e.is("native")&&"__mark:do__"!==e.value||e.is("statement")&&"new"!==e.value||e.is("try")||e.is("while")))(c[2])||(n.i=o+(l?0:1),n.scope=a,n.isObjectWithoutBrackets=l)})),t.reload(s)})(e),O(e),e.options.anonymous&&t.has("anonymous")&&((e=>{x(e),W(e)})(e),t=D(e)),((e,t)=>{J(e,t)})(e,t),(e=>{const{content:t}=e;let n=!1;const s=[];t.list.forEach((e=>{if(n&&(e.is("new-line")||e.is("bracket","}")||e.is("bracket",")"))){n=!1;const t=[...e.scope.list,"call"];s.push(new d("bracket",")",e.scope),new d("edge","call-start",t),new d("edge","call-end",t),e)}else e.is("native","__mark:do__")?(n=!0,s.push(new d("bracket","(",e.scope))):s.push(e)})),t.reload(s)})(e),e.options.track&&(e=>{const{content:t}=e,n=`__rf_${e.options.salt}__`,s=[],i=[];t.list.forEach(((e,n)=>{if(!e.is("edge","call-start"))return;const r=t.at(n-1);if(!r)return;if(r.is("function"))return;if(r.is("super"))return;const[o,a]=Q({countBracket:0,hasIdentifier:!1,i:n-1,list:t.list,result:[],scope:r.scope}),c=a.filter((e=>e.is("identifier")||e.is("property"))),l=c[c.length-1];var u;l.value.startsWith("__")||(u=l.value).startsWith(u[0].toLowerCase())&&(s.push(o),i.push(n-1))}));const r=[];let o=0;t.list.forEach(((t,a)=>{s.includes(a)&&r.push(new d("identifier",n,t.scope),new d("edge","call-start",[...t.scope.list,"call"])),r.push(t),i.includes(a)&&r.push(new d("sign",",",t.scope),new d("string",`"#rf/${e.options.salt}/${++o}"`,t.scope),new d("edge","call-end",[...t.scope.list,"call"]))})),t.reload(r)})(e)},Y=e=>{(e=>{const{content:t}=e,n=[],s="__object__";let i=[];const r=e=>{const n=t.at(e);return n?"new-line"===n.type?parseInt(n.value,10):r(e-1):0},o=e=>{const s=t.at(e);s&&(s.is("bracket","{")||(s.is("identifier")&&n.push(s.value),i.pop(),o(e-1)))};t.list.forEach(((e,a)=>{if(n.length&&"new-line"===e.type){const t=r(a-1),o=e.scope;for(let e=0;e<n.length;e++)i=[...i,new d("new-line",t.toString(),o),new d("identifier",n[n.length-e-1],o),new d("sign","=",o),new d("identifier",s,o),new d("edge","index-start",o),new d("string",`"${n[n.length-e-1]}"`,o),new d("edge","index-end",o)];return n.length=0,void i.push(e)}e.is("sign","=")&&t.at(a-1)?.is("bracket","}")?(o(a),i=[...i,new d("identifier",s,e.scope),new d("sign","=",e.scope)]):i.push(e)})),t.reload(i)})(e),(e=>{const{content:t}=e,n=[];t.list.forEach(((e,s)=>{if(n.push(e),!e.is("identifier"))return;if("object"!==e.scope.at(-1))return;const i=t.at(s-1);if(!i)return;if(!i.is("bracket","{")&&!i.is("sign",","))return;const r=t.at(s+1);r&&(r.is("bracket","}")||r.is("sign",","))&&n.push(new d("sign",":",e.scope.list),new d("identifier",e.value,e.scope.list))})),t.reload(n)})(e)};const Z=["ACos","ASin","ATan","Abs","Asc","AutoTrim","Bind","BlockInput","Break","Catch","Ceil","Chr","Click","ComObjActive","ComObjAddRef","ComObjArray","ComObjConnect","ComObjCreate","ComObjError","ComObjFlags","ComObjGet","ComObjQuery","ComObjRelease","ComObjType","ComObjValue","Continue","Control","ControlClick","ControlSend","ControlSendRaw","CoordMode","Cos","Critical","DetectHiddenText","DetectHiddenWindows","DllCall","Drive","DriveGet","DriveSpaceFree","Edit","Else","EnvAdd","EnvDiv","EnvGet","EnvMult","EnvSet","EnvSub","EnvUpdate","Error","ErrorLevel","Exception","Exit","ExitApp","Exp","File","FileAppend","FileCopy","FileCopyDir","FileCreateDir","FileCreateShortcut","FileDelete","FileEncoding","FileExist","FileGetAttrib","FileGetShortcut","FileGetSize","FileGetTime","FileGetVersion","FileInstall","FileMove","FileMoveDir","FileOpen","FileRead","FileReadLine","FileRecycle","FileRecycleEmpty","FileRemoveDir","FileSelectFile","FileSelectFolder","FileSetAttrib","FileSetTime","Finally","Floor","Format","FormatTime","Func","GetKeyName","GetKeySC","GetKeyState","GetKeyVK","Gosub","Goto","GroupActivate","Gui","GuiControl","GuiControlGet","Hotkey","Hotstring","If","IfExist","IfInString","IfMsgBox","IfNotExist","IfNotInString","IfWinActive","IfWinExist","IfWinNotActive","IfWinNotExist","ImageSearch","InStr","Include","IncludeAgain","IniDelete","IniRead","IniWrite","Input","InputBox","InputHook","InstallKeybdHook","InstallMouseHook","IsByRef","IsFunc","IsLabel","IsObject","KeyHistory","KeyWait","LTrim","ListLines","ListVars","Ln","LoadPicture","Log","Loop","Max","Menu","MenuGetHandle","MenuGetName","Min","Mod","MouseClick","MouseClickDrag","MouseGetPos","MouseMove","MsxBox","NumGet","NumPut","OnClipboardChange","OnError","OnExit","OnMessage","Ord","OutputDebug","Pause","PixelGetColor","PixelSearch","Process","Progress","RTrim","Random","RegDelete","RegExMatch","RegRead","RegWrite","RegisterCallback","Reload","Return","Round","Run","RunAs","Send","SendEvent","SendInput","SendLevel","SendMode","SendPlay","SetBatchLines","SetCapsLockState","SetControlDelay","SetDefaultMouseSpeed","SetFormat","SetKeyDelay","SetMouseDelay","SetNumLockState","SetRegView","SetScrollLockState","SetStoreCapsLockMode","SetTimer","SetTitleMatchMode","SetWinDelay","SetWorkingDir","ShutDown","Sin","Sleep","Sort","SoundBeep","SoundGet","SoundGetWaveVolume","SoundPlay","SoundSet","SoundSetWaveVolume","SplashImage","SplitPath","Sqrt","StrGet","StrLen","StrPut","StrReplace","StrSplit","StringCaseSense","StringGetPos","StringLeft","StringLen","StringLower","StringMid","StringReplace","StringRight","StringSplit","StringTrimLeft","StringTrimRight","StringUpper","SubStr","Suspend","Switch","SysGet","Tan","Thread","Throw","ToolTip","Transform","TrayTip","Trim","Try","URLDownloadToFile","Until","VarSetCapacity","Warn","While","WinActivate","WinActivateBottom","WinActive","WinClose","WinExist","WinGetTitle","WinSet","WinWait","WinWaitActive","WinWaitClose"].map((e=>e.toLowerCase())),ee=e=>{(e=>{const{content:t}=e;t.list.forEach(((e,n)=>{if(!e.is("identifier"))return;const s=t.at(n+1);if(!s?.is("sign","="))return;const i=e.value.toLowerCase();if(i.startsWith("a_")||Z.includes(i))throw new Error(`ahk/forbidden: variable name '${e.value}' is not allowed`)}))})(e),(e=>{const{content:t}=e,n=new Set;let s=0;const i=[];t.list.forEach(((e,r)=>{if(s)return void s--;if(i.push(e),!e.is("sign","="))return;const o=t.at(r-1);if(o?.is("identifier")&&!o.scope.length&&(!(r-2>=0)||t.at(r-2)?.is("new-line"))&&!n.has(o.value)){if(n.add(o.value),t.at(r+1)?.is("identifier",o.value)&&t.at(r+2)?.is("new-line"))return i.splice(i.length-2,2),void(s=2);i.splice(i.length-2,0,new d("native","global ",e.scope))}})),t.reload(i),e.cache.global=n})(e),(e=>{const{content:t}=e,n=[];t.list.forEach(((e,s)=>{if(!e.is("statement","new"))return void n.push(e);const i=t.at(s+1);i?.is("identifier","Error")?i.value="Exception":n.push(e)})),t.reload(n)})(e)},te=e=>{(e=>{const{content:t}=e;t.reload(t.list.filter(((e,n)=>!((e,t,n)=>{if(!t.is("new-line"))return!1;const s=e.at(n-1);return!(!s||!s.is("bracket","(")&&!s.is("sign","="))})(t,e,n))))})(e),(e=>{const{content:t}=e,n=e=>{const s=t.at(e);return s?s.is("edge","block-start")&&"for"===s.scope.at(-1)?e:n(e+1):0},s=e=>{const n=t.at(e);if(!n)return"";if(n.is("for","for")){const n=t.at(e+1);if(!n)throw new Error("Unexpected error: picker/for/2");return n.value}return s(e-1)},i=[];if(t.list.forEach(((e,r)=>{if(!e.is("for-in","in"))return;const o=s(r);if(o.startsWith("__")&&o.endsWith("__"))return;const a=n(r),c=t.at(a+1);if(!c)throw new Error("Unexpected error: picker/for/1");const l=c.value,{scope:u}=c;i.unshift([a+1,[new d("new-line",l,u),new d("identifier",o,u),new d("sign","=",u),new d("identifier",o,u),new d("math","-",u),new d("number","1",u)]])})),i.length){const e=t.list;for(const t of i)e.splice(t[0],0,...t[1]);t.reload(e)}})(e),m(e),Y(e),ee(e),(e=>{e.options.builtins&&(S(e,"isChangeIndexUsed",_),e.options.track&&S(e,"isFunctionIncluded",b))})(e),E(e),X(e)},ne={"array-end":"]","array-start":"[","block-end":"}","block-start":"{","call-end":")","call-start":"(","expression-end":")","expression-start":"(","index-end":"]","index-start":"[","interpolation-end":") . ","interpolation-start":" . (","parameter-end":")","parameter-start":"("};let se=[];const ie=e=>{const{i:t,it:n}=e,s=e.content.at(t+1);return s?.is("new-line")?n.value:`${n.value} `},re=e=>{let t=parseInt(e.it.value,10);return t>=0||(t=0),`\n${" ".repeat(2*t)}`},oe=(e,t)=>{if(!t.options.comments)return e;const{i:n,it:s}=t;if(!se.length)return e;if("new-line"!==s.type)return e;const i=t.content.at(n-1),r=i&&"new-line"!==i.type&&i.value?" ; ":"; ",o=re(t),a=`${r}${se.join(" ")}${o}`;return se=[],a},ae=e=>e.content.list.map(((t,n)=>{const s={...e,i:n,it:t};t.comment&&(se=[...se,...t.comment]);for(const e of Object.keys(ce))if(t.type===e){const n=ce[e],i="string"==typeof n?n.replace(/~/g,t.value):n(s);return oe(i,s)}return oe(t.value,s)})).join(""),ce={"for-in":" in ","logical-operator":e=>{const{value:t}=e.it;return["&&","||"].includes(t)?` ${t} `:t},"new-line":re,await:"await ",class:"class ",compare:" ~ ",edge:e=>{const{content:t,i:n,it:s}=e,{value:i}=s;if("block-start"===i){const e=ne[i],s=t.at(n-1);return s?s.is("sign",":")?e:` ${e}`:e}if("call-start"===i){const e=t.at(n-1);if(!e)throw new Error("Unexpected error: renderer/index/1");const s=a(e.value,"_");return s.startsWith(s[0].toLowerCase())?".Call(":"("}return ne[i]||i},for:"for ",if:e=>{const{content:t,i:n,it:s}=e,{value:i}=s;if("case"===i)return"case ";if("default"===i)return"default";if("else"===i)return" else";if("if"===i){const e=t.at(n-1);return e?.is("if","else")?" if ":"if "}return"switch"===i?"switch ":""},math:" ~ ",negative:e=>{const{value:t}=e.it;return"-"===t?t:""},sign:e=>{const{value:t}=e.it;return[",",":"].includes(t)?ie(e):"="===t?" := ":"..."===t?"*":t},statement:e=>{const{value:t}=e.it;return"export"===t?"return ":"extends"===t?" extends ":["new","return","throw"].includes(t)?ie(e):e.it.value},super:"base",try:e=>{const{content:t,i:n,it:s}=e,{value:i}=s;if("catch"===i){const e=t.at(n+1);return e?.is("edge","block-start")?" catch":" catch "}return"finally"===i?" finally":"try"===i?"try":""},void:"",while:"while "},le=(e,t)=>{const n=o(e,{ast:!0}),s=new f,i=new v(s),r={cache:{global:new Set},content:i,flag:{isChangeIndexUsed:!1,isFunctionIncluded:!1},indent:0,options:t,token:void 0,scope:s,type:"",value:""};for(const e of n.tokens)r.token=e,r.token[2]={},r.type=e[0].toLowerCase(),r.value=e[1].toString(),w(r);return te(r),{ast:i.list,content:ae(r),raw:n.tokens}},ue=new Map,pe=[".ahk",".coffee",".json",".yaml"];let fe="",de=0;const he=e=>e.split(/\n/u).map((e=>` ${e}`)).join("\n"),ge=(e,t)=>{const n=e.split("\n");for(const e of n)if(e.startsWith(t))return!0;return!1},ye=async(e,i)=>{const[r,o]=i.includes(" from ")?i.replace("import ","").split(" from ").map((e=>e.trim())):["",i.replace("import ","").trim()],c=await(async(e,n)=>{const i=n.startsWith("."),r=pe.some((e=>n.endsWith(e)))?[n]:[`${n}.coffee`,`${n}/index.coffee`];r.filter(((t,n)=>r[n]=i?`${e}/${t}`:`./node_modules/${t}`));const o=await s(r);if(o.length)return o[0];const a=await t(`./node_modules/${n}/package.json`);if(!a?.main)throw new Error(`invalid package '${e}'`);const c=await s(`./node_modules/${n}/${a.main}`);if(!c.length)throw new Error(`invalid package '${e}'`);return c[0]})(n(e),a(o," /'\""));return[r,c]},we=async(e,t)=>{const n=[];for(const s of t.split("\n")){if(!s.startsWith("import ")){n.push(s);continue}const[t,i]=await ye(e,s);ue.has(i)||ue.set(i,{content:"",dependencies:[],id:t?++de:0});const r=ue.get(i)?.id??0;if(!r)continue;const o=t?`${t} = __${fe}_module_${r}__`:"";o&&n.push(o)}return n.join("\n")},ve=(e=[],t=[])=>([...ue].forEach((n=>{const[s,{content:i,dependencies:r}]=n;r.length||(e.push(i),t.push(s),ue.delete(s))})),ue.size?([...ue].forEach((e=>{const[n,{dependencies:s}]=e;ue.set(n,{...e[1],dependencies:s.filter((e=>!t.includes(e)))})})),ve(e,t)):e),me=async()=>{for(const e of[...ue]){const[n,s]=e;if(s.content)continue;const i=await t(n);if(!i){ue.delete(n);continue}const r=i instanceof Buffer?l.decode(i,"utf8",{addBOM:!0}):"string"==typeof i?i:i.toString(),o=await(async()=>{if(n.endsWith(".coffee")){const e=[];for(const t of r.split("\n")){if(!t.startsWith("import "))continue;const[,s]=await ye(n,t);e.push(s)}return e}return[]})(),a=n.endsWith(".coffee")?await we(n,r):r,u=(()=>{if(n.endsWith(".ahk"))return["```",a,"```"].join("\n");if(n.endsWith(".coffee"))return ge(a,"export ")?[`__${fe}_module_${s.id}__ = do ->`,he(a)].join("\n"):a;if(n.endsWith(".json")||n.endsWith(".yaml")){const e=c.stringify(JSON.parse(a));return`__${fe}_module_${s.id}__ = ${e.includes("\n")?`\n${e}`:e}`}throw new Error(`invalid source '${n}'`)})();ue.set(n,{...s,content:u,dependencies:o})}[...ue].filter((e=>!e[1].content)).length&&await me()},_e=async(e,n)=>{let s=e;const i=".coffee";s.endsWith(i)||(s+=i);const r=await(async(e,n)=>{fe=n;const s=await t(e);if(!s)throw new Error(`invalid source '${e}'`);const i=await we(e,s);return await me(),[...ve(),i].join("\n")})(s,n);if(!r)throw new Error(`invalid source '${s}'`);return r.replace(/\r/g,"")};const be=e=>{const t="string"!=typeof e?e.toString():e;console.log(),console.log(u.blue(((e,t,n=" ")=>{if(e.length>=t)return e;const s=t-e.length,i=Math.floor(s/2),r=s-i;return n.repeat(i)+e+n.repeat(r)})(t,80,"-")))},Se=e=>{let t=0;be(++t);for(let n=0;n<e.length;n++){const s=e[n];console.log(n,s),"new-line"===s.type&&be(++t)}be("eof")},ke={anonymous:!0,ast:!1,builtins:!0,coffeeAst:!1,comments:!1,metadata:!0,salt:"",save:!0,string:!1,track:!1,verbose:!1},Ee=(e,t={})=>{const n={...ke,...t};return n.salt||(n.salt=Math.random().toString(32).split(".")[1].padStart(11,"0")),n.string?Ce(e,n):xe(e,n)},xe=async(e,t)=>{const n=e.endsWith(".coffee")?[e]:[e,`${e}.coffee`,`${e}/index.coffee`],[o]=(await s(n)).filter((e=>e.endsWith(".coffee")));if(!o)throw new Error(`invalid source '${e}'`);const a=await _e(o,t.salt),c=le(a,t);return t.verbose&&(t.coffeeAst&&console.log(c.raw),Se(c.ast)),t.save&&await(async(e,t,n)=>{const{basename:s,dirname:o}=i(e);await r(`${o}/${s}.ahk`,l.encode(n.metadata?["; Generated by Coffee-AHK/0.0.58",t.content].join("\n"):t.content,"utf8",{addBOM:!0}).toString()),n.ast&&await r(`${o}/${s}.ast.json`,t.ast)})(o,c,t),c.content},Ce=(e,t)=>{const n=le(e,t);return t.verbose&&(t.coffeeAst&&console.log(n.raw),Se(n.ast)),n.content};export{Ee as default};