hackmud-script-manager 0.19.0-fa82f73 → 0.19.1-003b022

Sign up to get free protection for your applications and to get access to all the features.
@@ -1 +1,661 @@
1
- import e from"@babel/traverse";import i from"@babel/types";import{assert as t}from"@samual/lib/assert";import{clearObject as r}from"@samual/lib/clearObject";import{validDBMethods as n}from"../constants.js";import{getReferencePathsToGlobal as o}from"./shared.js";const{default:a}=e,s=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"],transform=(e,p,{uniqueID:l="00000000000",scriptUser:c="UNKNOWN",scriptName:d="UNKNOWN",seclevel:f=4}={})=>{const b=`_${l}_SCRIPT_`,y=new Map,m=new Map;let $;if(a(e,{Program(e){$=e,e.skip()}}),$.scope.hasGlobal("_SOURCE"))for(const e of o("_SOURCE",$))e.replaceWith(i.stringLiteral(p));if($.scope.hasGlobal("_BUILD_DATE"))for(const e of o("_BUILD_DATE",$))e.replaceWith(i.numericLiteral(Date.now()));if($.scope.hasGlobal("_SCRIPT_USER"))for(const e of o("_SCRIPT_USER",$))1==c?e.replaceWith(i.stringLiteral(`$${l}$SCRIPT_USER$`)):e.replaceWith(i.stringLiteral(c));if($.scope.hasGlobal("_SCRIPT_NAME"))for(const e of o("_SCRIPT_NAME",$))1==d?e.replaceWith(i.stringLiteral(`$${l}$SCRIPT_NAME$`)):e.replaceWith(i.stringLiteral(d));if($.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of o("_FULL_SCRIPT_NAME",$))1==c||1==d?e.replaceWith(i.stringLiteral(`$${l}$FULL_SCRIPT_NAME$`)):e.replaceWith(i.stringLiteral(`${c}.${d}`));let h=!1;const createGetFunctionPrototypeNode=()=>{for(const e of s)if(!$.scope.hasOwnBinding(e))return i.memberExpression(i.memberExpression(i.identifier(e),i.identifier("constructor")),i.identifier("prototype"));return i.memberExpression(i.memberExpression(i.arrowFunctionExpression([i.identifier("_")],i.identifier("_")),i.identifier("constructor")),i.identifier("prototype"))};if($.scope.hasGlobal("Function")){const e=o("Function",$);if(1==e.length){const i=e[0];t("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),i.parentPath.replaceWith(createGetFunctionPrototypeNode())}else{for(const r of e)t("MemberExpression"==r.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("Identifier"==r.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("prototype"==r.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),h=!0,r.parentPath.replaceWith(i.identifier(`_${l}_FUNCTION_DOT_PROTOTYPE_`));h=!0}}let E=4;const processFakeSubscriptObject=e=>{for(const r of o(e,$))t("MemberExpression"==r.parent.type),t("Identifier"==r.parent.property.type),t("MemberExpression"==r.parentPath.parentPath?.node.type),t("Identifier"==r.parentPath.parentPath.node.property.type),t(/^[_a-z][\d_a-z]{0,24}$/.test(r.parent.property.name),`invalid user "${r.parent.property.name}" in subscript`),t(/^[_a-z][\d_a-z]{0,24}$/.test(r.parentPath.parentPath.node.property.name),`invalid script name "${r.parentPath.parentPath.node.property.name}" in subscript`),"CallExpression"==r.parentPath.parentPath.parentPath?.type?r.parentPath.parentPath.replaceWith(i.identifier(`$${l}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}$`)):r.parentPath.parentPath.replaceWith(i.arrowFunctionExpression([i.restElement(i.identifier("args"))],i.callExpression(i.identifier(`$${l}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}$`),[i.spreadElement(i.identifier("args"))])))};for(const e of["$fs","$4s","$s"])$.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])$.scope.hasGlobal(e)&&(E=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])$.scope.hasGlobal(e)&&(E=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])$.scope.hasGlobal(e)&&(E=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])$.scope.hasGlobal(e)&&(E=0,processFakeSubscriptObject(e));if(f=Math.min(f,E),$.scope.hasGlobal("$db"))for(const e of o("$db",$)){t("MemberExpression"==e.parentPath.node.type),t("Identifier"==e.parentPath.node.property.type);const r=e.parentPath.node.property.name;t(n.includes(r),`invalid db method "${r}", valid db methods are "${n.join('", "')}"`),"CallExpression"==e.parentPath.parentPath?.type?e.parentPath.replaceWith(i.identifier(`$${l}$DB$${r}$`)):"ObjectId"==r?e.parentPath.replaceWith(i.arrowFunctionExpression([],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[]))):"i"==r||"r"==r?e.parentPath.replaceWith(i.arrowFunctionExpression([i.identifier("a")],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[i.identifier("a")]))):e.parentPath.replaceWith(i.arrowFunctionExpression([i.identifier("a"),i.identifier("b")],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[i.identifier("a"),i.identifier("b")])))}if($.scope.hasGlobal("$D"))for(const e of o("$D",$))"CallExpression"==e.parentPath.type?e.replaceWith(i.identifier(`$${l}$DEBUG$`)):e.replaceWith(i.arrowFunctionExpression([i.identifier("a")],i.callExpression(i.identifier(`$${l}$DEBUG$`),[i.identifier("a")])));if($.scope.hasGlobal("$FMCL"))for(const e of o("$FMCL",$))e.replaceWith(i.identifier(`$${l}$FMCL$`));if($.scope.hasGlobal("$G"))for(const e of o("$G",$))e.replaceWith(i.identifier(`$${l}$GLOBAL$`));if($.scope.hasGlobal("_SECLEVEL"))for(const e of o("_SECLEVEL",$))e.replaceWith(i.numericLiteral(f));let _=!1,u=!1;if($.scope.hasGlobal("Object"))for(const e of o("Object",$))"MemberExpression"!=e.parent.type||e.parent.computed||(t("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(i.identifier(`_${l}_GET_PROTOTYPE_OF_`)),_=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(i.identifier(`_${l}_SET_PROTOTYPE_OF_`)),u=!0));const P=$.node.body.at(-1);let x;if(t(P,"program is empty"),"ExportNamedDeclaration"==P.type){$.node.body.pop();for(const e of P.specifiers){t("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const i="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==i?x=e.local.name:y.set(e.local.name,i)}}const O=i.blockStatement([]);let D;for(const e of $.node.body)if("VariableDeclaration"==e.type)for(const t of e.declarations)if("Identifier"!=t.id.type||t.id.name!=x||!t.init||"FunctionExpression"!=t.init.type&&"ArrowFunctionExpression"!=t.init.type||t.init.async||t.init.generator){for(const r in i.getBindingIdentifiers(t.id))r==x&&(D=i.functionDeclaration(i.identifier(b),[i.identifier("context"),i.identifier("args")],i.blockStatement([i.returnStatement(i.callExpression(i.identifier(x),[]))]))),"const"!=e.kind&&y.has(r)&&(m.set(r,y.get(r)),y.delete(r)),O.body.push(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(r))]));t.init&&O.body.push(i.expressionStatement(i.assignmentExpression("=",t.id,t.init)))}else D=i.functionDeclaration(i.identifier(b),t.init.params,"BlockStatement"==t.init.body.type?t.init.body:i.blockStatement([i.returnStatement(t.init.body)]));else"FunctionDeclaration"==e.type?e.id.name==x?D=e:O.body.push(i.variableDeclaration("let",[i.variableDeclarator(e.id,i.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):O.body.push(e);if(D||=i.functionDeclaration(i.identifier(b),[i.identifier("context"),i.identifier("args")],i.blockStatement([])),$.node.body=[D],O.body.length){(y.size||m.size)&&D.body.body.push(i.returnStatement(i.objectExpression([...[...y].map((([e,t])=>i.objectProperty(i.identifier(t),i.identifier(e)))),...[...m].map((([e,t])=>i.objectMethod("get",i.identifier(t),[],i.blockStatement([i.returnStatement(i.identifier(e))]))))]))),$.scope.crawl();const e=new Set;let n=0;for(const[o,a]of[...O.body.entries()].reverse())if("VariableDeclaration"==a.type){t(1==a.declarations.length);const s=a.declarations[0];if(t("Identifier"==s.id.type,`declarator.id.type was "${s.id.type}"`),$.scope.crawl(),$.scope.hasGlobal(s.id.name)){O.body.splice(o,1);const[p]=$.unshiftContainer("body",O),[c]=$.unshiftContainer("body",a);if($.scope.crawl(),!s.init||"FunctionExpression"!=s.init.type&&"ArrowFunctionExpression"!=s.init.type||Object.keys($.scope.globals).some((i=>e.has(i)))){const e=$.scope.getBinding(s.id.name);t(e);for(const r of e.referencePaths)t("Identifier"==r.node.type),r.replaceWith(i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(r.node.name)));for(const t of e.constantViolations)if("AssignmentExpression"==t.node.type)for(const[e,n]of Object.entries(i.getBindingIdentifiers(t.node)))e==s.id.name&&(r(n),Object.assign(n,i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(e))));p.remove(),c.remove(),s.init&&O.body.splice(o,0,i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(s.id.name)),s.init)))}else p.remove(),c.remove(),D.body.body.unshift(a),n++}else e.add(s.id.name)}else if("ClassDeclaration"==a.type&&($.scope.crawl(),t(a.id,"src/processScript/transform.ts:564:37"),$.scope.hasGlobal(a.id.name))){O.body.splice(o,1);const[e]=$.unshiftContainer("body",O),[r]=$.unshiftContainer("body",a);$.scope.crawl();const n=$.scope.getBinding(a.id.name);t(n);for(const e of n.referencePaths)t("Identifier"==e.node.type),e.replaceWith(i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(e.node.name)));e.remove(),r.remove(),O.body.splice(o,0,i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(a.id.name)),i.classExpression(void 0,a.superClass,a.body,a.decorators))))}if($.scope.hasGlobal("_EXPORTS"))for(const e of o("_EXPORTS",$))e.replaceWith(i.arrayExpression([...y.keys(),...m.keys()].map((e=>i.stringLiteral(e)))));O.body.length&&D.body.body.splice(n,0,i.ifStatement(i.unaryExpression("!",i.identifier(`$${l}$FMCL$`)),O))}return h&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_FUNCTION_DOT_PROTOTYPE_`),createGetFunctionPrototypeNode())])),u&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_SET_PROTOTYPE_OF_`),i.callExpression(i.memberExpression(i.memberExpression(i.identifier("Object"),i.identifier("call")),i.identifier("bind")),[i.identifier(`_${l}_DUNDER_PROTO_SETTER_`)]))])),_&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_GET_PROTOTYPE_OF_`),i.callExpression(i.memberExpression(i.memberExpression(i.identifier("Object"),i.identifier("call")),i.identifier("bind")),[i.identifier(`_${l}_DUNDER_PROTO_GETTER_`)]))])),(_||u)&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.objectPattern(_?u?[i.objectProperty(i.identifier("get"),i.identifier(`_${l}_DUNDER_PROTO_GETTER_`)),i.objectProperty(i.identifier("set"),i.identifier(`_${l}_DUNDER_PROTO_SETTER_`))]:[i.objectProperty(i.identifier("get"),i.identifier(`_${l}_DUNDER_PROTO_GETTER_`))]:[i.objectProperty(i.identifier("set"),i.identifier(`_${l}_DUNDER_PROTO_SETTER_`))]),i.callExpression(i.memberExpression(i.identifier("Object"),i.identifier("getOwnPropertyDescriptor")),[i.memberExpression(i.identifier("Object"),i.identifier("prototype")),i.stringLiteral("__proto__")]))])),a(e,{BlockStatement({node:e}){for(const[t,r]of e.body.entries())"FunctionDeclaration"!=r.type||r.generator||(e.body.splice(t,1),e.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(r.id,i.arrowFunctionExpression(r.params,r.body,r.async))])))},ClassBody({node:e,scope:r,parent:n}){t(i.isClass(n));let o=!1;for(const t of e.body){if("ClassMethod"!=t.type)continue;let e=!1;if(a(t.body,{ThisExpression(t){e=!0,o=!0,t.replaceWith(i.identifier(`_${l}_THIS_`))},Function(e){e.skip()}},r),e)if("constructor"!=t.kind)t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),i.callExpression(i.memberExpression(i.super(),i.identifier("valueOf")),[]))]));else{const e=[];if(a(t.body,{CallExpression(i){"Super"==i.node.callee.type&&e.push(i)}},r),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==t)e[0].parentPath.replaceWith(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),e[0].node)]));else{for(const t of e)t.replaceWith(i.assignmentExpression("=",i.identifier(`_${l}_THIS_`),t.node));t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`))]))}else t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),i.callExpression(i.super(),[]))]))}}!n.superClass&&o&&(n.superClass=i.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(i.identifier("undefined"))},BigIntLiteral(e){const t=Number(e.node.value);BigInt(t)==BigInt(e.node.value)?e.replaceWith(i.callExpression(i.identifier("BigInt"),[i.numericLiteral(t)])):e.replaceWith(i.callExpression(i.identifier("BigInt"),[i.stringLiteral(e.node.value)]))}}),{file:e,seclevel:f}};export{transform as default,transform};
1
+ import babelTraverse from "@babel/traverse"
2
+ import t from "@babel/types"
3
+ import { assert } from "@samual/lib/assert"
4
+ import { clearObject } from "@samual/lib/clearObject"
5
+ import { validDBMethods } from "../constants.js"
6
+ import { getReferencePathsToGlobal } from "./shared.js"
7
+ const { default: traverse } = babelTraverse,
8
+ globalFunctionsUnder7Characters = [
9
+ "Map",
10
+ "Set",
11
+ "Date",
12
+ "JSON",
13
+ "Math",
14
+ "Array",
15
+ "Error",
16
+ "isNaN",
17
+ "Number",
18
+ "Object",
19
+ "RegExp",
20
+ "String",
21
+ "Symbol",
22
+ "BigInt"
23
+ ],
24
+ transform = (
25
+ file,
26
+ sourceCode,
27
+ { uniqueID = "00000000000", scriptUser = "UNKNOWN", scriptName = "UNKNOWN", seclevel = 4 } = {}
28
+ ) => {
29
+ const topFunctionName = `_${uniqueID}_SCRIPT_`,
30
+ exports = new Map(),
31
+ liveExports = new Map()
32
+ let program
33
+ traverse(file, {
34
+ Program(path) {
35
+ program = path
36
+ path.skip()
37
+ }
38
+ })
39
+ if (program.scope.hasGlobal("_SOURCE"))
40
+ for (const referencePath of getReferencePathsToGlobal("_SOURCE", program))
41
+ referencePath.replaceWith(t.stringLiteral(sourceCode))
42
+ if (program.scope.hasGlobal("_BUILD_DATE"))
43
+ for (const referencePath of getReferencePathsToGlobal("_BUILD_DATE", program))
44
+ referencePath.replaceWith(t.numericLiteral(Date.now()))
45
+ if (program.scope.hasGlobal("_SCRIPT_USER"))
46
+ for (const referencePath of getReferencePathsToGlobal("_SCRIPT_USER", program))
47
+ 1 == scriptUser ?
48
+ referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$SCRIPT_USER$`))
49
+ : referencePath.replaceWith(t.stringLiteral(scriptUser))
50
+ if (program.scope.hasGlobal("_SCRIPT_NAME"))
51
+ for (const referencePath of getReferencePathsToGlobal("_SCRIPT_NAME", program))
52
+ 1 == scriptName ?
53
+ referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$SCRIPT_NAME$`))
54
+ : referencePath.replaceWith(t.stringLiteral(scriptName))
55
+ if (program.scope.hasGlobal("_FULL_SCRIPT_NAME"))
56
+ for (const referencePath of getReferencePathsToGlobal("_FULL_SCRIPT_NAME", program))
57
+ 1 == scriptUser || 1 == scriptName ?
58
+ referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$FULL_SCRIPT_NAME$`))
59
+ : referencePath.replaceWith(t.stringLiteral(`${scriptUser}.${scriptName}`))
60
+ let functionDotPrototypeIsReferencedMultipleTimes = !1
61
+ const createGetFunctionPrototypeNode = () => {
62
+ for (const globalFunction of globalFunctionsUnder7Characters)
63
+ if (!program.scope.hasOwnBinding(globalFunction))
64
+ return t.memberExpression(
65
+ t.memberExpression(t.identifier(globalFunction), t.identifier("constructor")),
66
+ t.identifier("prototype")
67
+ )
68
+ return t.memberExpression(
69
+ t.memberExpression(
70
+ t.arrowFunctionExpression([t.identifier("_")], t.identifier("_")),
71
+ t.identifier("constructor")
72
+ ),
73
+ t.identifier("prototype")
74
+ )
75
+ }
76
+ if (program.scope.hasGlobal("Function")) {
77
+ const FunctionReferencePaths = getReferencePathsToGlobal("Function", program)
78
+ if (1 == FunctionReferencePaths.length) {
79
+ const referencePath = FunctionReferencePaths[0]
80
+ assert(
81
+ "MemberExpression" == referencePath.parent.type,
82
+ "`Function` isn't available in hackmud, only `Function.prototype` is accessible"
83
+ )
84
+ assert(
85
+ "Identifier" == referencePath.parent.property.type,
86
+ "`Function` isn't available in hackmud, only `Function.prototype` is accessible"
87
+ )
88
+ assert(
89
+ "prototype" == referencePath.parent.property.name,
90
+ "`Function` isn't available in hackmud, only `Function.prototype` is accessible"
91
+ )
92
+ referencePath.parentPath.replaceWith(createGetFunctionPrototypeNode())
93
+ } else {
94
+ for (const referencePath of FunctionReferencePaths) {
95
+ assert(
96
+ "MemberExpression" == referencePath.parent.type,
97
+ "`Function` isn't available in hackmud, only `Function.prototype` is accessible"
98
+ )
99
+ assert(
100
+ "Identifier" == referencePath.parent.property.type,
101
+ "`Function` isn't available in hackmud, only `Function.prototype` is accessible"
102
+ )
103
+ assert(
104
+ "prototype" == referencePath.parent.property.name,
105
+ "`Function` isn't available in hackmud, only `Function.prototype` is accessible"
106
+ )
107
+ functionDotPrototypeIsReferencedMultipleTimes = !0
108
+ referencePath.parentPath.replaceWith(t.identifier(`_${uniqueID}_FUNCTION_DOT_PROTOTYPE_`))
109
+ }
110
+ functionDotPrototypeIsReferencedMultipleTimes = !0
111
+ }
112
+ }
113
+ let detectedSeclevel = 4
114
+ const neededSubscriptLets = new Set(),
115
+ processFakeSubscriptObject = fakeSubscriptObjectName => {
116
+ for (const referencePath of getReferencePathsToGlobal(fakeSubscriptObjectName, program)) {
117
+ assert("MemberExpression" == referencePath.parent.type)
118
+ assert("Identifier" == referencePath.parent.property.type)
119
+ assert("MemberExpression" == referencePath.parentPath.parentPath?.node.type)
120
+ assert("Identifier" == referencePath.parentPath.parentPath.node.property.type)
121
+ assert(
122
+ /^[_a-z][\d_a-z]{0,24}$/.test(referencePath.parent.property.name),
123
+ `invalid user "${referencePath.parent.property.name}" in subscript`
124
+ )
125
+ assert(
126
+ /^[_a-z][\d_a-z]{0,24}$/.test(referencePath.parentPath.parentPath.node.property.name),
127
+ `invalid script name "${referencePath.parentPath.parentPath.node.property.name}" in subscript`
128
+ )
129
+ if ("CallExpression" == referencePath.parentPath.parentPath.parentPath?.type)
130
+ referencePath.parentPath.parentPath.replaceWith(
131
+ t.identifier(
132
+ `$${uniqueID}$SUBSCRIPT$${referencePath.parent.property.name}$${referencePath.parentPath.parentPath.node.property.name}$`
133
+ )
134
+ )
135
+ else {
136
+ const name = `${referencePath.parent.property.name}$${referencePath.parentPath.parentPath.node.property.name}`
137
+ referencePath.parentPath.parentPath.replaceWith(t.identifier(`_${uniqueID}_SUBSCRIPT_${name}_`))
138
+ neededSubscriptLets.add(name)
139
+ }
140
+ }
141
+ }
142
+ for (const fakeSubscriptObjectName of ["$fs", "$4s", "$s"])
143
+ program.scope.hasGlobal(fakeSubscriptObjectName) && processFakeSubscriptObject(fakeSubscriptObjectName)
144
+ for (const fakeSubscriptObjectName of ["$hs", "$3s"])
145
+ if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
146
+ detectedSeclevel = 3
147
+ processFakeSubscriptObject(fakeSubscriptObjectName)
148
+ }
149
+ for (const fakeSubscriptObjectName of ["$ms", "$2s"])
150
+ if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
151
+ detectedSeclevel = 2
152
+ processFakeSubscriptObject(fakeSubscriptObjectName)
153
+ }
154
+ for (const fakeSubscriptObjectName of ["$ls", "$1s"])
155
+ if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
156
+ detectedSeclevel = 1
157
+ processFakeSubscriptObject(fakeSubscriptObjectName)
158
+ }
159
+ for (const fakeSubscriptObjectName of ["$ns", "$0s"])
160
+ if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
161
+ detectedSeclevel = 0
162
+ processFakeSubscriptObject(fakeSubscriptObjectName)
163
+ }
164
+ seclevel = Math.min(seclevel, detectedSeclevel)
165
+ const neededDbMethodLets = new Set()
166
+ if (program.scope.hasGlobal("$db"))
167
+ for (const referencePath of getReferencePathsToGlobal("$db", program)) {
168
+ assert("MemberExpression" == referencePath.parentPath.node.type)
169
+ assert("Identifier" == referencePath.parentPath.node.property.type)
170
+ const databaseOpMethodName = referencePath.parentPath.node.property.name
171
+ assert(
172
+ validDBMethods.includes(databaseOpMethodName),
173
+ `invalid db method "${databaseOpMethodName}", valid db methods are "${validDBMethods.join('", "')}"`
174
+ )
175
+ if ("CallExpression" == referencePath.parentPath.parentPath?.type)
176
+ referencePath.parentPath.replaceWith(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`))
177
+ else {
178
+ referencePath.parentPath.replaceWith(
179
+ t.identifier(`_${uniqueID}_CONSOLE_METHOD_${databaseOpMethodName}_`)
180
+ )
181
+ neededDbMethodLets.add(databaseOpMethodName)
182
+ }
183
+ }
184
+ let needDebugLet = !1
185
+ if (program.scope.hasGlobal("$D"))
186
+ for (const referencePath of getReferencePathsToGlobal("$D", program))
187
+ if ("CallExpression" == referencePath.parentPath.type)
188
+ referencePath.replaceWith(t.identifier(`$${uniqueID}$DEBUG$`))
189
+ else {
190
+ referencePath.replaceWith(t.identifier(`_${uniqueID}_DEBUG_`))
191
+ needDebugLet = !0
192
+ }
193
+ if (program.scope.hasGlobal("$FMCL"))
194
+ for (const referencePath of getReferencePathsToGlobal("$FMCL", program))
195
+ referencePath.replaceWith(t.identifier(`$${uniqueID}$FMCL$`))
196
+ if (program.scope.hasGlobal("$G"))
197
+ for (const referencePath of getReferencePathsToGlobal("$G", program))
198
+ referencePath.replaceWith(t.identifier(`$${uniqueID}$GLOBAL$`))
199
+ if (program.scope.hasGlobal("_SECLEVEL"))
200
+ for (const referencePath of getReferencePathsToGlobal("_SECLEVEL", program))
201
+ referencePath.replaceWith(t.numericLiteral(seclevel))
202
+ let needGetPrototypeOf = !1
203
+ if (program.scope.hasGlobal("Object"))
204
+ for (const referencePath of getReferencePathsToGlobal("Object", program))
205
+ if ("MemberExpression" == referencePath.parent.type && !referencePath.parent.computed) {
206
+ assert("Identifier" == referencePath.parent.property.type)
207
+ if ("getPrototypeOf" == referencePath.parent.property.name) {
208
+ referencePath.parentPath.replaceWith(t.identifier(`_${uniqueID}_GET_PROTOTYPE_OF_`))
209
+ needGetPrototypeOf = !0
210
+ }
211
+ }
212
+ const consoleMethodsReferenced = new Set()
213
+ if (program.scope.hasGlobal("console"))
214
+ for (const referencePath of getReferencePathsToGlobal("console", program))
215
+ if ("MemberExpression" == referencePath.parent.type && !referencePath.parent.computed) {
216
+ assert("Identifier" == referencePath.parent.property.type)
217
+ referencePath.parentPath.replaceWith(
218
+ t.identifier(`_${uniqueID}_CONSOLE_METHOD_${referencePath.parent.property.name}_`)
219
+ )
220
+ consoleMethodsReferenced.add(referencePath.parent.property.name)
221
+ }
222
+ const lastStatement = program.node.body.at(-1)
223
+ let exportDefaultName
224
+ assert(lastStatement, "program is empty")
225
+ if ("ExportNamedDeclaration" == lastStatement.type) {
226
+ program.node.body.pop()
227
+ for (const specifier of lastStatement.specifiers) {
228
+ assert("ExportSpecifier" == specifier.type, specifier.type + " is currently unsupported")
229
+ const exportedName =
230
+ "Identifier" == specifier.exported.type ? specifier.exported.name : specifier.exported.value
231
+ "default" == exportedName ?
232
+ (exportDefaultName = specifier.local.name)
233
+ : exports.set(specifier.local.name, exportedName)
234
+ }
235
+ }
236
+ const globalBlock = t.blockStatement([])
237
+ let mainFunction
238
+ for (const statement of program.node.body)
239
+ if ("VariableDeclaration" == statement.type)
240
+ for (const declarator of statement.declarations)
241
+ if (
242
+ "Identifier" != declarator.id.type ||
243
+ declarator.id.name != exportDefaultName ||
244
+ !declarator.init ||
245
+ ("FunctionExpression" != declarator.init.type &&
246
+ "ArrowFunctionExpression" != declarator.init.type) ||
247
+ declarator.init.async ||
248
+ declarator.init.generator
249
+ ) {
250
+ for (const identifierName in t.getBindingIdentifiers(declarator.id)) {
251
+ identifierName == exportDefaultName &&
252
+ (mainFunction = t.functionDeclaration(
253
+ t.identifier(topFunctionName),
254
+ [t.identifier("context"), t.identifier("args")],
255
+ t.blockStatement([
256
+ t.returnStatement(t.callExpression(t.identifier(exportDefaultName), []))
257
+ ])
258
+ ))
259
+ if ("const" != statement.kind && exports.has(identifierName)) {
260
+ liveExports.set(identifierName, exports.get(identifierName))
261
+ exports.delete(identifierName)
262
+ }
263
+ globalBlock.body.push(
264
+ t.variableDeclaration("let", [t.variableDeclarator(t.identifier(identifierName))])
265
+ )
266
+ }
267
+ declarator.init &&
268
+ globalBlock.body.push(
269
+ t.expressionStatement(t.assignmentExpression("=", declarator.id, declarator.init))
270
+ )
271
+ } else
272
+ mainFunction = t.functionDeclaration(
273
+ t.identifier(topFunctionName),
274
+ declarator.init.params,
275
+ "BlockStatement" == declarator.init.body.type ?
276
+ declarator.init.body
277
+ : t.blockStatement([t.returnStatement(declarator.init.body)])
278
+ )
279
+ else
280
+ "FunctionDeclaration" == statement.type ?
281
+ statement.id.name == exportDefaultName ?
282
+ (mainFunction = statement)
283
+ : globalBlock.body.push(
284
+ t.variableDeclaration("let", [
285
+ t.variableDeclarator(
286
+ statement.id,
287
+ t.functionExpression(
288
+ void 0,
289
+ statement.params,
290
+ statement.body,
291
+ statement.generator,
292
+ statement.async
293
+ )
294
+ )
295
+ ])
296
+ )
297
+ : globalBlock.body.push(statement)
298
+ mainFunction ||= t.functionDeclaration(
299
+ t.identifier(topFunctionName),
300
+ [t.identifier("context"), t.identifier("args")],
301
+ t.blockStatement([])
302
+ )
303
+ program.node.body = [mainFunction]
304
+ if (globalBlock.body.length) {
305
+ ;(exports.size || liveExports.size) &&
306
+ mainFunction.body.body.push(
307
+ t.returnStatement(
308
+ t.objectExpression([
309
+ ...[...exports].map(([local, exported]) =>
310
+ t.objectProperty(t.identifier(exported), t.identifier(local))
311
+ ),
312
+ ...[...liveExports].map(([local, exported]) =>
313
+ t.objectMethod(
314
+ "get",
315
+ t.identifier(exported),
316
+ [],
317
+ t.blockStatement([t.returnStatement(t.identifier(local))])
318
+ )
319
+ )
320
+ ])
321
+ )
322
+ )
323
+ program.scope.crawl()
324
+ const globalBlockVariables = new Set()
325
+ let hoistedGlobalBlockFunctions = 0
326
+ for (const [globalBlockIndex, globalBlockStatement] of [...globalBlock.body.entries()].reverse())
327
+ if ("VariableDeclaration" == globalBlockStatement.type) {
328
+ assert(1 == globalBlockStatement.declarations.length)
329
+ const declarator = globalBlockStatement.declarations[0]
330
+ assert("Identifier" == declarator.id.type, `declarator.id.type was "${declarator.id.type}"`)
331
+ program.scope.crawl()
332
+ if (program.scope.hasGlobal(declarator.id.name)) {
333
+ globalBlock.body.splice(globalBlockIndex, 1)
334
+ const [globalBlockPath] = program.unshiftContainer("body", globalBlock),
335
+ [globalBlockStatementPath] = program.unshiftContainer("body", globalBlockStatement)
336
+ program.scope.crawl()
337
+ if (
338
+ !declarator.init ||
339
+ ("FunctionExpression" != declarator.init.type &&
340
+ "ArrowFunctionExpression" != declarator.init.type) ||
341
+ Object.keys(program.scope.globals).some(global => globalBlockVariables.has(global))
342
+ ) {
343
+ const binding = program.scope.getBinding(declarator.id.name)
344
+ assert(binding)
345
+ for (const referencePath of binding.referencePaths) {
346
+ assert("Identifier" == referencePath.node.type)
347
+ referencePath.replaceWith(
348
+ t.memberExpression(
349
+ t.identifier(`$${uniqueID}$GLOBAL$`),
350
+ t.identifier(referencePath.node.name)
351
+ )
352
+ )
353
+ }
354
+ for (const referencePath of binding.constantViolations)
355
+ if ("AssignmentExpression" == referencePath.node.type)
356
+ for (const [name, node] of Object.entries(
357
+ t.getBindingIdentifiers(referencePath.node)
358
+ ))
359
+ if (name == declarator.id.name) {
360
+ clearObject(node)
361
+ Object.assign(
362
+ node,
363
+ t.memberExpression(
364
+ t.identifier(`$${uniqueID}$GLOBAL$`),
365
+ t.identifier(name)
366
+ )
367
+ )
368
+ }
369
+ globalBlockPath.remove()
370
+ globalBlockStatementPath.remove()
371
+ declarator.init &&
372
+ globalBlock.body.splice(
373
+ globalBlockIndex,
374
+ 0,
375
+ t.expressionStatement(
376
+ t.assignmentExpression(
377
+ "=",
378
+ t.memberExpression(
379
+ t.identifier(`$${uniqueID}$GLOBAL$`),
380
+ t.identifier(declarator.id.name)
381
+ ),
382
+ declarator.init
383
+ )
384
+ )
385
+ )
386
+ } else {
387
+ globalBlockPath.remove()
388
+ globalBlockStatementPath.remove()
389
+ mainFunction.body.body.unshift(globalBlockStatement)
390
+ hoistedGlobalBlockFunctions++
391
+ }
392
+ } else globalBlockVariables.add(declarator.id.name)
393
+ } else if ("ClassDeclaration" == globalBlockStatement.type) {
394
+ program.scope.crawl()
395
+ assert(globalBlockStatement.id, "src/processScript/transform.ts:544:37")
396
+ if (program.scope.hasGlobal(globalBlockStatement.id.name)) {
397
+ globalBlock.body.splice(globalBlockIndex, 1)
398
+ const [globalBlockPath] = program.unshiftContainer("body", globalBlock),
399
+ [globalBlockStatementPath] = program.unshiftContainer("body", globalBlockStatement)
400
+ program.scope.crawl()
401
+ const binding = program.scope.getBinding(globalBlockStatement.id.name)
402
+ assert(binding)
403
+ for (const referencePath of binding.referencePaths) {
404
+ assert("Identifier" == referencePath.node.type)
405
+ referencePath.replaceWith(
406
+ t.memberExpression(
407
+ t.identifier(`$${uniqueID}$GLOBAL$`),
408
+ t.identifier(referencePath.node.name)
409
+ )
410
+ )
411
+ }
412
+ globalBlockPath.remove()
413
+ globalBlockStatementPath.remove()
414
+ globalBlock.body.splice(
415
+ globalBlockIndex,
416
+ 0,
417
+ t.expressionStatement(
418
+ t.assignmentExpression(
419
+ "=",
420
+ t.memberExpression(
421
+ t.identifier(`$${uniqueID}$GLOBAL$`),
422
+ t.identifier(globalBlockStatement.id.name)
423
+ ),
424
+ t.classExpression(
425
+ void 0,
426
+ globalBlockStatement.superClass,
427
+ globalBlockStatement.body,
428
+ globalBlockStatement.decorators
429
+ )
430
+ )
431
+ )
432
+ )
433
+ }
434
+ }
435
+ if (program.scope.hasGlobal("_EXPORTS"))
436
+ for (const referencePath of getReferencePathsToGlobal("_EXPORTS", program))
437
+ referencePath.replaceWith(
438
+ t.arrayExpression([...exports.keys(), ...liveExports.keys()].map(name => t.stringLiteral(name)))
439
+ )
440
+ globalBlock.body.length &&
441
+ mainFunction.body.body.splice(
442
+ hoistedGlobalBlockFunctions,
443
+ 0,
444
+ t.ifStatement(t.unaryExpression("!", t.identifier(`$${uniqueID}$FMCL$`)), globalBlock)
445
+ )
446
+ }
447
+ functionDotPrototypeIsReferencedMultipleTimes &&
448
+ mainFunction.body.body.unshift(
449
+ t.variableDeclaration("let", [
450
+ t.variableDeclarator(
451
+ t.identifier(`_${uniqueID}_FUNCTION_DOT_PROTOTYPE_`),
452
+ createGetFunctionPrototypeNode()
453
+ )
454
+ ])
455
+ )
456
+ needGetPrototypeOf &&
457
+ mainFunction.body.body.unshift(
458
+ t.variableDeclaration("let", [
459
+ t.variableDeclarator(
460
+ t.objectPattern([
461
+ t.objectProperty(t.identifier("get"), t.identifier(`_${uniqueID}_DUNDER_PROTO_GETTER_`))
462
+ ]),
463
+ t.callExpression(
464
+ t.memberExpression(t.identifier("Object"), t.identifier("getOwnPropertyDescriptor")),
465
+ [
466
+ t.memberExpression(t.identifier("Object"), t.identifier("prototype")),
467
+ t.stringLiteral("__proto__")
468
+ ]
469
+ )
470
+ ),
471
+ t.variableDeclarator(
472
+ t.identifier(`_${uniqueID}_GET_PROTOTYPE_OF_`),
473
+ t.callExpression(
474
+ t.memberExpression(
475
+ t.memberExpression(
476
+ t.identifier(
477
+ globalFunctionsUnder7Characters.find(name => !program.scope.hasOwnBinding(name))
478
+ ),
479
+ t.identifier("call")
480
+ ),
481
+ t.identifier("bind")
482
+ ),
483
+ [t.identifier(`_${uniqueID}_DUNDER_PROTO_GETTER_`)]
484
+ )
485
+ )
486
+ ])
487
+ )
488
+ consoleMethodsReferenced.size &&
489
+ mainFunction.body.body.unshift(
490
+ t.variableDeclaration(
491
+ "let",
492
+ [...consoleMethodsReferenced].map(name =>
493
+ t.variableDeclarator(
494
+ t.identifier(`_${uniqueID}_CONSOLE_METHOD_${name}_`),
495
+ t.arrowFunctionExpression(
496
+ [t.restElement(t.identifier("args"))],
497
+ t.unaryExpression(
498
+ "void",
499
+ t.callExpression(t.identifier(`$${uniqueID}$DEBUG$`), [t.identifier("args")])
500
+ )
501
+ )
502
+ )
503
+ )
504
+ )
505
+ )
506
+ neededDbMethodLets.size &&
507
+ mainFunction.body.body.unshift(
508
+ t.variableDeclaration(
509
+ "let",
510
+ [...neededDbMethodLets].map(name => {
511
+ const getArgs = () =>
512
+ "ObjectId" == name ? []
513
+ : "i" == name || "r" == name ? [t.identifier("a")]
514
+ : [t.identifier("a"), t.identifier("b")]
515
+ return t.variableDeclarator(
516
+ t.identifier(`_${uniqueID}_CONSOLE_METHOD_${name}_`),
517
+ t.arrowFunctionExpression(
518
+ getArgs(),
519
+ t.callExpression(t.identifier(`$${uniqueID}$DB$${name}$`), getArgs())
520
+ )
521
+ )
522
+ })
523
+ )
524
+ )
525
+ needDebugLet &&
526
+ mainFunction.body.body.unshift(
527
+ t.variableDeclaration("let", [
528
+ t.variableDeclarator(
529
+ t.identifier(`_${uniqueID}_DEBUG_`),
530
+ t.callExpression(t.identifier(`$${uniqueID}$DEBUG$`), [t.identifier("a")])
531
+ )
532
+ ])
533
+ )
534
+ neededSubscriptLets.size &&
535
+ mainFunction.body.body.unshift(
536
+ t.variableDeclaration(
537
+ "let",
538
+ [...neededSubscriptLets].map(name =>
539
+ t.variableDeclarator(
540
+ t.identifier(`_${uniqueID}_SUBSCRIPT_${name}_`),
541
+ t.arrowFunctionExpression(
542
+ [t.restElement(t.identifier("args"))],
543
+ t.callExpression(t.identifier(`$${uniqueID}$SUBSCRIPT$${name}$`), [
544
+ t.spreadElement(t.identifier("args"))
545
+ ])
546
+ )
547
+ )
548
+ )
549
+ )
550
+ )
551
+ traverse(file, {
552
+ BlockStatement({ node: blockStatement }) {
553
+ for (const [index, functionDeclaration] of blockStatement.body.entries())
554
+ if ("FunctionDeclaration" == functionDeclaration.type && !functionDeclaration.generator) {
555
+ blockStatement.body.splice(index, 1)
556
+ blockStatement.body.unshift(
557
+ t.variableDeclaration("let", [
558
+ t.variableDeclarator(
559
+ functionDeclaration.id,
560
+ t.arrowFunctionExpression(
561
+ functionDeclaration.params,
562
+ functionDeclaration.body,
563
+ functionDeclaration.async
564
+ )
565
+ )
566
+ ])
567
+ )
568
+ }
569
+ },
570
+ ClassBody({ node: classBody, scope, parent }) {
571
+ assert(t.isClass(parent))
572
+ let thisIsReferenced = !1
573
+ for (const classMethod of classBody.body) {
574
+ if ("ClassMethod" != classMethod.type) continue
575
+ let methodReferencesThis = !1
576
+ traverse(
577
+ classMethod.body,
578
+ {
579
+ ThisExpression(path) {
580
+ methodReferencesThis = !0
581
+ thisIsReferenced = !0
582
+ path.replaceWith(t.identifier(`_${uniqueID}_THIS_`))
583
+ },
584
+ Function(path) {
585
+ path.skip()
586
+ }
587
+ },
588
+ scope
589
+ )
590
+ if (methodReferencesThis)
591
+ if ("constructor" != classMethod.kind)
592
+ classMethod.body.body.unshift(
593
+ t.variableDeclaration("let", [
594
+ t.variableDeclarator(
595
+ t.identifier(`_${uniqueID}_THIS_`),
596
+ t.callExpression(t.memberExpression(t.super(), t.identifier("valueOf")), [])
597
+ )
598
+ ])
599
+ )
600
+ else {
601
+ const superCalls = []
602
+ traverse(
603
+ classMethod.body,
604
+ {
605
+ CallExpression(path) {
606
+ "Super" == path.node.callee.type && superCalls.push(path)
607
+ }
608
+ },
609
+ scope
610
+ )
611
+ if (superCalls.length)
612
+ if (
613
+ 1 == superCalls.length &&
614
+ "ExpressionStatement" == superCalls[0].parent.type &&
615
+ superCalls[0].parentPath.parentPath.parent == classMethod
616
+ )
617
+ superCalls[0].parentPath.replaceWith(
618
+ t.variableDeclaration("let", [
619
+ t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`), superCalls[0].node)
620
+ ])
621
+ )
622
+ else {
623
+ for (const path of superCalls)
624
+ path.replaceWith(
625
+ t.assignmentExpression("=", t.identifier(`_${uniqueID}_THIS_`), path.node)
626
+ )
627
+ classMethod.body.body.unshift(
628
+ t.variableDeclaration("let", [
629
+ t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`))
630
+ ])
631
+ )
632
+ }
633
+ else
634
+ classMethod.body.body.unshift(
635
+ t.variableDeclaration("let", [
636
+ t.variableDeclarator(
637
+ t.identifier(`_${uniqueID}_THIS_`),
638
+ t.callExpression(t.super(), [])
639
+ )
640
+ ])
641
+ )
642
+ }
643
+ }
644
+ !parent.superClass && thisIsReferenced && (parent.superClass = t.identifier("Object"))
645
+ },
646
+ VariableDeclaration({ node: variableDeclaration }) {
647
+ "const" == variableDeclaration.kind && (variableDeclaration.kind = "let")
648
+ },
649
+ ThisExpression(path) {
650
+ path.replaceWith(t.identifier("undefined"))
651
+ },
652
+ BigIntLiteral(path) {
653
+ const bigIntAsNumber = Number(path.node.value)
654
+ BigInt(bigIntAsNumber) == BigInt(path.node.value) ?
655
+ path.replaceWith(t.callExpression(t.identifier("BigInt"), [t.numericLiteral(bigIntAsNumber)]))
656
+ : path.replaceWith(t.callExpression(t.identifier("BigInt"), [t.stringLiteral(path.node.value)]))
657
+ }
658
+ })
659
+ return { file, seclevel }
660
+ }
661
+ export { transform as default, transform }