diff --git a/design/author.md b/design/author.md index 40e9e20b..6d01c7a6 100644 --- a/design/author.md +++ b/design/author.md @@ -15,7 +15,7 @@ already holds text to the content check's rules, from the pack an untrusted chec `apps/skills` plays every example untrusted too. Measured on a five-question quiz, at four characters a token: `content.json` was about 3,470 tokens to write by hand, after reading 3,900 to 9,500 of a type's semantics; the source is 1,000 to 1,800 tokens, written from a type file of 200 -to 3,000. Fourteen things the code does not say by itself: +to 3,000. Eighteen things the code does not say by itself: - **One generator, three ways to run it.** The third, `saved`, checks content as H5P stores it (*Saved content is checked as the build checks what it writes*, below). `ContentGenerator` was the sweep's @@ -319,6 +319,84 @@ to 3,000. Fourteen things the code does not say by itself: where the verifier's preview opens: a real browser, in which the player runs as it is, video included. The owner chose the panel, with media to come, and the card was not built. +- **A problem says what to write, and what is in the wrong place is checked all the same** + (2026-11-10, #172). The owner gave the skill to Gemini in Chrome, which could not build a simple + Interactive Book and quoted `params.chapters: has 0 items; it takes at least 1`. A chat there has + the skill's text, no type file and nothing to run, so it learns a type's shape from the build's + problems alone. Measured that way with the weakest Claude model, Haiku 5.5: SKILL.md's text, each + reply built as the build page builds it, its problems pasted back in the page's words, up to four + rounds; an Interactive Book, a Course Presentation, a Column, a Question Set and a Branching + Scenario, three runs each, the same 15 first replies under each set of messages. With 0.6.0's + messages 3 built at once, the Question Sets, 8 by the second round, 12 by the third, 13 by the + fourth, and two scenarios never. What cost the rounds was a type's levels, not its fields: + - Sub-content in the place of the group that holds it, `{ "library", "params" }` where a + Column's item is `{ "content": { … } }`, a slide's element `{ "action": { … } }` and a + scenario's node `{ "type": { … } }`: 9 of the 24 failed rounds, three or four problems an item, + one of them a list of 35 libraries, none saying what to write. + - A field a level above its group, `params.slides` for `params.presentation.slides`: the build + said it was no field there and checked nothing of what was written in it, so the next round + found what was wrong inside, an `

` a slide's text does not take. + - A book's chapters written as pages, `{ "title", "content": [ … ] }`, with no H5P.Column around + them, in two of three books: "expected sub-content", and then "has 0 items", which the last + check counted after the generator had refused the chapters and which was not so. + - "expected sub-content, { "library": "H5P.BranchingQuestion" … }" for a field that takes seven + libraries: the first read as the one to write, and a scenario's texts came back as questions. + + So the generator says each such thing once, by its path and with what to write there, then puts + what was written where it belongs and checks it, naming what is wrong inside by where the source + has it (`moved`, by which the build's last check names what it finds too). The one library a + field takes is loaded whether or not a source names it, which is what reads a chapter without + its Column as the Column's parameters. What the last check says of a list an item of which was + refused is left out, the list being another than the one written (`shortened`). A field that + takes several libraries names them all. A scenario's question with no alternatives is reported + as that and not as a loop besides. And a problem's list of fields names those an author writes, + the interface texts as one: a book's was 39 names long. With these messages the same first + replies built 12 by the second round and all 15 by the third, and every package built under + either set plays (h5p-verify). The first wording, "is sub-content, which goes in the field + content here", did worse than the three problems it replaced: a Column's list and its items' + field are both `content`, one run sent the same source again and one made the list an object. + So the problem names the item and shows it whole, `write params.content[0] as { "content": … }`. + Only an object or a list, a text, a number or a flag whose name one group below has, in a field + an author writes that takes such a value, is taken to belong there; an interface text is none, + since a question's text sent to a label of its name would build and read wrong. And an object + goes to a group only where it writes one of the group's fields, not one of its interface texts: + a Game Map's `map`, written for the picture, was first sent to `behaviour.map`, the map's labels + and fog, a name and no more, and an object that holds only a group's `l10n` is no proof of it. +- **The package carries the skill's type files** (2026-11-10, #172). In the same measurement, what + did most was no message: with the type files pasted back beside the first problems, the content + type's and those of the libraries the source names, all 15 built by the second round, in two + runs of the twelve that had failed. A chat with the skill has those files; one in a browser has + the build page, which has the package and no skill. So `prepack` copies + `skills/h5p-author/references/types/*.md` into the package, `references/types/.md`, each + an export, for the page to hand over with a source's problems. They stay the skill's, at the + repository's root where `npx skills add` looks, written by `sync:skill` as before; the copy is + not in git, and `build.test.ts` holds it to the skill's files, file for file. + + The same test on the 23 other content types the skill lists says how far each thing reaches: + two runs each, 46 first replies, each built package checked against what its task asked for. + 16 were right at once. By the fourth round 35 were right under 0.6.0's messages and 36 under + the new ones, which is no difference: there a weak model does not misplace what it knows, it + does not know a type's names (`options`, `sequenceImages`, `questionnaireElements`) or its rules + (the right answer first, a card a pair), and a problem gives it one level's names a round. 9 + and 7 packages built and were not what was asked, a question's feedback left out once no field + took it. With the type files handed back, 42 were right by the second round and 43 by the third, + and none stayed unbuilt; three had built at once and wrong, with no problem to hand a file back + with, and one source named a type the pack has not, which no file answers until the next round + names a real one. With the type's file before the first reply, one run of each of the 28 types, + all 28 were right at once and play. So the messages are for a type's levels, and the type's file + is what lets a weak model write any type: the page hands it back, the skill gives its address. +- **The skill says where a container holds its sub-content** (2026-11-10, #172). The one thing in + SKILL.md that repeats a type file, for the chat that cannot read one. Its line on sub-content + names the three commonest places: an item of H5P.Column's `content` is + `{ "content": }`, a slide's element `{ "action": }` in + `presentation.slides[].elements`, a book's chapter an H5P.Column. In the measurement above no + first reply for a book, a page or slides built, 0 of 9; with that sentence in the skill's text + all 9 built at once and play. A scenario, which it does not name, still took a round of + problems, and so do the six other listed types that hold content (Accordion, Questionnaire, + Interactive Video, Image Hotspots, Image Choice, Game Map): of 12 first replies 2 were right at + once with the sentence and 2 without, the Accordions. The skill gives the type files' address + on GitHub too, for a chat that has its text and can open a link. + Not built: editing an existing package, which a tool beside it does with `checkContent` as its check; layout for Drag and Drop and Crossword; and any judgement of whether content is right, which stays the person's, in the verifier's preview. diff --git a/design/layout.md b/design/layout.md index a60b977f..48bafebf 100644 --- a/design/layout.md +++ b/design/layout.md @@ -190,9 +190,10 @@ packages/author/ @missing-elements/h5p-author — a playable .h5p of an `packageLibraries`, a package's own over the pack's (#107); no Node import of its own, nor has lib/source-error.mjs, `SourceError` (#106) lib/generator.mjs `ContentGenerator`: content from a type's `semantics.json`, authoring - (every written value checked as the editor's form would), lenient, as - the sweep runs it, or saved, as `checkContent` runs it; moved out of the - demo on 2026-11-01 (#100) + (every written value checked as the editor's form would, and what is + written in the wrong place said once, put where it belongs and checked + there, #172), lenient, as the sweep runs it, or saved, as `checkContent` + runs it; moved out of the demo on 2026-11-01 (#100) lib/types.mjs what the editor's own widgets set and check, per content type: Course Presentation's layout, Interactive Video's placement, Branching Scenario's paths, Game Map's stages, Find the Hotspot's areas @@ -205,7 +206,9 @@ packages/author/ @missing-elements/h5p-author — a playable .h5p of an scripts/ sync-skill.mjs writes the skill's type files' generated sections from the pack (`pnpm --filter @missing-elements/h5p-author sync:skill`); check-pack-published.mjs, the publish guard for the pinned pack and player, - and the normalizer's `./crc32` + and the normalizer's `./crc32`; copy-type-files.mjs, `prepack`'s copy of + the skill's type files into `references/types/`, which the package + carries and git does not (#172) tests/ node tests: the generator, text and translations, layouts and schema, the loader, builds with media from disk and a local server, the command, the quiz format, the check of saved content, the demo's packages among it, and diff --git a/packages/author/README.md b/packages/author/README.md index 681e10d8..74b73091 100644 --- a/packages/author/README.md +++ b/packages/author/README.md @@ -87,6 +87,16 @@ h5p-author: The source has 2 problems: params.behaviour.sideways: is not a field here; the fields are enableRetry, enableSolutionsButton, … ``` +What is written in the wrong place is said once, with what to write, and still checked, so that +what is wrong inside it comes in the same round: + +``` +h5p-author: The source has 3 problems: + params.slides: is a field of presentation, not of this level: write params.presentation.slides + params.slides[0].elements[0]: is sub-content, but here it goes inside an object, in its field action: write params.slides[0].elements[0] as { "action": { "library": "H5P.AdvancedText", "params": { … } } } + params.slides[0].elements[0].params.text: has

, which this field does not take; it takes
… +``` + The quiz format the h5p-author skill published first (`{ "kind": "question-set", "questions": [ … ] }`) is still taken, for a Multiple Choice question or a Question Set of them. @@ -108,6 +118,11 @@ H5P.TrueFalse 1.8: True/False Question `--all` adds the interface texts; `--markdown` prints the section the skill's type files carry. An unknown name lists the pack's content types. +The package carries those type files too, as the release has them: +`@missing-elements/h5p-author/references/types/H5P.TrueFalse.md` is the type's notes, an example and +these fields. A page that builds for a chat with no skill beside it hands them over with a source's +problems, as the [build page](https://missing-elements.github.io/h5p/build/) does. + ## A content type's bundle ```bash diff --git a/packages/author/lib/build.mjs b/packages/author/lib/build.mjs index 78923f80..e5a160da 100644 --- a/packages/author/lib/build.mjs +++ b/packages/author/lib/build.mjs @@ -190,11 +190,23 @@ export async function composePackage(source, pack, media) { // what the editor's widgets set and check what they would not let pass. Where the source has a // problem already, the check finds the same one again, or the gap it left: a value missing // where the generator refused what was written inside it. Only what it finds elsewhere is added. + // Since #172 it is named by where the source has it, which is another place than the content's + // for what the generator moved to its field; such a move is a problem of the source's, but + // nothing was refused there, so what the check finds inside it is added like any other. And + // what it says of a list an item of which was refused, or of anything in one, is left out: the + // list it counted is shorter than the one written, its items at other indices, so a book whose + // chapters were all refused had "0 items" besides. const checked = checkContent({ entries, main: mainLibrary, translations }, { type: libraryString(mainLibrary.library), params: generated }) const fromSource = [...problems] - const known = (/** @type {Problem} */ problem) => fromSource.some(({ path }) => path === problem.path || inside(problem.path, path) || - (inside(path, problem.path) && valueAt(checked.params, problem.path) === undefined)) - for (const problem of checked.problems) if (!known(problem)) problems.push(problem) + const moves = new Set(generator.moved.map(({ from }) => from)) + const inSource = (/** @type {string} */ path) => generator.moved.reduce((at, { from, to }) => at === to || inside(at, to) ? from + at.slice(to.length) : at, path) + const shortened = (/** @type {string} */ path) => generator.shortened.some((list) => path === list || inside(path, list)) + for (const { path: inContent, message } of checked.problems) { + const path = inSource(inContent) + const known = fromSource.some((problem) => problem.path === path || (inside(path, problem.path) && !moves.has(problem.path)) || + (inside(problem.path, path) && valueAt(checked.params, inContent) === undefined)) + if (!known && !shortened(path)) problems.push({ path, message }) + } for (const added of checked.notes) if (!notes.some(({ path, message }) => path === added.path && message === added.message)) notes.push(added) if (problems.length) throw new SourceError(problems) const content = checked.params diff --git a/packages/author/lib/generator.mjs b/packages/author/lib/generator.mjs index 26b77dba..db909e17 100644 --- a/packages/author/lib/generator.mjs +++ b/packages/author/lib/generator.mjs @@ -1,4 +1,5 @@ import { checkMetadata } from './metadata.mjs' +import { isInterfaceText } from './schema.mjs' import { allowedTags, markupText, plainText, takesMarkup } from './text.mjs' /** @@ -23,6 +24,17 @@ import { allowedTags, markupText, plainText, takesMarkup } from './text.mjs' * the player upgrades content written for an older minor, which may be what moves it, and plays * content written for a newer one without it. * + * Authoring, a problem says what to write, and what was written in another place than its field's + * is checked in the same round (#172). A source written without its type's file gets a type's + * levels wrong before anything else, and each such mistake hid all that was written inside it + * until the next build: sub-content in the place of the group that holds it in one of its fields, + * a field a level above the group that has it, and the parameters of the one library a field takes + * without the sub-content around them. Each is reported once, where it was written, and then + * generated where it belongs, its own problems named by where the source has them; `moved` says + * what went where, for whoever checks the content afterwards. A list an item of which was refused + * is named too, in `shortened`: it holds fewer items than were written, at other indices, so that + * what a later check says of it is not of the list in the source. + * * The editor is h5p-editor-php-library's form at commit 3bec2594356cf1be4e6401f7e7e557650720aa9b * (2026-10-08), and H5PEditor.ShowWhen 1.0.9 at 93678737300e084cb9390a691d3e1ad4e793fbaa for * `showWhen`. Each rule taken from them names the script it follows, here and in text.mjs, @@ -58,6 +70,9 @@ const SUB_CONTENT_ID = /^\{?[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f */ const FILE_KEYS = { file: [], image: ['width', 'height', 'originalImage'], video: ['width', 'height', 'codecs', 'quality', 'bitrate'], audio: [] } +/** What sub-content is written with, and the id H5P stores with it. */ +const SUB_CONTENT = ['library', 'params', 'metadata', 'subContentId'] + /** * @typedef {{ folder: string, library: any, semantics: any[] | null }} PackEntry * @typedef {{ path: string, message: string }} Problem @@ -79,6 +94,13 @@ export class ContentGenerator { */ #other = null + /** + * Where the source has what is stored in another place than it was written in, by the place it + * is stored in: its problems are named by where it was written. + * @type {Map} + */ + #written = new Map() + /** * @param {Map} pack every library folder the content may use, by folder name * @param {GeneratorOptions} [options] @@ -103,6 +125,13 @@ export class ContentGenerator { this.unset = [] /** @type {{ fields: any[], given: Record }[]} the levels a `showWhen` path climbs, innermost last */ this.scopes = [] + /** @type {string[]} written lists an item of which was refused: each holds fewer items than were written, at other indices */ + this.shortened = [] + /** + * @type {{ from: string, to: string }[]} what was written in another place than its field's: + * where the source has it, and where the content does, outermost first + */ + this.moved = [] } /** @@ -277,10 +306,10 @@ export class ContentGenerator { /** @type {Record} */ const out = {} if (!this.lenient && written !== undefined && !isObject(written)) { - this.report(path, `expected an object with the fields ${names(fields)}`) + this.report(path, `expected an object with the fields ${fieldNames(fields)}`) return out } - const given = isObject(written) ? written : {} + const given = !isObject(written) ? {} : this.lenient || this.saved ? written : this.#placed(fields, written, path) this.#level(fields, given, () => { for (const field of fields) { const value = this.field(this.#shown(field), given[field.name], stack, lenient, `${path}.${field.name}`) @@ -297,11 +326,67 @@ export class ContentGenerator { else if (this.saved && this.#other) { out[key] = value this.note(`${path}.${key}`, otherMinor(this.#other)) - } else this.report(`${path}.${key}`, `is not a field here; the fields are ${names(fields)}`) + } else this.report(`${path}.${key}`, `is not a field here; the fields are ${fieldNames(fields)}`) } return out } + /** + * What was written for a level, with what was written in another place than its field's put + * there, so that it is checked in the same round as what holds it. Each is reported once, where + * it was written, with what to write, and what is wrong inside it is named by where it was + * written too. Two mistakes, the ones a source written without its type's file makes first: + * + * - Sub-content in the place of the group that holds it: `{ "library", "params" }` where an item + * of a Column's `content` is `{ "content": { "library", "params" } }`, and a slide's element + * `{ "action": … }`. It was three problems an item, none of which said what to write. The + * problem names the item and shows it whole, since "it goes in the field content" was read as + * the list of that name, which the item is in already. + * - A field a level or more above the group that has it: `params.slides` for Course + * Presentation's `params.presentation.slides`, `params.enableRetry` for a question's + * `params.behaviour.enableRetry`. Only where one group within the level has a field of that + * name that takes such a value, and nothing is written there. An interface text is no such + * field: a question's text sent to a label of the same name would build, and read wrong. + * @param {any[]} fields + * @param {Record} given + * @param {string} path + * @returns {Record} + */ + #placed(fields, given, path) { + const holder = holderOf(fields, given) + if (holder) { + const subContent = pick(given, SUB_CONTENT) + const shown = ['library', 'params', 'metadata'].filter((key) => Object.hasOwn(subContent, key)) + .map((key) => key === 'library' ? `"library": ${JSON.stringify(given.library)}` : `"${key}": { … }`) + const beside = Object.keys(given).filter((key) => !SUB_CONTENT.includes(key) && fields.some((field) => field.name === key)).map((key) => `, "${key}": …`) + this.report(path, `is sub-content, but here it goes inside an object, in its field ${holder.name}: write ${path} as { "${holder.name}": { ${shown.join(', ')} }${beside.join('')} }`) + this.#move(path, `${path}.${holder.name}`) + given = { ...omit(given, SUB_CONTENT), [holder.name]: subContent } + } + for (const [key, value] of Object.entries(given)) { + if (value === null || value === undefined || fields.some((field) => field.name === key)) continue + const homes = homesOf(fields, key, value) + if (homes.length !== 1) continue + const placed = placedIn(omit(given, [key]), homes[0], key, value) + if (!placed) continue + const home = homes[0].join('.') + this.report(`${path}.${key}`, `is a field of ${home}, not of this level: write ${path}.${home}.${key}`) + this.#move(`${path}.${key}`, `${path}.${home}.${key}`) + given = placed + } + return given + } + + /** + * Notes what is stored in another place than it was written in. + * @param {string} from where the source has it + * @param {string} to where the content does + */ + #move(from, to) { + this.#written.set(to, from) + this.moved.push({ from, to }) + } + /** * @param {any} field * @param {any} written the written value, `null` to leave the field out, or undefined @@ -312,6 +397,8 @@ export class ContentGenerator { */ field(field, written, stack, lenient, path) { const optional = field.optional || lenient + // What is stored in another place than it was written in is named by where it was written. + path = this.#written.get(path) ?? path if (written === null) { if (!this.lenient && !field.optional && field.default === undefined && field.type !== 'boolean') this.report(path, 'is required and cannot be null') return undefined @@ -356,10 +443,21 @@ export class ContentGenerator { if (field.min !== undefined && written.length < field.min && !lenient) this.report(path, `has ${written.length} item${written.length === 1 ? '' : 's'}; it takes at least ${field.min}`) if (field.max !== undefined && written.length > field.max) this.report(path, `has ${written.length} items; it takes at most ${field.max}`) } - // Saved, an item that holds nothing an author has to write is one the editor started an - // optional list with, and nobody filled: nothing is asked of it. - return this.#level([], {}, () => written.map((each, index) => - this.field(item, each, stack, lenient || (this.saved && field.optional === true && !holds(item, each)), `${path}[${index}]`)).filter((each) => each !== undefined)) + return this.#level([], {}, () => { + /** @type {unknown[]} */ + const items = [] + let refused = false + written.forEach((each, index) => { + const before = this.problems.length + // Saved, an item that holds nothing an author has to write is one the editor started + // an optional list with, and nobody filled: nothing is asked of it. + const value = this.field(item, each, stack, lenient || (this.saved && field.optional === true && !holds(item, each)), `${path}[${index}]`) + if (value !== undefined) items.push(value) + else if (this.problems.length > before) refused = true + }) + if (refused) this.shortened.push(path) + return items + }) } if (written !== undefined && !this.lenient) { this.report(path, 'expected a list') @@ -387,7 +485,18 @@ export class ContentGenerator { case 'library': if (isObject(written) && typeof written.library === 'string') return this.writtenLibrary(written, stack, path, field) if (written !== undefined && !this.lenient) { - this.report(path, `expected sub-content, { "library": "${optionNames(field)[0] ?? 'H5P.…'}", "params": { … } }`) + // The parameters of the one library the field takes, without the sub-content around + // them, as a book's chapters written `{ "content": [ … ] }` (#172): said so, and checked + // as its parameters in the same round, named by where they are written. + const entry = !this.saved && isObject(written) ? this.#only(field) : null + const own = entry ? Object.keys(written).filter((key) => (entry.semantics ?? []).some((/** @type {any} */ each) => each.name === key)) : [] + if (entry && own.length) { + const metadata = own.includes('metadata') ? undefined : written.metadata + this.report(path, `is the params of sub-content, without the sub-content around them: write ${path} as { "library": "${entry.library.machineName}", "params": { "${own[0]}": … }${metadata === undefined ? '' : ', "metadata": { … }'} }`) + this.#move(path, `${path}.params`) + return this.writtenLibrary({ library: entry.library.machineName, params: metadata === undefined ? written : omit(written, ['metadata']), ...(metadata === undefined ? {} : { metadata }) }, stack, path, field, path) + } + this.report(path, `expected sub-content, ${subContentOf(field, written)}`) return undefined } // A default names the content the editor starts with (h5peditor.js puts it in the @@ -439,13 +548,15 @@ export class ContentGenerator { * @returns {T} */ #quietly(generate) { - const counts = [this.problems.length, this.notes.length, this.unset.length] + const counts = [this.problems.length, this.notes.length, this.unset.length, this.shortened.length, this.moved.length] try { return generate() } finally { this.problems.length = counts[0] this.notes.length = counts[1] this.unset.length = counts[2] + this.shortened.length = counts[3] + for (const { to } of this.moved.splice(counts[4])) this.#written.delete(to) } } @@ -518,6 +629,17 @@ export class ContentGenerator { return undefined } + /** + * The one library a field takes, as the pack has it: what parameters written without their + * sub-content are taken to be of. + * @param {any} field + */ + #only(field) { + const options = libraryOptions(field) + if (!options.length || options.some((option) => option.machineName !== options[0].machineName)) return null + return this.find(options[0].machineName, options[0].major) + } + /** * Written sub-content: the library it names, its parameters filled in from that library's * semantics. Lenient, a library the pack does not have is kept as written, for the check to @@ -526,8 +648,9 @@ export class ContentGenerator { * @param {string[]} stack * @param {string} path * @param {any} field the library field, or null for a default the semantics give + * @param {string} [at] where its parameters are written, where that is not in its `params` */ - writtenLibrary(written, stack, path, field) { + writtenLibrary(written, stack, path, field, at) { if (this.lenient) { const match = /^(\S+) (\d+)\.(\d+)$/.exec(written.library) const entry = match ? this.find(match[1], Number(match[2])) : null @@ -574,7 +697,7 @@ export class ContentGenerator { else if (isObject(written.metadata)) { for (const key of Object.keys(written.metadata)) if (key !== 'title') this.report(`${path}.metadata.${key}`, 'is not set per sub-content here; write only its title, the rest comes from the source') } - return this.subContent(entry, written.params, written.metadata, stack, path) + return this.subContent(entry, written.params, written.metadata, stack, path, { at }) } /** @@ -583,11 +706,12 @@ export class ContentGenerator { * @param {any} metadata its written metadata * @param {string[]} stack * @param {string} path - * @param {{ id?: unknown, minor?: number, closed?: boolean }} [saved] saved sub-content's id, the - * minor of its library it names, and whether nothing is asked of it + * @param {{ id?: unknown, minor?: number, closed?: boolean, at?: string }} [saved] saved + * sub-content's id, the minor of its library it names, and whether nothing is asked of it; + * `at`, where its parameters are written, where that is not in its `params` */ - subContent(entry, written, metadata, stack, path, { id, minor, closed = false } = {}) { - const params = this.#of(entry, minor, () => this.fields(entry.semantics ?? [], written, [...stack, entry.library.machineName], closed, `${path}.params`)) + subContent(entry, written, metadata, stack, path, { id, minor, closed = false, at = `${path}.params` } = {}) { + const params = this.#of(entry, minor, () => this.fields(entry.semantics ?? [], written, [...stack, entry.library.machineName], closed, at)) return { library: libraryString(entry.library), params, @@ -765,6 +889,100 @@ function optionNames(field) { return libraryOptions(field).map((option) => option.machineName) } +/** + * Sub-content as a field takes it, for a problem to show: with the library named where the field + * takes one alone, or where what was written names one it takes; else with every library it + * takes, since the first of several read as the one to write, and a scenario's texts came back as + * branching questions. + * @param {any} field + * @param {unknown} [written] + */ +function subContentOf(field, written) { + const taken = [...new Set(optionNames(field))] + const named = typeof written === 'string' ? written.trim().split(/\s+/)[0] : undefined + const library = taken.length === 1 ? taken[0] : taken.find((name) => name === named) + if (library) return `{ "library": "${library}", "params": { … } }` + return `{ "library": "${taken.length ? '…' : 'H5P.…'}", "params": { … } }${taken.length ? `, of ${taken.join(', ')}` : ''}` +} + +/** + * The field of a group that sub-content written in the group's place belongs in: the one library + * field that takes its library, or the group's only library field. None where `library` is a field + * of the group that holds no sub-content, where that field is written too, or where more than one + * could be meant. + * @param {any[]} fields + * @param {Record} given + */ +function holderOf(fields, given) { + if (typeof given.library !== 'string') return null + const holders = fields.filter((field) => field.type === 'library') + if (fields.some((field) => SUB_CONTENT.includes(field.name) && field.type !== 'library')) return null + const machineName = given.library.trim().split(/\s+/)[0] + const taking = holders.filter((field) => optionNames(field).includes(machineName)) + const holder = taking.length === 1 ? taking[0] : holders.length === 1 ? holders[0] : null + return holder && (holder.name === 'library' || !Object.hasOwn(given, holder.name)) ? holder : null +} + +/** + * The ways from a level's fields to a field of this name in a group within it, one an author + * writes and that takes a value of the kind written: for each, the groups' names, outermost + * first. So a list written as `slides` is Course Presentation's `presentation.slides` and not its + * interface text `l10n.slides`. A group of one field is no level of a source, being written as + * that field's value. + * @param {any[]} fields + * @param {string} name + * @param {unknown} value + * @param {string[]} [chain] + * @param {string[][]} [found] + */ +function homesOf(fields, name, value, chain = [], found = []) { + for (const field of fields) { + const children = field.fields ?? [] + if (field.type !== 'group' || (children.length === 1 && !field.isSubContent) || isInterfaceText(field)) continue + const within = [...chain, field.name] + if (children.some((/** @type {any} */ child) => child.name === name && !isInterfaceText(child) && takes(child, value))) found.push(within) + homesOf(children, name, value, within, found) + } + return found +} + +/** + * Whether a field takes a value of this kind: a list, an object, a text, a number, or true or + * false. A group of one field takes what that field does. + * @param {any} field + * @param {unknown} value + * @returns {boolean} + */ +function takes(field, value) { + if (field.type === 'group' && (field.fields ?? []).length === 1 && !field.isSubContent) return takes(field.fields[0], value) + if (Array.isArray(value)) return ['list', 'video', 'audio'].includes(field.type) || (field.type === 'select' && Boolean(field.multiple)) + // A group is the home of an object that writes a field of it. Its name alone is a coincidence: + // Game Map's `behaviour.map`, its labels and fog, is not where a `map` written for the picture goes. + // Nor is an interface text such a field: a source never writes one, so `{ l10n }` alone proves nothing. + if (isObject(value) && field.type === 'group') return Object.keys(value).some((key) => (field.fields ?? []).some((/** @type {any} */ each) => each.name === key && !isInterfaceText(each))) + if (isObject(value)) return ['library', 'image', 'file', 'video', 'audio'].includes(field.type) + if (typeof value === 'string') return field.type === 'text' || (field.type === 'select' && !field.multiple) + return typeof value === field.type +} + +/** + * What is written for a level, with a value put in a group within it, each group within the one + * named before; or null where something is written there already, or one of the groups is written + * as something else than an object. + * @param {Record} given + * @param {string[]} chain + * @param {string} key + * @param {unknown} value + * @returns {Record | null} + */ +function placedIn(given, chain, key, value) { + if (!chain.length) return Object.hasOwn(given, key) ? null : { ...given, [key]: value } + const [name, ...rest] = chain + if (given[name] !== undefined && !isObject(given[name])) return null + const placed = placedIn(given[name] ?? {}, rest, key, value) + return placed && { ...given, [name]: placed } +} + /** What a field's semantics add to what the platforms keep of its value. @param {any} field @returns {string[]} */ function extraAttributes(field) { return Array.isArray(field?.extraAttributes) ? field.extraAttributes.filter((/** @type {unknown} */ name) => typeof name === 'string') : [] @@ -828,6 +1046,16 @@ function names(fields) { return fields.map((field) => field.name).join(', ') } +/** + * A level's fields by name, for a problem to list: those an author writes, and the interface + * texts as one, since a translation supplies them and an Interactive Book has 35. + * @param {any[]} fields + */ +function fieldNames(fields) { + const written = fields.filter((field) => !isInterfaceText(field)) + return written.length && written.length < fields.length ? `${names(written)}, and the interface texts` : names(fields) +} + /** @param {string} html */ function stripTags(html) { return html.replace(/<[^<>]*>/g, ' ').replace(/\s+/g, ' ').trim() @@ -838,6 +1066,11 @@ function omit(object, keys) { return Object.fromEntries(Object.entries(object).filter(([key]) => !keys.includes(key))) } +/** @param {any} object @param {string[]} keys */ +function pick(object, keys) { + return Object.fromEntries(Object.entries(object).filter(([key]) => keys.includes(key))) +} + /** @param {unknown} value @returns {value is Record} */ function isObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value) diff --git a/packages/author/lib/libraries.mjs b/packages/author/lib/libraries.mjs index 25e4eb3a..be4ec45d 100644 --- a/packages/author/lib/libraries.mjs +++ b/packages/author/lib/libraries.mjs @@ -1,5 +1,5 @@ import { ownLibraries } from '@missing-elements/h5p-offline-player/plan' -import { libraryString } from './generator.mjs' +import { libraryOptions, libraryString } from './generator.mjs' import { SourceError } from './source-error.mjs' import { localize, translationFiles } from './translate.mjs' import { patchSemantics } from './types.mjs' @@ -50,7 +50,10 @@ const isObject = (value) => value !== null && typeof value === 'object' && !Arra * build loads them: the content type, every library its parameters name, and every one a library * field names as its default. Each library's semantics come with the interface texts of its own * translation for the language and with the fields a layout sets marked optional - * (`patchSemantics`). Every other library of the pack is in the map too, without its semantics. + * (`patchSemantics`). A library that is the only one a field takes is loaded too, named or not + * (#172): a book's chapters written without their H5P.Column can then be read as its parameters + * and checked. Such a library is in `translations` only where the content names it. Every other + * library of the pack is in the map too, without its semantics. * @param {LibrarySource} pack * @param {{ type: string, language: string, params?: unknown }} content `type` a machine name, with * a major and minor when known, `H5P.Blanks` or `H5P.Blanks 1.14` @@ -65,8 +68,12 @@ export async function loadLibraries(pack, { type, language, params }) { const main = /^(\S+?)(?:\s+(\d+)\.\d+)?$/.exec(String(type).trim()) const mainEntry = main ? pack.newest(main[1], main[2] === undefined ? undefined : Number(main[2])) : null if (!mainEntry) throw new SourceError([{ path: 'type', message: `the library pack has no content type ${type}` }]) - /** @type {{ machineName: string, major?: number }[]} */ + /** @type {{ machineName: string, major?: number, unnamed?: boolean }[]} */ const queue = [{ machineName: mainEntry.machineName, major: mainEntry.majorVersion }] + /** @type {Set} the folders of the libraries the content names, or a default does */ + const namedFolders = new Set() + /** @type {Map} by folder, in the order loaded */ + const reports = new Map() /** @param {unknown} value */ const named = (value) => { if (Array.isArray(value)) value.forEach(named) @@ -84,13 +91,22 @@ export async function loadLibraries(pack, { type, language, params }) { const defaults = (fields) => { for (const field of fields) { if (field.type === 'library' && isObject(field.default)) named(field.default) + if (field.type === 'library') { + // Read as the generator reads them, a name or `{ name }`, so that the two agree on which + // library is a field's only one. + const options = libraryOptions(field) + if (options.length && options.every(({ machineName }) => machineName === options[0].machineName)) { + for (const { machineName, major } of options) queue.push({ machineName, major, unnamed: true }) + } + } if (field.fields) defaults(field.fields) if (field.field) defaults([field.field]) } } while (queue.length) { - const { machineName, major } = /** @type {{ machineName: string, major?: number }} */ (queue.shift()) + const { machineName, major, unnamed } = /** @type {{ machineName: string, major?: number, unnamed?: boolean }} */ (queue.shift()) const entry = pack.newest(machineName, major) + if (entry && !unnamed) namedFolders.add(entry.folder) if (!entry || entries.has(entry.folder)) continue const part = await pack.open(entry) let semantics = part.semantics @@ -99,11 +115,12 @@ export async function loadLibraries(pack, { type, language, params }) { const localized = await localize(semantics, files, libraryString(part.library)) semantics = patchSemantics(part.library.machineName, localized.semantics) // By folder, not identity: a source may build its records anew on each call. - if (part.library.runnable || entry.folder === mainEntry.folder) translations.push(localized.report) + if (part.library.runnable || entry.folder === mainEntry.folder) reports.set(entry.folder, localized.report) defaults(semantics) } entries.set(entry.folder, { folder: entry.folder, library: part.library, semantics }) } + for (const [folder, report] of reports) if (namedFolders.has(folder)) translations.push(report) // Every library the index knows stays findable, so a name the pre-pass did not see is reported // as a library of the pack and not as an unknown one; its semantics are read when it is found. for (const entry of pack.libraries) { diff --git a/packages/author/lib/types.mjs b/packages/author/lib/types.mjs index 016d696c..6cfdc9cc 100644 --- a/packages/author/lib/types.mjs +++ b/packages/author/lib/types.mjs @@ -470,6 +470,9 @@ const branchingScenario = { // question, is -1 here: the field is hidden and required, and would be reported unset. if (node.nextContentId === undefined) node.nextContentId = -1 const alternatives = node?.type?.params?.branchingQuestion?.alternatives ?? [] + // Without alternatives it goes nowhere, which the list's own size reports: taken as an + // end, so that it is not reported again as a loop, which it is not (#172). + if (!alternatives.length) return [-1] return alternatives.map((/** @type {any} */ alternative, /** @type {number} */ j) => check(alternative?.nextContentId, `${nodeAt}.type.params.branchingQuestion.alternatives[${j}].nextContentId`)) } if (node?.nextContentId === undefined) { diff --git a/packages/author/package.json b/packages/author/package.json index e2a2f0cd..36e3fe99 100644 --- a/packages/author/package.json +++ b/packages/author/package.json @@ -32,11 +32,13 @@ "types": "./types/browser.d.mts", "default": "./lib/browser.mjs" }, + "./references/types/*.md": "./references/types/*.md", "./package.json": "./package.json" }, "files": [ "bin", "lib", + "references", "types" ], "keywords": [ @@ -54,7 +56,7 @@ "test:unit": "pnpm --filter @missing-elements/h5p-offline-player build:plan && vitest run --project node", "typecheck": "pnpm types && tsc -p tsconfig.json", "sync:skill": "pnpm --filter @missing-elements/h5p-offline-player build:plan && node scripts/sync-skill.mjs", - "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\" && pnpm types", + "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\" && node scripts/copy-type-files.mjs && pnpm types", "prepublishOnly": "node -e \"if (!/^pnpm\\//.test(process.env.npm_config_user_agent || '')) { console.error('Publish with pnpm publish: npm would ship the workspace: dependency ranges as they are, and the package would not install.'); process.exit(1) }\" && node scripts/check-pack-published.mjs && pnpm typecheck && pnpm test", "types": "pnpm --filter @missing-elements/h5p-offline-player exec tsc -b && node -e \"require('node:fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json" }, diff --git a/packages/author/scripts/copy-type-files.mjs b/packages/author/scripts/copy-type-files.mjs new file mode 100644 index 00000000..05f52e2b --- /dev/null +++ b/packages/author/scripts/copy-type-files.mjs @@ -0,0 +1,16 @@ +// The h5p-author skill's type files, copied into the package as `prepack` runs: each content +// type's notes, an example and its fields, as the release has them. A page that builds, with no +// skill beside it, hands them to a chat whose source had problems (#172). They are the skill's, at +// the repository's root, where `npx skills add` looks; the copy is not in git. +import { cp, mkdir, readdir, rm } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' + +const from = fileURLToPath(new URL('../../../skills/h5p-author/references/types/', import.meta.url)) +const to = fileURLToPath(new URL('../references/types/', import.meta.url)) + +await rm(fileURLToPath(new URL('../references/', import.meta.url)), { recursive: true, force: true }) +await mkdir(to, { recursive: true }) +const files = (await readdir(from)).filter((name) => name.endsWith('.md')) +if (!files.length) throw new Error(`No type files in ${from}`) +for (const name of files) await cp(`${from}${name}`, `${to}${name}`) +console.log(`Copied ${files.length} type files to references/types/`) diff --git a/packages/author/tests/build.test.ts b/packages/author/tests/build.test.ts index 45885ed4..c3a56e6d 100644 --- a/packages/author/tests/build.test.ts +++ b/packages/author/tests/build.test.ts @@ -1,6 +1,7 @@ import { execFile } from 'node:child_process' import { cp, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { createServer, type Server } from 'node:http' +import { createRequire } from 'node:module' import type { AddressInfo } from 'node:net' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' @@ -337,6 +338,45 @@ describe('any content type in the pack', () => { expect((await readdir(dir)).filter(name => name.startsWith('failed-') || name.startsWith('.h5p-author-'))).toEqual([]) }) + it('says what to write for what is in the wrong place, checks it in the same build, and counts no list it refused an item of (#172)', async () => { + // A book's chapters as a chat without the type's file writes them: pages of their own, with no + // H5P.Column around them, and sub-content in the place of a page's items. Every one of it in + // one build, by where the source has it; it was "expected sub-content" and "has 0 items". + expect(await problems({ ...META, type: 'H5P.InteractiveBook', params: { chapters: [ + { title: 'Sources', content: [{ library: 'H5P.AdvancedText', params: { text: 'A river begins at its source.' } }] } + ] } })).toEqual([ + 'params.chapters[0]: is the params of sub-content, without the sub-content around them: write params.chapters[0] as { "library": "H5P.Column", "params": { "content": … } }', + 'params.chapters[0].content[0]: is sub-content, but here it goes inside an object, in its field content: write params.chapters[0].content[0] as { "content": { "library": "H5P.AdvancedText", "params": { … } } }', + 'params.chapters[0].title: is not a field here; the fields are content', + 'params.chapters[0].metadata.title: is required: the chapter\'s name in the table of contents' + ]) + // A chapter refused whole leaves the list shorter: no count of what is left, and nothing said + // of the chapter after it under the index of the one refused. + expect(await problems({ ...META, type: 'H5P.InteractiveBook', params: { chapters: [ + 'Sources', + { library: 'H5P.Column', params: { content: [{ content: { library: 'H5P.AdvancedText', params: { text: 'A river ends at its mouth.' } } }] } } + ] } })).toEqual(['params.chapters[0]: expected sub-content, { "library": "H5P.Column", "params": { … } }']) + // A list a level above its group, and what is wrong inside it, in the same build. + expect(await problems({ ...META, type: 'H5P.CoursePresentation', params: { slides: [ + { elements: [{ library: 'H5P.AdvancedText', params: { text: '

