aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/Scripting.ts
blob: c67cc067a7874844278dad251cb5a00f0f744bcf (plain)
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
// import * as ts from "typescript"
let ts = (window as any).ts;
import { Opt, Field } from "../../fields/Field";
import { Document } from "../../fields/Document";
import { NumberField } from "../../fields/NumberField";
import { ImageField } from "../../fields/ImageField";
import { TextField } from "../../fields/TextField";
import { RichTextField } from "../../fields/RichTextField";
import { KeyStore } from "../../fields/KeyStore";
import { ListField } from "../../fields/ListField";
// // @ts-ignore
// import * as typescriptlib from '!!raw-loader!../../../node_modules/typescript/lib/lib.d.ts'
// // @ts-ignore
// import * as typescriptes5 from '!!raw-loader!../../../node_modules/typescript/lib/lib.es5.d.ts'

// @ts-ignore
import * as typescriptlib from '!!raw-loader!./type_decls.d';
import { Documents } from "../documents/Documents";
import { Key } from "../../fields/Key";

export interface ScriptSucccess {
    success: true;
    result: any;
}

export interface ScriptError {
    success: false;
    error: any;
}

export type ScriptResult = ScriptSucccess | ScriptError;

export interface CompiledScript {
    readonly compiled: true;
    readonly originalScript: string;
    readonly options: Readonly<ScriptOptions>;
    run(args?: { [name: string]: any }): ScriptResult;
}

export interface CompileError {
    compiled: false;
    errors: any[];
}

export type CompileResult = CompiledScript | CompileError;

function Run(script: string | undefined, customParams: string[], diagnostics: any[], originalScript: string, options: ScriptOptions): CompileResult {
    const errors = diagnostics.some(diag => diag.category === ts.DiagnosticCategory.Error);
    if (errors || !script) {
        return { compiled: false, errors: diagnostics };
    }

    let fieldTypes = [Document, NumberField, TextField, ImageField, RichTextField, ListField, Key];
    let paramNames = ["KeyStore", "Documents", ...fieldTypes.map(fn => fn.name)];
    let params: any[] = [KeyStore, Documents, ...fieldTypes];
    let compiledFunction = new Function(...paramNames, `return ${script}`);
    let { capturedVariables = {} } = options;
    let run = (args: { [name: string]: any } = {}): ScriptResult => {
        let argsArray: any[] = [];
        for (let name of customParams) {
            if (name === "this") {
                continue;
            }
            if (name in args) {
                argsArray.push(args[name]);
            } else {
                argsArray.push(capturedVariables[name]);
            }
        }
        let thisParam = args.this || capturedVariables.this;
        try {
            const result = compiledFunction.apply(thisParam, params).apply(thisParam, argsArray);
            return { success: true, result };
        } catch (error) {
            return { success: false, error };
        }
    };
    return { compiled: true, run, originalScript, options };
}

interface File {
    fileName: string;
    content: string;
}

// class ScriptingCompilerHost implements ts.CompilerHost {
class ScriptingCompilerHost {
    files: File[] = [];

    // getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError?: ((message: string) => void) | undefined, shouldCreateNewSourceFile?: boolean | undefined): ts.SourceFile | undefined {
    getSourceFile(fileName: string, languageVersion: any, onError?: ((message: string) => void) | undefined, shouldCreateNewSourceFile?: boolean | undefined): any | undefined {
        let contents = this.readFile(fileName);
        if (contents !== undefined) {
            return ts.createSourceFile(fileName, contents, languageVersion, true);
        }
        return undefined;
    }
    // getDefaultLibFileName(options: ts.CompilerOptions): string {
    getDefaultLibFileName(options: any): string {
        return 'node_modules/typescript/lib/lib.d.ts'; // No idea what this means...
    }
    writeFile(fileName: string, content: string) {
        const file = this.files.find(file => file.fileName === fileName);
        if (file) {
            file.content = content;
        } else {
            this.files.push({ fileName, content });
        }
    }
    getCurrentDirectory(): string {
        return '';
    }
    getCanonicalFileName(fileName: string): string {
        return this.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase();
    }
    useCaseSensitiveFileNames(): boolean {
        return true;
    }
    getNewLine(): string {
        return '\n';
    }
    fileExists(fileName: string): boolean {
        return this.files.some(file => file.fileName === fileName);
    }
    readFile(fileName: string): string | undefined {
        let file = this.files.find(file => file.fileName === fileName);
        if (file) {
            return file.content;
        }
        return undefined;
    }
}

export interface ScriptOptions {
    requiredType?: string;
    addReturn?: boolean;
    params?: { [name: string]: string };
    capturedVariables?: { [name: string]: Field };
}

export function CompileScript(script: string, options: ScriptOptions = {}): CompileResult {
    const { requiredType = "", addReturn = false, params = {}, capturedVariables = {} } = options;
    let host = new ScriptingCompilerHost;
    let paramNames: string[] = [];
    if ("this" in params || "this" in capturedVariables) {
        paramNames.push("this");
    }
    for (const key in params) {
        if (key === "this") continue;
        paramNames.push(key);
    }
    let paramList = paramNames.map(key => {
        const val = params[key];
        return `${key}: ${val}`;
    });
    for (const key in capturedVariables) {
        if (key === "this") continue;
        paramNames.push(key);
        paramList.push(`${key}: ${capturedVariables[key].constructor.name}`);
    }
    let paramString = paramList.join(", ");
    let funcScript = `(function(${paramString})${requiredType ? `: ${requiredType}` : ''} {
        ${addReturn ? `return ${script};` : script}
    })`;
    host.writeFile("file.ts", funcScript);
    host.writeFile('node_modules/typescript/lib/lib.d.ts', typescriptlib);
    let program = ts.createProgram(["file.ts"], {}, host);
    let testResult = program.emit();
    let outputText = host.readFile("file.js");

    let diagnostics = ts.getPreEmitDiagnostics(program).concat(testResult.diagnostics);

    return Run(outputText, paramNames, diagnostics, script, options);
}

export function OrLiteralType(returnType: string): string {
    return `${returnType} | string | number`;
}

export function ToField(data: any): Opt<Field> {
    if (typeof data === "string") {
        return new TextField(data);
    } else if (typeof data === "number") {
        return new NumberField(data);
    }
    return undefined;
}