hackmud-script-manager 0.19.0-f59b4c9 → 0.20.0-b71a8be
Sign up to get free protection for your applications and to get access to all the features.
- package/LICENSE +21 -674
- package/bin/hsm.d.ts +0 -0
- package/bin/hsm.js +1 -1
- package/constants.d.ts +2 -0
- package/{constants-9bb78688.js → constants.js} +1 -1
- package/generateTypeDeclaration.js +1 -1
- package/index.d.ts +2 -2
- package/index.js +1 -1
- package/package.json +45 -85
- package/processScript/index.d.ts +2 -2
- package/processScript/index.js +1 -1
- package/processScript/minify.d.ts +3 -3
- package/processScript/minify.js +1 -1
- package/processScript/postprocess.js +1 -1
- package/processScript/preprocess.d.ts +1 -1
- package/processScript/preprocess.js +1 -1
- package/processScript/shared.d.ts +3 -3
- package/processScript/shared.js +1 -1
- package/processScript/transform.d.ts +3 -3
- package/processScript/transform.js +1 -1
- package/pull.js +1 -1
- package/push.d.ts +3 -3
- package/push.js +1 -1
- package/syncMacros.js +1 -1
- package/tsconfig.tsbuildinfo +1 -1
- package/watch.d.ts +3 -3
- package/watch.js +1 -1
- package/assert-22a7ef8a.js +0 -1
- package/countHackmudCharacters-a08a265f.js +0 -1
- package/spliceString-0e6b5d6d.js +0 -1
- package/writeFilePersistent-ee9c9bfd.js +0 -1
package/bin/hsm.d.ts
CHANGED
File without changes
|
package/bin/hsm.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import{readFile as e,writeFile as t,mkdir as n,rmdir as a}from"fs/promises";import{homedir as s}from"os";import{s as o}from"../constants-9bb78688.js";import{generateTypeDeclaration as i}from"../generateTypeDeclaration.js";import{pull as r}from"../pull.js";import{syncMacros as c}from"../syncMacros.js";import{resolve as l,extname as f,basename as $,dirname as p,relative as h}from"path";import{D as m,w as d}from"../writeFilePersistent-ee9c9bfd.js";import{a as g}from"../assert-22a7ef8a.js";import{c as u}from"../countHackmudCharacters-a08a265f.js";import"fs";const y=l(s(),".config"),b=l(y,"hsm.json"),k=new Map,w=[],v=new m((e=>{let t=0;for(const n of e)t+=(t>>1)+t+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(n)+1;return[W,_,I,D,x,q][t%6](e)})),logNeedHackmudPathMessage=()=>console.error(R(`${C("You need to set hackmudPath in config before you can use this command")}\n\n${T("To fix this:")}\nOpen hackmud and run "${z("#dir")}"\nThis will open a file browser and print your hackmud user's script directory\nGo up 2 directories and then copy the path\nThen in a terminal run "${z("hsm")} ${x("config set")} ${A("hackmudPath")} ${q("<the path you copied>")}"`)),logHelp=()=>{const e="Push scripts from a directory to hackmud user's scripts directories",t="Watch a directory and push a script when modified",n="Minify a script file on the spot",a="Generate a type declaration file for a directory of scripts",s="Sync macros across all hackmud users",o="Retrieve a value from the config file",i="Assign a value to the config file",r="Remove a key and value from the config file",c="Pull a script a from a hackmud user's script directory",l="Skip minification to produce a readable script",f="Reduce character count further but lose function names in error call stacks",$="Force quine cheats even if the character count is higher";switch(console.log(J("Version")+R(": ")+A("0.19.0-f59b4c9")),w[0]){case"config":switch(w[1]){case"get":console.log(`\n${W(o)}\n\n${T("Usage:")}\n${z("hsm")} ${x(`${w[0]} ${w[1]}`)} ${q("<key>")}`);break;case"set":console.log(`\n${W(i)}\n\n${T("Usage:")}\n${z("hsm")} ${x(`${w[0]} ${w[1]}`)} ${q("<key> <value>")}`);break;case"delete":console.log(`\n${W(r)}\n\n${T("Usage:")}\n${z("hsm")} ${x(`${w[0]} ${w[1]}`)} ${q("<key>")}`);break;default:console.log(R(`${J("Config path")}: ${A(b)}\n\n${W("Modify the config file")}\n\n${T("Usage:")}\n${z("hsm")} ${x(`${w[0]} get`)} ${q("<key>")}\n ${o}\n${z("hsm")} ${x(`${w[0]} set`)} ${q("<key> <value>")}\n ${i}\n${z("hsm")} ${x(`${w[0]} delete`)} ${q("<key>")}\n ${r}`))}break;case"push":console.log(R(`\n${W(e)}\n\n${T("Usage:")}\n${z("hsm")} ${x(w[0])} ${q("<directory> [<script user>.<script name>...]")}\n\n${T("Options:")}\n${J("--skip-minify")}\n ${l}\n${J("--mangle-names")}\n ${f}\n${J("--force-quine-cheats")}\n ${$}`));break;case"dev":case"watch":console.log(R(`${J("Aliases")}: ${A("watch, dev")}\n\n${W(t)}\n\n${T("Usage:")}\n${z("hsm")} ${x(w[0])} ${q("<directory> [<script user>.<script name>...]")}\n\n${T("Options:")}\n${J("--skip-minify")}\n ${l}\n${J("--mangle-names")}\n ${f}\n${J("--type-declaration-path")}=${q("<path>")}\n Path to generate a type declaration file for the scripts\n${J("--force-quine-cheats")}\n ${$}`));break;case"pull":console.log(R(`\n${W(c)}\n\n${T("Usage:")}\n${z("hsm")} ${x(w[0])} ${q("<script user>")}${A(".")}${q("<script name>")}`));break;case"minify":case"golf":console.log(R(`${J("Aliases")}: ${A("minify, golf")}\n\n${W(n)}\n\n${T("Usage:")}\n${z("hsm")} ${x(w[0])} ${q("<target> [output path]")}\n\n${T("Options:")}\n${J("--skip-minify")}\n ${l}\n${J("--mangle-names")}\n ${f}\n${J("--force-quine-cheats")}\n ${$}\n${J("--watch")}\n Watch for changes`));break;case"generate-type-declaration":case"gen-type-declaration":case"gen-dts":case"gen-types":console.log(R(`${J("Aliases")}: ${A("generate-type-declaration, gen-type-declaration, gen-types, gen-dts")}\n\n${W(a)}\n\n${T("Usage:")}\n${z("hsm")} ${x(w[0])} ${q("<directory> [output path]")}`));break;case"sync-macros":console.log(`\n${W(s)}`);break;default:console.log(R(`\n${W("Hackmud Script Manager")}\n\n${T("Commands:")}\n${x("push")}\n ${e}\n${x("watch")}, ${x("dev")}\n ${t}\n${x("minify")}, ${x("golf")}\n ${n}\n${x("generate-type-declaration")}, ${x("gen-type-declaration")}, ${x("gen-types")}, ${x("gen-dts")}\n ${a}\n${x("sync-macros")}\n ${s}\n${x("config")}\n Modify and view the config file\n${x("pull")}\n ${c}`))}},exploreObject=(e,t,n=!1)=>{for(const s of t){var a;e=n?"object"==typeof e[s]?e[s]:e[s]={}:null===(a=e)||void 0===a?void 0:a[s]}return e},logInfo=({file:e,users:t,minLength:n,error:a},s)=>{a?logError(`error "${U.bold(a.message)}" in ${U.bold(e)}`):console.log(`pushed ${U.bold(e)} to ${t.map((e=>U.bold(v.get(e)))).join(", ")} | ${U.bold(String(n))} chars | ${U.bold(`${l(s,t[0],"scripts",$(e,f(e)))}.js`)}`)},log=e=>{console.log(R(e))},logError=e=>{console.error(C(e)),process.exitCode=1};for(const e of process.argv.slice(2))if("-"==e[0]){const[t,n]=e.split("=");let a=n;if(a)if("true"==a)a=!0;else if("false"==a)a=!1;else{const e=Number(a);isFinite(e)&&(a=e)}else a=!0;if("-"==e[1])k.set(t.slice(2),a);else for(const e of t.slice(1))k.set(e,a)}else w.push(e);("v"==w[0]||"version"==w[0]||k.get("version")||k.get("v"))&&(console.log("0.19.0-f59b4c9"),process.exit());let j=!1;const S=e(b,{encoding:"utf-8"}).then((e=>{let t;try{t=JSON.parse(e)}catch{return log("Config file was corrupted, resetting"),{}}return t&&"object"==typeof t?("hackmudPath"in t&&"string"!=typeof t.hackmudPath&&(log('Property "hackmudPath" of config file was corrupted, removing'),delete t.hackmudPath),t):(log("Config file was corrupted, resetting"),{})}),(()=>(j=!0,{}))),P=import("../push.js"),N=import("../processScript/index.js"),O=import("../watch.js"),M=import("chokidar"),{default:U}=await import("chalk"),T=U.rgb(255,255,255),q=U.rgb(202,202,202),z=U.rgb(155,155,155),C=U.rgb(255,0,0),W=U.rgb(255,244,4),_=U.rgb(243,249,152),x=U.rgb(30,255,0),I=U.rgb(179,255,155),J=U.rgb(0,255,255),R=U.rgb(122,178,244),A=U.rgb(255,0,236),D=U.rgb(255,150,224);switch((k.get("help")||k.get("h"))&&(logHelp(),process.exit()),w[0]){case"push":{const{hackmudPath:e}=await S;if(!e){logNeedHackmudPathMessage();break}const t=w[1];if(!t){logError("Must provide the directory to push from\n"),logHelp();break}const n=w.slice(2);if(n.length){const e=n.find((e=>!/^(?:[a-z_][a-z\d_]{0,24}|\*)\.(?:[a-z_][a-z\d_]{0,24}|\*)$/.test(e)));if(e){logError(`Invalid script name: ${JSON.stringify(e)}\n`),logHelp();break}}else n.push("*.*");if(k.has("skip-minify")&&k.has("mangle-names")){logError(`Option ${J("--mangle-names")} is not compatible with ${J("--skip-minify")}\n`),logHelp();break}const a=k.get("skip-minify");let s;if(null!=a){if("boolean"!=typeof a){logError(`The value for ${J("--skip-minify")} must be ${A("true")} or ${A("false")}\n`),logHelp();break}s=!a}const o=k.get("mangle-names");if(null!=o&&"boolean"!=typeof o){logError(`The value for ${J("--mangle-names")} must be ${A("true")} or ${A("false")}\n`),logHelp();break}const i=k.get("force-quine-cheats");if(null!=i&&"boolean"!=typeof i){logError(`The value for ${J("--force-quine-cheats")} must be ${A("true")} or ${A("false")}\n`),logHelp();break}const{push:r}=await P;(await r(t,e,{scripts:n,onPush:t=>logInfo(t,e),minify:s,mangleNames:o,forceQuineCheats:i})).length||logError("Could not find any scripts to push")}break;case"dev":case"watch":{var E;const{hackmudPath:e}=await S;if(!e){logNeedHackmudPathMessage();break}const t=w[1];if(!t){logError("Must provide the directory to watch\n"),logHelp();break}const n=w.slice(2);if(n.length){const e=n.find((e=>!/^(?:[a-z_][a-z\d_]{0,24}|\*)\.(?:[a-z_][a-z\d_]{0,24}|\*)$/.test(e)));if(e){logError(`Invalid script name: ${JSON.stringify(e)}\n`),logHelp();break}}else n.push("*.*");if(k.has("skip-minify")&&k.has("mangle-names")){logError(`Option ${J("--mangle-names")} is not compatible with ${J("--skip-minify")}\n`),logHelp();break}const a=k.get("skip-minify");let s;if(null!=a){if("boolean"!=typeof a){logError(`The value for ${J("--skip-minify")} must be ${A("true")} or ${A("false")}\n`),logHelp();break}s=!a}const o=k.get("mangle-names");if(null!=o&&"boolean"!=typeof o){logError(`The value for ${J("--mangle-names")} must be ${A("true")} or ${A("false")}\n`),logHelp();break}const i=k.get("force-quine-cheats");if(null!=i&&"boolean"!=typeof i){logError(`The value for ${J("--force-quine-cheats")} must be ${A("true")} or ${A("false")}\n`),logHelp();break}const{watch:r}=await O;r(t,e,{scripts:n,onPush:t=>logInfo(t,e),typeDeclarationPath:null===(E=k.get("type-declaration-path")||k.get("type-declaration")||k.get("dts")||k.get("gen-types"))||void 0===E?void 0:E.toString(),minify:s,mangleNames:o,onReady:()=>log("Watching"),forceQuineCheats:i})}break;case"pull":{const{hackmudPath:e}=await S;if(!e){logNeedHackmudPathMessage();break}const t=w[1];if(!t){logError("Must provide the script to pull\n"),logHelp();break}const n=w[2]||".";try{await r(n,e,t)}catch(e){console.error(e),logError(`Something went wrong, did you forget to ${z("#down")} the script?`)}}break;case"sync-macros":{const{hackmudPath:e}=await S;if(!e){logNeedHackmudPathMessage();break}const{macrosSynced:t,usersSynced:n}=await c(e);log(`Synced ${t} macros to ${n} users`)}break;case"generate-type-declaration":case"gen-type-declaration":case"gen-dts":case"gen-types":{const e=w[1];if(!e){logError("Must provide target directory\n"),logHelp();break}const n=l(e),a=w[2]||"./player.d.ts",s=await i(n,(await S).hackmudPath);let o=l(a);try{await t(o,s)}catch(e){if(g(e instanceof Error),"EISDIR"!=e.code)throw e;o=l(o,"player.d.ts"),await t(o,s)}log(`Wrote type declaration to ${U.bold(o)}`)}break;case"config":switch(w[1]){case"get":{const e=w[2];e?log(exploreObject(await S,e.split("."))):console.log(await S)}break;case"delete":{var F;const e=w[2];if(!e){logError("Must provide a key to delete\n"),logHelp();break}const t=e.split("."),n=t.map((e=>/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e))).join("."),a=t.pop();null===(F=exploreObject(await S,t))||void 0===F||delete F[a],log(`Removed ${A(n)} from config file`)}break;case"set":{const e=w[2],o=w[3];if(!e){logError("Must provide a key and value\n"),logHelp();break}const i=e.split("."),r=i.map((e=>/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e))).join(".");if(!o){logError(`Must provide a value for the key ${r}\n`),logHelp();break}const c=i.pop(),f=await S;if(i.length||"hackmudPath"!=c){let e=f;for(const t of i)"object"==typeof e[t]||(e[t]={}),e=e[t];e[c]=o}else f.hackmudPath=l(o.startsWith("~/")?s()+o.slice(1):o);console.log(f),(async e=>{const s=JSON.stringify(e,void 0,"\t");j&&log(`Creating config file at ${b}`),await t(b,s).catch((async e=>{switch(e.code){case"EISDIR":await a(b);break;case"ENOENT":await n(y);break;default:throw e}await t(b,s)}))})(f)}break;default:w[1]&&logError(`Unknown command: ${JSON.stringify(w[1])}\n`),logHelp()}break;case"help":case"h":logHelp();break;case"golf":case"minify":{const t=w[1];if(!t){logError("Must provide target\n"),logHelp();break}const n=f(t);if(!o.includes(n)){logError(`Unsupported file extension "${U.bold(n)}"\nSupported extensions are "${o.map((e=>U.bold(e))).join('", "')}"`);break}const{processScript:a}=await N,s=$(t,n),i=s.endsWith(".src"),r=i?s.slice(0,-4):s,c="scripts"==$(l(t,".."))&&"hackmud"==$(l(t,"../../.."))?$(l(t,"../..")):"UNKNOWN",m=!k.get("skip-minify");if(k.has("skip-minify")&&k.has("mangle-names")){logError(`Option ${J("--mangle-names")} would have no effect if minification is skipped\n`),logHelp();break}const g=k.get("mangle-names");if(null!=g&&"boolean"!=typeof g){logError(`The value for ${J("--mangle-names")} must be ${A("true")} or ${A("false")}\n`),logHelp();break}const y=g,b=k.get("force-quine-cheats");if(null!=b&&"boolean"!=typeof b){logError(`the value for ${J("--force-quine-cheats")} must be ${A("true")} or ${A("false")}\n`),logHelp();break}const v=b;let j=w[2]||l(p(t),i?`${r}.js`:".js"==n?`${s}.min.js`:`${s}.js`);const golfFile=()=>e(t,{encoding:"utf-8"}).then((async e=>{const s=performance.now(),{script:o,warnings:i}=await a(e,{minify:m,scriptUser:c,scriptName:r,filePath:t,mangleNames:y,forceQuineCheats:v}),f=performance.now()-s;for(const{message:e,line:t}of i)log(`Warning "${U.bold(e)}" on line ${U.bold(String(t))}`);await d(j,o).catch((async e=>{if(!w[2]||"EISDIR"!=e.code)throw e;j=l(j,`${$(t,n)}.js`),await d(j,o)})).then((()=>log(`Wrote ${U.bold(u(o))} chars to ${U.bold(h(".",j))} | took ${Math.round(100*f)/100}ms`)),(e=>logError(e.message)))}),(e=>logError(e.message)));if(k.get("watch")){const{watch:e}=await M;e(t,{awaitWriteFinish:{stabilityThreshold:100}}).on("ready",(()=>log(`Watching ${t}`))).on("change",golfFile)}else golfFile()}break;default:w[0]&&logError(`Unknown command: ${JSON.stringify(w[0])}\n`),logHelp()}
|
2
|
+
import{DynamicMap as e}from"@samual/lib/DynamicMap";import{assert as t}from"@samual/lib/assert";import{countHackmudCharacters as n}from"@samual/lib/countHackmudCharacters";import{writeFilePersistent as a}from"@samual/lib/writeFilePersistent";import{readFile as s,writeFile as o,mkdir as i,rmdir as r}from"fs/promises";import{homedir as c}from"os";import{supportedExtensions as l}from"../constants.js";import{generateTypeDeclaration as f}from"../generateTypeDeclaration.js";import{pull as $}from"../pull.js";import{syncMacros as p}from"../syncMacros.js";import{resolve as m,extname as h,basename as u,dirname as g,relative as d}from"path";import"@samual/lib/copyFilePersistent";const y="0.20.0-b71a8be",b=m(c(),".config"),k=m(b,"hsm.json"),w=new Map,v=[],S=new e((e=>{let t=0;for(const n of e)t+=(t>>1)+t+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(n)+1;return[_,x,J,F,I,z][t%6](e)})),logNeedHackmudPathMessage=()=>console.error(D(`${W("You need to set hackmudPath in config before you can use this command")}\n\n${q("To fix this:")}\nOpen hackmud and run "${C("#dir")}"\nThis will open a file browser and print your hackmud user's script directory\nGo up 2 directories and then copy the path\nThen in a terminal run "${C("hsm")} ${I("config set")} ${E("hackmudPath")} ${z("<the path you copied>")}"`)),logHelp=()=>{const e="Push scripts from a directory to hackmud user's scripts directories",t="Watch a directory and push a script when modified",n="Minify a script file on the spot",a="Generate a type declaration file for a directory of scripts",s="Sync macros across all hackmud users",o="Retrieve a value from the config file",i="Assign a value to the config file",r="Remove a key and value from the config file",c="Pull a script a from a hackmud user's script directory",l="Skip minification to produce a readable script",f="Reduce character count further but lose function names in error call stacks",$="Force quine cheats even if the character count is higher";switch(console.log(R("Version")+D(": ")+E(y)),v[0]){case"config":switch(v[1]){case"get":console.log(`\n${_(o)}\n\n${q("Usage:")}\n${C("hsm")} ${I(`${v[0]} ${v[1]}`)} ${z("<key>")}`);break;case"set":console.log(`\n${_(i)}\n\n${q("Usage:")}\n${C("hsm")} ${I(`${v[0]} ${v[1]}`)} ${z("<key> <value>")}`);break;case"delete":console.log(`\n${_(r)}\n\n${q("Usage:")}\n${C("hsm")} ${I(`${v[0]} ${v[1]}`)} ${z("<key>")}`);break;default:console.log(D(`${R("Config path")}: ${E(k)}\n\n${_("Modify the config file")}\n\n${q("Usage:")}\n${C("hsm")} ${I(`${v[0]} get`)} ${z("<key>")}\n ${o}\n${C("hsm")} ${I(`${v[0]} set`)} ${z("<key> <value>")}\n ${i}\n${C("hsm")} ${I(`${v[0]} delete`)} ${z("<key>")}\n ${r}`))}break;case"push":console.log(D(`\n${_(e)}\n\n${q("Usage:")}\n${C("hsm")} ${I(v[0])} ${z("<directory> [<script user>.<script name>...]")}\n\n${q("Options:")}\n${R("--skip-minify")}\n ${l}\n${R("--mangle-names")}\n ${f}\n${R("--force-quine-cheats")}\n ${$}`));break;case"dev":case"watch":console.log(D(`${R("Aliases")}: ${E("watch, dev")}\n\n${_(t)}\n\n${q("Usage:")}\n${C("hsm")} ${I(v[0])} ${z("<directory> [<script user>.<script name>...]")}\n\n${q("Options:")}\n${R("--skip-minify")}\n ${l}\n${R("--mangle-names")}\n ${f}\n${R("--type-declaration-path")}=${z("<path>")}\n Path to generate a type declaration file for the scripts\n${R("--force-quine-cheats")}\n ${$}`));break;case"pull":console.log(D(`\n${_(c)}\n\n${q("Usage:")}\n${C("hsm")} ${I(v[0])} ${z("<script user>")}${E(".")}${z("<script name>")}`));break;case"minify":case"golf":console.log(D(`${R("Aliases")}: ${E("minify, golf")}\n\n${_(n)}\n\n${q("Usage:")}\n${C("hsm")} ${I(v[0])} ${z("<target> [output path]")}\n\n${q("Options:")}\n${R("--skip-minify")}\n ${l}\n${R("--mangle-names")}\n ${f}\n${R("--force-quine-cheats")}\n ${$}\n${R("--watch")}\n Watch for changes`));break;case"generate-type-declaration":case"gen-type-declaration":case"gen-dts":case"gen-types":console.log(D(`${R("Aliases")}: ${E("generate-type-declaration, gen-type-declaration, gen-types, gen-dts")}\n\n${_(a)}\n\n${q("Usage:")}\n${C("hsm")} ${I(v[0])} ${z("<directory> [output path]")}`));break;case"sync-macros":console.log(`\n${_(s)}`);break;default:console.log(D(`\n${_("Hackmud Script Manager")}\n\n${q("Commands:")}\n${I("push")}\n ${e}\n${I("watch")}, ${I("dev")}\n ${t}\n${I("minify")}, ${I("golf")}\n ${n}\n${I("generate-type-declaration")}, ${I("gen-type-declaration")}, ${I("gen-types")}, ${I("gen-dts")}\n ${a}\n${I("sync-macros")}\n ${s}\n${I("config")}\n Modify and view the config file\n${I("pull")}\n ${c}`))}},exploreObject=(e,t,n=!1)=>{for(const a of t)e=n?"object"==typeof e[a]?e[a]:e[a]={}:e?.[a];return e},logInfo=({file:e,users:t,minLength:n,error:a},s)=>{a?logError(`error "${T.bold(a.message)}" in ${T.bold(e)}`):console.log(`pushed ${T.bold(e)} to ${t.map((e=>T.bold(S.get(e)))).join(", ")} | ${T.bold(String(n))} chars | ${T.bold(`${m(s,t[0],"scripts",u(e,h(e)))}.js`)}`)},log=e=>{console.log(D(e))},logError=e=>{console.error(W(e)),process.exitCode=1};for(const e of process.argv.slice(2))if("-"==e[0]){const[t,n]=e.split("=");let a=n;if(a)if("true"==a)a=!0;else if("false"==a)a=!1;else{const e=Number(a);isFinite(e)&&(a=e)}else a=!0;if("-"==e[1])w.set(t.slice(2),a);else for(const e of t.slice(1))w.set(e,a)}else v.push(e);("v"==v[0]||"version"==v[0]||w.get("version")||w.get("v"))&&(console.log(y),process.exit());let P=!1;const j=s(k,{encoding:"utf-8"}).then((e=>{let t;try{t=JSON.parse(e)}catch{return log("Config file was corrupted, resetting"),{}}return t&&"object"==typeof t?("hackmudPath"in t&&"string"!=typeof t.hackmudPath&&(log('Property "hackmudPath" of config file was corrupted, removing'),delete t.hackmudPath),t):(log("Config file was corrupted, resetting"),{})}),(()=>(P=!0,{}))),N=import("../push.js"),O=import("../processScript/index.js"),M=import("../watch.js"),U=import("chokidar"),{default:T}=await import("chalk"),q=T.rgb(255,255,255),z=T.rgb(202,202,202),C=T.rgb(155,155,155),W=T.rgb(255,0,0),_=T.rgb(255,244,4),x=T.rgb(243,249,152),I=T.rgb(30,255,0),J=T.rgb(179,255,155),R=T.rgb(0,255,255),D=T.rgb(122,178,244),E=T.rgb(255,0,236),F=T.rgb(255,150,224);(w.get("help")||w.get("h"))&&(logHelp(),process.exit());let A=!0;switch(v[0]){case"push":{const{hackmudPath:e}=await j;if(!e){logNeedHackmudPathMessage();break}const t=v[1];if(!t){logError("Must provide the directory to push from\n"),logHelp();break}const n=v.slice(2);if(n.length){const e=n.find((e=>!/^(?:[a-z_][a-z\d_]{0,24}|\*)\.(?:[a-z_][a-z\d_]{0,24}|\*)$/.test(e)));if(e){logError(`Invalid script name: ${JSON.stringify(e)}\n`),logHelp();break}}else n.push("*.*");if(w.has("skip-minify")&&w.has("mangle-names")){logError(`Option ${R("--mangle-names")} is not compatible with ${R("--skip-minify")}\n`),logHelp();break}const a=w.get("skip-minify");let s;if(null!=a){if("boolean"!=typeof a){logError(`The value for ${R("--skip-minify")} must be ${E("true")} or ${E("false")}\n`),logHelp();break}s=!a}const o=w.get("mangle-names");if(null!=o&&"boolean"!=typeof o){logError(`The value for ${R("--mangle-names")} must be ${E("true")} or ${E("false")}\n`),logHelp();break}const i=w.get("force-quine-cheats");if(null!=i&&"boolean"!=typeof i){logError(`The value for ${R("--force-quine-cheats")} must be ${E("true")} or ${E("false")}\n`),logHelp();break}const{push:r}=await N;(await r(t,e,{scripts:n,onPush:t=>logInfo(t,e),minify:s,mangleNames:o,forceQuineCheats:i})).length||logError("Could not find any scripts to push")}break;case"dev":case"watch":{const{hackmudPath:e}=await j;if(!e){logNeedHackmudPathMessage();break}const t=v[1];if(!t){logError("Must provide the directory to watch\n"),logHelp();break}const n=v.slice(2);if(n.length){const e=n.find((e=>!/^(?:[a-z_][a-z\d_]{0,24}|\*)\.(?:[a-z_][a-z\d_]{0,24}|\*)$/.test(e)));if(e){logError(`Invalid script name: ${JSON.stringify(e)}\n`),logHelp();break}}else n.push("*.*");if(w.has("skip-minify")&&w.has("mangle-names")){logError(`Option ${R("--mangle-names")} is not compatible with ${R("--skip-minify")}\n`),logHelp();break}const a=w.get("skip-minify");let s;if(null!=a){if("boolean"!=typeof a){logError(`The value for ${R("--skip-minify")} must be ${E("true")} or ${E("false")}\n`),logHelp();break}s=!a}const o=w.get("mangle-names");if(null!=o&&"boolean"!=typeof o){logError(`The value for ${R("--mangle-names")} must be ${E("true")} or ${E("false")}\n`),logHelp();break}const i=w.get("force-quine-cheats");if(null!=i&&"boolean"!=typeof i){logError(`The value for ${R("--force-quine-cheats")} must be ${E("true")} or ${E("false")}\n`),logHelp();break}const{watch:r}=await M;r(t,e,{scripts:n,onPush:t=>logInfo(t,e),typeDeclarationPath:(w.get("type-declaration-path")||w.get("type-declaration")||w.get("dts")||w.get("gen-types"))?.toString(),minify:s,mangleNames:o,onReady:()=>log("Watching"),forceQuineCheats:i}),A=!1}break;case"pull":{const{hackmudPath:e}=await j;if(!e){logNeedHackmudPathMessage();break}const t=v[1];if(!t){logError("Must provide the script to pull\n"),logHelp();break}const n=v[2]||".";try{await $(n,e,t)}catch(e){console.error(e),logError(`Something went wrong, did you forget to ${C("#down")} the script?`)}}break;case"sync-macros":{const{hackmudPath:e}=await j;if(!e){logNeedHackmudPathMessage();break}const{macrosSynced:t,usersSynced:n}=await p(e);log(`Synced ${t} macros to ${n} users`)}break;case"generate-type-declaration":case"gen-type-declaration":case"gen-dts":case"gen-types":{const e=v[1];if(!e){logError("Must provide target directory\n"),logHelp();break}const n=m(e),a=v[2]||"./player.d.ts",s=await f(n,(await j).hackmudPath);let i=m(a);try{await o(i,s)}catch(e){if(t(e instanceof Error),"EISDIR"!=e.code)throw e;i=m(i,"player.d.ts"),await o(i,s)}log(`Wrote type declaration to ${T.bold(i)}`)}break;case"config":switch(v[1]){case"get":{const e=v[2];e?log(exploreObject(await j,e.split("."))):console.log(await j)}break;case"delete":{const e=v[2];if(!e){logError("Must provide a key to delete\n"),logHelp();break}const t=e.split("."),n=t.map((e=>/^[a-z_$][\w$]*$/i.test(e)?e:JSON.stringify(e))).join("."),a=t.pop(),s=await j;delete exploreObject(s,t)?.[a],log(`Removed ${E(n)} from config file`)}break;case"set":{const e=v[2],t=v[3];if(!e){logError("Must provide a key and value\n"),logHelp();break}const n=e.split("."),a=n.map((e=>/^[a-z_$][\w$]*$/i.test(e)?e:JSON.stringify(e))).join(".");if(!t){logError(`Must provide a value for the key ${a}\n`),logHelp();break}const s=n.pop(),l=await j;if(n.length||"hackmudPath"!=s){let e=l;for(const t of n)"object"==typeof e[t]||(e[t]={}),e=e[t];e[s]=t}else l.hackmudPath=m(t.startsWith("~/")?c()+t.slice(1):t);console.log(l),await(async e=>{const t=JSON.stringify(e,void 0,"\t");P&&log(`Creating config file at ${k}`),await o(k,t).catch((async e=>{switch(e.code){case"EISDIR":await r(k);break;case"ENOENT":await i(b);break;default:throw e}await o(k,t)}))})(l)}break;default:v[1]&&logError(`Unknown command: ${JSON.stringify(v[1])}\n`),logHelp()}break;case"help":case"h":logHelp();break;case"golf":case"minify":{const e=v[1];if(!e){logError("Must provide target\n"),logHelp();break}const t=h(e);if(!l.includes(t)){logError(`Unsupported file extension "${T.bold(t)}"\nSupported extensions are "${l.map((e=>T.bold(e))).join('", "')}"`);break}const{processScript:o}=await O,i=u(e,t),r=i.endsWith(".src"),c=r?i.slice(0,-4):i,f="scripts"==u(m(e,".."))&&"hackmud"==u(m(e,"../../.."))?u(m(e,"../..")):"UNKNOWN",$=!w.get("skip-minify");if(w.has("skip-minify")&&w.has("mangle-names")){logError(`Option ${R("--mangle-names")} would have no effect if minification is skipped\n`),logHelp();break}const p=w.get("mangle-names");if(null!=p&&"boolean"!=typeof p){logError(`The value for ${R("--mangle-names")} must be ${E("true")} or ${E("false")}\n`),logHelp();break}const y=p,b=w.get("force-quine-cheats");if(null!=b&&"boolean"!=typeof b){logError(`the value for ${R("--force-quine-cheats")} must be ${E("true")} or ${E("false")}\n`),logHelp();break}const k=b;let S=v[2]||m(g(e),r?`${c}.js`:".js"==t?`${i}.min.js`:`${i}.js`);const golfFile=()=>s(e,{encoding:"utf-8"}).then((async s=>{const i=performance.now(),{script:r,warnings:l}=await o(s,{minify:$,scriptUser:f,scriptName:c,filePath:e,mangleNames:y,forceQuineCheats:k}),p=performance.now()-i;for(const{message:e,line:t}of l)log(`Warning "${T.bold(e)}" on line ${T.bold(String(t))}`);await a(S,r).catch((async n=>{if(!v[2]||"EISDIR"!=n.code)throw n;S=m(S,`${u(e,t)}.js`),await a(S,r)})).then((()=>log(`Wrote ${T.bold(n(r))} chars to ${T.bold(d(".",S))} | took ${Math.round(100*p)/100}ms`)),(e=>logError(e.message)))}),(e=>logError(e.message)));if(w.get("watch")){const{watch:t}=await U;t(e,{awaitWriteFinish:{stabilityThreshold:100}}).on("ready",(()=>log(`Watching ${e}`))).on("change",golfFile),A=!1}else await golfFile()}break;default:v[0]&&logError(`Unknown command: ${JSON.stringify(v[0])}\n`),logHelp()}A&&process.exit();
|
package/constants.d.ts
ADDED
@@ -1 +1 @@
|
|
1
|
-
const s=[".js",".ts"],t=["i","r","f","u","u1","us","ObjectId"];export{s,t as
|
1
|
+
const s=[".js",".ts"],t=["i","r","f","u","u1","us","ObjectId"];export{s as supportedExtensions,t as validDBMethods};
|
@@ -1 +1 @@
|
|
1
|
-
import{readdir as e}from"fs/promises";import{basename as t,resolve as n}from"path";const generateTypeDeclaration=async(s,i)=>{const a=new Set;if(i)for(const n of await e(i,{withFileTypes:!0}))n.isFile()&&n.name.endsWith(".key")&&a.add(t(n.name,".key"));const r=[],o=[],f={},l={};await Promise.all((await e(s,{withFileTypes:!0})).map((async i=>{if(i.isFile())i.name.endsWith(".ts")?i.name.endsWith(".d.ts")||r.push(t(i.name,".ts")):i.name.endsWith(".js")&&o.push(t(i.name,".js"));else if(i.isDirectory()){const r=[],o=[];f[i.name]=r,l[i.name]=o,a.add(i.name);for(const a of await e(n(s,i.name),{withFileTypes:!0}))a.isFile()&&(a.name.endsWith(".ts")?i.name.endsWith(".d.ts")||r.push(t(a.name,".ts")):a.name.endsWith(".js")&&o.push(t(a.name,".js")))}}))),s=n(s);let c="";for(const e of r)c+=`type $${e}$ = typeof import("${s}/${e}").default\n`;c+="\n";for(const e in f){const t=f[e];for(const n of t)c+=`type $${e}$${n}$ = typeof import("${s}/${e}/${n}").default\n`}c+="\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 r)c+=`\t${e}: Subscript<$${e}$>\n`;for(const e of o)c+=`\t${e}: (...args: any) => any\n`;c+="}\n\ninterface PlayerFullsec {";let m=!0;for(const e of a){const t=f[e],n=l[e];if(t&&t.length||n&&n.length){if(m=!0,c+=`\n\t${e}: WildFullsec & {\n`,t)for(const n of t)c+=`\t\t${n}: Subscript<$${e}$${n}$>\n`;if(n)for(const e of n)c+=`\t\t${e}: (...args: any) => any\n`;c+="\t}"}else m&&(c+="\n",m=!1),c+=`\t${e}: WildFullsec`;c+="\n"}return c+="}\n",c};export{generateTypeDeclaration as default,generateTypeDeclaration};
|
1
|
+
import{readdir as e}from"fs/promises";import{basename as t,resolve as n}from"path";const generateTypeDeclaration=async(s,i)=>{const a=new Set;if(i)for(const n of await e(i,{withFileTypes:!0}))n.isFile()&&n.name.endsWith(".key")&&a.add(t(n.name,".key"));const r=[],o=[],f={},l={};await Promise.all((await e(s,{withFileTypes:!0})).map((async i=>{if(i.isFile())i.name.endsWith(".ts")?i.name.endsWith(".d.ts")||r.push(t(i.name,".ts")):i.name.endsWith(".js")&&o.push(t(i.name,".js"));else if(i.isDirectory()){const r=[],o=[];f[i.name]=r,l[i.name]=o,a.add(i.name);for(const a of await e(n(s,i.name),{withFileTypes:!0}))a.isFile()&&(a.name.endsWith(".ts")?i.name.endsWith(".d.ts")||r.push(t(a.name,".ts")):a.name.endsWith(".js")&&o.push(t(a.name,".js")))}}))),s=n(s);let c="";for(const e of r)c+=`type $${e}$ = typeof import("${s}/${e}").default\n`;c+="\n";for(const e in f){const t=f[e];for(const n of t)c+=`type $${e}$${n}$ = typeof import("${s}/${e}/${n}").default\n`}c+="\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 r)c+=`\t${e}: Subscript<$${e}$>\n`;for(const e of o)c+=`\t${e}: (...args: any) => any\n`;c+="}\n\ninterface PlayerFullsec {";let m=!0;for(const e of a){const t=f[e],n=l[e];if(t&&t.length||n&&n.length){if(m=!0,c+=`\n\t${e}: WildFullsec & {\n`,t)for(const n of t)c+=`\t\t${n}: Subscript<$${e}$${n}$>\n`;if(n)for(const e of n)c+=`\t\t${e}: (...args: any) => any\n`;c+="\t}"}else m&&(c+="\n",m=!1),c+=`\t${e}: WildFullsec`;c+="\n"}return c+="}\n",c};export{generateTypeDeclaration as default,generateTypeDeclaration};
|
package/index.d.ts
CHANGED
@@ -1,11 +1,11 @@
|
|
1
|
-
export { supportedExtensions } from "./constants
|
1
|
+
export { supportedExtensions } from "./constants";
|
2
2
|
export { generateTypeDeclaration } from "./generateTypeDeclaration";
|
3
3
|
export { processScript } from "./processScript";
|
4
4
|
export { pull } from "./pull";
|
5
5
|
export { push } from "./push";
|
6
6
|
export { syncMacros } from "./syncMacros";
|
7
7
|
export { watch } from "./watch";
|
8
|
-
export
|
8
|
+
export type Info = {
|
9
9
|
file: string;
|
10
10
|
users: string[];
|
11
11
|
minLength: number;
|
package/index.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
export{
|
1
|
+
export{supportedExtensions}from"./constants.js";export{generateTypeDeclaration}from"./generateTypeDeclaration.js";export{processScript}from"./processScript/index.js";export{pull}from"./pull.js";export{push}from"./push.js";export{syncMacros}from"./syncMacros.js";export{watch}from"./watch.js";import"fs/promises";import"path";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-destructuring-private";import"@babel/plugin-proposal-explicit-resource-management";import"@babel/plugin-transform-class-properties";import"@babel/plugin-transform-class-static-block";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-json-strings";import"@babel/plugin-transform-logical-assignment-operators";import"@babel/plugin-transform-nullish-coalescing-operator";import"@babel/plugin-transform-numeric-separator";import"@babel/plugin-transform-object-rest-spread";import"@babel/plugin-transform-optional-catch-binding";import"@babel/plugin-transform-optional-chaining";import"@babel/plugin-transform-private-property-in-object";import"@babel/plugin-transform-unicode-sets-regex";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"@samual/lib/assert";import"prettier";import"rollup";import"./processScript/minify.js";import"@samual/lib/countHackmudCharacters";import"@samual/lib/spliceString";import"acorn";import"terser";import"./processScript/shared.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"import-meta-resolve";import"./processScript/transform.js";import"@samual/lib/clearObject";import"@samual/lib/copyFilePersistent";import"@samual/lib/DynamicMap";import"@samual/lib/writeFilePersistent";import"chokidar";
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "hackmud-script-manager",
|
3
|
-
"version": "0.
|
3
|
+
"version": "0.20.0-b71a8be",
|
4
4
|
"description": "Script manager for game hackmud, with minification, TypeScript support, and player script type definition generation.",
|
5
5
|
"keywords": [
|
6
6
|
"api",
|
@@ -19,7 +19,7 @@
|
|
19
19
|
],
|
20
20
|
"homepage": "https://github.com/samualtnorman/hackmud-script-manager#readme",
|
21
21
|
"bugs": "https://github.com/samualtnorman/hackmud-script-manager/issues",
|
22
|
-
"license": "
|
22
|
+
"license": "MIT",
|
23
23
|
"author": "Samual Norman",
|
24
24
|
"main": "index.js",
|
25
25
|
"repository": {
|
@@ -27,98 +27,58 @@
|
|
27
27
|
"url": "https://github.com/samualtnorman/hackmud-script-manager.git"
|
28
28
|
},
|
29
29
|
"dependencies": {
|
30
|
-
"@babel/
|
31
|
-
"@babel/
|
32
|
-
"@babel/
|
33
|
-
"@babel/plugin-proposal-
|
34
|
-
"@babel/plugin-proposal-
|
35
|
-
"@babel/plugin-proposal-
|
36
|
-
"@babel/plugin-proposal-
|
37
|
-
"@babel/plugin-proposal-function-
|
38
|
-
"@babel/plugin-proposal-
|
39
|
-
"@babel/plugin-proposal-
|
40
|
-
"@babel/plugin-proposal-
|
41
|
-
"@babel/plugin-proposal-
|
42
|
-
"@babel/plugin-
|
43
|
-
"@babel/plugin-
|
44
|
-
"@babel/plugin-
|
45
|
-
"@babel/plugin-
|
46
|
-
"@babel/plugin-
|
47
|
-
"@babel/plugin-
|
48
|
-
"@babel/plugin-
|
49
|
-
"@babel/plugin-
|
50
|
-
"@babel/plugin-
|
51
|
-
"@babel/plugin-transform-
|
52
|
-
"@babel/plugin-transform-
|
53
|
-
"@babel/
|
54
|
-
"@babel/
|
30
|
+
"@babel/generator": "^7.23.6",
|
31
|
+
"@babel/parser": "^7.23.6",
|
32
|
+
"@babel/plugin-proposal-decorators": "^7.23.7",
|
33
|
+
"@babel/plugin-proposal-destructuring-private": "^7.23.3",
|
34
|
+
"@babel/plugin-proposal-do-expressions": "^7.23.3",
|
35
|
+
"@babel/plugin-proposal-explicit-resource-management": "^7.23.3",
|
36
|
+
"@babel/plugin-proposal-function-bind": "^7.23.3",
|
37
|
+
"@babel/plugin-proposal-function-sent": "^7.23.3",
|
38
|
+
"@babel/plugin-proposal-partial-application": "^7.23.3",
|
39
|
+
"@babel/plugin-proposal-pipeline-operator": "^7.23.3",
|
40
|
+
"@babel/plugin-proposal-record-and-tuple": "^7.23.3",
|
41
|
+
"@babel/plugin-proposal-throw-expressions": "^7.23.3",
|
42
|
+
"@babel/plugin-transform-class-properties": "^7.23.3",
|
43
|
+
"@babel/plugin-transform-class-static-block": "^7.23.4",
|
44
|
+
"@babel/plugin-transform-exponentiation-operator": "^7.23.3",
|
45
|
+
"@babel/plugin-transform-json-strings": "^7.23.4",
|
46
|
+
"@babel/plugin-transform-logical-assignment-operators": "^7.23.4",
|
47
|
+
"@babel/plugin-transform-nullish-coalescing-operator": "^7.23.4",
|
48
|
+
"@babel/plugin-transform-numeric-separator": "^7.23.4",
|
49
|
+
"@babel/plugin-transform-object-rest-spread": "^7.23.4",
|
50
|
+
"@babel/plugin-transform-optional-catch-binding": "^7.23.4",
|
51
|
+
"@babel/plugin-transform-optional-chaining": "^7.23.4",
|
52
|
+
"@babel/plugin-transform-private-property-in-object": "^7.23.4",
|
53
|
+
"@babel/plugin-transform-typescript": "^7.23.6",
|
54
|
+
"@babel/plugin-transform-unicode-sets-regex": "^7.23.3",
|
55
|
+
"@babel/traverse": "^7.23.7",
|
56
|
+
"@babel/types": "^7.23.6",
|
55
57
|
"@bloomberg/record-tuple-polyfill": "^0.0.4",
|
56
|
-
"@rollup/plugin-babel": "^
|
57
|
-
"@rollup/plugin-commonjs": "^
|
58
|
-
"@rollup/plugin-json": "^
|
59
|
-
"@rollup/plugin-node-resolve": "^
|
60
|
-
"
|
61
|
-
"
|
58
|
+
"@rollup/plugin-babel": "^6.0.4",
|
59
|
+
"@rollup/plugin-commonjs": "^25.0.7",
|
60
|
+
"@rollup/plugin-json": "^6.1.0",
|
61
|
+
"@rollup/plugin-node-resolve": "^15.2.3",
|
62
|
+
"@samual/lib": "^0.9.1",
|
63
|
+
"acorn": "^8.11.3",
|
64
|
+
"chalk": "^5.3.0",
|
62
65
|
"chokidar": "^3.5.3",
|
63
|
-
"import-meta-resolve": "^
|
64
|
-
"prettier": "^2.
|
66
|
+
"import-meta-resolve": "^4.0.0",
|
67
|
+
"prettier": "^3.2.2",
|
65
68
|
"proxy-polyfill": "^0.3.2",
|
66
|
-
"rollup": "^
|
67
|
-
"terser": "^5.
|
68
|
-
},
|
69
|
-
"devDependencies": {
|
70
|
-
"@babel/preset-env": "^7.18.9",
|
71
|
-
"@babel/preset-typescript": "^7.18.6",
|
72
|
-
"@samual/lib": "^0.3.4",
|
73
|
-
"@types/babel__core": "^7.1.19",
|
74
|
-
"@types/babel__generator": "^7.6.4",
|
75
|
-
"@types/babel__traverse": "^7.17.1",
|
76
|
-
"@types/node": "^14.18.22",
|
77
|
-
"@types/prettier": "^2.6.3",
|
78
|
-
"@types/semver": "^7.3.10",
|
79
|
-
"@typescript-eslint/eslint-plugin": "^5.30.7",
|
80
|
-
"@typescript-eslint/parser": "^5.30.7",
|
81
|
-
"eslint": "^8.20.0",
|
82
|
-
"eslint-plugin-array-func": "^3.1.7",
|
83
|
-
"eslint-plugin-eslint-comments": "^3.2.0",
|
84
|
-
"eslint-plugin-regexp": "^1.7.0",
|
85
|
-
"eslint-plugin-unicorn": "^43.0.2",
|
86
|
-
"latest-version": "^7.0.0",
|
87
|
-
"rollup-plugin-preserve-shebang": "^1.0.1",
|
88
|
-
"rollup-plugin-terser": "^7.0.2",
|
89
|
-
"semver": "^7.3.7",
|
90
|
-
"typescript": "^4.7.4"
|
91
|
-
},
|
92
|
-
"optionalDependencies": {
|
93
|
-
"deasync": "^0.1.27"
|
69
|
+
"rollup": "^4.9.5",
|
70
|
+
"terser": "^5.26.0"
|
94
71
|
},
|
95
72
|
"engines": {
|
96
|
-
"node": ">=
|
73
|
+
"node": ">=20"
|
97
74
|
},
|
98
|
-
"types": "index.d.ts",
|
99
75
|
"type": "module",
|
100
76
|
"exports": {
|
101
|
-
"
|
102
|
-
|
103
|
-
"require": "./index.cjs"
|
104
|
-
},
|
105
|
-
"./*": "./*",
|
106
|
-
"./generateTypeDeclaration": "./generateTypeDeclaration.js",
|
107
|
-
"./index": "./index.js",
|
108
|
-
"./pull": "./pull.js",
|
109
|
-
"./push": "./push.js",
|
110
|
-
"./syncMacros": "./syncMacros.js",
|
111
|
-
"./watch": "./watch.js",
|
112
|
-
"./bin/hsm": "./bin/hsm.js",
|
113
|
-
"./processScript/index": "./processScript/index.js",
|
114
|
-
"./processScript": "./processScript/index.js",
|
115
|
-
"./processScript/minify": "./processScript/minify.js",
|
116
|
-
"./processScript/postprocess": "./processScript/postprocess.js",
|
117
|
-
"./processScript/preprocess": "./processScript/preprocess.js",
|
118
|
-
"./processScript/shared": "./processScript/shared.js",
|
119
|
-
"./processScript/transform": "./processScript/transform.js"
|
77
|
+
"./*": "./*.js",
|
78
|
+
"./*.js": "./*.js"
|
120
79
|
},
|
121
80
|
"bin": {
|
122
|
-
"hsm": "
|
81
|
+
"hsm.d": "bin/hsm.d.ts",
|
82
|
+
"hsm": "bin/hsm.js"
|
123
83
|
}
|
124
84
|
}
|
package/processScript/index.d.ts
CHANGED
@@ -1,9 +1,9 @@
|
|
1
|
-
import { LaxPartial } from "@samual/lib";
|
1
|
+
import type { LaxPartial } from "@samual/lib";
|
2
2
|
export { minify } from "./minify";
|
3
3
|
export { postprocess } from "./postprocess";
|
4
4
|
export { preprocess } from "./preprocess";
|
5
5
|
export { transform } from "./transform";
|
6
|
-
export
|
6
|
+
export type ProcessOptions = {
|
7
7
|
/** whether to minify the given code */
|
8
8
|
minify: boolean;
|
9
9
|
/** 11 a-z 0-9 characters */
|
package/processScript/index.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/generator";import{parse as
|
1
|
+
import e from"@babel/generator";import{parse as r}from"@babel/parser";import o from"@babel/plugin-proposal-decorators";import t from"@babel/plugin-proposal-destructuring-private";import a from"@babel/plugin-proposal-explicit-resource-management";import l from"@babel/plugin-transform-class-properties";import p from"@babel/plugin-transform-class-static-block";import s from"@babel/plugin-transform-exponentiation-operator";import i from"@babel/plugin-transform-json-strings";import n from"@babel/plugin-transform-logical-assignment-operators";import m from"@babel/plugin-transform-nullish-coalescing-operator";import c from"@babel/plugin-transform-numeric-separator";import u from"@babel/plugin-transform-object-rest-spread";import f from"@babel/plugin-transform-optional-catch-binding";import b from"@babel/plugin-transform-optional-chaining";import d from"@babel/plugin-transform-private-property-in-object";import g from"@babel/plugin-transform-unicode-sets-regex";import h from"@babel/traverse";import y from"@babel/types";import{babel as w}from"@rollup/plugin-babel";import k from"@rollup/plugin-commonjs";import x from"@rollup/plugin-json";import v from"@rollup/plugin-node-resolve";import{assert as j}from"@samual/lib/assert";import{resolve as C}from"path";import E from"prettier";import{rollup as S}from"rollup";import{supportedExtensions as L}from"../constants.js";import{minify as $}from"./minify.js";import{postprocess as N}from"./postprocess.js";import{preprocess as I}from"./preprocess.js";import{includesIllegalString as P,replaceUnsafeStrings as D}from"./shared.js";import{transform as _}from"./transform.js";import"@samual/lib/countHackmudCharacters";import"@samual/lib/spliceString";import"acorn";import"terser";import"import-meta-resolve";import"@samual/lib/clearObject";const{format:O}=E,{default:M}=e,{default:T}=h,processScript=async(e,{minify:h=!0,uniqueID:E=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:U="UNKNOWN",scriptName:W="UNKNOWN",filePath:q,mangleNames:A=!1,forceQuineCheats:F}={})=>{j(/^\w{11}$/.exec(E));const H=e;let z,K;const Q=/^function\s*\(.+\/\/(?<autocomplete>.+)/.exec(e);if(Q)e=`export default ${e}`,({autocomplete:z}=Q.groups);else for(const r of e.split("\n")){const e=/^\s*\/\/(?<commentContent>.+)/.exec(r);if(!e)break;const o=e.groups.commentContent.trim();if(o.startsWith("@autocomplete "))z=o.slice(14).trimStart();else if(o.startsWith("@seclevel ")){const e=o.slice(10).trimStart().toLowerCase();switch(e){case"fullsec":case"full":case"fs":case"4s":case"f":case"4":K=4;break;case"highsec":case"high":case"hs":case"3s":case"h":case"3":K=3;break;case"midsec":case"mid":case"ms":case"2s":case"m":case"2":K=2;break;case"lowsec":case"low":case"ls":case"1s":case"l":case"1":K=1;break;case"nullsec":case"null":case"ns":case"0s":case"n":case"0":K=0;break;default:throw new Error(`unrecognised seclevel "${e}"`)}}}j(/^\w{11}$/.exec(E));const V=[[o.default,{decoratorsBeforeExport:!0}],[l.default],[p.default],[d.default],[n.default],[c.default],[m.default],[b.default],[f.default],[i.default],[u.default],[s.default],[g.default],[t.default],[a.default]];let B;if(q)if(B=C(q),q.endsWith(".ts"))V.push([(await import("@babel/plugin-transform-typescript")).default,{allowDeclareFields:!0,optimizeConstEnums:!0}]);else{const[e,r,o,t,a,l,p]=await Promise.all([import("@babel/plugin-proposal-do-expressions"),import("@babel/plugin-proposal-function-bind"),import("@babel/plugin-proposal-function-sent"),import("@babel/plugin-proposal-partial-application"),import("@babel/plugin-proposal-pipeline-operator"),import("@babel/plugin-proposal-throw-expressions"),import("@babel/plugin-proposal-record-and-tuple")]);V.push([e.default],[r.default],[o.default],[t.default],[a.default,{proposal:"hack",topicToken:"%"}],[l.default],[p.default,{syntaxType:"hash",importPolyfill:!0}])}else{B=`${E}.ts`;const[e,r,o,t,a,l,p,s]=await Promise.all([import("@babel/plugin-transform-typescript"),import("@babel/plugin-proposal-do-expressions"),import("@babel/plugin-proposal-function-bind"),import("@babel/plugin-proposal-function-sent"),import("@babel/plugin-proposal-partial-application"),import("@babel/plugin-proposal-pipeline-operator"),import("@babel/plugin-proposal-throw-expressions"),import("@babel/plugin-proposal-record-and-tuple")]);V.push([e.default,{allowDeclareFields:!0,optimizeConstEnums:!0}],[r.default],[o.default],[t.default],[a.default],[l.default,{proposal:"hack",topicToken:"%"}],[p.default],[s.default,{syntaxType:"hash",importPolyfill:!0}])}const G=await S({input:B,plugins:[{name:"hackmud-script-manager",transform:async e=>(await I(e,{uniqueID:E})).code},w({babelHelpers:"bundled",plugins:V,configFile:!1,extensions:L}),k(),v({extensions:L}),x()],treeshake:{moduleSideEffects:!1}}),R=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];e=(await G.generate({})).output[0].code;const{file:J,seclevel:X}=_(r(e,{sourceType:"module"}),H,{uniqueID:E,scriptUser:U,scriptName:W});if(null!=K&&X<K)throw new Error(`detected seclevel ${R[X]} is lower than stated seclevel ${R[K]}`);if(e=M(J).code,h?e=await $(J,{uniqueID:E,mangleNames:A,forceQuineCheats:F,autocomplete:z}):(T(J,{MemberExpression({node:e}){e.computed||(j("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=y.stringLiteral("prototype")):"__proto__"==e.property.name?(e.computed=!0,e.property=y.stringLiteral("__proto__")):P(e.property.name)&&(e.computed=!0,e.property=y.stringLiteral(D(E,e.property.name))))},VariableDeclarator(e){const renameVariables=r=>{switch(r.type){case"Identifier":P(r.name)&&e.scope.rename(r.name,`$${Math.floor(Math.random()*2**52).toString(36).padStart(11,"0")}`);break;case"ObjectPattern":for(const e of r.properties)j("ObjectProperty"==e.type),renameVariables(e.value);break;case"ArrayPattern":for(const e of r.elements)e&&renameVariables(e);break;default:throw new Error(`unknown lValue type "${r.type}"`)}};renameVariables(e.node.id)},ObjectProperty({node:e}){"Identifier"==e.key.type&&P(e.key.name)&&(e.key=y.stringLiteral(D(E,e.key.name)),e.shorthand=!1)},StringLiteral({node:e}){e.value=D(E,e.value)},TemplateLiteral({node:e}){for(const r of e.quasis)r.value.cooked?(r.value.cooked=D(E,r.value.cooked),r.value.raw=r.value.cooked.replaceAll("\\","\\\\").replaceAll("`","\\`").replaceAll("${","$\\{")):r.value.raw=D(E,r.value.raw)},RegExpLiteral(e){e.node.pattern=D(E,e.node.pattern),delete e.node.extra}}),e=await O(M(J,{comments:!1}).code,{parser:"babel",arrowParens:"avoid",semi:!1,trailingComma:"none"})),e=N(e,X,E),P(e))throw new Error('you found a weird edge case where I wasn\'t able to replace illegal strings like "SC$", please report thx');return{script:e,warnings:[]}};export{processScript as default,$ as minify,N as postprocess,I as preprocess,processScript,_ as transform};
|
@@ -1,6 +1,6 @@
|
|
1
|
-
import { File } from "@babel/types";
|
2
|
-
import { LaxPartial } from "@samual/lib";
|
3
|
-
|
1
|
+
import type { File } from "@babel/types";
|
2
|
+
import type { LaxPartial } from "@samual/lib";
|
3
|
+
type MinifyOptions = {
|
4
4
|
/** 11 a-z 0-9 characters */
|
5
5
|
uniqueID: string;
|
6
6
|
/** whether to mangle function and class names (defaults to `false`) */
|
package/processScript/minify.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/generator";import t from"@babel/traverse";import r from"@babel/types";import{
|
1
|
+
import e from"@babel/generator";import t from"@babel/traverse";import r from"@babel/types";import{assert as i}from"@samual/lib/assert";import{countHackmudCharacters as n}from"@samual/lib/countHackmudCharacters";import{spliceString as a}from"@samual/lib/spliceString";import{tokenizer as o,tokTypes as s}from"acorn";import*as l from"terser";import{getReferencePathsToGlobal as p,includesIllegalString as u,replaceUnsafeStrings as c}from"./shared.js";const{default:d}=e,{default:f}=t,minify=async(e,{uniqueID:t="00000000000",mangleNames:o=!1,forceQuineCheats:s,autocomplete:m}={})=>{let _;if(i(/^\w{11}$/.exec(t)),f(e,{Program(e){_=e,e.skip()}}),_.scope.hasGlobal("_START"))for(const e of p("_START",_))e.replaceWith(r.identifier("_ST"));if(_.scope.hasGlobal("_TIMEOUT"))for(const e of p("_TIMEOUT",_))e.replaceWith(r.identifier("_TO"));const y=_.get("body.0");for(const e of[...y.node.params].reverse()){if("Identifier"!=e.type||y.scope.getBinding(e.name).referenced)break;y.node.params.pop()}for(const e in _.scope.globals){if("arguments"==e||e.startsWith(`$${t}$`))continue;const i=p(e,_);if(!(5+e.length+i.length>=e.length*i.length)){for(const n of i)n.replaceWith(r.identifier(`_${t}_GLOBAL_${e}_`));y.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${t}_GLOBAL_${e}_`),r.identifier(e))]))}}const $=p(`$${t}$GLOBAL$`,_);if($.length>3){for(const e of $)e.replaceWith(r.identifier(`_${t}_G_`));y.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${t}_G_`),r.identifier(`$${t}$GLOBAL$`))]))}const b=[];let g,E,v=!1;if(1!=s){const n=r.cloneNode(e);if(f(n,{MemberExpression({node:e}){e.computed||(i("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=r.identifier(`_${t}_PROTOTYPE_PROPERTY_`)):"__proto__"==e.property.name?(e.computed=!0,e.property=r.identifier(`_${t}_PROTO_PROPERTY_`)):u(e.property.name)&&(e.computed=!0,e.property=r.stringLiteral(c(t,e.property.name))))},ObjectProperty({node:e}){"Identifier"==e.key.type&&u(e.key.name)&&(e.key=r.stringLiteral(c(t,e.key.name)),e.shorthand=!1)},StringLiteral({node:e}){e.value=c(t,e.value)},TemplateLiteral({node:e}){for(const r of e.quasis)r.value.cooked?(r.value.cooked=c(t,r.value.cooked),r.value.raw=r.value.cooked.replaceAll("\\","\\\\").replaceAll("`","\\`").replaceAll("${","$\\{")):r.value.raw=c(t,r.value.raw)},RegExpLiteral(e){e.node.pattern=c(t,e.node.pattern),delete e.node.extra}}),g=(await l.minify(d(n).code,{ecma:2015,compress:{passes:1/0,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,unsafe_symbols:!0,unsafe_methods:!0,unsafe_proto:!0,unsafe_regexp:!0,unsafe_undefined:!0,sequences:!1},format:{semicolons:!1},keep_classnames:!o,keep_fnames:!o})).code.replace(new RegExp(`_${t}_PROTOTYPE_PROPERTY_`,"g"),'"prototype"').replace(new RegExp(`_${t}_PROTO_PROPERTY_`,"g"),'"__proto__"'),m&&(g=a(g,`//${m}\n`,getFunctionBodyStart(g)+1)),0==s)return g}let h,k=!1;{const n=[];f(e,{FunctionDeclaration(e){e.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(e){const i={};parseObjectExpression(e.node,i)&&e.replaceWith(r.identifier(`_${t}_JSON_VALUE_${b.push(i)-1}_`))},ArrayExpression(e){const i=[];parseArrayExpression(e.node,i)&&e.replaceWith(r.identifier(`_${t}_JSON_VALUE_${b.push(i)-1}_`))}}),e.traverse({TemplateLiteral(e){if("TaggedTemplateExpression"==e.parent.type)return;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(`_${t}_UNDEFINED_`)),v=!0);else if("-"==e.node.operator&&"NumericLiteral"==e.node.argument.type){const i=-e.node.argument.value;n.push((async()=>{if((await minifyNumber(i)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let n=b.indexOf(i);-1==n&&(n+=b.push(i)),e.replaceWith(r.identifier(`_${t}_JSON_VALUE_${n}_`))})()),e.skip()}},NullLiteral(e){let i=b.indexOf(null);-1==i&&(i+=b.push(null)),e.replaceWith(r.identifier(`_${t}_JSON_VALUE_${i}_`))},NumericLiteral(e){n.push((async()=>{if((await minifyNumber(e.node.value)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let i=b.indexOf(e.node.value);-1==i&&(i+=b.push(e.node.value)),e.replaceWith(r.identifier(`_${t}_JSON_VALUE_${i}_`))})())},StringLiteral(e){if(e.node.value=c(t,e.node.value),JSON.stringify(e.node.value).includes("\\u00")||e.toString().length<4)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let i=b.indexOf(e.node.value);-1==i&&(i+=b.push(e.node.value)),e.replaceWith(r.identifier(`_${t}_JSON_VALUE_${i}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let i=b.indexOf(e.key.name);-1==i&&(i+=b.push(e.key.name)),e.computed=!0,e.key=r.identifier(`_${t}_JSON_VALUE_${i}_`)},RegExpLiteral(e){e.node.pattern=c(t,e.node.pattern),delete e.node.extra}}),e.skip()}}),await Promise.all(n);const a=e.program.body[0];if(i("FunctionDeclaration"==a.type),b.length)if(k=!0,1==b.length)if("string"!=typeof b[0]||b[0].includes("\n")||b[0].includes("\t")){const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${t}_JSON_VALUE_0_`),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${t}$SUBSCRIPT$scripts$quine$`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${t}$SPLIT_INDEX$`),!0)]))]);v&&e.declarations.push(r.variableDeclarator(r.identifier(`_${t}_UNDEFINED_`))),a.body.body.unshift(e),E=JSON.stringify(b[0])}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${t}_JSON_VALUE_0_`),r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${t}$SUBSCRIPT$scripts$quine$`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${t}$SPLIT_INDEX$`),!0))]);v&&e.declarations.push(r.variableDeclarator(r.identifier(`_${t}_UNDEFINED_`))),a.body.body.unshift(e),E=b[0]}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.arrayPattern(b.map(((e,i)=>r.identifier(`_${t}_JSON_VALUE_${i}_`)))),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${t}$SUBSCRIPT$scripts$quine$`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${t}$SPLIT_INDEX$`),!0)]))]);v&&e.declarations.push(r.variableDeclarator(r.identifier(`_${t}_UNDEFINED_`))),a.body.body.unshift(e),E=JSON.stringify(b)}else v&&a.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${t}_UNDEFINED_`))]));h=d(e).code}return h=(await l.minify(h,{ecma:2015,compress:{passes:1/0,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,unsafe_symbols:!0,unsafe_methods:!0,unsafe_proto:!0,unsafe_regexp:!0,unsafe_undefined:!0,sequences:!1},format:{semicolons:!1},keep_classnames:!o,keep_fnames:!o})).code||"",null!=E&&(h=a(h,`${m?`//${m}\n`:""}\n//\t${E}\t\n`,getFunctionBodyStart(h)+1),h=h.replace(`$${t}$SPLIT_INDEX$`,await minifyNumber(h.split("\t").findIndex((e=>e==E))))),1==s?h:(i(g),n(g)<=n(h)+Number(k)?g:h)},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)t["Identifier"==r.key.type?r.key.name:r.key.value]=r.value.value;else{if("TemplateLiteral"!=r.value.type||r.value.expressions.length)return!1;t["Identifier"==r.key.type?r.key.name:r.key.value]=r.value.quasis[0].value.cooked}}return!0},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)t.push(r.value);else{if("TemplateLiteral"!=r.type||r.expressions.length)return!1;t.push(r.quasis[0].value.cooked)}}return!0},minifyNumber=async e=>/\$\((?<number>.+)\)/.exec((await l.minify(`$(${e})`,{ecma:2015})).code).groups.number,getFunctionBodyStart=e=>{const t=o(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{minify as default,minify};
|
@@ -1 +1 @@
|
|
1
|
-
const postprocess=($,e,p)=>$.replace(/^function\s*\w+\(/,"function(").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$SC_DOLLAR\\$`,"g"),"S\\C$").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$DB_DOLLAR\\$`,"g"),"D\\B$").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$D\\$`,"g"),"_\\_D_S").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$FMCL\\$`,"g"),"_\\_FMCL_").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$G\\$`,"g"),"_\\_G_").replace(new RegExp(`\\$${p}\\$SUBSCRIPT\\$(\\w+)\\$(\\w+)\\$`,"g"),`#${"nlmhf"[e]}s.$1.$2`).replace(new RegExp(`\\$${p}\\$DEBUG\\$`,"g"),"#D").replace(new RegExp(`\\$${p}\\$FMCL\\$`,"g"),"#FMCL").replace(new RegExp(`\\$${p}\\$GLOBAL\\$`,"g"),"#G").replace(new RegExp(`\\$${p}\\$DB\\$(\\w+)\\$`,"g"),"#db.$1").replace(new RegExp(`\\$${p}\\$SLASH_SLASH\\$`,"g"),"/\\/").replace(new RegExp(`\\$${p}\\$NOT_A_SUBSCRIPT\\$(#[\\w\\.]+)\\(\\$`,"g"),"$1\\(").replace(new RegExp(`\\$${p}\\$NOT_A_DB_CALL\\$(\\w+)\\$`,"g"),"#db.$1\\(").replace(new RegExp(`\\$${p}\\$NOT_A_DEBUG_CALL\\$`,"g"),"#D\\(").replace(new RegExp(`\\$${p}\\$NOT_FMCL\\$`,"g"),"#\\FMCL").replace(new RegExp(`\\$${p}\\$NOT_G\\$`,"g"),"#\\G");export{postprocess as default,postprocess};
|
1
|
+
const postprocess=($,e,p)=>$.replace(/^function\s*\w+\(/,"function(").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$SC_DOLLAR\\$`,"g"),"S\\C$").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$DB_DOLLAR\\$`,"g"),"D\\B$").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$D\\$`,"g"),"_\\_D_S").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$FMCL\\$`,"g"),"_\\_FMCL_").replace(new RegExp(`\\$${p}\\$\\\\(?:\\\\)?\\$G\\$`,"g"),"_\\_G_").replace(new RegExp(`\\$${p}\\$SUBSCRIPT\\$(\\w+)\\$(\\w+)\\$`,"g"),`#${"nlmhf"[e]}s.$1.$2`).replace(new RegExp(`\\$${p}\\$DEBUG\\$`,"g"),"#D").replace(new RegExp(`\\$${p}\\$FMCL\\$`,"g"),"#FMCL").replace(new RegExp(`\\$${p}\\$GLOBAL\\$`,"g"),"#G").replace(new RegExp(`\\$${p}\\$DB\\$(\\w+)\\$`,"g"),"#db.$1").replace(new RegExp(`\\$${p}\\$SLASH_SLASH\\$`,"g"),"/\\/").replace(new RegExp(`\\$${p}\\$NOT_A_SUBSCRIPT\\$(#[\\w\\.]+)\\(\\$`,"g"),"$1\\(").replace(new RegExp(`\\$${p}\\$NOT_A_DB_CALL\\$(\\w+)\\$`,"g"),"#db.$1\\(").replace(new RegExp(`\\$${p}\\$NOT_A_DEBUG_CALL\\$`,"g"),"#D\\(").replace(new RegExp(`\\$${p}\\$NOT_FMCL\\$`,"g"),"#\\FMCL").replace(new RegExp(`\\$${p}\\$NOT_G\\$`,"g"),"#\\G");export{postprocess as default,postprocess};
|
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/generator";import{parse as o}from"@babel/parser";import r from"@babel/traverse";import i from"@babel/types";import{
|
1
|
+
import e from"@babel/generator";import{parse as o}from"@babel/parser";import r from"@babel/traverse";import i from"@babel/types";import{assert as t}from"@samual/lib/assert";import{spliceString as l}from"@samual/lib/spliceString";import{resolve as s}from"import-meta-resolve";const{default:p}=r,{default:a}=e,preprocess=async(e,{uniqueID:r="00000000000"}={})=>{t(/^\w{11}$/.test(r));const n=e;let c,f,d;do{c=e.length,e=e.replace(/^\s+/,"").replace(/^\/\/.*/,"").replace(/^\/\*[\s\S]*?\*\//,"")}while(e.length!=c);for(e=e.replace(/^function\s*\(/,"export default function (");;){let i;try{f=o(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}if("BABEL_PARSER_SYNTAX_ERROR"!=i.code||"PrivateInExpectedIn"!=i.reasonCode)throw console.log(/.+/.exec(e.slice(i.pos))?.[0]),i;const s=e.slice(i.pos);let p;if(p=/^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(s))e=l(e,JSON.stringify(n),i.pos,p[0].length);else if(p=/^#[0-4fhmln]?s\./.exec(s))e=l(e,"$",i.pos,1);else if(p=/^#D[^\w$]/.exec(s))e=l(e,"$",i.pos,1);else if(p=/^#FMCL/.exec(s))e=l(e,`$${r}$FMCL$`,i.pos,p[0].length);else if(p=/^#G/.exec(s))e=l(e,`$${r}$GLOBAL$`,i.pos,p[0].length);else{if(!(p=/^#db\./.exec(s)))throw i;e=l(e,"$",i.pos,1)}}p(f,{Program(e){d=e,e.skip()}});const m=d.scope.hasGlobal("Record"),u=d.scope.hasGlobal("Tuple");return(m||u)&&f.program.body.unshift(i.importDeclaration(m?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"))),d.scope.hasGlobal("Proxy")&&f.program.body.unshift(i.importDeclaration([i.importDefaultSpecifier(i.identifier("Proxy"))],i.stringLiteral((await s("proxy-polyfill/src/proxy.js",import.meta.url)).slice(7)))),1==d.node.body.length&&"FunctionDeclaration"==d.node.body[0].type?{code:`export default ${a(f).code}`}:{code:a(f).code}};export{preprocess as default,preprocess};
|
@@ -1,5 +1,5 @@
|
|
1
|
-
import { NodePath } from "@babel/traverse";
|
2
|
-
import
|
3
|
-
export declare const getReferencePathsToGlobal: (name: string, program: NodePath<Program>) => NodePath<
|
1
|
+
import type { NodePath } from "@babel/traverse";
|
2
|
+
import type { Identifier, Program } from "@babel/types";
|
3
|
+
export declare const getReferencePathsToGlobal: (name: string, program: NodePath<Program>) => NodePath<Identifier>[];
|
4
4
|
export declare const includesIllegalString: (toCheck: string) => boolean;
|
5
5
|
export declare const replaceUnsafeStrings: (uniqueID: string, toReplace: string) => string;
|
package/processScript/shared.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import $ from"@babel/types";import{e}from"
|
1
|
+
import $ from"@babel/types";import{ensure as e}from"@samual/lib/assert";const getReferencePathsToGlobal=(l,_)=>{const[r]=_.unshiftContainer("body",$.variableDeclaration("let",[$.variableDeclarator($.identifier(l))]));_.scope.crawl();const a=e(_.scope.getBinding(l));return r.remove(),a.referencePaths},includesIllegalString=$=>$.includes("SC$")||$.includes("DB$")||$.includes("__D_S")||$.includes("__FMCL_")||$.includes("__G_"),replaceUnsafeStrings=($,e)=>e.replaceAll("SC$",`$${$}$\\$SC_DOLLAR$`).replaceAll("DB$",`$${$}$\\$DB_DOLLAR$`).replaceAll("__D_S",`$${$}$\\$D$`).replaceAll("__FMCL_",`$${$}$\\$FMCL$`).replaceAll("__G_",`$${$}$\\$G$`).replaceAll("//",`$${$}$SLASH_SLASH$`).replaceAll(/#[0-4fhmln]?s(?:\.[_a-z][\d_a-z]{0,24}){2}\(/g,`$${$}$NOT_A_SUBSCRIPT$$$&$`).replaceAll(/#db\.(?<methodName>[irfu]|u1|us|ObjectId)\(/g,`$${$}$NOT_A_DB_CALL$$$1$`).replaceAll("#D(",`$${$}$NOT_A_DEBUG_CALL$`).replaceAll("#FMCL",`$${$}$NOT_FMCL$`).replaceAll("#G",`$${$}$NOT_G$`);export{getReferencePathsToGlobal,includesIllegalString,replaceUnsafeStrings};
|
@@ -1,5 +1,5 @@
|
|
1
|
-
import
|
2
|
-
export
|
1
|
+
import type { File } from "@babel/types";
|
2
|
+
export type TransformOptions = {
|
3
3
|
/** 11 a-z 0-9 characters */
|
4
4
|
uniqueID: string;
|
5
5
|
/** the user going to be hosting this script (or set to `true` if not yet known) */
|
@@ -18,7 +18,7 @@ export declare type TransformOptions = {
|
|
18
18
|
* @param options {@link TransformOptions details}
|
19
19
|
*/
|
20
20
|
export declare const transform: (file: File, sourceCode: string, { uniqueID, scriptUser, scriptName, seclevel }?: Partial<TransformOptions>) => {
|
21
|
-
file:
|
21
|
+
file: File;
|
22
22
|
seclevel: number;
|
23
23
|
};
|
24
24
|
export default transform;
|
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/traverse";import t from"@babel/types";import{v as i}from"../constants-9bb78688.js";import{getReferencePathsToGlobal as r}from"./shared.js";import{a as n}from"../assert-22a7ef8a.js";function clearObject(e,t){for(const t of Object.getOwnPropertyNames(e))delete e[t];for(const t of Object.getOwnPropertySymbols(e))delete e[t];void 0!==t&&Object.setPrototypeOf(e,t)}const{default:o}=e,a=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"],transform=(e,s,{uniqueID:p="00000000000",scriptUser:l="UNKNOWN",scriptName:c="UNKNOWN",seclevel:d=4}={})=>{const f=`_${p}_SCRIPT_`,b=new Map,y=new Map;let $;if(o(e,{Program(e){$=e,e.skip()}}),$.scope.hasGlobal("_SOURCE"))for(const e of r("_SOURCE",$))e.replaceWith(t.stringLiteral(s));if($.scope.hasGlobal("_BUILD_DATE"))for(const e of r("_BUILD_DATE",$))e.replaceWith(t.numericLiteral(Date.now()));if($.scope.hasGlobal("_SCRIPT_USER"))for(const e of r("_SCRIPT_USER",$))1==l?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_USER$`)):e.replaceWith(t.stringLiteral(l));if($.scope.hasGlobal("_SCRIPT_NAME"))for(const e of r("_SCRIPT_NAME",$))1==c?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_NAME$`)):e.replaceWith(t.stringLiteral(c));if($.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of r("_FULL_SCRIPT_NAME",$))1==l||1==c?e.replaceWith(t.stringLiteral(`$${p}$FULL_SCRIPT_NAME$`)):e.replaceWith(t.stringLiteral(`${l}.${c}`));let m=!1;const createGetFunctionPrototypeNode=()=>{for(const e of a)if(!$.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"))};if($.scope.hasGlobal("Function")){const e=r("Function",$);if(1==e.length){const t=e[0];n("MemberExpression"==t.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("Identifier"==t.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("prototype"==t.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t.parentPath.replaceWith(createGetFunctionPrototypeNode())}else{for(const i of e)n("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),n("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),m=!0,i.parentPath.replaceWith(t.identifier(`_${p}_FUNCTION_DOT_PROTOTYPE_`));m=!0}}let h=4;const processFakeSubscriptObject=e=>{for(const a of r(e,$)){var i,o;n("MemberExpression"==a.parent.type),n("Identifier"==a.parent.property.type),n("MemberExpression"==(null===(i=a.parentPath.parentPath)||void 0===i?void 0:i.node.type)),n("Identifier"==a.parentPath.parentPath.node.property.type),n(/^[_a-z][\d_a-z]{0,24}$/.test(a.parent.property.name),`invalid user "${a.parent.property.name}" in subscript`),n(/^[_a-z][\d_a-z]{0,24}$/.test(a.parentPath.parentPath.node.property.name),`invalid script name "${a.parentPath.parentPath.node.property.name}" in subscript`),"CallExpression"==(null===(o=a.parentPath.parentPath.parentPath)||void 0===o?void 0:o.type)?a.parentPath.parentPath.replaceWith(t.identifier(`$${p}$SUBSCRIPT$${a.parent.property.name}$${a.parentPath.parentPath.node.property.name}$`)):a.parentPath.parentPath.replaceWith(t.arrowFunctionExpression([t.restElement(t.identifier("args"))],t.callExpression(t.identifier(`$${p}$SUBSCRIPT$${a.parent.property.name}$${a.parentPath.parentPath.node.property.name}$`),[t.spreadElement(t.identifier("args"))])))}};for(const e of["$fs","$4s","$s"])$.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])$.scope.hasGlobal(e)&&(h=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])$.scope.hasGlobal(e)&&(h=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])$.scope.hasGlobal(e)&&(h=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])$.scope.hasGlobal(e)&&(h=0,processFakeSubscriptObject(e));if(d=Math.min(d,h),$.scope.hasGlobal("$db"))for(const e of r("$db",$)){var E;n("MemberExpression"==e.parentPath.node.type),n("Identifier"==e.parentPath.node.property.type);const r=e.parentPath.node.property.name;n(i.includes(r),`invalid db method "${r}", valid db methods are "${i.join('", "')}"`),"CallExpression"==(null===(E=e.parentPath.parentPath)||void 0===E?void 0:E.type)?e.parentPath.replaceWith(t.identifier(`$${p}$DB$${r}$`)):"ObjectId"==r?e.parentPath.replaceWith(t.arrowFunctionExpression([],t.callExpression(t.identifier(`$${p}$DB$${r}$`),[]))):"i"==r||"r"==r?e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a")],t.callExpression(t.identifier(`$${p}$DB$${r}$`),[t.identifier("a")]))):e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a"),t.identifier("b")],t.callExpression(t.identifier(`$${p}$DB$${r}$`),[t.identifier("a"),t.identifier("b")])))}if($.scope.hasGlobal("$D"))for(const e of r("$D",$))"CallExpression"==e.parentPath.type?e.replaceWith(t.identifier(`$${p}$DEBUG$`)):e.replaceWith(t.arrowFunctionExpression([t.identifier("a")],t.callExpression(t.identifier(`$${p}$DEBUG$`),[t.identifier("a")])));if($.scope.hasGlobal("$FMCL"))for(const e of r("$FMCL",$))e.replaceWith(t.identifier(`$${p}$FMCL$`));if($.scope.hasGlobal("$G"))for(const e of r("$G",$))e.replaceWith(t.identifier(`$${p}$GLOBAL$`));if($.scope.hasGlobal("_SECLEVEL"))for(const e of r("_SECLEVEL",$))e.replaceWith(t.numericLiteral(d));let _=!1,u=!1;if($.scope.hasGlobal("Object"))for(const e of r("Object",$))"MemberExpression"!=e.parent.type||e.parent.computed||(n("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(t.identifier(`_${p}_GET_PROTOTYPE_OF_`)),_=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(t.identifier(`_${p}_SET_PROTOTYPE_OF_`)),u=!0));const P=$.node.body[$.node.body.length-1];let x;if(n(P,"program is empty"),"ExportNamedDeclaration"==P.type){$.node.body.pop();for(const e of P.specifiers){n("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const t="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==t?x=e.local.name:b.set(e.local.name,t)}}const O=t.blockStatement([]);let D;for(const e of $.node.body)if("VariableDeclaration"==e.type)for(const i of e.declarations)if("Identifier"!=i.id.type||i.id.name!=x||!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==x&&(D=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(t.identifier(x),[]))]))),"const"!=e.kind&&b.has(r)&&(y.set(r,b.get(r)),b.delete(r)),O.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(r))]));i.init&&O.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else D=t.functionDeclaration(t.identifier(f),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==x?D=e:O.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):O.body.push(e);if(D||(D=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),$.node.body=[D],O.body.length){(b.size||y.size)&&D.body.body.push(t.returnStatement(t.objectExpression([...[...b].map((([e,i])=>t.objectProperty(t.identifier(i),t.identifier(e)))),...[...y].map((([e,i])=>t.objectMethod("get",t.identifier(i),[],t.blockStatement([t.returnStatement(t.identifier(e))]))))]))),$.scope.crawl();const e=new Set;let i=0;for(const[r,o]of[...O.body.entries()].reverse())if("VariableDeclaration"==o.type){n(1==o.declarations.length);const a=o.declarations[0];if(n("Identifier"==a.id.type,`declarator.id.type was "${a.id.type}"`),$.scope.crawl(),$.scope.hasGlobal(a.id.name)){O.body.splice(r,1);const[s]=$.unshiftContainer("body",O),[l]=$.unshiftContainer("body",o);if($.scope.crawl(),!a.init||"FunctionExpression"!=a.init.type&&"ArrowFunctionExpression"!=a.init.type||Object.keys($.scope.globals).some((t=>e.has(t)))){const e=$.scope.getBinding(a.id.name);n(e);for(const i of e.referencePaths)n("Identifier"==i.node.type),i.replaceWith(t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(i.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&&(clearObject(r),Object.assign(r,t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(e))));s.remove(),l.remove(),a.init&&O.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(a.id.name)),a.init)))}else s.remove(),l.remove(),D.body.body.unshift(o),i++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&($.scope.crawl(),$.scope.hasGlobal(o.id.name))){O.body.splice(r,1);const[e]=$.unshiftContainer("body",O),[i]=$.unshiftContainer("body",o);$.scope.crawl();const a=$.scope.getBinding(o.id.name);n(a);for(const e of a.referencePaths)n("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(e.node.name)));e.remove(),i.remove(),O.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(o.id.name)),t.classExpression(void 0,o.superClass,o.body,o.decorators))))}if($.scope.hasGlobal("_EXPORTS"))for(const e of r("_EXPORTS",$))e.replaceWith(t.arrayExpression([...b.keys(),...y.keys()].map((e=>t.stringLiteral(e)))));O.body.length&&D.body.body.splice(i,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${p}$FMCL$`)),O))}return m&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_FUNCTION_DOT_PROTOTYPE_`),createGetFunctionPrototypeNode())])),u&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_SET_PROTOTYPE_OF_`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`_${p}_DUNDER_PROTO_SETTER_`)]))])),_&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_GET_PROTOTYPE_OF_`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`_${p}_DUNDER_PROTO_GETTER_`)]))])),(_||u)&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.objectPattern(_?u?[t.objectProperty(t.identifier("get"),t.identifier(`_${p}_DUNDER_PROTO_GETTER_`)),t.objectProperty(t.identifier("set"),t.identifier(`_${p}_DUNDER_PROTO_SETTER_`))]:[t.objectProperty(t.identifier("get"),t.identifier(`_${p}_DUNDER_PROTO_GETTER_`))]:[t.objectProperty(t.identifier("set"),t.identifier(`_${p}_DUNDER_PROTO_SETTER_`))]),t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getOwnPropertyDescriptor")),[t.memberExpression(t.identifier("Object"),t.identifier("prototype")),t.stringLiteral("__proto__")]))])),o(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:i,parent:r}){n(t.isClass(r));let a=!1;for(const r of e.body){if("ClassMethod"!=r.type)continue;let e=!1;if(o(r.body,{ThisExpression(i){e=!0,a=!0,i.replaceWith(t.identifier(`_${p}_THIS_`))},Function(e){e.skip()}},i),e)if("constructor"!=r.kind)r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_THIS_`),t.callExpression(t.memberExpression(t.super(),t.identifier("valueOf")),[]))]));else{const e=[];if(o(r.body,{CallExpression(t){"Super"==t.node.callee.type&&e.push(t)}},i),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==r)e[0].parentPath.replaceWith(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_THIS_`),e[0].node)]));else{for(const i of e)i.replaceWith(t.assignmentExpression("=",t.identifier(`_${p}_THIS_`),i.node));r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_THIS_`))]))}else r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_THIS_`),t.callExpression(t.super(),[]))]))}}!r.superClass&&a&&(r.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:d}};export{transform as default,transform};
|
1
|
+
import e from"@babel/traverse";import i from"@babel/types";import{assert as t}from"@samual/lib/assert";import{clearObject as r}from"@samual/lib/clearObject";import{validDBMethods as n}from"../constants.js";import{getReferencePathsToGlobal as o}from"./shared.js";const{default:a}=e,s=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"],transform=(e,p,{uniqueID:l="00000000000",scriptUser:c="UNKNOWN",scriptName:d="UNKNOWN",seclevel:f=4}={})=>{const b=`_${l}_SCRIPT_`,y=new Map,m=new Map;let $;if(a(e,{Program(e){$=e,e.skip()}}),$.scope.hasGlobal("_SOURCE"))for(const e of o("_SOURCE",$))e.replaceWith(i.stringLiteral(p));if($.scope.hasGlobal("_BUILD_DATE"))for(const e of o("_BUILD_DATE",$))e.replaceWith(i.numericLiteral(Date.now()));if($.scope.hasGlobal("_SCRIPT_USER"))for(const e of o("_SCRIPT_USER",$))1==c?e.replaceWith(i.stringLiteral(`$${l}$SCRIPT_USER$`)):e.replaceWith(i.stringLiteral(c));if($.scope.hasGlobal("_SCRIPT_NAME"))for(const e of o("_SCRIPT_NAME",$))1==d?e.replaceWith(i.stringLiteral(`$${l}$SCRIPT_NAME$`)):e.replaceWith(i.stringLiteral(d));if($.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of o("_FULL_SCRIPT_NAME",$))1==c||1==d?e.replaceWith(i.stringLiteral(`$${l}$FULL_SCRIPT_NAME$`)):e.replaceWith(i.stringLiteral(`${c}.${d}`));let h=!1;const createGetFunctionPrototypeNode=()=>{for(const e of s)if(!$.scope.hasOwnBinding(e))return i.memberExpression(i.memberExpression(i.identifier(e),i.identifier("constructor")),i.identifier("prototype"));return i.memberExpression(i.memberExpression(i.arrowFunctionExpression([i.identifier("_")],i.identifier("_")),i.identifier("constructor")),i.identifier("prototype"))};if($.scope.hasGlobal("Function")){const e=o("Function",$);if(1==e.length){const i=e[0];t("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),i.parentPath.replaceWith(createGetFunctionPrototypeNode())}else{for(const r of e)t("MemberExpression"==r.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("Identifier"==r.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("prototype"==r.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),h=!0,r.parentPath.replaceWith(i.identifier(`_${l}_FUNCTION_DOT_PROTOTYPE_`));h=!0}}let E=4;const processFakeSubscriptObject=e=>{for(const r of o(e,$))t("MemberExpression"==r.parent.type),t("Identifier"==r.parent.property.type),t("MemberExpression"==r.parentPath.parentPath?.node.type),t("Identifier"==r.parentPath.parentPath.node.property.type),t(/^[_a-z][\d_a-z]{0,24}$/.test(r.parent.property.name),`invalid user "${r.parent.property.name}" in subscript`),t(/^[_a-z][\d_a-z]{0,24}$/.test(r.parentPath.parentPath.node.property.name),`invalid script name "${r.parentPath.parentPath.node.property.name}" in subscript`),"CallExpression"==r.parentPath.parentPath.parentPath?.type?r.parentPath.parentPath.replaceWith(i.identifier(`$${l}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}$`)):r.parentPath.parentPath.replaceWith(i.arrowFunctionExpression([i.restElement(i.identifier("args"))],i.callExpression(i.identifier(`$${l}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}$`),[i.spreadElement(i.identifier("args"))])))};for(const e of["$fs","$4s","$s"])$.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])$.scope.hasGlobal(e)&&(E=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])$.scope.hasGlobal(e)&&(E=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])$.scope.hasGlobal(e)&&(E=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])$.scope.hasGlobal(e)&&(E=0,processFakeSubscriptObject(e));if(f=Math.min(f,E),$.scope.hasGlobal("$db"))for(const e of o("$db",$)){t("MemberExpression"==e.parentPath.node.type),t("Identifier"==e.parentPath.node.property.type);const r=e.parentPath.node.property.name;t(n.includes(r),`invalid db method "${r}", valid db methods are "${n.join('", "')}"`),"CallExpression"==e.parentPath.parentPath?.type?e.parentPath.replaceWith(i.identifier(`$${l}$DB$${r}$`)):"ObjectId"==r?e.parentPath.replaceWith(i.arrowFunctionExpression([],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[]))):"i"==r||"r"==r?e.parentPath.replaceWith(i.arrowFunctionExpression([i.identifier("a")],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[i.identifier("a")]))):e.parentPath.replaceWith(i.arrowFunctionExpression([i.identifier("a"),i.identifier("b")],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[i.identifier("a"),i.identifier("b")])))}if($.scope.hasGlobal("$D"))for(const e of o("$D",$))"CallExpression"==e.parentPath.type?e.replaceWith(i.identifier(`$${l}$DEBUG$`)):e.replaceWith(i.arrowFunctionExpression([i.identifier("a")],i.callExpression(i.identifier(`$${l}$DEBUG$`),[i.identifier("a")])));if($.scope.hasGlobal("$FMCL"))for(const e of o("$FMCL",$))e.replaceWith(i.identifier(`$${l}$FMCL$`));if($.scope.hasGlobal("$G"))for(const e of o("$G",$))e.replaceWith(i.identifier(`$${l}$GLOBAL$`));if($.scope.hasGlobal("_SECLEVEL"))for(const e of o("_SECLEVEL",$))e.replaceWith(i.numericLiteral(f));let _=!1,u=!1;if($.scope.hasGlobal("Object"))for(const e of o("Object",$))"MemberExpression"!=e.parent.type||e.parent.computed||(t("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(i.identifier(`_${l}_GET_PROTOTYPE_OF_`)),_=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(i.identifier(`_${l}_SET_PROTOTYPE_OF_`)),u=!0));const P=$.node.body.at(-1);let x;if(t(P,"program is empty"),"ExportNamedDeclaration"==P.type){$.node.body.pop();for(const e of P.specifiers){t("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const i="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==i?x=e.local.name:y.set(e.local.name,i)}}const O=i.blockStatement([]);let D;for(const e of $.node.body)if("VariableDeclaration"==e.type)for(const t of e.declarations)if("Identifier"!=t.id.type||t.id.name!=x||!t.init||"FunctionExpression"!=t.init.type&&"ArrowFunctionExpression"!=t.init.type||t.init.async||t.init.generator){for(const r in i.getBindingIdentifiers(t.id))r==x&&(D=i.functionDeclaration(i.identifier(b),[i.identifier("context"),i.identifier("args")],i.blockStatement([i.returnStatement(i.callExpression(i.identifier(x),[]))]))),"const"!=e.kind&&y.has(r)&&(m.set(r,y.get(r)),y.delete(r)),O.body.push(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(r))]));t.init&&O.body.push(i.expressionStatement(i.assignmentExpression("=",t.id,t.init)))}else D=i.functionDeclaration(i.identifier(b),t.init.params,"BlockStatement"==t.init.body.type?t.init.body:i.blockStatement([i.returnStatement(t.init.body)]));else"FunctionDeclaration"==e.type?e.id.name==x?D=e:O.body.push(i.variableDeclaration("let",[i.variableDeclarator(e.id,i.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):O.body.push(e);if(D||=i.functionDeclaration(i.identifier(b),[i.identifier("context"),i.identifier("args")],i.blockStatement([])),$.node.body=[D],O.body.length){(y.size||m.size)&&D.body.body.push(i.returnStatement(i.objectExpression([...[...y].map((([e,t])=>i.objectProperty(i.identifier(t),i.identifier(e)))),...[...m].map((([e,t])=>i.objectMethod("get",i.identifier(t),[],i.blockStatement([i.returnStatement(i.identifier(e))]))))]))),$.scope.crawl();const e=new Set;let n=0;for(const[o,a]of[...O.body.entries()].reverse())if("VariableDeclaration"==a.type){t(1==a.declarations.length);const s=a.declarations[0];if(t("Identifier"==s.id.type,`declarator.id.type was "${s.id.type}"`),$.scope.crawl(),$.scope.hasGlobal(s.id.name)){O.body.splice(o,1);const[p]=$.unshiftContainer("body",O),[c]=$.unshiftContainer("body",a);if($.scope.crawl(),!s.init||"FunctionExpression"!=s.init.type&&"ArrowFunctionExpression"!=s.init.type||Object.keys($.scope.globals).some((i=>e.has(i)))){const e=$.scope.getBinding(s.id.name);t(e);for(const r of e.referencePaths)t("Identifier"==r.node.type),r.replaceWith(i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(r.node.name)));for(const t of e.constantViolations)if("AssignmentExpression"==t.node.type)for(const[e,n]of Object.entries(i.getBindingIdentifiers(t.node)))e==s.id.name&&(r(n),Object.assign(n,i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(e))));p.remove(),c.remove(),s.init&&O.body.splice(o,0,i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(s.id.name)),s.init)))}else p.remove(),c.remove(),D.body.body.unshift(a),n++}else e.add(s.id.name)}else if("ClassDeclaration"==a.type&&($.scope.crawl(),t(a.id,"src/processScript/transform.ts:564:37"),$.scope.hasGlobal(a.id.name))){O.body.splice(o,1);const[e]=$.unshiftContainer("body",O),[r]=$.unshiftContainer("body",a);$.scope.crawl();const n=$.scope.getBinding(a.id.name);t(n);for(const e of n.referencePaths)t("Identifier"==e.node.type),e.replaceWith(i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(e.node.name)));e.remove(),r.remove(),O.body.splice(o,0,i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(a.id.name)),i.classExpression(void 0,a.superClass,a.body,a.decorators))))}if($.scope.hasGlobal("_EXPORTS"))for(const e of o("_EXPORTS",$))e.replaceWith(i.arrayExpression([...y.keys(),...m.keys()].map((e=>i.stringLiteral(e)))));O.body.length&&D.body.body.splice(n,0,i.ifStatement(i.unaryExpression("!",i.identifier(`$${l}$FMCL$`)),O))}return h&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_FUNCTION_DOT_PROTOTYPE_`),createGetFunctionPrototypeNode())])),u&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_SET_PROTOTYPE_OF_`),i.callExpression(i.memberExpression(i.memberExpression(i.identifier("Object"),i.identifier("call")),i.identifier("bind")),[i.identifier(`_${l}_DUNDER_PROTO_SETTER_`)]))])),_&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_GET_PROTOTYPE_OF_`),i.callExpression(i.memberExpression(i.memberExpression(i.identifier("Object"),i.identifier("call")),i.identifier("bind")),[i.identifier(`_${l}_DUNDER_PROTO_GETTER_`)]))])),(_||u)&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.objectPattern(_?u?[i.objectProperty(i.identifier("get"),i.identifier(`_${l}_DUNDER_PROTO_GETTER_`)),i.objectProperty(i.identifier("set"),i.identifier(`_${l}_DUNDER_PROTO_SETTER_`))]:[i.objectProperty(i.identifier("get"),i.identifier(`_${l}_DUNDER_PROTO_GETTER_`))]:[i.objectProperty(i.identifier("set"),i.identifier(`_${l}_DUNDER_PROTO_SETTER_`))]),i.callExpression(i.memberExpression(i.identifier("Object"),i.identifier("getOwnPropertyDescriptor")),[i.memberExpression(i.identifier("Object"),i.identifier("prototype")),i.stringLiteral("__proto__")]))])),a(e,{BlockStatement({node:e}){for(const[t,r]of e.body.entries())"FunctionDeclaration"!=r.type||r.generator||(e.body.splice(t,1),e.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(r.id,i.arrowFunctionExpression(r.params,r.body,r.async))])))},ClassBody({node:e,scope:r,parent:n}){t(i.isClass(n));let o=!1;for(const t of e.body){if("ClassMethod"!=t.type)continue;let e=!1;if(a(t.body,{ThisExpression(t){e=!0,o=!0,t.replaceWith(i.identifier(`_${l}_THIS_`))},Function(e){e.skip()}},r),e)if("constructor"!=t.kind)t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),i.callExpression(i.memberExpression(i.super(),i.identifier("valueOf")),[]))]));else{const e=[];if(a(t.body,{CallExpression(i){"Super"==i.node.callee.type&&e.push(i)}},r),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==t)e[0].parentPath.replaceWith(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),e[0].node)]));else{for(const t of e)t.replaceWith(i.assignmentExpression("=",i.identifier(`_${l}_THIS_`),t.node));t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`))]))}else t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),i.callExpression(i.super(),[]))]))}}!n.superClass&&o&&(n.superClass=i.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(i.identifier("undefined"))},BigIntLiteral(e){const t=Number(e.node.value);BigInt(t)==BigInt(e.node.value)?e.replaceWith(i.callExpression(i.identifier("BigInt"),[i.numericLiteral(t)])):e.replaceWith(i.callExpression(i.identifier("BigInt"),[i.stringLiteral(e.node.value)]))}}),{file:e,seclevel:f}};export{transform as default,transform};
|
package/pull.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import{
|
1
|
+
import{copyFilePersistent as t}from"@samual/lib/copyFilePersistent";import{resolve as r}from"path";const pull=async(s,a,i)=>{const[o,e]=i.split(".");if(!o||!e)throw new Error('`script` argument must be in "user.name" format');await t(r(a,o,"scripts",`${e}.js`),r(s,o,`${e}.js`))};export{pull as default,pull};
|
package/push.d.ts
CHANGED
@@ -1,6 +1,6 @@
|
|
1
|
-
import { LaxPartial } from "@samual/lib";
|
2
|
-
import { Info } from ".";
|
3
|
-
export
|
1
|
+
import type { LaxPartial } from "@samual/lib";
|
2
|
+
import type { Info } from ".";
|
3
|
+
export type PushOptions = {
|
4
4
|
/** whether to do the minify step (defaults to `true`) */
|
5
5
|
minify: boolean;
|
6
6
|
/** whether to mangle function and class names (defaults to `false`) */
|