hackmud-script-manager 0.13.0-af0e1ee → 0.13.0-bf69e1f

Sign up to get free protection for your applications and to get access to all the features.
package/bin/hsm.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import o from"fs";import{resolve as e,basename as s,extname as t,dirname as n,relative as r}from"path";import{D as i,s as a,p as l,w as c,t as p,a as g,b as m}from"../processScript/compile.js";import{g as u}from"../processScript/minify.js";import b from"chalk";import{homedir as f}from"os";import{generateTypings as d}from"../generateTypings.js";import{syncMacros as h}from"../syncMacros.js";import{pull as k}from"../pull.js";import"@babel/generator";import"../assert-1b7dada8.js";import"perf_hooks";import"prettier";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"rollup";import"acorn";import"terser";import"../processScript/preprocess.js";import"../spliceString-2c6f214f.js";import"chokidar";import"../processScript/postprocess.js";const{readFile:w,rmdir:y,writeFile:$,mkdir:v}=o.promises,j=e(f(),".config"),P=e(j,"hsm.json"),S=new Map,C=[];let x;const N=b.rgb(255,244,4),O=b.rgb(243,249,152),L=b.rgb(179,255,155),T=b.rgb(255,150,224),E=b.rgb(30,255,0),I=b.rgb(202,202,202),M=new i((o=>{let e=0;for(const s of o)e+=(e>>1)+e+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[N,O,L,T,E,I][e%6](o)}));for(const o of process.argv.slice(2))if("-"==o[0]){const[e,s]=o.split("=");let t=s;if(t)if("true"==t)t=!0;else if("false"==t)t=!1;else{const o=Number(t);isFinite(o)&&(t=o)}else t=!0;if("-"==o[1])S.set(e.slice(2),t);else for(const o of e.slice(1))S.set(o,t)}else C.push(o);function help(){switch(C[0]){case"config":switch(C[1]){case"get":console.log("hsm config get <key>");break;case"set":console.log("hsm config set <key> <value>");break;case"delete":console.log("hsm config delete <key>");break;default:console.log("hsm config <get, delete, set>")}break;case"push":console.log('hsm push [<dir> [..."<script user>.<script name>"]]');break;case"watch":console.log("hsm watch [dir]");break;case"pull":console.log("hsm pull <script user>.<script name>");break;case"minify":case"golf":console.log(`${s(process.argv[1])} ${C[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}async function version(){console.log("0.13.0-af0e1ee")}async function getConfig(){return x||(x=await w(P,{encoding:"utf-8"}).then((o=>{let e;try{e=JSON.parse(o)}catch{return console.log("config file was corrupted, resetting"),{}}return e&&"object"==typeof e?e:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${P}`),{}))))}function exploreObject(o,e,s=!1){for(const n of e){var t;o=s?"object"==typeof o[n]?o[n]:o[n]={}:null===(t=o)||void 0===t?void 0:t[n]}return o}function updateConfig(){if(x){const o=JSON.stringify(x);$(P,o).catch((async e=>{switch(e.code){case"EISDIR":await y(P);break;case"ENOENT":await v(j);break;default:throw e}$(P,o)}))}}function onPushLogger({file:o,users:n,srcLength:r,minLength:i,error:a}){n.length&&(a?console.log(`error "${b.bold(a.message)}" in ${b.bold(o)}`):console.log(`pushed ${b.bold(o)} to ${n.map((o=>b.bold(M.get(o)))).join(", ")} | ${b.bold(String(i))} chars from ${b.bold(String(r))} | saved ${b.bold(String(r-i))} (${b.bold(`${Math.round(100*(1-i/r))}%`)}) | ${b.bold(`${e(x.hackmudPath,n[0],"scripts",s(o,t(o)))}.js`)}`))}(async()=>{if(S.get("version")||S.get("v"))version();else if(S.get("help")||S.get("h"))help();else{switch(C[0]){case"push":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1]||".",s=o.hackmudPath,t=C.slice(2);t.length||t.push("*.*");(await m(e,s,{scripts:t,onPush:onPushLogger,minify:!S.get("skip-minify")})).length||console.warn("couldn't find any scripts to push"),updateConfig()}break;case"dev":case"watch":{var o,i,f;const e=await getConfig();if(!e.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const s=C[1]||".",t=e.hackmudPath,n=(null===(o=S.get("users"))||void 0===o?void 0:o.toString().split(","))||[],r=(null===(i=S.get("scripts"))||void 0===i?void 0:i.toString().split(","))||[],a=null===(f=S.get("gen-types"))||void 0===f?void 0:f.toString();g(s,t,n,r,onPushLogger,{genTypes:a})}break;case"pull":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1];if(!e){help();break}const s=C[2]||".",t=o.hackmudPath;try{await k(s,t,e)}catch(o){console.log("something went wrong, did you forget to #down the script?")}}break;case"sync-macros":{const{hackmudPath:o}=await getConfig();if(!o){console.log("you need to set hackmudPath in config before you can use this command");break}const{macrosSynced:e,usersSynced:s}=await h(o);console.log(`synced ${e} macros to ${s} users`)}break;case"test":{const o=e(C[1]||".");let s=0;console.log(`testing scripts in ${b.bold(o)}\n`);for(const{file:e,line:t,message:n}of await p(o))console.log(`error "${b.bold(n)}" in ${b.bold(e)} on line ${b.bold(String(t))}`),s++;if(!s){console.log("no errors found");break}if(s){process.exitCode=1,console.log(`\nencountered ${b.bold(String(s))} errors`);break}console.log("no errors found")}break;case"gen-types":{const o=e(C[1]||".");let s;s=C[2]?e(C[2]):e(o,"../player.d.ts"),d(o,s,(await getConfig()).hackmudPath)}break;case"config":switch(C[1]){case"get":console.log(exploreObject(await getConfig(),C[2].split(".")));break;case"delete":{var y;const o=C[2].split(".");if(!o.length){help();break}const e=await getConfig();null===(y=exploreObject(e,o))||void 0===y||delete y[C[3]],console.log(e)}break;case"set":{const o=C[2].split(".");if(!o.length){help();break}const s=await getConfig();let t=s;for(let e of o.slice(0,-1))t="object"==typeof t[e]?t[e]:t[e]={};t[o.slice(-1)[0]]=C[3],s.hackmudPath&&(s.hackmudPath=e(s.hackmudPath)),console.log(s)}break;default:C[1]&&console.log("unknown command"),help()}break;case"help":case"h":help();break;case"version":case"v":version();break;case"golf":case"minify":{if(!C[1]){console.log(`Target required\nUsage: ${s(process.argv[1])} ${C[0]} <target> [output]`);break}const o=t(C[1]);if(!a.includes(o)){console.log(`Unsupported file extension "${b.bold(o)}"\nSupported extensions are "${a.map((o=>b.bold(o))).join('", "')}"`);break}await w(C[1],{encoding:"utf-8"}).then((async t=>{const i=s(C[1],o),a=i.endsWith(".src"),p=a?i.slice(0,-4):i;let g="UNKNOWN";"scripts"==s(e(C[1],".."))&&"hackmud"==s(e(C[1],"../../.."))&&(g=s(e(C[1],"../..")));const m=!S.get("skip-minify"),f=Boolean(S.get("mangle-names"));!m&&f&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const{script:d,srcLength:h,warnings:k,timeTook:w}=await l(t,{minify:m,scriptUser:g,scriptName:p,filePath:C[1],mangleNames:f});for(const{message:o,line:e}of k)console.log(`warning "${b.bold(o)}" on line ${b.bold(String(e))}`);let y;y=C[2]?C[2]:e(n(C[1]),a?`${p}.js`:".js"==o?`${i}.min.js`:`${i}.js`);const $=u(d);await c(y,d).catch((async t=>{if(!C[2]||"EISDIR"!=t.code)throw t;y=e(y,`${s(C[1],o)}.js`),await c(y,d)})).then((()=>console.log(`wrote ${b.bold($)} chars to ${b.bold(r(".",y))} | saved ${b.bold(h-$)} chars | took ${Math.round(100*w)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}break;default:C[0]&&console.log("unknown command"),help()}updateConfig()}})();
2
+ import o from"fs";import{resolve as e,basename as s,extname as t,dirname as r,relative as n}from"path";import{c as i}from"../processScript/minify.js";import{D as a,w as l,push as c}from"../push.js";import p from"chalk";import{homedir as g}from"os";import{s as m,processScript as f}from"../processScript/index.js";import{generateTypings as u}from"../generateTypings.js";import{pull as b}from"../pull.js";import{syncMacros as d}from"../syncMacros.js";import{test as h}from"../test.js";import{watch as k}from"../watch.js";import"@babel/generator";import"@babel/traverse";import"@babel/types";import"../assert-1b7dada8.js";import"../spliceString-2c6f214f.js";import"acorn";import"terser";import"../processScript/shared.js";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"../processScript/postprocess.js";import"../processScript/preprocess.js";import"../processScript/transform.js";import"chokidar";const{readFile:w,rmdir:y,writeFile:j,mkdir:$}=o.promises,v=e(g(),".config"),S=e(v,"hsm.json"),P=new Map,C=[];let x;const N=p.rgb(255,244,4),O=p.rgb(243,249,152),L=p.rgb(179,255,155),U=p.rgb(255,150,224),T=p.rgb(30,255,0),E=p.rgb(202,202,202),I=new a((o=>{let e=0;for(const s of o)e+=(e>>1)+e+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[N,O,L,U,T,E][e%6](o)}));for(const o of process.argv.slice(2))if("-"==o[0]){const[e,s]=o.split("=");let t=s;if(t)if("true"==t)t=!0;else if("false"==t)t=!1;else{const o=Number(t);isFinite(o)&&(t=o)}else t=!0;if("-"==o[1])P.set(e.slice(2),t);else for(const o of e.slice(1))P.set(o,t)}else C.push(o);function help(){switch(C[0]){case"config":switch(C[1]){case"get":console.log("hsm config get <key>");break;case"set":console.log("hsm config set <key> <value>");break;case"delete":console.log("hsm config delete <key>");break;default:console.log("hsm config <get, delete, set>")}break;case"push":console.log('hsm push [<dir> [..."<script user>.<script name>"]]');break;case"watch":console.log("hsm watch [dir]");break;case"pull":console.log("hsm pull <script user>.<script name>");break;case"minify":case"golf":console.log(`${s(process.argv[1])} ${C[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.13.0-bf69e1f")}function getConfig(){return x||(x=w(S,{encoding:"utf-8"}).then((o=>{let e;try{e=JSON.parse(o)}catch{return console.log("config file was corrupted, resetting"),{}}return e&&"object"==typeof e?e:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${S}`),{}))))}function exploreObject(o,e,s=!1){for(const r of e){var t;o=s?"object"==typeof o[r]?o[r]:o[r]={}:null===(t=o)||void 0===t?void 0:t[r]}return o}function updateConfig(){if(x){const o=JSON.stringify(x);j(S,o).catch((async e=>{switch(e.code){case"EISDIR":await y(S);break;case"ENOENT":await $(v);break;default:throw e}j(S,o)}))}}function onPushLogger({file:o,users:r,srcLength:n,minLength:i,error:a}){r.length&&(a?console.log(`error "${p.bold(a.message)}" in ${p.bold(o)}`):console.log(`pushed ${p.bold(o)} to ${r.map((o=>p.bold(I.get(o)))).join(", ")} | ${p.bold(String(i))} chars from ${p.bold(String(n))} | saved ${p.bold(String(n-i))} (${p.bold(`${Math.round(100*(1-i/n))}%`)}) | ${p.bold(`${e(x.hackmudPath,r[0],"scripts",s(o,t(o)))}.js`)}`))}(async()=>{if(P.get("version")||P.get("v"))version();else if(P.get("help")||P.get("h"))help();else{switch(C[0]){case"push":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1]||".",s=o.hackmudPath,t=C.slice(2);t.length||t.push("*.*");(await c(e,s,{scripts:t,onPush:onPushLogger,minify:!P.get("skip-minify")})).length||console.warn("couldn't find any scripts to push"),updateConfig()}break;case"dev":case"watch":{var o,a,g;const e=await getConfig();if(!e.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const s=C[1]||".",t=e.hackmudPath,r=(null===(o=P.get("users"))||void 0===o?void 0:o.toString().split(","))||[],n=(null===(a=P.get("scripts"))||void 0===a?void 0:a.toString().split(","))||[],i=null===(g=P.get("gen-types"))||void 0===g?void 0:g.toString();k(s,t,r,n,onPushLogger,{genTypes:i})}break;case"pull":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1];if(!e){help();break}const s=C[2]||".",t=o.hackmudPath;try{await b(s,t,e)}catch{console.log("something went wrong, did you forget to #down the script?")}}break;case"sync-macros":{const{hackmudPath:o}=await getConfig();if(!o){console.log("you need to set hackmudPath in config before you can use this command");break}const{macrosSynced:e,usersSynced:s}=await d(o);console.log(`synced ${e} macros to ${s} users`)}break;case"test":{const o=e(C[1]||".");let s=0;console.log(`testing scripts in ${p.bold(o)}\n`);for(const{file:e,line:t,message:r}of await h(o))console.log(`error "${p.bold(r)}" in ${p.bold(e)} on line ${p.bold(String(t))}`),s++;if(!s){console.log("no errors found");break}if(s){process.exitCode=1,console.log(`\nencountered ${p.bold(String(s))} errors`);break}console.log("no errors found")}break;case"gen-types":{const o=e(C[1]||".");u(o,C[2]?e(C[2]):e(o,"../player.d.ts"),(await getConfig()).hackmudPath)}break;case"config":switch(C[1]){case"get":C[2]?console.log(exploreObject(await getConfig(),C[2].split("."))):console.log(await getConfig());break;case"delete":if(C[2]){var y;const o=C[2].split("."),e=o.pop();if(!o.length){help();break}const s=await getConfig();null===(y=exploreObject(s,o))||void 0===y||delete y[e],console.log(s)}else console.log("Usage:\nhsm config delete <key>");break;case"set":if(C[2]&&C[3]){const o=C[2].split("."),s=o.pop();if(!o.length){help();break}const t=await getConfig();if(o.length||"hackmudPath"!=s){let e=t;for(const s of o)"object"==typeof e[s]||(e[s]={}),e=e[s];e[s]=C[3]}else t.hackmudPath=e(C[3]);console.log(t)}else console.log("Usage:\nhsm config set <key> <value>");break;default:C[1]&&console.log("unknown command"),help()}break;case"help":case"h":help();break;case"version":case"v":version();break;case"golf":case"minify":{const o=C[1];if(!o){console.log(`Target required\nUsage: ${s(process.argv[1])} ${C[0]} <target> [output]`);break}const a=t(o);if(!m.includes(a)){console.log(`Unsupported file extension "${p.bold(a)}"\nSupported extensions are "${m.map((o=>p.bold(o))).join('", "')}"`);break}await w(o,{encoding:"utf-8"}).then((async t=>{const c=s(o,a),g=c.endsWith(".src"),m=g?c.slice(0,-4):c;let u="UNKNOWN";"scripts"==s(e(o,".."))&&"hackmud"==s(e(o,"../../.."))&&(u=s(e(o,"../..")));const b=!P.get("skip-minify"),d=Boolean(P.get("mangle-names"));!b&&d&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const{script:h,srcLength:k,warnings:w,timeTook:y}=await f(t,{minify:b,scriptUser:u,scriptName:m,filePath:o,mangleNames:d});for(const{message:o,line:e}of w)console.log(`warning "${p.bold(o)}" on line ${p.bold(String(e))}`);let j;j=C[2]?C[2]:e(r(o),g?`${m}.js`:".js"==a?`${c}.min.js`:`${c}.js`);const $=i(h);await l(j,h).catch((async t=>{if(!C[2]||"EISDIR"!=t.code)throw t;j=e(j,`${s(o,a)}.js`),await l(j,h)})).then((()=>console.log(`wrote ${p.bold($)} chars to ${p.bold(n(".",j))} | saved ${p.bold(k-$)} chars | took ${Math.round(100*y)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}break;default:C[0]&&console.log("unknown command"),help()}updateConfig()}})();
@@ -1,2 +1,2 @@
1
- export declare function generateTypings(srcDir: string, target: string, hackmudPath?: string): Promise<void>;
1
+ export declare function generateTypings(sourceDirectory: string, target: string, hackmudPath?: string): Promise<void>;
2
2
  export default generateTypings;
@@ -1 +1 @@
1
- import{promises as t}from"fs";import{extname as e,basename as n,resolve as s}from"path";const{readdir:r,writeFile:o}=t;async function generateTypings(t,a,i){const f=new Set;if(i)for(const t of await r(i,{withFileTypes:!0}))t.isFile()&&".key"==e(t.name)&&f.add(n(t.name,".key"));const c=[],l=[],p={},m={};for(const o of await r(t,{withFileTypes:!0}))if(o.isFile())".ts"==e(o.name)?c.push(n(o.name,".ts")):".js"==e(o.name)&&l.push(n(o.name,".js"));else if(o.isDirectory()){const a=p[o.name]=[],i=m[o.name]=[];f.add(o.name);for(const f of await r(s(t,o.name),{withFileTypes:!0}))f.isFile()&&(".ts"==e(f.name)?a.push(n(f.name,".ts")):".js"==e(f.name)&&i.push(n(f.name,".js")))}let y="";for(const t of c)y+=`import { script as $${t}$ } from "./src/${t}"\n`;y+="\n";for(const t in p){const e=p[t];for(const n of e)y+=`import { script as $${t}$${n}$ } from "./src/${t}/${n}"\n`}y+="\ntype ArrayRemoveFirst<A> = A extends [ infer FirstItem, ...infer Rest ] ? Rest : never\n\ntype Subscript<T extends (...args: any) => any> =\n\t(...args: ArrayRemoveFirst<Parameters<T>>) => ReturnType<T> | ScriptFailure\n\ntype WildFullsec = Record<string, () => ScriptFailure> & {\n";for(const t of c)y+=`\t${t}: Subscript<typeof $${t}$>\n`;for(const t of l)y+=`\t${t}: (...args: any) => any\n`;y+="}\n\ndeclare global {\n\tinterface PlayerFullsec {";let $=!0;for(const t of f){const e=p[t],n=m[t];if(e&&e.length||n&&n.length){$=!0,y+=`\n\t\t${t}: WildFullsec & {\n`;for(const n of e)y+=`\t\t\t${n}: Subscript<typeof $${t}$${n}$>\n`;for(const t of n)y+=`\t\t\t${t}: (...args: any) => any\n`;y+="\t\t}"}else $&&(y+="\n",$=!1),y+=`\t\t${t}: WildFullsec`;y+="\n"}y+="\t}\n}\n",await o(a,y)}export{generateTypings as default,generateTypings};
1
+ import e from"fs";import{extname as t,basename as n,resolve as s}from"path";const{readdir:r,writeFile:a}=e.promises;async function generateTypings(e,i,o){const f=new Set;if(o)for(const e of await r(o,{withFileTypes:!0}))e.isFile()&&".key"==t(e.name)&&f.add(n(e.name,".key"));const c=[],l=[],p={},m={};await Promise.all((await r(e,{withFileTypes:!0})).map((async a=>{if(a.isFile())".ts"==t(a.name)?c.push(n(a.name,".ts")):".js"==t(a.name)&&l.push(n(a.name,".js"));else if(a.isDirectory()){const i=[],o=[];p[a.name]=i,m[a.name]=o,f.add(a.name);for(const f of await r(s(e,a.name),{withFileTypes:!0}))f.isFile()&&(".ts"==t(f.name)?i.push(n(f.name,".ts")):".js"==t(f.name)&&o.push(n(f.name,".js")))}})));let y="";for(const e of c)y+=`import { script as $${e}$ } from "./src/${e}"\n`;y+="\n";for(const e in p){const t=p[e];for(const n of t)y+=`import { script as $${e}$${n}$ } from "./src/${e}/${n}"\n`}y+="\ntype ArrayRemoveFirst<A> = A extends [ infer FirstItem, ...infer Rest ] ? Rest : never\n\ntype Subscript<T extends (...args: any) => any> =\n\t(...args: ArrayRemoveFirst<Parameters<T>>) => ReturnType<T> | ScriptFailure\n\ntype WildFullsec = Record<string, () => ScriptFailure> & {\n";for(const e of c)y+=`\t${e}: Subscript<typeof $${e}$>\n`;for(const e of l)y+=`\t${e}: (...args: any) => any\n`;y+="}\n\ndeclare global {\n\tinterface PlayerFullsec {";let $=!0;for(const e of f){const t=p[e],n=m[e];if(t&&t.length||n&&n.length){if($=!0,y+=`\n\t\t${e}: WildFullsec & {\n`,t)for(const n of t)y+=`\t\t\t${n}: Subscript<typeof $${e}$${n}$>\n`;if(n)for(const e of n)y+=`\t\t\t${e}: (...args: any) => any\n`;y+="\t\t}"}else $&&(y+="\n",$=!1),y+=`\t\t${e}: WildFullsec`;y+="\n"}y+="\t}\n}\n",await a(i,y)}export{generateTypings as default,generateTypings};
package/index.d.ts CHANGED
@@ -1,11 +1,4 @@
1
- export interface Info {
2
- file: string;
3
- users: string[];
4
- srcLength: number;
5
- minLength: number;
6
- error: Error | null;
7
- }
8
- export declare const supportedExtensions: string[];
1
+ export { supportedExtensions } from "./constants.json";
9
2
  export { generateTypings } from "./generateTypings";
10
3
  export { processScript } from "./processScript";
11
4
  export { pull } from "./pull";
@@ -13,3 +6,10 @@ export { push } from "./push";
13
6
  export { syncMacros } from "./syncMacros";
14
7
  export { test } from "./test";
15
8
  export { watch } from "./watch";
9
+ export declare type Info = {
10
+ file: string;
11
+ users: string[];
12
+ srcLength: number;
13
+ minLength: number;
14
+ error: Error | null;
15
+ };
package/index.js CHANGED
@@ -1 +1 @@
1
- export{generateTypings}from"./generateTypings.js";export{p as processScript,b as push,s as supportedExtensions,t as test,a as watch}from"./processScript/compile.js";export{pull}from"./pull.js";export{syncMacros}from"./syncMacros.js";import"fs";import"path";import"@babel/generator";import"./assert-1b7dada8.js";import"./processScript/minify.js";import"@babel/parser";import"@babel/traverse";import"@babel/types";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"perf_hooks";import"prettier";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"rollup";import"./processScript/preprocess.js";import"chokidar";import"./processScript/postprocess.js";
1
+ export{processScript,s as supportedExtensions}from"./processScript/index.js";export{generateTypings}from"./generateTypings.js";export{pull}from"./pull.js";export{push}from"./push.js";export{syncMacros}from"./syncMacros.js";export{test}from"./test.js";export{watch}from"./watch.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"./assert-1b7dada8.js";import"path";import"./processScript/minify.js";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"./processScript/shared.js";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";import"fs";import"chokidar";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hackmud-script-manager",
3
- "version": "0.13.0-af0e1ee",
3
+ "version": "0.13.0-bf69e1f",
4
4
  "description": "Script manager for game hackmud, with minification, TypeScript support, and player script type definition generation.",
5
5
  "keywords": [
6
6
  "api",
@@ -21,27 +21,11 @@
21
21
  "bugs": "https://github.com/samualtnorman/hackmud-script-manager/issues",
22
22
  "license": "GPL-3.0-or-later",
23
23
  "author": "Samual Norman",
24
- "files": [
25
- "*.d.ts",
26
- "*.js",
27
- "!*.config.js",
28
- "index.cjs",
29
- "bin",
30
- "processScript"
31
- ],
32
24
  "main": "index.js",
33
- "bin": {
34
- "hsm": "bin/hsm.js"
35
- },
36
25
  "repository": {
37
26
  "type": "git",
38
27
  "url": "https://github.com/samualtnorman/hackmud-script-manager.git"
39
28
  },
40
- "scripts": {
41
- "build": "rollup --config && tsc --project src",
42
- "dev": "rollup --config --watch",
43
- "prepublishOnly": "npm run build"
44
- },
45
29
  "dependencies": {
46
30
  "@babel/core": "^7.16.0",
47
31
  "@babel/generator": "^7.16.0",
@@ -74,25 +58,38 @@
74
58
  "@rollup/plugin-json": "^4.1.0",
75
59
  "@rollup/plugin-node-resolve": "^13.0.6",
76
60
  "acorn": "^8.5.0",
77
- "chalk": "^4.1.2",
61
+ "chalk": "^5.0.0",
78
62
  "chokidar": "^3.5.2",
79
63
  "prettier": "^2.4.1",
64
+ "proxy-polyfill": "^0.3.2",
80
65
  "rollup": "^2.60.0",
81
66
  "terser": "^5.10.0"
82
67
  },
83
68
  "devDependencies": {
84
69
  "@babel/preset-env": "^7.16.4",
85
70
  "@babel/preset-typescript": "^7.16.0",
86
- "@samual/lib": "^0.2.0-e6a06ca",
71
+ "@samual/lib": "^0.2.0-890d658",
87
72
  "@types/babel__core": "^7.1.16",
88
73
  "@types/node": "^12.20.37",
89
74
  "@types/prettier": "^2.4.2",
90
75
  "@types/semver": "^7.3.9",
76
+ "@typescript-eslint/eslint-plugin": "^5.8.0",
77
+ "@typescript-eslint/parser": "^5.8.1",
78
+ "eslint": "^8.5.0",
79
+ "eslint-plugin-array-func": "^3.1.7",
80
+ "eslint-plugin-eslint-comments": "^3.2.0",
81
+ "eslint-plugin-optimize-regex": "^1.2.1",
82
+ "eslint-plugin-regexp": "^1.5.1",
83
+ "eslint-plugin-unicorn": "^39.0.0",
84
+ "eslint-plugin-write-good-comments": "^0.1.3",
91
85
  "rollup-plugin-preserve-shebang": "^1.0.1",
92
86
  "rollup-plugin-terser": "^7.0.2",
93
87
  "semver": "^7.3.5",
94
88
  "typescript": "^4.5.2"
95
89
  },
90
+ "optionalDependencies": {
91
+ "deasync": "^0.1.24"
92
+ },
96
93
  "engines": {
97
94
  "node": "^12.20 || >=14"
98
95
  },
@@ -103,9 +100,24 @@
103
100
  "import": "./index.js",
104
101
  "require": "./index.cjs"
105
102
  },
106
- "./*": "./*"
103
+ "./*": "./*",
104
+ "./generateTypings": "./generateTypings.js",
105
+ "./index": "./index.js",
106
+ "./pull": "./pull.js",
107
+ "./push": "./push.js",
108
+ "./syncMacros": "./syncMacros.js",
109
+ "./test": "./test.js",
110
+ "./watch": "./watch.js",
111
+ "./bin/hsm": "./bin/hsm.js",
112
+ "./processScript/index": "./processScript/index.js",
113
+ "./processScript": "./processScript/index.js",
114
+ "./processScript/minify": "./processScript/minify.js",
115
+ "./processScript/postprocess": "./processScript/postprocess.js",
116
+ "./processScript/preprocess": "./processScript/preprocess.js",
117
+ "./processScript/shared": "./processScript/shared.js",
118
+ "./processScript/transform": "./processScript/transform.js"
107
119
  },
108
- "optionalDependencies": {
109
- "deasync": "^0.1.24"
120
+ "bin": {
121
+ "hsm": "./bin/hsm.js"
110
122
  }
111
- }
123
+ }
@@ -1,15 +1,15 @@
1
- export { compile } from "./compile";
2
1
  export { minify } from "./minify";
3
2
  export { postprocess } from "./postprocess";
4
3
  export { preprocess } from "./preprocess";
4
+ export { transform as compile } from "./transform";
5
5
  export declare type ProcessOptions = {
6
6
  /** whether to minify the given code */
7
7
  minify: boolean;
8
8
  /** 11 a-z 0-9 characters */
9
9
  uniqueID: string;
10
- /** the user the script will be uploaded to (or set to `true` if it is not yet known) */
10
+ /** the user going to be hosting this script (or set to `true` if not yet known) */
11
11
  scriptUser: string | true;
12
- /** the name of this script (or set to `true` if it is not yet known) */
12
+ /** the name of this script (or set to `true` if not yet known) */
13
13
  scriptName: string | true;
14
14
  filePath: string;
15
15
  /** whether to mangle function and class names (defaults to `false`) */
@@ -1 +1 @@
1
- import"@babel/generator";import"../assert-1b7dada8.js";import"fs";import"path";export{minify}from"./minify.js";import"perf_hooks";import"prettier";export{compile,p as default,p as processScript}from"./compile.js";export{postprocess}from"./postprocess.js";export{preprocess}from"./preprocess.js";import"@babel/parser";import"@babel/traverse";import"@babel/types";import"../spliceString-2c6f214f.js";import"acorn";import"terser";import"../generateTypings.js";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"rollup";import"../pull.js";import"../syncMacros.js";import"chokidar";
1
+ import e from"@babel/generator";import{parse as o}from"@babel/parser";import r from"@babel/plugin-proposal-class-properties";import t from"@babel/plugin-proposal-class-static-block";import s from"@babel/plugin-proposal-decorators";import p from"@babel/plugin-proposal-do-expressions";import a from"@babel/plugin-proposal-function-bind";import l from"@babel/plugin-proposal-function-sent";import i from"@babel/plugin-proposal-json-strings";import n from"@babel/plugin-proposal-logical-assignment-operators";import m from"@babel/plugin-proposal-nullish-coalescing-operator";import c from"@babel/plugin-proposal-numeric-separator";import f from"@babel/plugin-proposal-object-rest-spread";import u from"@babel/plugin-proposal-optional-catch-binding";import b from"@babel/plugin-proposal-optional-chaining";import d from"@babel/plugin-proposal-partial-application";import g from"@babel/plugin-proposal-pipeline-operator";import h from"@babel/plugin-proposal-private-property-in-object";import w from"@babel/plugin-proposal-record-and-tuple";import y from"@babel/plugin-proposal-throw-expressions";import x from"@babel/plugin-transform-exponentiation-operator";import j from"@babel/plugin-transform-typescript";import S from"@babel/traverse";import k from"@babel/types";import v from"@rollup/plugin-babel";import E from"@rollup/plugin-commonjs";import N from"@rollup/plugin-json";import C from"@rollup/plugin-node-resolve";import{a as L}from"../assert-1b7dada8.js";import{resolve as _}from"path";import{c as I,minify as D}from"./minify.js";export{minify}from"./minify.js";import{performance as U}from"perf_hooks";import $ from"prettier";import{rollup as M}from"rollup";import{postprocess as W}from"./postprocess.js";export{postprocess}from"./postprocess.js";import{preprocess as q}from"./preprocess.js";export{preprocess}from"./preprocess.js";import{transform as F}from"./transform.js";export{transform as compile}from"./transform.js";import"../spliceString-2c6f214f.js";import"acorn";import"terser";import"./shared.js";const T=[".js",".ts"],{default:H}=v,{format:O}=$,{default:P}=e,{default:K}=S;async function processScript(e,{minify:S=!0,uniqueID:v=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:$="UNKNOWN",scriptName:z="UNKNOWN",filePath:B,mangleNames:G=!1}={}){L(/^\w{11}$/.exec(v)),B=B?_(B):"script";const A=U.now(),J=e;let Q,R;const V=/^function\s*\(.+\/\/(?<autocomplete>.+)/.exec(e);if(V)e=`export default ${e}`,({autocomplete:Q}=V.groups);else for(const o of e.split("\n")){const e=/^\s*\/\/(?<commentContent>.+)/.exec(o);if(!e)break;const r=e.groups.commentContent.trim();if(r.startsWith("@autocomplete "))Q=r.slice(14).trimStart();else if(r.startsWith("@seclevel ")){const e=r.slice(10).trimStart().toLowerCase();switch(e){case"fullsec":case"full":case"fs":case"4s":case"f":case"4":R=4;break;case"highsec":case"high":case"hs":case"3s":case"h":case"3":R=3;break;case"midsec":case"mid":case"ms":case"2s":case"m":case"2":R=2;break;case"lowsec":case"low":case"ls":case"1s":case"l":case"1":R=1;break;case"nullsec":case"null":case"ns":case"0s":case"n":case"0":R=0;break;default:throw new Error(`unrecognised seclevel "${e}"`)}}}L(/^\w{11}$/.exec(v));const X=B?_(B):"script";let Y=4;const Z=await M({plugins:[{name:"emit script",buildStart(){this.emitFile({type:"chunk",id:X})},load:o=>o==X?e:null,transform(e){const{code:o,seclevel:r}=q(e,{uniqueID:v});return Y=Math.min(Y,r),o}},H({babelHelpers:"bundled",plugins:[[j.default,{allowDeclareFields:!0,optimizeConstEnums:!0}],[s.default,{decoratorsBeforeExport:!0}],[p.default],[a.default],[l.default],[d.default],[g.default,{proposal:"hack",topicToken:"%"}],[y.default],[w.default,{syntaxType:"hash",importPolyfill:!0}],[r.default],[t.default],[h.default],[n.default],[c.default],[m.default],[b.default],[u.default],[i.default],[f.default],[x.default]],configFile:!1,extensions:T}),E(),C({extensions:T}),N()],treeshake:{moduleSideEffects:!1}}),ee=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];let oe;if(e=(await Z.generate({})).output[0].code,({file:oe,seclevel:Y}=await F(o(e,{sourceType:"module"}),J,{uniqueID:v,scriptUser:$,scriptName:z,seclevel:Y})),null!=R&&Y<R)throw new Error(`detected seclevel ${ee[Y]} is lower than stated seclevel ${ee[R]}`);e=P(oe).code;const re=I(e.replace(/^function\s*\w+\(/,"function("));return S?e=await D(oe,Q,{uniqueID:v,mangleNames:G}):(K(oe,{MemberExpression({node:e}){e.computed||(L("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=k.stringLiteral("prototype")):"__proto__"==e.property.name&&(e.computed=!0,e.property=k.stringLiteral("__proto__")))}}),e=O(P(oe).code,{parser:"babel",arrowParens:"avoid",semi:!1,trailingComma:"none"})),{srcLength:re,script:e=W(e,Y,v),warnings:[],timeTook:U.now()-A}}export{processScript as default,processScript,T as s};
@@ -1,3 +1,4 @@
1
+ import { File } from "@babel/types";
1
2
  declare type MinifyOptions = {
2
3
  /** 11 a-z 0-9 characters */
3
4
  uniqueID: string;
@@ -9,5 +10,5 @@ declare type MinifyOptions = {
9
10
  * @param autocomplete the comment inserted after the function signature
10
11
  * @param options {@link MinifyOptions details}
11
12
  */
12
- export declare function minify(code: string, autocomplete: string, { uniqueID, mangleNames }?: Partial<MinifyOptions>): Promise<string>;
13
+ export declare function minify(file: File, autocomplete?: string, { uniqueID, mangleNames }?: Partial<MinifyOptions>): Promise<string>;
13
14
  export default minify;
@@ -1 +1 @@
1
- import e from"@babel/generator";import{parse as t}from"@babel/parser";import r from"@babel/traverse";import i from"@babel/types";import{a as n}from"../assert-1b7dada8.js";import"fs";import"path";import{s as a}from"../spliceString-2c6f214f.js";import{tokenizer as s,tokTypes as o}from"acorn";import*as p from"terser";function getHackmudCharacterCount(e){return e.replace(/\/\/.*/g,"").replace(/[ \t\n\r\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]/g,"").length}const{default:l}=e,{default:u}=r;async function minify(e,r,{uniqueID:s="00000000000",mangleNames:o=!1}={}){n(s.match(/^\w{11}$/));const c=[];let f,m=!1;e=(await p.minify(e,{ecma:2015,parse:{bare_returns:!0},compress:{passes:1/0,unsafe:!0,booleans:!1,sequences:!1},keep_classnames:!o,keep_fnames:!o})).code||"";{const r=await t(e);u(r,{MemberExpression({node:e}){e.computed||(n("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=i.identifier(`_PROTOTYPE_PROPERTY_${s}_`)):"__proto__"==e.property.name&&(e.computed=!0,e.property=i.identifier(`_PROTO_PROPERTY_${s}_`)))}}),f=(await p.minify(l(r).code,{ecma:2015,compress:{passes:1/0,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,unsafe_symbols:!0,unsafe_methods:!0,unsafe_proto:!0,unsafe_regexp:!0,unsafe_undefined:!0,sequences:!1},format:{semicolons:!1},keep_classnames:!o,keep_fnames:!o})).code.replace(new RegExp(`_PROTOTYPE_PROPERTY_${s}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${s}_`,"g"),'"__proto__"')}let d=null,y=!1;{const r=await t(e),a=[];u(r,{FunctionDeclaration(e){e.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(e){const t={};parseObjectExpression(e.node,t)&&e.replaceWith(i.identifier(`_JSON_VALUE_${c.push(t)-1}_${s}_`))},ArrayExpression(e){const t=[];parseArrayExpression(e.node,t)&&e.replaceWith(i.identifier(`_JSON_VALUE_${c.push(t)-1}_${s}_`))}}),e.traverse({TemplateLiteral(e){const t=e.node;let r=i.stringLiteral(t.quasis[0].value.cooked);for(let e=0;e<t.expressions.length;e++){const n=t.expressions[e],a=t.quasis[e+1];r=i.binaryExpression("+",r,n),a.value.cooked&&(r=i.binaryExpression("+",r,i.stringLiteral(a.value.cooked)))}e.replaceWith(r)},MemberExpression({node:e}){e.computed||(n("Identifier"==e.property.type),e.property.name.length<3||(e.computed=!0,e.property=i.stringLiteral(e.property.name)))},UnaryExpression(e){if("void"==e.node.operator)"NumericLiteral"!=e.node.argument.type||e.node.argument.value||(e.replaceWith(i.identifier(`_UNDEFINED_${s}_`)),m=!0);else if("-"==e.node.operator&&"NumericLiteral"==e.node.argument.type){const t=-e.node.argument.value;a.push((async()=>{if((await minifyNumber(t)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let r=c.indexOf(t);-1==r&&(r+=c.push(t)),e.replaceWith(i.identifier(`_JSON_VALUE_${r}_${s}_`))})()),e.skip()}},NullLiteral(e){let t=c.indexOf(null);-1==t&&(t+=c.push(null)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${s}_`))},BooleanLiteral(e){let t=c.indexOf(e.node.value);-1==t&&(t+=c.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${s}_`))},NumericLiteral(e){a.push((async()=>{if((await minifyNumber(e.node.value)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=c.indexOf(e.node.value);-1==t&&(t+=c.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${s}_`))})())},StringLiteral(e){if(e.node.value.includes("\0")||e.toString().length<4)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=c.indexOf(e.node.value);-1==t&&(t+=c.push(e.node.value)),e.replaceWith(i.identifier(`_JSON_VALUE_${t}_${s}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let t=c.indexOf(e.key.name);-1==t&&(t+=c.push(e.key.name)),e.computed=!0,e.key=i.identifier(`_JSON_VALUE_${t}_${s}_`)}}),e.skip()}}),await Promise.all(a);const[o]=r.program.body;if(n("FunctionDeclaration"==o.type),c.length)if(y=!0,1==c.length)if("string"!=typeof c[0]||c[0].includes("\n")||c[0].includes("\t")){const e=i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_JSON_VALUE_0_${s}_`),i.callExpression(i.memberExpression(i.identifier("JSON"),i.identifier("parse")),[i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier(`$${s}$SUBSCRIPT$scripts$quine`),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`$${s}$SPLIT_INDEX`),!0)]))]);m&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${s}_`))),o.body.body.unshift(e),d=JSON.stringify(c[0])}else{const e=i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_JSON_VALUE_0_${s}_`),i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier(`$${s}$SUBSCRIPT$scripts$quine`),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`$${s}$SPLIT_INDEX`),!0))]);m&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${s}_`))),o.body.body.unshift(e),d=c[0]}else{const e=i.variableDeclaration("let",[i.variableDeclarator(i.arrayPattern(c.map(((e,t)=>i.identifier(`_JSON_VALUE_${t}_${s}_`)))),i.callExpression(i.memberExpression(i.identifier("JSON"),i.identifier("parse")),[i.memberExpression(i.taggedTemplateExpression(i.memberExpression(i.callExpression(i.identifier(`$${s}$SUBSCRIPT$scripts$quine`),[]),i.identifier("split")),i.templateLiteral([i.templateElement({raw:"\t",cooked:"\t"},!0)],[])),i.identifier(`$${s}$SPLIT_INDEX`),!0)]))]);m&&e.declarations.push(i.variableDeclarator(i.identifier(`_UNDEFINED_${s}_`))),o.body.body.unshift(e),d=JSON.stringify(c)}else m&&o.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_UNDEFINED_${s}_`))]));e=l(r).code}if(e=(await p.minify(e,{ecma:2015,compress:{passes:1/0,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,unsafe_symbols:!0,unsafe_methods:!0,unsafe_proto:!0,unsafe_regexp:!0,unsafe_undefined:!0,sequences:!1},format:{semicolons:!1},keep_classnames:!o,keep_fnames:!o})).code||"",null!=d){e=a(e,`${r?`//${r}\n`:""}\n//\t${d}\t\n`,getFunctionBodyStart(e)+1);for(const[t,r]of e.split("\t").entries())if(r==d){e=e.replace(`$${s}$SPLIT_INDEX`,await minifyNumber(t));break}}return getHackmudCharacterCount(f)<=getHackmudCharacterCount(e)+Number(y)&&(e=f,r&&(e=a(e,`//${r}\n`,getFunctionBodyStart(e)+1))),e}function parseObjectExpression(e,t){if(!e.properties.length)return!1;for(const r of e.properties){if("ObjectProperty"!=r.type||r.computed)return!1;if(n("Identifier"==r.key.type||"NumericLiteral"==r.key.type||"StringLiteral"==r.key.type),"ArrayExpression"==r.value.type){const e=[];if(!parseArrayExpression(r.value,e))return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=e}else if("ObjectExpression"==r.value.type){const e={};if(!parseObjectExpression(r.value,e))return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=e}else if("NullLiteral"==r.value.type)t["Identifier"==r.key.type?r.key.name:r.key.value]=null;else{if("BooleanLiteral"!=r.value.type&&"NumericLiteral"!=r.value.type&&"StringLiteral"!=r.value.type)return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=r.value.value}}return!0}function parseArrayExpression(e,t){if(!e.elements.length)return!1;for(const r of e.elements){if(!r)return!1;if("ArrayExpression"==r.type){const e=[];if(!parseArrayExpression(r,e))return!1;e.push(e)}else if("ObjectExpression"==r.type){const e={};if(!parseObjectExpression(r,e))return!1;t.push(e)}else if("NullLiteral"==r.type)t.push(null);else{if("BooleanLiteral"!=r.type&&"NumericLiteral"!=r.type&&"StringLiteral"!=r.type)return!1;t.push(r.value)}}return!0}async function minifyNumber(e){return(await p.minify(`$(${e})`,{ecma:2015})).code.match(/\$\((.+)\)/)[1]}function getFunctionBodyStart(e){const t=s(e,{ecmaVersion:2015});t.getToken(),t.getToken(),t.getToken();let r=1;for(;r;){const e=t.getToken();e.type==o.parenL?r++:e.type==o.parenR&&r--}return t.getToken().start}export{minify as default,getHackmudCharacterCount as g,minify};
1
+ import e from"@babel/generator";import t from"@babel/traverse";import r from"@babel/types";import{a as i}from"../assert-1b7dada8.js";import{s as n}from"../spliceString-2c6f214f.js";import{tokenizer as a,tokTypes as s}from"acorn";import*as o from"terser";import{getReferencePathsToGlobal as p}from"./shared.js";function countHackmudCharacters(e){return e.replace(/\/\/.*/g,"").replace(/[ \t\n\r\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]/g,"").length}const{default:l}=e,{default:u}=t;async function minify(e,t,{uniqueID:a="00000000000",mangleNames:s=!1}={}){let c;i(/^\w{11}$/.exec(a)),u(e,{Program(e){c=e,e.skip()}});const f=c.get("body.0");for(const e of[...f.node.params].reverse()){if("Identifier"==e.type){if(!f.scope.getBinding(e.name).referenced){f.node.params.pop();continue}}break}for(const e in c.scope.globals){if("arguments"==e||e.startsWith(`$${a}`))continue;const t=p(e,c);if(!(5+e.length+t.length>=e.length*t.length)){for(const i of t)i.replaceWith(r.identifier(`_GLOBAL_${e}_${a}_`));f.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_GLOBAL_${e}_${a}_`),r.identifier(e))]))}}const d=[];let m=!1;u(e,{MemberExpression({node:e}){e.computed||(i("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=r.identifier(`_PROTOTYPE_PROPERTY_${a}_`)):"__proto__"==e.property.name&&(e.computed=!0,e.property=r.identifier(`_PROTO_PROPERTY_${a}_`)))}});const _=(await o.minify(l(e).code,{ecma:2015,compress:{passes:1/0,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,unsafe_symbols:!0,unsafe_methods:!0,unsafe_proto:!0,unsafe_regexp:!0,unsafe_undefined:!0,sequences:!1},format:{semicolons:!1},keep_classnames:!s,keep_fnames:!s})).code.replace(new RegExp(`_PROTOTYPE_PROPERTY_${a}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${a}_`,"g"),'"__proto__"');let y,E=null,$=!1;{const t=[];u(e,{FunctionDeclaration(e){e.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(e){const t={};parseObjectExpression(e.node,t)&&e.replaceWith(r.identifier(`_JSON_VALUE_${d.push(t)-1}_${a}_`))},ArrayExpression(e){const t=[];parseArrayExpression(e.node,t)&&e.replaceWith(r.identifier(`_JSON_VALUE_${d.push(t)-1}_${a}_`))}}),e.traverse({TemplateLiteral(e){const t=e.node;let i=r.stringLiteral(t.quasis[0].value.cooked);for(let e=0;e<t.expressions.length;e++){const n=t.expressions[e],a=t.quasis[e+1];i=r.binaryExpression("+",i,n),a.value.cooked&&(i=r.binaryExpression("+",i,r.stringLiteral(a.value.cooked)))}e.replaceWith(i)},MemberExpression({node:e}){e.computed||(i("Identifier"==e.property.type),e.property.name.length<3||(e.computed=!0,e.property=r.stringLiteral(e.property.name)))},UnaryExpression(e){if("void"==e.node.operator)"NumericLiteral"!=e.node.argument.type||e.node.argument.value||(e.replaceWith(r.identifier(`_UNDEFINED_${a}_`)),m=!0);else if("-"==e.node.operator&&"NumericLiteral"==e.node.argument.type){const i=-e.node.argument.value;t.push((async()=>{if((await minifyNumber(i)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=d.indexOf(i);-1==t&&(t+=d.push(i)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${a}_`))})()),e.skip()}},NullLiteral(e){let t=d.indexOf(null);-1==t&&(t+=d.push(null)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${a}_`))},BooleanLiteral(e){let t=d.indexOf(e.node.value);-1==t&&(t+=d.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${a}_`))},NumericLiteral(e){t.push((async()=>{if((await minifyNumber(e.node.value)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=d.indexOf(e.node.value);-1==t&&(t+=d.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${a}_`))})())},StringLiteral(e){if(e.node.value.includes("\0")||e.toString().length<4)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=d.indexOf(e.node.value);-1==t&&(t+=d.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${a}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let t=d.indexOf(e.key.name);-1==t&&(t+=d.push(e.key.name)),e.computed=!0,e.key=r.identifier(`_JSON_VALUE_${t}_${a}_`)}}),e.skip()}}),await Promise.all(t);const n=e.program.body[0];if(i("FunctionDeclaration"==n.type),d.length)if($=!0,1==d.length)if("string"!=typeof d[0]||d[0].includes("\n")||d[0].includes("\t")){const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_JSON_VALUE_0_${a}_`),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${a}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${a}$SPLIT_INDEX`),!0)]))]);m&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${a}_`))),n.body.body.unshift(e),E=JSON.stringify(d[0])}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_JSON_VALUE_0_${a}_`),r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${a}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${a}$SPLIT_INDEX`),!0))]);m&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${a}_`))),n.body.body.unshift(e),E=d[0]}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.arrayPattern(d.map(((e,t)=>r.identifier(`_JSON_VALUE_${t}_${a}_`)))),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${a}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${a}$SPLIT_INDEX`),!0)]))]);m&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${a}_`))),n.body.body.unshift(e),E=JSON.stringify(d)}else m&&n.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_UNDEFINED_${a}_`))]));y=l(e).code}return y=(await o.minify(y,{ecma:2015,compress:{passes:1/0,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,unsafe_symbols:!0,unsafe_methods:!0,unsafe_proto:!0,unsafe_regexp:!0,unsafe_undefined:!0,sequences:!1},format:{semicolons:!1},keep_classnames:!s,keep_fnames:!s})).code||"",null!=E&&(y=n(y,`${t?`//${t}\n`:""}\n//\t${E}\t\n`,getFunctionBodyStart(y)+1),y=y.replace(`$${a}$SPLIT_INDEX`,await minifyNumber(y.split("\t").findIndex((e=>e==E))))),countHackmudCharacters(_)<=countHackmudCharacters(y)+Number($)&&(y=_,t&&(y=n(y,`//${t}\n`,getFunctionBodyStart(y)+1))),y}function parseObjectExpression(e,t){if(!e.properties.length)return!1;for(const r of e.properties){if("ObjectProperty"!=r.type||r.computed)return!1;if(i("Identifier"==r.key.type||"NumericLiteral"==r.key.type||"StringLiteral"==r.key.type),"ArrayExpression"==r.value.type){const e=[];if(!parseArrayExpression(r.value,e))return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=e}else if("ObjectExpression"==r.value.type){const e={};if(!parseObjectExpression(r.value,e))return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=e}else if("NullLiteral"==r.value.type)t["Identifier"==r.key.type?r.key.name:r.key.value]=null;else{if("BooleanLiteral"!=r.value.type&&"NumericLiteral"!=r.value.type&&"StringLiteral"!=r.value.type)return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=r.value.value}}return!0}function parseArrayExpression(e,t){if(!e.elements.length)return!1;for(const r of e.elements){if(!r)return!1;if("ArrayExpression"==r.type){const e=[];if(!parseArrayExpression(r,e))return!1;e.push(e)}else if("ObjectExpression"==r.type){const e={};if(!parseObjectExpression(r,e))return!1;t.push(e)}else if("NullLiteral"==r.type)t.push(null);else{if("BooleanLiteral"!=r.type&&"NumericLiteral"!=r.type&&"StringLiteral"!=r.type)return!1;t.push(r.value)}}return!0}async function minifyNumber(e){return/\$\((?<number>.+)\)/.exec((await o.minify(`$(${e})`,{ecma:2015})).code).groups.number}function getFunctionBodyStart(e){const t=a(e,{ecmaVersion:2015});t.getToken(),t.getToken(),t.getToken();let r=1;for(;r;){const e=t.getToken();e.type==s.parenL?r++:e.type==s.parenR&&r--}return t.getToken().start}export{countHackmudCharacters as c,minify as default,minify};
@@ -1 +1 @@
1
- import"fs";import"path";import{s as e}from"../spliceString-2c6f214f.js";function*findMatches(e,t){let s;for(;s=e.exec(t);)yield{index:s.index,match:s[0]}}function postprocess(t,s,r){t=t.replace(/^function\s*\w+\(/,"function(");for(const{index:n,match:c}of[...findMatches(new RegExp(`\\$${r}\\$[\\w$]+`,"g"),t)].reverse()){const[r,...o]=c.slice(13).split("$");switch(r){case"SUBSCRIPT":t=e(t,`#${"nlmhf"[s]}s.${o[0]}.${o[1]}`,n,c.length);break;case"DEBUG":t=e(t,"#D",n,c.length);break;case"FMCL":t=e(t,"#FMCL",n,c.length);break;case"GLOBAL":t=e(t,"#G",n,c.length);break;case"DB":t=e(t,`#db.${o[0]}`,n,c.length);break;default:throw new Error(`unknown preprocessor directive type "${r}"`)}}return t}export{postprocess as default,postprocess};
1
+ import{s as e}from"../spliceString-2c6f214f.js";function*findMatches(e,s){let t;for(;t=e.exec(s);)yield{index:t.index,match:t[0]}}function postprocess(s,t,n){s=s.replace(/^function\s*\w+\(/,"function(");for(const{index:c,match:r}of[...findMatches(new RegExp(`\\$${n}\\$[\\w$]+`,"g"),s)].reverse()){const[n,...o]=r.slice(13).split("$");switch(n){case"SUBSCRIPT":s=e(s,`#${"nlmhf"[t]}s.${o[0]}.${o[1]}`,c,r.length);break;case"DEBUG":s=e(s,"#D",c,r.length);break;case"FMCL":s=e(s,"#FMCL",c,r.length);break;case"GLOBAL":s=e(s,"#G",c,r.length);break;case"DB":s=e(s,`#db.${o[0]}`,c,r.length);break;default:throw new Error(`unknown type "${n}"`)}}return s}export{postprocess as default,postprocess};
@@ -3,13 +3,11 @@ export declare type PreprocessOptions = {
3
3
  uniqueID: string;
4
4
  };
5
5
  /**
6
- * @param code source code to be preprocessed
6
+ * @param code source code for preprocessing
7
7
  * @param options {@link PreprocessOptions details}
8
8
  */
9
9
  export declare function preprocess(code: string, { uniqueID }?: Partial<PreprocessOptions>): {
10
- semicolons: number;
11
- autocomplete: string;
12
- seclevel: number;
13
10
  code: string;
11
+ seclevel: number;
14
12
  };
15
13
  export default preprocess;
@@ -1 +1 @@
1
- import{parse as e}from"@babel/parser";import{a as s}from"../assert-1b7dada8.js";import"fs";import"path";import{s as t}from"../spliceString-2c6f214f.js";function preprocess(a,{uniqueID:o="00000000000"}={}){var l,r;let c,i,n;if(s(o.match(/^\w{11}$/)),[,c,a,i]=a.match(/((?:^\s*\/\/.*\n)*)\s*((?:.+?\/\/\s*(.+?)\s*$)?[^]*)/m),a.match(/(?:SC|DB)\$/))throw new Error("SC$ and DB$ are protected and cannot appear in a script");for(const e of c.split("\n")){let[,s,t]=e.match(/^\s*\/\/\s*(?:@autocomplete\s*([^\s].*?)|@seclevel\s*([^\s].*?))\s*$/)||[];s?i=s:t&&(t.match(/^(?:fullsec|f|4|fs|full)$/i)?n=4:t.match(/^(?:highsec|h|3|hs|high)$/i)?n=3:t.match(/^(?:midsec|m|2|ms|mid)$/i)?n=2:t.match(/^(?:lowsec|l|1|ls|low)$/i)?n=1:t.match(/^(?:nullsec|n|0|ns|null)$/i)&&(n=0))}let p=4;a.match(/[#$][n0]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?p=0:a.match(/[#$][l1]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?p=1:a.match(/[#$][m2]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?p=2:a.match(/[#$][h3]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)&&(p=3);const h=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];if(null==n)n=p;else if(p<n)throw new Error(`detected seclevel ${h[p]} is lower than stated seclevel ${h[n]}`);const m=null!==(l=null===(r=a.match(/;/g))||void 0===r?void 0:r.length)&&void 0!==l?l:0,$=a;let f;for(a=a.replace(/^function\s*\(/,"export default function (");;){let l;try{f=e(a,{plugins:["typescript",["decorators",{decoratorsBeforeExport:!0}],"doExpressions","functionBind","functionSent","partialApplication",["pipelineOperator",{proposal:"hack",topicToken:"%"}],"throwExpressions",["recordAndTuple",{syntaxType:"hash"}],"classProperties","classPrivateProperties","classPrivateMethods","logicalAssignment","numericSeparator","nullishCoalescingOperator","optionalChaining","optionalCatchBinding","objectRestSpread"],sourceType:"module"});break}catch(e){s(e instanceof SyntaxError),l=e}var d;if("BABEL_PARSER_SYNTAX_ERROR"!=l.code||"PrivateInExpectedIn"!=l.reasonCode)throw console.log(null===(d=a.slice(l.pos).match(/.+/))||void 0===d?void 0:d[0]),l;const r=a.slice(l.pos);let c;if(c=r.match(/^#[fhmln43210]s\.scripts\.quine\(\)/))a=t(a,JSON.stringify($),l.pos,c[0].length);else if(c=r.match(/^#[fhmln43210]?s\.([a-z_][a-z_0-9]{0,24})\.([a-z_][a-z_0-9]{0,24})\(/))a=t(a,`$${o}$SUBSCRIPT$${c[1]}$${c[2]}(`,l.pos,c[0].length);else if(c=r.match(/^#D\(/))a=t(a,`$${o}$DEBUG(`,l.pos,c[0].length);else if(c=r.match(/^#FMCL/))a=t(a,`$${o}$FMCL`,l.pos,c[0].length);else if(c=r.match(/^#G/))a=t(a,`$${o}$GLOBAL`,l.pos,c[0].length);else{if(!(c=r.match(/^#db\.(i|r|f|u|u1|us|ObjectId)\(/)))throw l;a=t(a,`$${o}$DB$${c[1]}(`,l.pos,c[0].length)}}return{semicolons:m,autocomplete:i,seclevel:n,code:a}}export{preprocess as default,preprocess};
1
+ import e from"@babel/generator";import{parse as r}from"@babel/parser";import o from"@babel/traverse";import i from"@babel/types";import{a as t}from"../assert-1b7dada8.js";import{s}from"../spliceString-2c6f214f.js";const{default:p}=o,{default:a}=e;function preprocess(e,{uniqueID:o="00000000000"}={}){if(t(/^\w{11}$/.test(o)),/(?:SC|DB)\$/.test(e))throw new Error("SC$ and DB$ are protected and cannot appear in a script");const n=e;e=e.replace(/^function\s*\(/,"export default function (");const l={f:4,h:3,m:2,l:1,n:0,4:4,3:3,2:2,1:1,0:0};let c,f,d=4;for(;;){let i;try{c=r(e,{plugins:["typescript",["decorators",{decoratorsBeforeExport:!0}],"doExpressions","functionBind","functionSent","partialApplication",["pipelineOperator",{proposal:"hack",topicToken:"%"}],"throwExpressions",["recordAndTuple",{syntaxType:"hash"}],"classProperties","classPrivateProperties","classPrivateMethods","logicalAssignment","numericSeparator","nullishCoalescingOperator","optionalChaining","optionalCatchBinding","objectRestSpread"],sourceType:"module"});break}catch(e){t(e instanceof SyntaxError),i=e}var m;if("BABEL_PARSER_SYNTAX_ERROR"!=i.code||"PrivateInExpectedIn"!=i.reasonCode)throw console.log(null===(m=/.+/.exec(e.slice(i.pos)))||void 0===m?void 0:m[0]),i;const p=e.slice(i.pos);let a;if(a=/^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(p))e=s(e,JSON.stringify(n),i.pos,a[0].length);else if(a=/^#(?<seclevel>[0-4fhmln])?s\.(?<userName>[_a-z][\d_a-z]{0,24})\.(?<scriptName>[_a-z][\d_a-z]{0,24})\(/.exec(p))a[1]&&(d=Math.min(d,l[a[1]])),e=s(e,`$${o}$SUBSCRIPT$${a[2]}$${a[3]}(`,i.pos,a[0].length);else if(a=/^#D\(/.exec(p))e=s(e,`$${o}$DEBUG(`,i.pos,a[0].length);else if(a=/^#FMCL/.exec(p))e=s(e,`$${o}$FMCL`,i.pos,a[0].length);else if(a=/^#G/.exec(p))e=s(e,`$${o}$GLOBAL`,i.pos,a[0].length);else{if(!(a=/^#db\.(?<methodName>[irfu]|u1|us|ObjectId)\(/.exec(p)))throw i;e=s(e,`$${o}$DB$${a[1]}(`,i.pos,a[0].length)}}p(c,{Program(e){f=e,e.skip()}});const u=f.scope.hasGlobal("Record"),h=f.scope.hasGlobal("Tuple");return(u||h)&&c.program.body.unshift(i.importDeclaration(u?h?[i.importSpecifier(i.identifier("Record"),i.identifier("Record")),i.importSpecifier(i.identifier("Tuple"),i.identifier("Tuple"))]:[i.importSpecifier(i.identifier("Record"),i.identifier("Record"))]:[i.importSpecifier(i.identifier("Tuple"),i.identifier("Tuple"))],i.stringLiteral("@bloomberg/record-tuple-polyfill"))),f.scope.hasGlobal("Proxy")&&c.program.body.unshift(i.importDeclaration([i.importDefaultSpecifier(i.identifier("Proxy"))],i.stringLiteral("proxy-polyfill/src/proxy.js"))),{code:a(c).code,seclevel:d}}export{preprocess as default,preprocess};
@@ -0,0 +1,3 @@
1
+ import { NodePath } from "@babel/traverse";
2
+ import t, { Program } from "@babel/types";
3
+ export declare function getReferencePathsToGlobal(name: string, program: NodePath<Program>): NodePath<t.Identifier>[];
@@ -0,0 +1 @@
1
+ import e from"@babel/types";import{e as r}from"../assert-1b7dada8.js";function getReferencePathsToGlobal(t,a){const[o]=a.unshiftContainer("body",e.variableDeclaration("let",[e.variableDeclarator(e.identifier(t))]));a.scope.crawl();const n=r(a.scope.getBinding(t));return o.remove(),n.referencePaths}export{getReferencePathsToGlobal};
@@ -0,0 +1,22 @@
1
+ import t, { File } from "@babel/types";
2
+ export declare type TransformOptions = {
3
+ /** 11 a-z 0-9 characters */
4
+ uniqueID: string;
5
+ /** the user going to be hosting this script (or set to `true` if not yet known) */
6
+ scriptUser: string | true;
7
+ /** the name of this script (or set to `true` if not yet known) */
8
+ scriptName: string | true;
9
+ seclevel: number;
10
+ };
11
+ /**
12
+ * transform a given babel `File` to be hackmud compatible
13
+ *
14
+ * (returned File will need `postprocess()`ing)
15
+ *
16
+ * @param options {@link TransformOptions details}
17
+ */
18
+ export declare function transform(file: File, sourceCode: string, { uniqueID, scriptUser, scriptName, seclevel }?: Partial<TransformOptions>): {
19
+ file: t.File;
20
+ seclevel: number;
21
+ };
22
+ export default transform;
@@ -0,0 +1 @@
1
+ import e from"@babel/traverse";import t from"@babel/types";import{a as i}from"../assert-1b7dada8.js";import{getReferencePathsToGlobal as r}from"./shared.js";function clearObject(e,t=Object.prototype){for(const t of Object.getOwnPropertyNames(e))delete e[t];for(const t of Object.getOwnPropertySymbols(e))delete e[t];return Object.setPrototypeOf(e,t),e}const{default:n}=e,o=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"];function transform(e,a,{uniqueID:s="00000000000",scriptUser:p="UNKNOWN",scriptName:l="UNKNOWN",seclevel:c=4}={}){const d=`_SCRIPT_${s}_`,f=new Map,b=new Map;let y;if(n(e,{Program(e){y=e,e.skip()}}),y.scope.hasGlobal("_START"))for(const e of r("_START",y))e.replaceWith(t.identifier("_ST"));if(y.scope.hasGlobal("_TIMEOUT"))for(const e of r("_START",y))e.replaceWith(t.identifier("_TO"));if(y.scope.hasGlobal("_SOURCE"))for(const e of r("_SOURCE",y))e.replaceWith(t.stringLiteral(a));if(y.scope.hasGlobal("_BUILD_DATE"))for(const e of r("_BUILD_DATE",y))e.replaceWith(t.numericLiteral(Date.now()));if(y.scope.hasGlobal("_SCRIPT_USER"))for(const e of r("_SCRIPT_USER",y))1==p?e.replaceWith(t.stringLiteral(`$${s}$SCRIPT_USER`)):e.replaceWith(t.stringLiteral(p));if(y.scope.hasGlobal("_SCRIPT_NAME"))for(const e of r("_SCRIPT_NAME",y))1==l?e.replaceWith(t.stringLiteral(`$${s}$SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(l));if(y.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of r("_FULL_SCRIPT_NAME",y))1==p||1==l?e.replaceWith(t.stringLiteral(`$${s}$FULL_SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(`${p}.${l}`));let h=!1;if(y.scope.hasGlobal("Function")){const e=r("Function",y);if(1==e.length){const t=e[0];i("MemberExpression"==t.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),i("Identifier"==t.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),i("prototype"==t.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t.parentPath.replaceWith(createGetFunctionPrototypeNode())}else{for(const r of e)i("MemberExpression"==r.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),i("Identifier"==r.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),i("prototype"==r.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),h=!0,r.parentPath.replaceWith(t.identifier(`$${s}$FUNCTION_DOT_PROTOTYPE`));h=!0}}let $=4;for(const e of["$fs","$4s","$s"])if(y.scope.hasGlobal(e))for(const n of r(e,y)){var m;i("MemberExpression"==n.parent.type),i("Identifier"==n.parent.property.type),i("MemberExpression"==(null===(m=n.parentPath.parentPath)||void 0===m?void 0:m.node.type)),i("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}for(const e of["$hs","$3s"])if(y.scope.hasGlobal(e)){$=3;for(const n of r(e,y)){var E;i("MemberExpression"==n.parent.type),i("Identifier"==n.parent.property.type),i("MemberExpression"==(null===(E=n.parentPath.parentPath)||void 0===E?void 0:E.node.type)),i("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ms","$2s"])if(y.scope.hasGlobal(e)){$=2;for(const n of r(e,y)){var u;i("MemberExpression"==n.parent.type),i("Identifier"==n.parent.property.type),i("MemberExpression"==(null===(u=n.parentPath.parentPath)||void 0===u?void 0:u.node.type)),i("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ls","$1s"])if(y.scope.hasGlobal(e)){$=1;for(const n of r(e,y)){var P;i("MemberExpression"==n.parent.type),i("Identifier"==n.parent.property.type),i("MemberExpression"==(null===(P=n.parentPath.parentPath)||void 0===P?void 0:P.node.type)),i("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ns","$0s"])if(y.scope.hasGlobal(e)){$=0;for(const n of r(e,y)){var _;i("MemberExpression"==n.parent.type),i("Identifier"==n.parent.property.type),i("MemberExpression"==(null===(_=n.parentPath.parentPath)||void 0===_?void 0:_.node.type)),i("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}if(c=Math.min(c,$),y.scope.hasGlobal("$db"))for(const e of r("$db",y))i("MemberExpression"==e.parentPath.node.type),i("Identifier"==e.parentPath.node.property.type),e.parentPath.replaceWith(t.identifier(`$${s}$DB$${e.parentPath.node.property.name}`));if(y.scope.hasGlobal("$D"))for(const e of r("$D",y))e.replaceWith(t.identifier(`$${s}$DEBUG`));if(y.scope.hasGlobal("$FMCL"))for(const e of r("$FMCL",y))e.replaceWith(t.identifier(`$${s}$FMCL`));if(y.scope.hasGlobal("$G"))for(const e of r("$G",y))e.replaceWith(t.identifier(`$${s}$GLOBAL`));if(y.scope.hasGlobal("_SECLEVEL"))for(const e of r("_SECLEVEL",y))e.replaceWith(t.numericLiteral(c));let T=!1,O=!1;if(y.scope.hasGlobal("Object"))for(const e of r("Object",y))"MemberExpression"!=e.parent.type||e.parent.computed||(i("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(t.identifier(`$${s}$GET_PROTOTYPE_OF`)),T=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(t.identifier(`$${s}$SET_PROTOTYPE_OF`)),O=!0));const x=y.node.body[y.node.body.length-1];let S;if("ExportNamedDeclaration"==x.type){y.node.body.pop();for(const e of x.specifiers){i("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const t="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==t?S=e.local.name:f.set(e.local.name,t)}}const v=t.blockStatement([]);let D;for(const e of y.node.body)if("VariableDeclaration"==e.type)for(const i of e.declarations)if("Identifier"!=i.id.type||i.id.name!=S||!i.init||"FunctionExpression"!=i.init.type&&"ArrowFunctionExpression"!=i.init.type||i.init.async||i.init.generator){for(const r in t.getBindingIdentifiers(i.id))r==S&&(D=t.functionDeclaration(t.identifier(d),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(t.identifier(S),[]))]))),"const"!=e.kind&&f.has(r)&&(b.set(r,f.get(r)),f.delete(r)),v.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(r))]));i.init&&v.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else D=t.functionDeclaration(t.identifier(d),i.init.params,"BlockStatement"==i.init.body.type?i.init.body:t.blockStatement([t.returnStatement(i.init.body)]));else"FunctionDeclaration"==e.type?e.id.name==S?D=e:v.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(null,e.params,e.body,e.generator,e.async))])):v.body.push(e);if(D||(D=t.functionDeclaration(t.identifier(d),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),y.node.body=[D],v.body.length){(f.size||b.size)&&D.body.body.push(t.returnStatement(t.objectExpression([...[...f].map((([e,i])=>t.objectProperty(t.identifier(i),t.identifier(e)))),...[...b].map((([e,i])=>t.objectMethod("get",t.identifier(i),[],t.blockStatement([t.returnStatement(t.identifier(e))]))))]))),y.scope.crawl();const e=new Set;let n=0;for(const[r,o]of[...v.body.entries()].reverse())if("VariableDeclaration"==o.type){i(1==o.declarations.length);const a=o.declarations[0];if(i("Identifier"==a.id.type,`declarator.id.type was "${a.id.type}"`),y.scope.crawl(),y.scope.hasGlobal(a.id.name)){v.body.splice(r,1);const[p]=y.unshiftContainer("body",v),[l]=y.unshiftContainer("body",o);if(y.scope.crawl(),!a.init||"FunctionExpression"!=a.init.type&&"ArrowFunctionExpression"!=a.init.type||Object.keys(y.scope.globals).some((t=>e.has(t)))){const e=y.scope.getBinding(a.id.name);i(e);for(const r of e.referencePaths)i("Identifier"==r.node.type),r.replaceWith(t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(r.node.name)));for(const i of e.constantViolations)if("AssignmentExpression"==i.node.type)for(const[e,r]of Object.entries(t.getBindingIdentifiers(i.node)))e==a.id.name&&Object.assign(clearObject(r),t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(e)));p.remove(),l.remove(),a.init&&v.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(a.id.name)),a.init)))}else p.remove(),l.remove(),D.body.body.unshift(o),n++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&(y.scope.crawl(),y.scope.hasGlobal(o.id.name))){v.body.splice(r,1);const[e]=y.unshiftContainer("body",v),[n]=y.unshiftContainer("body",o);y.scope.crawl();const a=y.scope.getBinding(o.id.name);i(a);for(const e of a.referencePaths)i("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(e.node.name)));e.remove(),n.remove(),v.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(o.id.name)),t.classExpression(null,o.superClass,o.body,o.decorators))))}if(y.scope.hasGlobal("_EXPORTS"))for(const e of r("_EXPORTS",y))e.replaceWith(t.arrayExpression([...f.keys(),...b.keys()].map((e=>t.stringLiteral(e)))));v.body.length&&D.body.body.splice(n,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${s}$FMCL`)),v))}return h&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$FUNCTION_DOT_PROTOTYPE`),createGetFunctionPrototypeNode())])),O&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$SET_PROTOTYPE_OF`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`$${s}$DUNDER_PROTO_SETTER`)]))])),T&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$GET_PROTOTYPE_OF`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`$${s}$DUNDER_PROTO_GETTER`)]))])),(T||O)&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.objectPattern(T?O?[t.objectProperty(t.identifier("get"),t.identifier(`$${s}$DUNDER_PROTO_GETTER`)),t.objectProperty(t.identifier("set"),t.identifier(`$${s}$DUNDER_PROTO_SETTER`))]:[t.objectProperty(t.identifier("get"),t.identifier(`$${s}$DUNDER_PROTO_GETTER`))]:[t.objectProperty(t.identifier("set"),t.identifier(`$${s}$DUNDER_PROTO_SETTER`))]),t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getOwnPropertyDescriptor")),[t.memberExpression(t.identifier("Object"),t.identifier("prototype")),t.stringLiteral("__proto__")]))])),n(e,{BlockStatement({node:e}){for(const[i,r]of e.body.entries())"FunctionDeclaration"!=r.type||r.generator||(e.body.splice(i,1),e.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(r.id,t.arrowFunctionExpression(r.params,r.body,r.async))])))},ClassBody({node:e,scope:r,parent:o}){i(t.isClass(o));let a=!1;for(const i of e.body){if("ClassMethod"!=i.type)continue;let e=!1;if(n(i.body,{ThisExpression(i){e=!0,a=!0,i.replaceWith(t.identifier(`_THIS_${s}_`))},Function(e){e.skip()}},r),e)if("constructor"!=i.kind)i.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`),t.callExpression(t.memberExpression(t.super(),t.identifier("valueOf")),[]))]));else{const e=[];if(n(i.body,{CallExpression(t){"Super"==t.node.callee.type&&e.push(t)}},r),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==i)e[0].parentPath.replaceWith(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`),e[0].node)]));else{for(const i of e)i.replaceWith(t.assignmentExpression("=",t.identifier(`_THIS_${s}_`),i.node));i.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`))]))}else i.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`),t.callExpression(t.super(),[]))]))}}!o.superClass&&a&&(o.superClass=t.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(t.identifier("undefined"))},BigIntLiteral(e){const i=Number(e.node.value);BigInt(i)==BigInt(e.node.value)?e.replaceWith(t.callExpression(t.identifier("BigInt"),[t.numericLiteral(i)])):e.replaceWith(t.callExpression(t.identifier("BigInt"),[t.stringLiteral(e.node.value)]))}}),{file:e,seclevel:c};function createGetFunctionPrototypeNode(){for(const e of o)if(!y.scope.hasOwnBinding(e))return t.memberExpression(t.memberExpression(t.identifier(e),t.identifier("constructor")),t.identifier("prototype"));return t.memberExpression(t.memberExpression(t.arrowFunctionExpression([t.identifier("_")],t.identifier("_")),t.identifier("constructor")),t.identifier("prototype"))}}export{transform as default,transform};
package/pull.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @param sourceFolderPath path to folder containing source files
5
5
  * @param hackmudPath path to hackmud directory
