Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support dots in identifiers #27

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
16 changes: 16 additions & 0 deletions lib/sheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ const wrap = (target) =>
},
});

const wrapValue = (target, path, prop) =>
new Proxy(target, {
get: (currentTarget, currentProp) => {
const targetProp = `${prop}.${currentProp}`;
if (target.data.has(targetProp)) return target.data.get(targetProp);
if (!path.startsWith(targetProp)) return undefined;

return wrapValue(currentTarget, path, targetProp);
},
});

const math = wrap(Math);

const getValue = (target, prop) => {
Expand All @@ -37,6 +48,11 @@ const setCell = (target, prop, value) => {
const options = { context: target.context };
const script = metavm.createScript(prop, src, options);
target.expressions.set(prop, script.exports);
} else if (prop.includes('.')) {
const rootKey = prop.substring(0, prop.indexOf('.'));
const proxyValue = wrapValue(target, prop, rootKey);
target.data.set(rootKey, proxyValue);
target.data.set(prop, value);
} else {
target.data.set(prop, value);
}
Expand Down
29 changes: 29 additions & 0 deletions test/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,35 @@ metatests.test('Correct cell values', async (test) => {
test.end();
});

metatests.test('Non-table identifiers', async (test) => {
const sheet = new Sheet();
sheet.cells['item1.price'] = 100;
sheet.cells['item2.price'] = 200;
sheet.cells['item3.price'] = 300;
sheet.cells['total'] = '=item1.price + item2.price + item3.price';
test.strictSame(sheet.values['total'], 600);

sheet.cells['item3'] = 42;
test.strictSame(sheet.values['item3'], 42);
test.strictSame(sheet.values['total'], NaN);

test.end();
});

metatests.test(
'Read undefined property in non-table identifier',
async (test) => {
const sheet = new Sheet();
sheet.cells['item.price'] = 100;
sheet.cells['item.quantity'] = 2;
sheet.cells['item.total'] =
'=item.price * item.quantity * (item.discount ?? 1)';
test.strictSame(sheet.values['item.total'], 200);

test.end();
},
);

metatests.test('Prevent arbitrary js code execution', async (test) => {
const sheet = new Sheet();

Expand Down