hackmud-script-manager 0.13.0-0425e06 → 0.13.0-3909530

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1 @@
1
+ class CustomError extends Error{constructor(...r){super(...r),function _defineProperty(r,e,s){return e in r?Object.defineProperty(r,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):r[e]=s,r}(this,"name",this.constructor.name)}}class AssertError extends CustomError{}function assert(r,e="assertion failed"){if(!r)throw new AssertError(e)}function ensure(r,e="ensure failed"){return assert(r,e),r}export{assert as a,ensure as e};
package/bin/hsm.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import e from"chalk";import o from"fs";import{homedir as s}from"os";import{resolve as t,basename as n,extname as c,dirname as a,relative as r}from"path";import{supportedExtensions as i,test as l,watch as g,push as d}from"../index.js";import{DynamicMap as f,hackmudLength as h,writeFilePersist as u}from"../lib.js";import{syncMacros as m}from"../syncMacros.js";import{pull as b}from"../pull.js";import{processScript as p}from"../processScript.js";import{generateTypings as k}from"../generateTypings.js";import"chokidar";import"@babel/core";import"@babel/generator";import"acorn";import"terser";const{readFile:w,rmdir:y,writeFile:$,mkdir:v}=o.promises,j=t(s(),".config"),S=t(j,"hsm.json"),P=new Map,x=[];let z;const N=e.rgb(255,244,4),_=e.rgb(243,249,152),E=e.rgb(179,255,155),I=e.rgb(255,150,224),O=e.rgb(30,255,0),T=e.rgb(202,202,202),F=new f((e=>{let o=0;for(const s of e)o+=(o>>1)+o+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[N,_,E,I,O,T][o%6](e)}));for(const e of process.argv.slice(2))if("-"==e[0]){const[o,s]=e.split("=");let t=s;if(t)if("true"==t)t=!0;else if("false"==t)t=!1;else{const e=Number(t);isFinite(e)&&(t=e)}else t=!0;if("-"==e[1])P.set(o.slice(2),t);else for(const e of o.slice(1))P.set(e,t)}else x.push(e);function L(){switch(x[0]){case"config":switch(x[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]");break;case"watch":console.log("hsm watch [dir]");break;case"pull":console.log("hsm pull <user.script>");break;case"minify":case"golf":console.log(`${n(process.argv[1])} ${x[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}async function M(){console.log("0.12.0")}async function q(){return z||(z=await w(S,{encoding:"utf-8"}).then((e=>{let o;try{o=JSON.parse(e)}catch{return console.log("config file was corrupted, resetting"),{}}return o&&"object"==typeof o?o:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${S}`),{}))))}function D(e,o,s=!1){for(const t of o)e=s?"object"==typeof e[t]?e[t]:e[t]={}:null==e?void 0:e[t];return e}function J(){if(z){const e=JSON.stringify(z);$(S,e).catch((async o=>{switch(o.code){case"EISDIR":await y(S);break;case"ENOENT":await v(j);break;default:throw o}$(S,e)}))}}function R({file:o,users:s,srcLength:a,minLength:r,error:i}){s.length&&(i?console.log(`error "${e.bold(i.message)}" in ${e.bold(o)}`):console.log(`pushed ${e.bold(o)} to ${s.map((o=>e.bold(F.get(o)))).join(", ")} | ${e.bold(String(r))} chars from ${e.bold(String(a))} | saved ${e.bold(String(a-r))} (${e.bold(`${Math.round(100*(1-r/a))}%`)}) | ${e.bold(`${t(z.hackmudPath,s[0],"scripts",n(o,c(o)))}.js`)}`))}(async()=>{var o,s,f,y,$,v;if(P.get("version")||P.get("v"))M();else if(P.get("help")||P.get("h"))L();else{switch(x[0]){case"push":{const t=await q();if(!t.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const n=x[1]||".",c=t.hackmudPath;let a,r;if(x[2]){const o=x[2].match(/^([a-z_][a-z_0-9]{0,24})\.([a-z_][a-z_0-9]{0,24})$/);if(!o){console.log(`"${e.bold(x[2])}" is not a valid script name`);break}a=[o[1]],r=[o[2]]}else a=(null===(o=P.get("users"))||void 0===o?void 0:o.toString().split(","))||[],r=(null===(s=P.get("scripts"))||void 0===s?void 0:s.toString().split(","))||[];await d(n,c,a,r,R),J()}break;case"dev":case"watch":{const e=await q();if(!e.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const o=x[1]||".",s=e.hackmudPath,t=(null===(f=P.get("users"))||void 0===f?void 0:f.toString().split(","))||[],n=(null===(y=P.get("scripts"))||void 0===y?void 0:y.toString().split(","))||[],c=null===($=P.get("gen-types"))||void 0===$?void 0:$.toString();g(o,s,t,n,R,{genTypes:c})}break;case"pull":{const e=await q();if(!e.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const o=x[1];if(!o){L();break}const s=x[2]||".",t=e.hackmudPath;try{await b(s,t,o)}catch(e){console.log("something went wrong, did you forget to #down the script?")}}break;case"sync-macros":{const{hackmudPath:e}=await q();if(!e){console.log("you need to set hackmudPath in config before you can use this command");break}const{macrosSynced:o,usersSynced:s}=await m(e);console.log(`synced ${o} macros to ${s} users`)}break;case"test":{const o=t(x[1]||".");let s=0;console.log(`testing scripts in ${e.bold(o)}\n`);for(const{file:t,line:n,message:c}of await l(o))console.log(`error "${e.bold(c)}" in ${e.bold(t)} on line ${e.bold(String(n))}`),s++;if(!s){console.log("no errors found");break}if(s){process.exitCode=1,console.log(`\nencountered ${e.bold(String(s))} errors`);break}console.log("no errors found")}break;case"gen-types":{const e=t(x[1]||".");let o;o=x[2]?t(x[2]):t(e,"../player.d.ts"),k(e,o,(await q()).hackmudPath)}break;case"config":switch(x[1]){case"get":console.log(D(await q(),x.slice(2)));break;case"delete":{const e=x.slice(2);if(!e.length){L();break}const o=await q();null===(v=D(o,e.slice(0,-1)))||void 0===v||delete v[e.slice(-1)[0]],console.log(o)}break;case"set":{const e=x.slice(2),o=e.pop();if(!e.length){L();break}const s=await q();let n=s;for(let o of e.slice(0,-1))n="object"==typeof n[o]?n[o]:n[o]={};n[e.slice(-1)[0]]=o,s.hackmudPath&&(s.hackmudPath=t(s.hackmudPath)),console.log(s)}break;default:x[1]&&console.log("unknown command"),L()}break;case"help":case"h":L();break;case"version":case"v":M();break;case"golf":case"minify":{if(!x[1]){console.log(`Target required\nUsage: ${n(process.argv[1])} ${x[0]} <target> [output]`);break}const o=c(x[1]);if(!i.includes(o)){console.log(`Unsupported file extension "${e.bold(o)}"\nSupported extensions are "${i.map((o=>e.bold(o))).join('", "')}"`);break}await w(x[1],{encoding:"utf-8"}).then((async s=>{const{script:c,srcLength:i,warnings:l}=await p(s);for(const{message:o,line:s}of l)console.log(`warning "${e.bold(o)}" on line ${e.bold(String(s))}`);let g;if(x[2])g=x[2];else{const e=n(x[1],o);g=t(a(x[1]),e.endsWith(".src")?`${e.slice(0,-4)}.js`:".js"==o?`${e}.min.js`:`${e}.js`)}const d=h(c);await u(g,c).catch((async e=>{if(!x[2]||"EISDIR"!=e.code)throw e;g=t(g,`${n(x[1],o)}.js`),await u(g,c)})).then((()=>console.log(`wrote ${e.bold(d)} chars to ${e.bold(r(".",g))} | saved ${e.bold(i-d)} chars`)),(e=>console.log(e.message)))}),(e=>console.log(e.message)))}break;default:x[0]&&console.log("unknown command"),L()}J()}})();
2
+ import o from"fs";import{resolve as e,basename as s,extname as t,dirname as r,relative as i}from"path";import{c as n}from"../processScript/minify.js";import{D as a,push as l}from"../push.js";import{w as c}from"../writeFilePersistent-4e3ff264.js";import p from"chalk";import{homedir as g}from"os";import{s as m,processScript as u}from"../processScript/index.js";import{generateTypings as f}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),T=p.rgb(255,150,224),E=p.rgb(30,255,0),F=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,T,E,F][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>")}}async function version(){console.log("0.13.0-3909530")}async function getConfig(){return x||(x=await 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:i,minLength:n,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(n))} chars from ${p.bold(String(i))} | saved ${p.bold(String(i-n))} (${p.bold(`${Math.round(100*(1-n/i))}%`)}) | ${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 l(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(","))||[],i=(null===(a=P.get("scripts"))||void 0===a?void 0:a.toString().split(","))||[],n=null===(g=P.get("gen-types"))||void 0===g?void 0:g.toString();k(s,t,r,i,onPushLogger,{genTypes:n})}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(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 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]||".");let s;s=C[2]?e(C[2]):e(o,"../player.d.ts"),f(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(!m.includes(o)){console.log(`Unsupported file extension "${p.bold(o)}"\nSupported extensions are "${m.map((o=>p.bold(o))).join('", "')}"`);break}await w(C[1],{encoding:"utf-8"}).then((async t=>{const a=s(C[1],o),l=a.endsWith(".src"),g=l?a.slice(0,-4):a;let m="UNKNOWN";"scripts"==s(e(C[1],".."))&&"hackmud"==s(e(C[1],"../../.."))&&(m=s(e(C[1],"../..")));const f=!P.get("skip-minify"),b=Boolean(P.get("mangle-names"));!f&&b&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const{script:d,srcLength:h,warnings:k,timeTook:w}=await u(t,{minify:f,scriptUser:m,scriptName:g,filePath:C[1],mangleNames:b});for(const{message:o,line:e}of k)console.log(`warning "${p.bold(o)}" on line ${p.bold(String(e))}`);let y;y=C[2]?C[2]:e(r(C[1]),l?`${g}.js`:".js"==o?`${a}.min.js`:`${a}.js`);const j=n(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 ${p.bold(j)} chars to ${p.bold(i(".",y))} | saved ${p.bold(h-j)} 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()}})();
@@ -1 +1 @@
1
- import t from"fs";import{extname as e,basename as n,resolve as s}from"path";const{readdir:r,writeFile:o}=t.promises;async function a(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=[],m={},p={};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=m[o.name]=[],i=p[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 $="";for(const t of c)$+=`import { script as $${t}$ } from "./src/${t}"\n`;$+="\n";for(const t in m){const e=m[t];for(const n of e)$+=`import { script as $${t}$${n}$ } from "./src/${t}/${n}"\n`}$+="\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)$+=`\t${t}: Subscript<typeof $${t}$>\n`;for(const t of l)$+=`\t${t}: (...args: any) => any\n`;$+="}\n\ndeclare global {\n\tinterface PlayerFullsec {";let y=!0;for(const t of f){const e=m[t],n=p[t];if(e&&e.length||n&&n.length){y=!0,$+=`\n\t\t${t}: WildFullsec & {\n`;for(const n of e)$+=`\t\t\t${n}: Subscript<typeof $${t}$${n}$>\n`;for(const t of n)$+=`\t\t\t${t}: (...args: any) => any\n`;$+="\t\t}"}else y&&($+="\n",y=!1),$+=`\t\t${t}: WildFullsec`;$+="\n"}$+="\t}\n}\n",await o(a,$)}export{a as default,a as generateTypings};
1
+ import e from"fs";import{extname as t,basename as n,resolve as s}from"path";const{readdir:r,writeFile:o}=e.promises;async function generateTypings(e,a,i){const f=new Set;if(i)for(const e of await r(i,{withFileTypes:!0}))e.isFile()&&".key"==t(e.name)&&f.add(n(e.name,".key"));const c=[],l=[],p={},m={};for(const o of await r(e,{withFileTypes:!0}))if(o.isFile())".ts"==t(o.name)?c.push(n(o.name,".ts")):".js"==t(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(e,o.name),{withFileTypes:!0}))f.isFile()&&(".ts"==t(f.name)?a.push(n(f.name,".ts")):".js"==t(f.name)&&i.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){$=!0,y+=`\n\t\t${e}: WildFullsec & {\n`;for(const n of t)y+=`\t\t\t${n}: Subscript<typeof $${e}$${n}$>\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 o(a,y)}export{generateTypings as default,generateTypings};
package/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ module.exports = null
2
+ import("./index.js").then(esModule => module.exports = esModule)
3
+ require("deasync").loopWhile(() => !module.exports)
package/index.d.ts CHANGED
@@ -1,3 +1,11 @@
1
+ export { supportedExtensions } from "./constants.json";
2
+ export { generateTypings } from "./generateTypings";
3
+ export { processScript } from "./processScript";
4
+ export { pull } from "./pull";
5
+ export { push } from "./push";
6
+ export { syncMacros } from "./syncMacros";
7
+ export { test } from "./test";
8
+ export { watch } from "./watch";
1
9
  export interface Info {
2
10
  file: string;
3
11
  users: string[];
@@ -5,11 +13,3 @@ export interface Info {
5
13
  minLength: number;
6
14
  error: Error | null;
7
15
  }
8
- export declare const supportedExtensions: string[];
9
- export * from "./push";
10
- export * from "./watch";
11
- export * from "./pull";
12
- export * from "./syncMacros";
13
- export * from "./test";
14
- export * from "./generateTypings";
15
- export * from "./processScript";
package/index.js CHANGED
@@ -1 +1 @@
1
- import e from"fs";import{resolve as s,extname as n,basename as t}from"path";import{watch as i}from"chokidar";import{hackmudLength as r,writeFilePersist as o}from"./lib.js";import{generateTypings as c}from"./generateTypings.js";export{generateTypings}from"./generateTypings.js";import{processScript as a}from"./processScript.js";export{processScript}from"./processScript.js";export{pull}from"./pull.js";export{syncMacros}from"./syncMacros.js";import"@babel/core";import"@babel/generator";import"acorn";import"terser";const{readFile:l,readdir:p}=e.promises;function m(e,i,c,m,h){return new Promise((async f=>{const u=[],g=await p(e,{withFileTypes:!0}),w=new Map,d=[];for(const f of g){const g=f.name;!f.isDirectory()||c.length&&!c.includes(g)||d.push(p(s(e,g),{withFileTypes:!0}).then((c=>{for(const p of c){const c=n(p.name),f=t(p.name,c);if(y.includes(c)&&p.isFile()&&(!m.length||m.includes(f))){let n=w.get(f);n?n.push(g):w.set(f,[g]),l(s(e,g,p.name),{encoding:"utf-8"}).then((async e=>{let n=null;const{srcLength:t,script:c}=await a(e).catch((e=>(n=e,{srcLength:0,script:""}))),l={file:`${g}/${p.name}`,users:[g],minLength:0,error:n,srcLength:t};u.push(l),n||(c?(l.minLength=r(c),await o(s(i,g,"scripts",`${f}.js`),c)):l.error=new Error("processed script was empty")),null==h||h(l)}))}}})))}c.length||(c=(await p(i,{withFileTypes:!0})).filter((e=>e.isFile()&&".key"==n(e.name))).map((e=>t(e.name,".key")))),Promise.all(d).then((()=>{const p=[];for(const f of g)if(f.isFile()){const g=n(f.name);if(y.includes(g)){const n=t(f.name,g);m.length&&!m.includes(n)||p.push(l(s(e,f.name),{encoding:"utf-8"}).then((async e=>{let t=null;const{script:l,srcLength:m}=await a(e).catch((e=>(t=e,{script:"",srcLength:0}))),g={file:f.name,users:[],minLength:0,error:t,srcLength:m};if(u.push(g),!t)if(l){g.minLength=r(l);const e=w.get(n)||[],t=[];for(const r of c)e.includes(r)||(g.users.push(r),t.push(o(s(i,r,"scripts",`${n}.js`),l)))}else g.error=new Error("processed script was empty");h&&Promise.all(p).then((()=>h(g)))})))}}Promise.all(p).then((()=>f(u)))}))}))}const{readFile:h,readdir:f}=e.promises;function u(e,l,p,m,u,{genTypes:g}={}){const w=i("",{depth:1,cwd:e,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async i=>{const c=n(i);if(y.includes(c)){const g=t(i,c);if(i==t(i)){if(!m.length||m.includes(g)){const c=await h(s(e,i),{encoding:"utf-8"}),m=new Map,w=[];for(const i of await f(e,{withFileTypes:!0}))i.isDirectory()&&w.push(f(s(e,i.name),{withFileTypes:!0}).then((e=>{for(const s of e){if(!s.isFile())continue;const e=n(s.name);if(!y.includes(e))continue;const r=t(s.name,e),o=m.get(r);o?o.push(i.name):m.set(r,[i.name])}})));await Promise.all(w);let d=null;const{script:L,srcLength:F}=await a(c).catch((e=>(d=e,{script:"",srcLength:0}))),T={file:i,users:[],minLength:0,error:d,srcLength:F},j=[];if(!d)if(L){const e=m.get(g)||[];T.minLength=r(L),p.length||(p=(await f(l,{withFileTypes:!0})).filter((e=>e.isFile()&&".key"==n(e.name))).map((e=>t(e.name,".key"))));for(const n of p)e.includes(n)||(T.users.push(n),j.push(o(s(l,n,"scripts",`${g}.js`),L)))}else T.error=new Error("processed script was empty");u&&(await Promise.all(j),u(T))}}else{const n=t(s(i,".."));if((!p.length||p.includes(n))&&(!m.length||m.includes(g))){const t=await h(s(e,i),{encoding:"utf-8"});let c=null;const{script:p,srcLength:m}=await a(t).catch((e=>(c=e,{script:"",srcLength:0}))),f={file:i,users:[n],minLength:0,error:c,srcLength:m};c||(p?(f.minLength=r(p),await o(s(l,n,"scripts",`${g}.js`),p)):f.error=new Error("processed script was empty")),null==u||u(f)}}}}));g&&(c(e,s(e,g),l),w.on("add",(()=>c(e,s(e,g),l))),w.on("unlink",(()=>c(e,s(e,g),l))))}const{readFile:g,readdir:w}=e.promises;async function d(e){const t=[],i=[];for(const r of await w(e,{withFileTypes:!0}))r.isDirectory()?t.push(w(s(e,r.name),{withFileTypes:!0}).then((t=>{const o=[];for(const c of t)c.isFile()&&y.includes(n(c.name))&&o.push(g(s(e,r.name,c.name),{encoding:"utf-8"}).then(a).then((({warnings:e})=>i.push(...e.map((({message:e,line:s})=>({file:`${r.name}/${c.name}`,message:e,line:s})))))));return Promise.all(o)}))):r.isFile()&&y.includes(n(r.name))&&t.push(g(s(e,r.name),{encoding:"utf-8"}).then(a).then((({warnings:e})=>i.push(...e.map((({message:e,line:s})=>({file:r.name,message:e,line:s})))))));return await Promise.all(t),i}const y=[".js",".ts"];export{m as push,y as supportedExtensions,d as test,u as watch};
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"./writeFilePersistent-4e3ff264.js";import"chokidar";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hackmud-script-manager",
3
- "version": "0.13.0-0425e06",
3
+ "version": "0.13.0-3909530",
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,30 +21,18 @@
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
- "bin"
28
- ],
29
24
  "main": "index.js",
30
- "bin": {
31
- "hsm": "bin/hsm.js"
32
- },
33
25
  "repository": {
34
26
  "type": "git",
35
27
  "url": "https://github.com/samualtnorman/hackmud-script-manager.git"
36
28
  },
37
- "scripts": {
38
- "build": "rollup -c",
39
- "dev": "rollup -cw",
40
- "gen-types": ""
41
- },
42
29
  "dependencies": {
43
30
  "@babel/core": "^7.16.0",
44
31
  "@babel/generator": "^7.16.0",
32
+ "@babel/parser": "^7.16.4",
45
33
  "@babel/plugin-proposal-class-properties": "^7.16.0",
46
34
  "@babel/plugin-proposal-class-static-block": "^7.16.0",
47
- "@babel/plugin-proposal-decorators": "^7.16.0",
35
+ "@babel/plugin-proposal-decorators": "^7.16.4",
48
36
  "@babel/plugin-proposal-do-expressions": "^7.16.0",
49
37
  "@babel/plugin-proposal-function-bind": "^7.16.0",
50
38
  "@babel/plugin-proposal-function-sent": "^7.16.0",
@@ -62,27 +50,64 @@
62
50
  "@babel/plugin-proposal-throw-expressions": "^7.16.0",
63
51
  "@babel/plugin-transform-exponentiation-operator": "^7.16.0",
64
52
  "@babel/plugin-transform-typescript": "^7.16.1",
65
- "acorn": "8.x",
66
- "chalk": "4.x",
67
- "chokidar": "3.x",
68
- "terser": "5.x"
53
+ "@babel/traverse": "^7.16.3",
54
+ "@babel/types": "^7.16.0",
55
+ "@bloomberg/record-tuple-polyfill": "^0.0.4",
56
+ "@rollup/plugin-babel": "^5.3.0",
57
+ "@rollup/plugin-commonjs": "^21.0.1",
58
+ "@rollup/plugin-json": "^4.1.0",
59
+ "@rollup/plugin-node-resolve": "^13.0.6",
60
+ "acorn": "^8.5.0",
61
+ "chalk": "^4.1.2",
62
+ "chokidar": "^3.5.2",
63
+ "prettier": "^2.4.1",
64
+ "proxy-polyfill": "^0.3.2",
65
+ "rollup": "^2.60.0",
66
+ "terser": "^5.10.0"
69
67
  },
70
68
  "devDependencies": {
71
- "@rollup/plugin-json": "^4.1.0",
72
- "@rollup/plugin-typescript": "^8.2.5",
69
+ "@babel/preset-env": "^7.16.4",
70
+ "@babel/preset-typescript": "^7.16.0",
71
+ "@samual/lib": "^0.2.0-27ea8d5",
73
72
  "@types/babel__core": "^7.1.16",
74
- "@types/node": "12.x",
75
- "@types/semver": "7.x",
76
- "rollup": "^2.56.3",
73
+ "@types/node": "^12.20.37",
74
+ "@types/prettier": "^2.4.2",
75
+ "@types/semver": "^7.3.9",
77
76
  "rollup-plugin-preserve-shebang": "^1.0.1",
78
77
  "rollup-plugin-terser": "^7.0.2",
79
- "semver": "7.x",
80
- "tslib": "^2.3.1",
81
- "typescript": "^4.4.4"
78
+ "semver": "^7.3.5",
79
+ "typescript": "^4.5.2"
80
+ },
81
+ "optionalDependencies": {
82
+ "deasync": "^0.1.24"
82
83
  },
83
84
  "engines": {
84
- "node": "^12.17 || ^13.1 || >=14"
85
+ "node": "^12.20 || >=14"
85
86
  },
86
87
  "types": "index.d.ts",
87
- "type": "module"
88
- }
88
+ "type": "module",
89
+ "exports": {
90
+ ".": {
91
+ "import": "./index.js",
92
+ "require": "./index.cjs"
93
+ },
94
+ "./*": "./*",
95
+ "./generateTypings": "./generateTypings.js",
96
+ "./index": "./index.js",
97
+ "./processScript/index": "./processScript/index.js",
98
+ "./processScript": "./processScript/index.js",
99
+ "./processScript/minify": "./processScript/minify.js",
100
+ "./processScript/postprocess": "./processScript/postprocess.js",
101
+ "./processScript/preprocess": "./processScript/preprocess.js",
102
+ "./processScript/shared": "./processScript/shared.js",
103
+ "./processScript/transform": "./processScript/transform.js",
104
+ "./pull": "./pull.js",
105
+ "./push": "./push.js",
106
+ "./syncMacros": "./syncMacros.js",
107
+ "./test": "./test.js",
108
+ "./watch": "./watch.js"
109
+ },
110
+ "bin": {
111
+ "hsm": "./bin/hsm.js"
112
+ }
113
+ }
@@ -0,0 +1,33 @@
1
+ export { minify } from "./minify";
2
+ export { postprocess } from "./postprocess";
3
+ export { preprocess } from "./preprocess";
4
+ export { transform as compile } from "./transform";
5
+ export declare type ProcessOptions = {
6
+ /** whether to minify the given code */
7
+ minify: boolean;
8
+ /** 11 a-z 0-9 characters */
9
+ uniqueID: string;
10
+ /** the user the script will be uploaded to (or set to `true` if it is not yet known) */
11
+ scriptUser: string | true;
12
+ /** the name of this script (or set to `true` if it is not yet known) */
13
+ scriptName: string | true;
14
+ filePath: string;
15
+ /** whether to mangle function and class names (defaults to `false`) */
16
+ mangleNames: boolean;
17
+ };
18
+ /**
19
+ * Minifies a given script
20
+ *
21
+ * @param code JavaScript or TypeScript code
22
+ * @param options {@link ProcessOptions details}
23
+ */
24
+ export declare function processScript(code: string, { minify: shouldMinify, uniqueID, scriptUser, scriptName, filePath, mangleNames }?: Partial<ProcessOptions>): Promise<{
25
+ srcLength: number;
26
+ script: string;
27
+ warnings: {
28
+ message: string;
29
+ line: number;
30
+ }[];
31
+ timeTook: number;
32
+ }>;
33
+ export default processScript;
@@ -0,0 +1 @@
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 a from"@babel/plugin-proposal-do-expressions";import p 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 j from"@babel/plugin-transform-exponentiation-operator";import x from"@babel/plugin-transform-typescript";import S from"@babel/traverse";import k from"@babel/types";import v from"@rollup/plugin-babel";import N from"@rollup/plugin-commonjs";import E from"@rollup/plugin-json";import L from"@rollup/plugin-node-resolve";import{a as _}from"../assert-1b7dada8.js";import{resolve as C}from"path";import{c as I,minify as U}from"./minify.js";export{minify}from"./minify.js";import{performance as $}from"perf_hooks";import D 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 T}from"./transform.js";export{transform as compile}from"./transform.js";import"../spliceString-2c6f214f.js";import"acorn";import"terser";import"./shared.js";const F=[".js",".ts"],{default:H}=v,{format:O}=D,{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:D="UNKNOWN",scriptName:B="UNKNOWN",filePath:G,mangleNames:z=!1}={}){_(v.match(/^\w{11}$/)),G=G?C(G):"script";const A=$.now(),J=e;let Q,R;const V=e.match(/^function\s*\((?:.+\/\/(.+)|)/);if(V)e=`export default ${e}`,Q=V[1];else for(const o of e.split("\n")){const e=o.match(/^\s*\/\/(.+)/);if(!e)break;const r=e[1].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}"`)}}}_(v.match(/^\w{11}$/));const X=G?C(G):"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:[[x.default],[s.default,{decoratorsBeforeExport:!0}],[a.default],[p.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],[j.default]],configFile:!1,extensions:F}),N(),L({extensions:F}),E()],treeshake:{moduleSideEffects:"no-external"}}),ee=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];let oe;if(e=(await Z.generate({})).output[0].code,({file:oe,seclevel:Y}=await T(o(e,{sourceType:"module"}),J,{uniqueID:v,scriptUser:D,scriptName:B,seclevel:Y})),null!=R&&Y<R)throw new Error(`detected seclevel ${ee[Y]} is lower than stated seclevel ${ee[R]}`);e=P(oe).code;let re=I(e.replace(/^function\s*\w+\(/,"function("));return S?e=await U(oe,Q,{uniqueID:v,mangleNames:z}):(K(oe,{MemberExpression({node:e}){e.computed||(_("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:$.now()-A}}export{processScript as default,processScript,F as s};
@@ -0,0 +1,14 @@
1
+ import { File } from "@babel/types";
2
+ declare type MinifyOptions = {
3
+ /** 11 a-z 0-9 characters */
4
+ uniqueID: string;
5
+ /** whether to mangle function and class names (defaults to `false`) */
6
+ mangleNames: boolean;
7
+ };
8
+ /**
9
+ * @param code compiled code and/or hackmud compatible code
10
+ * @param autocomplete the comment inserted after the function signature
11
+ * @param options {@link MinifyOptions details}
12
+ */
13
+ export declare function minify(file: File, autocomplete?: string, { uniqueID, mangleNames }?: Partial<MinifyOptions>): Promise<string>;
14
+ export default minify;
@@ -0,0 +1 @@
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(a.match(/^\w{11}$/)),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}_`)))}}),m=(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}_`)),_=!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;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)]))]);_&&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))]);_&&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)]))]);_&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${a}_`))),n.body.body.unshift(e),E=JSON.stringify(d)}else _&&n.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_UNDEFINED_${a}_`))]));y=l(e).code}if(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);for(const[e,t]of y.split("\t").entries())if(t==E){y=y.replace(`$${a}$SPLIT_INDEX`,await minifyNumber(e));break}}return countHackmudCharacters(m)<=countHackmudCharacters(y)+Number($)&&(y=m,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(await o.minify(`$(${e})`,{ecma:2015})).code.match(/\$\((.+)\)/)[1]}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};
@@ -0,0 +1,2 @@
1
+ export declare function postprocess(code: string, seclevel: number, uniqueID: string): string;
2
+ export default postprocess;
@@ -0,0 +1 @@
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,c){s=s.replace(/^function\s*\w+\(/,"function(");for(const{index:n,match:o}of[...findMatches(new RegExp(`\\$${c}\\$[\\w$]+`,"g"),s)].reverse()){const[c,...r]=o.slice(13).split("$");switch(c){case"SUBSCRIPT":s=e(s,`#${"nlmhf"[t]}s.${r[0]}.${r[1]}`,n,o.length);break;case"DEBUG":s=e(s,"#D",n,o.length);break;case"FMCL":s=e(s,"#FMCL",n,o.length);break;case"GLOBAL":s=e(s,"#G",n,o.length);break;case"DB":s=e(s,`#db.${r[0]}`,n,o.length)}}return s}export{postprocess as default,postprocess};
@@ -0,0 +1,13 @@
1
+ export declare type PreprocessOptions = {
2
+ /** 11 a-z 0-9 characters */
3
+ uniqueID: string;
4
+ };
5
+ /**
6
+ * @param code source code to be preprocessed
7
+ * @param options {@link PreprocessOptions details}
8
+ */
9
+ export declare function preprocess(code: string, { uniqueID }?: Partial<PreprocessOptions>): {
10
+ code: string;
11
+ seclevel: number;
12
+ };
13
+ export default preprocess;
@@ -0,0 +1 @@
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:a}=o,{default:p}=e;function preprocess(e,{uniqueID:o="00000000000"}={}){if(t(o.match(/^\w{11}$/)),e.match(/(?:SC|DB)\$/))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=e.slice(i.pos).match(/.+/))||void 0===m?void 0:m[0]),i;const a=e.slice(i.pos);let p;if(p=a.match(/^#[fhmln43210]s\.scripts\.quine\(\)/))e=s(e,JSON.stringify(n),i.pos,p[0].length);else if(p=a.match(/^#([fhmln43210])?s\.([a-z_][a-z_0-9]{0,24})\.([a-z_][a-z_0-9]{0,24})\(/))p[1]&&(d=Math.min(d,l[p[1]])),e=s(e,`$${o}$SUBSCRIPT$${p[2]}$${p[3]}(`,i.pos,p[0].length);else if(p=a.match(/^#D\(/))e=s(e,`$${o}$DEBUG(`,i.pos,p[0].length);else if(p=a.match(/^#FMCL/))e=s(e,`$${o}$FMCL`,i.pos,p[0].length);else if(p=a.match(/^#G/))e=s(e,`$${o}$GLOBAL`,i.pos,p[0].length);else{if(!(p=a.match(/^#db\.(i|r|f|u|u1|us|ObjectId)\(/)))throw i;e=s(e,`$${o}$DB$${p[1]}(`,i.pos,p[0].length)}}a(c,{Program(e){f=e,e.skip()}});const h=f.scope.hasGlobal("Record"),u=f.scope.hasGlobal("Tuple");return(h||u)&&c.program.body.unshift(i.importDeclaration(h?u?[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:p(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 the script will be uploaded to (or set to `true` if it is not yet known) */
6
+ scriptUser: string | true;
7
+ /** the name of this script (or set to `true` if it is 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>): Promise<{
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"];async 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;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,E;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"==(null===(E=n.parentPath.parentPath)||void 0===E?void 0:E.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 u,P;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"==(null===(P=n.parentPath.parentPath)||void 0===P?void 0:P.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 _,T;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"==(null===(T=n.parentPath.parentPath)||void 0===T?void 0:T.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 O,x;i("MemberExpression"==n.parent.type),i("Identifier"==n.parent.property.type),i("MemberExpression"==(null===(O=n.parentPath.parentPath)||void 0===O?void 0:O.node.type)),i("Identifier"==(null===(x=n.parentPath.parentPath)||void 0===x?void 0:x.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 v,S;i("MemberExpression"==n.parent.type),i("Identifier"==n.parent.property.type),i("MemberExpression"==(null===(v=n.parentPath.parentPath)||void 0===v?void 0:v.node.type)),i("Identifier"==(null===(S=n.parentPath.parentPath)||void 0===S?void 0:S.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 D=!1,g=!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`)),D=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(t.identifier(`$${s}$SET_PROTOTYPE_OF`)),g=!0));const I=y.node.body[y.node.body.length-1];let R;if("ExportNamedDeclaration"==I.type){y.node.body.pop();for(const e of I.specifiers){i("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const t="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==t?R=e.local.name:f.set(e.local.name,t)}}const L=t.blockStatement([]);let F;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!=R||!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==R&&(F=t.functionDeclaration(t.identifier(d),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(t.identifier(R),[]))]))),"const"!=e.kind&&f.has(r)&&(b.set(r,f.get(r)),f.delete(r)),L.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(r))]));i.init&&L.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else F=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==R?F=e:L.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(null,e.params,e.body,e.generator,e.async))])):L.body.push(e);if(F||(F=t.functionDeclaration(t.identifier(d),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),y.node.body=[F],L.body.length){(f.size||b.size)&&F.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[...L.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)){L.body.splice(r,1);const[p]=y.unshiftContainer("body",L),[l]=y.unshiftContainer("body",o);if(y.scope.crawl(),!a.init||"FunctionExpression"!=a.init.type&&"ArrowFunctionExpression"!=a.init.type||Object.keys(y.scope.globals).find((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&&L.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(),F.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))){L.body.splice(r,1);const[e]=y.unshiftContainer("body",L),[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(),L.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)))));L.body.length&&F.body.body.splice(n,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${s}$FMCL`)),L))}return h&&F.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$FUNCTION_DOT_PROTOTYPE`),createGetFunctionPrototypeNode())])),g&&F.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`)]))])),D&&F.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`)]))])),(D||g)&&F.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.objectPattern(D?g?[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.js CHANGED
@@ -1 +1 @@
1
- import{resolve as t}from"path";import{copyFilePersist as s}from"./lib.js";import"fs";async function i(i,o,p){const[r,a]=p.split(".");await s(t(o,r,"scripts",`${a}.js`),t(i,r,`${a}.js`))}export{i as default,i as pull};
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};
package/push.d.ts CHANGED
@@ -1,15 +1,28 @@
1
- import { Info } from ".";
1
+ import type { Info } from ".";
2
+ interface PushOptions {
3
+ /**
4
+ * array of scripts in the format `foo.bar`
5
+ *
6
+ * also accepts wild card e.g. `*.bar` or `foo.*`
7
+ *
8
+ * pushes everything by default
9
+ */
10
+ scripts: string | string[];
11
+ /** callback when a script is pushed */
12
+ 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
+ }
2
18
  /**
3
- * Push a specific or all scripts to a specific or all users.
4
- * In source directory, scripts in folders will override scripts with same name for user with folder name.
19
+ * Push scripts from a source directory to the hackmud directory.
5
20
  *
6
- * e.g. foo/bar.js overrides other bar.js script just for user foo.
7
- *
8
- * @param srcDir path to folder containing source files
9
- * @param hackmudDir path to hackmud directory
10
- * @param users users to push to (pushes to all if empty)
11
- * @param scripts scripts to push from (pushes from all if empty)
12
- * @param onPush function that's called when a script has been pushed
21
+ * Files directly in the source folder are pushed to all users
22
+ * @param sourceDirectory directory containing source code
23
+ * @param hackmudDirectory directory created by hackmud containing user data including scripts
24
+ * @param options {@link PushOptions details}
25
+ * @returns array of info on pushed scripts
13
26
  */
14
- export declare function push(srcDir: string, hackmudDir: string, users: string[], scripts: string[], onPush?: (info: Info) => void): Promise<Info[]>;
27
+ export declare function push(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify, mangleNames }?: Partial<PushOptions>): Promise<Info[]>;
15
28
  export default push;