6
- * @param script script to pull in `user.name` format
6
+ * @param script to pull in `user.name` format
7
7
  */
8
8
  export declare function pull(sourceFolderPath: string, hackmudPath: string, script: string): Promise<void>;
9
9
  export default pull;
package/pull.js CHANGED
@@ -1 +1 @@
1
- import{promises as t}from"fs";import{dirname as i,resolve as s}from"path";const{mkdir:c,copyFile:o}=t;async function pull(t,r,a){const[p,e]=a.split(".");await function copyFilePersistent(t,s,r){return o(t,s,r).catch((async a=>{if("ENOENT"!=a.code)throw a;await c(i(s),{recursive:!0}),await o(t,s,r)}))}(s(r,p,"scripts",`${e}.js`),s(t,p,`${e}.js`))}export{pull as default,pull};
1
+ import{promises as t}from"fs";import{dirname as r,resolve as i}from"path";const{mkdir:s,copyFile:o}=t;async function pull(t,a,e){const[c,n]=e.split(".");if(!c||!n)throw new Error('`script` argument must be in "user.name" format');await function copyFilePersistent(t,i,a){return o(t,i,a).catch((async e=>{if("ENOENT"!=e.code)throw e;await s(r(i),{recursive:!0}),await o(t,i,a)}))}(i(a,c,"scripts",`${n}.js`),i(t,c,`${n}.js`))}export{pull as default,pull};
package/push.d.ts CHANGED
@@ -1,24 +1,24 @@
1
1
  import { Info } from ".";
