formlab-mcp 0.6.77 → 0.6.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cloud.js +13 -2
- package/package.json +1 -1
- package/server.json +2 -2
- package/theoretical.js +4 -4
- package/vendor/cost.js +5 -5
- package/vendor/reactive.js +1 -1
- package/vendor/safe-expr.js +224 -0
- package/vendor/theoretical-params.js +3 -5
package/cloud.js
CHANGED
|
@@ -47,8 +47,15 @@ async function _fetchDb({ url, anonKey, token }) {
|
|
|
47
47
|
}
|
|
48
48
|
let body = null;
|
|
49
49
|
try { body = await res.json(); } catch { /* non-JSON error page */ }
|
|
50
|
+
if (res.status === 429) {
|
|
51
|
+
const e = new Error('the MCP endpoint asks for a short wait between full reads');
|
|
52
|
+
e.tooSoon = true;
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
50
55
|
if (res.status === 401) {
|
|
51
|
-
|
|
56
|
+
const e = new Error('the MCP token was rejected: it is missing, revoked or malformed, or the workspace owner has turned off AI tools for members. Reconnect from FormLab → Settings → Account → AI tools (MCP) → Connect, and paste the new FORMLAB_MCP_TOKEN.');
|
|
57
|
+
e.revoked = true;
|
|
58
|
+
throw e;
|
|
52
59
|
}
|
|
53
60
|
if (!res.ok || !body || body.ok !== true || !body.db) {
|
|
54
61
|
throw new Error(`MCP endpoint error (HTTP ${res.status})${body && body.error ? ': ' + body.error : ''}`);
|
|
@@ -84,6 +91,8 @@ export async function startCloud({ url, anonKey, token, refreshSeconds = 300, on
|
|
|
84
91
|
if (now() - loadedAt < maxAgeMs) return false;
|
|
85
92
|
if (!inflight) {
|
|
86
93
|
inflight = refresh().then(() => true, (e) => {
|
|
94
|
+
// Token ended (revoked, expired, the person left): the copy goes too, so nothing keeps answering from it.
|
|
95
|
+
if (e && e.revoked) { setStoreFromDb({}, { source: 'cloud', workspaceId, schemaName: 'formlab-live', loadedAt: new Date(now()).toISOString() }); loadedAt = now(); }
|
|
87
96
|
process.stderr.write(`[formlab-mcp] cloud refresh failed, answering from the copy loaded ${Math.round((now() - loadedAt) / 1000)} s ago: ${e.message}\n`);
|
|
88
97
|
return false;
|
|
89
98
|
}).finally(() => { inflight = null; });
|
|
@@ -91,6 +100,8 @@ export async function startCloud({ url, anonKey, token, refreshSeconds = 300, on
|
|
|
91
100
|
return inflight;
|
|
92
101
|
};
|
|
93
102
|
|
|
94
|
-
|
|
103
|
+
// A second copy started moments ago (Claude Desktop and Code): the endpoint asks for a short wait, once.
|
|
104
|
+
try { await refresh(); } catch (e) { if (!e.tooSoon) throw e; await new Promise((r) => setTimeout(r, 11000)); await refresh(); }
|
|
105
|
+
// initial load before tools accept calls (and an early, clear error for a bad token)
|
|
95
106
|
return { workspaceId, refresh, ensureFresh, stop: () => {} };
|
|
96
107
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "formlab-mcp",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.79",
|
|
4
4
|
"mcpName": "io.github.juliu1980/formlab-mcp",
|
|
5
5
|
"description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
|
|
6
6
|
"homepage": "https://formvix.com/mcp",
|
package/server.json
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
3
|
"name": "io.github.juliu1980/formlab-mcp",
|
|
4
4
|
"description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
|
|
5
|
-
"version": "0.6.
|
|
5
|
+
"version": "0.6.79",
|
|
6
6
|
"websiteUrl": "https://formvix.com/mcp",
|
|
7
7
|
"packages": [
|
|
8
8
|
{
|
|
9
9
|
"registryType": "npm",
|
|
10
10
|
"identifier": "formlab-mcp",
|
|
11
|
-
"version": "0.6.
|
|
11
|
+
"version": "0.6.79",
|
|
12
12
|
"runtimeHint": "npx",
|
|
13
13
|
"transport": {
|
|
14
14
|
"type": "stdio"
|
package/theoretical.js
CHANGED
|
@@ -8,15 +8,15 @@
|
|
|
8
8
|
// They run in a node:vm context that holds ONLY a JSON copy of the data: no
|
|
9
9
|
// host objects (whose prototype chain would lead back to this process), no
|
|
10
10
|
// require, no process. Formulas are shared workspace data and the engine
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// runs them through flSafeExpr (its own parser, never the JS engine). The vm is
|
|
12
|
+
// a second wall, so a formula from someone else's workspace can't reach this
|
|
13
|
+
// machine either way.
|
|
14
14
|
// =====================================================================
|
|
15
15
|
import { readFileSync } from 'node:fs';
|
|
16
16
|
import vm from 'node:vm';
|
|
17
17
|
|
|
18
18
|
const VENDOR = new URL('./vendor/', import.meta.url);
|
|
19
|
-
const FILES = ['cost.js', 'nesting.js', 'theoretical-params.js', 'reactive.js']; // reactive.js: ing.epoxy … ing.vinyl for the Reactive presets
|
|
19
|
+
const FILES = ['safe-expr.js', 'cost.js', 'nesting.js', 'theoretical-params.js', 'reactive.js']; // reactive.js: ing.epoxy … ing.vinyl for the Reactive presets
|
|
20
20
|
let _source = null;
|
|
21
21
|
function source() {
|
|
22
22
|
if (!_source) _source = FILES.map(f => readFileSync(new URL(f, VENDOR), 'utf8')).join('\n;\n');
|
package/vendor/cost.js
CHANGED
|
@@ -1994,7 +1994,7 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
|
|
|
1994
1994
|
` <span style="font-size:9.5px;color:var(--dk-amber-fg, #b45309);font-weight:600;background:var(--dk-amber-bg, #fffbeb);border:1px solid var(--dk-amber-line, #fde68a);border-radius:4px;padding:0 3px;vertical-align:middle;white-space:nowrap" title="Lot ${esc(String(r.lotDev.lotNumber))} assays ${esc(String(+r.lotDev.lotPurity))}% but the weigh-out is grossed up on the nominal ${esc(String(+r.lotDev.nominal))}%. ${r.lotDev.consumed ? 'This batch drew from that lot.' : 'FIFO will draw from that lot next.'} To deliver the spec active at the lot's assay, weigh ${r.lotDev.correctedAmount != null ? esc(_rNumFmt(r.lotDev.correctedAmount)) + ' ' + esc(String(displayUnit || w.unit || '')) : 'the corrected amount'} instead.">⚠ lot ${esc(String(+r.lotDev.lotPurity))}% vs ${esc(String(+r.lotDev.nominal))}%${r.lotDev.correctedAmount != null ? ' → ' + esc(_rNumFmt(r.lotDev.correctedAmount)) : ''}</span>`);
|
|
1995
1995
|
const _woVolTarget = (typeof isVolUnit === 'function') && isVolUnit(w.unit);
|
|
1996
1996
|
const qsTag = r => (!r.qs) ? '' :
|
|
1997
|
-
` <span style="font-size:9.5px;color:var(--dk-sky-fg, #0369a1);font-weight:600;background:var(--dk-blue-bg, #eff6ff);border:1px solid var(--dk-blue-line, #bfdbfe);border-radius:4px;padding:0 3px;vertical-align:middle;white-space:nowrap" title="${_woVolTarget ? `Balance ingredient — add it up to the ${w.qty} ${esc(w.unit)} mark rather than to this number, then log what actually went in` : 'Balance ingredient, set to hold the batch at its target size'}">${_woVolTarget ? `q.s. to ${w.qty} ${esc(w.unit)}` : 'q.s.'}</span>`;
|
|
1997
|
+
` <span style="font-size:9.5px;color:var(--dk-sky-fg, #0369a1);font-weight:600;background:var(--dk-blue-bg, #eff6ff);border:1px solid var(--dk-blue-line, #bfdbfe);border-radius:4px;padding:0 3px;vertical-align:middle;white-space:nowrap" title="${_woVolTarget ? `Balance ingredient — add it up to the ${esc(w.qty)} ${esc(w.unit)} mark rather than to this number, then log what actually went in` : 'Balance ingredient, set to hold the batch at its target size'}">${_woVolTarget ? `q.s. to ${esc(w.qty)} ${esc(w.unit)}` : 'q.s.'}</span>`;
|
|
1998
1998
|
const dColor = rel => rel == null ? 'var(--dk-faint, #94a3b8)' : (rel < 0.02 ? 'var(--dk-green-fg, #15803d)' : rel < 0.10 ? 'var(--dk-amber-fg, #b45309)' : 'var(--dk-red-fg, #b91c1c)');
|
|
1999
1999
|
// Tint a whole row when it deviates, so off-plan ingredients pop at a glance
|
|
2000
2000
|
// (matches the composition-% table's row tinting). On-target rows stay white.
|
|
@@ -2092,13 +2092,13 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
|
|
|
2092
2092
|
return (inAlt != null && isFinite(inAlt)) ? `<strong>${fmt(inAlt)}</strong> <span translate="no" style="color:var(--dk-faint, #94a3b8);font-size:10px">${esc(altUnit)}</span>` : null;
|
|
2093
2093
|
})();
|
|
2094
2094
|
const tfoot = `<tr style="border-top:1px solid #dbeafe">
|
|
2095
|
-
<td></td><td style="padding:5px 8px;font-weight:600">Total${_volTarget ? ` <span style="font-weight:400;color:var(--dk-faint, #94a3b8);font-size:10.5px" title="Sum of the pure-ingredient volumes in the Planned column. Not a lab quantity — the finished batch is ${w.qty} ${esc(w.unit)}; the mass in the ≈ column is what the batch weighs.">(pure-ingredient volumes)</span>` : ''}</td>
|
|
2096
|
-
<td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:${_volTarget ? 400 : 700};color:${_volTarget ? 'var(--dk-faint, #94a3b8)' : 'inherit'}" title="${_volTarget ? `Volumes aren't additive on mixing — this sum has no bench meaning. Finished batch: ${w.qty} ${esc(w.unit)}.` : ''}">${cv(w.total)}</td>
|
|
2095
|
+
<td></td><td style="padding:5px 8px;font-weight:600">Total${_volTarget ? ` <span style="font-weight:400;color:var(--dk-faint, #94a3b8);font-size:10.5px" title="Sum of the pure-ingredient volumes in the Planned column. Not a lab quantity — the finished batch is ${esc(w.qty)} ${esc(w.unit)}; the mass in the ≈ column is what the batch weighs.">(pure-ingredient volumes)</span>` : ''}</td>
|
|
2096
|
+
<td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:${_volTarget ? 400 : 700};color:${_volTarget ? 'var(--dk-faint, #94a3b8)' : 'inherit'}" title="${_volTarget ? `Volumes aren't additive on mixing — this sum has no bench meaning. Finished batch: ${esc(w.qty)} ${esc(w.unit)}.` : ''}">${cv(w.total)}</td>
|
|
2097
2097
|
${hasActuals ? `<td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;font-weight:700">${cv(actualTotal)}</td>
|
|
2098
2098
|
<td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums;color:var(--dk-muted, #64748b)">${cvs(totalDelta)}</td>` : ''}
|
|
2099
2099
|
<td style="padding:5px 8px;color:var(--dk-muted, #64748b)">${esc(displayUnit)}</td>
|
|
2100
2100
|
${_altAny ? (_totalMassCell
|
|
2101
|
-
? `<td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums" title="Total mass of the finished ${w.qty} ${esc(w.unit)} = volume × finished density. This is what the batch weighs — the number to reconcile the balance against.">${_totalMassCell}</td>`
|
|
2101
|
+
? `<td style="padding:5px 8px;text-align:right;font-variant-numeric:tabular-nums" title="Total mass of the finished ${esc(w.qty)} ${esc(w.unit)} = volume × finished density. This is what the batch weighs — the number to reconcile the balance against.">${_totalMassCell}</td>`
|
|
2102
2102
|
: `<td style="padding:5px 8px;text-align:right;color:var(--dk-dim, #cbd5e1)" title="No total — the ${esc(_altDim || '')} equivalent isn't additive across ingredients">—</td>`) : ''}
|
|
2103
2103
|
</tr>`;
|
|
2104
2104
|
const densityNote = w.anyNull
|
|
@@ -2125,7 +2125,7 @@ function renderWeighoutPanel(w, actuals, formula, copyOnclick, noun) {
|
|
|
2125
2125
|
const bal = (_qsRow.amount != null && isFinite(_qsRow.amount)) ? _qsRow.amount : null;
|
|
2126
2126
|
const balMass = (bal != null && typeof convertQuantity === 'function' && _qsRow.comp && _qsRow.comp.ingredientId)
|
|
2127
2127
|
? (() => { const ing = (db.ingredients || []).find(i => i.id === _qsRow.comp.ingredientId); const d = ing ? _densityToKgPerL(ing.density, ing.densityUnit) : null; return (d && VOL_TO_L[w.unit]) ? bal * VOL_TO_L[w.unit] * d * 1000 : null; })() : null;
|
|
2128
|
-
makeUpNote = `<div style="margin-top:7px;padding:7px 10px;background:var(--dk-sky-bg, #f0f9ff);border:1px solid var(--dk-sky-line, #bae6fd);border-radius:6px;font-size:11.5px;color:var(--dk-sky-fg, #0c4a6e);line-height:1.45"><strong>Make up to volume.</strong> Weigh the other rows as planned, then add <strong>${esc(_qsRow.name)}</strong> up to the <strong>${w.qty} ${esc(w.unit)}</strong> mark and log the amount that actually went in${balMass != null ? ` (planned ≈ ${+balMass.toFixed(1)} g)` : ''}. Volumes aren't additive, so the mark — not the planned number — decides the balance. Once logged, the batch page derives the finished density from the total mass ÷ ${w.qty} ${esc(w.unit)} and offers to save it on the formula for next time.</div>`;
|
|
2128
|
+
makeUpNote = `<div style="margin-top:7px;padding:7px 10px;background:var(--dk-sky-bg, #f0f9ff);border:1px solid var(--dk-sky-line, #bae6fd);border-radius:6px;font-size:11.5px;color:var(--dk-sky-fg, #0c4a6e);line-height:1.45"><strong>Make up to volume.</strong> Weigh the other rows as planned, then add <strong>${esc(_qsRow.name)}</strong> up to the <strong>${esc(w.qty)} ${esc(w.unit)}</strong> mark and log the amount that actually went in${balMass != null ? ` (planned ≈ ${+balMass.toFixed(1)} g)` : ''}. Volumes aren't additive, so the mark — not the planned number — decides the balance. Once logged, the batch page derives the finished density from the total mass ÷ ${esc(w.qty)} ${esc(w.unit)} and offers to save it on the formula for next time.</div>`;
|
|
2129
2129
|
}
|
|
2130
2130
|
const title = hasActuals ? '⚖ Weigh-out — planned vs actual amounts' : '⚖ Weigh-out — target amounts';
|
|
2131
2131
|
// One-line explainer so this table's job (concrete amounts) is unmistakable
|
package/vendor/reactive.js
CHANGED
|
@@ -396,7 +396,7 @@ function _flRxSolveRowHtml(f, st) {
|
|
|
396
396
|
const outRange = (lo != null && r.amount < lo) || (hi != null && r.amount > hi);
|
|
397
397
|
const total = comp.reduce((s, x, i) => s + (i === st.row ? r.amount : i === r.qsIdx ? r.qsAmount : (_flRxNum(x.amount) || 0)), 0);
|
|
398
398
|
// The amounts as typed (18.05 → 20.06), not rounded to three figures: both sides of the arrow read alike.
|
|
399
|
-
out = `${esc(_flRxRowName(c))} ${+r.from} → <b>${r.amount}</b> ${unit} <span class="fl-rx-dim">(${d >= 0 ? '+' : ''}${+d.toFixed(4)})</span>`
|
|
399
|
+
out = `${esc(_flRxRowName(c))} ${+r.from} → <b>${esc(r.amount)}</b> ${unit} <span class="fl-rx-dim">(${d >= 0 ? '+' : ''}${+d.toFixed(4)})</span>`
|
|
400
400
|
+ (r.qsIdx >= 0 ? ` <span class="fl-rx-dim">· ${esc(_flRxRowName(comp[r.qsIdx]))} ${+r.qsFrom} → ${r.qsAmount}</span>` : '')
|
|
401
401
|
+ ` <span class="fl-rx-dim">· total ${+total.toFixed(2)}</span>`
|
|
402
402
|
+ (() => { const k = flRxKitRatio(comp.map((x, i) => (i === st.row ? { ...x, amount: r.amount } : i === r.qsIdx ? { ...x, amount: r.qsAmount } : x))); return k ? ` <span class="fl-rx-dim">· mix ${_flRxRatioText(k.weight)}</span>` : ''; })()
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// flSafeExpr: evaluates the small expression languages (theoretical-parameter formulas, smart search, computed columns)
|
|
2
|
+
// WITHOUT handing text to the JavaScript engine. Those expressions are shared workspace data that run in every member's
|
|
3
|
+
// browser, and each earlier guard was a filter in front of `new Function`: a filter reads text one way and the engine
|
|
4
|
+
// another, so a gap between them was code execution on the lab origin (B21, then the security review of 5 Nov: a
|
|
5
|
+
// comment hid code from the filter). Here there is no second reading. This file tokenizes, parses and runs the
|
|
6
|
+
// expression itself, so nothing outside the grammar below can happen:
|
|
7
|
+
// literals (decimal numbers, quoted strings, true false null undefined NaN Infinity), [a, b] lists, names the caller
|
|
8
|
+
// passed in, x.y x?.y x[y], name(…) calls of a passed-in function, x => … , ! - +, * / % **, + -, < <= > >=,
|
|
9
|
+
// == != === !==, && || ??, ? :
|
|
10
|
+
// No comments, no regex, no templates, no assignment, no `new`, no statements. A call's target must be a name the
|
|
11
|
+
// caller passed in (or Math.fn when asked for), so a value can never be called. Reading a member never returns a
|
|
12
|
+
// function, and never reaches the prototype machinery.
|
|
13
|
+
// Kept dependency-free: mcp/vendor and kiosk/vendor hold exact copies.
|
|
14
|
+
const _FL_SX_BLOCKED = new Set(['constructor', '__proto__', 'prototype', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__']);
|
|
15
|
+
const _FL_SX_LITERALS = { true: true, false: false, null: null, undefined: undefined, NaN: NaN, Infinity: Infinity };
|
|
16
|
+
const _FL_SX_MATH = (() => {
|
|
17
|
+
const m = Object.create(null);
|
|
18
|
+
for (const k of Object.getOwnPropertyNames(Math)) m[k] = Math[k];
|
|
19
|
+
return Object.freeze(m);
|
|
20
|
+
})();
|
|
21
|
+
|
|
22
|
+
function _flSxTokens(src) {
|
|
23
|
+
const out = [], s = String(src), n = s.length;
|
|
24
|
+
const OPS = ['===', '!==', '**', '=>', '==', '!=', '<=', '>=', '&&', '||', '??', '?.', '+', '-', '*', '/', '%', '<', '>', '!', '?', ':', '(', ')', '[', ']', ',', '.'];
|
|
25
|
+
let i = 0;
|
|
26
|
+
while (i < n) {
|
|
27
|
+
const c = s[i];
|
|
28
|
+
if (/\s/.test(c)) { i++; continue; }
|
|
29
|
+
if (c === '"' || c === "'") {
|
|
30
|
+
let j = i + 1, v = '';
|
|
31
|
+
for (;;) {
|
|
32
|
+
if (j >= n) throw new Error('A quote is never closed');
|
|
33
|
+
const d = s[j];
|
|
34
|
+
if (d === c) break;
|
|
35
|
+
if (d === '\n') throw new Error('A quote is never closed');
|
|
36
|
+
if (d === '\\') {
|
|
37
|
+
const e = s[j + 1];
|
|
38
|
+
if (e === undefined) throw new Error('A quote is never closed');
|
|
39
|
+
if (e === 'u' && /^[0-9a-fA-F]{4}$/.test(s.slice(j + 2, j + 6))) { v += String.fromCharCode(parseInt(s.slice(j + 2, j + 6), 16)); j += 6; continue; }
|
|
40
|
+
v += ({ n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0' })[e] ?? e;
|
|
41
|
+
j += 2; continue;
|
|
42
|
+
}
|
|
43
|
+
v += d; j++;
|
|
44
|
+
}
|
|
45
|
+
out.push({ t: 'str', v }); i = j + 1; continue;
|
|
46
|
+
}
|
|
47
|
+
const num = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(s.slice(i, i + 64));
|
|
48
|
+
if (num) { out.push({ t: 'num', v: Number(num[0]) }); i += num[0].length; continue; }
|
|
49
|
+
const id = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(s.slice(i, i + 256));
|
|
50
|
+
if (id) { out.push({ t: 'id', v: id[0] }); i += id[0].length; continue; }
|
|
51
|
+
const op = OPS.find(o => s.startsWith(o, i));
|
|
52
|
+
if (!op) throw new Error(`"${c}" can't be used here`);
|
|
53
|
+
// `/*` and `//` are not in this language: a comment is how code once hid from a filter.
|
|
54
|
+
if (op === '/' && (s[i + 1] === '*' || s[i + 1] === '/')) throw new Error('Comments aren\'t part of this language');
|
|
55
|
+
out.push({ t: 'op', v: op }); i += op.length;
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function _flSxParse(src, names, nsNames) {
|
|
61
|
+
const toks = _flSxTokens(src);
|
|
62
|
+
let p = 0, depth = 0;
|
|
63
|
+
const peek = (v) => { const t = toks[p]; return !!t && t.t === 'op' && t.v === v; };
|
|
64
|
+
const eat = (v) => { if (peek(v)) { p++; return true; } return false; };
|
|
65
|
+
const need = (v) => { if (!eat(v)) throw new Error(`Expected "${v}"`); };
|
|
66
|
+
const enter = () => { if (++depth > 200) throw new Error('Too deeply nested'); };
|
|
67
|
+
|
|
68
|
+
// The compiled form: closures over an environment (no prototype, so a name can't resolve to anything inherited).
|
|
69
|
+
const member = (obj, key) => {
|
|
70
|
+
if (obj == null) throw new TypeError('Cannot read a member of nothing');
|
|
71
|
+
const k = typeof key === 'symbol' ? '' : String(key);
|
|
72
|
+
if (_FL_SX_BLOCKED.has(k)) return undefined;
|
|
73
|
+
const v = obj[k];
|
|
74
|
+
return typeof v === 'function' ? undefined : v;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
function primary(scope) {
|
|
78
|
+
const t = toks[p];
|
|
79
|
+
if (!t) throw new Error('The expression ends too soon');
|
|
80
|
+
if (t.t === 'num' || t.t === 'str') { p++; const v = t.v; return () => v; }
|
|
81
|
+
if (t.t === 'id') {
|
|
82
|
+
p++;
|
|
83
|
+
const name = t.v;
|
|
84
|
+
if (peek('=>')) { p++; return arrow([name], scope); }
|
|
85
|
+
if (peek('(')) {
|
|
86
|
+
if (!scope.has(name)) throw new Error(`"${name}" isn't part of this language`);
|
|
87
|
+
return call(name, null, scope);
|
|
88
|
+
}
|
|
89
|
+
if (nsNames.has(name) && peek('.') && toks[p + 1] && toks[p + 1].t === 'id' && toks[p + 2] && toks[p + 2].t === 'op' && toks[p + 2].v === '(') {
|
|
90
|
+
p++;
|
|
91
|
+
const fn = toks[p++].v;
|
|
92
|
+
return call(name, fn, scope);
|
|
93
|
+
}
|
|
94
|
+
if (scope.has(name)) return (env) => env[name];
|
|
95
|
+
if (Object.prototype.hasOwnProperty.call(_FL_SX_LITERALS, name)) { const v = _FL_SX_LITERALS[name]; return () => v; }
|
|
96
|
+
throw new Error(`"${name}" isn't part of this language`);
|
|
97
|
+
}
|
|
98
|
+
if (eat('(')) {
|
|
99
|
+
// (r) => … is the one parenthesised form that isn't a group.
|
|
100
|
+
if (toks[p] && toks[p].t === 'id' && toks[p + 1] && toks[p + 1].t === 'op' && toks[p + 1].v === ')' && toks[p + 2] && toks[p + 2].t === 'op' && toks[p + 2].v === '=>') {
|
|
101
|
+
const nm = toks[p].v; p += 3;
|
|
102
|
+
return arrow([nm], scope);
|
|
103
|
+
}
|
|
104
|
+
const e = expr(scope);
|
|
105
|
+
need(')');
|
|
106
|
+
return e;
|
|
107
|
+
}
|
|
108
|
+
if (eat('[')) {
|
|
109
|
+
const items = [];
|
|
110
|
+
if (!peek(']')) do { items.push(expr(scope)); } while (eat(','));
|
|
111
|
+
need(']');
|
|
112
|
+
return (env) => items.map(f => f(env));
|
|
113
|
+
}
|
|
114
|
+
throw new Error(`"${t.v}" can't be used here`);
|
|
115
|
+
}
|
|
116
|
+
function arrow(params, scope) {
|
|
117
|
+
const inner = new Set(scope); params.forEach(a => inner.add(a));
|
|
118
|
+
const body = expr(inner), name = params[0];
|
|
119
|
+
return (env) => (a) => { const e = Object.create(env); e[name] = a; return body(e); };
|
|
120
|
+
}
|
|
121
|
+
function call(name, method, scope) {
|
|
122
|
+
need('(');
|
|
123
|
+
const args = [];
|
|
124
|
+
if (!peek(')')) do { args.push(expr(scope)); } while (eat(','));
|
|
125
|
+
need(')');
|
|
126
|
+
if (method != null) {
|
|
127
|
+
return (env) => {
|
|
128
|
+
const ns = env[name], f = ns && !_FL_SX_BLOCKED.has(method) ? ns[method] : null;
|
|
129
|
+
if (typeof f !== 'function') throw new TypeError(`${name}.${method} isn't available`);
|
|
130
|
+
return f(...args.map(a => a(env)));
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
return (env) => {
|
|
134
|
+
const f = env[name];
|
|
135
|
+
if (typeof f !== 'function') throw new TypeError(`${name} can't be called`);
|
|
136
|
+
return f(...args.map(a => a(env)));
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function postfix(scope) {
|
|
140
|
+
let e = primary(scope);
|
|
141
|
+
for (;;) {
|
|
142
|
+
if (peek('.') || peek('?.')) {
|
|
143
|
+
const opt = toks[p].v === '?.'; p++;
|
|
144
|
+
if (opt && eat('[')) {
|
|
145
|
+
const k = expr(scope); need(']');
|
|
146
|
+
const o = e; e = (env) => { const v = o(env); return v == null ? undefined : member(v, k(env)); };
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const t = toks[p++];
|
|
150
|
+
if (!t || t.t !== 'id') throw new Error('Expected a name after "."');
|
|
151
|
+
const o = e, k = t.v;
|
|
152
|
+
e = opt ? (env) => { const v = o(env); return v == null ? undefined : member(v, k); } : (env) => member(o(env), k);
|
|
153
|
+
} else if (eat('[')) {
|
|
154
|
+
const k = expr(scope); need(']');
|
|
155
|
+
const o = e; e = (env) => member(o(env), k(env));
|
|
156
|
+
} else if (peek('(')) {
|
|
157
|
+
throw new Error('A value can\'t be called like a function');
|
|
158
|
+
} else return e;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function unary(scope) {
|
|
162
|
+
enter();
|
|
163
|
+
let r;
|
|
164
|
+
if (eat('!')) { const a = unary(scope); r = (env) => !a(env); }
|
|
165
|
+
else if (eat('-')) { const a = unary(scope); r = (env) => -a(env); }
|
|
166
|
+
else if (eat('+')) { const a = unary(scope); r = (env) => +a(env); }
|
|
167
|
+
else {
|
|
168
|
+
const a = postfix(scope);
|
|
169
|
+
if (eat('**')) { const b = unary(scope); r = (env) => a(env) ** b(env); } else r = a;
|
|
170
|
+
}
|
|
171
|
+
depth--;
|
|
172
|
+
return r;
|
|
173
|
+
}
|
|
174
|
+
const BINARY = [
|
|
175
|
+
['??'], ['||'], ['&&'], ['==', '!=', '===', '!=='], ['<', '<=', '>', '>='], ['+', '-'], ['*', '/', '%'],
|
|
176
|
+
];
|
|
177
|
+
const APPLY = {
|
|
178
|
+
'==': (a, b) => a == b, '!=': (a, b) => a != b, '===': (a, b) => a === b, '!==': (a, b) => a !== b, // eslint-disable-line eqeqeq
|
|
179
|
+
'<': (a, b) => a < b, '<=': (a, b) => a <= b, '>': (a, b) => a > b, '>=': (a, b) => a >= b,
|
|
180
|
+
'+': (a, b) => a + b, '-': (a, b) => a - b, '*': (a, b) => a * b, '/': (a, b) => a / b, '%': (a, b) => a % b,
|
|
181
|
+
};
|
|
182
|
+
function binary(level, scope) {
|
|
183
|
+
if (level >= BINARY.length) return unary(scope);
|
|
184
|
+
let left = binary(level + 1, scope);
|
|
185
|
+
for (;;) {
|
|
186
|
+
const t = toks[p];
|
|
187
|
+
if (!t || t.t !== 'op' || !BINARY[level].includes(t.v)) return left;
|
|
188
|
+
p++;
|
|
189
|
+
const a = left, b = binary(level + 1, scope), op = t.v;
|
|
190
|
+
if (op === '&&') left = (env) => a(env) && b(env);
|
|
191
|
+
else if (op === '||') left = (env) => a(env) || b(env);
|
|
192
|
+
else if (op === '??') left = (env) => a(env) ?? b(env);
|
|
193
|
+
else { const f = APPLY[op]; left = (env) => f(a(env), b(env)); }
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function expr(scope) {
|
|
197
|
+
enter();
|
|
198
|
+
const test = binary(0, scope);
|
|
199
|
+
let r = test;
|
|
200
|
+
if (eat('?')) {
|
|
201
|
+
const a = expr(scope); need(':'); const b = expr(scope);
|
|
202
|
+
r = (env) => (test(env) ? a(env) : b(env));
|
|
203
|
+
}
|
|
204
|
+
depth--;
|
|
205
|
+
return r;
|
|
206
|
+
}
|
|
207
|
+
const root = expr(new Set(names));
|
|
208
|
+
if (p < toks.length) throw new Error(`"${toks[p].v}" can't be used here`);
|
|
209
|
+
return root;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Compiles `src` once; the result takes one argument per name in `params`. Throws on anything outside the language.
|
|
213
|
+
// opts.math: `Math.fn(…)` and `Math.PI` become available.
|
|
214
|
+
function flSafeExpr(src, params, opts) {
|
|
215
|
+
const names = (params || []).slice(), ns = new Set();
|
|
216
|
+
if (opts && opts.math) { names.push('Math'); ns.add('Math'); }
|
|
217
|
+
const body = _flSxParse(src, names, ns);
|
|
218
|
+
return (...args) => {
|
|
219
|
+
const env = Object.create(null);
|
|
220
|
+
(params || []).forEach((n, i) => { env[n] = args[i]; });
|
|
221
|
+
if (opts && opts.math) env.Math = _FL_SX_MATH;
|
|
222
|
+
return body(env);
|
|
223
|
+
};
|
|
224
|
+
}
|
|
@@ -89,12 +89,10 @@ function _tpCompile(formula) {
|
|
|
89
89
|
// answers own fields only — _tpIngredientView).
|
|
90
90
|
_tpCheckNames(src);
|
|
91
91
|
|
|
92
|
-
// 4. Compile
|
|
93
|
-
//
|
|
92
|
+
// 4. Compile. flSafeExpr parses and runs the formula itself; nothing reaches the JS engine (js/safe-expr.js: the
|
|
93
|
+
// checks above give readable messages, this is what makes it safe). Any syntax error surfaces with a message.
|
|
94
94
|
try {
|
|
95
|
-
|
|
96
|
-
return new Function('SUM', 'AVG', 'MEAN', 'MIN', 'MAX', 'COUNT', 'PI', 'E', '_tpNum', '_tpHas', 'IF', '_tpCmp',
|
|
97
|
-
`"use strict"; return (${src});`);
|
|
95
|
+
return flSafeExpr(src, ['SUM', 'AVG', 'MEAN', 'MIN', 'MAX', 'COUNT', 'PI', 'E', '_tpNum', '_tpHas', 'IF', '_tpCmp']);
|
|
98
96
|
} catch (e) {
|
|
99
97
|
throw new Error(`Parse error: ${e.message}`);
|
|
100
98
|
}
|