Water

' }, x: 5, y: 5 }] } + ] } })).toEqual([ + 'params.slides: is a field of presentation, not of this level: write params.presentation.slides', + 'params.slides[0].elements[0]: is sub-content, but here it goes inside an object, in its field action: write params.slides[0].elements[0] as { "action": { "library": "H5P.AdvancedText", "params": { … } }, "x": …, "y": … }', + expect.stringMatching(/^params\.slides\[0\]\.elements\[0\]\.params\.text: has

, which this field does not take/) + ]) + // What only the last check finds, inside what was moved, is said too, by where the source has + // it: a scenario's node with no next. And a question with no alternatives is not a loop. + expect(await problems({ ...META, type: 'H5P.BranchingScenario', params: { branchingScenario: { title: 'A complaint', content: [ + { library: 'H5P.AdvancedText', params: { text: 'A customer calls.' } }, + { type: { library: 'H5P.BranchingQuestion', params: { question: 'What do you say?' } } } + ] } } })).toEqual([ + 'params.branchingScenario.content[0]: is sub-content, but here it goes inside an object, in its field type: write params.branchingScenario.content[0] as { "type": { "library": "H5P.AdvancedText", "params": { … } } }', + 'params.branchingScenario.content[1].type.params.question: is a field of branchingQuestion, not of this level: write params.branchingScenario.content[1].type.params.branchingQuestion.question', + 'params.branchingScenario.content[1].type.params.branchingQuestion.alternatives: is required: write at least 2 items', + 'params.branchingScenario.content[0].nextContentId: is required: the index in content of the node that follows, or -1 to end the scenario here' + ]) + }) + it('takes sub-content by machine name, at the pack\'s version, with its title', async () => { const { content, manifest } = await build({ ...META, @@ -631,6 +671,24 @@ describe('the build', () => { }, 120_000) }) +describe('the package', () => { + it('carries the skill\'s type files, copied as it is packed, for a page to hand to a chat (#172)', async () => { + const skill = resolve(import.meta.dirname, '../../../skills/h5p-author/references/types') + const copied = resolve(import.meta.dirname, '../references/types') + const { stdout } = await exec(process.execPath, [resolve(import.meta.dirname, '../scripts/copy-type-files.mjs')]) + const names = (await readdir(skill)).filter(name => name.endsWith('.md')).sort() + expect(names).toContain('H5P.InteractiveBook.md') + expect(stdout).toContain(`Copied ${names.length} type files`) + expect((await readdir(copied)).sort()).toEqual(names) + for (const name of names) expect(await readFile(join(copied, name), 'utf8'), name).toBe(await readFile(join(skill, name), 'utf8')) + // Packed and found: in `files`, copied by `prepack`, and each one an export of its own. + const manifest = JSON.parse(await readFile(resolve(import.meta.dirname, '../package.json'), 'utf8')) + expect(manifest.files).toContain('references') + expect(manifest.scripts.prepack).toContain('node scripts/copy-type-files.mjs') + expect(createRequire(import.meta.url).resolve('@missing-elements/h5p-author/references/types/H5P.InteractiveBook.md')).toBe(join(copied, 'H5P.InteractiveBook.md')) + }) +}) + describe('installing on an H5P site (#146)', () => { /** Every `library.json` an archive carries. */ const carried = (files: Map) => [...files].filter(([name]) => /^[^/]+\/library\.json$/.test(name)).map(([, text]) => JSON.parse(text)) diff --git a/packages/author/tests/generator.test.ts b/packages/author/tests/generator.test.ts index 02cf7348..9280dd8d 100644 --- a/packages/author/tests/generator.test.ts +++ b/packages/author/tests/generator.test.ts @@ -19,7 +19,7 @@ const LENIENT: GeneratorOptions = { lenient: true, id: (count) => `00000000-0000 function generate(semantics: unknown[], written?: unknown, others: Parameters[0] = [], options: GeneratorOptions = LENIENT) { const generator = new ContentGenerator(pack([{ machineName: 'H5P.Test', semantics }, ...others]), options) const params: Record = generator.generate(generator.find('H5P.Test')!, written) - return { params, problems: generator.problems, notes: generator.notes, media: generator.media, unset: generator.unset } + return { params, problems: generator.problems, notes: generator.notes, media: generator.media, unset: generator.unset, moved: generator.moved, shortened: generator.shortened } } describe('content generated from semantics, as the sweep runs it', () => { @@ -259,6 +259,170 @@ describe('content authored from semantics', () => { expect(wrong.problems).toEqual([{ path: 'params.content.library', message: 'H5P.Image is not one this field takes; it takes H5P.AdvancedText' }]) }) + it('shows sub-content with the library a field takes, every one where it takes several, and the one written by name (#172)', () => { + const IMAGE = { machineName: 'H5P.Image', minor: 1, title: 'Image', semantics: [{ name: 'alt', type: 'text' }] } + const { problems } = generate([ + { name: 'one', type: 'library', optional: true, options: ['H5P.AdvancedText 1.1'] }, + { name: 'any', type: 'library', optional: true, options: ['H5P.AdvancedText 1.1', 'H5P.Image 1.1'] }, + { name: 'named', type: 'library', optional: true, options: ['H5P.AdvancedText 1.1', 'H5P.Image 1.1'] } + ], { one: 'Hello', any: { text: 'Hello' }, named: 'H5P.Image 1.1' }, [TEXT, IMAGE], STRICT) + // The first of several read as the one to write, and a scenario's texts came back as questions. + expect(problems.map(({ path, message }) => `${path}: ${message}`)).toEqual([ + 'params.one: expected sub-content, { "library": "H5P.AdvancedText", "params": { … } }', + 'params.any: expected sub-content, { "library": "…", "params": { … } }, of H5P.AdvancedText, H5P.Image', + 'params.named: expected sub-content, { "library": "H5P.Image", "params": { … } }' + ]) + }) + + it('says once what to write for sub-content in the place of the group that holds it, and checks it in the same round (#172)', () => { + const column = [{ + name: 'content', + type: 'list', + field: { name: 'item', type: 'group', fields: [ + { name: 'content', type: 'library', options: ['H5P.AdvancedText 1.1'] }, + { name: 'useSeparator', type: 'select', default: 'auto', options: [{ value: 'auto' }, { value: 'enabled' }] } + ] } + }] + const { params, problems, moved } = generate(column, { content: [ + { library: 'H5P.AdvancedText', params: { text: 'One' }, metadata: { title: 'First' } }, + { library: 'H5P.AdvancedText 1.1', params: { text: '