2
- interface PushOptions {
2
+ declare type PushOptions = {
3
+ /** whether to do the minify step (defaults to `true`) */
4
+ minify: boolean;
5
+ /** whether to mangle function and class names (defaults to `false`) */
6
+ mangleNames: boolean;
3
7
  /**
4
8
  * array of scripts in the format `foo.bar`
5
9
  *
6
- * also accepts wild card e.g. `*.bar` or `foo.*`
10
+ * also accepts wild card (`*`) e.g. `*.bar` or `foo.*`
7
11
  *
8
- * pushes everything by default
12
+ * pushes everything by default (`*.*`)
9
13
  */
10
14
  scripts: string | string[];
11
- /** callback when a script is pushed */
15
+ /** callback called on script push */
12
16
  onPush: (info: Info) => void;
13
- /** whether to do the minify step (defaults to `true`) */
14
- minify: boolean;
15
- /** whether to mangle function and class names (defaults to `false`) */
16
- mangleNames: boolean;
17
- }
17
+ };
18
18
  /**
19
19
  * Push scripts from a source directory to the hackmud directory.
20
20
  *
21
- * Files directly in the source folder are pushed to all users
21
+ * Pushes files directly in the source folder to all users
22
22
  * @param sourceDirectory directory containing source code
23
23
  * @param hackmudDirectory directory created by hackmud containing user data including scripts
24
24
  * @param options {@link PushOptions details}
package/push.js CHANGED
@@ -1 +1 @@
1
- import"fs";import"path";export{b as default,b as push}from"./processScript/compile.js";import"./processScript/minify.js";import"./generateTypings.js";import"@babel/generator";import"./assert-1b7dada8.js";import"perf_hooks";import"prettier";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"rollup";import"acorn";import"terser";import"./processScript/preprocess.js";import"./spliceString-2c6f214f.js";import"./pull.js";import"./syncMacros.js";import"chokidar";import"./processScript/postprocess.js";
1
+ import e,{promises as r}from"fs";import{dirname as t,resolve as i,extname as a,basename as s}from"path";import{c as p}from"./processScript/minify.js";import{s as o,processScript as n}from"./processScript/index.js";import"@babel/generator";import"@babel/traverse";import"@babel/types";import"./assert-1b7dada8.js";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"./processScript/shared.js";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";class DynamicMap extends Map{constructor(e){super(),this.fallbackHandler=e}get(e){if(super.has(e))return super.get(e);const r=this.fallbackHandler(e);return super.set(e,r),r}}const{writeFile:l,mkdir:c}=r;function writeFilePersistent(e,r,i){return l(e,r,i).catch((async a=>{if("ENOENT"!=a.code)throw a;await c(t(e),{recursive:!0}),await l(e,r,i)}))}const{readFile:m,readdir:u}=e.promises;async function push(e,r,{scripts:t="*.*",onPush:l=(()=>{}),minify:c=!0,mangleNames:g=!1}={}){"string"==typeof t&&(t=[t]);const f=new DynamicMap((e=>new Set)),b=new Set,h=new Set;let w=!1;for(const e of t){const[r,t]=e.split(".");r&&"*"!=r?t&&"*"!=t?f.get(r).add(t):b.add(r):t&&"*"!=t?h.add(t):w=!0}const d=new DynamicMap((e=>new Set)),y=[],$=new DynamicMap((e=>new Set));let P;if(h.size||w){const t=await u(i(r),{withFileTypes:!0}),s=new Set([...(P=await u(i(e),{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name)),...t.filter((e=>e.isDirectory())).map((e=>e.name)),...t.filter((e=>e.isFile()&&".key"==a(e.name))).map((e=>e.name.slice(0,-4))),...f.keys(),...b]);if(w)for(const e of s)b.add(e);else for(const e of s){const r=f.get(e);for(const e of h)r.add(e)}}return await Promise.all([...b].map((async t=>{await u(i(e,t),{withFileTypes:!0}).then((async u=>{await Promise.all(u.map((async u=>{const f=a(u.name);if(u.isFile()&&o.includes(f)){const a=s(u.name,f),o=i(e,t,u.name),{srcLength:b,script:h}=await n(await m(o,{encoding:"utf-8"}),{minify:c,scriptUser:t,scriptName:a,filePath:o,mangleNames:g}),w={file:`${t}/${u.name}`,users:[t],minLength:p(h),error:null,srcLength:b};$.get(t).add(a),y.push(w),await writeFilePersistent(i(r,t,`scripts/${a}.js`),h),l(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...f].map((async([t,a])=>{b.has(t)||await Promise.all([...a].map((async a=>{let s,u,f;for(const r of o)try{u=`${a}${r}`,s=await m(f=i(e,t,u),{encoding:"utf-8"});break}catch{}if(s){const{srcLength:e,script:o}=await n(s,{minify:c,scriptUser:t,scriptName:a,filePath:f,mangleNames:g}),m={file:`${t}/${u}`,users:[t],minLength:p(o),error:null,srcLength:e};y.push(m),await writeFilePersistent(i(r,t,"scripts",`${a}.js`),o),l(m)}else d.get(a).add(t)})))}))),await(b.size?Promise.all((P||await u(i(e),{withFileTypes:!0})).map((async t=>{const u=a(t.name);if(!t.isFile()||!o.includes(u))return;const f=s(t.name,u),h=[...b,...d.get(f)].filter((e=>!$.get(e).has(f)));if(!h.length)return;const w=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),P=i(e,t.name),{srcLength:S,script:j}=await n(await m(P,{encoding:"utf-8"}),{minify:c,scriptUser:!0,scriptName:f,uniqueID:w,filePath:P,mangleNames:g}),F={file:t.name,users:h,minLength:p(j),error:null,srcLength:S};await Promise.all(h.map((e=>writeFilePersistent(i(r,e,`scripts/${f}.js`),j.replace(new RegExp(`$${w}$SCRIPT_USER`,"g"),e).replace(new RegExp(`$${w}$FULL_SCRIPT_NAME`,"g"),`${e}.${f}`))))),y.push(F),l(F)}))):Promise.all([...d].map((async([t,a])=>{let s,u,f;for(const r of o)try{u=`${t}${r}`,s=await m(f=i(e,u),{encoding:"utf-8"});break}catch{}if(s){const e=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{srcLength:o,script:m}=await n(s,{minify:c,scriptUser:!0,scriptName:t,uniqueID:e,filePath:f,mangleNames:g}),b={file:u,users:[...a],minLength:p(m),error:null,srcLength:o};await Promise.all([...a].map((a=>writeFilePersistent(i(r,a,`scripts/${t}.js`),m.replace(new RegExp(`$${e}$SCRIPT_USER`,"g"),a).replace(new RegExp(`$${e}$FULL_SCRIPT_NAME`,"g"),`${a}.${t}`))))),y.push(b),l(b)}})))),y}export{DynamicMap as D,push as default,push,writeFilePersistent as w};
package/syncMacros.js CHANGED
@@ -1 +1 @@
1
- import{promises as e}from"fs";import{extname as t,basename as a,resolve as o}from"path";const{readFile:s,readdir:n,stat:r,writeFile:c}=e;async function syncMacros(e){const i=await n(e,{withFileTypes:!0}),m=new Map,f=[];for(const n of i)if(n.isFile())switch(t(n.name)){case".macros":{const t=(await s(o(e,n.name),{encoding:"utf-8"})).split("\n"),a=(await r(o(e,n.name))).mtime;for(let e=0;e<t.length/2-1;e++){const o=t[2*e],s=m.get(o);(!s||a>s.date)&&m.set(o,{date:a,macro:t[2*e+1]})}}break;case".key":f.push(a(n.name,".key"))}let l="",d=0;for(const[e,{macro:t}]of[...m].sort((([e],[t])=>(e>t)-(e<t))))t[0]==t[0].toLowerCase()&&(l+=`${e}\n${t}\n`,d++);for(const t of f)c(o(e,t+".macros"),l);return{macrosSynced:d,usersSynced:f.length}}export{syncMacros as default,syncMacros};
1
+ import e from"fs";import{extname as a,basename as s,resolve as t}from"path";const{readFile:o,readdir:n,stat:r,writeFile:c}=e.promises;async function syncMacros(e){const i=await n(e,{withFileTypes:!0}),m=new Map,l=[];await Promise.all(i.map((async n=>{if(n.isFile())switch(a(n.name)){case".macros":{const[a,s]=await Promise.all([o(t(e,n.name),{encoding:"utf-8"}).then((e=>e.split("\n"))),r(t(e,n.name)).then((({mtime:e})=>e))]);for(let e=0;e<a.length/2-1;e++){const t=a[2*e],o=m.get(t);(!o||s>o.date)&&m.set(t,{date:s,macro:a[2*e+1]})}}break;case".key":l.push(s(n.name,".key"))}})));let f="",p=0;for(const[e,{macro:a}]of[...m].sort((([e],[a])=>(e>a)-(e<a))))a[0]==a[0].toLowerCase()&&(f+=`${e}\n${a}\n`,p++);for(const a of l)c(t(e,`${a}.macros`),f);return{macrosSynced:p,usersSynced:l.length}}export{syncMacros as default,syncMacros};
package/test.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare function test(srcPath: string): Promise<{
1
+ export declare function test(sourcePath: string): Promise<{
2
2
  file: string;
3
3
  message: string;
4
4
  line: number;
package/test.js CHANGED
@@ -1 +1 @@
1
- import"fs";import"path";export{t as default,t as test}from"./processScript/compile.js";import"./generateTypings.js";import"@babel/generator";import"./assert-1b7dada8.js";import"./processScript/minify.js";import"@babel/parser";import"@babel/traverse";import"@babel/types";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"perf_hooks";import"prettier";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"rollup";import"./processScript/preprocess.js";import"./pull.js";import"./syncMacros.js";import"chokidar";import"./processScript/postprocess.js";
1
+ import p from"fs";import{resolve as o,extname as r}from"path";import{s as i,processScript as e}from"./processScript/index.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"./assert-1b7dada8.js";import"./processScript/minify.js";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"./processScript/shared.js";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";const{readFile:s,readdir:t}=p.promises;async function test(p){const l=[],a=[];for(const n of await t(p,{withFileTypes:!0}))n.isDirectory()?l.push(t(o(p,n.name),{withFileTypes:!0}).then((t=>{const l=[];for(const m of t)m.isFile()&&i.includes(r(m.name))&&l.push(s(o(p,n.name,m.name),{encoding:"utf-8"}).then(e).then((({warnings:p})=>a.push(...p.map((({message:p,line:o})=>({file:`${n.name}/${m.name}`,message:p,line:o})))))));return Promise.all(l)}))):n.isFile()&&i.includes(r(n.name))&&l.push(s(o(p,n.name),{encoding:"utf-8"}).then(e).then((({warnings:p})=>a.push(...p.map((({message:p,line:o})=>({file:n.name,message:p,line:o})))))));return await Promise.all(l),a}export{test as default,test};
package/watch.d.ts CHANGED
@@ -2,13 +2,13 @@ import { Info } from ".";
2
2
  /**
3
3
  * Watches target file or folder for updates and builds and pushes updated file.
4
4
  *
5
- * @param srcDir path to folder containing source files
6
- * @param hackmudDir path to hackmud directory
7
- * @param users users to push to (pushes to all if empty)
8
- * @param scripts scripts to push from (pushes from all if empty)
9
- * @param onPush function that's called after each script has been built and written
5
+ * @param sourceDirectory path to folder containing source files
6
+ * @param hackmudDirectory path to hackmud directory
7
+ * @param users to push to (pushes to all if empty)
8
+ * @param scripts to push from (pushes from all if empty)
9
+ * @param onPush function that's called on each script push
10
10
  */
