forked from OnsenManju/Jist
-
Notifications
You must be signed in to change notification settings - Fork 2
/
JistEngine.cs
executable file
·551 lines (477 loc) · 18.9 KB
/
JistEngine.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wolfje.Plugins.Jist.Framework;
using Jint;
using Jint.Native;
using System.Linq.Expressions;
using System.IO;
using TerrariaApi.Server;
using Jint.Runtime.Descriptors;
using Jint.Runtime;
using Jint.Native.Json;
using TShockAPI;
using Jint.Parser;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace Wolfje.Plugins.Jist
{
/// <summary>
/// Jist Engine, provides the Javascript engine to TerrariaServer
/// using the bundled Jint interpreter.
/// </summary>
public class JistEngine : IDisposable
{
protected JistPlugin plugin;
protected Jint.Engine jsEngine;
protected List<string> providedPackages;
protected ScriptContainer scriptContainer;
protected int totalLoadingItems = 0;
protected int doneItems = 0;
protected int oldPercent = 0;
internal event EventHandler<PercentChangedEventArgs> PercentChanged;
protected static string scriptsDir = Path.Combine(Environment.CurrentDirectory, "serverscripts");
protected readonly object syncRoot = new object();
/*
* Standard library references.
*
* These hold all the javascript functions that jist
* provides in its base packages.
*/
public stdlib.std stdLib;
public stdlib.tshock stdTshock;
public stdlib.stdtask stdTask;
public stdlib.stdhook stdHook;
public JistEngine(JistPlugin parent)
{
this.providedPackages = new List<string>();
this.plugin = parent;
this.scriptContainer = new ScriptContainer(this);
ServerApi.Hooks.GamePostInitialize.Register(plugin, Game_PostInitialize);
PercentChanged += (sender, args) => ConsoleEx.WriteBar(args);
}
public JistPlugin PluginInstance { get { return plugin; } }
/// <summary>
/// Occurs when TerrariaServer has loaded the map.
/// </summary>
protected async void Game_PostInitialize(EventArgs args)
{
await LoadEngineAsync();
}
protected void RaisePercentChangedEvent(string label)
{
PercentChangedEventArgs args = new PercentChangedEventArgs();
double percentComplete = (double)++doneItems / totalLoadingItems * 100;
if (oldPercent != (int)percentComplete)
{
args.Percent = (int)percentComplete;
args.Label = label;
if (PercentChanged != null)
{
PercentChanged(this, args);
}
oldPercent = (int)percentComplete;
}
}
public async Task LoadEngineAsync()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" * Jist is loading");
Console.ResetColor();
if (Directory.Exists(scriptsDir) == false)
{
try
{
Directory.CreateDirectory(scriptsDir);
}
catch
{
TShock.Log.ConsoleError("jist load: Could not create serverscripts directory");
return;
}
}
totalLoadingItems = ScriptsCount() * 2 + 5;
this.jsEngine = new Engine(o => o.AllowClr(typeof(Terraria.Main).Assembly,
typeof(TShockAPI.TShock).Assembly));
RaisePercentChangedEvent("Engine");
/*
* Load the standard library collection.
*/
await Task.Run(() => LoadLibraries());
RaisePercentChangedEvent("Libraries");
/*
* Enumerate the libraries and ask them to submit
* their functions to the javascript runtime. All
* functions should be available before any scripts
* load.
*/
await Task.Run(() => CreateScriptFunctions());
RaisePercentChangedEvent("Functions");
ExecuteHardCodedScripts();
/*
* Load all scripts from disk, and preprocess them.
* Result should be a reference-counted list of sc-
* ripts that need to be executed in order.
*/
await Task.Run(() => LoadScripts());
RaisePercentChangedEvent("Scripts");
/*
* Engine executes all scripts only once. The are
* responsible for setting themselves up in the JS
* global environment when this happens, subscrib-
* ing to hooks, enlisting aliases, etc.
*/
await Task.Run(() => ExecuteScripts());
RaisePercentChangedEvent("Execute");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" * Loaded {0} scripts", ScriptsCount());
Console.ResetColor();
Console.WriteLine();
}
protected void ExecuteHardCodedScripts()
{
lock (syncRoot)
jsEngine.Execute(@"dump = function(o) {
var s = '';
if (typeof(o) == 'undefined') return 'undefined';
if (typeof o.valueOf == 'undefined') return ""'valueOf()' is missing on '"" + (typeof o) + ""' - if you are inheriting from V8ManagedObject, make sure you are not blocking the property."";
if (typeof o.toString == 'undefined') return ""'toString()' is missing on '"" + o.valueOf() + ""' - if you are inheriting from V8ManagedObject, make sure you are not blocking the property."";
for (var p in o) {
var ov = '',
pv = '';
try {
ov = o.valueOf();
} catch (e) {
ov = '{error: ' + e.message + ': ' + dump(o) + '}';
}
try {
pv = o[p];
} catch (e) {
pv = e.message;
}
s += '* ' + ov + '.' + p + ' = (' + pv + ')\r\n';
}
return s;
}");
}
/// <summary>
/// Loads the standard library collection inside Jist, and binds all
/// the functions in it to the running javascript engine.
/// </summary>
protected void LoadLibraries()
{
LoadLibrary((stdLib = new stdlib.std(this)));
LoadLibrary((stdTshock = new stdlib.tshock(this)));
LoadLibrary((stdTask = new stdlib.stdtask(this)));
LoadLibrary((stdHook = new stdlib.stdhook(this)));
}
/// <summary>
/// Causes the instance of stdlib_base to submit all
/// its functions to the JS function cache.
/// </summary>
public void LoadLibrary(stdlib.stdlib_base lib)
{
if (lib == null)
{
return;
}
CreateScriptFunctions(lib.GetType(), lib);
}
protected int ScriptsCount()
{
try
{
return Directory.EnumerateFiles(scriptsDir, "*.js").Count();
}
catch
{
return 0;
}
}
/// <summary>
/// Loads all scripts from the serverscripts directory, and
/// inserts them into the script container.
/// </summary>
protected void LoadScripts()
{
foreach (var file in Directory.EnumerateFiles(scriptsDir, "*.js"))
{
LoadScript(Path.GetFileName(file));
RaisePercentChangedEvent("Scripts");
}
}
/// <summary>
/// Loads a script from file into a reference-counted object, and inserts it into
/// the script container.
///
/// Scripts are /not/ executed by the javascript engine at this point.
/// </summary>
public JistScript LoadScript(string ScriptPath, bool IncreaseRefCount = true)
{
JistScript content;
/*
* if this script has already been called for, return the called object
* with an incremented ref count
*/
if (scriptContainer.Scripts.Count(i =>
i.FilePathOrUri.Equals(ScriptPath, StringComparison.InvariantCultureIgnoreCase)) > 0)
{
content = scriptContainer.Scripts.FirstOrDefault(i =>
i.FilePathOrUri.Equals(ScriptPath, StringComparison.InvariantCultureIgnoreCase));
if (IncreaseRefCount)
{
content.ReferenceCount++;
}
return null;
}
content = new JistScript();
content.FilePathOrUri = ScriptPath;
content.ReferenceCount = 1;
try
{
content.Script = File.ReadAllText(Path.Combine(scriptsDir, content.FilePathOrUri));
}
catch (Exception ex)
{
ScriptLog.ErrorFormat("engine", "Cannot load {0}: {1}", ScriptPath, ex.Message);
return null;
}
/*
* Script must be added to the content list before preprocessing
* this is to prevent cyclic references between @imports, used as an include guard
*/
scriptContainer.PreprocessScript(content);
scriptContainer.Scripts.Add(content);
return content;
}
/// <summary>
/// Executes a snippet of javascript in the
/// running jist instance and returns any
/// result in JSON format.
/// </summary>
public string Eval(string snippet)
{
JsValue returnValue = default(JsValue);
if (jsEngine == null || string.IsNullOrEmpty(snippet) == true)
{
return "undefined";
}
try
{
lock (syncRoot)
returnValue = jsEngine.GetValue(jsEngine.Execute(snippet).GetCompletionValue());
if (returnValue.Type == Types.None
|| returnValue.Type == Types.Null
|| returnValue.Type == Types.Undefined)
{
return "undefined";
}
}
catch (JavaScriptException jex)
{
StringBuilder sb = new StringBuilder("JavaScript error: " + jex.Message + "\r\n");
//sb.AppendLine(string.Format(" at line {0} column {1}", jex.LineNumber, jex.Column));
//sb.AppendLine(jex.Location.Source);
sb.AppendLine(jex.StackTrace);
return sb.ToString();
}
catch (ParserException pex)
{
StringBuilder sb = new StringBuilder("JavaScript parser error: " + pex.Message + "\r\n");
sb.AppendLine(string.Format(" at line {0} column {1}", pex.LineNumber, pex.Column));
sb.AppendLine(pex.Source);
sb.AppendLine(pex.StackTrace);
return sb.ToString();
}
catch (Exception ex)
{
return ex.ToString();
}
if (string.IsNullOrEmpty(returnValue.ToString()) == true)
{
TShock.Log.ConsoleError("[jist eval] result of \"{0}\" is null", snippet);
return "undefined";
}
return returnValue.ToString();
}
/// <summary>
/// Executes a script, and returns it's completion value.
/// </summary>
public JsValue ExecuteScript(JistScript script)
{
if (script == null || string.IsNullOrEmpty(script.Script) == true)
{
return JsValue.Undefined;
}
try
{
lock (syncRoot)
return jsEngine.Execute(script.Script).GetCompletionValue();
}
catch (Exception ex)
{
ScriptLog.ErrorFormat(script.FilePathOrUri, "Execution error: " + ex.Message);
return JsValue.Undefined;
}
}
/// <summary>
/// Enumerates all scripts in the the container, and execute the
/// scripts that have the highest reference count first.
/// </summary>
protected void ExecuteScripts()
{
foreach (JistScript script in scriptContainer.Scripts.OrderByDescending(i => i.ReferenceCount))
{
try
{
ExecuteScript(script);
RaisePercentChangedEvent("Execute");
}
catch (Exception ex)
{
ScriptLog.ErrorFormat(script.FilePathOrUri, "Execution error: " + ex.Message);
}
}
}
/// <summary>
/// Creates Javascript function delegates for the type specified, and
/// optionally by the object instance.
///
/// Instance may be null, however only static methods will be created.
/// </summary>
public async Task CreateScriptFunctionsAsync(Type type, object instance)
{
await Task.Run(() => CreateScriptFunctions(type, instance));
}
/// <summary>
/// Creates Javascript function delegates for the type specified, and
/// optionally by the object instance.
///
/// Instance may be null, however only static methods will be regarded
/// in this manner, since there is no 'this' pointer.
/// </summary>
public void CreateScriptFunctions(Type type, object instance)
{
Delegate functionDelegate = null;
Type delegateSignature = null;
string functionName = null;
JavascriptFunctionAttribute jsAttribute = null;
/*
* If the class provides functionality for scripts,
* add it into the providedpackages array.
*/
foreach (JavascriptProvidesAttribute attrib in type.GetCustomAttributes(true).OfType<JavascriptProvidesAttribute>())
{
if (!providedPackages.Contains(attrib.PackageName))
{
providedPackages.Add(attrib.PackageName);
}
}
/*
* look for JS methods in the type
*/
foreach (var jsFunction in type.GetMethods().Where(i => i.GetCustomAttributes(true).OfType<JavascriptFunctionAttribute>().Any()))
{
if (instance == null && jsFunction.IsStatic == false
|| (jsAttribute = jsFunction.GetCustomAttributes(true).OfType<JavascriptFunctionAttribute>().FirstOrDefault()) == null)
{
continue;
}
foreach (string func in jsAttribute.FunctionNames)
{
functionName = func ?? jsFunction.Name;
try
{
/*
* A delegate signature type matching every single parameter type,
* and the return type must be appended as the very last item
* in the array.
*/
delegateSignature = Expression.GetDelegateType(jsFunction.GetParameters().Select(i => i.ParameterType)
.Concat(new[] { jsFunction.ReturnType }).ToArray());
if (instance != null)
{
functionDelegate = Delegate.CreateDelegate(delegateSignature, instance, jsFunction);
}
else {
functionDelegate = Delegate.CreateDelegate(delegateSignature, jsFunction);
}
lock (syncRoot)
jsEngine.SetValue(functionName, functionDelegate);
}
catch (Exception ex)
{
ScriptLog.ErrorFormat("engine", "Error whilst creating javascript function for {0}: {1}",
functionName, ex.ToString());
continue;
}
}
}
}
/// <summary>
/// Loops through all types in the app domain and creates functions in
/// the engine for methods that have a JavascriptFunction attribute.
/// </summary>
protected void CreateScriptFunctions()
{
JistPlugin.RequestExternalFunctions();
lock (syncRoot)
jsEngine.SetValue("alert", new Action<object>(Console.WriteLine));
}
/// <summary>
/// Calls a javascript function encapsulated by JsValue
/// and returns it's result.
/// </summary>
public JsValue CallFunction(JsValue function, object thisObject, params object[] args)
{
object t = thisObject ?? (object)this;
try
{
lock (syncRoot)
return function.Invoke(JsValue.FromObject(jsEngine, t), args.ToJsValueArray(jsEngine));
}
catch (JavaScriptException jex)
{
StringBuilder sb = new StringBuilder("JavaScript error: " + jex.Message + "\r\n");
sb.AppendLine(string.Format(" at line {0} column {1}", jex.LineNumber, jex.Column));
sb.AppendLine(jex.Location.Source);
sb.AppendLine(jex.StackTrace);
TShock.Log.ConsoleError(sb.ToString());
}
catch (ParserException pex)
{
StringBuilder sb = new StringBuilder("JavaScript parser error: " + pex.Message + "\r\n");
sb.AppendLine(string.Format(" at line {0} column {1}", pex.LineNumber, pex.Column));
sb.AppendLine(pex.Source);
sb.AppendLine(pex.StackTrace);
TShock.Log.ConsoleError(sb.ToString());
}
catch (Exception ex)
{
TShock.Log.ConsoleError(ex.ToString());
}
return JsValue.Undefined;
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.stdLib.Dispose();
this.stdTshock.Dispose();
this.stdTask.Dispose();
this.stdHook.Dispose();
ServerApi.Hooks.GamePostInitialize.Deregister(plugin, Game_PostInitialize);
}
}
#endregion
}
}