hackmud-script-manager 0.15.0-4152f8d → 0.16.0-972cf7b

Sign up to get free protection for your applications and to get access to all the features.
package/bin/hsm.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import o from"chalk";import{watch as e}from"chokidar";import s from"fs";import{homedir as t}from"os";import{resolve as n,basename as i,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"prettier";import"rollup";import"../processScript/postprocess.js";import"../processScript/preprocess.js";import"../spliceString-2c6f214f.js";import"acorn";import"terser";const{readFile:w,rmdir:y,writeFile:j,mkdir:$}=s.promises,v=n(t(),".config"),P=n(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),D=o.rgb(202,202,202),E=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,D][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(`${i(process.argv[1])} ${C[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.15.0-4152f8d")}async function getConfig(){return x||(x=await w(P,{encoding:"utf-8"}).then((o=>{let e;try{e=JSON.parse(o)}catch{return console.log("config file was corrupted, resetting"),{}}return e&&"object"==typeof e?e:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${P}`),{}))))}function exploreObject(o,e,s=!1){for(const n of e){var t;o=s?"object"==typeof o[n]?o[n]:o[n]={}:null===(t=o)||void 0===t?void 0:t[n]}return o}function updateConfig(){if(x){const o=JSON.stringify(x,void 0,"\t");j(P,o).catch((async e=>{switch(e.code){case"EISDIR":await y(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(E.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(`${n(x.hackmudPath,s[0],"scripts",i(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")),onReady:()=>console.log("watching")})}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=n(C[1]||".");m(o,C[2]?n(C[2]):n(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=n(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: ${i(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 w(e,{encoding:"utf-8"}).then((async t=>{const a=i(e,s),c=a.endsWith(".src"),p=c?a.slice(0,-4):a;let m="UNKNOWN";"scripts"==i(n(e,".."))&&"hackmud"==i(n(e,"../../.."))&&(m=i(n(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 u=performance.now(),{script:b,srcLength:w,warnings:y}=await d(t,{minify:f,scriptUser:m,scriptName:p,filePath:e,mangleNames:h}),j=performance.now()-u;for(const{message:e,line:s}of y)console.log(`warning "${o.bold(e)}" on line ${o.bold(String(s))}`);let $;$=C[2]?C[2]:n(r(e),c?`${p}.js`:".js"==s?`${a}.min.js`:`${a}.js`);const v=k(b);await g($,b).catch((async o=>{if(!C[2]||"EISDIR"!=o.code)throw o;$=n($,`${i(e,s)}.js`),await g($,b)})).then((()=>console.log(`wrote ${o.bold(v)} chars to ${o.bold(l(".",$))} | saved ${o.bold(w-v)} chars | took ${Math.round(100*j)/100}ms`)),(o=>console.log(o.message)))}),(o=>console.log(o.message)))}})();
2
+ import e from"chalk";import{watch as o}from"chokidar";import s from"fs";import{homedir as n}from"os";import{resolve as t,basename as a,extname as i,dirname as c,relative as l}from"path";import{s as r}from"../constants-9bb78688.js";import{D as g,w as f}from"../writeFilePersistent-72dc81a3.js";import{generateTypings as h}from"../generateTypings.js";import{syncMacros as m}from"../syncMacros.js";import{pull as p}from"../pull.js";import{c as u}from"../countHackmudCharacters-1e122984.js";const{readFile:d,rmdir:k,writeFile:b,mkdir:w}=s.promises,y=t(n(),".config"),$=t(y,"hsm.json"),j=new Map,v=[];let P;const C=e.rgb(255,244,4),N=e.rgb(243,249,152),S=e.rgb(179,255,155),x=e.rgb(255,150,224),F=e.rgb(30,255,0),O=e.rgb(202,202,202),U=new g((e=>{let o=0;for(const s of e)o+=(o>>1)+o+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[C,N,S,x,F,O][o%6](e)}));for(const e of process.argv.slice(2))if("-"==e[0]){const[o,s]=e.split("=");let n=s;if(n)if("true"==n)n=!0;else if("false"==n)n=!1;else{const e=Number(n);isFinite(e)&&(n=e)}else n=!0;if("-"==e[1])j.set(o.slice(2),n);else for(const e of o.slice(1))j.set(e,n)}else v.push(e);function help(){switch(v[0]){case"config":switch(v[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>"] [--skip-minify] [--mangle-names]');break;case"dev":case"watch":console.log(`hsm ${v[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(`${a(process.argv[1])} ${v[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.16.0-972cf7b")}async function getConfig(){return P||(P=await d($,{encoding:"utf-8"}).then((e=>{let o;try{o=JSON.parse(e)}catch{return console.log("config file was corrupted, resetting"),{}}return o&&"object"==typeof o?o:(console.log("config file was corrupted, resetting"),{})}),(()=>(console.log(`creating config file at ${$}`),{}))))}function exploreObject(e,o,s=!1){for(const t of o){var n;e=s?"object"==typeof e[t]?e[t]:e[t]={}:null===(n=e)||void 0===n?void 0:n[t]}return e}function updateConfig(){if(P){const e=JSON.stringify(P,void 0,"\t");b($,e).catch((async o=>{switch(o.code){case"EISDIR":await k($);break;case"ENOENT":await w(y);break;default:throw o}b($,e)}))}}function onPushLogger({file:o,users:s,minLength:n,error:c}){c?console.log(`error "${e.bold(c.message)}" in ${e.bold(o)}`):console.log(`pushed ${e.bold(o)} to ${s.map((o=>e.bold(U.get(o)))).join(", ")} | ${e.bold(String(n))} chars | ${e.bold(`${t(P.hackmudPath,s[0],"scripts",a(o,i(o)))}.js`)}`)}(async()=>{if(j.get("version")||j.get("v"))version();else if(j.get("help")||j.get("h"))help();else{switch(v[0]){case"push":{const{push:e}=await import("../push.js"),o=await getConfig();if(!o.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const s=v[1];if(!s){console.error("specify the directory to watch"),help();break}const n=o.hackmudPath,t=v.slice(2);t.length||t.push("*.*"),j.has("skip-minify")&&j.has("mangle-names")&&console.warn("pointless specifying both --skip-minify and --mangle-names");(await e(s,n,{scripts:t,onPush:onPushLogger,minify:!j.get("skip-minify"),mangleNames:Boolean(j.get("mangle-names"))})).length||console.warn("couldn't find any scripts to push"),updateConfig()}break;case"dev":case"watch":{var s;const{watch:e}=await import("../watch.js");if(!v[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 n=v.slice(2);n.length||n.push("*.*"),j.has("skip-minify")&&j.has("mangle-names")&&console.warn("pointless specifying both --skip-minify and --mangle-names"),e(v[1],o.hackmudPath,{scripts:n,onPush:onPushLogger,typeDeclarationPath:null===(s=j.get("type-declaration-path"))||void 0===s?void 0:s.toString(),minify:!j.get("skip-minify"),mangleNames:Boolean(j.get("mangle-names")),onReady:()=>console.log("watching")})}break;case"pull":{const e=await getConfig();if(!e.hackmudPath){console.log("you need to set hackmudPath in config before you can use this command");break}const o=v[1];if(!o){help();break}const s=v[2]||".",n=e.hackmudPath;try{await p(s,n,o)}catch{console.log("something went wrong, did you forget to #down the script?")}}break;case"sync-macros":{const{hackmudPath:e}=await getConfig();if(!e){console.log("you need to set hackmudPath in config before you can use this command");break}const{macrosSynced:o,usersSynced:s}=await m(e);console.log(`synced ${o} macros to ${s} users`)}break;case"gen-types":{const e=t(v[1]||".");h(e,v[2]?t(v[2]):t(e,"../player.d.ts"),(await getConfig()).hackmudPath)}break;case"config":switch(v[1]){case"get":v[2]?console.log(exploreObject(await getConfig(),v[2].split("."))):console.log(await getConfig());break;case"delete":if(v[2]){var n;const e=v[2].split("."),o=e.pop();if(!e.length){help();break}const s=await getConfig();null===(n=exploreObject(s,e))||void 0===n||delete n[o],console.log(s)}else console.log("Usage:\nhsm config delete <key>");break;case"set":if(v[2]&&v[3]){const e=v[2].split(".");if(!e.length){help();break}const o=e.pop(),s=await getConfig();if(e.length||"hackmudPath"!=o){let n=s;for(const o of e)"object"==typeof n[o]||(n[o]={}),n=n[o];n[o]=v[3]}else s.hackmudPath=t(v[3]);console.log(s)}else console.log("Usage:\nhsm config set <key> <value>");break;default:v[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=v[1];if(!s){console.log(`Target required\nUsage: ${a(process.argv[1])} ${v[0]} <target> [output]`);break}const n=i(s);if(!r.includes(n)){console.log(`Unsupported file extension "${e.bold(n)}"\nSupported extensions are "${r.map((o=>e.bold(o))).join('", "')}"`);break}j.get("watch")?o(s,{awaitWriteFinish:{stabilityThreshold:100}}).on("ready",(()=>console.log(`watching ${s}`))).on("change",(()=>golfFile(s,n))):await golfFile(s,n)}break;default:v[0]&&console.log("unknown command"),help()}updateConfig()}async function golfFile(o,s){const{processScript:n}=await import("../processScript/index.js");await d(o,{encoding:"utf-8"}).then((async i=>{const r=a(o,s),g=r.endsWith(".src"),h=g?r.slice(0,-4):r;let m="UNKNOWN";"scripts"==a(t(o,".."))&&"hackmud"==a(t(o,"../../.."))&&(m=a(t(o,"../..")));const p=!j.get("skip-minify"),d=Boolean(j.get("mangle-names"));!p&&d&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const k=performance.now(),{script:b,warnings:w}=await n(i,{minify:p,scriptUser:m,scriptName:h,filePath:o,mangleNames:d}),y=performance.now()-k;for(const{message:o,line:s}of w)console.log(`warning "${e.bold(o)}" on line ${e.bold(String(s))}`);let $;$=v[2]?v[2]:t(c(o),g?`${h}.js`:".js"==s?`${r}.min.js`:`${r}.js`);const P=u(b);await f($,b).catch((async e=>{if(!v[2]||"EISDIR"!=e.code)throw e;$=t($,`${a(o,s)}.js`),await f($,b)})).then((()=>console.log(`wrote ${e.bold(P)} chars to ${e.bold(l(".",$))} | took ${Math.round(100*y)/100}ms`)),(e=>console.log(e.message)))}),(e=>console.log(e.message)))}})();
@@ -0,0 +1 @@
1
+ const s=[".js",".ts"],t=["i","r","f","u","u1","us","ObjectId"];export{s,t as v};
@@ -0,0 +1 @@
1
+ function countHackmudCharacters(u){return u.replace(/\/\/.*/g,"").replace(/[ \t\n\r\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000]/g,"").length}export{countHackmudCharacters as c};
package/index.d.ts CHANGED
@@ -8,7 +8,6 @@ export { watch } from "./watch";
8
8
  export declare type Info = {
9
9
  file: string;
10
10
  users: string[];
11
- srcLength: number;
12
11
  minLength: number;
13
12
  error: Error | undefined;
14
13
  };
package/index.js CHANGED
@@ -1 +1 @@
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"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";
1
+ export{s as supportedExtensions}from"./constants-9bb78688.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"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"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"prettier";import"rollup";import"./processScript/minify.js";import"acorn";import"terser";import"./processScript/shared.js";import"./assert-1556d989.js";import"./spliceString-2c6f214f.js";import"./countHackmudCharacters-1e122984.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"import-meta-resolve";import"./processScript/transform.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.15.0-4152f8d",
3
+ "version": "0.16.0-972cf7b",
4
4
  "description": "Script manager for game hackmud, with minification, TypeScript support, and player script type definition generation.",
5
5
  "keywords": [
6
6
  "api",
@@ -60,6 +60,7 @@
60
60
  "acorn": "^8.5.0",
61
61
  "chalk": "^5.0.0",
62
62
  "chokidar": "^3.5.2",
63
+ "import-meta-resolve": "^1.1.1",
63
64
  "prettier": "^2.4.1",
64
65
  "proxy-polyfill": "^0.3.2",
65
66
  "rollup": "^2.60.0",
@@ -1,7 +1,7 @@
1
1
  export { minify } from "./minify";
2
2
  export { postprocess } from "./postprocess";
3
3
  export { preprocess } from "./preprocess";
4
- export { transform as compile } from "./transform";
4
+ export { transform } from "./transform";
5
5
  export declare type ProcessOptions = {
6
6
  /** whether to minify the given code */
7
7
  minify: boolean;
@@ -22,7 +22,6 @@ export declare type ProcessOptions = {
22
22
  * @param options {@link ProcessOptions details}
23
23
  */
24
24
  export declare function processScript(code: string, { minify: shouldMinify, uniqueID, scriptUser, scriptName, filePath, mangleNames }?: Partial<ProcessOptions>): Promise<{
25
- srcLength: number;
26
25
  script: string;
27
26
  warnings: {
28
27
  message: string;
@@ -1 +1 @@
1
- import e from"@babel/generator";import{parse as r}from"@babel/parser";import o from"@babel/plugin-proposal-class-properties";import t from"@babel/plugin-proposal-class-static-block";import a from"@babel/plugin-proposal-decorators";import s from"@babel/plugin-proposal-do-expressions";import p from"@babel/plugin-proposal-function-bind";import l from"@babel/plugin-proposal-function-sent";import i from"@babel/plugin-proposal-json-strings";import n from"@babel/plugin-proposal-logical-assignment-operators";import c from"@babel/plugin-proposal-nullish-coalescing-operator";import m 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 d from"@babel/plugin-proposal-optional-chaining";import b 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 y from"@babel/plugin-proposal-record-and-tuple";import w from"@babel/plugin-proposal-throw-expressions";import k from"@babel/plugin-transform-exponentiation-operator";import j from"@babel/plugin-transform-typescript";import v from"@babel/traverse";import x from"@babel/types";import S from"@rollup/plugin-babel";import E from"@rollup/plugin-commonjs";import L from"@rollup/plugin-json";import $ from"@rollup/plugin-node-resolve";import{resolve as C}from"path";import N from"prettier";import{rollup as I}from"rollup";import{s as _,transform as D}from"./transform.js";export{transform as compile}from"./transform.js";import{c as P,minify as M}from"./minify.js";export{minify}from"./minify.js";import{postprocess as O}from"./postprocess.js";export{postprocess}from"./postprocess.js";import{preprocess as U}from"./preprocess.js";export{preprocess}from"./preprocess.js";import{includesIllegalString as q,replaceIllegalStrings as V}from"./shared.js";import{a as W}from"../assert-1556d989.js";import"acorn";import"terser";import"../spliceString-2c6f214f.js";const{default:T}=S,{format:F}=N,{default:H}=e,{default:K}=v;async function processScript(e,{minify:v=!0,uniqueID:S=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:N="UNKNOWN",scriptName:z="UNKNOWN",filePath:A,mangleNames:B=!1}={}){W(/^\w{11}$/.exec(S));const G=e;let J,Q;const R=/^function\s*\(.+\/\/(?<autocomplete>.+)/.exec(e);if(R)e=`export default ${e}`,({autocomplete:J}=R.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 "))J=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":Q=4;break;case"highsec":case"high":case"hs":case"3s":case"h":case"3":Q=3;break;case"midsec":case"mid":case"ms":case"2s":case"m":case"2":Q=2;break;case"lowsec":case"low":case"ls":case"1s":case"l":case"1":Q=1;break;case"nullsec":case"null":case"ns":case"0s":case"n":case"0":Q=0;break;default:throw new Error(`unrecognised seclevel "${e}"`)}}}W(/^\w{11}$/.exec(S));const X=A?C(A):`${S}.ts`,Y=await I({input:X,plugins:[{name:"hackmud-script-manager",transform:e=>U(e,{uniqueID:S}).code},T({babelHelpers:"bundled",plugins:[[j.default,{allowDeclareFields:!0,optimizeConstEnums:!0}],[a.default,{decoratorsBeforeExport:!0}],[s.default],[p.default],[l.default],[b.default],[g.default,{proposal:"hack",topicToken:"%"}],[w.default],[y.default,{syntaxType:"hash",importPolyfill:!0}],[o.default],[t.default],[h.default],[n.default],[m.default],[c.default],[d.default],[u.default],[i.default],[f.default],[k.default]],configFile:!1,extensions:_}),E(),$({extensions:_}),L()],treeshake:{moduleSideEffects:!1}}),Z=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];e=(await Y.generate({})).output[0].code;const{file:ee,seclevel:re}=D(r(e,{sourceType:"module"}),G,{uniqueID:S,scriptUser:N,scriptName:z});if(null!=Q&&re<Q)throw new Error(`detected seclevel ${Z[re]} is lower than stated seclevel ${Z[Q]}`);e=H(ee).code;const oe=P(e.replace(/^function\s*\w+\(/,"function("));if(v?e=await M(ee,J,{uniqueID:S,mangleNames:B}):(K(ee,{MemberExpression({node:e}){e.computed||(W("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=x.stringLiteral("prototype")):"__proto__"==e.property.name?(e.computed=!0,e.property=x.stringLiteral("__proto__")):q(e.property.name)&&(e.computed=!0,e.property=x.stringLiteral(V(S,e.property.name))))},VariableDeclarator(e){!function renameVariables(r){switch(r.type){case"Identifier":q(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)W("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}"`)}}(e.node.id)},ObjectProperty({node:e}){"Identifier"==e.key.type&&q(e.key.name)&&(e.key=x.stringLiteral(V(S,e.key.name)),e.shorthand=!1)},StringLiteral({node:e}){e.value=V(S,e.value)},TemplateLiteral({node:e}){for(const r of e.quasis)r.value.cooked?(r.value.cooked=V(S,r.value.cooked),r.value.raw=r.value.cooked.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"$\\{")):r.value.raw=V(S,r.value.raw)}}),e=F(H(ee,{comments:!1}).code,{parser:"babel",arrowParens:"avoid",semi:!1,trailingComma:"none"})),e=O(e,re,S),q(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{srcLength:oe,script:e,warnings:[]}}export{processScript as default,processScript};
1
+ import e from"@babel/generator";import{parse as r}from"@babel/parser";import o from"@babel/plugin-proposal-class-properties";import t from"@babel/plugin-proposal-class-static-block";import a from"@babel/plugin-proposal-decorators";import s from"@babel/plugin-proposal-do-expressions";import p from"@babel/plugin-proposal-function-bind";import l from"@babel/plugin-proposal-function-sent";import i from"@babel/plugin-proposal-json-strings";import n from"@babel/plugin-proposal-logical-assignment-operators";import m from"@babel/plugin-proposal-nullish-coalescing-operator";import c from"@babel/plugin-proposal-numeric-separator";import f from"@babel/plugin-proposal-object-rest-spread";import u from"@babel/plugin-proposal-optional-catch-binding";import d from"@babel/plugin-proposal-optional-chaining";import b from"@babel/plugin-proposal-partial-application";import g from"@babel/plugin-proposal-pipeline-operator";import y from"@babel/plugin-proposal-private-property-in-object";import h from"@babel/plugin-proposal-record-and-tuple";import w from"@babel/plugin-proposal-throw-expressions";import k from"@babel/plugin-transform-exponentiation-operator";import j from"@babel/plugin-transform-typescript";import x from"@babel/traverse";import v from"@babel/types";import S from"@rollup/plugin-babel";import E from"@rollup/plugin-commonjs";import L from"@rollup/plugin-json";import $ from"@rollup/plugin-node-resolve";import{resolve as C}from"path";import N from"prettier";import{rollup as I}from"rollup";import{s as _}from"../constants-9bb78688.js";import{minify as D}from"./minify.js";export{minify}from"./minify.js";import{postprocess as P}from"./postprocess.js";export{postprocess}from"./postprocess.js";import{preprocess as M}from"./preprocess.js";export{preprocess}from"./preprocess.js";import{includesIllegalString as O,replaceUnsafeStrings as U}from"./shared.js";import{transform as q}from"./transform.js";export{transform}from"./transform.js";import{a as V}from"../assert-1556d989.js";import"acorn";import"terser";import"../spliceString-2c6f214f.js";import"../countHackmudCharacters-1e122984.js";import"import-meta-resolve";const{default:W}=S,{format:H}=N,{default:T}=e,{default:F}=x;async function processScript(e,{minify:x=!0,uniqueID:S=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),scriptUser:N="UNKNOWN",scriptName:K="UNKNOWN",filePath:z,mangleNames:A=!1}={}){V(/^\w{11}$/.exec(S));const B=e;let G,R;const J=/^function\s*\(.+\/\/(?<autocomplete>.+)/.exec(e);if(J)e=`export default ${e}`,({autocomplete:G}=J.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 "))G=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":R=4;break;case"highsec":case"high":case"hs":case"3s":case"h":case"3":R=3;break;case"midsec":case"mid":case"ms":case"2s":case"m":case"2":R=2;break;case"lowsec":case"low":case"ls":case"1s":case"l":case"1":R=1;break;case"nullsec":case"null":case"ns":case"0s":case"n":case"0":R=0;break;default:throw new Error(`unrecognised seclevel "${e}"`)}}}V(/^\w{11}$/.exec(S));const Q=z?C(z):`${S}.ts`,X=await I({input:Q,plugins:[{name:"hackmud-script-manager",transform:async e=>(await M(e,{uniqueID:S})).code},W({babelHelpers:"bundled",plugins:[[j.default,{allowDeclareFields:!0,optimizeConstEnums:!0}],[a.default,{decoratorsBeforeExport:!0}],[s.default],[p.default],[l.default],[b.default],[g.default,{proposal:"hack",topicToken:"%"}],[w.default],[h.default,{syntaxType:"hash",importPolyfill:!0}],[o.default],[t.default],[y.default],[n.default],[c.default],[m.default],[d.default],[u.default],[i.default],[f.default],[k.default]],configFile:!1,extensions:_}),E(),$({extensions:_}),L()],treeshake:{moduleSideEffects:!1}}),Y=["NULLSEC","LOWSEC","MIDSEC","HIGHSEC","FULLSEC"];e=(await X.generate({})).output[0].code;const{file:Z,seclevel:ee}=q(r(e,{sourceType:"module"}),B,{uniqueID:S,scriptUser:N,scriptName:K});if(null!=R&&ee<R)throw new Error(`detected seclevel ${Y[ee]} is lower than stated seclevel ${Y[R]}`);if(e=T(Z).code,x?e=await D(Z,G,{uniqueID:S,mangleNames:A}):(F(Z,{MemberExpression({node:e}){e.computed||(V("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=v.stringLiteral("prototype")):"__proto__"==e.property.name?(e.computed=!0,e.property=v.stringLiteral("__proto__")):O(e.property.name)&&(e.computed=!0,e.property=v.stringLiteral(U(S,e.property.name))))},VariableDeclarator(e){!function renameVariables(r){switch(r.type){case"Identifier":O(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)V("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}"`)}}(e.node.id)},ObjectProperty({node:e}){"Identifier"==e.key.type&&O(e.key.name)&&(e.key=v.stringLiteral(U(S,e.key.name)),e.shorthand=!1)},StringLiteral({node:e}){e.value=U(S,e.value)},TemplateLiteral({node:e}){for(const r of e.quasis)r.value.cooked?(r.value.cooked=U(S,r.value.cooked),r.value.raw=r.value.cooked.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"$\\{")):r.value.raw=U(S,r.value.raw)},RegExpLiteral(e){e.node.pattern=U(S,e.node.pattern),delete e.node.extra}}),e=H(T(Z,{comments:!1}).code,{parser:"babel",arrowParens:"avoid",semi:!1,trailingComma:"none"})),e=P(e,ee,S),O(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,processScript};
@@ -1 +1 @@
1
- import e from"@babel/generator";import t from"@babel/traverse";import r from"@babel/types";import{tokenizer as i,tokTypes as n}from"acorn";import*as a from"terser";import{getReferencePathsToGlobal as o,includesIllegalString as s,replaceIllegalStrings as p}from"./shared.js";import{a as l}from"../assert-1556d989.js";import{s as u}from"../spliceString-2c6f214f.js";function countHackmudCharacters(e){return e.replace(/\/\/.*/g,"").replace(/[ \t\n\r\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000]/g,"").length}const{default:c}=e,{default:f}=t;async function minify(e,t,{uniqueID:i="00000000000",mangleNames:n=!1}={}){let d;l(/^\w{11}$/.exec(i)),f(e,{Program(e){d=e,e.skip()}});const m=d.get("body.0");for(const e of[...m.node.params].reverse()){if("Identifier"==e.type){if(!m.scope.getBinding(e.name).referenced){m.node.params.pop();continue}}break}for(const e in d.scope.globals){if("arguments"==e||e.startsWith(`$${i}`))continue;const t=o(e,d);if(!(5+e.length+t.length>=e.length*t.length)){for(const n of t)n.replaceWith(r.identifier(`_GLOBAL_${e}_${i}_`));m.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_GLOBAL_${e}_${i}_`),r.identifier(e))]))}}const y=o(`$${i}$GLOBAL`,d);if(y.length>3){for(const e of y)e.replaceWith(r.identifier(`_G_${i}_`));m.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_G_${i}_`),r.identifier(`$${i}$GLOBAL`))]))}const _=[];let $=!1;const g=r.cloneNode(e);f(g,{MemberExpression({node:e}){e.computed||(l("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=r.identifier(`_PROTOTYPE_PROPERTY_${i}_`)):"__proto__"==e.property.name?(e.computed=!0,e.property=r.identifier(`_PROTO_PROPERTY_${i}_`)):s(e.property.name)&&(e.computed=!0,e.property=r.stringLiteral(p(i,e.property.name))))},ObjectProperty({node:e}){"Identifier"==e.key.type&&s(e.key.name)&&(e.key=r.stringLiteral(p(i,e.key.name)),e.shorthand=!1)},StringLiteral({node:e}){e.value=p(i,e.value)},TemplateLiteral({node:e}){for(const t of e.quasis)t.value.cooked?(t.value.cooked=p(i,t.value.cooked),t.value.raw=t.value.cooked.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"$\\{")):t.value.raw=p(i,t.value.raw)}});const E=(await a.minify(c(g).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:!n,keep_fnames:!n})).code.replace(new RegExp(`_PROTOTYPE_PROPERTY_${i}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${i}_`,"g"),'"__proto__"');let b,v,h=!1;{const t=[];f(e,{FunctionDeclaration(e){e.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(e){const t={};parseObjectExpression(e.node,t)&&e.replaceWith(r.identifier(`_JSON_VALUE_${_.push(t)-1}_${i}_`))},ArrayExpression(e){const t=[];parseArrayExpression(e.node,t)&&e.replaceWith(r.identifier(`_JSON_VALUE_${_.push(t)-1}_${i}_`))}}),e.traverse({TemplateLiteral(e){const t=e.node;let i=r.stringLiteral(t.quasis[0].value.cooked);for(let e=0;e<t.expressions.length;e++){const n=t.expressions[e],a=t.quasis[e+1];i=r.binaryExpression("+",i,n),a.value.cooked&&(i=r.binaryExpression("+",i,r.stringLiteral(a.value.cooked)))}e.replaceWith(i)},MemberExpression({node:e}){e.computed||(l("Identifier"==e.property.type),e.property.name.length<3||(e.computed=!0,e.property=r.stringLiteral(e.property.name)))},UnaryExpression(e){if("void"==e.node.operator)"NumericLiteral"!=e.node.argument.type||e.node.argument.value||(e.replaceWith(r.identifier(`_UNDEFINED_${i}_`)),$=!0);else if("-"==e.node.operator&&"NumericLiteral"==e.node.argument.type){const n=-e.node.argument.value;t.push((async()=>{if((await minifyNumber(n)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=_.indexOf(n);-1==t&&(t+=_.push(n)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))})()),e.skip()}},NullLiteral(e){let t=_.indexOf(null);-1==t&&(t+=_.push(null)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))},BooleanLiteral(e){let t=_.indexOf(e.node.value);-1==t&&(t+=_.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))},NumericLiteral(e){t.push((async()=>{if((await minifyNumber(e.node.value)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=_.indexOf(e.node.value);-1==t&&(t+=_.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))})())},StringLiteral(e){if(e.node.value=p(i,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 t=_.indexOf(e.node.value);-1==t&&(t+=_.push(e.node.value)),e.replaceWith(r.identifier(`_JSON_VALUE_${t}_${i}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let t=_.indexOf(e.key.name);-1==t&&(t+=_.push(e.key.name)),e.computed=!0,e.key=r.identifier(`_JSON_VALUE_${t}_${i}_`)}}),e.skip()}}),await Promise.all(t);const n=e.program.body[0];if(l("FunctionDeclaration"==n.type),_.length)if(h=!0,1==_.length)if("string"!=typeof _[0]||_[0].includes("\n")||_[0].includes("\t")){const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_JSON_VALUE_0_${i}_`),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX`),!0)]))]);$&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),b=JSON.stringify(_[0])}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_JSON_VALUE_0_${i}_`),r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX`),!0))]);$&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),b=_[0]}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.arrayPattern(_.map(((e,t)=>r.identifier(`_JSON_VALUE_${t}_${i}_`)))),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX`),!0)]))]);$&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),b=JSON.stringify(_)}else $&&n.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))]));v=c(e).code}return v=(await a.minify(v,{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:!n,keep_fnames:!n})).code||"",null!=b&&(v=u(v,`${t?`//${t}\n`:""}\n//\t${b}\t\n`,getFunctionBodyStart(v)+1),v=v.replace(`$${i}$SPLIT_INDEX`,await minifyNumber(v.split("\t").findIndex((e=>e==b))))),countHackmudCharacters(E)<=countHackmudCharacters(v)+Number(h)&&(v=E,t&&(v=u(v,`//${t}\n`,getFunctionBodyStart(v)+1))),v}function parseObjectExpression(e,t){if(!e.properties.length)return!1;for(const r of e.properties){if("ObjectProperty"!=r.type||r.computed)return!1;if(l("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}function parseArrayExpression(e,t){if(!e.elements.length)return!1;for(const r of e.elements){if(!r)return!1;if("ArrayExpression"==r.type){const e=[];if(!parseArrayExpression(r,e))return!1;e.push(e)}else if("ObjectExpression"==r.type){const e={};if(!parseObjectExpression(r,e))return!1;t.push(e)}else if("NullLiteral"==r.type)t.push(null);else if("BooleanLiteral"==r.type||"NumericLiteral"==r.type||"StringLiteral"==r.type)t.push(r.value);else{if("TemplateLiteral"!=r.type||r.expressions.length)return!1;t.push(r.quasis[0].value.cooked)}}return!0}async function minifyNumber(e){return/\$\((?<number>.+)\)/.exec((await a.minify(`$(${e})`,{ecma:2015})).code).groups.number}function getFunctionBodyStart(e){const t=i(e,{ecmaVersion:2015});t.getToken(),t.getToken(),t.getToken();let r=1;for(;r;){const e=t.getToken();e.type==n.parenL?r++:e.type==n.parenR&&r--}return t.getToken().start}export{countHackmudCharacters as c,minify as default,minify};
1
+ import e from"@babel/generator";import t from"@babel/traverse";import r from"@babel/types";import{tokenizer as i,tokTypes as n}from"acorn";import*as a from"terser";import{getReferencePathsToGlobal as o,includesIllegalString as s,replaceUnsafeStrings as p}from"./shared.js";import{a as l}from"../assert-1556d989.js";import{s as u}from"../spliceString-2c6f214f.js";import{c}from"../countHackmudCharacters-1e122984.js";const{default:f}=e,{default:d}=t;async function minify(e,t,{uniqueID:i="00000000000",mangleNames:n=!1}={}){let m;if(l(/^\w{11}$/.exec(i)),d(e,{Program(e){m=e,e.skip()}}),m.scope.hasGlobal("_START"))for(const e of o("_START",m))e.replaceWith(r.identifier("_ST"));if(m.scope.hasGlobal("_TIMEOUT"))for(const e of o("_TIMEOUT",m))e.replaceWith(r.identifier("_TO"));const y=m.get("body.0");for(const e of[...y.node.params].reverse()){if("Identifier"==e.type){if(!y.scope.getBinding(e.name).referenced){y.node.params.pop();continue}}break}for(const e in m.scope.globals){if("arguments"==e||e.startsWith(`$${i}$`))continue;const t=o(e,m);if(!(5+e.length+t.length>=e.length*t.length)){for(const n of t)n.replaceWith(r.identifier(`_${i}_GLOBAL_${e}_`));y.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_GLOBAL_${e}_`),r.identifier(e))]))}}const _=o(`$${i}$GLOBAL$`,m);if(_.length>3){for(const e of _)e.replaceWith(r.identifier(`_${i}_G_`));y.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_G_`),r.identifier(`$${i}$GLOBAL$`))]))}const $=[];let E=!1;const g=r.cloneNode(e);d(g,{MemberExpression({node:e}){e.computed||(l("Identifier"==e.property.type),"prototype"==e.property.name?(e.computed=!0,e.property=r.identifier(`_${i}_PROTOTYPE_PROPERTY_`)):"__proto__"==e.property.name?(e.computed=!0,e.property=r.identifier(`_${i}_PROTO_PROPERTY_`)):s(e.property.name)&&(e.computed=!0,e.property=r.stringLiteral(p(i,e.property.name))))},ObjectProperty({node:e}){"Identifier"==e.key.type&&s(e.key.name)&&(e.key=r.stringLiteral(p(i,e.key.name)),e.shorthand=!1)},StringLiteral({node:e}){e.value=p(i,e.value)},TemplateLiteral({node:e}){for(const t of e.quasis)t.value.cooked?(t.value.cooked=p(i,t.value.cooked),t.value.raw=t.value.cooked.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"$\\{")):t.value.raw=p(i,t.value.raw)},RegExpLiteral(e){e.node.pattern=p(i,e.node.pattern),delete e.node.extra}});const b=(await a.minify(f(g).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:!n,keep_fnames:!n})).code.replace(new RegExp(`_${i}_PROTOTYPE_PROPERTY_`,"g"),'"prototype"').replace(new RegExp(`_${i}_PROTO_PROPERTY_`,"g"),'"__proto__"');let v,h,x=!1;{const t=[];d(e,{FunctionDeclaration(e){e.traverse({Function(e){"CallExpression"!=e.parent.type&&"callee"!=e.parentKey&&e.skip()},Loop(e){e.skip()},ObjectExpression(e){const t={};parseObjectExpression(e.node,t)&&e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${$.push(t)-1}_`))},ArrayExpression(e){const t=[];parseArrayExpression(e.node,t)&&e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${$.push(t)-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||(l("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(`_${i}_UNDEFINED_`)),E=!0);else if("-"==e.node.operator&&"NumericLiteral"==e.node.argument.type){const n=-e.node.argument.value;t.push((async()=>{if((await minifyNumber(n)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=$.indexOf(n);-1==t&&(t+=$.push(n)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))})()),e.skip()}},NullLiteral(e){let t=$.indexOf(null);-1==t&&(t+=$.push(null)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))},BooleanLiteral(e){let t=$.indexOf(e.node.value);-1==t&&(t+=$.push(e.node.value)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))},NumericLiteral(e){t.push((async()=>{if((await minifyNumber(e.node.value)).length<=3)return;"key"==e.parentKey&&"ObjectProperty"==e.parent.type&&(e.parent.computed=!0);let t=$.indexOf(e.node.value);-1==t&&(t+=$.push(e.node.value)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))})())},StringLiteral(e){if(e.node.value=p(i,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 t=$.indexOf(e.node.value);-1==t&&(t+=$.push(e.node.value)),e.replaceWith(r.identifier(`_${i}_JSON_VALUE_${t}_`))},ObjectProperty({node:e}){if(e.computed||"Identifier"!=e.key.type||e.key.name.length<4)return;let t=$.indexOf(e.key.name);-1==t&&(t+=$.push(e.key.name)),e.computed=!0,e.key=r.identifier(`_${i}_JSON_VALUE_${t}_`)},RegExpLiteral(e){e.node.pattern=p(i,e.node.pattern),delete e.node.extra}}),e.skip()}}),await Promise.all(t);const n=e.program.body[0];if(l("FunctionDeclaration"==n.type),$.length)if(x=!0,1==$.length)if("string"!=typeof $[0]||$[0].includes("\n")||$[0].includes("\t")){const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_JSON_VALUE_0_`),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine$`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX$`),!0)]))]);E&&e.declarations.push(r.variableDeclarator(r.identifier(`_${i}_UNDEFINED_`))),n.body.body.unshift(e),v=JSON.stringify($[0])}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_JSON_VALUE_0_`),r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine$`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX$`),!0))]);E&&e.declarations.push(r.variableDeclarator(r.identifier(`_${i}_UNDEFINED_`))),n.body.body.unshift(e),v=$[0]}else{const e=r.variableDeclaration("let",[r.variableDeclarator(r.arrayPattern($.map(((e,t)=>r.identifier(`_${i}_JSON_VALUE_${t}_`)))),r.callExpression(r.memberExpression(r.identifier("JSON"),r.identifier("parse")),[r.memberExpression(r.taggedTemplateExpression(r.memberExpression(r.callExpression(r.identifier(`$${i}$SUBSCRIPT$scripts$quine$`),[]),r.identifier("split")),r.templateLiteral([r.templateElement({raw:"\t",cooked:"\t"},!0)],[])),r.identifier(`$${i}$SPLIT_INDEX$`),!0)]))]);E&&e.declarations.push(r.variableDeclarator(r.identifier(`_${i}_UNDEFINED_`))),n.body.body.unshift(e),v=JSON.stringify($)}else E&&n.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_${i}_UNDEFINED_`))]));h=f(e).code}return h=(await a.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:!n,keep_fnames:!n})).code||"",null!=v&&(h=u(h,`${t?`//${t}\n`:""}\n//\t${v}\t\n`,getFunctionBodyStart(h)+1),h=h.replace(`$${i}$SPLIT_INDEX$`,await minifyNumber(h.split("\t").findIndex((e=>e==v))))),c(b)<=c(h)+Number(x)&&(h=b,t&&(h=u(h,`//${t}\n`,getFunctionBodyStart(h)+1))),h}function parseObjectExpression(e,t){if(!e.properties.length)return!1;for(const r of e.properties){if("ObjectProperty"!=r.type||r.computed)return!1;if(l("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}function parseArrayExpression(e,t){if(!e.elements.length)return!1;for(const r of e.elements){if(!r)return!1;if("ArrayExpression"==r.type){const e=[];if(!parseArrayExpression(r,e))return!1;e.push(e)}else if("ObjectExpression"==r.type){const e={};if(!parseObjectExpression(r,e))return!1;t.push(e)}else if("NullLiteral"==r.type)t.push(null);else if("BooleanLiteral"==r.type||"NumericLiteral"==r.type||"StringLiteral"==r.type)t.push(r.value);else{if("TemplateLiteral"!=r.type||r.expressions.length)return!1;t.push(r.quasis[0].value.cooked)}}return!0}async function minifyNumber(e){return/\$\((?<number>.+)\)/.exec((await a.minify(`$(${e})`,{ecma:2015})).code).groups.number}function getFunctionBodyStart(e){const t=i(e,{ecmaVersion:2015});t.getToken(),t.getToken(),t.getToken();let r=1;for(;r;){const e=t.getToken();e.type==n.parenL?r++:e.type==n.parenR&&r--}return t.getToken().start}export{minify as default,minify};
@@ -1 +1 @@
1
- function postprocess($,e,p){return $.replace(/^function\s*\w+\(/,"function(").replace(new RegExp(`\\$${p}\\$\\\\\\\\0\\$SC_DOLLAR\\$`,"g"),"SC\\$").replace(new RegExp(`\\$${p}\\$\\\\\\\\0\\$DB_DOLLAR\\$`,"g"),"DB\\$").replace(new RegExp(`\\$${p}\\$\\\\\\\\0\\$D\\$`,"g"),"__D_\\S").replace(new RegExp(`\\$${p}\\$\\\\\\\\0\\$FMCL\\$`,"g"),"__FMCL\\_").replace(new RegExp(`\\$${p}\\$\\\\\\\\0\\$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")}export{postprocess as default,postprocess};
1
+ function postprocess($,e,p){return $.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};
@@ -6,7 +6,7 @@ export declare type PreprocessOptions = {
6
6
  * @param code source code for preprocessing
7
7
  * @param options {@link PreprocessOptions details}
8
8
  */
9
- export declare function preprocess(code: string, { uniqueID }?: Partial<PreprocessOptions>): {
9
+ export declare function preprocess(code: string, { uniqueID }?: Partial<PreprocessOptions>): Promise<{
10
10
  code: string;
11
- };
11
+ }>;
12
12
  export default preprocess;
@@ -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{a as t}from"../assert-1556d989.js";import{s}from"../spliceString-2c6f214f.js";const{default:p}=r,{default:l}=e;function preprocess(e,{uniqueID:r="00000000000"}={}){t(/^\w{11}$/.test(r));const n=e;let c,a,f;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{a=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}var d;if("BABEL_PARSER_SYNTAX_ERROR"!=i.code||"PrivateInExpectedIn"!=i.reasonCode)throw console.log(null===(d=/.+/.exec(e.slice(i.pos)))||void 0===d?void 0:d[0]),i;const p=e.slice(i.pos);let l;if(l=/^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(p))e=s(e,JSON.stringify(n),i.pos,l[0].length);else if(l=/^#[0-4fhmln]?s\./.exec(p))e=s(e,"$",i.pos,1);else if(l=/^#D[^\w$]/.exec(p))e=s(e,"$",i.pos,1);else if(l=/^#FMCL/.exec(p))e=s(e,`$${r}$FMCL`,i.pos,l[0].length);else if(l=/^#G/.exec(p))e=s(e,`$${r}$GLOBAL`,i.pos,l[0].length);else{if(!(l=/^#db\./.exec(p)))throw i;e=s(e,"$",i.pos,1)}}p(a,{Program(e){f=e,e.skip()}});const u=f.scope.hasGlobal("Record"),m=f.scope.hasGlobal("Tuple");return(u||m)&&a.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"))),f.scope.hasGlobal("Proxy")&&a.program.body.unshift(i.importDeclaration([i.importDefaultSpecifier(i.identifier("Proxy"))],i.stringLiteral("proxy-polyfill/src/proxy.js"))),1==f.node.body.length&&"FunctionDeclaration"==f.node.body[0].type?{code:`export default ${l(a).code}`}:{code:l(a).code}}export{preprocess as default,preprocess};
1
+ import e from"@babel/generator";import{parse as o}from"@babel/parser";import r from"@babel/traverse";import i from"@babel/types";import{resolve as t}from"import-meta-resolve";import{a as s}from"../assert-1556d989.js";import{s as p}from"../spliceString-2c6f214f.js";const{default:l}=r,{default:n}=e;async function preprocess(e,{uniqueID:r="00000000000"}={}){s(/^\w{11}$/.test(r));const a=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){s(e instanceof SyntaxError),i=e}var m;if("BABEL_PARSER_SYNTAX_ERROR"!=i.code||"PrivateInExpectedIn"!=i.reasonCode)throw console.log(null===(m=/.+/.exec(e.slice(i.pos)))||void 0===m?void 0:m[0]),i;const t=e.slice(i.pos);let l;if(l=/^#[0-4fhmln]s\.scripts\.quine\(\)/.exec(t))e=p(e,JSON.stringify(a),i.pos,l[0].length);else if(l=/^#[0-4fhmln]?s\./.exec(t))e=p(e,"$",i.pos,1);else if(l=/^#D[^\w$]/.exec(t))e=p(e,"$",i.pos,1);else if(l=/^#FMCL/.exec(t))e=p(e,`$${r}$FMCL$`,i.pos,l[0].length);else if(l=/^#G/.exec(t))e=p(e,`$${r}$GLOBAL$`,i.pos,l[0].length);else{if(!(l=/^#db\./.exec(t)))throw i;e=p(e,"$",i.pos,1)}}l(f,{Program(e){d=e,e.skip()}});const u=d.scope.hasGlobal("Record"),h=d.scope.hasGlobal("Tuple");return(u||h)&&f.program.body.unshift(i.importDeclaration(u?h?[i.importSpecifier(i.identifier("Record"),i.identifier("Record")),i.importSpecifier(i.identifier("Tuple"),i.identifier("Tuple"))]:[i.importSpecifier(i.identifier("Record"),i.identifier("Record"))]:[i.importSpecifier(i.identifier("Tuple"),i.identifier("Tuple"))],i.stringLiteral("@bloomberg/record-tuple-polyfill"))),d.scope.hasGlobal("Proxy")&&f.program.body.unshift(i.importDeclaration([i.importDefaultSpecifier(i.identifier("Proxy"))],i.stringLiteral((await t("proxy-polyfill/src/proxy.js",import.meta.url)).slice(7)))),1==d.node.body.length&&"FunctionDeclaration"==d.node.body[0].type?{code:`export default ${n(f).code}`}:{code:n(f).code}}export{preprocess as default,preprocess};
@@ -2,4 +2,4 @@ import { NodePath } from "@babel/traverse";
2
2
  import t, { Program } from "@babel/types";
3
3
  export declare function getReferencePathsToGlobal(name: string, program: NodePath<Program>): NodePath<t.Identifier>[];
4
4
  export declare function includesIllegalString(toCheck: string): boolean;
5
- export declare function replaceIllegalStrings(uniqueID: string, toReplace: string): string;
5
+ export declare function replaceUnsafeStrings(uniqueID: string, toReplace: string): string;
@@ -1 +1 @@
1
- import e from"@babel/types";import{e as l}from"../assert-1556d989.js";function getReferencePathsToGlobal(r,n){const[a]=n.unshiftContainer("body",e.variableDeclaration("let",[e.variableDeclarator(e.identifier(r))]));n.scope.crawl();const t=l(n.scope.getBinding(r));return a.remove(),t.referencePaths}function includesIllegalString(e){return e.includes("SC$")||e.includes("DB$")||e.includes("__D_S")||e.includes("__FMCL_")||e.includes("__G_")}function replaceIllegalStrings(e,l){return l.replace(/SC\$/g,`$${e}$\\0$SC_DOLLAR$`).replace(/DB\$/g,`$${e}$\\0$DB_DOLLAR$`).replace(/__D_S/g,`$${e}$\\0$D$`).replace(/__FMCL_/g,`$${e}$\\0$FMCL$`).replace(/__G_/g,`$${e}$\\0$G$`)}export{getReferencePathsToGlobal,includesIllegalString,replaceIllegalStrings};
1
+ import e from"@babel/types";import{e as $}from"../assert-1556d989.js";function getReferencePathsToGlobal(r,a){const[l]=a.unshiftContainer("body",e.variableDeclaration("let",[e.variableDeclarator(e.identifier(r))]));a.scope.crawl();const n=$(a.scope.getBinding(r));return l.remove(),n.referencePaths}function includesIllegalString(e){return e.includes("SC$")||e.includes("DB$")||e.includes("__D_S")||e.includes("__FMCL_")||e.includes("__G_")}function replaceUnsafeStrings(e,$){return $.replace(/SC\$/g,`$${e}$\\$SC_DOLLAR$`).replace(/DB\$/g,`$${e}$\\$DB_DOLLAR$`).replace(/__D_S/g,`$${e}$\\$D$`).replace(/__FMCL_/g,`$${e}$\\$FMCL$`).replace(/__G_/g,`$${e}$\\$G$`).replace(/\/\//g,`$${e}$SLASH_SLASH$`).replace(/#[0-4fhmln]?s(?:\.[_a-z][\d_a-z]{0,24}){2}\(/g,`$${e}$NOT_A_SUBSCRIPT$$$&$`).replace(/#db\.(?<methodName>[irfu]|u1|us|ObjectId)\(/g,`$${e}$NOT_A_DB_CALL$$$1$`).replace(/#D\(/g,`$${e}$NOT_A_DEBUG_CALL$`).replace(/#FMCL/g,`$${e}$NOT_FMCL$`).replace(/#G/g,`$${e}$NOT_G$`)}export{getReferencePathsToGlobal,includesIllegalString,replaceUnsafeStrings};
@@ -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";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};
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-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:o}=e,a=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"];function transform(e,s,{uniqueID:p="00000000000",scriptUser:c="UNKNOWN",scriptName:l="UNKNOWN",seclevel:d=4}={}){const f=`_${p}_SCRIPT_`,b=new Map,y=new Map;let m;if(o(e,{Program(e){m=e,e.skip()}}),m.scope.hasGlobal("_SOURCE"))for(const e of r("_SOURCE",m))e.replaceWith(t.stringLiteral(s));if(m.scope.hasGlobal("_BUILD_DATE"))for(const e of r("_BUILD_DATE",m))e.replaceWith(t.numericLiteral(Date.now()));if(m.scope.hasGlobal("_SCRIPT_USER"))for(const e of r("_SCRIPT_USER",m))1==c?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_USER$`)):e.replaceWith(t.stringLiteral(c));if(m.scope.hasGlobal("_SCRIPT_NAME"))for(const e of r("_SCRIPT_NAME",m))1==l?e.replaceWith(t.stringLiteral(`$${p}$SCRIPT_NAME$`)):e.replaceWith(t.stringLiteral(l));if(m.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of r("_FULL_SCRIPT_NAME",m))1==c||1==l?e.replaceWith(t.stringLiteral(`$${p}$FULL_SCRIPT_NAME$`)):e.replaceWith(t.stringLiteral(`${c}.${l}`));let $=!1;if(m.scope.hasGlobal("Function")){const e=r("Function",m);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"),$=!0,i.parentPath.replaceWith(t.identifier(`_${p}_FUNCTION_DOT_PROTOTYPE_`));$=!0}}let h=4;for(const e of["$fs","$4s","$s"])m.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])m.scope.hasGlobal(e)&&(h=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])m.scope.hasGlobal(e)&&(h=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])m.scope.hasGlobal(e)&&(h=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])m.scope.hasGlobal(e)&&(h=0,processFakeSubscriptObject(e));if(d=Math.min(d,h),m.scope.hasGlobal("$db"))for(const e of r("$db",m)){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(m.scope.hasGlobal("$D"))for(const e of r("$D",m))"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(m.scope.hasGlobal("$FMCL"))for(const e of r("$FMCL",m))e.replaceWith(t.identifier(`$${p}$FMCL$`));if(m.scope.hasGlobal("$G"))for(const e of r("$G",m))e.replaceWith(t.identifier(`$${p}$GLOBAL$`));if(m.scope.hasGlobal("_SECLEVEL"))for(const e of r("_SECLEVEL",m))e.replaceWith(t.numericLiteral(d));let _=!1,u=!1;if(m.scope.hasGlobal("Object"))for(const e of r("Object",m))"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=m.node.body[m.node.body.length-1];let O;if(n(P,"program is empty"),"ExportNamedDeclaration"==P.type){m.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?O=e.local.name:b.set(e.local.name,t)}}const x=t.blockStatement([]);let S;for(const e of m.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&&(S=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 S=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?S=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(S||(S=t.functionDeclaration(t.identifier(f),[t.identifier("context"),t.identifier("args")],t.blockStatement([]))),m.node.body=[S],x.body.length){(b.size||y.size)&&S.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))]))))]))),m.scope.crawl();const e=new Set;let i=0;for(const[r,o]of[...x.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}"`),m.scope.crawl(),m.scope.hasGlobal(a.id.name)){x.body.splice(r,1);const[s]=m.unshiftContainer("body",x),[c]=m.unshiftContainer("body",o);if(m.scope.crawl(),!a.init||"FunctionExpression"!=a.init.type&&"ArrowFunctionExpression"!=a.init.type||Object.keys(m.scope.globals).some((t=>e.has(t)))){const e=m.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(),c.remove(),a.init&&x.body.splice(r,0,t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.identifier(`$${p}$GLOBAL$`),t.identifier(a.id.name)),a.init)))}else s.remove(),c.remove(),S.body.body.unshift(o),i++}else e.add(a.id.name)}else if("ClassDeclaration"==o.type&&(m.scope.crawl(),m.scope.hasGlobal(o.id.name))){x.body.splice(r,1);const[e]=m.unshiftContainer("body",x),[i]=m.unshiftContainer("body",o);m.scope.crawl();const a=m.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(),x.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(m.scope.hasGlobal("_EXPORTS"))for(const e of r("_EXPORTS",m))e.replaceWith(t.arrayExpression([...b.keys(),...y.keys()].map((e=>t.stringLiteral(e)))));x.body.length&&S.body.body.splice(i,0,t.ifStatement(t.unaryExpression("!",t.identifier(`$${p}$FMCL$`)),x))}return $&&S.body.body.unshift(t.variableDeclaration("let",[t.variableDeclarator(t.identifier(`_${p}_FUNCTION_DOT_PROTOTYPE_`),createGetFunctionPrototypeNode())])),u&&S.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_`)]))])),_&&S.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)&&S.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};function processFakeSubscriptObject(e){for(const a of r(e,m)){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"))])))}}function createGetFunctionPrototypeNode(){for(const e of a)if(!m.scope.hasOwnBinding(e))return t.memberExpression(t.memberExpression(t.identifier(e),t.identifier("constructor")),t.identifier("prototype"));return t.memberExpression(t.memberExpression(t.arrowFunctionExpression([t.identifier("_")],t.identifier("_")),t.identifier("constructor")),t.identifier("prototype"))}}export{transform as default,transform};
package/push.js CHANGED
@@ -1 +1 @@
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"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./spliceString-2c6f214f.js";import"acorn";import"terser";const{readFile:l,readdir:m}=e.promises;async function push(e,c,{scripts:g=["*.*"],onPush:u=(()=>{}),minify:f=!0,mangleNames:b=!1}={}){const d=new s((e=>new Set)),h=new Set,w=new Set;let $=!1;for(const e of g){const[r,i]=e.split(".");r&&"*"!=r?i&&"*"!=i?d.get(r).add(i):h.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))),...d.keys(),...h]);if($)for(const e of a)h.add(e);else for(const e of a){const r=d.get(e);for(const e of w)r.add(e)}}return await Promise.all([...h].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:d,script:h}=await o(await l(a,{encoding:"utf-8"}),{minify:f,scriptUser:s,scriptName:i,filePath:a,mangleNames:b}),w={file:`${s}/${m.name}`,users:[s],minLength:n(h),error:void 0,srcLength:d};j.get(s).add(i),S.push(w),await p(r(c,s,`scripts/${i}.js`),h),u(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...d].map((async([i,t])=>{h.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:f,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),u(l)}else y.get(t).add(i)})))}))),await(h.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),d=[...h,...y.get(g)].filter((e=>!j.get(e).has(g)));if(!d.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:f,scriptUser:!0,scriptName:g,uniqueID:w,filePath:$,mangleNames:b}),N={file:s.name,users:d,minLength:n(L),error:void 0,srcLength:P};await Promise.all(d.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),u(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:f,scriptUser:!0,scriptName:i,uniqueID:e,filePath:g,mangleNames:b}),d={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(d),u(d)}})))),S}export{push as default,push};
1
+ import e from"fs";import{resolve as i,extname as r,basename as t}from"path";import{s as a}from"./constants-9bb78688.js";import{processScript as o}from"./processScript/index.js";import{D as p,w as s}from"./writeFilePersistent-72dc81a3.js";import{c as n}from"./countHackmudCharacters-1e122984.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"prettier";import"rollup";import"./processScript/minify.js";import"acorn";import"terser";import"./processScript/shared.js";import"./assert-1556d989.js";import"./spliceString-2c6f214f.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"import-meta-resolve";import"./processScript/transform.js";const{readFile:l,readdir:m}=e.promises;async function push(e,c,{scripts:u=["*.*"],onPush:g=(()=>{}),minify:f=!0,mangleNames:b=!1}={}){const d=new p((e=>new Set)),w=new Set,h=new Set;let $=!1;for(const e of u){const[i,r]=e.split(".");i&&"*"!=i?r&&"*"!=r?d.get(i).add(r):w.add(i):r&&"*"!=r?h.add(r):$=!0}const y=new p((e=>new Set)),S=[],j=new p((e=>new Set));let P;if(h.size||$){const t=await m(i(c),{withFileTypes:!0}),a=new Set([...(P=await m(i(e),{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name)),...t.filter((e=>e.isDirectory())).map((e=>e.name)),...t.filter((e=>e.isFile()&&".key"==r(e.name))).map((e=>e.name.slice(0,-4))),...d.keys(),...w]);if($)for(const e of a)w.add(e);else for(const e of a){const i=d.get(e);for(const e of h)i.add(e)}}return await Promise.all([...w].map((async p=>{await m(i(e,p),{withFileTypes:!0}).then((async m=>{await Promise.all(m.map((async m=>{const u=r(m.name);if(m.isFile()&&a.includes(u)){const r=t(m.name,u),a=i(e,p,m.name),{script:d}=await o(await l(a,{encoding:"utf-8"}),{minify:f,scriptUser:p,scriptName:r,filePath:a,mangleNames:b}),w={file:`${p}/${m.name}`,users:[p],minLength:n(d),error:void 0};j.get(p).add(r),S.push(w),await s(i(c,p,`scripts/${r}.js`),d),g(w)}})))}),(e=>{if("ENOENT"!=e.code)throw e}))}))),await Promise.all([...d].map((async([r,t])=>{w.has(r)||await Promise.all([...t].map((async t=>{let p,m,u;for(const o of a)try{m=`${t}${o}`,p=await l(u=i(e,r,m),{encoding:"utf-8"});break}catch{}if(p){const{script:e}=await o(p,{minify:f,scriptUser:r,scriptName:t,filePath:u,mangleNames:b}),a={file:`${r}/${m}`,users:[r],minLength:n(e),error:void 0};S.push(a),await s(i(c,r,"scripts",`${t}.js`),e),g(a)}else y.get(t).add(r)})))}))),await(w.size?Promise.all((P||await m(i(e),{withFileTypes:!0})).map((async p=>{const m=r(p.name);if(!p.isFile()||!a.includes(m))return;const u=t(p.name,m),d=[...w,...y.get(u)].filter((e=>!j.get(e).has(u)));if(!d.length)return;const h=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),$=i(e,p.name),{script:P}=await o(await l($,{encoding:"utf-8"}),{minify:f,scriptUser:!0,scriptName:u,uniqueID:h,filePath:$,mangleNames:b}),N={file:p.name,users:d,minLength:n(P),error:void 0};await Promise.all(d.map((e=>s(i(c,e,`scripts/${u}.js`),P.replace(new RegExp(`\\$${h}\\$SCRIPT_USER\\$`,"g"),e).replace(new RegExp(`\\$${h}\\$FULL_SCRIPT_NAME\\$`,"g"),`${e}.${u}`))))),S.push(N),g(N)}))):Promise.all([...y].map((async([r,t])=>{let p,m,u;for(const t of a)try{m=`${r}${t}`,p=await l(u=i(e,m),{encoding:"utf-8"});break}catch{}if(p){const e=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),{script:a}=await o(p,{minify:f,scriptUser:!0,scriptName:r,uniqueID:e,filePath:u,mangleNames:b}),l={file:m,users:[...t],minLength:n(a),error:void 0};await Promise.all([...t].map((t=>s(i(c,t,`scripts/${r}.js`),a.replace(new RegExp(`\\$${e}\\$SCRIPT_USER\\$`,"g"),t).replace(new RegExp(`\\$${e}\\$FULL_SCRIPT_NAME\\$`,"g"),`${t}.${r}`))))),S.push(l),g(l)}})))),S}export{push as default,push};
package/watch.js CHANGED
@@ -1 +1 @@
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"prettier";import"rollup";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"./spliceString-2c6f214f.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,onReady:j}={}){if(!b.length)throw new Error("scripts option was an empty array");const S=new n((r=>new Set)),L=new Set,v=new Set;let F=!1;for(const r of b){const[o,t]=r.split(".");o&&"*"!=o?t&&"*"!=t?S.get(t).add(o):L.add(o):t&&"*"!=t?v.add(t):F=!0}const $=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(!(F||L.size||v.has(b)||S.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(F||v.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 S.values())for(const o of r)y.add(o)}for(const r of L)y.add(r);for(const r of S.get(b))y.add(r);const j=[...y].filter((r=>!p.has(r)));if(!j.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(j.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:j,minLength:m(T),error:void 0,srcLength:E}))}const y=i(e(r,".."));if(!(F||L.size||v.has(b)||S.get(b).has(y)))return;const j=e(o,r),$=await u(j,{encoding:"utf-8"});let P,E;try{({srcLength:P,script:E}=await a($,{minify:h,scriptUser:y,scriptName:b,filePath:j,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})}));j&&$.on("ready",j),y&&(p(o,e(o,y),f),$.on("add",(()=>p(o,e(o,y),f))),$.on("unlink",(()=>p(o,e(o,y),f))))}export{watch as default,watch};
1
+ import{watch as r}from"chokidar";import o from"fs";import{extname as i,basename as t,resolve as e}from"path";import{s}from"./constants-9bb78688.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"./countHackmudCharacters-1e122984.js";import"@babel/generator";import"@babel/parser";import"@babel/plugin-proposal-class-properties";import"@babel/plugin-proposal-class-static-block";import"@babel/plugin-proposal-decorators";import"@babel/plugin-proposal-do-expressions";import"@babel/plugin-proposal-function-bind";import"@babel/plugin-proposal-function-sent";import"@babel/plugin-proposal-json-strings";import"@babel/plugin-proposal-logical-assignment-operators";import"@babel/plugin-proposal-nullish-coalescing-operator";import"@babel/plugin-proposal-numeric-separator";import"@babel/plugin-proposal-object-rest-spread";import"@babel/plugin-proposal-optional-catch-binding";import"@babel/plugin-proposal-optional-chaining";import"@babel/plugin-proposal-partial-application";import"@babel/plugin-proposal-pipeline-operator";import"@babel/plugin-proposal-private-property-in-object";import"@babel/plugin-proposal-record-and-tuple";import"@babel/plugin-proposal-throw-expressions";import"@babel/plugin-transform-exponentiation-operator";import"@babel/plugin-transform-typescript";import"@babel/traverse";import"@babel/types";import"@rollup/plugin-babel";import"@rollup/plugin-commonjs";import"@rollup/plugin-json";import"@rollup/plugin-node-resolve";import"prettier";import"rollup";import"./processScript/minify.js";import"acorn";import"terser";import"./processScript/shared.js";import"./spliceString-2c6f214f.js";import"./processScript/postprocess.js";import"./processScript/preprocess.js";import"import-meta-resolve";import"./processScript/transform.js";const{readFile:u,readdir:f}=o.promises;function watch(o,b,{scripts:d=["*.*"],onPush:g,minify:h=!0,mangleNames:w=!1,typeDeclarationPath:y,onReady:j}={}){if(!d.length)throw new Error("scripts option was an empty array");const S=new n((r=>new Set)),$=new Set,v=new Set;let F=!1;for(const r of d){const[o,i]=r.split(".");o&&"*"!=o?i&&"*"!=i?S.get(i).add(o):$.add(o):i&&"*"!=i?v.add(i):F=!0}const P=r("",{depth:1,cwd:o,awaitWriteFinish:{stabilityThreshold:100}}).on("change",(async r=>{const p=i(r);if(!s.includes(p))return;const d=t(r,p);if(r==t(r)){if(!(F||$.size||v.has(d)||S.has(d)))return;const p=new n((r=>[]));await Promise.all((await f(o,{withFileTypes:!0})).map((async r=>{if(r.isDirectory())for(const a of await f(e(o,r.name),{withFileTypes:!0})){if(!a.isFile())continue;const o=i(a.name);s.includes(o)&&p.get(t(a.name,o)).push(r.name)}})));const y=new Set;if(F||v.has(d)){for(const r of await f(e(o),{withFileTypes:!0}))r.isDirectory()&&y.add(r.name);for(const r of await f(e(b),{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 S.values())for(const o of r)y.add(o)}for(const r of $)y.add(r);for(const r of S.get(d))y.add(r);const j=[...y].filter((r=>!p.has(r)));if(!j.length)return void(null==g||g({file:r,users:[],minLength:0,error:new Error("no users to push to")}));const P=Math.floor(Math.random()*2**52).toString(36).padStart(11,"0"),E=e(o,r);let T;try{({script:T}=await a(await u(E,{encoding:"utf-8"}),{minify:h,scriptUser:!0,scriptName:d,uniqueID:P,filePath:E,mangleNames:w}))}catch(o){return c(o instanceof Error),void(null==g||g({file:r,users:[],minLength:0,error:o}))}return await Promise.all(j.map((r=>l(e(b,r,`scripts/${d}.js`),T.replace(new RegExp(`\\$${P}\\$SCRIPT_USER\\$`,"g"),r).replace(new RegExp(`\\$${P}\\$FULL_SCRIPT_NAME\\$`,"g"),`${r}.${d}`))))),void(null==g||g({file:r,users:j,minLength:m(T),error:void 0}))}const y=t(e(r,".."));if(!(F||$.size||v.has(d)||S.get(d).has(y)))return;const j=e(o,r),P=await u(j,{encoding:"utf-8"});let E;try{({script:E}=await a(P,{minify:h,scriptUser:y,scriptName:d,filePath:j,mangleNames:w}))}catch(o){return c(o instanceof Error),void(null==g||g({file:r,users:[],minLength:0,error:o}))}await l(e(b,y,"scripts",`${d}.js`),E),null==g||g({file:r,users:[y],minLength:m(E),error:void 0})}));j&&P.on("ready",j),y&&(p(o,e(o,y),b),P.on("add",(()=>p(o,e(o,y),b))),P.on("unlink",(()=>p(o,e(o,y),b))))}export{watch as default,watch};