From 44c43e3c0a6f02018792686732c0fd1edd3ccbc0 Mon Sep 17 00:00:00 2001 From: Oliver Eyton-Williams Date: Mon, 10 Mar 2025 06:54:37 +0100 Subject: [PATCH] refactor: simplify test-evaluator (#59037) --- .../browser-scripts/test-evaluator.ts | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/tools/client-plugins/browser-scripts/test-evaluator.ts b/tools/client-plugins/browser-scripts/test-evaluator.ts index 1508457a3bf..3dd42108cc3 100644 --- a/tools/client-plugins/browser-scripts/test-evaluator.ts +++ b/tools/client-plugins/browser-scripts/test-evaluator.ts @@ -1,6 +1,6 @@ import chai from 'chai'; import { toString as __toString } from 'lodash-es'; -import * as helpers from '@freecodecamp/curriculum-helpers'; +import * as curriculumHelpers from '@freecodecamp/curriculum-helpers'; import { format as __format } from './utils/format'; const ctx: Worker & typeof globalThis = self as unknown as Worker & @@ -80,10 +80,23 @@ const __utils = (() => { }; })(); -// We freeze these two to prevent learners from getting the tester into a weird -// state. +// Fake Deep Equal dependency +// eslint-disable-next-line @typescript-eslint/no-unused-vars +const DeepEqual = (a: unknown, b: unknown) => + JSON.stringify(a) === JSON.stringify(b); + +// We can't simply import these because of how webpack names them when building +// the bundle. Since both assert and __helpers have to exist in the global +// scope, we have to declare them. +const assert = chai.assert; +const __helpers = curriculumHelpers; + +// We freeze to prevent learners from getting the tester into a weird +// state by modifying these objects. Object.freeze(self); Object.freeze(__utils); +Object.freeze(assert); +Object.freeze(__helpers); interface TestEvaluatorEvent extends MessageEvent { data: { @@ -104,18 +117,8 @@ interface TestEvaluatorEvent extends MessageEvent { /* Run the test if there is one. If not just evaluate the user code */ ctx.onmessage = async (e: TestEvaluatorEvent) => { /* eslint-disable @typescript-eslint/no-unused-vars */ - const code = (e.data?.code?.contents || '').slice(); - const editableContents = (e.data?.code?.editableContents || '').slice(); - - const assert = chai.assert; - const __helpers = helpers; - // Similarly to self and __utils, if the learner tries to modify these, weird - // behavior may result. Freezing them means they get an error instead. - Object.freeze(assert); - Object.freeze(__helpers); - // Fake Deep Equal dependency - const DeepEqual = (a: unknown, b: unknown) => - JSON.stringify(a) === JSON.stringify(b); + const code = e.data?.code?.contents || ''; + const editableContents = e.data?.code?.editableContents || ''; // Build errors should be reported, but only once: __utils.toggleProxyLogger(e.data.firstTest);