11
- export declare function watch(srcDir: string, hackmudDir: string, users: string[], scripts: string[], onPush?: (info: Info) => void, { genTypes }?: {
11
+ export declare function watch(sourceDirectory: string, hackmudDirectory: string, users: string[], scripts: string[], onPush?: (info: Info) => void, { genTypes }?: {
12
12
  genTypes?: string | undefined;
13
13
  }): void;
14
14
  export default watch;
package/watch.js CHANGED
@@ -1 +1 @@
1
- import"fs";import"path";import"./processScript/minify.js";export{a as default,a as watch}from"./processScript/compile.js";import"chokidar";import"./generateTypings.js";import"@babel/generator";import"@babel/parser";import"@babel/traverse";import"@babel/types";import"./assert-1b7dada8.js";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"perf_hooks";import"prettier";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"rollup";import"./processScript/preprocess.js";import"./pull.js";import"./syncMacros.js";import"./processScript/postprocess.js";
1
+ import{watch as o}from"chokidar";import p from"fs";import{extname as r,basename as i,resolve as t}from"path";import{s as e,processScript as s}from"./processScript/index.js";import{generateTypings as n}from"./generateTypings.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"./assert-1b7dada8.js";import"./processScript/minify.js";import"./spliceString-2c6f214f.js";import"acorn";import"terser";import"./processScript/shared.js";import"perf_hooks";import"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./processScript/transform.js";const{readFile:a,readdir:l}=p.promises;function watch(p,c,m,b,u,{genTypes:g}={}){const h=o("",{depth:1,cwd:p,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async o=>{const n=r(o);if(e.includes(n)){const c=i(o,n);if(o==i(o)){if(!b.length||b.includes(c)){const n=await a(t(p,o),{encoding:"utf-8"}),c=new Map;await Promise.all((await l(p,{withFileTypes:!0})).map((async o=>{o.isDirectory()&&await l(t(p,o.name),{withFileTypes:!0}).then((p=>{for(const t of p){if(!t.isFile())continue;const p=r(t.name);if(!e.includes(p))continue;const s=i(t.name,p),n=c.get(s);n?n.push(o.name):c.set(s,[o.name])}}))})));let m=null;const{srcLength:b}=await s(n).catch((o=>(m=o,{script:"",srcLength:0}))),g={file:o,users:[],minLength:0,error:m,srcLength:b};u&&u(g)}}else{const r=i(t(o,".."));if((!m.length||m.includes(r))&&(!b.length||b.includes(c))){const i=await a(t(p,o),{encoding:"utf-8"});let e=null;const{srcLength:n}=await s(i).catch((o=>(e=o,{script:"",srcLength:0}))),l={file:o,users:[r],minLength:0,error:e,srcLength:n};null==u||u(l)}}}}));g&&(n(p,t(p,g),c),h.on("add",(()=>n(p,t(p,g),c))),h.on("unlink",(()=>n(p,t(p,g),c))))}export{watch as default,watch};
@@ -1,19 +0,0 @@
1
- import t from "@babel/types";
2
- export declare type CompileOptions = {
3
- /** 11 a-z 0-9 characters */
4
- uniqueID: string;
5
- /** the unprocessed source code (defaults to the given `code` parameter) */
6
- sourceCode: string;
7
- /** the user the script will be uploaded to (or set to `true` if it is not yet known) */
8
- scriptUser: string | true;
9
- /** the name of this script (or set to `true` if it is not yet known) */
10
- scriptName: string | true;
11
- seclevel: number;
12
- filePath: string;
13
- };
14
- /**
15
- * @param code the preprocessed code to be compiled into hackmud compatible code
16
- * @param options {@link CompileOptions details}
17
- */
18
- export declare function compile(code: string, { uniqueID, sourceCode, scriptUser, scriptName, seclevel, filePath }?: Partial<CompileOptions>): Promise<import("@babel/parser").ParseResult<t.File>>;
19
- export default compile;
@@ -1 +0,0 @@
1
- import{generateTypings as e}from"../generateTypings.js";import t from"@babel/generator";import{a as i,e as r}from"../assert-1b7dada8.js";import a,{promises as n}from"fs";import{dirname as o,resolve as s,extname as l,basename as c}from"path";import{g as p,minify as f}from"./minify.js";import{performance as d}from"perf_hooks";import m from"prettier";import{parse as u}from"@babel/parser";import h from"@babel/plugin-proposal-class-properties";import b from"@babel/plugin-proposal-class-static-block";import g from"@babel/plugin-proposal-decorators";import y from"@babel/plugin-proposal-do-expressions";import $ from"@babel/plugin-proposal-function-bind";import w from"@babel/plugin-proposal-function-sent";import E from"@babel/plugin-proposal-json-strings";import P from"@babel/plugin-proposal-logical-assignment-operators";import S from"@babel/plugin-proposal-nullish-coalescing-operator";import _ from"@babel/plugin-proposal-numeric-separator";import L from"@babel/plugin-proposal-object-rest-spread";import T from"@babel/plugin-proposal-optional-catch-binding";import D from"@babel/plugin-proposal-optional-chaining";import x from"@babel/plugin-proposal-partial-application";import v from"@babel/plugin-proposal-pipeline-operator";import F from"@babel/plugin-proposal-private-property-in-object";import I from"@babel/plugin-proposal-record-and-tuple";import R from"@babel/plugin-proposal-throw-expressions";import G from"@babel/plugin-transform-exponentiation-operator";import N from"@babel/plugin-transform-typescript";import C from"@babel/traverse";import k from"@babel/types";import M from"@rollup/plugin-babel";import W from"@rollup/plugin-commonjs";import U from"@rollup/plugin-json";import j from"@rollup/plugin-node-resolve";import{rollup as B}from"rollup";import"acorn";import"terser";import{preprocess as A}from"./preprocess.js";import"../pull.js";import"../syncMacros.js";import{watch as O}from"chokidar";import{postprocess as H}from"./postprocess.js";import"../spliceString-2c6f214f.js";class DynamicMap extends Map{constructor(e){super(),this.fallbackHandler=e}get(e){if(super.has(e))return super.get(e);const t=this.fallbackHandler(e);return super.set(e,t),t}}function forEachParallel(e,t){const i=[];for(const r of e)i.push(t(r));return Promise.all(i)}const{writeFile:q,mkdir:V}=n;function writeFilePersistent(e,t,i){return q(e,t,i).catch((async r=>{if("ENOENT"!=r.code)throw r;await V(o(e),{recursive:!0}),await q(e,t,i)}))}const{default:z}=C,{default:K}=M;async function compile(e,{uniqueID:t="00000000000",sourceCode:r=e,scriptUser:a="UNKNOWN",scriptName:n="UNKNOWN",seclevel:o=-1,filePath:l}={}){i(t.match(/^\w{11}$/));const c=l?s(l):"script",p=await B({plugins:[{name:"emit script",buildStart(){this.emitFile({type:"chunk",id:c})},load:t=>t==c?e:null,transform:e=>A(e,{uniqueID:t}).code},K({babelHelpers:"bundled",plugins:[[N.default],[g.default,{decoratorsBeforeExport:!0}],[y.default],[$.default],[w.default],[x.default],[v.default,{proposal:"hack",topicToken:"%"}],[R.default],[I.default,{syntaxType:"hash",importPolyfill:!0}],[h.default],[b.default],[F.default],[P.default],[_.default],[S.default],[D.default],[T.default],[E.default],[L.default],[G.default]],configFile:!1,extensions:re}),W(),j({extensions:re}),U()]});e=(await p.generate({})).output[0].code;const f=u(e,{sourceType:"module"}),d=`_SCRIPT_${t}_`,m=new Map,C=new Map;let M;if(z(f,{Program(e){M=e,e.skip()}}),M.scope.hasGlobal("_START"))for(const e of getReferencePathsToGlobal("_START",M))e.replaceWith(k.identifier("_ST"));if(M.scope.hasGlobal("_TIMEOUT"))for(const e of getReferencePathsToGlobal("_START",M))e.replaceWith(k.identifier("_TO"));if(M.scope.hasGlobal("_SOURCE"))for(const e of getReferencePathsToGlobal("_SOURCE",M))e.replaceWith(k.stringLiteral(r));if(M.scope.hasGlobal("_BUILD_DATE"))for(const e of getReferencePathsToGlobal("_BUILD_DATE",M))e.replaceWith(k.numericLiteral(Date.now()));if(M.scope.hasGlobal("_SCRIPT_USER"))for(const e of getReferencePathsToGlobal("_SCRIPT_USER",M))1==a?e.replaceWith(k.stringLiteral(`$${t}$SCRIPT_USER`)):e.replaceWith(k.stringLiteral(a));if(M.scope.hasGlobal("_SCRIPT_NAME"))for(const e of getReferencePathsToGlobal("_SCRIPT_NAME",M))1==n?e.replaceWith(k.stringLiteral(`$${t}$SCRIPT_NAME`)):e.replaceWith(k.stringLiteral(n));if(M.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of getReferencePathsToGlobal("_FULL_SCRIPT_NAME",M))1==a||1==n?e.replaceWith(k.stringLiteral(`$${t}$FULL_SCRIPT_NAME`)):e.replaceWith(k.stringLiteral(`${a}.${n}`));for(const e of["$fs","$hs","$ms","$ls","$ns","$4s","$3s","$2s","$1s","$0s"])if(M.scope.hasGlobal(e))for(const r of getReferencePathsToGlobal(e,M)){var O,H;i("MemberExpression"==r.parent.type),i("Identifier"==r.parent.property.type),i("MemberExpression"==(null===(O=r.parentPath.parentPath)||void 0===O?void 0:O.node.type)),i("Identifier"==(null===(H=r.parentPath.parentPath)||void 0===H?void 0:H.node.property.type)),r.parentPath.parentPath.replaceWith(k.identifier(`$${t}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}`))}if(M.scope.hasGlobal("$db"))for(const e of getReferencePathsToGlobal("$db",M))i("MemberExpression"==e.parentPath.node.type),i("Identifier"==e.parentPath.node.property.type),e.parentPath.replaceWith(k.identifier(`$${t}$DB$${e.parentPath.node.property.name}`));if(M.scope.hasGlobal("$D"))for(const e of getReferencePathsToGlobal("$D",M))e.replaceWith(k.identifier(`$${t}$DEBUG`));if(M.scope.hasGlobal("$FMCL"))for(const e of getReferencePathsToGlobal("$FMCL",M))e.replaceWith(k.identifier(`$${t}$FMCL`));if(M.scope.hasGlobal("$G"))for(const e of getReferencePathsToGlobal("$G",M))e.replaceWith(k.identifier(`$${t}$GLOBAL`));if(M.scope.hasGlobal("_SECLEVEL"))for(const e of getReferencePathsToGlobal("_SECLEVEL",M))e.replaceWith(o<0?k.unaryExpression("-",k.numericLiteral(-o)):k.numericLiteral(o));const q=k.blockStatement([]);let V;const X=[];for(const e of M.node.body)if("ExportDefaultDeclaration"==e.type)"FunctionDeclaration"==e.declaration.type||"FunctionExpression"==e.declaration.type||"ArrowFunctionExpression"==e.declaration.type?V=k.functionDeclaration(k.identifier(d),e.declaration.params,"BlockStatement"==e.declaration.body.type?e.declaration.body:k.blockStatement([k.returnStatement(e.declaration.body)])):(i(k.isExpression(e.declaration)),V=k.functionDeclaration(k.identifier(d),[k.identifier("context"),k.identifier("args")],k.blockStatement([k.returnStatement(k.callExpression(e.declaration,[]))])));else if("ExportNamedDeclaration"==e.type){if(e.declaration)if("VariableDeclaration"==e.declaration.type)for(const t of e.declaration.declarations)i("Identifier"==t.id.type,"global variable declarations using destructure syntax is currently unsupported"),"const"==e.declaration.kind?m.set(t.id.name,t.id.name):C.set(t.id.name,t.id.name),q.body.push(k.variableDeclaration("let",[k.variableDeclarator(t.id,t.init)]));else{i("id"in e.declaration&&e.declaration.id,`unsupported export type "${e.declaration.type}"`);const t="Identifier"==e.declaration.id.type?e.declaration.id.name:e.declaration.id.value;m.set(t,t),q.body.push(e.declaration)}else if(e.specifiers)for(const t of e.specifiers){i("ExportSpecifier"==t.type,`${t.type} is currently unsupported`);const e="Identifier"==t.exported.type?t.exported.name:t.exported.value;"default"==e?V=k.functionDeclaration(k.identifier(d),[k.identifier("context"),k.identifier("args")],k.blockStatement([k.returnStatement(k.callExpression(t.local,[]))])):X.includes(t.local.name)?C.set(t.local.name,e):m.set(t.local.name,e)}}else if("VariableDeclaration"==e.type)for(const t of e.declarations)i("Identifier"==t.id.type,"global variable declarations using destructure syntax is currently unsupported"),"const"!=e.kind&&(m.has(t.id.name)?(C.set(t.id.name,m.get(t.id.name)),m.delete(t.id.name)):X.push(t.id.name)),q.body.push(k.variableDeclaration("let",[k.variableDeclarator(t.id,t.init)]));else"FunctionDeclaration"==e.type?q.body.push(k.variableDeclaration("let",[k.variableDeclarator(e.id,k.functionExpression(null,e.params,e.body,e.generator,e.async))])):q.body.push(e);if(V||(V=k.functionDeclaration(k.identifier(d),[k.identifier("context"),k.identifier("args")],k.blockStatement([]))),M.node.body=[V],q.body.length){(m.size||C.size)&&V.body.body.push(k.returnStatement(k.objectExpression([...[...m].map((([e,t])=>k.objectProperty(k.identifier(t),k.identifier(e)))),...[...C].map((([e,t])=>k.objectMethod("get",k.identifier(t),[],k.blockStatement([k.returnStatement(k.identifier(e))]))))]))),M.scope.crawl();const e=new Set;let r=0;for(const[a,n]of q.body.entries())if("VariableDeclaration"==n.type){const o=n.declarations[0];if(i("Identifier"==o.id.type,"global variable declarations using destructure syntax is currently unsupported"),M.scope.crawl(),M.scope.hasGlobal(o.id.name)){q.body.splice(a,1);const[s]=M.unshiftContainer("body",q),[l]=M.unshiftContainer("body",n);if(M.scope.crawl(),!o.init||"FunctionExpression"!=o.init.type&&"ArrowFunctionExpression"!=o.init.type||Object.keys(M.scope.globals).find((t=>e.has(t)))){const e=M.scope.getBinding(o.id.name);i(e);for(const r of e.referencePaths)i("Identifier"==r.node.type),r.replaceWith(k.memberExpression(k.identifier(`$${t}$GLOBAL`),k.identifier(r.node.name)));s.remove(),l.remove(),o.init&&q.body.splice(a,0,k.expressionStatement(k.assignmentExpression("=",k.memberExpression(k.identifier(`$${t}$GLOBAL`),k.identifier(o.id.name)),o.init)))}else s.remove(),l.remove(),V.body.body.unshift(n),r++}else e.add(o.id.name)}else if("ClassDeclaration"==n.type&&(M.scope.crawl(),M.scope.hasGlobal(n.id.name))){q.body.splice(a,1);const[e]=M.unshiftContainer("body",q),[r]=M.unshiftContainer("body",n);M.scope.crawl();const o=M.scope.getBinding(n.id.name);i(o);for(const e of o.referencePaths)i("Identifier"==e.node.type),e.replaceWith(k.memberExpression(k.identifier(`$${t}$GLOBAL`),k.identifier(e.node.name)));e.remove(),r.remove(),q.body.splice(a,0,k.expressionStatement(k.assignmentExpression("=",k.memberExpression(k.identifier(`$${t}$GLOBAL`),k.identifier(n.id.name)),k.classExpression(null,n.superClass,n.body,n.decorators))))}if(M.scope.hasGlobal("_EXPORTS"))for(const e of getReferencePathsToGlobal("_EXPORTS",M))e.replaceWith(k.arrayExpression([...m.keys(),...C.keys()].map((e=>k.stringLiteral(e)))));q.body.length&&V.body.body.splice(r,0,k.ifStatement(k.unaryExpression("!",k.identifier(`$${t}$FMCL`)),q))}z(f,{BlockStatement({node:e}){for(const[t,i]of e.body.entries())"FunctionDeclaration"!=i.type||i.generator||(e.body.splice(t,1),e.body.unshift(k.variableDeclaration("let",[k.variableDeclarator(i.id,k.arrowFunctionExpression(i.params,i.body,i.async))])))},ClassBody({node:e,scope:r,parent:a}){i(k.isClass(a));let n=!1;for(const i of e.body){if("ClassMethod"!=i.type)continue;let e=!1;if(z(i.body,{ThisExpression(i){e=!0,n=!0,i.replaceWith(k.identifier(`_THIS_${t}_`))},Function(e){e.skip()}},r),e)if("constructor"!=i.kind)i.body.body.unshift(k.variableDeclaration("let",[k.variableDeclarator(k.identifier(`_THIS_${t}_`),k.callExpression(k.memberExpression(k.super(),k.identifier("valueOf")),[]))]));else{const e=[];if(z(i.body,{CallExpression(t){"Super"==t.node.callee.type&&e.push(t)}},r),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==i)e[0].parentPath.replaceWith(k.variableDeclaration("let",[k.variableDeclarator(k.identifier(`_THIS_${t}_`),e[0].node)]));else{for(const i of e)i.replaceWith(k.assignmentExpression("=",k.identifier(`_THIS_${t}_`),i.node));i.body.body.unshift(k.variableDeclaration("let",[k.variableDeclarator(k.identifier(`_THIS_${t}_`))]))}else i.body.body.unshift(k.variableDeclaration("let",[k.variableDeclarator(k.identifier(`_THIS_${t}_`),k.callExpression(k.super(),[]))]))}}!a.superClass&&n&&(a.superClass=k.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(k.identifier(`_UNDEFINED_${t}_`))},BigIntLiteral(e){const t=Number(e.node.value);BigInt(t)==BigInt(e.node.value)?e.replaceWith(k.callExpression(k.identifier("BigInt"),[k.numericLiteral(t)])):e.replaceWith(k.callExpression(k.identifier("BigInt"),[k.stringLiteral(e.node.value)]))}});const J=M.get("body.0").scope;for(const e of[...V.params].reverse()){if("Identifier"==e.type){if(!J.getBinding(e.name).referenced){V.params.pop();continue}}break}for(const e in M.scope.globals){if("arguments"==e||e.startsWith(`$${t}`))continue;const i=getReferencePathsToGlobal(e,M);if(!(5+e.length+i.length>=e.length*i.length)){for(const r of i)r.replaceWith(k.identifier(`_GLOBAL_${e}_${t}_`));V.body.body.unshift(k.variableDeclaration("let",[k.variableDeclarator(k.identifier(`_GLOBAL_${e}_${t}_`),k.identifier(e))]))}}return f}function getReferencePathsToGlobal(e,t){const[i]=t.unshiftContainer("body",k.variableDeclaration("let",[k.variableDeclarator(k.identifier(e))]));t.scope.crawl();const a=r(t.scope.getBinding(e));return i.remove(),a.referencePaths}const{format:X}=m,{default:J}=t;async function processScript(e,{minify:t=!0,uniqueID:r=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:a="UNKNOWN",scriptName:n="UNKNOWN",filePath:o,mangleNames:l=!1}={}){var c;i(r.match(/^\w{11}$/)),o=o?s(o):"script";const m=d.now(),u=e;let h,b,g;({autocomplete:h,code:e,seclevel:b,semicolons:g}=A(e,{uniqueID:r})),e=J(await compile(e,{uniqueID:r,sourceCode:u,scriptUser:a,scriptName:n,seclevel:b,filePath:o})).code;let y=p(e.replace(/^function\s*\w+\(/,"function("))-((null===(c=e.match(/;/g))||void 0===c?void 0:c.length)||0)+g;return e=t?await f(e,h,{uniqueID:r,mangleNames:l}):X(e,{parser:"babel",arrowParens:"avoid",semi:!1}),{srcLength:y,script:e=H(e,b,r),warnings:[],timeTook:d.now()-m}}const{readFile:Q,readdir:Y}=n;async function push(e,t,{scripts:i="*.*",onPush:r=(e=>{}),minify:a=!0,mangleNames:n=!1}={}){"string"==typeof i&&(i=[i]);const o=new DynamicMap((e=>new Set)),f=new Set,d=new Set;let m=!1;for(const e of i){const[t,i]=e.split(".");t&&"*"!=t?i&&"*"!=i?o.get(t).add(i):f.add(t):i&&"*"!=i?d.add(i):m=!0}const u=new DynamicMap((e=>new Set)),h=[],b=new DynamicMap((e=>new Set));let g;if(d.size||m){const i=await Y(s(t),{withFileTypes:!0}),r=new Set([...(g=await Y(s(e),{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name)),...i.filter((e=>e.isDirectory())).map((e=>e.name)),...i.filter((e=>e.isFile()&&".key"==l(e.name))).map((e=>e.name.slice(0,-4))),...o.keys(),...f]);if(m)for(const e of r)f.add(e);else for(const e of r){const t=o.get(e);for(const e of d)t.add(e)}}return await forEachParallel(f,(async i=>{await Y(s(e,i),{withFileTypes:!0}).then((async o=>{await forEachParallel(o,(async o=>{const f=l(o.name);if(o.isFile()&&re.includes(f)){const l=c(o.name,f),d=s(e,i,o.name),{srcLength:m,script:u}=await processScript(await Q(d,{encoding:"utf-8"}),{minify:a,scriptUser:i,scriptName:l,filePath:d,mangleNames:n}),g={file:`${i}/${o.name}`,users:[i],minLength:p(u),error:null,srcLength:m};b.get(i).add(l),h.push(g),await writeFilePersistent(s(t,i,`scripts/${l}.js`),u),r(g)}}))}),(e=>{if("ENOENT"!=e.code)throw e}))})),await forEachParallel(o,(async([i,o])=>{f.has(i)||await forEachParallel(o,(async o=>{let l,c,f;for(const t of re)try{c=`${o}${t}`,l=await Q(f=s(e,i,c),{encoding:"utf-8"});break}catch{}if(l){const{srcLength:e,script:d}=await processScript(l,{minify:a,scriptUser:i,scriptName:o,filePath:f,mangleNames:n}),m={file:`${i}/${c}`,users:[i],minLength:p(d),error:null,srcLength:e};h.push(m),await writeFilePersistent(s(t,i,"scripts",`${o}.js`),d),r(m)}else u.get(o).add(i)}))})),f.size?await forEachParallel(g||await Y(s(e),{withFileTypes:!0}),(async i=>{const o=l(i.name);if(!i.isFile()||!re.includes(o))return;const d=c(i.name,o),m=[...f,...u.get(d)].filter((e=>!b.get(e).has(d)));if(!m.length)return;const g=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),y=s(e,i.name),{srcLength:$,script:w}=await processScript(await Q(y,{encoding:"utf-8"}),{minify:a,scriptUser:!0,scriptName:d,uniqueID:g,filePath:y,mangleNames:n}),E={file:i.name,users:m,minLength:p(w),error:null,srcLength:$};await forEachParallel(m,(e=>writeFilePersistent(s(t,e,`scripts/${d}.js`),w.replace(new RegExp(`$${g}$SCRIPT_USER`,"g"),e).replace(new RegExp(`$${g}$FULL_SCRIPT_NAME`,"g"),`${e}.${d}`)))),h.push(E),r(E)})):await forEachParallel(u,(async([i,o])=>{let l,c,f;for(const t of re)try{c=`${i}${t}`,l=await Q(f=s(e,c),{encoding:"utf-8"});break}catch{}if(l){const e=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{srcLength:d,script:m}=await processScript(l,{minify:a,scriptUser:!0,scriptName:i,uniqueID:e,filePath:f,mangleNames:n}),u={file:c,users:[...o],minLength:p(m),error:null,srcLength:d};await forEachParallel(o,(r=>writeFilePersistent(s(t,r,`scripts/${i}.js`),m.replace(new RegExp(`$${e}$SCRIPT_USER`,"g"),r).replace(new RegExp(`$${e}$FULL_SCRIPT_NAME`,"g"),`${r}.${i}`)))),h.push(u),r(u)}})),h}const{readFile:Z,readdir:ee}=a.promises;async function test(e){const t=[],i=[];for(const r of await ee(e,{withFileTypes:!0}))r.isDirectory()?t.push(ee(s(e,r.name),{withFileTypes:!0}).then((t=>{const a=[];for(const n of t)n.isFile()&&re.includes(l(n.name))&&a.push(Z(s(e,r.name,n.name),{encoding:"utf-8"}).then(processScript).then((({warnings:e})=>i.push(...e.map((({message:e,line:t})=>({file:`${r.name}/${n.name}`,message:e,line:t})))))));return Promise.all(a)}))):r.isFile()&&re.includes(l(r.name))&&t.push(Z(s(e,r.name),{encoding:"utf-8"}).then(processScript).then((({warnings:e})=>i.push(...e.map((({message:e,line:t})=>({file:r.name,message:e,line:t})))))));return await Promise.all(t),i}const{readFile:te,readdir:ie}=n;function watch(t,i,r,a,n,{genTypes:o}={}){const f=O("",{depth:1,cwd:t,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async e=>{const o=l(e);if(re.includes(o)){const f=c(e,o);if(e==c(e)){if(!a.length||a.includes(f)){const a=await te(s(t,e),{encoding:"utf-8"}),o=new Map,d=[];for(const e of await ie(t,{withFileTypes:!0}))e.isDirectory()&&d.push(ie(s(t,e.name),{withFileTypes:!0}).then((t=>{for(const i of t){if(!i.isFile())continue;const t=l(i.name);if(!re.includes(t))continue;const r=c(i.name,t),a=o.get(r);a?a.push(e.name):o.set(r,[e.name])}})));await Promise.all(d);let m=null;const{script:u,srcLength:h}=await processScript(a).catch((e=>(m=e,{script:"",srcLength:0}))),b={file:e,users:[],minLength:0,error:m,srcLength:h},g=[];if(!m)if(u){const e=o.get(f)||[];b.minLength=p(u),r.length||(r=(await ie(i,{withFileTypes:!0})).filter((e=>e.isFile()&&".key"==l(e.name))).map((e=>c(e.name,".key"))));for(const t of r)e.includes(t)||(b.users.push(t),g.push(writeFilePersistent(s(i,t,"scripts",`${f}.js`),u)))}else b.error=new Error("processed script was empty");n&&(await Promise.all(g),n(b))}}else{const o=c(s(e,".."));if((!r.length||r.includes(o))&&(!a.length||a.includes(f))){const r=await te(s(t,e),{encoding:"utf-8"});let a=null;const{script:l,srcLength:c}=await processScript(r).catch((e=>(a=e,{script:"",srcLength:0}))),d={file:e,users:[o],minLength:0,error:a,srcLength:c};a||(l?(d.minLength=p(l),await writeFilePersistent(s(i,o,"scripts",`${f}.js`),l)):d.error=new Error("processed script was empty")),null==n||n(d)}}}}));o&&(e(t,s(t,o),i),f.on("add",(()=>e(t,s(t,o),i))),f.on("unlink",(()=>e(t,s(t,o),i))))}const re=[".js",".ts"];export{DynamicMap as D,watch as a,push as b,compile,compile as default,processScript as p,re as s,test as t,writeFilePersistent as w};