hackmud-script-manager 0.15.0-65d6e88 → 0.15.0-dc021ad
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 e from"chalk";import{watch as o}from"chokidar";import s from"fs";import{homedir as t}from"os";import{resolve as n,basename as a,extname as c,dirname as i,relative as r}from"path";import{s as l}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 d}from"../countHackmudCharacters-1e122984.js";const{readFile:u,rmdir:b,writeFile:k,mkdir:w}=s.promises,y=n(t(),".config"),$=n(y,"hsm.json"),v=new Map,j=[];let P;const C=e.rgb(255,244,4),S=e.rgb(243,249,152),N=e.rgb(179,255,155),x=e.rgb(255,150,224),F=e.rgb(30,255,0),O=e.rgb(202,202,202),L=new g((e=>{let o=0;for(const s of e)o+=(o>>1)+o+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[C,S,N,x,F,O][o%6](e)}));for(const e of process.argv.slice(2))if("-"==e[0]){const[o,s]=e.split("=");let t=s;if(t)if("true"==t)t=!0;else if("false"==t)t=!1;else{const e=Number(t);isFinite(e)&&(t=e)}else t=!0;if("-"==e[1])v.set(o.slice(2),t);else for(const e of o.slice(1))v.set(e,t)}else j.push(e);function help(){switch(j[0]){case"config":switch(j[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 ${j[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])} ${j[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.15.0-
|
2
|
+
import e from"chalk";import{watch as o}from"chokidar";import s from"fs";import{homedir as t}from"os";import{resolve as n,basename as a,extname as c,dirname as i,relative as r}from"path";import{s as l}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 d}from"../countHackmudCharacters-1e122984.js";const{readFile:u,rmdir:b,writeFile:k,mkdir:w}=s.promises,y=n(t(),".config"),$=n(y,"hsm.json"),v=new Map,j=[];let P;const C=e.rgb(255,244,4),S=e.rgb(243,249,152),N=e.rgb(179,255,155),x=e.rgb(255,150,224),F=e.rgb(30,255,0),O=e.rgb(202,202,202),L=new g((e=>{let o=0;for(const s of e)o+=(o>>1)+o+"xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(s)+1;return[C,S,N,x,F,O][o%6](e)}));for(const e of process.argv.slice(2))if("-"==e[0]){const[o,s]=e.split("=");let t=s;if(t)if("true"==t)t=!0;else if("false"==t)t=!1;else{const e=Number(t);isFinite(e)&&(t=e)}else t=!0;if("-"==e[1])v.set(o.slice(2),t);else for(const e of o.slice(1))v.set(e,t)}else j.push(e);function help(){switch(j[0]){case"config":switch(j[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 ${j[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])} ${j[0]} <target> [output]`);break;default:console.log("hsm <push, watch, pull, config, golf>")}}function version(){console.log("0.15.0-dc021ad")}async function getConfig(){return P||(P=await u($,{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 n of o){var t;e=s?"object"==typeof e[n]?e[n]:e[n]={}:null===(t=e)||void 0===t?void 0:t[n]}return e}function updateConfig(){if(P){const e=JSON.stringify(P,void 0,"\t");k($,e).catch((async o=>{switch(o.code){case"EISDIR":await b($);break;case"ENOENT":await w(y);break;default:throw o}k($,e)}))}}function onPushLogger({file:o,users:s,srcLength:t,minLength:i,error:r}){r?console.log(`error "${e.bold(r.message)}" in ${e.bold(o)}`):console.log(`pushed ${e.bold(o)} to ${s.map((o=>e.bold(L.get(o)))).join(", ")} | ${e.bold(String(i))} chars from ${e.bold(String(t))} | saved ${e.bold(String(t-i))} (${e.bold(`${Math.round(100*(1-i/t))}%`)}) | ${e.bold(`${n(P.hackmudPath,s[0],"scripts",a(o,c(o)))}.js`)}`)}(async()=>{if(v.get("version")||v.get("v"))version();else if(v.get("help")||v.get("h"))help();else{switch(j[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=j[1];if(!s){console.error("specify the directory to watch"),help();break}const t=o.hackmudPath,n=j.slice(2);n.length||n.push("*.*");(await e(s,t,{scripts:n,onPush:onPushLogger,minify:!v.get("skip-minify")})).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(!j[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 t=j.slice(2);t.length||t.push("*.*"),v.has("skip-minify")&&v.has("mangle-names")&&console.warn("pointless specifying both --skip-minify and --mangle-names"),e(j[1],o.hackmudPath,{scripts:t,onPush:onPushLogger,typeDeclarationPath:null===(s=v.get("type-declaration-path"))||void 0===s?void 0:s.toString(),minify:!v.get("skip-minify"),mangleNames:Boolean(v.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=j[1];if(!o){help();break}const s=j[2]||".",t=e.hackmudPath;try{await p(s,t,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=n(j[1]||".");h(e,j[2]?n(j[2]):n(e,"../player.d.ts"),(await getConfig()).hackmudPath)}break;case"config":switch(j[1]){case"get":j[2]?console.log(exploreObject(await getConfig(),j[2].split("."))):console.log(await getConfig());break;case"delete":if(j[2]){var t;const e=j[2].split("."),o=e.pop();if(!e.length){help();break}const s=await getConfig();null===(t=exploreObject(s,e))||void 0===t||delete t[o],console.log(s)}else console.log("Usage:\nhsm config delete <key>");break;case"set":if(j[2]&&j[3]){const e=j[2].split(".");if(!e.length){help();break}const o=e.pop(),s=await getConfig();if(e.length||"hackmudPath"!=o){let t=s;for(const o of e)"object"==typeof t[o]||(t[o]={}),t=t[o];t[o]=j[3]}else s.hackmudPath=n(j[3]);console.log(s)}else console.log("Usage:\nhsm config set <key> <value>");break;default:j[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=j[1];if(!s){console.log(`Target required\nUsage: ${a(process.argv[1])} ${j[0]} <target> [output]`);break}const t=c(s);if(!l.includes(t)){console.log(`Unsupported file extension "${e.bold(t)}"\nSupported extensions are "${l.map((o=>e.bold(o))).join('", "')}"`);break}v.get("watch")?o(s,{awaitWriteFinish:{stabilityThreshold:100}}).on("ready",(()=>console.log(`watching ${s}`))).on("change",(()=>golfFile(s,t))):await golfFile(s,t)}break;default:j[0]&&console.log("unknown command"),help()}updateConfig()}async function golfFile(o,s){const{processScript:t}=await import("../processScript/index.js");await u(o,{encoding:"utf-8"}).then((async c=>{const l=a(o,s),g=l.endsWith(".src"),h=g?l.slice(0,-4):l;let m="UNKNOWN";"scripts"==a(n(o,".."))&&"hackmud"==a(n(o,"../../.."))&&(m=a(n(o,"../..")));const p=!v.get("skip-minify"),u=Boolean(v.get("mangle-names"));!p&&u&&console.warn("warning: `--mangle-names` has no effect while `--skip-minify` is active");const b=performance.now(),{script:k,srcLength:w,warnings:y}=await t(c,{minify:p,scriptUser:m,scriptName:h,filePath:o,mangleNames:u}),$=performance.now()-b;for(const{message:o,line:s}of y)console.log(`warning "${e.bold(o)}" on line ${e.bold(String(s))}`);let P;P=j[2]?j[2]:n(i(o),g?`${h}.js`:".js"==s?`${l}.min.js`:`${l}.js`);const C=d(k);await f(P,k).catch((async e=>{if(!j[2]||"EISDIR"!=e.code)throw e;P=n(P,`${a(o,s)}.js`),await f(P,k)})).then((()=>console.log(`wrote ${e.bold(C)} chars to ${e.bold(r(".",P))} | saved ${e.bold(w-C)} chars | took ${Math.round(100*$)/100}ms`)),(e=>console.log(e.message)))}),(e=>console.log(e.message)))}})();
|
package/package.json
CHANGED
package/processScript/index.js
CHANGED
@@ -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
|
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 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{c as W}from"../countHackmudCharacters-1e122984.js";import"acorn";import"terser";import"../spliceString-2c6f214f.js";import"import-meta-resolve";const{default:H}=S,{format:T}=N,{default:F}=e,{default:K}=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:z="UNKNOWN",filePath:A,mangleNames:B=!1}={}){V(/^\w{11}$/.exec(S));const G=e;let R,J;const Q=/^function\s*\(.+\/\/(?<autocomplete>.+)/.exec(e);if(Q)e=`export default ${e}`,({autocomplete:R}=Q.groups);else for(const r of e.split("\n")){const e=/^\s*\/\/(?<commentContent>.+)/.exec(r);if(!e)break;const o=e.groups.commentContent.trim();if(o.startsWith("@autocomplete "))R=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":J=4;break;case"highsec":case"high":case"hs":case"3s":case"h":case"3":J=3;break;case"midsec":case"mid":case"ms":case"2s":case"m":case"2":J=2;break;case"lowsec":case"low":case"ls":case"1s":case"l":case"1":J=1;break;case"nullsec":case"null":case"ns":case"0s":case"n":case"0":J=0;break;default:throw new Error(`unrecognised seclevel "${e}"`)}}}V(/^\w{11}$/.exec(S));const X=A?C(A):`${S}.ts`,Y=await I({input:X,plugins:[{name:"hackmud-script-manager",transform:async e=>(await M(e,{uniqueID:S})).code},H({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}=q(r(e,{sourceType:"module"}),G,{uniqueID:S,scriptUser:N,scriptName:z});if(null!=J&&re<J)throw new Error(`detected seclevel ${Z[re]} is lower than stated seclevel ${Z[J]}`);e=F(ee).code;const oe=W(e.replace(/^function\s*\w+\(/,"function("));if(x?e=await D(ee,R,{uniqueID:S,mangleNames:B}):(K(ee,{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).replace(/\\/g,"\\\\").replace(/\//g,"\\/"),delete e.node.extra}}),e=T(F(ee,{comments:!1}).code,{parser:"babel",arrowParens:"avoid",semi:!1,trailingComma:"none"})),e=P(e,re,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{srcLength:oe,script:e,warnings:[]}}export{processScript as default,processScript};
|
package/processScript/minify.js
CHANGED
@@ -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,
|
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:d}=e,{default:f}=t;async function minify(e,t,{uniqueID:i="00000000000",mangleNames:n=!1}={}){let m;l(/^\w{11}$/.exec(i)),f(e,{Program(e){m=e,e.skip()}});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(`_GLOBAL_${e}_${i}_`));y.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_GLOBAL_${e}_${i}_`),r.identifier(e))]))}}const _=o(`$${i}$GLOBAL`,m);if(_.length>3){for(const e of _)e.replaceWith(r.identifier(`_G_${i}_`));y.node.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_G_${i}_`),r.identifier(`$${i}$GLOBAL`))]))}const $=[];let g=!1;const E=r.cloneNode(e);f(E,{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)},RegExpLiteral(e){e.node.pattern=p(i,e.node.pattern).replace(/\\/g,"\\\\").replace(/\//g,"\\/"),delete e.node.extra}});const b=(await a.minify(d(E).code,{ecma:2015,compress:{passes:1/0,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,unsafe_symbols:!0,unsafe_methods:!0,unsafe_proto:!0,unsafe_regexp:!0,unsafe_undefined:!0,sequences:!1},format:{semicolons:!1},keep_classnames:!n,keep_fnames:!n})).code.replace(new RegExp(`_PROTOTYPE_PROPERTY_${i}_`,"g"),'"prototype"').replace(new RegExp(`_PROTO_PROPERTY_${i}_`,"g"),'"__proto__"');let v,h,x=!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){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(`_UNDEFINED_${i}_`)),g=!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}_`)},RegExpLiteral(e){e.node.pattern=p(i,e.node.pattern).replace(/\\/g,"\\\\").replace(/\//g,"\\/"),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(`_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)]))]);g&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),v=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))]);g&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),v=$[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)]))]);g&&e.declarations.push(r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))),n.body.body.unshift(e),v=JSON.stringify($)}else g&&n.body.body.unshift(r.variableDeclaration("let",[r.variableDeclarator(r.identifier(`_UNDEFINED_${i}_`))]));h=d(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}
|
1
|
+
function postprocess($,e,p){return $.replace(/^function\s*\w+\(/,"function(").replace(new RegExp(`\\$${p}\\$\\\\\\\\\\$SC_DOLLAR\\$`,"g"),"SC\\$").replace(new RegExp(`\\$${p}\\$\\\\\\\\\\$DB_DOLLAR\\$`,"g"),"DB\\$").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"),"#FMC\\L").replace(new RegExp(`\\$${p}\\$NOT_G\\$`,"g"),"#\\G")}export{postprocess as default,postprocess};
|
@@ -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
|
5
|
+
export declare function replaceUnsafeStrings(uniqueID: string, toReplace: string): string;
|
package/processScript/shared.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
import e from"@babel/types";import{e as
|
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};
|