hackmud-script-manager 0.19.0-7c69a3b → 0.19.0-b5e2c0b

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,393 +1 @@
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
-
8
- // eslint-disable-next-line @typescript-eslint/consistent-type-imports
9
- const {
10
- default: traverse
11
- } = babelTraverse;
12
- const globalFunctionsUnder7Characters = [`Map`, `Set`, `Date`, `JSON`, `Math`, `Array`, `Error`, `isNaN`, `Number`, `Object`, `RegExp`, `String`, `Symbol`, `BigInt`];
13
-
14
- /**
15
- * transform a given babel `File` to be hackmud compatible
16
- *
17
- * (returned File will need `postprocess()`ing)
18
- *
19
- * @param file babel ast node representing a file containing preprocessed code
20
- * @param sourceCode the original untouched source code
21
- * @param options {@link TransformOptions details}
22
- */
23
- const transform = (file, sourceCode, {
24
- uniqueID = `00000000000`,
25
- scriptUser = `UNKNOWN`,
26
- scriptName = `UNKNOWN`,
27
- seclevel = 4
28
- } = {}) => {
29
- const topFunctionName = `_${uniqueID}_SCRIPT_`;
30
- const exports = new Map();
31
- const 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)) referencePath.replaceWith(t.stringLiteral(sourceCode));
41
- }
42
- if (program.scope.hasGlobal(`_BUILD_DATE`)) {
43
- for (const referencePath of getReferencePathsToGlobal(`_BUILD_DATE`, program)) referencePath.replaceWith(t.numericLiteral(Date.now()));
44
- }
45
- if (program.scope.hasGlobal(`_SCRIPT_USER`)) {
46
- for (const referencePath of getReferencePathsToGlobal(`_SCRIPT_USER`, program)) {
47
- if (scriptUser == true) referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$SCRIPT_USER$`));else referencePath.replaceWith(t.stringLiteral(scriptUser));
48
- }
49
- }
50
- if (program.scope.hasGlobal(`_SCRIPT_NAME`)) {
51
- for (const referencePath of getReferencePathsToGlobal(`_SCRIPT_NAME`, program)) {
52
- if (scriptName == true) referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$SCRIPT_NAME$`));else referencePath.replaceWith(t.stringLiteral(scriptName));
53
- }
54
- }
55
- if (program.scope.hasGlobal(`_FULL_SCRIPT_NAME`)) {
56
- for (const referencePath of getReferencePathsToGlobal(`_FULL_SCRIPT_NAME`, program)) {
57
- if (scriptUser == true || scriptName == true) referencePath.replaceWith(t.stringLiteral(`$${uniqueID}$FULL_SCRIPT_NAME$`));else referencePath.replaceWith(t.stringLiteral(`${scriptUser}.${scriptName}`));
58
- }
59
- }
60
- let functionDotPrototypeIsReferencedMultipleTimes = false;
61
- const createGetFunctionPrototypeNode = () => {
62
- for (const globalFunction of globalFunctionsUnder7Characters) {
63
- if (program.scope.hasOwnBinding(globalFunction)) continue;
64
- return t.memberExpression(t.memberExpression(t.identifier(globalFunction), t.identifier(`constructor`)), t.identifier(`prototype`));
65
- }
66
- return t.memberExpression(t.memberExpression(t.arrowFunctionExpression([t.identifier(`_`)], t.identifier(`_`)), t.identifier(`constructor`)), t.identifier(`prototype`));
67
- };
68
- if (program.scope.hasGlobal(`Function`)) {
69
- const FunctionReferencePaths = getReferencePathsToGlobal(`Function`, program);
70
- if (FunctionReferencePaths.length == 1) {
71
- const referencePath = FunctionReferencePaths[0];
72
- assert(referencePath.parent.type == `MemberExpression`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
73
- assert(referencePath.parent.property.type == `Identifier`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
74
- assert(referencePath.parent.property.name == `prototype`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
75
- referencePath.parentPath.replaceWith(createGetFunctionPrototypeNode());
76
- } else {
77
- for (const referencePath of FunctionReferencePaths) {
78
- assert(referencePath.parent.type == `MemberExpression`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
79
- assert(referencePath.parent.property.type == `Identifier`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
80
- assert(referencePath.parent.property.name == `prototype`, `\`Function\` isn't available in hackmud, only \`Function.prototype\` is accessible`);
81
- functionDotPrototypeIsReferencedMultipleTimes = true;
82
- referencePath.parentPath.replaceWith(t.identifier(`_${uniqueID}_FUNCTION_DOT_PROTOTYPE_`));
83
- }
84
- functionDotPrototypeIsReferencedMultipleTimes = true;
85
- }
86
- }
87
- let detectedSeclevel = 4;
88
- const processFakeSubscriptObject = fakeSubscriptObjectName => {
89
- for (const referencePath of getReferencePathsToGlobal(fakeSubscriptObjectName, program)) {
90
- assert(referencePath.parent.type == `MemberExpression`);
91
- assert(referencePath.parent.property.type == `Identifier`);
92
- assert(referencePath.parentPath.parentPath?.node.type == `MemberExpression`);
93
- assert(referencePath.parentPath.parentPath.node.property.type == `Identifier`);
94
- assert(/^[_a-z][\d_a-z]{0,24}$/.test(referencePath.parent.property.name), `invalid user "${referencePath.parent.property.name}" in subscript`);
95
- assert(/^[_a-z][\d_a-z]{0,24}$/.test(referencePath.parentPath.parentPath.node.property.name), `invalid script name "${referencePath.parentPath.parentPath.node.property.name}" in subscript`);
96
- if (referencePath.parentPath.parentPath.parentPath?.type == `CallExpression`) {
97
- // BUG this is causing typescript to be slow
98
- referencePath.parentPath.parentPath.replaceWith(t.identifier(`$${uniqueID}$SUBSCRIPT$${referencePath.parent.property.name}$${referencePath.parentPath.parentPath.node.property.name}$`));
99
- } else {
100
- // BUG this is causing typescript to be slow
101
- referencePath.parentPath.parentPath.replaceWith(t.arrowFunctionExpression([t.restElement(t.identifier(`args`))], t.callExpression(t.identifier(`$${uniqueID}$SUBSCRIPT$${referencePath.parent.property.name}$${referencePath.parentPath.parentPath.node.property.name}$`), [t.spreadElement(t.identifier(`args`))])));
102
- }
103
- }
104
- };
105
- for (const fakeSubscriptObjectName of [`$fs`, `$4s`, `$s`]) {
106
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) processFakeSubscriptObject(fakeSubscriptObjectName);
107
- }
108
- for (const fakeSubscriptObjectName of [`$hs`, `$3s`]) {
109
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
110
- detectedSeclevel = 3;
111
- processFakeSubscriptObject(fakeSubscriptObjectName);
112
- }
113
- }
114
- for (const fakeSubscriptObjectName of [`$ms`, `$2s`]) {
115
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
116
- detectedSeclevel = 2;
117
- processFakeSubscriptObject(fakeSubscriptObjectName);
118
- }
119
- }
120
- for (const fakeSubscriptObjectName of [`$ls`, `$1s`]) {
121
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
122
- detectedSeclevel = 1;
123
- processFakeSubscriptObject(fakeSubscriptObjectName);
124
- }
125
- }
126
- for (const fakeSubscriptObjectName of [`$ns`, `$0s`]) {
127
- if (program.scope.hasGlobal(fakeSubscriptObjectName)) {
128
- detectedSeclevel = 0;
129
- processFakeSubscriptObject(fakeSubscriptObjectName);
130
- }
131
- }
132
- seclevel = Math.min(seclevel, detectedSeclevel);
133
- if (program.scope.hasGlobal(`$db`)) {
134
- for (const referencePath of getReferencePathsToGlobal(`$db`, program)) {
135
- assert(referencePath.parentPath.node.type == `MemberExpression`);
136
- assert(referencePath.parentPath.node.property.type == `Identifier`);
137
- const databaseOpMethodName = referencePath.parentPath.node.property.name;
138
- assert(validDBMethods.includes(databaseOpMethodName), `invalid db method "${databaseOpMethodName}", valid db methods are "${validDBMethods.join(`", "`)}"`);
139
- if (referencePath.parentPath.parentPath?.type == `CallExpression`) referencePath.parentPath.replaceWith(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`));else if (databaseOpMethodName == `ObjectId`) {
140
- referencePath.parentPath.replaceWith(t.arrowFunctionExpression([], t.callExpression(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`), [])));
141
- } else if (databaseOpMethodName == `i` || databaseOpMethodName == `r`) {
142
- referencePath.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier(`a`)], t.callExpression(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`), [t.identifier(`a`)])));
143
- } else {
144
- referencePath.parentPath.replaceWith(t.arrowFunctionExpression([t.identifier(`a`), t.identifier(`b`)], t.callExpression(t.identifier(`$${uniqueID}$DB$${databaseOpMethodName}$`), [t.identifier(`a`), t.identifier(`b`)])));
145
- }
146
- }
147
- }
148
- if (program.scope.hasGlobal(`$D`)) {
149
- for (const referencePath of getReferencePathsToGlobal(`$D`, program)) {
150
- if (referencePath.parentPath.type == `CallExpression`) referencePath.replaceWith(t.identifier(`$${uniqueID}$DEBUG$`));else {
151
- referencePath.replaceWith(t.arrowFunctionExpression([t.identifier(`a`)], t.callExpression(t.identifier(`$${uniqueID}$DEBUG$`), [t.identifier(`a`)])));
152
- }
153
- }
154
- }
155
- if (program.scope.hasGlobal(`$FMCL`)) {
156
- for (const referencePath of getReferencePathsToGlobal(`$FMCL`, program)) referencePath.replaceWith(t.identifier(`$${uniqueID}$FMCL$`));
157
- }
158
- if (program.scope.hasGlobal(`$G`)) {
159
- for (const referencePath of getReferencePathsToGlobal(`$G`, program)) referencePath.replaceWith(t.identifier(`$${uniqueID}$GLOBAL$`));
160
- }
161
- if (program.scope.hasGlobal(`_SECLEVEL`)) {
162
- for (const referencePath of getReferencePathsToGlobal(`_SECLEVEL`, program)) referencePath.replaceWith(t.numericLiteral(seclevel));
163
- }
164
- let needGetPrototypeOf = false;
165
- let needSetPrototypeOf = false;
166
- if (program.scope.hasGlobal(`Object`)) {
167
- for (const referencePath of getReferencePathsToGlobal(`Object`, program)) {
168
- if (referencePath.parent.type != `MemberExpression` || referencePath.parent.computed) continue;
169
- assert(referencePath.parent.property.type == `Identifier`);
170
- if (referencePath.parent.property.name == `getPrototypeOf`) {
171
- referencePath.parentPath.replaceWith(t.identifier(`_${uniqueID}_GET_PROTOTYPE_OF_`));
172
- needGetPrototypeOf = true;
173
- } else if (referencePath.parent.property.name == `setPrototypeOf`) {
174
- referencePath.parentPath.replaceWith(t.identifier(`_${uniqueID}_SET_PROTOTYPE_OF_`));
175
- needSetPrototypeOf = true;
176
- }
177
- }
178
- }
179
-
180
- // rollup removes all the inline exports and places a statement at the end instead
181
- const lastStatement = program.node.body.at(-1);
182
- let exportDefaultName;
183
- assert(lastStatement, `program is empty`);
184
- if (lastStatement.type == `ExportNamedDeclaration`) {
185
- program.node.body.pop();
186
- for (const specifier of lastStatement.specifiers) {
187
- assert(specifier.type == `ExportSpecifier`, `${specifier.type} is currently unsupported`);
188
- const exportedName = specifier.exported.type == `Identifier` ? specifier.exported.name : specifier.exported.value;
189
- if (exportedName == `default`) exportDefaultName = specifier.local.name;else exports.set(specifier.local.name, exportedName);
190
- }
191
- }
192
- const globalBlock = t.blockStatement([]);
193
- let mainFunction;
194
- for (const statement of program.node.body) {
195
- if (statement.type == `VariableDeclaration`) {
196
- for (const declarator of statement.declarations) {
197
- if (declarator.id.type == `Identifier` && declarator.id.name == exportDefaultName && declarator.init && (declarator.init.type == `FunctionExpression` || declarator.init.type == `ArrowFunctionExpression`) && !declarator.init.async && !declarator.init.generator) {
198
- mainFunction = t.functionDeclaration(t.identifier(topFunctionName), declarator.init.params, declarator.init.body.type == `BlockStatement` ? declarator.init.body : t.blockStatement([t.returnStatement(declarator.init.body)]));
199
- continue;
200
- }
201
- for (const identifierName in t.getBindingIdentifiers(declarator.id)) {
202
- if (identifierName == exportDefaultName) {
203
- mainFunction = t.functionDeclaration(t.identifier(topFunctionName), [t.identifier(`context`), t.identifier(`args`)], t.blockStatement([t.returnStatement(t.callExpression(t.identifier(exportDefaultName), []))]));
204
- }
205
- if (statement.kind != `const` && exports.has(identifierName)) {
206
- liveExports.set(identifierName, exports.get(identifierName));
207
- exports.delete(identifierName);
208
- }
209
- globalBlock.body.push(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(identifierName))]));
210
- }
211
- if (declarator.init) {
212
- globalBlock.body.push(t.expressionStatement(t.assignmentExpression(`=`, declarator.id, declarator.init)));
213
- }
214
- }
215
- } else if (statement.type == `FunctionDeclaration`) {
216
- if (statement.id.name == exportDefaultName) mainFunction = statement;else {
217
- globalBlock.body.push(t.variableDeclaration(`let`, [t.variableDeclarator(statement.id, t.functionExpression(undefined, statement.params, statement.body, statement.generator, statement.async))]));
218
- }
219
- } else globalBlock.body.push(statement);
220
- }
221
- mainFunction ||= t.functionDeclaration(t.identifier(topFunctionName), [t.identifier(`context`), t.identifier(`args`)], t.blockStatement([]));
222
- program.node.body = [mainFunction];
223
- if (globalBlock.body.length) {
224
- if (exports.size || liveExports.size) {
225
- mainFunction.body.body.push(t.returnStatement(t.objectExpression([...[...exports].map(([local, exported]) => t.objectProperty(t.identifier(exported), t.identifier(local))), ...[...liveExports].map(([local, exported]) => t.objectMethod(`get`, t.identifier(exported), [], t.blockStatement([t.returnStatement(t.identifier(local))])))])));
226
- }
227
- program.scope.crawl();
228
- const globalBlockVariables = new Set();
229
- let hoistedGlobalBlockFunctions = 0;
230
- for (const [globalBlockIndex, globalBlockStatement] of [...globalBlock.body.entries()].reverse()) {
231
- if (globalBlockStatement.type == `VariableDeclaration`) {
232
- assert(globalBlockStatement.declarations.length == 1);
233
- const declarator = globalBlockStatement.declarations[0];
234
- assert(declarator.id.type == `Identifier`, `declarator.id.type was "${declarator.id.type}"`);
235
- program.scope.crawl();
236
- if (program.scope.hasGlobal(declarator.id.name)) {
237
- globalBlock.body.splice(globalBlockIndex, 1);
238
- const [globalBlockPath] = program.unshiftContainer(`body`, globalBlock);
239
- const [globalBlockStatementPath] = program.unshiftContainer(`body`, globalBlockStatement);
240
- program.scope.crawl();
241
- if (!declarator.init || declarator.init.type != `FunctionExpression` && declarator.init.type != `ArrowFunctionExpression` || Object.keys(program.scope.globals).some(global => globalBlockVariables.has(global))) {
242
- const binding = program.scope.getBinding(declarator.id.name);
243
- assert(binding);
244
- for (const referencePath of binding.referencePaths) {
245
- assert(referencePath.node.type == `Identifier`);
246
- referencePath.replaceWith(t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(referencePath.node.name)));
247
- }
248
- for (const referencePath of binding.constantViolations) {
249
- if (referencePath.node.type != `AssignmentExpression`) continue;
250
- for (const [name, node] of Object.entries(t.getBindingIdentifiers(referencePath.node))) {
251
- if (name == declarator.id.name) {
252
- clearObject(node);
253
- Object.assign(node, t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(name)));
254
- }
255
- }
256
- }
257
- globalBlockPath.remove();
258
- globalBlockStatementPath.remove();
259
- if (declarator.init) {
260
- globalBlock.body.splice(globalBlockIndex, 0, t.expressionStatement(t.assignmentExpression(`=`, t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(declarator.id.name)), declarator.init)));
261
- }
262
- } else {
263
- globalBlockPath.remove();
264
- globalBlockStatementPath.remove();
265
- mainFunction.body.body.unshift(globalBlockStatement);
266
- hoistedGlobalBlockFunctions++;
267
- }
268
- } else globalBlockVariables.add(declarator.id.name);
269
- } else if (globalBlockStatement.type == `ClassDeclaration`) {
270
- program.scope.crawl();
271
- assert(globalBlockStatement.id, "src/processScript/transform.ts:564:37");
272
- if (program.scope.hasGlobal(globalBlockStatement.id.name)) {
273
- globalBlock.body.splice(globalBlockIndex, 1);
274
- const [globalBlockPath] = program.unshiftContainer(`body`, globalBlock);
275
- const [globalBlockStatementPath] = program.unshiftContainer(`body`, globalBlockStatement);
276
- program.scope.crawl();
277
- const binding = program.scope.getBinding(globalBlockStatement.id.name);
278
- assert(binding);
279
- for (const referencePath of binding.referencePaths) {
280
- assert(referencePath.node.type == `Identifier`);
281
- referencePath.replaceWith(t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(referencePath.node.name)));
282
- }
283
- globalBlockPath.remove();
284
- globalBlockStatementPath.remove();
285
- globalBlock.body.splice(globalBlockIndex, 0, t.expressionStatement(t.assignmentExpression(`=`, t.memberExpression(t.identifier(`$${uniqueID}$GLOBAL$`), t.identifier(globalBlockStatement.id.name)), t.classExpression(undefined, globalBlockStatement.superClass, globalBlockStatement.body, globalBlockStatement.decorators))));
286
- }
287
- }
288
- }
289
- if (program.scope.hasGlobal(`_EXPORTS`)) {
290
- for (const referencePath of getReferencePathsToGlobal(`_EXPORTS`, program)) {
291
- referencePath.replaceWith(t.arrayExpression([...exports.keys(), ...liveExports.keys()].map(name => t.stringLiteral(name))));
292
- }
293
- }
294
- if (globalBlock.body.length) {
295
- mainFunction.body.body.splice(hoistedGlobalBlockFunctions, 0, t.ifStatement(t.unaryExpression(`!`, t.identifier(`$${uniqueID}$FMCL$`)), globalBlock));
296
- }
297
- }
298
- if (functionDotPrototypeIsReferencedMultipleTimes) {
299
- mainFunction.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_FUNCTION_DOT_PROTOTYPE_`), createGetFunctionPrototypeNode())]));
300
- }
301
- if (needSetPrototypeOf) {
302
- mainFunction.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_SET_PROTOTYPE_OF_`), t.callExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`), t.identifier(`call`)), t.identifier(`bind`)), [t.identifier(`_${uniqueID}_DUNDER_PROTO_SETTER_`)]))]));
303
- }
304
- if (needGetPrototypeOf) {
305
- mainFunction.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_GET_PROTOTYPE_OF_`), t.callExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`), t.identifier(`call`)), t.identifier(`bind`)), [t.identifier(`_${uniqueID}_DUNDER_PROTO_GETTER_`)]))]));
306
- }
307
- if (needGetPrototypeOf || needSetPrototypeOf) {
308
- mainFunction.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.objectPattern(needGetPrototypeOf ? needSetPrototypeOf ? [t.objectProperty(t.identifier(`get`), t.identifier(`_${uniqueID}_DUNDER_PROTO_GETTER_`)), t.objectProperty(t.identifier(`set`), t.identifier(`_${uniqueID}_DUNDER_PROTO_SETTER_`))] : [t.objectProperty(t.identifier(`get`), t.identifier(`_${uniqueID}_DUNDER_PROTO_GETTER_`))] : [t.objectProperty(t.identifier(`set`), t.identifier(`_${uniqueID}_DUNDER_PROTO_SETTER_`))]), t.callExpression(t.memberExpression(t.identifier(`Object`), t.identifier(`getOwnPropertyDescriptor`)), [t.memberExpression(t.identifier(`Object`), t.identifier(`prototype`)), t.stringLiteral(`__proto__`)]))]));
309
- }
310
- traverse(file, {
311
- BlockStatement({
312
- node: blockStatement
313
- }) {
314
- for (const [index, functionDeclaration] of blockStatement.body.entries()) {
315
- if (functionDeclaration.type != `FunctionDeclaration` || functionDeclaration.generator) continue;
316
- blockStatement.body.splice(index, 1);
317
- blockStatement.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(functionDeclaration.id, t.arrowFunctionExpression(functionDeclaration.params, functionDeclaration.body, functionDeclaration.async))]));
318
- }
319
- },
320
- ClassBody({
321
- node: classBody,
322
- scope,
323
- parent
324
- }) {
325
- assert(t.isClass(parent));
326
- let thisIsReferenced = false;
327
- for (const classMethod of classBody.body) {
328
- if (classMethod.type != `ClassMethod`) continue;
329
- let methodReferencesThis = false;
330
- traverse(classMethod.body, {
331
- ThisExpression(path) {
332
- methodReferencesThis = true;
333
- thisIsReferenced = true;
334
- path.replaceWith(t.identifier(`_${uniqueID}_THIS_`));
335
- },
336
- Function(path) {
337
- path.skip();
338
- }
339
- }, scope);
340
- if (!methodReferencesThis) continue;
341
- if (classMethod.kind == `constructor`) {
342
- const superCalls = [];
343
- traverse(classMethod.body, {
344
- CallExpression(path) {
345
- if (path.node.callee.type == `Super`) superCalls.push(path);
346
- }
347
- }, scope);
348
- if (!superCalls.length) {
349
- classMethod.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`), t.callExpression(t.super(), []))]));
350
- } else if (superCalls.length == 1 && superCalls[0].parent.type == `ExpressionStatement` && superCalls[0].parentPath.parentPath.parent == classMethod) {
351
- superCalls[0].parentPath.replaceWith(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`), superCalls[0].node)]));
352
- } else {
353
- for (const path of superCalls) {
354
- path.replaceWith(t.assignmentExpression(`=`, t.identifier(`_${uniqueID}_THIS_`), path.node));
355
- }
356
- classMethod.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`))]));
357
- }
358
- continue;
359
- }
360
-
361
- // BUG if the class or a super class overwrites `valueOf()` (or `Object.prototype` isn't even in the chain), this breaks
362
- // TODO track whether the class is extending a class that at some point extends from `Object` (if unsure, assume no)
363
- // TODO track whether any class in the chain overwrites `valueOf()` (if unsure, assume yes)
364
- // TODO for classes that need it, create a super class for this one to extend from with `valueOf()` assigned to an unused name
365
-
366
- classMethod.body.body.unshift(t.variableDeclaration(`let`, [t.variableDeclarator(t.identifier(`_${uniqueID}_THIS_`), t.callExpression(t.memberExpression(t.super(), t.identifier(`valueOf`)), []))]));
367
- }
368
- if (!parent.superClass && thisIsReferenced) parent.superClass = t.identifier(`Object`);
369
- },
370
- VariableDeclaration({
371
- node: variableDeclaration
372
- }) {
373
- if (variableDeclaration.kind == `const`) variableDeclaration.kind = `let`;
374
- },
375
- ThisExpression(path) {
376
- path.replaceWith(t.identifier(`undefined`));
377
- },
378
- BigIntLiteral(path) {
379
- const bigIntAsNumber = Number(path.node.value);
380
- if (BigInt(bigIntAsNumber) == BigInt(path.node.value)) {
381
- path.replaceWith(t.callExpression(t.identifier(`BigInt`), [t.numericLiteral(bigIntAsNumber)]));
382
- } else {
383
- path.replaceWith(t.callExpression(t.identifier(`BigInt`), [t.stringLiteral(path.node.value)]));
384
- }
385
- }
386
- });
387
- return {
388
- file,
389
- seclevel
390
- };
391
- };
392
-
393
- export { transform as default, transform };
1
+ import e from"@babel/traverse";import i from"@babel/types";import{assert as t}from"@samual/lib/assert";import{clearObject as r}from"@samual/lib/clearObject";import{validDBMethods as n}from"../constants.js";import{getReferencePathsToGlobal as o}from"./shared.js";const{default:a}=e,s=["Map","Set","Date","JSON","Math","Array","Error","isNaN","Number","Object","RegExp","String","Symbol","BigInt"],transform=(e,p,{uniqueID:l="00000000000",scriptUser:c="UNKNOWN",scriptName:d="UNKNOWN",seclevel:f=4}={})=>{const b=`_${l}_SCRIPT_`,y=new Map,m=new Map;let $;if(a(e,{Program(e){$=e,e.skip()}}),$.scope.hasGlobal("_SOURCE"))for(const e of o("_SOURCE",$))e.replaceWith(i.stringLiteral(p));if($.scope.hasGlobal("_BUILD_DATE"))for(const e of o("_BUILD_DATE",$))e.replaceWith(i.numericLiteral(Date.now()));if($.scope.hasGlobal("_SCRIPT_USER"))for(const e of o("_SCRIPT_USER",$))1==c?e.replaceWith(i.stringLiteral(`$${l}$SCRIPT_USER$`)):e.replaceWith(i.stringLiteral(c));if($.scope.hasGlobal("_SCRIPT_NAME"))for(const e of o("_SCRIPT_NAME",$))1==d?e.replaceWith(i.stringLiteral(`$${l}$SCRIPT_NAME$`)):e.replaceWith(i.stringLiteral(d));if($.scope.hasGlobal("_FULL_SCRIPT_NAME"))for(const e of o("_FULL_SCRIPT_NAME",$))1==c||1==d?e.replaceWith(i.stringLiteral(`$${l}$FULL_SCRIPT_NAME$`)):e.replaceWith(i.stringLiteral(`${c}.${d}`));let h=!1;const createGetFunctionPrototypeNode=()=>{for(const e of s)if(!$.scope.hasOwnBinding(e))return i.memberExpression(i.memberExpression(i.identifier(e),i.identifier("constructor")),i.identifier("prototype"));return i.memberExpression(i.memberExpression(i.arrowFunctionExpression([i.identifier("_")],i.identifier("_")),i.identifier("constructor")),i.identifier("prototype"))};if($.scope.hasGlobal("Function")){const e=o("Function",$);if(1==e.length){const i=e[0];t("MemberExpression"==i.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("Identifier"==i.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("prototype"==i.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),i.parentPath.replaceWith(createGetFunctionPrototypeNode())}else{for(const r of e)t("MemberExpression"==r.parent.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("Identifier"==r.parent.property.type,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),t("prototype"==r.parent.property.name,"`Function` isn't available in hackmud, only `Function.prototype` is accessible"),h=!0,r.parentPath.replaceWith(i.identifier(`_${l}_FUNCTION_DOT_PROTOTYPE_`));h=!0}}let E=4;const processFakeSubscriptObject=e=>{for(const r of o(e,$))t("MemberExpression"==r.parent.type),t("Identifier"==r.parent.property.type),t("MemberExpression"==r.parentPath.parentPath?.node.type),t("Identifier"==r.parentPath.parentPath.node.property.type),t(/^[_a-z][\d_a-z]{0,24}$/.test(r.parent.property.name),`invalid user "${r.parent.property.name}" in subscript`),t(/^[_a-z][\d_a-z]{0,24}$/.test(r.parentPath.parentPath.node.property.name),`invalid script name "${r.parentPath.parentPath.node.property.name}" in subscript`),"CallExpression"==r.parentPath.parentPath.parentPath?.type?r.parentPath.parentPath.replaceWith(i.identifier(`$${l}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}$`)):r.parentPath.parentPath.replaceWith(i.arrowFunctionExpression([i.restElement(i.identifier("args"))],i.callExpression(i.identifier(`$${l}$SUBSCRIPT$${r.parent.property.name}$${r.parentPath.parentPath.node.property.name}$`),[i.spreadElement(i.identifier("args"))])))};for(const e of["$fs","$4s","$s"])$.scope.hasGlobal(e)&&processFakeSubscriptObject(e);for(const e of["$hs","$3s"])$.scope.hasGlobal(e)&&(E=3,processFakeSubscriptObject(e));for(const e of["$ms","$2s"])$.scope.hasGlobal(e)&&(E=2,processFakeSubscriptObject(e));for(const e of["$ls","$1s"])$.scope.hasGlobal(e)&&(E=1,processFakeSubscriptObject(e));for(const e of["$ns","$0s"])$.scope.hasGlobal(e)&&(E=0,processFakeSubscriptObject(e));if(f=Math.min(f,E),$.scope.hasGlobal("$db"))for(const e of o("$db",$)){t("MemberExpression"==e.parentPath.node.type),t("Identifier"==e.parentPath.node.property.type);const r=e.parentPath.node.property.name;t(n.includes(r),`invalid db method "${r}", valid db methods are "${n.join('", "')}"`),"CallExpression"==e.parentPath.parentPath?.type?e.parentPath.replaceWith(i.identifier(`$${l}$DB$${r}$`)):"ObjectId"==r?e.parentPath.replaceWith(i.arrowFunctionExpression([],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[]))):"i"==r||"r"==r?e.parentPath.replaceWith(i.arrowFunctionExpression([i.identifier("a")],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[i.identifier("a")]))):e.parentPath.replaceWith(i.arrowFunctionExpression([i.identifier("a"),i.identifier("b")],i.callExpression(i.identifier(`$${l}$DB$${r}$`),[i.identifier("a"),i.identifier("b")])))}if($.scope.hasGlobal("$D"))for(const e of o("$D",$))"CallExpression"==e.parentPath.type?e.replaceWith(i.identifier(`$${l}$DEBUG$`)):e.replaceWith(i.arrowFunctionExpression([i.identifier("a")],i.callExpression(i.identifier(`$${l}$DEBUG$`),[i.identifier("a")])));if($.scope.hasGlobal("$FMCL"))for(const e of o("$FMCL",$))e.replaceWith(i.identifier(`$${l}$FMCL$`));if($.scope.hasGlobal("$G"))for(const e of o("$G",$))e.replaceWith(i.identifier(`$${l}$GLOBAL$`));if($.scope.hasGlobal("_SECLEVEL"))for(const e of o("_SECLEVEL",$))e.replaceWith(i.numericLiteral(f));let _=!1,u=!1;if($.scope.hasGlobal("Object"))for(const e of o("Object",$))"MemberExpression"!=e.parent.type||e.parent.computed||(t("Identifier"==e.parent.property.type),"getPrototypeOf"==e.parent.property.name?(e.parentPath.replaceWith(i.identifier(`_${l}_GET_PROTOTYPE_OF_`)),_=!0):"setPrototypeOf"==e.parent.property.name&&(e.parentPath.replaceWith(i.identifier(`_${l}_SET_PROTOTYPE_OF_`)),u=!0));const P=$.node.body.at(-1);let x;if(t(P,"program is empty"),"ExportNamedDeclaration"==P.type){$.node.body.pop();for(const e of P.specifiers){t("ExportSpecifier"==e.type,`${e.type} is currently unsupported`);const i="Identifier"==e.exported.type?e.exported.name:e.exported.value;"default"==i?x=e.local.name:y.set(e.local.name,i)}}const O=i.blockStatement([]);let D;for(const e of $.node.body)if("VariableDeclaration"==e.type)for(const t of e.declarations)if("Identifier"!=t.id.type||t.id.name!=x||!t.init||"FunctionExpression"!=t.init.type&&"ArrowFunctionExpression"!=t.init.type||t.init.async||t.init.generator){for(const r in i.getBindingIdentifiers(t.id))r==x&&(D=i.functionDeclaration(i.identifier(b),[i.identifier("context"),i.identifier("args")],i.blockStatement([i.returnStatement(i.callExpression(i.identifier(x),[]))]))),"const"!=e.kind&&y.has(r)&&(m.set(r,y.get(r)),y.delete(r)),O.body.push(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(r))]));t.init&&O.body.push(i.expressionStatement(i.assignmentExpression("=",t.id,t.init)))}else D=i.functionDeclaration(i.identifier(b),t.init.params,"BlockStatement"==t.init.body.type?t.init.body:i.blockStatement([i.returnStatement(t.init.body)]));else"FunctionDeclaration"==e.type?e.id.name==x?D=e:O.body.push(i.variableDeclaration("let",[i.variableDeclarator(e.id,i.functionExpression(void 0,e.params,e.body,e.generator,e.async))])):O.body.push(e);if(D||=i.functionDeclaration(i.identifier(b),[i.identifier("context"),i.identifier("args")],i.blockStatement([])),$.node.body=[D],O.body.length){(y.size||m.size)&&D.body.body.push(i.returnStatement(i.objectExpression([...[...y].map((([e,t])=>i.objectProperty(i.identifier(t),i.identifier(e)))),...[...m].map((([e,t])=>i.objectMethod("get",i.identifier(t),[],i.blockStatement([i.returnStatement(i.identifier(e))]))))]))),$.scope.crawl();const e=new Set;let n=0;for(const[o,a]of[...O.body.entries()].reverse())if("VariableDeclaration"==a.type){t(1==a.declarations.length);const s=a.declarations[0];if(t("Identifier"==s.id.type,`declarator.id.type was "${s.id.type}"`),$.scope.crawl(),$.scope.hasGlobal(s.id.name)){O.body.splice(o,1);const[p]=$.unshiftContainer("body",O),[c]=$.unshiftContainer("body",a);if($.scope.crawl(),!s.init||"FunctionExpression"!=s.init.type&&"ArrowFunctionExpression"!=s.init.type||Object.keys($.scope.globals).some((i=>e.has(i)))){const e=$.scope.getBinding(s.id.name);t(e);for(const r of e.referencePaths)t("Identifier"==r.node.type),r.replaceWith(i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(r.node.name)));for(const t of e.constantViolations)if("AssignmentExpression"==t.node.type)for(const[e,n]of Object.entries(i.getBindingIdentifiers(t.node)))e==s.id.name&&(r(n),Object.assign(n,i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(e))));p.remove(),c.remove(),s.init&&O.body.splice(o,0,i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(s.id.name)),s.init)))}else p.remove(),c.remove(),D.body.body.unshift(a),n++}else e.add(s.id.name)}else if("ClassDeclaration"==a.type&&($.scope.crawl(),t(a.id,"src/processScript/transform.ts:564:37"),$.scope.hasGlobal(a.id.name))){O.body.splice(o,1);const[e]=$.unshiftContainer("body",O),[r]=$.unshiftContainer("body",a);$.scope.crawl();const n=$.scope.getBinding(a.id.name);t(n);for(const e of n.referencePaths)t("Identifier"==e.node.type),e.replaceWith(i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(e.node.name)));e.remove(),r.remove(),O.body.splice(o,0,i.expressionStatement(i.assignmentExpression("=",i.memberExpression(i.identifier(`$${l}$GLOBAL$`),i.identifier(a.id.name)),i.classExpression(void 0,a.superClass,a.body,a.decorators))))}if($.scope.hasGlobal("_EXPORTS"))for(const e of o("_EXPORTS",$))e.replaceWith(i.arrayExpression([...y.keys(),...m.keys()].map((e=>i.stringLiteral(e)))));O.body.length&&D.body.body.splice(n,0,i.ifStatement(i.unaryExpression("!",i.identifier(`$${l}$FMCL$`)),O))}return h&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_FUNCTION_DOT_PROTOTYPE_`),createGetFunctionPrototypeNode())])),u&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_SET_PROTOTYPE_OF_`),i.callExpression(i.memberExpression(i.memberExpression(i.identifier("Object"),i.identifier("call")),i.identifier("bind")),[i.identifier(`_${l}_DUNDER_PROTO_SETTER_`)]))])),_&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_GET_PROTOTYPE_OF_`),i.callExpression(i.memberExpression(i.memberExpression(i.identifier("Object"),i.identifier("call")),i.identifier("bind")),[i.identifier(`_${l}_DUNDER_PROTO_GETTER_`)]))])),(_||u)&&D.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.objectPattern(_?u?[i.objectProperty(i.identifier("get"),i.identifier(`_${l}_DUNDER_PROTO_GETTER_`)),i.objectProperty(i.identifier("set"),i.identifier(`_${l}_DUNDER_PROTO_SETTER_`))]:[i.objectProperty(i.identifier("get"),i.identifier(`_${l}_DUNDER_PROTO_GETTER_`))]:[i.objectProperty(i.identifier("set"),i.identifier(`_${l}_DUNDER_PROTO_SETTER_`))]),i.callExpression(i.memberExpression(i.identifier("Object"),i.identifier("getOwnPropertyDescriptor")),[i.memberExpression(i.identifier("Object"),i.identifier("prototype")),i.stringLiteral("__proto__")]))])),a(e,{BlockStatement({node:e}){for(const[t,r]of e.body.entries())"FunctionDeclaration"!=r.type||r.generator||(e.body.splice(t,1),e.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(r.id,i.arrowFunctionExpression(r.params,r.body,r.async))])))},ClassBody({node:e,scope:r,parent:n}){t(i.isClass(n));let o=!1;for(const t of e.body){if("ClassMethod"!=t.type)continue;let e=!1;if(a(t.body,{ThisExpression(t){e=!0,o=!0,t.replaceWith(i.identifier(`_${l}_THIS_`))},Function(e){e.skip()}},r),e)if("constructor"!=t.kind)t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),i.callExpression(i.memberExpression(i.super(),i.identifier("valueOf")),[]))]));else{const e=[];if(a(t.body,{CallExpression(i){"Super"==i.node.callee.type&&e.push(i)}},r),e.length)if(1==e.length&&"ExpressionStatement"==e[0].parent.type&&e[0].parentPath.parentPath.parent==t)e[0].parentPath.replaceWith(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),e[0].node)]));else{for(const t of e)t.replaceWith(i.assignmentExpression("=",i.identifier(`_${l}_THIS_`),t.node));t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`))]))}else t.body.body.unshift(i.variableDeclaration("let",[i.variableDeclarator(i.identifier(`_${l}_THIS_`),i.callExpression(i.super(),[]))]))}}!n.superClass&&o&&(n.superClass=i.identifier("Object"))},VariableDeclaration({node:e}){"const"==e.kind&&(e.kind="let")},ThisExpression(e){e.replaceWith(i.identifier("undefined"))},BigIntLiteral(e){const t=Number(e.node.value);BigInt(t)==BigInt(e.node.value)?e.replaceWith(i.callExpression(i.identifier("BigInt"),[i.numericLiteral(t)])):e.replaceWith(i.callExpression(i.identifier("BigInt"),[i.stringLiteral(e.node.value)]))}}),{file:e,seclevel:f}};export{transform as default,transform};
package/pull.js CHANGED
@@ -1,17 +1 @@
1
- import { copyFilePersistent } from '@samual/lib/copyFilePersistent';
2
- import { resolve } from 'path';
3
-
4
- /**
5
- * Copies script from hackmud to local source folder.
6
- *
7
- * @param sourceFolderPath path to folder containing source files
8
- * @param hackmudPath path to hackmud directory
9
- * @param script to pull in `user.name` format
10
- */
11
- const pull = async (sourceFolderPath, hackmudPath, script) => {
12
- const [user, name] = script.split(`.`);
13
- if (!user || !name) throw new Error(`\`script\` argument must be in "user.name" format`);
14
- await copyFilePersistent(resolve(hackmudPath, user, `scripts`, `${name}.js`), resolve(sourceFolderPath, user, `${name}.js`));
15
- };
16
-
17
- export { pull as default, pull };
1
+ import{copyFilePersistent as t}from"@samual/lib/copyFilePersistent";import{resolve as r}from"path";const pull=async(s,a,i)=>{const[o,e]=i.split(".");if(!o||!e)throw new Error('`script` argument must be in "user.name" format');await t(r(a,o,"scripts",`${e}.js`),r(s,o,`${e}.js`))};export{pull as default,pull};