hackmud-script-manager 0.14.0-049ae05 → 0.14.0-9126de3
Sign up to get free protection for your applications and to get access to all the features.
- package/bin/hsm.js +1 -1
- package/index.js +1 -1
- package/package.json +2 -2
- package/processScript/index.js +1 -1
- package/processScript/preprocess.d.ts +0 -1
- package/processScript/preprocess.js +1 -1
- package/processScript/transform.js +1 -1
- package/push.d.ts +4 -3
- package/push.js +1 -1
- package/watch.d.ts +11 -4
- package/watch.js +1 -1
- package/writeFilePersistent-72dc81a3.js +1 -0
package/bin/hsm.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import o from"chalk";import e from"fs";import{homedir as
|
2
|
+
import o from"chalk";import{watch as e}from"chokidar";import s from"fs";import{homedir as t}from"os";import{resolve as i,basename as n,extname as a,dirname as r,relative as l}from"path";import{s as c}from"../processScript/transform.js";import{D as p,w as g}from"../writeFilePersistent-72dc81a3.js";import{generateTypings as m}from"../generateTypings.js";import{syncMacros as f}from"../syncMacros.js";import{pull as h}from"../pull.js";import{watch as u}from"../watch.js";import{push as b}from"../push.js";import{processScript as d}from"../processScript/index.js";import{c as k}from"../processScript/minify.js";import"@babel/traverse";import"@babel/types";import"../processScript/shared.js";import"../assert-1556d989.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"@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"../spliceString-2c6f214f.js";import"../processScript/preprocess.js";import"acorn";import"terser";const{readFile:y,rmdir:w,writeFile:j,mkdir:$}=s.promises,v=i(t(),".config"),P=i(v,"hsm.json"),S=new Map,C=[];let x;const N=o.rgb(255,244,4),F=o.rgb(243,249,152),O=o.rgb(179,255,155),L=o.rgb(255,150,224),U=o.rgb(30,255,0),T=o.rgb(202,202,202),D=new p((o=>{let e=0;for(const s of o)e+=(e>>1)+e+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[N,F,O,L,U,T][e%6](o)}));for(const o of process.argv.slice(2))if("-"==o[0]){const[e,s]=o.split("=");let t=s;if(t)if("true"==t)t=!0;else if("false"==t)t=!1;else{const o=Number(t);isFinite(o)&&(t=o)}else t=!0;if("-"==o[1])S.set(e.slice(2),t);else for(const o of e.slice(1))S.set(o,t)}else C.push(o);function help(){switch(C[0]){case"config":switch(C[1]){case"get":console.log("hsm config get <key>");break;case"set":console.log("hsm config set <key> <value>");break;case"delete":console.log("hsm config delete <key>");break;default:console.log("hsm config <get, delete, set>")}break;case"push":console.log('hsm push [<dir> [..."<script user>.<script name>"]]');break;case"dev":case"watch":console.log(`hsm ${C[0]} <dir> [..."<script user>.<script name>"] [--skip-minify] [--mangle-names]`);break;case"pull":console.log("hsm pull <script user>.<script name>");break;case"minify":case"golf":console.log(`${n(process.argv[1])} ${C[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.14.0-9126de3")}async function getConfig(){return x||(x=await y(P,{encoding:"utf-8"}).then((o=>{let e;try{e=JSON.parse(o)}catch{return console.log("config file was corrupted, resetting"),{}}return e&&"object"==typeof e?e:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${P}`),{}))))}function exploreObject(o,e,s=!1){for(const i of e){var t;o=s?"object"==typeof o[i]?o[i]:o[i]={}:null===(t=o)||void 0===t?void 0:t[i]}return o}function updateConfig(){if(x){const o=JSON.stringify(x,void 0,"\t");j(P,o).catch((async e=>{switch(e.code){case"EISDIR":await w(P);break;case"ENOENT":await $(v);break;default:throw e}j(P,o)}))}}function onPushLogger({file:e,users:s,srcLength:t,minLength:r,error:l}){l?console.log(`error "${o.bold(l.message)}" in ${o.bold(e)}`):console.log(`pushed ${o.bold(e)} to ${s.map((e=>o.bold(D.get(e)))).join(", ")} | ${o.bold(String(r))} chars from ${o.bold(String(t))} | saved ${o.bold(String(t-r))} (${o.bold(`${Math.round(100*(1-r/t))}%`)}) | ${o.bold(`${i(x.hackmudPath,s[0],"scripts",n(e,a(e)))}.js`)}`)}(async()=>{if(S.get("version")||S.get("v"))version();else if(S.get("help")||S.get("h"))help();else{switch(C[0]){case"push":{const o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const e=C[1]||".",s=o.hackmudPath,t=C.slice(2);t.length||t.push("*.*");(await b(e,s,{scripts:t,onPush:onPushLogger,minify:!S.get("skip-minify")})).length||console.warn("couldn't find any scripts to push"),updateConfig()}break;case"dev":case"watch":{var s;if(!C[1]){console.error("specify the directory to watch"),help();break}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.slice(2);e.length||e.push("*.*"),S.has("skip-minify")&&S.has("mangle-names")&&console.warn("pointless specifying both --skip-minify and --mangle-names"),u(C[1],o.hackmudPath,{scripts:e,onPush:onPushLogger,typeDeclarationPath:null===(s=S.get("type-declaration-path"))||void 0===s?void 0:s.toString(),minify:!S.get("skip-minify"),mangleNames:Boolean(S.get("mangle-names"))})}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 h(s,t,e)}catch{console.log("something went wrong, did you forget to #down the script?")}}break;case"sync-macros":{const{hackmudPath:o}=await getConfig();if(!o){console.log("you need to set hackmudPath in config before you can use this command");break}const{macrosSynced:e,usersSynced:s}=await f(o);console.log(`synced ${e} macros to ${s} users`)}break;case"gen-types":{const o=i(C[1]||".");m(o,C[2]?i(C[2]):i(o,"../player.d.ts"),(await getConfig()).hackmudPath)}break;case"config":switch(C[1]){case"get":C[2]?console.log(exploreObject(await getConfig(),C[2].split("."))):console.log(await getConfig());break;case"delete":if(C[2]){var t;const o=C[2].split("."),e=o.pop();if(!o.length){help();break}const s=await getConfig();null===(t=exploreObject(s,o))||void 0===t||delete t[e],console.log(s)}else console.log("Usage:\nhsm config delete <key>");break;case"set":if(C[2]&&C[3]){const o=C[2].split(".");if(!o.length){help();break}const e=o.pop(),s=await getConfig();if(o.length||"hackmudPath"!=e){let t=s;for(const e of o)"object"==typeof t[e]||(t[e]={}),t=t[e];t[e]=C[3]}else s.hackmudPath=i(C[3]);console.log(s)}else console.log("Usage:\nhsm config set <key> <value>");break;default:C[1]&&console.log("unknown command"),help()}break;case"help":case"h":help();break;case"version":case"v":version();break;case"golf":case"minify":{const s=C[1];if(!s){console.log(`Target required\nUsage: ${n(process.argv[1])} ${C[0]} <target> [output]`);break}const t=a(s);if(!c.includes(t)){console.log(`Unsupported file extension "${o.bold(t)}"\nSupported extensions are "${c.map((e=>o.bold(e))).join('", "')}"`);break}S.get("watch")?e(s,{awaitWriteFinish:{stabilityThreshold:100}}).on("ready",(()=>console.log(`watching ${s}`))).on("change",(()=>golfFile(s,t))):await golfFile(s,t)}break;default:C[0]&&console.log("unknown command"),help()}updateConfig()}async function golfFile(e,s){await y(e,{encoding:"utf-8"}).then((async t=>{const a=n(e,s),c=a.endsWith(".src"),p=c?a.slice(0,-4):a;let m="UNKNOWN";"scripts"==n(i(e,".."))&&"hackmud"==n(i(e,"../../.."))&&(m=n(i(e,"../..")));const f=!S.get("skip-minify"),h=Boolean(S.get("mangle-names"));!f&&h&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const{script:u,srcLength:b,warnings:y,timeTook:w}=await d(t,{minify:f,scriptUser:m,scriptName:p,filePath:e,mangleNames:h});for(const{message:e,line:s}of y)console.log(`warning "${o.bold(e)}" on line ${o.bold(String(s))}`);let j;j=C[2]?C[2]:i(r(e),c?`${p}.js`:".js"==s?`${a}.min.js`:`${a}.js`);const $=k(u);await g(j,u).catch((async o=>{if(!C[2]||"EISDIR"!=o.code)throw o;j=i(j,`${n(e,s)}.js`),await g(j,u)})).then((()=>console.log(`wrote ${o.bold($)} chars to ${o.bold(l(".",j))} | saved ${o.bold(b-$)} chars | took ${Math.round(100*w)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}})();
|
package/index.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
export{
|
1
|
+
export{s as supportedExtensions}from"./processScript/transform.js";export{generateTypings}from"./generateTypings.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"@babel/traverse";import"@babel/types";import"./processScript/shared.js";import"./assert-1556d989.js";import"fs";import"path";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"@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/minify.js";import"acorn";import"terser";import"./spliceString-2c6f214f.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./writeFilePersistent-72dc81a3.js";import"chokidar";
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "hackmud-script-manager",
|
3
|
-
"version": "0.14.0-
|
3
|
+
"version": "0.14.0-9126de3",
|
4
4
|
"description": "Script manager for game hackmud, with minification, TypeScript support, and player script type definition generation.",
|
5
5
|
"keywords": [
|
6
6
|
"api",
|
@@ -68,7 +68,7 @@
|
|
68
68
|
"devDependencies": {
|
69
69
|
"@babel/preset-env": "^7.16.4",
|
70
70
|
"@babel/preset-typescript": "^7.16.0",
|
71
|
-
"@samual/lib": "^0.
|
71
|
+
"@samual/lib": "^0.3.0",
|
72
72
|
"@types/babel__core": "^7.1.16",
|
73
73
|
"@types/node": "^12.20.37",
|
74
74
|
"@types/prettier": "^2.4.2",
|
package/processScript/index.js
CHANGED
@@ -1 +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 p from"@babel/plugin-proposal-do-expressions";import a from"@babel/plugin-proposal-function-bind";import l from"@babel/plugin-proposal-function-sent";import i from"@babel/plugin-proposal-json-strings";import n from"@babel/plugin-proposal-logical-assignment-operators";import m from"@babel/plugin-proposal-nullish-coalescing-operator";import c from"@babel/plugin-proposal-numeric-separator";import f from"@babel/plugin-proposal-object-rest-spread";import u from"@babel/plugin-proposal-optional-catch-binding";import b from"@babel/plugin-proposal-optional-chaining";import d from"@babel/plugin-proposal-partial-application";import g from"@babel/plugin-proposal-pipeline-operator";import h from"@babel/plugin-proposal-private-property-in-object";import w from"@babel/plugin-proposal-record-and-tuple";import y from"@babel/plugin-proposal-throw-expressions";import x from"@babel/plugin-transform-exponentiation-operator";import j from"@babel/plugin-transform-typescript";import S from"@babel/traverse";import k from"@babel/types";import
|
1
|
+
import e from"@babel/generator";import{parse as o}from"@babel/parser";import r from"@babel/plugin-proposal-class-properties";import t from"@babel/plugin-proposal-class-static-block";import s from"@babel/plugin-proposal-decorators";import p from"@babel/plugin-proposal-do-expressions";import a from"@babel/plugin-proposal-function-bind";import l from"@babel/plugin-proposal-function-sent";import i from"@babel/plugin-proposal-json-strings";import n from"@babel/plugin-proposal-logical-assignment-operators";import m from"@babel/plugin-proposal-nullish-coalescing-operator";import c from"@babel/plugin-proposal-numeric-separator";import f from"@babel/plugin-proposal-object-rest-spread";import u from"@babel/plugin-proposal-optional-catch-binding";import b from"@babel/plugin-proposal-optional-chaining";import d from"@babel/plugin-proposal-partial-application";import g from"@babel/plugin-proposal-pipeline-operator";import h from"@babel/plugin-proposal-private-property-in-object";import w from"@babel/plugin-proposal-record-and-tuple";import y from"@babel/plugin-proposal-throw-expressions";import x from"@babel/plugin-transform-exponentiation-operator";import j from"@babel/plugin-transform-typescript";import S from"@babel/traverse";import k from"@babel/types";import E from"@rollup/plugin-babel";import N from"@rollup/plugin-commonjs";import C from"@rollup/plugin-json";import v from"@rollup/plugin-node-resolve";import{resolve as L}from"path";import{performance as _}from"perf_hooks";import I from"prettier";import{rollup as $}from"rollup";import{s as D,transform as U}from"./transform.js";export{transform as compile}from"./transform.js";import{c as W,minify as q}from"./minify.js";export{minify}from"./minify.js";import{postprocess as M}from"./postprocess.js";export{postprocess}from"./postprocess.js";import{preprocess as T}from"./preprocess.js";export{preprocess}from"./preprocess.js";import{a as F}from"../assert-1556d989.js";import"./shared.js";import"acorn";import"terser";import"../spliceString-2c6f214f.js";const{default:H}=E,{format:O}=I,{default:P}=e,{default:K}=S;async function processScript(e,{minify:S=!0,uniqueID:E=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:I="UNKNOWN",scriptName:z="UNKNOWN",filePath:B,mangleNames:G=!1}={}){F(/^\w{11}$/.exec(E));const A=_.now(),J=e;let Q,R;const V=/^function\s*\(.+\/\/(?<autocomplete>.+)/.exec(e);if(V)e=`export default ${e}`,({autocomplete:Q}=V.groups);else for(const o of e.split("\n")){const e=/^\s*\/\/(?<commentContent>.+)/.exec(o);if(!e)break;const r=e.groups.commentContent.trim();if(r.startsWith("@autocomplete "))Q=r.slice(14).trimStart();else if(r.startsWith("@seclevel ")){const e=r.slice(10).trimStart().toLowerCase();switch(e){case"fullsec":case"full":case"fs":case"4s":case"f":case"4":R=4;break;case"highsec":case"high":case"hs":case"3s":case"h":case"3":R=3;break;case"midsec":case"mid":case"ms":case"2s":case"m":case"2":R=2;break;case"lowsec":case"low":case"ls":case"1s":case"l":case"1":R=1;break;case"nullsec":case"null":case"ns":case"0s":case"n":case"0":R=0;break;default:throw new Error(`unrecognised seclevel "${e}"`)}}}F(/^\w{11}$/.exec(E));const X=B?L(B):`${E}.ts`,Y=await $({input:X,plugins:[{name:"hackmud-script-manager",transform:e=>T(e,{uniqueID:E}).code},H({babelHelpers:"bundled",plugins:[[j.default,{allowDeclareFields:!0,optimizeConstEnums:!0}],[s.default,{decoratorsBeforeExport:!0}],[p.default],[a.default],[l.default],[d.default],[g.default,{proposal:"hack",topicToken:"%"}],[y.default],[w.default,{syntaxType:"hash",importPolyfill:!0}],[r.default],[t.default],[h.default],[n.default],[c.default],[m.default],[b.default],[u.default],[i.default],[f.default],[x.default]],configFile:!1,extensions:D}),N(),v({extensions:D}),C()],treeshake:{moduleSideEffects:!1}}),Z=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];e=(await Y.generate({})).output[0].code;const{file:ee,seclevel:oe}=U(o(e,{sourceType:"module"}),J,{uniqueID:E,scriptUser:I,scriptName:z});if(null!=R&&oe<R)throw new Error(`detected seclevel ${Z[oe]} is lower than stated seclevel ${Z[R]}`);e=P(ee).code;const re=W(e.replace(/^function\s*\w+\(/,"function("));return S?e=await q(ee,Q,{uniqueID:E,mangleNames:G}):(K(ee,{MemberExpression({node:e}){e.computed||(F("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(ee).code,{parser:"babel",arrowParens:"avoid",semi:!1,trailingComma:"none"})),{srcLength:re,script:e=M(e,oe,E),warnings:[],timeTook:_.now()-A}}export{processScript as default,processScript};
|
@@ -1 +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-1556d989.js";import{s}from"../spliceString-2c6f214f.js";const{default:p}=o,{default:
|
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-1556d989.js";import{s}from"../spliceString-2c6f214f.js";const{default:p}=o,{default:n}=e;function preprocess(e,{uniqueID:o="00000000000"}={}){if(t(/^\w{11}$/.test(o)),/(?:SC|DB)\$/.test(e))throw new Error("SC$ and DB$ are protected and cannot appear in a script");const l=e;let a,c,d;do{a=e.length,e=e.replace(/^\s+/,"").replace(/^\/\/.*/,"").replace(/^\/\*[\s\S]*?\*\//,"")}while(e.length!=a);for(e=e.replace(/^function\s*\(/,"export default function (");;){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 f;if("BABEL_PARSER_SYNTAX_ERROR"!=i.code||"PrivateInExpectedIn"!=i.reasonCode)throw console.log(null===(f=/.+/.exec(e.slice(i.pos)))||void 0===f?void 0:f[0]),i;const p=e.slice(i.pos);let n;if(n=/^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(p))e=s(e,JSON.stringify(l),i.pos,n[0].length);else if(n=/^#[0-4fhmln]?s\./.exec(p))e=s(e,"$",i.pos,1);else if(n=/^#D[^\w$]/.exec(p))e=s(e,"$",i.pos,1);else if(n=/^#FMCL/.exec(p))e=s(e,`$${o}$FMCL`,i.pos,n[0].length);else if(n=/^#G/.exec(p))e=s(e,`$${o}$GLOBAL`,i.pos,n[0].length);else{if(!(n=/^#db\./.exec(p)))throw i;e=s(e,"$",i.pos,1)}}p(c,{Program(e){d=e,e.skip()}});const u=d.scope.hasGlobal("Record"),m=d.scope.hasGlobal("Tuple");return(u||m)&&c.program.body.unshift(i.importDeclaration(u?m?[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")&&c.program.body.unshift(i.importDeclaration([i.importDefaultSpecifier(i.identifier("Proxy"))],i.stringLiteral("proxy-polyfill/src/proxy.js"))),1==d.node.body.length&&"FunctionDeclaration"==d.node.body[0].type?{code:`export default ${n(c).code}`}:{code:n(c).code}}export{preprocess as default,preprocess};
|
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/traverse";import t from"@babel/types";import{getReferencePathsToGlobal as i}from"./shared.js";import{a as r}from"../assert-1556d989.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:n}=e,o=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"];function transform(e,a,{uniqueID:s="00000000000",scriptUser:p="UNKNOWN",scriptName:l="UNKNOWN",seclevel:c=4}={}){const d=`_SCRIPT_${s}_`,f=new Map,b=new Map;let y;if(n(e,{Program(e){y=e,e.skip()}}),y.scope.hasGlobal("_START"))for(const e of i("_START",y))e.replaceWith(t.identifier("_ST"));if(y.scope.hasGlobal("_TIMEOUT"))for(const e of i("_START",y))e.replaceWith(t.identifier("_TO"));if(y.scope.hasGlobal("_SOURCE"))for(const e of i("_SOURCE",y))e.replaceWith(t.stringLiteral(a));if(y.scope.hasGlobal("_BUILD_DATE"))for(const e of i("_BUILD_DATE",y))e.replaceWith(t.numericLiteral(Date.now()));if(y.scope.hasGlobal("_SCRIPT_USER"))for(const e of i("_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 i("_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 i("_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=i("Function",y);if(1==e.length){const t=e[0];r("MemberExpression"==t.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("Identifier"==t.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("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)r("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),h=!0,i.parentPath.replaceWith(t.identifier(`$${s}$FUNCTION_DOT_PROTOTYPE`));h=!0}}let m=4;for(const e of["$fs","$4s","$s"])if(y.scope.hasGlobal(e))for(const n of i(e,y)){var $;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===($=n.parentPath.parentPath)||void 0===$?void 0:$.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}for(const e of["$hs","$3s"])if(y.scope.hasGlobal(e)){m=3;for(const n of i(e,y)){var E;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===(E=n.parentPath.parentPath)||void 0===E?void 0:E.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ms","$2s"])if(y.scope.hasGlobal(e)){m=2;for(const n of i(e,y)){var P;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===(P=n.parentPath.parentPath)||void 0===P?void 0:P.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ls","$1s"])if(y.scope.hasGlobal(e)){m=1;for(const n of i(e,y)){var u;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===(u=n.parentPath.parentPath)||void 0===u?void 0:u.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}for(const e of["$ns","$0s"])if(y.scope.hasGlobal(e)){m=0;for(const n of i(e,y)){var _;r("MemberExpression"==n.parent.type),r("Identifier"==n.parent.property.type),r("MemberExpression"==(null===(_=n.parentPath.parentPath)||void 0===_?void 0:_.node.type)),r("Identifier"==n.parentPath.parentPath.node.property.type),n.parentPath.parentPath.replaceWith(t.identifier(`$${s}$SUBSCRIPT$${n.parent.property.name}$${n.parentPath.parentPath.node.property.name}`))}}if(c=Math.min(c,m),y.scope.hasGlobal("$db"))for(const e of i("$db",y))r("MemberExpression"==e.parentPath.node.type),r("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 i("$D",y))e.replaceWith(t.identifier(`$${s}$DEBUG`));if(y.scope.hasGlobal("$FMCL"))for(const e of i("$FMCL",y))e.replaceWith(t.identifier(`$${s}$FMCL`));if(y.scope.hasGlobal("$G"))for(const e of i("$G",y))e.replaceWith(t.identifier(`$${s}$GLOBAL`));if(y.scope.hasGlobal("_SECLEVEL"))for(const e of i("_SECLEVEL",y))e.replaceWith(t.numericLiteral(c));let T=!1,O=!1;if(y.scope.hasGlobal("Object"))for(const e of i("Object",y))"MemberExpression"!=e.parent.type||e.parent.computed||(r("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(t.identifier(`$${s}$GET_PROTOTYPE_OF`)),T=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(t.identifier(`$${s}$SET_PROTOTYPE_OF`)),O=!0));const x=y.node.body[y.node.body.length-1];let S;if(r(x,"program is empty"),"ExportNamedDeclaration"==x.type){y.node.body.pop();for(const e of x.specifiers){r("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const t="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==t?S=e.local.name:f.set(e.local.name,t)}}const v=t.blockStatement([]);let D;for(const e of y.node.body)if("VariableDeclaration"==e.type)for(const i of e.declarations)if("Identifier"!=i.id.type||i.id.name!=S||!i.init||"FunctionExpression"!=i.init.type&&"ArrowFunctionExpression"!=i.init.type||i.init.async||i.init.generator){for(const r in t.getBindingIdentifiers(i.id))r==S&&(D=t.functionDeclaration(t.identifier(d),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(t.identifier(S),[]))]))),"const"!=e.kind&&f.has(r)&&(b.set(r,f.get(r)),f.delete(r)),v.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(r))]));i.init&&v.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else D=t.functionDeclaration(t.identifier(d),i.init.params,"BlockStatement"==i.init.body.type?i.init.body:t.blockStatement([t.returnStatement(i.init.body)]));else"FunctionDeclaration"==e.type?e.id.name==S?D=e:v.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):v.body.push(e);if(D||(D=t.functionDeclaration(t.identifier(d),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),y.node.body=[D],v.body.length){(f.size||b.size)&&D.body.body.push(t.returnStatement(t.objectExpression([...[...f].map((([e,i])=>t.objectProperty(t.identifier(i),t.identifier(e)))),...[...b].map((([e,i])=>t.objectMethod("get",t.identifier(i),[],t.blockStatement([t.returnStatement(t.identifier(e))]))))]))),y.scope.crawl();const e=new Set;let n=0;for(const[i,o]of[...v.body.entries()].reverse())if("VariableDeclaration"==o.type){r(1==o.declarations.length);const a=o.declarations[0];if(r("Identifier"==a.id.type,`declarator.id.type was "${a.id.type}"`),y.scope.crawl(),y.scope.hasGlobal(a.id.name)){v.body.splice(i,1);const[p]=y.unshiftContainer("body",v),[l]=y.unshiftContainer("body",o);if(y.scope.crawl(),!a.init||"FunctionExpression"!=a.init.type&&"ArrowFunctionExpression"!=a.init.type||Object.keys(y.scope.globals).some((t=>e.has(t)))){const e=y.scope.getBinding(a.id.name);r(e);for(const i of e.referencePaths)r("Identifier"==i.node.type),i.replaceWith(t.memberExpression(t.identifier(`$${s}$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(`$${s}$GLOBAL`),t.identifier(e))));p.remove(),l.remove(),a.init&&v.body.splice(i,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(a.id.name)),a.init)))}else p.remove(),l.remove(),D.body.body.unshift(o),n++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&(y.scope.crawl(),y.scope.hasGlobal(o.id.name))){v.body.splice(i,1);const[e]=y.unshiftContainer("body",v),[n]=y.unshiftContainer("body",o);y.scope.crawl();const a=y.scope.getBinding(o.id.name);r(a);for(const e of a.referencePaths)r("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(e.node.name)));e.remove(),n.remove(),v.body.splice(i,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${s}$GLOBAL`),t.identifier(o.id.name)),t.classExpression(void 0,o.superClass,o.body,o.decorators))))}if(y.scope.hasGlobal("_EXPORTS"))for(const e of i("_EXPORTS",y))e.replaceWith(t.arrayExpression([...f.keys(),...b.keys()].map((e=>t.stringLiteral(e)))));v.body.length&&D.body.body.splice(n,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${s}$FMCL`)),v))}return h&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$FUNCTION_DOT_PROTOTYPE`),createGetFunctionPrototypeNode())])),O&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$SET_PROTOTYPE_OF`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`$${s}$DUNDER_PROTO_SETTER`)]))])),T&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${s}$GET_PROTOTYPE_OF`),t.callExpression(t.memberExpression(t.memberExpression(t.identifier("Object"),t.identifier("call")),t.identifier("bind")),[t.identifier(`$${s}$DUNDER_PROTO_GETTER`)]))])),(T||O)&&D.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.objectPattern(T?O?[t.objectProperty(t.identifier("get"),t.identifier(`$${s}$DUNDER_PROTO_GETTER`)),t.objectProperty(t.identifier("set"),t.identifier(`$${s}$DUNDER_PROTO_SETTER`))]:[t.objectProperty(t.identifier("get"),t.identifier(`$${s}$DUNDER_PROTO_GETTER`))]:[t.objectProperty(t.identifier("set"),t.identifier(`$${s}$DUNDER_PROTO_SETTER`))]),t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getOwnPropertyDescriptor")),[t.memberExpression(t.identifier("Object"),t.identifier("prototype")),t.stringLiteral("__proto__")]))])),n(e,{BlockStatement({node:e}){for(const[i,r]of e.body.entries())"FunctionDeclaration"!=r.type||r.generator||(e.body.splice(i,1),e.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(r.id,t.arrowFunctionExpression(r.params,r.body,r.async))])))},ClassBody({node:e,scope:i,parent:o}){r(t.isClass(o));let a=!1;for(const r of e.body){if("ClassMethod"!=r.type)continue;let e=!1;if(n(r.body,{ThisExpression(i){e=!0,a=!0,i.replaceWith(t.identifier(`_THIS_${s}_`))},Function(e){e.skip()}},i),e)if("constructor"!=r.kind)r.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(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(`_THIS_${s}_`),e[0].node)]));else{for(const i of e)i.replaceWith(t.assignmentExpression("=",t.identifier(`_THIS_${s}_`),i.node));r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${s}_`))]))}else r.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};
|
1
|
+
import e from"@babel/traverse";import t from"@babel/types";import{getReferencePathsToGlobal as i}from"./shared.js";import{a as r}from"../assert-1556d989.js";const n=[".js",".ts"],o=["i","r","f","u","u1","us","ObjectId"];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:a}=e,s=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"];function transform(e,n,{uniqueID:p="00000000000",scriptUser:c="UNKNOWN",scriptName:l="UNKNOWN",seclevel:d=4}={}){const f=`_SCRIPT_${p}_`,b=new Map,y=new Map;let $;if(a(e,{Program(e){$=e,e.skip()}}),$.scope.hasGlobal("_START"))for(const e of i("_START",$))e.replaceWith(t.identifier("_ST"));if($.scope.hasGlobal("_TIMEOUT"))for(const e of i("_START",$))e.replaceWith(t.identifier("_TO"));if($.scope.hasGlobal("_SOURCE"))for(const e of i("_SOURCE",$))e.replaceWith(t.stringLiteral(n));if($.scope.hasGlobal("_BUILD_DATE"))for(const e of i("_BUILD_DATE",$))e.replaceWith(t.numericLiteral(Date.now()));if($.scope.hasGlobal("_SCRIPT_USER"))for(const e of i("_SCRIPT_USER",$))1==c?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_USER`)):e.replaceWith(t.stringLiteral(c));if($.scope.hasGlobal("_SCRIPT_NAME"))for(const e of i("_SCRIPT_NAME",$))1==l?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(l));if($.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of i("_FULL_SCRIPT_NAME",$))1==c||1==l?e.replaceWith(t.stringLiteral(`$${p}$FULL_SCRIPT_NAME`)):e.replaceWith(t.stringLiteral(`${c}.${l}`));let h=!1;if($.scope.hasGlobal("Function")){const e=i("Function",$);if(1==e.length){const t=e[0];r("MemberExpression"==t.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("Identifier"==t.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("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)r("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),r("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),h=!0,i.parentPath.replaceWith(t.identifier(`$${p}$FUNCTION_DOT_PROTOTYPE`));h=!0}}let m=4;for(const e of["$fs","$4s","$s"])$.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])$.scope.hasGlobal(e)&&(m=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])$.scope.hasGlobal(e)&&(m=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])$.scope.hasGlobal(e)&&(m=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])$.scope.hasGlobal(e)&&(m=0,processFakeSubscriptObject(e));if(d=Math.min(d,m),$.scope.hasGlobal("$db"))for(const e of i("$db",$)){var E;r("MemberExpression"==e.parentPath.node.type),r("Identifier"==e.parentPath.node.property.type);const i=e.parentPath.node.property.name;r(o.includes(i),`invalid db method "${i}", valid db methods are "${o.join('", "')}"`),"CallExpression"==(null===(E=e.parentPath.parentPath)||void 0===E?void 0:E.type)?e.parentPath.replaceWith(t.identifier(`$${p}$DB$${i}`)):"ObjectId"==i?e.parentPath.replaceWith(t.arrowFunctionExpression([],t.callExpression(t.identifier(`$${p}$DB$${i}`),[]))):"i"==i||"r"==i?e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a")],t.callExpression(t.identifier(`$${p}$DB$${i}`),[t.identifier("a")]))):e.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier("a"),t.identifier("b")],t.callExpression(t.identifier(`$${p}$DB$${i}`),[t.identifier("a"),t.identifier("b")])))}if($.scope.hasGlobal("$D"))for(const e of i("$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 i("$FMCL",$))e.replaceWith(t.identifier(`$${p}$FMCL`));if($.scope.hasGlobal("$G"))for(const e of i("$G",$))e.replaceWith(t.identifier(`$${p}$GLOBAL`));if($.scope.hasGlobal("_SECLEVEL"))for(const e of i("_SECLEVEL",$))e.replaceWith(t.numericLiteral(d));let u=!1,_=!1;if($.scope.hasGlobal("Object"))for(const e of i("Object",$))"MemberExpression"!=e.parent.type||e.parent.computed||(r("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(t.identifier(`$${p}$GET_PROTOTYPE_OF`)),u=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(t.identifier(`$${p}$SET_PROTOTYPE_OF`)),_=!0));const P=$.node.body[$.node.body.length-1];let O;if(r(P,"program is empty"),"ExportNamedDeclaration"==P.type){$.node.body.pop();for(const e of P.specifiers){r("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const t="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==t?O=e.local.name:b.set(e.local.name,t)}}const x=t.blockStatement([]);let T;for(const e of $.node.body)if("VariableDeclaration"==e.type)for(const i of e.declarations)if("Identifier"!=i.id.type||i.id.name!=O||!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==O&&(T=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([t.returnStatement(t.callExpression(t.identifier(O),[]))]))),"const"!=e.kind&&b.has(r)&&(y.set(r,b.get(r)),b.delete(r)),x.body.push(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(r))]));i.init&&x.body.push(t.expressionStatement(t.assignmentExpression("=",i.id,i.init)))}else T=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==O?T=e:x.body.push(t.variableDeclaration("let",[t.variableDeclarator(e.id,t.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):x.body.push(e);if(T||(T=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),$.node.body=[T],x.body.length){(b.size||y.size)&&T.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 n=0;for(const[i,o]of[...x.body.entries()].reverse())if("VariableDeclaration"==o.type){r(1==o.declarations.length);const a=o.declarations[0];if(r("Identifier"==a.id.type,`declarator.id.type was "${a.id.type}"`),$.scope.crawl(),$.scope.hasGlobal(a.id.name)){x.body.splice(i,1);const[s]=$.unshiftContainer("body",x),[c]=$.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);r(e);for(const i of e.referencePaths)r("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(),c.remove(),a.init&&x.body.splice(i,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${p}$GLOBAL`),t.identifier(a.id.name)),a.init)))}else s.remove(),c.remove(),T.body.body.unshift(o),n++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&($.scope.crawl(),$.scope.hasGlobal(o.id.name))){x.body.splice(i,1);const[e]=$.unshiftContainer("body",x),[n]=$.unshiftContainer("body",o);$.scope.crawl();const a=$.scope.getBinding(o.id.name);r(a);for(const e of a.referencePaths)r("Identifier"==e.node.type),e.replaceWith(t.memberExpression(t.identifier(`$${p}$GLOBAL`),t.identifier(e.node.name)));e.remove(),n.remove(),x.body.splice(i,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 i("_EXPORTS",$))e.replaceWith(t.arrayExpression([...b.keys(),...y.keys()].map((e=>t.stringLiteral(e)))));x.body.length&&T.body.body.splice(n,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${p}$FMCL`)),x))}return h&&T.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`$${p}$FUNCTION_DOT_PROTOTYPE`),createGetFunctionPrototypeNode())])),_&&T.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`)]))])),u&&T.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||_)&&T.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__")]))])),a(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:n}){r(t.isClass(n));let o=!1;for(const r of e.body){if("ClassMethod"!=r.type)continue;let e=!1;if(a(r.body,{ThisExpression(i){e=!0,o=!0,i.replaceWith(t.identifier(`_THIS_${p}_`))},Function(e){e.skip()}},i),e)if("constructor"!=r.kind)r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${p}_`),t.callExpression(t.memberExpression(t.super(),t.identifier("valueOf")),[]))]));else{const e=[];if(a(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(`_THIS_${p}_`),e[0].node)]));else{for(const i of e)i.replaceWith(t.assignmentExpression("=",t.identifier(`_THIS_${p}_`),i.node));r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${p}_`))]))}else r.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_THIS_${p}_`),t.callExpression(t.super(),[]))]))}}!n.superClass&&o&&(n.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};function processFakeSubscriptObject(e){for(const a of i(e,$)){var n,o;r("MemberExpression"==a.parent.type),r("Identifier"==a.parent.property.type),r("MemberExpression"==(null===(n=a.parentPath.parentPath)||void 0===n?void 0:n.node.type)),r("Identifier"==a.parentPath.parentPath.node.property.type),r(/^[_a-z][\d_a-z]{0,24}$/.test(a.parent.property.name),`invalid user "${a.parent.property.name}" in subscript`),r(/^[_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"))])))}}function createGetFunctionPrototypeNode(){for(const e of s)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"))}}export{transform as default,n as s,transform};
|
package/push.d.ts
CHANGED
@@ -1,5 +1,6 @@
|
|
1
|
+
import { LaxPartial } from "@samual/lib";
|
1
2
|
import { Info } from ".";
|
2
|
-
declare type PushOptions = {
|
3
|
+
export declare type PushOptions = {
|
3
4
|
/** whether to do the minify step (defaults to `true`) */
|
4
5
|
minify: boolean;
|
5
6
|
/** whether to mangle function and class names (defaults to `false`) */
|
@@ -11,7 +12,7 @@ declare type PushOptions = {
|
|
11
12
|
*
|
12
13
|
* pushes everything by default (`*.*`)
|
13
14
|
*/
|
14
|
-
scripts: string
|
15
|
+
scripts: string[];
|
15
16
|
/** callback called on script push */
|
16
17
|
onPush: (info: Info) => void;
|
17
18
|
};
|
@@ -24,5 +25,5 @@ declare type PushOptions = {
|
|
24
25
|
* @param options {@link PushOptions details}
|
25
26
|
* @returns array of info on pushed scripts
|
26
27
|
*/
|
27
|
-
export declare function push(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify, mangleNames }?:
|
28
|
+
export declare function push(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify, mangleNames }?: LaxPartial<PushOptions>): Promise<Info[]>;
|
28
29
|
export default push;
|
package/push.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import e from"fs";import{
|
1
|
+
import e from"fs";import{resolve as r,extname as i,basename as t}from"path";import{s as a}from"./processScript/transform.js";import{processScript as o}from"./processScript/index.js";import{D as s,w as p}from"./writeFilePersistent-72dc81a3.js";import{c as n}from"./processScript/minify.js";import"@babel/traverse";import"@babel/types";import"./processScript/shared.js";import"./assert-1556d989.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"@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"./spliceString-2c6f214f.js";import"./processScript/preprocess.js";import"acorn";import"terser";const{readFile:l,readdir:m}=e.promises;async function push(e,c,{scripts:g=["*.*"],onPush:f=(()=>{}),minify:u=!0,mangleNames:b=!1}={}){const h=new s((e=>new Set)),d=new Set,w=new Set;let $=!1;for(const e of g){const[r,i]=e.split(".");r&&"*"!=r?i&&"*"!=i?h.get(r).add(i):d.add(r):i&&"*"!=i?w.add(i):$=!0}const y=new s((e=>new Set)),S=[],j=new s((e=>new Set));let P;if(w.size||$){const t=await m(r(c),{withFileTypes:!0}),a=new Set([...(P=await m(r(e),{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name)),...t.filter((e=>e.isDirectory())).map((e=>e.name)),...t.filter((e=>e.isFile()&&".key"==i(e.name))).map((e=>e.name.slice(0,-4))),...h.keys(),...d]);if($)for(const e of a)d.add(e);else for(const e of a){const r=h.get(e);for(const e of w)r.add(e)}}return await Promise.all([...d].map((async s=>{await m(r(e,s),{withFileTypes:!0}).then((async m=>{await Promise.all(m.map((async m=>{const g=i(m.name);if(m.isFile()&&a.includes(g)){const i=t(m.name,g),a=r(e,s,m.name),{srcLength:h,script:d}=await o(await l(a,{encoding:"utf-8"}),{minify:u,scriptUser:s,scriptName:i,filePath:a,mangleNames:b}),w={file:`${s}/${m.name}`,users:[s],minLength:n(d),error:void 0,srcLength:h};j.get(s).add(i),S.push(w),await p(r(c,s,`scripts/${i}.js`),d),f(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...h].map((async([i,t])=>{d.has(i)||await Promise.all([...t].map((async t=>{let s,m,g;for(const o of a)try{m=`${t}${o}`,s=await l(g=r(e,i,m),{encoding:"utf-8"});break}catch{}if(s){const{srcLength:e,script:a}=await o(s,{minify:u,scriptUser:i,scriptName:t,filePath:g,mangleNames:b}),l={file:`${i}/${m}`,users:[i],minLength:n(a),error:void 0,srcLength:e};S.push(l),await p(r(c,i,"scripts",`${t}.js`),a),f(l)}else y.get(t).add(i)})))}))),await(d.size?Promise.all((P||await m(r(e),{withFileTypes:!0})).map((async s=>{const m=i(s.name);if(!s.isFile()||!a.includes(m))return;const g=t(s.name,m),h=[...d,...y.get(g)].filter((e=>!j.get(e).has(g)));if(!h.length)return;const w=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),$=r(e,s.name),{srcLength:P,script:L}=await o(await l($,{encoding:"utf-8"}),{minify:u,scriptUser:!0,scriptName:g,uniqueID:w,filePath:$,mangleNames:b}),N={file:s.name,users:h,minLength:n(L),error:void 0,srcLength:P};await Promise.all(h.map((e=>p(r(c,e,`scripts/${g}.js`),L.replace(new RegExp(`$${w}$SCRIPT_USER`,"g"),e).replace(new RegExp(`$${w}$FULL_SCRIPT_NAME`,"g"),`${e}.${g}`))))),S.push(N),f(N)}))):Promise.all([...y].map((async([i,t])=>{let s,m,g;for(const t of a)try{m=`${i}${t}`,s=await l(g=r(e,m),{encoding:"utf-8"});break}catch{}if(s){const e=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{srcLength:a,script:l}=await o(s,{minify:u,scriptUser:!0,scriptName:i,uniqueID:e,filePath:g,mangleNames:b}),h={file:m,users:[...t],minLength:n(l),error:void 0,srcLength:a};await Promise.all([...t].map((t=>p(r(c,t,`scripts/${i}.js`),l.replace(new RegExp(`$${e}$SCRIPT_USER`,"g"),t).replace(new RegExp(`$${e}$FULL_SCRIPT_NAME`,"g"),`${t}.${i}`))))),S.push(h),f(h)}})))),S}export{push as default,push};
|
package/watch.d.ts
CHANGED
@@ -1,4 +1,13 @@
|
|
1
|
-
import {
|
1
|
+
import { LaxPartial } from "@samual/lib";
|
2
|
+
import { PushOptions } from "./push";
|
3
|
+
export declare type WatchOptions = PushOptions & {
|
4
|
+
/**
|
5
|
+
* if provided, will write typescript type declarations for all the scripts on every change detected
|
6
|
+
*
|
7
|
+
* writing the type declarations enables interscript type checking and autocompletetes for the args
|
8
|
+
*/
|
9
|
+
typeDeclarationPath: string;
|
10
|
+
};
|
2
11
|
/**
|
3
12
|
* Watches target file or folder for updates and builds and pushes updated file.
|
4
13
|
*
|
@@ -8,7 +17,5 @@ import { Info } from ".";
|
|
8
17
|
* @param scripts to push from (pushes from all if empty)
|
9
18
|
* @param onPush function that's called on each script push
|
10
19
|
*/
|
11
|
-
export declare function watch(sourceDirectory: string, hackmudDirectory: string,
|
12
|
-
genTypes?: string | undefined;
|
13
|
-
}): void;
|
20
|
+
export declare function watch(sourceDirectory: string, hackmudDirectory: string, { scripts, onPush, minify, mangleNames, typeDeclarationPath }?: LaxPartial<WatchOptions>): void;
|
14
21
|
export default watch;
|
package/watch.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import{watch as
|
1
|
+
import{watch as r}from"chokidar";import o from"fs";import{extname as t,basename as i,resolve as e}from"path";import{s}from"./processScript/transform.js";import{generateTypings as p}from"./generateTypings.js";import{processScript as a}from"./processScript/index.js";import{D as n,w as l}from"./writeFilePersistent-72dc81a3.js";import{a as c}from"./assert-1556d989.js";import{c as m}from"./processScript/minify.js";import"@babel/traverse";import"@babel/types";import"./processScript/shared.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"@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"./spliceString-2c6f214f.js";import"./processScript/preprocess.js";import"acorn";import"terser";const{readFile:u,readdir:g}=o.promises;function watch(o,f,{scripts:b=["*.*"],onPush:d,minify:h=!0,mangleNames:w=!1,typeDeclarationPath:y}={}){if(!b.length)throw new Error("scripts option was an empty array");const j=new n((r=>new Set)),S=new Set,L=new Set;let v=!1;for(const r of b){const[o,t]=r.split(".");o&&"*"!=o?t&&"*"!=t?j.get(t).add(o):S.add(o):t&&"*"!=t?L.add(t):v=!0}const F=r("",{depth:1,cwd:o,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async r=>{const p=t(r);if(!s.includes(p))return;const b=i(r,p);if(r==i(r)){if(!(v||S.size||L.has(b)||j.has(b)))return;const p=new n((r=>[]));await Promise.all((await g(o,{withFileTypes:!0})).map((async r=>{if(r.isDirectory())for(const a of await g(e(o,r.name),{withFileTypes:!0})){if(!a.isFile())continue;const o=t(a.name);s.includes(o)&&p.get(i(a.name,o)).push(r.name)}})));const y=new Set;if(v||L.has(b)){for(const r of await g(e(o),{withFileTypes:!0}))r.isDirectory()&&y.add(r.name);for(const r of await g(e(f),{withFileTypes:!0}))r.isDirectory()?y.add(r.name):r.isFile()&&r.name.endsWith(".key")&&y.add(r.name.slice(0,-4));for(const r of j.values())for(const o of r)y.add(o)}for(const r of S)y.add(r);for(const r of j.get(b))y.add(r);const F=[...y].filter((r=>!p.has(r)));if(!F.length)return void(null==d||d({file:r,users:[],srcLength:0,minLength:0,error:new Error("no users to push to")}));const $=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),P=e(o,r);let E,T;try{({srcLength:E,script:T}=await a(await u(P,{encoding:"utf-8"}),{minify:h,scriptUser:!0,scriptName:b,uniqueID:$,filePath:P,mangleNames:w}))}catch(o){return c(o instanceof Error),void(null==d||d({file:r,users:[],srcLength:0,minLength:0,error:o}))}return await Promise.all(F.map((r=>l(e(f,r,`scripts/${b}.js`),T.replace(new RegExp(`$${$}$SCRIPT_USER`,"g"),r).replace(new RegExp(`$${$}$FULL_SCRIPT_NAME`,"g"),`${r}.${b}`))))),void(null==d||d({file:r,users:F,minLength:m(T),error:void 0,srcLength:E}))}const y=i(e(r,".."));if(!(v||S.size||L.has(b)||j.get(b).has(y)))return;const F=e(o,r),$=await u(F,{encoding:"utf-8"});let P,E;try{({srcLength:P,script:E}=await a($,{minify:h,scriptUser:y,scriptName:b,filePath:F,mangleNames:w}))}catch(o){return c(o instanceof Error),void(null==d||d({file:r,users:[],srcLength:0,minLength:0,error:o}))}await l(e(f,y,"scripts",`${b}.js`),E),null==d||d({file:r,users:[y],srcLength:P,minLength:m(E),error:void 0})}));y&&(p(o,e(o,y),f),F.on("add",(()=>p(o,e(o,y),f))),F.on("unlink",(()=>p(o,e(o,y),f))))}export{watch as default,watch};
|
@@ -0,0 +1 @@
|
|
1
|
+
import e from"fs";import{dirname as r}from"path";class DynamicMap extends Map{constructor(e){super(),this.fallbackHandler=e}get(e){if(super.has(e))return super.get(e);const r=this.fallbackHandler(e);return super.set(e,r),r}}const{writeFile:t,mkdir:s}=e.promises;function writeFilePersistent(e,a,i){return t(e,a,i).catch((async n=>{if("ENOENT"!=n.code)throw n;await s(r(e),{recursive:!0}),await t(e,a,i)}))}export{DynamicMap as D,writeFilePersistent as w};
|