Two

', size: 2 }, useSeparator: 'enabled', colour: 'red' } + ] }, [TEXT], STRICT) + // One problem an item, naming the item and showing it whole: "it goes in the field content" + // was read as the list of that name. What is wrong inside is named by where the source has it. + expect(problems.map(({ path, message }) => `${path}: ${message}`)).toEqual([ + 'params.content[0]: is sub-content, but here it goes inside an object, in its field content: write params.content[0] as { "content": { "library": "H5P.AdvancedText", "params": { … }, "metadata": { … } } }', + 'params.content[1]: is sub-content, but here it goes inside an object, in its field content: write params.content[1] as { "content": { "library": "H5P.AdvancedText 1.1", "params": { … } }, "useSeparator": … }', + expect.stringMatching(/^params\.content\[1\]\.params\.text: has

, which this field does not take/), + 'params.content[1].params.size: is not a field here; the fields are text', + 'params.content[1].colour: is not a field here; the fields are content, useSeparator' + ]) + // Generated where it belongs, so that a check of the content finds what is inside it. + expect(params.content[0]).toMatchObject({ content: { library: 'H5P.AdvancedText 1.1', params: { text: '
One
' } }, useSeparator: 'auto' }) + expect(params.content[1].useSeparator).toBe('enabled') + expect(moved).toEqual([{ from: 'params.content[0]', to: 'params.content[0].content' }, { from: 'params.content[1]', to: 'params.content[1].content' }]) + + // Nothing is guessed where `library` is a field of the group that holds no sub-content, where + // the field that holds it is written too, or where two fields could be meant. + const plain = generate([{ name: 'item', type: 'group', fields: [{ name: 'library', type: 'text' }, { name: 'content', type: 'library', optional: true, options: ['H5P.AdvancedText 1.1'] }] }], { item: { library: 'The city library' } }, [TEXT], STRICT) + expect(plain.problems).toEqual([]) + const both = generate(column, { content: [{ library: 'H5P.AdvancedText', content: { library: 'H5P.AdvancedText', params: { text: 'One' } } }] }, [TEXT], STRICT) + expect(both.problems.map(({ path, message }) => `${path}: ${message}`)).toEqual(['params.content[0].library: is not a field here; the fields are content, useSeparator']) + const two = generate([{ name: 'item', type: 'group', fields: [ + { name: 'front', type: 'library', optional: true, options: ['H5P.AdvancedText 1.1'] }, + { name: 'back', type: 'library', optional: true, options: ['H5P.AdvancedText 1.1'] } + ] }], { item: { library: 'H5P.AdvancedText', params: { text: 'One' } } }, [TEXT], STRICT) + expect(two.problems.map(({ path }) => path)).toEqual(['params.item.library', 'params.item.params']) + expect(two.moved).toEqual([]) + }) + + it('takes the params of the one library a field takes, written without their sub-content, as such, and checks them (#172)', () => { + const book = [{ name: 'chapters', type: 'list', min: 1, field: { name: 'chapter', type: 'library', options: ['H5P.AdvancedText 1.1'] } }] + const { params, problems, moved, shortened } = generate(book, { chapters: [{ text: '

One

', title: 'First' }, { text: 'Two', metadata: { title: 'Second' } }] }, [TEXT], { + ...STRICT, + metadata: (entry, written) => ({ contentType: entry.library.title, title: written?.title }) + }) + expect(problems.map(({ path, message }) => `${path}: ${message}`)).toEqual([ + 'params.chapters[0]: is the params of sub-content, without the sub-content around them: write params.chapters[0] as { "library": "H5P.AdvancedText", "params": { "text": … } }', + expect.stringMatching(/^params\.chapters\[0\]\.text: has

, which this field does not take/), + 'params.chapters[0].title: is not a field here; the fields are text', + 'params.chapters[1]: is the params of sub-content, without the sub-content around them: write params.chapters[1] as { "library": "H5P.AdvancedText", "params": { "text": … }, "metadata": { … } }' + ]) + expect(params.chapters[1]).toMatchObject({ library: 'H5P.AdvancedText 1.1', params: { text: '
Two
' }, metadata: { title: 'Second' } }) + expect(moved).toEqual([{ from: 'params.chapters[0]', to: 'params.chapters[0].params' }, { from: 'params.chapters[1]', to: 'params.chapters[1].params' }]) + expect(shortened).toEqual([]) + // Not where the field takes several libraries, or none of what is written is a field of the one. + const other = generate(book, { chapters: [{ heading: 'One' }] }, [TEXT], STRICT) + expect(other.problems).toEqual([{ path: 'params.chapters[0]', message: 'expected sub-content, { "library": "H5P.AdvancedText", "params": { … } }' }]) + }) + + it('says where a field written above the group that has it belongs, and checks it there in the same round (#172)', () => { + const semantics = [ + { name: 'presentation', type: 'group', fields: [ + { name: 'slides', type: 'list', field: { name: 'slide', type: 'group', fields: [{ name: 'title', type: 'text' }, { name: 'keywords', type: 'text', optional: true }] } }, + { name: 'display', type: 'boolean', default: true } + ] }, + { name: 'behaviour', type: 'group', fields: [ + { name: 'enableRetry', type: 'boolean', default: true }, + { name: 'passPercentage', type: 'number', min: 0, max: 100, default: 100 }, + { name: 'deep', type: 'group', fields: [{ name: 'mode', type: 'select', default: 'a', options: [{ value: 'a' }, { value: 'b' }] }, { name: 'depth', type: 'number', default: 1 }] } + ] }, + { name: 'solo', type: 'group', optional: true, fields: [{ name: 'inner', type: 'text', optional: true }] }, + { name: 'l10n', type: 'group', common: true, fields: [{ name: 'slides', type: 'text', default: 'Slides' }, { name: 'retry', type: 'text', default: 'Retry' }] } + ] + const { params, problems, moved } = generate(semantics, { + slides: [{ title: 'One' }, { title: 2 }], enableRetry: false, passPercentage: 150, mode: 'c', inner: 'x', retry: 'Again', nowhere: [] + }, [], STRICT) + expect(problems.map(({ path, message }) => `${path}: ${message}`)).toEqual([ + // A list named as an interface text is too is the list's field: `l10n.slides` takes a text. + 'params.slides: is a field of presentation, not of this level: write params.presentation.slides', + 'params.enableRetry: is a field of behaviour, not of this level: write params.behaviour.enableRetry', + 'params.passPercentage: is a field of behaviour, not of this level: write params.behaviour.passPercentage', + 'params.mode: is a field of behaviour.deep, not of this level: write params.behaviour.deep.mode', + 'params.slides[1].title: expected text, such as "2"', + 'params.passPercentage: is 150; the most it takes is 100', + 'params.mode: "c" is not an option; the options are "a", "b"', + // A group of one field is written as that field's value, so it is no level to point to. + 'params.inner: is not a field here; the fields are presentation, behaviour, solo, and the interface texts', + // Nor is an interface text: a text sent to a label of its name would build, and read wrong. + 'params.retry: is not a field here; the fields are presentation, behaviour, solo, and the interface texts', + 'params.nowhere: is not a field here; the fields are presentation, behaviour, solo, and the interface texts' + ]) + expect(params.presentation.slides).toEqual([{ title: 'One' }, {}]) + expect(params.behaviour).toMatchObject({ enableRetry: false, deep: { depth: 1 } }) + expect(moved.map(({ from, to }) => `${from} > ${to}`)).toEqual([ + 'params.slides > params.presentation.slides', 'params.enableRetry > params.behaviour.enableRetry', + 'params.passPercentage > params.behaviour.passPercentage', 'params.mode > params.behaviour.deep.mode' + ]) + + // Left where it is, where something is written in its place already, or two groups have such a field. + const taken = generate(semantics, { slides: [{ title: 'One' }], presentation: { slides: [{ title: 'Two' }] } }, [], STRICT) + expect(taken.problems.map(({ path }) => path)).toEqual(['params.slides']) + expect(taken.moved).toEqual([]) + const twice = generate([ + { name: 'first', type: 'group', fields: [{ name: 'label', type: 'text', default: 'a' }, { name: 'x', type: 'number', default: 0 }] }, + { name: 'second', type: 'group', fields: [{ name: 'label', type: 'text', default: 'b' }, { name: 'y', type: 'number', default: 0 }] } + ], { label: 'c' }, [], STRICT) + expect(twice.problems).toEqual([{ path: 'params.label', message: 'is not a field here; the fields are first, second' }]) + // Or where an object has a group's name and writes none of its fields: a `map` written for a + // picture is not Game Map's `behaviour.map`, and saying so would send the next source the wrong way. + const namesake = generate(semantics, { presentation: { slides: [{ title: 'One' }] }, deep: { picture: 'x' } }, [], STRICT) + expect(namesake.problems).toEqual([{ path: 'params.deep', message: 'is not a field here; the fields are presentation, behaviour, solo, and the interface texts' }]) + expect(namesake.moved).toEqual([]) + const written = generate(semantics, { presentation: { slides: [{ title: 'One' }] }, deep: { depth: 2, picture: 'x' } }, [], STRICT) + expect(written.problems.map(({ path, message }) => `${path}: ${message}`)).toEqual([ + 'params.deep: is a field of behaviour, not of this level: write params.behaviour.deep', + 'params.deep.picture: is not a field here; the fields are mode, depth' + ]) + expect(written.params.behaviour.deep.depth).toBe(2) + // Or one that writes only the group's interface texts, which a source does not write: they would + // be moved, checked there and refused, and the problem would say a label's place, not that it is no field. + const labelled = [{ name: 'wrapper', type: 'group', fields: [ + { name: 'panel', type: 'group', fields: [{ name: 'depth', type: 'number', default: 1 }, { name: 'l10n', type: 'group', common: true, fields: [{ name: 'retry', type: 'text', default: 'Retry' }, { name: 'check', type: 'text', default: 'Check' }] }] }, + { name: 'other', type: 'boolean', default: true } + ] }] + const texts = generate(labelled, { panel: { l10n: { retry: 'Again' } } }, [], STRICT) + expect(texts.problems).toEqual([{ path: 'params.panel', message: 'is not a field here; the fields are wrapper' }]) + expect(texts.moved).toEqual([]) + const both = generate(labelled, { panel: { depth: 2, l10n: { retry: 'Again' } } }, [], STRICT) + // One that writes a field of the group besides is moved, on that field's account. + expect(both.problems.map(({ path, message }) => `${path}: ${message}`)).toEqual([ + 'params.panel: is a field of wrapper, not of this level: write params.wrapper.panel' + ]) + expect(both.params.wrapper.panel.depth).toBe(2) + }) + + it('names a list it refused an item of, which then holds fewer items than were written (#172)', () => { + const { params, problems, shortened } = generate([ + { name: 'chapters', type: 'list', min: 2, field: { name: 'chapter', type: 'library', options: ['H5P.AdvancedText 1.1', 'H5P.Image 1.1'] } }, + { name: 'tags', type: 'list', optional: true, field: { name: 'tag', type: 'text', default: 'none' } } + ], { chapters: [{ title: 'One' }, { library: 'H5P.AdvancedText', params: { text: 'Two' } }, 'Three'], tags: ['a', null] }, [TEXT], STRICT) + expect(problems.map(({ path }) => path)).toEqual(['params.chapters[0]', 'params.chapters[2]']) + expect(params.chapters).toHaveLength(1) + // An item written as null and left out, as one with a default may be, is no refusal. + expect(params.tags).toEqual(['a']) + expect(shortened).toEqual(['params.chapters']) + }) + it('leaves a library default an author never opened as the editor leaves it, asking nothing', () => { const { params, problems } = generate([{ name: 'task', type: 'library', default: { library: 'H5P.AdvancedText 1.1', params: {} }, options: ['H5P.AdvancedText 1.1'] }], {}, [TEXT], STRICT) expect(problems).toEqual([]) diff --git a/packages/author/tests/libraries.test.ts b/packages/author/tests/libraries.test.ts index d58dd9e9..e573e00e 100644 --- a/packages/author/tests/libraries.test.ts +++ b/packages/author/tests/libraries.test.ts @@ -51,6 +51,38 @@ describe('loadLibraries', () => { expect(translations.find((report) => report.library.startsWith('H5P.InteractiveVideo '))?.translation).toBe('de') }) + it('loads the only library a field takes, named or not, and reports its translation only where it is named (#172)', async () => { + // A book's chapters written without their H5P.Column: its semantics are what reads them as its + // parameters, and nothing is said of its translation, which the content does not use yet. + const unnamed = await loadLibraries(pack, { type: 'H5P.InteractiveBook', language: 'de', params: { chapters: [{ content: [] }] } }) + expect(entryOf(unnamed.entries, 'H5P.Column')?.semantics).not.toBeNull() + expect(unnamed.translations.map((report) => report.library.split(' ')[0])).toEqual(['H5P.InteractiveBook']) + // Named, it is reported where it was before: after the content type, in the order named. + const named = await loadLibraries(pack, { type: 'H5P.InteractiveBook', language: 'de', params: { chapters: [{ library: 'H5P.Column', params: { content: [{ content: { library: 'H5P.TrueFalse', params: {} } }] } }] } }) + expect(named.translations.map((report) => report.library.split(' ')[0])).toEqual(['H5P.InteractiveBook', 'H5P.Column', 'H5P.TrueFalse']) + // A field that takes several is left alone: Column's own content loads nothing it does not name. + expect(entryOf(named.entries, 'H5P.MultiChoice')).toMatchObject({ semantics: null }) + // An option written `{ name }`, as semantics may write one and the generator reads it, counts too. + const book = pack.newest('H5P.InteractiveBook')! + const source: LibrarySource = { + libraries: pack.libraries, + newest: (machineName, major) => pack.newest(machineName, major), + open: async (entry) => { + const part = await pack.open(pack.libraries.find(({ folder }) => folder === entry.folder)!) + if (entry.folder !== book.folder) return part + // A chapter is a group of one field, the page's library field. + const semantics = (part.semantics as Field[]).map((field) => field.name !== 'chapters' ? field : { + ...field, + field: { ...field.field!, fields: field.field!.fields!.map((page) => ({ ...page, options: (page as Field & { options: string[] }).options.map((name) => ({ name })) })) } + }) + return { ...part, semantics } + }, + translation: (part, name) => pack.translation(part, name) + } + const objects = await loadLibraries(source, { type: 'H5P.InteractiveBook', language: 'en', params: {} }) + expect(entryOf(objects.entries, 'H5P.Column')?.semantics).not.toBeNull() + }) + it('marks the fields a layout sets optional, and leaves the pack\'s own semantics as they are', async () => { const { entries } = await loadLibraries(pack, content) expect(fieldAt(entryOf(entries, 'H5P.Video')!.semantics as Field[], 'visuals.poster')?.optional).toBe(true) diff --git a/skills/h5p-author/SKILL.md b/skills/h5p-author/SKILL.md index be8925b8..bd91220f 100644 --- a/skills/h5p-author/SKILL.md +++ b/skills/h5p-author/SKILL.md @@ -58,7 +58,11 @@ the same package. ## 2. Write the source Read the type's file, `references/types/.md`: notes, an example, its fields. Parts other -content holds have files too: H5P.AdvancedText, H5P.Image, H5P.Video, H5P.Text. +content holds have files too: H5P.AdvancedText, H5P.Image, H5P.Video, H5P.Text. With this text +alone and no file beside it, open the file at +`https://raw.githubusercontent.com/missing-elements/h5p-offline-player/main/skills/h5p-author/references/types/.md`; +where nothing opens, write the source from what you know of the type: the build says, for each +place that is wrong, what to write there. ```json { @@ -74,6 +78,9 @@ content holds have files too: H5P.AdvancedText, H5P.Image, H5P.Video, H5P.Text. - A file is `{ "path": "photo.jpg" }`, beside the source or a web address, with `copyright` when known. - Sub-content is `{ "library": "H5P.MultiChoice", "params": { … }, "metadata": { "title": "…" } }`. + Where it sits is the type file's to say, a level deeper than a guess puts it: an item of + H5P.Column's `content` is `{ "content": }`, a slide's element + `{ "action": }` in `presentation.slides[].elements`, a book's chapter an H5P.Column. ## 3. Build