package/push.js CHANGED
@@ -1 +1 @@
1
- import"fs";import"path";export{push as default,push}from"./index.js";import"./lib.js";import"./processScript.js";import"chokidar";import"./generateTypings.js";import"./pull.js";import"./syncMacros.js";import"@babel/core";import"@babel/generator";import"acorn";import"terser";
1
+ import e from"fs";import{resolve as r,extname as t,basename as i}from"path";import{c as a}from"./processScript/minify.js";import{w as s}from"./writeFilePersistent-4e3ff264.js";import{s as p,processScript as o}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{readFile:n,readdir:l}=e.promises;async function push(e,c,{scripts:m="*.*",onPush:g=(e=>{}),minify:u=!0,mangleNames:f=!1}={}){"string"==typeof m&&(m=[m]);const b=new DynamicMap((e=>new Set)),h=new Set,d=new Set;let w=!1;for(const e of m){const[r,t]=e.split(".");r&&"*"!=r?t&&"*"!=t?b.get(r).add(t):h.add(r):t&&"*"!=t?d.add(t):w=!0}const y=new DynamicMap((e=>new Set)),$=[],S=new DynamicMap((e=>new Set));let j;if(d.size||w){const i=await l(r(c),{withFileTypes:!0}),a=new Set([...(j=await l(r(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"==t(e.name))).map((e=>e.name.slice(0,-4))),...b.keys(),...h]);if(w)for(const e of a)h.add(e);else for(const e of a){const r=b.get(e);for(const e of d)r.add(e)}}return await Promise.all([...h].map((async m=>{await l(r(e,m),{withFileTypes:!0}).then((async l=>{await Promise.all(l.map((async l=>{const b=t(l.name);if(l.isFile()&&p.includes(b)){const t=i(l.name,b),p=r(e,m,l.name),{srcLength:h,script:d}=await o(await n(p,{encoding:"utf-8"}),{minify:u,scriptUser:m,scriptName:t,filePath:p,mangleNames:f}),w={file:`${m}/${l.name}`,users:[m],minLength:a(d),error:null,srcLength:h};S.get(m).add(t),$.push(w),await s(r(c,m,`scripts/${t}.js`),d),g(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...b].map((async([t,i])=>{h.has(t)||await Promise.all([...i].map((async i=>{let l,m,b;for(const a of p)try{m=`${i}${a}`,l=await n(b=r(e,t,m),{encoding:"utf-8"});break}catch{}if(l){const{srcLength:e,script:p}=await o(l,{minify:u,scriptUser:t,scriptName:i,filePath:b,mangleNames:f}),n={file:`${t}/${m}`,users:[t],minLength:a(p),error:null,srcLength:e};$.push(n),await s(r(c,t,"scripts",`${i}.js`),p),g(n)}else y.get(i).add(t)})))}))),h.size?await Promise.all((j||await l(r(e),{withFileTypes:!0})).map((async l=>{const m=t(l.name);if(!l.isFile()||!p.includes(m))return;const b=i(l.name,m),d=[...h,...y.get(b)].filter((e=>!S.get(e).has(b)));if(!d.length)return;const w=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),j=r(e,l.name),{srcLength:P,script:L}=await o(await n(j,{encoding:"utf-8"}),{minify:u,scriptUser:!0,scriptName:b,uniqueID:w,filePath:j,mangleNames:f}),N={file:l.name,users:d,minLength:a(L),error:null,srcLength:P};await Promise.all(d.map((e=>s(r(c,e,`scripts/${b}.js`),L.replace(new RegExp(`$${w}$SCRIPT_USER`,"g"),e).replace(new RegExp(`$${w}$FULL_SCRIPT_NAME`,"g"),`${e}.${b}`))))),$.push(N),g(N)}))):await Promise.all([...y].map((async([t,i])=>{let l,m,b;for(const i of p)try{m=`${t}${i}`,l=await n(b=r(e,m),{encoding:"utf-8"});break}catch{}if(l){const e=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{srcLength:p,script:n}=await o(l,{minify:u,scriptUser:!0,scriptName:t,uniqueID:e,filePath:b,mangleNames:f}),h={file:m,users:[...i],minLength:a(n),error:null,srcLength:p};await Promise.all([...i].map((i=>s(r(c,i,`scripts/${t}.js`),n.replace(new RegExp(`$${e}$SCRIPT_USER`,"g"),i).replace(new RegExp(`$${e}$FULL_SCRIPT_NAME`,"g"),`${i}.${t}`))))),$.push(h),g(h)}}))),$}export{DynamicMap as D,push as default,push};
@@ -0,0 +1 @@
1
+ function spliceString(i,e,s,c=0){return i.slice(0,s)+e+i.slice(s+c)}export{spliceString as s};
package/syncMacros.js CHANGED
@@ -1 +1 @@
1
- import e from"fs";import{extname as t,basename as o,resolve as a}from"path";const{readFile:s,readdir:n,stat:r,writeFile:c}=e.promises;async function i(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(a(e,n.name),{encoding:"utf-8"})).split("\n"),o=(await r(a(e,n.name))).mtime;for(let e=0;e<t.length/2-1;e++){const a=t[2*e],s=m.get(a);(!s||o>s.date)&&m.set(a,{date:o,macro:t[2*e+1]})}}break;case".key":f.push(o(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(a(e,t+".macros"),l);return{macrosSynced:d,usersSynced:f.length}}export{i as default,i as syncMacros};
1
+ import e from"fs";import{extname as t,basename as s,resolve as o}from"path";const{readFile:a,readdir:n,stat:r,writeFile:c}=e.promises;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 a(o(e,n.name),{encoding:"utf-8"})).split("\n"),s=(await r(o(e,n.name))).mtime;for(let e=0;e<t.length/2-1;e++){const o=t[2*e],a=m.get(o);(!a||s>a.date)&&m.set(o,{date:s,macro:t[2*e+1]})}}break;case".key":f.push(s(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};
package/test.js CHANGED
@@ -1 +1 @@
1
- import"fs";import"path";export{test as default,test}from"./index.js";import"./processScript.js";import"chokidar";import"./lib.js";import"./generateTypings.js";import"./pull.js";import"./syncMacros.js";import"@babel/core";import"@babel/generator";import"acorn";import"terser";
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
@@ -1,4 +1,4 @@
1
- import { Info } from ".";
1
+ import type { Info } from ".";
2
2
  /**
3
3
  * Watches target file or folder for updates and builds and pushes updated file.
4
4
  *
package/watch.js CHANGED
@@ -1 +1 @@
1
- import"chokidar";import"fs";import"path";export{watch as default,watch}from"./index.js";import"./lib.js";import"./generateTypings.js";import"./processScript.js";import"./pull.js";import"./syncMacros.js";import"@babel/core";import"@babel/generator";import"acorn";import"terser";
1
+ import r from"fs";import{extname as o,basename as i,resolve as p}from"path";import{c as t}from"./processScript/minify.js";import{w as e}from"./writeFilePersistent-4e3ff264.js";import{watch as s}from"chokidar";import{s as n,processScript as a}from"./processScript/index.js";import{generateTypings as l}from"./generateTypings.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";const{readFile:c,readdir:m}=r.promises;function watch(r,b,u,g,h,{genTypes:f}={}){const d=s("",{depth:1,cwd:r,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async s=>{const l=o(s);if(n.includes(l)){const f=i(s,l);if(s==i(s)){if(!g.length||g.includes(f)){const l=await c(p(r,s),{encoding:"utf-8"}),g=new Map,d=[];for(const t of await m(r,{withFileTypes:!0}))t.isDirectory()&&d.push(m(p(r,t.name),{withFileTypes:!0}).then((r=>{for(const p of r){if(!p.isFile())continue;const r=o(p.name);if(!n.includes(r))continue;const e=i(p.name,r),s=g.get(e);s?s.push(t.name):g.set(e,[t.name])}})));await Promise.all(d);let w=null;const{script:j,srcLength:y}=await a(l).catch((r=>(w=r,{script:"",srcLength:0}))),L={file:s,users:[],minLength:0,error:w,srcLength:y},F=[];if(!w)if(j){const r=g.get(f)||[];L.minLength=t(j),u.length||(u=(await m(b,{withFileTypes:!0})).filter((r=>r.isFile()&&".key"==o(r.name))).map((r=>i(r.name,".key"))));for(const o of u)r.includes(o)||(L.users.push(o),F.push(e(p(b,o,"scripts",`${f}.js`),j)))}else L.error=new Error("processed script was empty");h&&(await Promise.all(F),h(L))}}else{const o=i(p(s,".."));if((!u.length||u.includes(o))&&(!g.length||g.includes(f))){const i=await c(p(r,s),{encoding:"utf-8"});let n=null;const{script:l,srcLength:m}=await a(i).catch((r=>(n=r,{script:"",srcLength:0}))),u={file:s,users:[o],minLength:0,error:n,srcLength:m};n||(l?(u.minLength=t(l),await e(p(b,o,"scripts",`${f}.js`),l)):u.error=new Error("processed script was empty")),null==h||h(u)}}}}));f&&(l(r,p(r,f),b),d.on("add",(()=>l(r,p(r,f),b))),d.on("unlink",(()=>l(r,p(r,f),b))))}export{watch as default,watch};
@@ -0,0 +1 @@
1
+ import{promises as t}from"fs";import{dirname as i}from"path";const{writeFile:r,mkdir:e}=t;function writeFilePersistent(t,o,s){return r(t,o,s).catch((async a=>{if("ENOENT"!=a.code)throw a;await e(i(t),{recursive:!0}),await r(t,o,s)}))}export{writeFilePersistent as w};
package/bin/hsm.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/lib.d.ts DELETED
@@ -1,21 +0,0 @@
1
- /// <reference types="node" />
2
- import { PathLike } from "fs";
3
- export declare function writeFilePersist(path: string, data: any, options?: {
4
- encoding?: string | null | undefined;
5
- mode?: string | number | undefined;
6
- flag?: string | number | undefined;
7
- } | string | null): Promise<void>;
8
- export declare function copyFilePersist(src: PathLike, dest: string, flags?: number): Promise<void>;
9
- export declare function hackmudLength(script: string): number;
10
- export declare function stringSplice(original: string, replacement: string, start: number, end?: number): string;
11
- export declare class DynamicMap<K, V> extends Map<K, V> {
12
- private fallbackHandler;
13
- constructor(fallbackHandler: (key: K) => V);
14
- get(key: K): V;
15
- }
16
- export declare class CustomError extends Error {
17
- name: string;
18
- }
19
- export declare class AssertError extends CustomError {
20
- }
21
- export declare function assert(value: any, message?: string): asserts value;
package/lib.js DELETED
@@ -1 +0,0 @@
1
- import r from"fs";import{dirname as t}from"path";const{writeFile:e,mkdir:u,copyFile:s}=r.promises;function n(r,s,n){return e(r,s,n).catch((async c=>{if("ENOENT"!=c.code)throw c;await u(t(r),{recursive:!0}),await e(r,s,n)}))}function c(r,e,n){return s(r,e,n).catch((async c=>{if("ENOENT"!=c.code)throw c;await u(t(e),{recursive:!0}),await s(r,e,n)}))}function a(r){return r.replace(/\/\/.*/g,"").replace(/[ \t\n\r\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]/g,"").length}function i(r,t,e,u=e){return r.slice(0,e)+t+r.slice(u)}class o extends Map{constructor(r){super(),this.fallbackHandler=r}get(r){if(super.has(r))return super.get(r);const t=this.fallbackHandler(r);return super.set(r,t),t}}class f extends Error{constructor(){super(...arguments),this.name=this.constructor.name}}class l extends f{}function p(r,t="assertion failed"){if(!r)throw new l(t)}export{l as AssertError,f as CustomError,o as DynamicMap,p as assert,c as copyFilePersist,a as hackmudLength,i as stringSplice,n as writeFilePersist};
@@ -1,11 +0,0 @@
1
- /**
2
- * Minifies a given script
3
- *
4
- * @param script JavaScript or TypeScript code
5
- */
6
- export declare function processScript(script: string): Promise<{
7
- srcLength: number;
8
- script: string;
9
- warnings: never[];
10
- }>;
11
- export default processScript;
package/processScript.js DELETED
@@ -1 +0,0 @@
1
- import e from"@babel/core";import t from"@babel/generator";import{tokenizer as r,tokTypes as a}from"acorn";import{minify as i}from"terser";import{hackmudLength as s,assert as n,stringSplice as p}from"./lib.js";import"fs";import"path";const o=t.default;async function l(t){var r,a,l,_,f,m,b,g;let h,$,E;if([,h,t,$]=t.match(/((?:^\s*\/\/.*\n)*)\s*((?:.+?\/\/\s*(.+?)\s*$)?[^]*)/m),!t)throw new Error("script was empty");if(t.match(/(?:SC|DB)\$/))throw new Error("SC$ and DB$ are protected and cannot appear in a script");for(const e of h.split("\n")){let[,t,r]=e.match(/^\s*\/\/\s*(?:@autocomplete\s*([^\s].*?)|@seclevel\s*([^\s].*?))\s*$/)||[];t?$=t:r&&(r.match(/^(?:fullsec|f|4|fs|full)$/i)?E=4:r.match(/^(?:highsec|h|3|hs|high)$/i)?E=3:r.match(/^(?:midsec|m|2|ms|mid)$/i)?E=2:r.match(/^(?:lowsec|l|1|ls|low)$/i)?E=1:r.match(/^(?:nullsec|n|0|ns|null)$/i)&&(E=0))}let v=4;t.match(/[#$][n0]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?v=0:t.match(/[#$][l1]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?v=1:t.match(/[#$][m2]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)?v=2:t.match(/[#$][h3]s\.[a-z_][a-z_0-9]{0,24}\.[a-z_][a-z_0-9]{0,24}\(/)&&(v=3);const x=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];if(null==E)E=v;else if(v<E)throw new Error(`detected seclevel ${x[v]} is lower than stated seclevel ${x[E]}`);const L=null!==(a=null===(r=t.match(/;/g))||void 0===r?void 0:r.length)&&void 0!==a?a:0;t=t.replace(/#[fhmln43210]s\.scripts\.quine\(\)/g,JSON.stringify(t)).replace(/[#$][fhmln43210]?s\.([a-z_][a-z_0-9]{0,24})\.([a-z_][a-z_0-9]{0,24})\(/g,"SC$$$1$$$2(").replace(/^function\s*\(/,"function script(").replace(/#D\(/g,"$D(").replace(/#FMCL/g,"$FMCL").replace(/#G/g,"$G").replace(/[#$]db\./g,"DB$");const D=(await e.transformAsync(t,{plugins:["@babel/plugin-transform-typescript",["@babel/plugin-proposal-decorators",{decoratorsBeforeExport:!0}],"@babel/plugin-proposal-do-expressions","@babel/plugin-proposal-function-bind","@babel/plugin-proposal-function-sent","@babel/plugin-proposal-partial-application",["@babel/plugin-proposal-pipeline-operator",{proposal:"hack",topicToken:"%"}],"@babel/plugin-proposal-throw-expressions",["@babel/plugin-proposal-record-and-tuple",{syntaxType:"hash"}],"@babel/plugin-proposal-class-properties","@babel/plugin-proposal-class-static-block","@babel/plugin-proposal-private-property-in-object","@babel/plugin-proposal-logical-assignment-operators","@babel/plugin-proposal-numeric-separator","@babel/plugin-proposal-nullish-coalescing-operator","@babel/plugin-proposal-optional-chaining","@babel/plugin-proposal-optional-catch-binding","@babel/plugin-proposal-json-strings","@babel/plugin-proposal-object-rest-spread","@babel/plugin-transform-exponentiation-operator"],code:!1,ast:!0})).ast,[k]=D.program.body;"ExportNamedDeclaration"==k.type&&(D.program.body[0]=k.declaration);const S=(Math.random()*2**53).toString(36),N=[];let O=!1;e.traverse(D,{BlockStatement({node:t}){for(const[r,a]of t.body.entries())"FunctionDeclaration"!=a.type||a.generator||(t.body.splice(r,1),t.body.unshift(e.types.variableDeclaration("let",[e.types.variableDeclarator(a.id,e.types.arrowFunctionExpression(a.params,a.body,a.async))])))},ClassBody({node:t,scope:r}){for(const a of t.body)"ClassMethod"==a.type&&(e.traverse(a.body,{ThisExpression(t){t.replaceWith(e.types.identifier(`_THIS_${S}_`))}},r),"constructor"!=a.kind?a.body.body.unshift(e.types.variableDeclaration("let",[e.types.variableDeclarator(e.types.identifier(`_THIS_${S}_`),e.types.callExpression(e.types.memberExpression(e.types.super(),e.types.identifier("valueOf")),[]))])):(e.traverse(a.body,{CallExpression(t){"Super"==t.node.callee.type&&(t.replaceWith(e.types.assignmentExpression("=",e.types.identifier(`_THIS_${S}_`),t.node)),t.skip())}},r),a.body.body.unshift(e.types.variableDeclaration("let",[e.types.variableDeclarator(e.types.identifier(`_THIS_${S}_`))]))))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(t){t.replaceWith(e.types.identifier(`_UNDEFINED_${S}_`))},BigIntLiteral(t){const r=Number(t.node.value);BigInt(r)==BigInt(t.node.value)?t.replaceWith(e.types.callExpression(e.types.identifier("BigInt"),[e.types.numericLiteral(r)])):t.replaceWith(e.types.callExpression(e.types.identifier("BigInt"),[e.types.stringLiteral(t.node.value)]))},Identifier({node:e}){"_START"==e.name?e.name="_ST":"_TIMEOUT"==e.name&&(e.name="_TO")}}),t=o(D).code;let T,I=s(t.replace(/^function\s*\w+\(/,"function("))-(null!==(_=null===(l=t.match(/;/g))||void 0===l?void 0:l.length)&&void 0!==_?_:0)+L+(null!==(m=null===(f=t.match(/SC\$[a-zA-Z_][a-zA-Z0-9_]*\$[a-zA-Z_][a-zA-Z0-9_]*\(/g))||void 0===f?void 0:f.length)&&void 0!==m?m:0)+(null!==(g=null===(b=t.match(/DB\$/g))||void 0===b?void 0:b.length)&&void 0!==g?g:0);(t=(await i(t,{ecma:2015,parse:{bare_returns:!0},compress:{passes:1/0,unsafe:!0,booleans:!1}})).code||"").startsWith("function ")||(t=`function script(context, args) {\n${t}\n}`,I+=24);{const r=await e.parseAsync(t);e.traverse(r,{MemberExpression({node:t}){t.computed||(n("Identifier"==t.property.type),"prototype"==t.property.name?(t.computed=!0,t.property=e.types.identifier(`_PROTOTYPE_PROPERTY_${S}_`)):"__proto__"==t.property.name&&(t.computed=!0,t.property=e.types.identifier(`_PROTO_PROPERTY_${S}_`)))}}),T=(await i(o(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},format:{semicolons:!1}})).code.replace(new RegExp(`_PROTOTYPE_PROPERTY_${S}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${S}_`,"g"),'"__proto__"')}let w=null,z=!1;{const r=await e.parseAsync(t),a=[];e.traverse(r,{FunctionDeclaration(t){t.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(t){const r={};u(t.node,r)&&t.replaceWith(e.types.identifier(`_JSON_VALUE_${N.push(r)-1}_${S}_`))},ArrayExpression(t){const r=[];d(t.node,r)&&t.replaceWith(e.types.identifier(`_JSON_VALUE_${N.push(r)-1}_${S}_`))}}),t.traverse({TemplateLiteral(t){const r=t.node;let a=e.types.stringLiteral(r.quasis[0].value.cooked);for(let t=0;t<r.expressions.length;t++){const i=r.expressions[t],s=r.quasis[t+1];a=e.types.binaryExpression("+",a,i),s.value.cooked&&(a=e.types.binaryExpression("+",a,e.types.stringLiteral(s.value.cooked)))}t.replaceWith(a)},MemberExpression({node:t}){t.computed||(n("Identifier"==t.property.type),t.property.name.length<3||(t.computed=!0,t.property=e.types.stringLiteral(t.property.name)))},UnaryExpression(t){"void"!=t.node.operator||"NumericLiteral"!=t.node.argument.type||t.node.argument.value||(t.replaceWith(e.types.identifier(`_UNDEFINED_${S}_`)),O=!0)},NullLiteral(t){let r=N.indexOf(null);-1==r&&(r+=N.push(null)),t.replaceWith(e.types.identifier(`_JSON_VALUE_${r}_${S}_`))},BooleanLiteral(t){let r=N.indexOf(t.node.value);-1==r&&(r+=N.push(t.node.value)),t.replaceWith(e.types.identifier(`_JSON_VALUE_${r}_${S}_`))},NumericLiteral(t){a.push((async()=>{if((await c(t.node.value)).length<=3)return;"key"==t.parentKey&&"ObjectProperty"==t.parent.type&&(t.parent.computed=!0);let r=N.indexOf(t.node.value);-1==r&&(r+=N.push(t.node.value)),t.replaceWith(e.types.identifier(`_JSON_VALUE_${r}_${S}_`))})())},StringLiteral(t){if(t.node.value.includes("\0")||t.node.value.length<2)return;"key"==t.parentKey&&"ObjectProperty"==t.parent.type&&(t.parent.computed=!0);let r=N.indexOf(t.node.value);-1==r&&(r+=N.push(t.node.value)),t.replaceWith(e.types.identifier(`_JSON_VALUE_${r}_${S}_`))},ObjectProperty({node:t}){if(t.computed||"Identifier"!=t.key.type||t.key.name.length<4)return;let r=N.indexOf(t.key.name);-1==r&&(r+=N.push(t.key.name)),t.computed=!0,t.key=e.types.identifier(`_JSON_VALUE_${r}_${S}_`)}}),t.skip()}}),await Promise.all(a);const[i]=r.program.body;if(n("FunctionDeclaration"==i.type),N.length)if(z=!0,1==N.length)if("string"!=typeof N[0]||N[0].includes("\n")||N[0].includes("\t")){const t=e.types.variableDeclaration("let",[e.types.variableDeclarator(e.types.identifier(`_JSON_VALUE_0_${S}_`),e.types.callExpression(e.types.memberExpression(e.types.identifier("JSON"),e.types.identifier("parse")),[e.types.memberExpression(e.types.taggedTemplateExpression(e.types.memberExpression(e.types.callExpression(e.types.identifier("SC$scripts$quine"),[]),e.types.identifier("split")),e.types.templateLiteral([e.types.templateElement({raw:"\t",cooked:"\t"},!0)],[])),e.types.identifier(`_SPLIT_INDEX_${S}_`),!0)]))]);O&&t.declarations.push(e.types.variableDeclarator(e.types.identifier(`_UNDEFINED_${S}_`))),i.body.body.unshift(t),w=JSON.stringify(N[0])}else{const t=e.types.variableDeclaration("let",[e.types.variableDeclarator(e.types.identifier(`_JSON_VALUE_0_${S}_`),e.types.memberExpression(e.types.taggedTemplateExpression(e.types.memberExpression(e.types.callExpression(e.types.identifier("SC$scripts$quine"),[]),e.types.identifier("split")),e.types.templateLiteral([e.types.templateElement({raw:"\t",cooked:"\t"},!0)],[])),e.types.identifier(`_SPLIT_INDEX_${S}_`),!0))]);O&&t.declarations.push(e.types.variableDeclarator(e.types.identifier(`_UNDEFINED_${S}_`))),i.body.body.unshift(t),w=N[0]}else{const t=e.types.variableDeclaration("let",[e.types.variableDeclarator(e.types.arrayPattern(N.map(((t,r)=>e.types.identifier(`_JSON_VALUE_${r}_${S}_`)))),e.types.callExpression(e.types.memberExpression(e.types.identifier("JSON"),e.types.identifier("parse")),[e.types.memberExpression(e.types.taggedTemplateExpression(e.types.memberExpression(e.types.callExpression(e.types.identifier("SC$scripts$quine"),[]),e.types.identifier("split")),e.types.templateLiteral([e.types.templateElement({raw:"\t",cooked:"\t"},!0)],[])),e.types.identifier(`_SPLIT_INDEX_${S}_`),!0)]))]);O&&t.declarations.push(e.types.variableDeclarator(e.types.identifier(`_UNDEFINED_${S}_`))),i.body.body.unshift(t),w=JSON.stringify(N)}else O&&i.body.body.unshift(e.types.variableDeclaration("let",[e.types.variableDeclarator(e.types.identifier(`_UNDEFINED_${S}_`))]));t=o(r).code}if(t=(await i(t,{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},format:{semicolons:!1}})).code||"",null!=w){t=p(t,`${$?`//${$}\n`:""}\n//\t${w}\t\n`,y(t)+1);for(const[e,r]of t.split("\t").entries())if(r==w){t=t.replace(`_SPLIT_INDEX_${S}_`,await c(e));break}}return s(T)<=s(t)+Number(z)&&(t=T,$&&(t=p(t,`//${$}\n`,y(t)+1))),{srcLength:I,script:t=t.replace(/^function\s*\w+\(/,"function(").replace(/SC\$([a-zA-Z_][a-zA-Z0-9_]*)\$([a-zA-Z_][a-zA-Z0-9_]*)\(/g,`#${"nlmhf"[E]}s.$1.$2(`).replace(/\$D\(/g,"#D(").replace(/\$FMCL/g,"#FMCL").replace(/\$G/g,"#G").replace(/DB\$/g,"#db."),warnings:[]}}async function c(e){return(await i(`$(${e})`,{ecma:2015})).code.match(/\$\((.+)\)/)[1]}function y(e){const t=r(e,{ecmaVersion:2015});t.getToken(),t.getToken(),t.getToken();let i=1;for(;i;){const e=t.getToken();e.type==a.parenL?i++:e.type==a.parenR&&i--}return t.getToken().start}function u(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=[];d(r.value,e)&&(t["Identifier"==r.key.type?r.key.name:r.key.value]=e)}else if("ObjectExpression"==r.value.type){const e={};u(r.value,e)&&(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 d(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(!d(r,e))return!1;e.push(e)}else if("ObjectExpression"==r.type){const e={};if(!u(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}export{l as default,l as processScript};
package/rollup.config.js DELETED
@@ -1,84 +0,0 @@
1
- import json from "@rollup/plugin-json"
2
- import typescript from "@rollup/plugin-typescript"
3
- import { promises as fsPromises } from "fs"
4
- import preserveShebang from "rollup-plugin-preserve-shebang"
5
- import { terser } from "rollup-plugin-terser"
6
- import { dependencies } from "./package.json"
7
-
8
- const { readdir: readDirectory } = fsPromises
9
-
10
- /** @typedef {import("rollup").RollupOptions} RollupOptions */
11
-
12
- const sourceDirectory = "src"
13
-
14
- /** @type {(command: Record<string, unknown>) => Promise<RollupOptions>} */
15
- export default async () => ({
16
- input: Object.fromEntries((await findFiles(sourceDirectory))
17
- .filter(path => path.endsWith(".ts"))
18
- .map(path => [ path.slice(sourceDirectory.length + 1, -3), path ])
19
- ),
20
- output: {
21
- dir: "."
22
- },
23
- plugins: [
24
- json({ preferConst: true }),
25
- typescript({ tsconfig: `${sourceDirectory}/tsconfig.json` }),
26
- preserveShebang(),
27
- terser()
28
- ],
29
- external: [
30
- ...Object.keys(dependencies),
31
- "fs",
32
- "path",
33
- "os"
34
- ]
35
- })
36
-
37
- /**
38
- * @param path the directory to start recursively finding files in
39
- * @param filter either a blacklist or a filter function that returns false to ignore file name
40
- * @returns promise that resolves to array of found files
41
- * @type {(path: string, filter?: string[] | ((name: string) => boolean)) => Promise<string[]>}
42
- */
43
- async function findFiles(path, filter = []) {
44
- const paths = []
45
- let /** @type {(name: string) => boolean} */ filterFunction
46
-
47
- if (Array.isArray(filter))
48
- filterFunction = name => !filter.includes(name)
49
- else
50
- filterFunction = filter
51
-
52
- for (const dirent of await readDirectory(path, { withFileTypes: true })) {
53
- if (!filterFunction(dirent.name))
54
- continue
55
-
56
- const direntPath = `${path}/${dirent.name}`
57
-
58
- if (dirent.isDirectory())
59
- await findFilesSub(direntPath, filterFunction, paths)
60
- else if (dirent.isFile())
61
- paths.push(direntPath)
62
- }
63
-
64
- return paths
65
- }
66
-
67
- async function findFilesSub(path, filterFunction, paths) {
68
- const promises = []
69
-
70
- for (const dirent of await readDirectory(path, { withFileTypes: true })) {
71
- if (!filterFunction(dirent.name))
72
- continue
73
-
74
- const direntPath = `${path}/${dirent.name}`
75
-
76
- if (dirent.isDirectory())
77
- promises.push(findFilesSub(direntPath, filterFunction, paths))
78
- else if (dirent.isFile())
79
- paths.push(direntPath)
80
- }
81
-
82
- await Promise.all(promises)
83
- return paths
84
- }