From 2205d64ea3abb22245f474ea6143e667b7759a4d Mon Sep 17 00:00:00 2001 From: denis Date: Fri, 16 Oct 2026 16:44:05 +0200 Subject: [PATCH] Add LevelLinter (static checks) and LevelChecker (execution checks) shared by tests and the future author editor Co-Authored-By: Claude Sonnet 5.5 --- app/js/core/LevelChecker.js | 96 +++ app/js/core/LevelLinter.js | 237 ++++++ app/js/core/ValidationEngine.js | 5 + app/js/lib/json-schema/LICENSE | 21 + app/js/lib/json-schema/README.md | 6 + app/js/lib/json-schema/deep-compare-strict.js | 39 + app/js/lib/json-schema/dereference.js | 143 ++++ app/js/lib/json-schema/format.js | 108 +++ app/js/lib/json-schema/index.js | 8 + app/js/lib/json-schema/pointer.js | 6 + app/js/lib/json-schema/types.js | 6 + app/js/lib/json-schema/ucs2-length.js | 17 + app/js/lib/json-schema/validate.js | 802 ++++++++++++++++++ app/js/lib/json-schema/validator.js | 23 + tests/js/level-linter.test.mjs | 80 ++ tests/js/level-solutions.integration.test.mjs | 91 +- 16 files changed, 1637 insertions(+), 51 deletions(-) create mode 100644 app/js/core/LevelChecker.js create mode 100644 app/js/core/LevelLinter.js create mode 100644 app/js/lib/json-schema/LICENSE create mode 100644 app/js/lib/json-schema/README.md create mode 100644 app/js/lib/json-schema/deep-compare-strict.js create mode 100644 app/js/lib/json-schema/dereference.js create mode 100644 app/js/lib/json-schema/format.js create mode 100644 app/js/lib/json-schema/index.js create mode 100644 app/js/lib/json-schema/pointer.js create mode 100644 app/js/lib/json-schema/types.js create mode 100644 app/js/lib/json-schema/ucs2-length.js create mode 100644 app/js/lib/json-schema/validate.js create mode 100644 app/js/lib/json-schema/validator.js create mode 100644 tests/js/level-linter.test.mjs diff --git a/app/js/core/LevelChecker.js b/app/js/core/LevelChecker.js new file mode 100644 index 0000000..47cccdd --- /dev/null +++ b/app/js/core/LevelChecker.js @@ -0,0 +1,96 @@ +// Vérifications d'exécution d'un niveau, avec le vrai moteur Python : la solution de chaque étape de +// code (et de la mission) doit passer ses tests, et le code de départ ne doit PAS les passer (sinon +// l'exercice serait déjà résolu), sauf pour les étapes « exécute pour voir » (départ = solution à des +// commentaires près). Même logique que l'application (StepValidator, ValidationEngine). Utilisé par +// `make test` et par l'éditeur de niveaux. Même forme de problèmes que LevelLinter. + +import { StepValidator } from './StepValidator.js'; +import { ValidationEngine } from './ValidationEngine.js'; + +/** Code sans commentaires ni lignes vides, pour comparer départ et solution. */ +export function bare(code) { + return code + .split('\n') + .filter((line) => line.trim() !== '' && !line.trim().startsWith('#')) + .join('\n'); +} + +export class LevelChecker { + #client; + #stepValidator; + + /** + * @param {object} deps + * @param {import('./PyodideWorkerClient.js').PyodideWorkerClient} deps.client + * @param {ValidationEngine} [deps.validator] + */ + constructor({ client, validator = new ValidationEngine() }) { + this.#client = client; + this.#stepValidator = new StepValidator({ client, validator }); + } + + /** + * @param {object} level Niveau (déjà valide structurellement). + * @param {object} [options] + * @param {(done: number, total: number) => void} [options.onProgress] + * @returns {Promise<{exercises: {path: (string|number)[], runOnly: boolean, solutionPassed: boolean|null}[], problems: object[]}>} + */ + async check(level, { onProgress = () => {} } = {}) { + await this.#client.reset(); + const exercises = [ + ...level.steps.map((step, index) => ({ path: ['steps', index], exercise: step })).filter(({ exercise }) => exercise.type === 'code'), + ...(level.mission?.tests?.length ? [{ path: ['mission'], exercise: level.mission }] : []), + ]; + const problems = []; + const summary = []; + let done = 0; + for (const { path, exercise } of exercises) { + const add = (severity, code, params = {}) => problems.push({ severity, code, path, params }); + const entry = { path, runOnly: false, solutionPassed: null }; + summary.push(entry); + onProgress(done, exercises.length); + if (!exercise.solution?.trim()) { + // Déjà signalé par LevelLinter ; rien à exécuter. + done += 1; + continue; + } + const solved = await this.#attempt(exercise.solution, exercise.tests); + entry.solutionPassed = solved.passed; + if (solved.error) { + add('error', 'solution_error', { type: solved.error.type, message: solved.error.message, line: solved.error.lineno }); + } else if (!solved.passed) { + add('error', 'solution_fails', { failures: solved.failures }); + } + entry.runOnly = bare(exercise.starter ?? '') === bare(exercise.solution); + if (!entry.runOnly && exercise.starter?.trim()) { + const started = await this.#attempt(exercise.starter, exercise.tests); + if (started.error?.type === 'SyntaxError') { + add('error', 'starter_error', { type: started.error.type, message: started.error.message, line: started.error.lineno }); + } else if (started.passed) { + add('error', 'starter_passes'); + } + } + done += 1; + } + onProgress(done, exercises.length); + return { exercises: summary, problems }; + } + + /** Exécute `code` comme l'apprenant (saisies du premier test scripté), puis valide ses tests. */ + async #attempt(code, tests) { + const queue = [...(tests.find((test) => test.inputs)?.inputs ?? [])]; + let stdout = ''; + const result = await this.#client.run(code, { + collect: ValidationEngine.variablesToCollect(tests), + onStdout: (text) => (stdout += text), + onStderr: (text) => (stdout += text), + onInput: async () => (queue.length > 0 ? queue.shift() : null), + }); + const outcome = await this.#stepValidator.validate(code, tests, { stdout, result }); + return { + passed: outcome.passed, + error: result.error, + failures: outcome.results.filter((entry) => !entry.passed).map((entry) => ({ kind: entry.kind, reason: entry.reason })), + }; + } +} diff --git a/app/js/core/LevelLinter.js b/app/js/core/LevelLinter.js new file mode 100644 index 0000000..6846768 --- /dev/null +++ b/app/js/core/LevelLinter.js @@ -0,0 +1,237 @@ +// Vérifications statiques d'un niveau (sans exécuter Python) : conformité au schéma, traductions, +// cohérence des tests, règles de contribution. Même esprit que scripts/validate_levels.py, utilisé +// par l'éditeur de niveaux (mode auteur). Chaque problème est un objet { severity, code, path, params } ; +// les textes affichés viennent des catalogues (clé `lint.`), jamais d'ici. + +import { Validator } from '../lib/json-schema/index.js'; +import { ValidationEngine } from './ValidationEngine.js'; + +const DRAFT = '2020-12'; +const PYTHON_TYPES = ['str', 'int', 'float', 'bool', 'list', 'dict', 'tuple', 'set', 'NoneType']; +// Mots-clés qui ne sont que des enveloppes : seuls les « feuilles » donnent un message utile. +const WRAPPER_KEYWORDS = new Set(['properties', 'items', '$ref', 'oneOf', 'anyOf', 'allOf', 'false']); + +export class LevelLinter { + #schema; + #parts = new Map(); + #top; + #full; + + /** @param {object} schema Contenu de levels/schema/level.schema.json. */ + constructor(schema) { + this.#schema = schema; + // Niveau sans le détail des étapes et de la mission : on les valide à part, avec des messages ciblés. + const shallow = structuredClone(schema); + shallow.properties.steps = { type: 'array' }; + shallow.properties.mission = { type: 'object' }; + this.#top = new Validator(shallow, DRAFT, false); + // Le validateur annote les sous-schémas qu'il reçoit : chaque instance travaille sur sa propre copie. + this.#full = new Validator(structuredClone(schema), DRAFT, false); + } + + /** + * @param {object} level Niveau au format du schéma. + * @param {object} [options] + * @param {string[]|null} [options.knownLevelIds] Ids des niveaux existants (vérifie `requires` et l'unicité de l'id). + * @param {boolean} [options.requireEnglish] + * @returns {{severity: 'error'|'warning'|'info', code: string, path: (string|number)[], params: object}[]} + */ + lint(level, { knownLevelIds = null, requireEnglish = true } = {}) { + const problems = []; + const add = (severity, code, path = [], params = {}) => problems.push({ severity, code, path, params }); + + this.#schemaProblems(level, add); + if (problems.every((problem) => problem.severity !== 'error')) { + // Filet de sécurité : le schéma complet fait foi si les contrôles ciblés n'ont rien vu. + const full = this.#full.validate(level); + if (!full.valid) { + add('error', 'schema_invalid', [], { detail: full.errors.find((error) => !WRAPPER_KEYWORDS.has(error.keyword))?.error ?? full.errors[0].error }); + } + } + const structurallySound = problems.every((problem) => problem.severity !== 'error'); + if (!structurallySound) { + // Les règles suivantes supposent une structure correcte (sinon elles produiraient du bruit). + return problems; + } + if (requireEnglish) { + this.#missingEnglish(level, [], add); + } + this.#references(level, knownLevelIds, add); + this.#contribution(level, add); + return problems; + } + + // ---- Schéma ------------------------------------------------------------------------------------------- + + #schemaProblems(level, add) { + if (level === null || typeof level !== 'object' || Array.isArray(level)) { + add('error', 'schema_type', [], { expected: 'object' }); + return; + } + this.#report(this.#top.validate(level), [], add); + if (!Array.isArray(level.steps)) { + return; + } + level.steps.forEach((step, index) => { + const type = step?.type; + const part = type === 'explain' ? 'stepExplain' : type === 'code' ? 'stepCode' : null; + if (part === null) { + add('error', 'schema_enum', ['steps', index, 'type'], { allowed: 'explain, code' }); + } else { + this.#report(this.#part(part).validate(step), ['steps', index], add); + } + }); + if (level.mission && typeof level.mission === 'object') { + this.#report(this.#part('mission').validate(level.mission), ['mission'], add); + } + } + + #part(name) { + if (!this.#parts.has(name)) { + this.#parts.set(name, new Validator({ $id: this.#schema.$id, $schema: this.#schema.$schema, $defs: structuredClone(this.#schema.$defs), $ref: `#/$defs/${name}` }, DRAFT, false)); + } + return this.#parts.get(name); + } + + /** Traduit les erreurs du validateur en problèmes lisibles (feuilles uniquement). */ + #report(result, basePath, add) { + if (result.valid) { + return; + } + let reported = 0; + for (const error of result.errors) { + if (WRAPPER_KEYWORDS.has(error.keyword)) { + continue; + } + const path = [...basePath, ...error.instanceLocation.replace(/^#\/?/, '').split('/').filter(Boolean).map((segment) => (/^\d+$/.test(segment) ? Number(segment) : segment))]; + const quoted = /"([^"]+)"/.exec(error.error)?.[1]; + switch (error.keyword) { + case 'required': + add('error', 'schema_required', path, { field: quoted }); + break; + case 'additionalProperties': + add('error', 'schema_unknown_field', path, { field: quoted }); + break; + case 'pattern': + add('error', 'schema_pattern', path); + break; + case 'enum': + case 'const': + add('error', 'schema_enum', path); + break; + case 'type': + add('error', 'schema_type', path); + break; + case 'minimum': + case 'maximum': + case 'minItems': + add('error', 'schema_range', path); + break; + default: + add('error', 'schema_invalid', path, { detail: error.error }); + } + reported += 1; + } + if (reported === 0) { + add('error', 'schema_invalid', basePath, { detail: result.errors[0]?.error ?? '' }); + } + } + + // ---- Traductions -------------------------------------------------------------------------------------- + + /** Toute chaîne i18n {fr: …} doit avoir un `en` non vide (règle de contribution du projet). */ + #missingEnglish(node, path, add) { + if (Array.isArray(node)) { + node.forEach((child, index) => this.#missingEnglish(child, [...path, index], add)); + } else if (node !== null && typeof node === 'object') { + if ('fr' in node && (typeof node.fr === 'string' || Array.isArray(node.fr))) { + const english = node.en; + const empty = english === undefined || (typeof english === 'string' && english.trim() === '') || (Array.isArray(english) && english.length === 0); + if (empty) { + add('error', 'missing_english', path); + } else if (Array.isArray(node.fr) && Array.isArray(english) && english.length !== node.fr.length) { + add('warning', 'hint_count_differs', path, { fr: node.fr.length, en: english.length }); + } + } + for (const [key, child] of Object.entries(node)) { + this.#missingEnglish(child, [...path, key], add); + } + } + } + + // ---- Références --------------------------------------------------------------------------------------- + + #references(level, knownLevelIds, add) { + if (knownLevelIds === null) { + return; + } + if (knownLevelIds.includes(level.id)) { + add('warning', 'id_already_exists', ['id'], { id: level.id }); + } + (level.requires ?? []).forEach((required, index) => { + if (required === level.id) { + add('error', 'requires_self', ['requires', index]); + } else if (!knownLevelIds.includes(required)) { + add('error', 'requires_unknown', ['requires', index], { id: required }); + } + }); + } + + // ---- Règles de contribution et cohérence des tests ---------------------------------------------------- + + #contribution(level, add) { + level.steps.forEach((step, index) => { + const path = ['steps', index]; + if (step.type === 'explain') { + if (step.voice) { + add('info', 'voice_to_generate', path); + } + return; + } + this.#tests(step.tests, [...path, 'tests'], add); + if (!step.solution?.trim()) { + add('error', 'solution_missing', [...path, 'solution']); + } + if (!step.hints?.fr?.length) { + add('warning', 'hints_missing', [...path, 'hints']); + } + }); + const { mission } = level; + if (mission.tests?.length) { + this.#tests(mission.tests, ['mission', 'tests'], add); + if (!mission.solution?.trim()) { + add('error', 'solution_missing', ['mission', 'solution']); + } + } + } + + #tests(tests, path, add) { + const supported = new Set(ValidationEngine.supportedKinds); + tests.forEach((test, index) => { + const here = [...path, index]; + if (!supported.has(test.kind)) { + add('error', 'kind_unsupported', [...here, 'kind'], { kind: test.kind }); + return; + } + if (test.kind.startsWith('var_') && !test.name?.trim()) { + add('error', 'test_name_missing', [...here, 'name']); + } + if (test.kind !== 'no_syntax_error' && test.kind !== 'var_equals' && (typeof test.value !== 'string' || test.value === '')) { + add('error', 'test_value_missing', [...here, 'value']); + } + if (test.kind === 'var_equals' && test.value === undefined) { + add('error', 'test_value_missing', [...here, 'value']); + } + if (test.kind === 'var_type_is' && !PYTHON_TYPES.includes(test.value)) { + add('warning', 'type_unusual', [...here, 'value'], { allowed: PYTHON_TYPES.join(', ') }); + } + if (test.kind === 'stdout_matches_regex' && typeof test.value === 'string') { + try { + new RegExp(test.value); + } catch (error) { + add('error', 'regex_invalid', [...here, 'value'], { detail: error.message }); + } + } + }); + } +} diff --git a/app/js/core/ValidationEngine.js b/app/js/core/ValidationEngine.js index be9a4a1..475b735 100644 --- a/app/js/core/ValidationEngine.js +++ b/app/js/core/ValidationEngine.js @@ -4,6 +4,11 @@ const FLOAT_TOLERANCE = 1e-9; export class ValidationEngine { + /** Kinds de test interprétés par le moteur (le schéma en autorise davantage : certains sont encore à définir). */ + static get supportedKinds() { + return ['no_syntax_error', 'stdout_equals', 'stdout_contains', 'stdout_matches_regex', 'code_contains', 'var_equals', 'var_type_is']; + } + /** Noms de variables à relire côté Python (option `collect` de run_code) pour ces tests. */ static variablesToCollect(tests) { const names = tests.filter((test) => test.kind.startsWith('var_')).map((test) => test.name); diff --git a/app/js/lib/json-schema/LICENSE b/app/js/lib/json-schema/LICENSE new file mode 100644 index 0000000..85bcd78 --- /dev/null +++ b/app/js/lib/json-schema/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jeremy Danyow + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/js/lib/json-schema/README.md b/app/js/lib/json-schema/README.md new file mode 100644 index 0000000..052d8f8 --- /dev/null +++ b/app/js/lib/json-schema/README.md @@ -0,0 +1,6 @@ +# @cfworker/json-schema 4.1.1 (MIT) + +Copie vendorisée de `dist/esm` (npm `@cfworker/json-schema@4.1.1`), servie depuis le même domaine +(COEP). Validateur JSON Schema 2020-12 sans `eval`, utilisé par l'éditeur de niveaux (mode auteur) +pour valider un niveau contre `levels/schema/level.schema.json` dans le navigateur. +Licence : voir `LICENSE`. diff --git a/app/js/lib/json-schema/deep-compare-strict.js b/app/js/lib/json-schema/deep-compare-strict.js new file mode 100644 index 0000000..845f719 --- /dev/null +++ b/app/js/lib/json-schema/deep-compare-strict.js @@ -0,0 +1,39 @@ +export function deepCompareStrict(a, b) { + const typeofa = typeof a; + if (typeofa !== typeof b) { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + const length = a.length; + if (length !== b.length) { + return false; + } + for (let i = 0; i < length; i++) { + if (!deepCompareStrict(a[i], b[i])) { + return false; + } + } + return true; + } + if (typeofa === 'object') { + if (!a || !b) { + return a === b; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const length = aKeys.length; + if (length !== bKeys.length) { + return false; + } + for (const k of aKeys) { + if (!deepCompareStrict(a[k], b[k])) { + return false; + } + } + return true; + } + return a === b; +} diff --git a/app/js/lib/json-schema/dereference.js b/app/js/lib/json-schema/dereference.js new file mode 100644 index 0000000..81805ba --- /dev/null +++ b/app/js/lib/json-schema/dereference.js @@ -0,0 +1,143 @@ +import { encodePointer } from './pointer.js'; +export const schemaKeyword = { + additionalItems: true, + unevaluatedItems: true, + items: true, + contains: true, + additionalProperties: true, + unevaluatedProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true +}; +export const schemaArrayKeyword = { + prefixItems: true, + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; +export const schemaMapKeyword = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependentSchemas: true +}; +export const ignoredKeyword = { + id: true, + $id: true, + $ref: true, + $schema: true, + $anchor: true, + $vocabulary: true, + $comment: true, + default: true, + enum: true, + const: true, + required: true, + type: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; +export let initialBaseURI = typeof self !== 'undefined' && + self.location && + self.location.origin !== 'null' + ? + new URL(self.location.origin + self.location.pathname + location.search) + : new URL('https://github.com/cfworker'); +export function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') { + if (schema && typeof schema === 'object' && !Array.isArray(schema)) { + const id = schema.$id || schema.id; + if (id) { + const url = new URL(id, baseURI.href); + if (url.hash.length > 1) { + lookup[url.href] = schema; + } + else { + url.hash = ''; + if (basePointer === '') { + baseURI = url; + } + else { + dereference(schema, lookup, baseURI); + } + } + } + } + else if (schema !== true && schema !== false) { + return lookup; + } + const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : ''); + if (lookup[schemaURI] !== undefined) { + throw new Error(`Duplicate schema URI "${schemaURI}".`); + } + lookup[schemaURI] = schema; + if (schema === true || schema === false) { + return lookup; + } + if (schema.__absolute_uri__ === undefined) { + Object.defineProperty(schema, '__absolute_uri__', { + enumerable: false, + value: schemaURI + }); + } + if (schema.$ref && schema.__absolute_ref__ === undefined) { + const url = new URL(schema.$ref, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, '__absolute_ref__', { + enumerable: false, + value: url.href + }); + } + if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { + const url = new URL(schema.$recursiveRef, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, '__absolute_recursive_ref__', { + enumerable: false, + value: url.href + }); + } + if (schema.$anchor) { + const url = new URL('#' + schema.$anchor, baseURI.href); + lookup[url.href] = schema; + } + for (let key in schema) { + if (ignoredKeyword[key]) { + continue; + } + const keyBase = `${basePointer}/${encodePointer(key)}`; + const subSchema = schema[key]; + if (Array.isArray(subSchema)) { + if (schemaArrayKeyword[key]) { + const length = subSchema.length; + for (let i = 0; i < length; i++) { + dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); + } + } + } + else if (schemaMapKeyword[key]) { + for (let subKey in subSchema) { + dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); + } + } + else { + dereference(subSchema, lookup, baseURI, keyBase); + } + } + return lookup; +} diff --git a/app/js/lib/json-schema/format.js b/app/js/lib/json-schema/format.js new file mode 100644 index 0000000..8495dc0 --- /dev/null +++ b/app/js/lib/json-schema/format.js @@ -0,0 +1,108 @@ +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +const HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; +const URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +const URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +const URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +const JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +const JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +const RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; +const EMAIL = (input) => { + if (input[0] === '"') + return false; + const [name, host, ...rest] = input.split('@'); + if (!name || + !host || + rest.length !== 0 || + name.length > 64 || + host.length > 253) + return false; + if (name[0] === '.' || name.endsWith('.') || name.includes('..')) + return false; + if (!/^[a-z0-9.-]+$/i.test(host) || + !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) + return false; + return host + .split('.') + .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); +}; +const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; +const IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; +const DURATION = (input) => input.length > 1 && + input.length < 80 && + (/^P\d+([.,]\d+)?W$/.test(input) || + (/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && + /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input))); +function bind(r) { + return r.test.bind(r); +} +export const format = { + date, + time: time.bind(undefined, false), + 'date-time': date_time, + duration: DURATION, + uri, + 'uri-reference': bind(URIREF), + 'uri-template': bind(URITEMPLATE), + url: bind(URL_), + email: EMAIL, + hostname: bind(HOSTNAME), + ipv4: bind(IPV4), + ipv6: bind(IPV6), + regex: regex, + uuid: bind(UUID), + 'json-pointer': bind(JSON_POINTER), + 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT), + 'relative-json-pointer': bind(RELATIVE_JSON_POINTER) +}; +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +function date(str) { + const matches = str.match(DATE); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return (month >= 1 && + month <= 12 && + day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month])); +} +function time(full, str) { + const matches = str.match(TIME); + if (!matches) + return false; + const hour = +matches[1]; + const minute = +matches[2]; + const second = +matches[3]; + const timeZone = !!matches[5]; + return (((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone)); +} +const DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]); +} +const NOT_URI_FRAGMENT = /\/|:/; +const URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); +} +const Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str, 'u'); + return true; + } + catch (e) { + return false; + } +} diff --git a/app/js/lib/json-schema/index.js b/app/js/lib/json-schema/index.js new file mode 100644 index 0000000..1324c12 --- /dev/null +++ b/app/js/lib/json-schema/index.js @@ -0,0 +1,8 @@ +export * from './deep-compare-strict.js'; +export * from './dereference.js'; +export * from './format.js'; +export * from './pointer.js'; +export * from './types.js'; +export * from './ucs2-length.js'; +export * from './validate.js'; +export * from './validator.js'; diff --git a/app/js/lib/json-schema/pointer.js b/app/js/lib/json-schema/pointer.js new file mode 100644 index 0000000..039f2ab --- /dev/null +++ b/app/js/lib/json-schema/pointer.js @@ -0,0 +1,6 @@ +export function encodePointer(p) { + return encodeURI(escapePointer(p)); +} +export function escapePointer(p) { + return p.replace(/~/g, '~0').replace(/\//g, '~1'); +} diff --git a/app/js/lib/json-schema/types.js b/app/js/lib/json-schema/types.js new file mode 100644 index 0000000..ea8b90f --- /dev/null +++ b/app/js/lib/json-schema/types.js @@ -0,0 +1,6 @@ +export var OutputFormat; +(function (OutputFormat) { + OutputFormat[OutputFormat["Flag"] = 1] = "Flag"; + OutputFormat[OutputFormat["Basic"] = 2] = "Basic"; + OutputFormat[OutputFormat["Detailed"] = 4] = "Detailed"; +})(OutputFormat || (OutputFormat = {})); diff --git a/app/js/lib/json-schema/ucs2-length.js b/app/js/lib/json-schema/ucs2-length.js new file mode 100644 index 0000000..dedab66 --- /dev/null +++ b/app/js/lib/json-schema/ucs2-length.js @@ -0,0 +1,17 @@ +export function ucs2length(s) { + let result = 0; + let length = s.length; + let index = 0; + let charCode; + while (index < length) { + result++; + charCode = s.charCodeAt(index++); + if (charCode >= 0xd800 && charCode <= 0xdbff && index < length) { + charCode = s.charCodeAt(index); + if ((charCode & 0xfc00) == 0xdc00) { + index++; + } + } + } + return result; +} diff --git a/app/js/lib/json-schema/validate.js b/app/js/lib/json-schema/validate.js new file mode 100644 index 0000000..7a52374 --- /dev/null +++ b/app/js/lib/json-schema/validate.js @@ -0,0 +1,802 @@ +import { deepCompareStrict } from './deep-compare-strict.js'; +import { dereference } from './dereference.js'; +import { format } from './format.js'; +import { encodePointer } from './pointer.js'; +import { ucs2length } from './ucs2-length.js'; +export function validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) { + if (schema === true) { + return { valid: true, errors: [] }; + } + if (schema === false) { + return { + valid: false, + errors: [ + { + instanceLocation, + keyword: 'false', + keywordLocation: instanceLocation, + error: 'False boolean schema.' + } + ] + }; + } + const rawInstanceType = typeof instance; + let instanceType; + switch (rawInstanceType) { + case 'boolean': + case 'number': + case 'string': + instanceType = rawInstanceType; + break; + case 'object': + if (instance === null) { + instanceType = 'null'; + } + else if (Array.isArray(instance)) { + instanceType = 'array'; + } + else { + instanceType = 'object'; + } + break; + default: + throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); + } + const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; + const errors = []; + if ($recursiveAnchor === true && recursiveAnchor === null) { + recursiveAnchor = schema; + } + if ($recursiveRef === '#') { + const refSchema = recursiveAnchor === null + ? lookup[__absolute_recursive_ref__] + : recursiveAnchor; + const keywordLocation = `${schemaLocation}/$recursiveRef`; + const result = validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: '$recursiveRef', + keywordLocation, + error: 'A subschema had errors.' + }, ...result.errors); + } + } + if ($ref !== undefined) { + const uri = __absolute_ref__ || $ref; + const refSchema = lookup[uri]; + if (refSchema === undefined) { + let message = `Unresolved $ref "${$ref}".`; + if (__absolute_ref__ && __absolute_ref__ !== $ref) { + message += ` Absolute URI "${__absolute_ref__}".`; + } + message += `\nKnown schemas:\n- ${Object.keys(lookup).join('\n- ')}`; + throw new Error(message); + } + const keywordLocation = `${schemaLocation}/$ref`; + const result = validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: '$ref', + keywordLocation, + error: 'A subschema had errors.' + }, ...result.errors); + } + if (draft === '4' || draft === '7') { + return { valid: errors.length === 0, errors }; + } + } + if (Array.isArray($type)) { + let length = $type.length; + let valid = false; + for (let i = 0; i < length; i++) { + if (instanceType === $type[i] || + ($type[i] === 'integer' && + instanceType === 'number' && + instance % 1 === 0 && + instance === instance)) { + valid = true; + break; + } + } + if (!valid) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` + }); + } + } + else if ($type === 'integer') { + if (instanceType !== 'number' || instance % 1 || instance !== instance) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } + } + else if ($type !== undefined && instanceType !== $type) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } + if ($const !== undefined) { + if (instanceType === 'object' || instanceType === 'array') { + if (!deepCompareStrict(instance, $const)) { + errors.push({ + instanceLocation, + keyword: 'const', + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); + } + } + else if (instance !== $const) { + errors.push({ + instanceLocation, + keyword: 'const', + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); + } + } + if ($enum !== undefined) { + if (instanceType === 'object' || instanceType === 'array') { + if (!$enum.some(value => deepCompareStrict(instance, value))) { + errors.push({ + instanceLocation, + keyword: 'enum', + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } + } + else if (!$enum.some(value => instance === value)) { + errors.push({ + instanceLocation, + keyword: 'enum', + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } + } + if ($not !== undefined) { + const keywordLocation = `${schemaLocation}/not`; + const result = validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); + if (result.valid) { + errors.push({ + instanceLocation, + keyword: 'not', + keywordLocation, + error: 'Instance matched "not" schema.' + }); + } + } + let subEvaluateds = []; + if ($anyOf !== undefined) { + const keywordLocation = `${schemaLocation}/anyOf`; + const errorsLength = errors.length; + let anyValid = false; + for (let i = 0; i < $anyOf.length; i++) { + const subSchema = $anyOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + anyValid = anyValid || result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + } + if (anyValid) { + errors.length = errorsLength; + } + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'anyOf', + keywordLocation, + error: 'Instance does not match any subschemas.' + }); + } + } + if ($allOf !== undefined) { + const keywordLocation = `${schemaLocation}/allOf`; + const errorsLength = errors.length; + let allValid = true; + for (let i = 0; i < $allOf.length; i++) { + const subSchema = $allOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + allValid = allValid && result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + } + if (allValid) { + errors.length = errorsLength; + } + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'allOf', + keywordLocation, + error: `Instance does not match every subschema.` + }); + } + } + if ($oneOf !== undefined) { + const keywordLocation = `${schemaLocation}/oneOf`; + const errorsLength = errors.length; + const matches = $oneOf.filter((subSchema, i) => { + const subEvaluated = Object.create(evaluated); + const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + return result.valid; + }).length; + if (matches === 1) { + errors.length = errorsLength; + } + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'oneOf', + keywordLocation, + error: `Instance does not match exactly one subschema (${matches} matches).` + }); + } + } + if (instanceType === 'object' || instanceType === 'array') { + Object.assign(evaluated, ...subEvaluateds); + } + if ($if !== undefined) { + const keywordLocation = `${schemaLocation}/if`; + const conditionResult = validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; + if (conditionResult) { + if ($then !== undefined) { + const thenResult = validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); + if (!thenResult.valid) { + errors.push({ + instanceLocation, + keyword: 'if', + keywordLocation, + error: `Instance does not match "then" schema.` + }, ...thenResult.errors); + } + } + } + else if ($else !== undefined) { + const elseResult = validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); + if (!elseResult.valid) { + errors.push({ + instanceLocation, + keyword: 'if', + keywordLocation, + error: `Instance does not match "else" schema.` + }, ...elseResult.errors); + } + } + } + if (instanceType === 'object') { + if ($required !== undefined) { + for (const key of $required) { + if (!(key in instance)) { + errors.push({ + instanceLocation, + keyword: 'required', + keywordLocation: `${schemaLocation}/required`, + error: `Instance does not have required property "${key}".` + }); + } + } + } + const keys = Object.keys(instance); + if ($minProperties !== undefined && keys.length < $minProperties) { + errors.push({ + instanceLocation, + keyword: 'minProperties', + keywordLocation: `${schemaLocation}/minProperties`, + error: `Instance does not have at least ${$minProperties} properties.` + }); + } + if ($maxProperties !== undefined && keys.length > $maxProperties) { + errors.push({ + instanceLocation, + keyword: 'maxProperties', + keywordLocation: `${schemaLocation}/maxProperties`, + error: `Instance does not have at least ${$maxProperties} properties.` + }); + } + if ($propertyNames !== undefined) { + const keywordLocation = `${schemaLocation}/propertyNames`; + for (const key in instance) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'propertyNames', + keywordLocation, + error: `Property name "${key}" does not match schema.` + }, ...result.errors); + } + } + } + if ($dependentRequired !== undefined) { + const keywordLocation = `${schemaLocation}/dependantRequired`; + for (const key in $dependentRequired) { + if (key in instance) { + const required = $dependentRequired[key]; + for (const dependantKey of required) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: 'dependentRequired', + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + } + } + if ($dependentSchemas !== undefined) { + for (const key in $dependentSchemas) { + const keywordLocation = `${schemaLocation}/dependentSchemas`; + if (key in instance) { + const result = validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'dependentSchemas', + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } + if ($dependencies !== undefined) { + const keywordLocation = `${schemaLocation}/dependencies`; + for (const key in $dependencies) { + if (key in instance) { + const propsOrSchema = $dependencies[key]; + if (Array.isArray(propsOrSchema)) { + for (const dependantKey of propsOrSchema) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: 'dependencies', + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + else { + const result = validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'dependencies', + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } + } + const thisEvaluated = Object.create(null); + let stop = false; + if ($properties !== undefined) { + const keywordLocation = `${schemaLocation}/properties`; + for (const key in $properties) { + if (!(key in instance)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'properties', + keywordLocation, + error: `Property "${key}" does not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if (!stop && $patternProperties !== undefined) { + const keywordLocation = `${schemaLocation}/patternProperties`; + for (const pattern in $patternProperties) { + const regex = new RegExp(pattern, 'u'); + const subSchema = $patternProperties[pattern]; + for (const key in instance) { + if (!regex.test(key)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'patternProperties', + keywordLocation, + error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` + }, ...result.errors); + } + } + } + } + if (!stop && $additionalProperties !== undefined) { + const keywordLocation = `${schemaLocation}/additionalProperties`; + for (const key in instance) { + if (thisEvaluated[key]) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'additionalProperties', + keywordLocation, + error: `Property "${key}" does not match additional properties schema.` + }, ...result.errors); + } + } + } + else if (!stop && $unevaluatedProperties !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedProperties`; + for (const key in instance) { + if (!evaluated[key]) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } + else { + errors.push({ + instanceLocation, + keyword: 'unevaluatedProperties', + keywordLocation, + error: `Property "${key}" does not match unevaluated properties schema.` + }, ...result.errors); + } + } + } + } + } + else if (instanceType === 'array') { + if ($maxItems !== undefined && instance.length > $maxItems) { + errors.push({ + instanceLocation, + keyword: 'maxItems', + keywordLocation: `${schemaLocation}/maxItems`, + error: `Array has too many items (${instance.length} > ${$maxItems}).` + }); + } + if ($minItems !== undefined && instance.length < $minItems) { + errors.push({ + instanceLocation, + keyword: 'minItems', + keywordLocation: `${schemaLocation}/minItems`, + error: `Array has too few items (${instance.length} < ${$minItems}).` + }); + } + const length = instance.length; + let i = 0; + let stop = false; + if ($prefixItems !== undefined) { + const keywordLocation = `${schemaLocation}/prefixItems`; + const length2 = Math.min($prefixItems.length, length); + for (; i < length2; i++) { + const result = validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'prefixItems', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if ($items !== undefined) { + const keywordLocation = `${schemaLocation}/items`; + if (Array.isArray($items)) { + const length2 = Math.min($items.length, length); + for (; i < length2; i++) { + const result = validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'items', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + else { + for (; i < length; i++) { + const result = validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'items', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if (!stop && $additionalItems !== undefined) { + const keywordLocation = `${schemaLocation}/additionalItems`; + for (; i < length; i++) { + const result = validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'additionalItems', + keywordLocation, + error: `Items did not match additional items schema.` + }, ...result.errors); + } + } + } + } + if ($contains !== undefined) { + if (length === 0 && $minContains === undefined) { + errors.push({ + instanceLocation, + keyword: 'contains', + keywordLocation: `${schemaLocation}/contains`, + error: `Array is empty. It must contain at least one item matching the schema.` + }); + } + else if ($minContains !== undefined && length < $minContains) { + errors.push({ + instanceLocation, + keyword: 'minContains', + keywordLocation: `${schemaLocation}/minContains`, + error: `Array has less items (${length}) than minContains (${$minContains}).` + }); + } + else { + const keywordLocation = `${schemaLocation}/contains`; + const errorsLength = errors.length; + let contained = 0; + for (let j = 0; j < length; j++) { + const result = validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); + if (result.valid) { + evaluated[j] = true; + contained++; + } + else { + errors.push(...result.errors); + } + } + if (contained >= ($minContains || 0)) { + errors.length = errorsLength; + } + if ($minContains === undefined && + $maxContains === undefined && + contained === 0) { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'contains', + keywordLocation, + error: `Array does not contain item matching schema.` + }); + } + else if ($minContains !== undefined && contained < $minContains) { + errors.push({ + instanceLocation, + keyword: 'minContains', + keywordLocation: `${schemaLocation}/minContains`, + error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` + }); + } + else if ($maxContains !== undefined && contained > $maxContains) { + errors.push({ + instanceLocation, + keyword: 'maxContains', + keywordLocation: `${schemaLocation}/maxContains`, + error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` + }); + } + } + } + if (!stop && $unevaluatedItems !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedItems`; + for (i; i < length; i++) { + if (evaluated[i]) { + continue; + } + const result = validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'unevaluatedItems', + keywordLocation, + error: `Items did not match unevaluated items schema.` + }, ...result.errors); + } + } + } + if ($uniqueItems) { + for (let j = 0; j < length; j++) { + const a = instance[j]; + const ao = typeof a === 'object' && a !== null; + for (let k = 0; k < length; k++) { + if (j === k) { + continue; + } + const b = instance[k]; + const bo = typeof b === 'object' && b !== null; + if (a === b || (ao && bo && deepCompareStrict(a, b))) { + errors.push({ + instanceLocation, + keyword: 'uniqueItems', + keywordLocation: `${schemaLocation}/uniqueItems`, + error: `Duplicate items at indexes ${j} and ${k}.` + }); + j = Number.MAX_SAFE_INTEGER; + k = Number.MAX_SAFE_INTEGER; + } + } + } + } + } + else if (instanceType === 'number') { + if (draft === '4') { + if ($minimum !== undefined && + (($exclusiveMinimum === true && instance <= $minimum) || + instance < $minimum)) { + errors.push({ + instanceLocation, + keyword: 'minimum', + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.` + }); + } + if ($maximum !== undefined && + (($exclusiveMaximum === true && instance >= $maximum) || + instance > $maximum)) { + errors.push({ + instanceLocation, + keyword: 'maximum', + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.` + }); + } + } + else { + if ($minimum !== undefined && instance < $minimum) { + errors.push({ + instanceLocation, + keyword: 'minimum', + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$minimum}.` + }); + } + if ($maximum !== undefined && instance > $maximum) { + errors.push({ + instanceLocation, + keyword: 'maximum', + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$maximum}.` + }); + } + if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { + errors.push({ + instanceLocation, + keyword: 'exclusiveMinimum', + keywordLocation: `${schemaLocation}/exclusiveMinimum`, + error: `${instance} is less than ${$exclusiveMinimum}.` + }); + } + if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { + errors.push({ + instanceLocation, + keyword: 'exclusiveMaximum', + keywordLocation: `${schemaLocation}/exclusiveMaximum`, + error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` + }); + } + } + if ($multipleOf !== undefined) { + const remainder = instance % $multipleOf; + if (Math.abs(0 - remainder) >= 1.1920929e-7 && + Math.abs($multipleOf - remainder) >= 1.1920929e-7) { + errors.push({ + instanceLocation, + keyword: 'multipleOf', + keywordLocation: `${schemaLocation}/multipleOf`, + error: `${instance} is not a multiple of ${$multipleOf}.` + }); + } + } + } + else if (instanceType === 'string') { + const length = $minLength === undefined && $maxLength === undefined + ? 0 + : ucs2length(instance); + if ($minLength !== undefined && length < $minLength) { + errors.push({ + instanceLocation, + keyword: 'minLength', + keywordLocation: `${schemaLocation}/minLength`, + error: `String is too short (${length} < ${$minLength}).` + }); + } + if ($maxLength !== undefined && length > $maxLength) { + errors.push({ + instanceLocation, + keyword: 'maxLength', + keywordLocation: `${schemaLocation}/maxLength`, + error: `String is too long (${length} > ${$maxLength}).` + }); + } + if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) { + errors.push({ + instanceLocation, + keyword: 'pattern', + keywordLocation: `${schemaLocation}/pattern`, + error: `String does not match pattern.` + }); + } + if ($format !== undefined && + format[$format] && + !format[$format](instance)) { + errors.push({ + instanceLocation, + keyword: 'format', + keywordLocation: `${schemaLocation}/format`, + error: `String does not match format "${$format}".` + }); + } + } + return { valid: errors.length === 0, errors }; +} diff --git a/app/js/lib/json-schema/validator.js b/app/js/lib/json-schema/validator.js new file mode 100644 index 0000000..9893aba --- /dev/null +++ b/app/js/lib/json-schema/validator.js @@ -0,0 +1,23 @@ +import { dereference } from './dereference.js'; +import { validate } from './validate.js'; +export class Validator { + schema; + draft; + shortCircuit; + lookup; + constructor(schema, draft = '2019-09', shortCircuit = true) { + this.schema = schema; + this.draft = draft; + this.shortCircuit = shortCircuit; + this.lookup = dereference(schema); + } + validate(instance) { + return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); + } + addSchema(schema, id) { + if (id) { + schema = { ...schema, $id: id }; + } + dereference(schema, this.lookup); + } +} diff --git a/tests/js/level-linter.test.mjs b/tests/js/level-linter.test.mjs new file mode 100644 index 0000000..620f589 --- /dev/null +++ b/tests/js/level-linter.test.mjs @@ -0,0 +1,80 @@ +// Vérifications statiques : les vrais niveaux n'ont aucune erreur ; des niveaux fautifs fabriqués sont +// détectés avec le bon code, au bon endroit. +import { readFileSync, readdirSync } from 'node:fs'; +import assert from 'node:assert'; +import yaml from '../../app/js/lib/js-yaml/js-yaml.mjs'; +import { LevelLinter } from '../../app/js/core/LevelLinter.js'; + +const root = new URL('../../', import.meta.url).pathname; +const schema = JSON.parse(readFileSync(`${root}levels/schema/level.schema.json`, 'utf8')); +const linter = new LevelLinter(schema); +const ids = readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name)); +const load = (id) => yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8')); +const codes = (problems, severity) => problems.filter((p) => !severity || p.severity === severity).map((p) => p.code); +const find = (problems, code) => problems.find((p) => p.code === code); + +// --- Tous les niveaux existants : aucune erreur (les avertissements et infos sont permis). +for (const id of ids) { + const problems = linter.lint(load(id), { knownLevelIds: ids.filter((other) => other !== id) }); + assert.deepEqual(codes(problems, 'error'), [], `${id} : ${JSON.stringify(problems.filter((p) => p.severity === 'error'))}`); +} + +const base = () => structuredClone(load('05-decide')); +const lint = (level, options = {}) => linter.lint(level, { knownLevelIds: ids, ...options }); + +// --- Schéma : messages ciblés (et pas le déluge d'erreurs d'enveloppe du validateur). +let level = base(); delete level.mission.goal; +assert.deepEqual(find(lint(level), 'schema_required').path, ['mission']); +assert.equal(find(lint(level), 'schema_required').params.field, 'goal'); +level = base(); level.id = 'Mauvais Id'; +assert.deepEqual(find(lint(level), 'schema_pattern').path, ['id']); +level = base(); level.steps[1].type = 'video'; +assert.deepEqual(find(lint(level), 'schema_enum').path, ['steps', 1, 'type']); +level = base(); level.steps[1].tests[0].kind = 'nope'; +assert.ok(codes(lint(level), 'error').length > 0); +level = base(); level.steps[1].bonus = true; +assert.equal(find(lint(level), 'schema_unknown_field').params.field, 'bonus'); +assert.ok(lint(level).length <= 2, 'pas de cascade de messages'); +level = base(); level.difficulty = 99; +assert.deepEqual(find(lint(level), 'schema_range').path, ['difficulty']); +assert.equal(lint('pas un objet').at(0).code, 'schema_type'); + +// --- Traductions. +level = base(); delete level.title.en; +assert.deepEqual(find(lint(level), 'missing_english').path, ['title']); +level = base(); level.steps[1].hints.en = []; +assert.deepEqual(find(lint(level), 'missing_english').path, ['steps', 1, 'hints']); +level = base(); level.mission.goal.en = ' '; +assert.ok(find(lint(level), 'missing_english')); +assert.equal(find(lint(level, { requireEnglish: false }), 'missing_english'), undefined, 'option requireEnglish'); +level = base(); level.steps[3].hints.en.pop(); +assert.equal(find(lint(level), 'hint_count_differs').severity, 'warning'); + +// --- Références. +level = base(); level.requires = ['99-inconnu']; +assert.equal(find(lint(level), 'requires_unknown').params.id, '99-inconnu'); +level = base(); level.requires = [level.id]; +assert.ok(find(lint(level), 'requires_self')); +assert.equal(find(lint(base()), 'id_already_exists').severity, 'warning'); +assert.equal(find(linter.lint(base(), { knownLevelIds: null }), 'id_already_exists'), undefined); + +// --- Règles de contribution et tests. +level = base(); delete level.steps[1].solution; +assert.deepEqual(find(lint(level), 'solution_missing').path, ['steps', 1, 'solution']); +level = base(); delete level.mission.solution; +assert.deepEqual(find(lint(level), 'solution_missing').path, ['mission', 'solution']); +level = base(); delete level.steps[1].hints; +assert.equal(find(lint(level), 'hints_missing').severity, 'warning'); +level = base(); level.steps[1].tests = [{ kind: 'function_called_with', value: 'f' }]; +assert.equal(find(lint(level), 'kind_unsupported').params.kind, 'function_called_with'); +level = base(); level.steps[1].tests = [{ kind: 'var_equals', value: 3 }]; +assert.ok(find(lint(level), 'test_name_missing')); +level = base(); level.steps[1].tests = [{ kind: 'stdout_equals' }]; +assert.ok(find(lint(level), 'test_value_missing')); +level = base(); level.steps[1].tests = [{ kind: 'stdout_matches_regex', value: '([' }]; +assert.ok(find(lint(level), 'regex_invalid')); +level = base(); level.steps[1].tests = [{ kind: 'var_type_is', name: 'x', value: 'entier' }]; +assert.equal(find(lint(level), 'type_unusual').severity, 'warning'); +assert.ok(find(lint(load('01-hello')), 'voice_to_generate'), 'rappel : narration à générer'); + +console.log('level linter ok'); diff --git a/tests/js/level-solutions.integration.test.mjs b/tests/js/level-solutions.integration.test.mjs index c59797c..085bd3b 100644 --- a/tests/js/level-solutions.integration.test.mjs +++ b/tests/js/level-solutions.integration.test.mjs @@ -1,71 +1,60 @@ -// Pour chaque niveau : la solution de référence de chaque étape et de la mission doit passer tous -// les tests, et le code de départ ne doit pas les passer (sinon l'exercice serait déjà résolu). -// Pyodide réel (vendor/pyodide requis) ; exécute exactement la logique de l'application -// (StepValidator, ValidationEngine, PyodideWorkerClient). +// Pour chaque niveau : la solution de référence de chaque étape et de la mission passe tous les tests, et +// le code de départ ne les passe pas. Pyodide réel (vendor/pyodide requis). Utilise LevelChecker, le même +// module que l'éditeur de niveaux ; vérifie aussi qu'il détecte bien des niveaux fautifs fabriqués. import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { test } from 'node:test'; import assert from 'node:assert'; import yaml from '../../app/js/lib/js-yaml/js-yaml.mjs'; +import { LevelChecker } from '../../app/js/core/LevelChecker.js'; import { PyodideWorkerClient } from '../../app/js/core/PyodideWorkerClient.js'; -import { StepValidator } from '../../app/js/core/StepValidator.js'; -import { ValidationEngine } from '../../app/js/core/ValidationEngine.js'; import { installNodeWorker } from './helpers/node-worker.mjs'; const root = new URL('../../', import.meta.url).pathname; -// Code sans commentaires ni lignes vides, pour comparer départ et solution. -const bare = (code) => - code - .split('\n') - .filter((line) => line.trim() !== '' && !line.trim().startsWith('#')) - .join('\n'); const hasPyodide = existsSync(`${root}vendor/pyodide/pyodide.mjs`); +const load = (id) => yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8')); +const summary = (problems) => problems.map((problem) => `${problem.code}@${problem.path.join('.')}`); test('les solutions de référence passent, les codes de départ échouent', { skip: !hasPyodide && 'vendor/pyodide absent', timeout: 300000 }, async () => { const { indexURL } = installNodeWorker(); const client = new PyodideWorkerClient({ indexURL, workerUrl: 'ignored' }); - const stepValidator = new StepValidator({ client, validator: new ValidationEngine() }); - - // Comme l'application : exécution « interactive » de l'apprenant, puis validation des tests. - const attempt = async (code, tests) => { - // Saisies de l'exécution interactive : celles du premier test scripté, sinon aucune. - const queue = [...(tests.find((t) => t.inputs)?.inputs ?? [])]; - let stdout = ''; - const result = await client.run(code, { - collect: ValidationEngine.variablesToCollect(tests), - onStdout: (text) => (stdout += text), - onStderr: (text) => (stdout += text), - onInput: async () => (queue.length > 0 ? queue.shift() : null), - }); - return stepValidator.validate(code, tests, { stdout, result }); - }; - const failures = (outcome) => outcome.results.filter((r) => !r.passed).map((r) => `${r.kind}:${r.reason}`); - - const problems = []; - let checked = 0; + const checker = new LevelChecker({ client }); try { + // --- Tous les niveaux existants. + let checked = 0; for (const id of readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name))) { - const level = yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8')); - await client.reset(); - const exercises = [ - ...level.steps.map((step, i) => ({ label: `${id} étape ${i + 1}`, step })).filter(({ step }) => step.type === 'code'), - ...(level.mission.tests?.length ? [{ label: `${id} mission`, step: { ...level.mission, solution: level.mission.solution } }] : []), - ]; - for (const { label, step } of exercises) { - assert.ok(step.solution, `${label} : solution manquante`); - const solved = await attempt(step.solution, step.tests); - checked += 1; - if (!solved.passed) problems.push(`${label} : la solution échoue (${failures(solved)})`); - // Les étapes « exécuter pour voir » ont un code de départ égal à la solution. - if (bare(step.starter) !== bare(step.solution)) { - const starter = await attempt(step.starter, step.tests); - if (starter.passed) problems.push(`${label} : le code de départ passe déjà les tests`); - } - } + const { exercises, problems } = await checker.check(load(id)); + assert.deepEqual(summary(problems), [], `${id}`); + checked += exercises.length; } + assert.ok(checked > 0); + + // --- Niveaux fautifs fabriqués : chaque défaut est détecté, au bon endroit. + const base = () => structuredClone(load('04-math')); + let level = base(); level.steps[1].solution = 'print(1 + 1)'; + assert.deepEqual(summary((await checker.check(level)).problems), ['solution_fails@steps.1']); + + level = base(); level.steps[1].starter = level.steps[1].solution; + assert.deepEqual(summary((await checker.check(level)).problems), [], 'départ = solution : étape « exécuter pour voir »'); + + level = base(); level.steps[1].starter = '# Exécute pour voir\nprice = 12\nquantity = 3\nprint(price * quantity)'; + assert.deepEqual(summary((await checker.check(level)).problems), [], 'départ = solution + commentaires de ligne : idem'); + + level = base(); level.steps[1].starter = 'print(36)'; + assert.deepEqual(summary((await checker.check(level)).problems), ['starter_passes@steps.1'], 'départ qui passe déjà sans être la solution'); + + level = base(); level.steps[1].solution = 'print('; + const syntax = (await checker.check(level)).problems; + assert.deepEqual(summary(syntax), ['solution_error@steps.1']); + assert.equal(syntax[0].params.type, 'SyntaxError'); + + level = base(); level.mission.solution = 'print("rien")'; + assert.deepEqual(summary((await checker.check(level)).problems), ['solution_fails@mission']); + + level = base(); level.steps[1].starter = 'print('; + assert.deepEqual(summary((await checker.check(level)).problems), ['starter_error@steps.1']); + + console.log(`${checked} exercices vérifiés`); } finally { client.dispose(); } - assert.deepEqual(problems, []); - assert.ok(checked > 0); - console.log(`${checked} exercices vérifiés`); });