-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjs-code-view.js
More file actions
196 lines (185 loc) · 5.69 KB
/
js-code-view.js
File metadata and controls
196 lines (185 loc) · 5.69 KB
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
const markupTags = require("@saltcorn/markup/tags");
const View = require("@saltcorn/data/models/view");
const User = require("@saltcorn/data/models/user");
const File = require("@saltcorn/data/models/file");
const Workflow = require("@saltcorn/data/models/workflow");
const Table = require("@saltcorn/data/models/table");
const Trigger = require("@saltcorn/data/models/trigger");
const Form = require("@saltcorn/data/models/form");
const Field = require("@saltcorn/data/models/field");
const {
jsexprToWhere,
jsexprToSQL,
} = require("@saltcorn/data/models/expression");
const db = require("@saltcorn/data/db");
const { getState, features } = require("@saltcorn/data/db/state");
const { stateFieldsToWhere } = require("@saltcorn/data/plugin-helper");
const { mergeIntoWhere } = require("@saltcorn/data/utils");
const vm = require("vm");
const configuration_workflow = () =>
new Workflow({
steps: [
{
name: "Code",
form: () => {
return new Form({
fields: [
{
name: "code",
label: "Code",
input_type: "code",
attributes: { mode: "application/javascript" },
validator(s) {
try {
let AsyncFunction = Object.getPrototypeOf(
async function () {},
).constructor;
AsyncFunction(s);
return true;
} catch (e) {
return e.message;
}
},
},
{
name: "run_where",
label: "Run where",
input_type: "select",
options: ["Server", "Client page"],
},
],
});
},
},
],
});
const get_state_fields = () => [];
const run = async (
table_id,
viewname,
{ code, run_where },
state,
extraArgs,
queriesObj,
) => {
const table = Table.findOne(table_id);
if (run_where === "Client page") {
const rndid = Math.floor(Math.random() * 16777215).toString(16);
return (
markupTags.div({ id: `jsv${rndid}` }) +
markupTags.script(
markupTags.domReady(`
const out = (()=>{
${code}
})()
if(typeof out !== "undefined" && out !==null)
$('#jsv${rndid}').html(out);`),
)
);
}
return queriesObj?.runCodeQuery
? await queriesObj.runCodeQuery(state)
: await runCodeImpl({ code }, state, extraArgs.req);
};
const runCodeImpl = async ({ code }, state, req) => {
const user = req.user;
const Actions = {};
Object.entries(getState().actions).forEach(([k, v]) => {
Actions[k] = (args = {}) => {
v.run({ user, configuration: args, ...args });
};
});
const trigger_actions = await Trigger.find({
when_trigger: { or: ["API call", "Never"] },
});
for (const trigger of trigger_actions) {
const state_action = getState().actions[trigger.action];
Actions[trigger.name] = (args = {}) => {
state_action.run({
configuration: trigger.configuration,
user,
...args,
});
};
}
const emitEvent = (eventType, channel, payload) =>
Trigger.emitEvent(eventType, channel, user, payload);
const output = [];
const fakeConsole = {
log(...s) {
console.log(...s);
output.push([s, false]);
},
error(...s) {
console.error(...s);
output.push([s, true]);
},
};
try {
const f = vm.runInNewContext(`async () => {${code}\n}`, {
Table,
user,
console: fakeConsole,
Actions,
View,
User,
File,
emitEvent,
markupTags,
db,
req: req,
state,
...getState().function_context,
});
const runRes = await f();
if (output.length > 0 && typeof runRes === "string")
return (
runRes +
`<script>${output
.map(
([s, isError]) =>
`console.${isError ? "error" : "log"}(...${JSON.stringify(s)})`,
)
.join("\n")}</script>`
);
else return runRes;
} catch (err) {
if (output.length > 0)
err.message += `\n\nConsole output:\n\n${output
.map(([s, isError]) => s.map((x) => `${JSON.stringify(x)}`).join(" "))
.join("\n")}`;
throw err;
}
};
module.exports = {
name: "JsCodeView",
display_state_form: false,
tableless: true,
run,
get_state_fields,
configuration_workflow,
queries: ({ configuration: { code }, req }) => ({
async runCodeQuery(state) {
return await runCodeImpl({ code }, state, req);
},
}),
copilot_generate_view_prompt: getState().functions.copilot_standard_prompt
? async () => {
const table_prompt =
await getState().functions.copilot_standard_prompt.run({
language: "javascript",
has_table: true,
has_functions: true,
});
return `You are generating JavaScript code which will return the html to be displayed as a string.
The view can run in two different modes: Server and Client page.
in both cases, you write asyncronous code that returns an HTML string. you can use await at the top level.
The HTML you return will be inserted in an element on an existing page; do not include head and body tags.
If you select Client page mode, the code will run in the browser. You can use jQuery and bootstrap code.
If you select Server mode, you do not have access to the browser client environment, all code will be run
on the server. But you can access the database with the Table object. In this case there is no associated single table.
${table_prompt}
`;
}
: undefined,
};