diff --git a/.github/workflows/content-types.yml b/.github/workflows/content-types.yml index db936c6a..b18be677 100644 --- a/.github/workflows/content-types.yml +++ b/.github/workflows/content-types.yml @@ -16,6 +16,8 @@ on: - 'apps/demo/sweep/**' - 'apps/demo/scripts/sweep-content-types.mjs' - 'apps/demo/scripts/lib/sweep-content.mjs' + # The generator the sweep runs, the author package's since #100. + - 'packages/author/lib/generator.mjs' - '.github/workflows/content-types.yml' schedule: - cron: '0 7 * * 1' diff --git a/.github/workflows/libraries.yml b/.github/workflows/libraries.yml index 1def6aed..b4760980 100644 --- a/.github/workflows/libraries.yml +++ b/.github/workflows/libraries.yml @@ -1,8 +1,8 @@ name: Library pack # Rebuilds packages/libraries from the H5P hub every week and opens a pull request when a library -# changed. The pack is built deterministically, in any time zone, so an unchanged hub leaves the -# tree clean. +# changed, saying whether every content type and h5p-author's examples play against it. The pack is +# built deterministically, in any time zone, so an unchanged hub leaves the tree clean. on: schedule: @@ -62,6 +62,8 @@ jobs: # The player's libraries="pack" pins this version and carries its parts' index: stamp # both in the same change. pnpm --filter @missing-elements/h5p-offline-player sync:assets + # The h5p-author skill's type files list each content type's fields from the pack. + pnpm --filter @missing-elements/h5p-author sync:skill # Every content type played against the new pack, for the review: CI does not start on # a pull request a workflow opened, so the result goes into its description. @@ -73,10 +75,26 @@ jobs: fi report=$(cat "$RUNNER_TEMP/sweep/report.md" 2>/dev/null || tail -n 30 "$RUNNER_TEMP/sweep.log") + # h5p-author against the new pack, for the same reason: its own tests, then every type + # file's example built and played, untrusted and trusted (apps/skills), which is where a + # library's renamed, new or hidden field shows. The playback test drives Playwright's + # Chromium. + pnpm --filter @missing-elements/h5p-offline-player exec playwright install chromium > /dev/null + author_ok=true + NO_COLOR=1 pnpm --filter @missing-elements/h5p-author test > "$RUNNER_TEMP/author.log" 2>&1 || author_ok=false + NO_COLOR=1 pnpm --filter @missing-elements/h5p-skills test >> "$RUNNER_TEMP/author.log" 2>&1 || author_ok=false + if $author_ok; then + author="h5p-author builds and plays every type file's example against the new pack, untrusted and trusted, and its own tests pass." + author_details="" + else + author="**h5p-author fails against the new pack**: fix the type file, its example or \`packages/author/lib/types.mjs\` on this branch. The tests' output is below." + author_details=$(printf '%s\n' "
h5p-author's tests" "" '```' "$(tail -n 120 "$RUNNER_TEMP/author.log" | sed -e 's/\x1b\[[0-9;]*m//g')" '```' "" "
") + fi + git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' git switch -C "$branch" - git add packages/libraries packages/player/src/shared/constants.ts packages/player/src/shared/pack-index.ts + git add packages/libraries packages/player/src/shared/constants.ts packages/player/src/shared/pack-index.ts skills/h5p-author/references/types git commit -m "chore(libraries): refresh from the H5P hub, $version" git push --force origin "$branch" @@ -96,11 +114,15 @@ jobs: "" \ "$sweep" \ "" \ + "$author" \ + "" \ "
The sweep's report" \ "" \ "$report" \ "" \ - "
") + "" \ + "" \ + "$author_details") if gh pr view "$branch" --json state --jq .state 2>/dev/null | grep -q OPEN; then gh pr edit "$branch" --title "Library pack $version" --body "$body" diff --git a/.gitignore b/.gitignore index 0309098c..52072b77 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ node_modules dist dist-demo +# The plain-JS packages' generated declarations; the h5p-author skill's content-type files are not. types +!skills/h5p-author/references/types/ .vercel # Generated: the player's `sync:assets` vendors the h5p-standalone runtime into @@ -12,9 +14,10 @@ public # Copied from the repository root by the player's `prepack`, so npm finds them in the package. packages/player/README.md packages/player/LICENSE -# The same for the normalizer, the verifier, the cmi5 wiring and the embed site writer, whose `prepack` copies the LICENSE. +# The same for the normalizer, the verifier, the author, the cmi5 wiring and the embed site writer, whose `prepack` copies the LICENSE. packages/normalize/LICENSE packages/verify/LICENSE +packages/author/LICENSE packages/cmi5/LICENSE packages/embed/LICENSE diff --git a/AGENTS.md b/AGENTS.md index bfb3e7aa..0d6a1727 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,8 +28,8 @@ The hard constraints that shape every file here: ## Layout -A pnpm workspace of ten parts: eight packages and two apps, the demo and the skills' test project. -Seven of the packages are published to npm; the eighth, the VS Code extension, is a `.vsix`. Paths +A pnpm workspace of eleven parts: nine packages and two apps, the demo and the skills' test project. +Eight of the packages are published to npm; the ninth, the VS Code extension, is a `.vsix`. Paths elsewhere in this file are relative to the part they belong to — `src/…` and `scripts/…` mean the player's unless a section says otherwise. @@ -167,6 +167,28 @@ packages/verify/ @missing-elements/h5p-verify — plays a package headl ranges, a browser playing from it, its ending and its command line types/ generated, not in git: the declarations, `VerifyReport` among them +packages/author/ @missing-elements/h5p-author — a playable .h5p of any content type in the pack from a short + source, published as a command (see *The author package*) + bin/h5p-author.mjs the command: `build` and `schema` + lib/build.mjs the source read and checked, the libraries loaded and localized, the + content generated, media copied, layouts run, the archive written + lib/generator.mjs `ContentGenerator`: content from a type's `semantics.json`, authoring + (every written value checked as the editor's form would) or lenient, as + the sweep 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 + lib/text.mjs, translate.mjs, media.mjs, pack.mjs, schema.mjs, quiz.mjs text as H5P stores it; the + libraries' translations; files and web addresses; the pinned pack read + by part; the field list a source is written from; the skill's quiz format + 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 + tests/ node tests: the generator, text and translations, layouts and schema, + builds with media from disk and a local server, the command; + package-types.ts as for the normalizer + types/ generated, not in git: the declarations + packages/cmi5/ @missing-elements/h5p-cmi5 — cmi5 for the element, published as a library src/index.ts startCmi5(player): the launch, the outcome, terminate; its pure parts (allowedStatement, cmi5Score, webAddress) exported for tests @@ -249,7 +271,7 @@ apps/demo/ the demo app: the dev server for the whole repository, tests/app.test.ts the installable app's screens, history and keyboard, through the dev server; engine.ts and harness.ts its helpers. The demo's other pages have no tests (see *Commands*) - tests/sweep-content.test.ts the sweep's content generator, in Node + tests/sweep-content.test.ts the sweep's fill for h5p-author's generator, in Node cmi5-catapult/ docker-compose.yml for ADL's CATAPULT player, MySQL and the SQL LRS; scripts/cmi5-catapult.mjs clones CATAPULT into it (ignored) and proves the cmi5 page against the player @@ -264,7 +286,8 @@ apps/demo/ the demo app: the dev server for the whole repository, scripts/ build-demo (the site into dist-demo/), build-demo-content, build-og-image, build-app-icons, build-app-screenshots, build-libraries (the pack, into packages/libraries), sweep-content-types (every content type in the pack - played; see *The content-type sweep*), lib/sweep-content.mjs its generator, + played; see *The content-type sweep*), lib/sweep-content.mjs its way of running + h5p-author's generator, lib/code-blocks.mjs the Vite plugin that highlights the pages' code, lib/hub.mjs the hub host, the cache and the download the two hub-reading scripts share, lib/pages.mjs the one list of the site's pages, for the @@ -281,20 +304,15 @@ apps/demo/ the demo app: the dev server for the whole repository, site root -> dist-demo/ apps/skills/ the skills' test project, a project of the kind a skill's user runs it in: - it installs what h5p-author tells its user to install, the library pack and - zip.js, which the script resolves from it, and the verifier the skill runs - with npx; nothing in it ships. Out of the demo since 2026-10-23, by the - owner's choice - tests/author.test.ts h5p-author's helper in Node: its quiz validation, its archives, the - interface texts from the libraries' translations for the quiz's language, - a damaged library part refused by its SHA-256 before anything is - published, a zip.js older than 2.24 stopped with the install command, - and the skill copied outside the checkout, resolving its dependencies - from the calling project - tests/author-verify.test.ts both quiz kinds, the eight-scenario example, a quiz in Ukrainian and one - whose titles and author carry quotes and markup through the verifier's - published API, trusted and untrusted against the installed pack: each a - pass with no warnings + it installs the commands the skills run with npx, the author package and + the verifier, and the library pack; nothing in it ships. Out of the demo + since 2026-10-23, by the owner's choice + tests/author-verify.test.ts every h5p-author type file's example built, with sample media, and + played trusted and untrusted through the verifier's published API, each + a pass with no warnings; each file's generated section compared with + the pack's, so a pack refresh shows a change; and the quiz format: both + kinds, the eight-scenario example, a quiz in Ukrainian and one whose + titles and author carry quotes and markup tests/author-playback.test.ts the eight-scenario example in the verifier's preview, the review the skill hands a person, trusted and untrusted: every question's feedback, 75% failing and 83.3% passing an 80% threshold, retry to 100%, and only @@ -325,12 +343,12 @@ skills/ agent skills, one directory per skill, at the root bec `npx skills add ` looks: h5p-verify (when to run the verifier and how to read its report), h5p-player-setup (putting the player on a site), h5p-normalize (when a package needs rewriting to stream, and how to read the dry run) - and h5p-author (text-only Multiple Choice and Question Set from a prompt: - a quiz JSON source, the installed pack's semantics, its translations for - the quiz's language (2026-10-31, #96) and runtime dependency closure, - then the verifier's check, its screenshot and its preview for the user; - its bundled scripts/build-quiz.mjs resolves dependencies from the - caller's project, and is tested from apps/skills) + and h5p-author (any of 28 content types from a prompt, since #100: the + type chosen with the user first, a source of only what differs from the + defaults, written from references/types/.md — notes, a tested + example and the fields, their section generated from the pack — built + with `npx @missing-elements/h5p-author`, then the verifier's check, its + screenshot and its preview for the user; tested from apps/skills) api/no-range.js the Vercel function that stands in for a host without Range on the demo vercel.json the deployment: build command, the /no-range rewrite, caching and security headers @@ -369,6 +387,8 @@ pnpm typecheck # every package pnpm build # the player: types, element, both workers; builds the runtime package on the way pnpm normalize course.h5p # rewrite a package so it streams: media stored, mp4 index first pnpm verify course.h5p # play a package in a headless browser and report whether it works +pnpm author build source.json course.h5p # a package of any content type in the pack from a short source +pnpm --filter @missing-elements/h5p-author sync:skill # the h5p-author skill's type files' fields, from the pack pnpm --filter h5p-preview package # the VS Code extension's .vsix, from the player as pnpm build left it pnpm --filter h5p-preview test:vscode # its suite in a VS Code it downloads; under xvfb-run on Linux pnpm --filter h5p-preview screenshot # its listing's screenshot, images/preview.png, in that VS Code @@ -438,10 +458,11 @@ cmi5 page also against CATAPULT (`pnpm cmi5:catapult`). Where a page's test was package's behaviour, the test moved into the package: the embed page asking before it plays a package that needs its own code, and `resizer.js` answering a frame that loaded before it, are in `packages/embed/tests/site.test.ts`; the cmi5 page's were already in `packages/cmi5/tests/`. -The skills' scripts are source too, tested from `apps/skills`, a project of their own (2026-10-23, -the owner's choice). h5p-author's tests were first in the demo, which had the pack and zip.js -installed, and in the verifier's tests, and the playback test played the quiz through the -installable app. It plays it in the verifier's preview now, the page the skill hands a person to +The skills are source too, tested from `apps/skills`, a project of their own (2026-10-23, the +owner's choice): what they tell an agent to write builds and plays. h5p-author's own code is the +author package's since #100, tested with it. Its tests were first in the demo, which had the pack +and zip.js installed, and in the verifier's tests, and the playback test played the quiz through +the installable app. It plays it in the verifier's preview now, the page the skill hands a person to review it in, and in Chromium only, where in the demo the `engines` job ran it in Firefox and WebKit too; the player's own suite covers the engines. @@ -1928,6 +1949,121 @@ The tests need the player built (`pnpm build`); the package's `test` script does The repository's own sweep does click through content and read its statements (next section), for packages it makes; the verifier, which is handed a stranger's, still does not. +## The author package + +`@missing-elements/h5p-author` builds a playable package of any content type in the pack from a +source of only what an author would write: `{ type, title, language, license, authors, params }`, +`params` holding the fields that differ from their defaults. Built on 2026-11-01 for #100, the +owner's design: the content type chosen with the user first, a file per type in the h5p-author +skill so no agent works out how a type is built, a short skill, one package for the whole pack. It +replaced the skill's bundled `scripts/build-quiz.mjs`, which built Multiple Choice and Question Set +alone, and its quiz format stays a source the build takes (`lib/quiz.mjs` maps it), so nothing +written in it broke. 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. Seven things the code +does not say by itself: + +- **One generator, two ways to run it.** `ContentGenerator` was the sweep's + (`apps/demo/scripts/lib/sweep-content.mjs`), and moved here so there is one copy; the sweep runs + it `lenient`, keeping what its files write as written and filling every required field from its + own samples, and its 55 types came out byte for byte the same after the move. Authoring checks + every written value as H5P's editor would let an author save it, and reports every problem with + its path, all at once, so a fix is one round: a field the semantics do not name, a select's + unknown option, a number out of range or with decimals the editor's number field refuses, a list + too short or long, a required field with neither a value nor a default, sub-content of a library + the field does not take. What the editor does is the rule, read from h5p-editor-php-library's + widgets at a pinned commit (*The editor is pinned* below): a new list starts with `defaultNum`, + `min` or one item, and a list such an item needs writing in is reported as one missing list; a + field its `showWhen` rule hides is not asked for (Multimedia Choice's poster, wanted only for + audio), the rule's `../` climbing a level for each group and each list, as the editor's + `findField` climbs from widget to parent; media fields, which the editor + never asks for, are required where the semantics say so, and optional where a type plays without + them (H5P.Video's poster); a library default nobody opened, Interactive Video's summary task, is + left as the editor leaves it, asking nothing. +- **Text is stored as the platforms store it.** A plain field is escaped as `htmlspecialchars` + does, existing entities kept, and a tag in it is noted, since a learner sees it as written. A + field with `tags` takes markup with the tags the content check keeps for it (its own, `div`, + `span`, `p`, `br`, and what they imply), checked here rather than filtered later: any other tag, + an event handler, a style the field does not allow, a script address or a comment is a problem + by name. Plain text written into such a field is wrapped as the editor wraps typing: in `

` + where the field's `enterMode` is `p` or its tags offer headings, `pre`, `p` or `div`, in `

` + otherwise. Every plain default is escaped too, English or translated, and a `null` default (Course + Presentation's colours) is left out, which the content check would otherwise turn into a + warning. Every type file's example plays untrusted with no warning, which is the test of this. +- **Some types need what their editor widget does.** Course Presentation, Interactive Video, Game + Map and Branching Scenario are edited on a slide, a video, a map and a tree of their own, which set + fields the form hides (`widget: "none"`). `lib/types.mjs` does each one's work on the generated + content, wherever the type appears: a slide's unplaced elements stacked, text as tall as its lines + on CP's 16:9 slide at 16 px per 640, pictures shrunk in shape, a question in what is left, with a + note when a slide holds too much; interactions placed apart, clear of what shows at the same + time, and named by their library; a poster sized by what it holds, in IV's em (a 16:9 video is + 40 by 22.5): a picture in its shape, as the editor's own widget does, a text as wide as keeps + it short, a question 17 by 16. The editor starts every interaction at 10 by 10 and leaves the + rest to the author's mouse, and seen in Chrome, 10 by 10 showed two answers of four and hid the + Check button behind a scroll (#100's review); on a phone IV shows posters as buttons. Stages + given ids and types, neighbours named by label made indices both ways; end screens numbered. It + checks what those widgets would not let pass: a scenario node with no next, a link to no node, a + loop no path leaves; a map with no start; a hotspot question with no right area. A hidden field + nothing set is reported. Lists such a widget draws start empty. +- **Media are copied and described.** A file is `{ path }`, beside the source or an `http(s)` + address, downloaded at build time; it lands under `content/images|videos|audios|files/` with its + MIME type, an image's size read from its header (PNG, JPEG, GIF, BMP; a JPEG's segments walked to + its frame header, which a colour profile can put past the first 64 kB, where the first cut + stopped and refused the picture), and its copyright, on H5P's own list of types (no SVG, no + WebP). A download is given up after a minute with no byte, not after a fixed time: the first cut + allowed two minutes in all, which a large video over a slow link outlasts. A YouTube, Vimeo, + Panopto or Echo360 address stays, as the editor embeds it, and only one H5P.Video plays: it + chooses a player by its own pattern for each host, and an address none matches goes to its + HTML5 player, which cannot play a page. So the build takes an address only where that pattern + does too, a Short's or a live stream's written as its video's watch address, and refuses + another on those hosts, naming the form; `build.test.ts` holds each accepted address to the + patterns read from H5P.Video's scripts in the pack. The first cut took `youtube.com/shorts/`, + `player.vimeo.com` and any `panopto.com` address, which built and then did not play, and knew + no Echo360 (found in the PR's own review). A package with media goes through the + normalizer's `normalizeArchive`, so it is stored and laid out to stream, an mp4's index first. + An addon whose pattern the text matches, H5P.MathDisplay for LaTeX, is carried as a site with + it installed exports it. +- **The pack is pinned.** The dependency is `workspace:*`, published as the exact version + packages/libraries has, so a release builds with the libraries it was tested with and one command + needs no project set up; `--libraries` names another `parts/` folder. Each part is checked + against the index's SHA-256 before it is read. `prepublishOnly` refuses while that version is not + on npm with this checkout's index (`scripts/check-pack-published.mjs`), as the player's does. +- **The skill's type files are partly generated.** `skills/h5p-author/references/types/.md` + holds hand-written notes, an example, and the type's fields between two markers, written by + `schemaOf(…, { markdown: true })`: names, kinds, defaults, options, list sizes, a markup field's + tags, the sub-content the pack has, the syntax the editor's `important` box explains, `showWhen` + conditions; interface texts and the fields a layout sets left out. The weekly pack refresh runs + `sync:skill`; `apps/skills`' test fails on a file out of date, and builds and plays every + example. 28 content types have files, and the parts other content holds (Text, Image, Video); + any other type's fields are one `h5p-author schema` away. +- **The editor is pinned, and not watched** (2026-11-01, the owner's choice, as for the content + check). Nothing the editor does decides whether a package plays: the libraries and the platforms' + validator do, both pinned here too. A change in the editor makes a build differ from what the + editor now saves, in the rule that changed, and no more. A change in a library can matter, and + reaches the author with the weekly pack refresh, which since #100's review runs the author's + tests and `apps/skills`' against the new pack and says in its pull request whether every + example still builds and plays: a renamed field, a new required one or a new hidden one fails + there by name. The rules were read from h5p-editor-php-library at 3bec259 (2026-10-08), whose + `master` had not moved since, and H5PEditor.ShowWhen 1.0.9; the layouts' from the editors the + pack's content types name in `editorDependencies`, each at the newest release of the minor named, + which GitHub's default branch is not always: H5PEditor.InteractiveVideo 1.26.3, + H5PEditor.BranchingScenario 1.5.13 (its `main` is 1.6) and H5PEditor.GameMap 1.2.5 (1.5). + `generator.mjs` and `types.mjs` name the commits and where they depart from the editor, and each + rule the script it follows. To move to a newer editor by hand: diff those scripts between the + pinned commit and `master`, or between the pinned release and the one a refreshed pack names; + port what changed; move the commits named in the two files; and run the author's tests and + `apps/skills`'. Pinning found three things the first cut had wrong: a number's steps were + counted from `min`, where the editor's `value % step` counts from 0; a `showWhen` path skipped + the level the editor gives a list and a group of one field, which only Advent Calendar's door + cover reached (`../../modeDoorImage`, from a list's item, optional either way; the pack's other + 98 rules resolve alike); and two comments said the editor sets what it does not, a Branching + Question's own `nextContentId`, which it deletes, and a Game Map stage's `type`, which it keeps + out of the content. Both fields are still written, being hidden and required, and the runtime + ignores the first and works the second out again. + +Not built: editing an existing package, 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. + ## The VS Code extension `packages/vscode` is **H5P Preview by Missing Elements** (`MissingElements.h5p-preview`): a `.h5p` @@ -2306,7 +2442,7 @@ Not covered: ## Types for the plain-JS packages -The normalizer, the verifier and the embed package are JavaScript with JSDoc, and since #60 their +The normalizer, the verifier, the embed package and the author are JavaScript with JSDoc, and since #60 their documented API ships with declarations generated from it: `tsconfig.json` checks `lib/` (and `site/embed.js`) with `checkJs`, `tsconfig.types.json` emits the entries' declarations into `types/` with `stripInternal`, and each `exports` entry names them under `types`. `pnpm types` @@ -2349,8 +2485,9 @@ been measured on four content types: the hub serves no example content, and h5p. carry licences of their own and old versions, so each package is made here. 110 plays take about three minutes locally, five on CI. -- **Content is generated from the content type's own `semantics.json`** - (`lib/sweep-content.mjs`), as H5P's editor saves a form: every default, and for a required field +- **Content is generated from the content type's own `semantics.json`** by the author package's + generator, run lenient with the sweep's fill (`lib/sweep-content.mjs`; one copy since #100, + checked byte for byte on all 55 types when it moved), as H5P's editor saves a form: every default, and for a required field without one the smallest value the content check accepts — a label as text, the first sample a pattern accepts, the minimum number, the first option, a list as long as its `min` or `defaultNum`, the sample image, video or audio. A group's own default is its whole value; a group diff --git a/README.md b/README.md index 9057b53b..fb96f063 100644 --- a/README.md +++ b/README.md @@ -63,8 +63,10 @@ something else. [privacy](https://github.com/missing-elements/h5p-offline-player/blob/main/docs/privacy.md). - **Comes with tools for pipelines.** [`h5p-verify`](https://github.com/missing-elements/h5p-offline-player/blob/main/docs/verify.md) plays a package headless and says whether it works, [`h5p-normalize`](https://github.com/missing-elements/h5p-offline-player/blob/main/docs/streaming-video.md) - rewrites one so its video streams, and [`h5p-embed`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/embed#readme) - writes the embed site. The [agent skills](#agent-skills) cover those workflows and quiz authoring. + rewrites one so its video streams, [`h5p-embed`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/embed#readme) + writes the embed site, and [`h5p-author`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/author#readme) + builds a package of any content type from a short JSON source. The [agent skills](#agent-skills) + cover those workflows and authoring. - **Is tested where it runs.** CI runs the browser tests in Chromium, Firefox and WebKit on every change, and plays every content type in the library pack, untrusted and trusted, on each change to the player, the runtime or the pack, and every week. @@ -199,8 +201,10 @@ npx skills add missing-elements/h5p-offline-player ``` [`h5p-author`](https://github.com/missing-elements/h5p-offline-player/tree/main/skills/h5p-author) -turns a prompt or lesson into a Multiple Choice or Question Set, verifies it in the real player and -opens it in your browser for you to play before handing it over. `h5p-player-setup` puts H5P on a +turns a prompt or lesson into H5P content of any of 28 types, chosen with you first: quizzes, fill +in the blanks, flash cards, presentations, interactive books, branching scenarios, interactive video +and more. It verifies the package in the real player and opens it in your browser for you to play +before handing it over. `h5p-player-setup` puts H5P on a site, `h5p-normalize` fixes packages whose video will not stream, and `h5p-verify` checks that a generated package plays. They work with Claude Code and other agents with filesystem and command access, with no provider API key or H5P server; a verifier pass checks startup and rendering, not diff --git a/apps/demo/package.json b/apps/demo/package.json index 81770a77..59865fc7 100644 --- a/apps/demo/package.json +++ b/apps/demo/package.json @@ -23,6 +23,7 @@ "@vercel/analytics": "^2.0.1" }, "devDependencies": { + "@missing-elements/h5p-author": "workspace:*", "@missing-elements/h5p-libraries": "workspace:*", "@missing-elements/h5p-normalize": "workspace:*", "@types/node": "^26.6.5", diff --git a/apps/demo/scripts/lib/sweep-content.mjs b/apps/demo/scripts/lib/sweep-content.mjs index df5faa14..a18986d2 100644 --- a/apps/demo/scripts/lib/sweep-content.mjs +++ b/apps/demo/scripts/lib/sweep-content.mjs @@ -1,17 +1,19 @@ +import { ContentGenerator, librariesIn, libraryString } from '@missing-elements/h5p-author' + /** - * Content for a content type, made from its own `semantics.json` as H5P's editor would save a form: - * what is written by hand in `apps/demo/sweep/.json` where it says something, and - * everywhere else every default the semantics give and, for a required field without one, the - * smallest value the content check accepts. A field that holds another content type takes the - * library the hand-written value names, filled in the same way, or else the first of its options - * the pack has. So a hand-written file states only what generation cannot know — a question's - * right answer, which drop zone an item belongs in — and a list in it is as long as it is written. + * The sweep's way of running the content generator, which is @missing-elements/h5p-author's (one + * copy since 2026-11-01, #100): lenient, taking what `apps/demo/sweep/.json` writes as + * it is, and filling every required field the semantics give no default for with the smallest + * value the content check accepts — a label as text, the first sample a pattern accepts, the + * minimum number, the first option, the sample image, video or audio, the first sub-content the + * pack has. Authoring refuses such a field instead; the sweep has to make every content type play. * - * Pure: the pack is handed in as a map of folders, and a value points at media by the paths in - * `MEDIA` without writing them, so `tests/sweep-content.test.ts` runs it in Node. The sweep finds - * the files and the libraries a package uses in its final parameters (`mediaIn`, `librariesIn`). + * Deterministic: sub-content ids are numbered, so generated packages are the same bytes every run. + * `tests/sweep-content.test.ts` holds the sweep's rules; the generator's own are the package's. */ +export { ContentGenerator, librariesIn, libraryString } + /** The files a generated value may point at, under `content/`, and what each one is. */ export const MEDIA = { image: { path: 'images/sample.png', mime: 'image/png', width: 640, height: 360 }, @@ -27,181 +29,28 @@ export const MEDIA = { */ const PATTERNED_SAMPLES = ['Sample', '#808080', 'https://example.org/', 'sample@example.org', '+1 555 0100', '2026/1/1', '12:00', '2026,1,1', '100px', '0', 'a'] -/** The nesting depth at which a library field stops choosing content of its own. */ -const MAX_DEPTH = 4 - -/** @typedef {{ folder: string, library: any, semantics: any[] | null }} PackLibrary */ - -export class ContentGenerator { - /** @param {Map} pack every library folder in the pack, by folder name */ - constructor(pack) { - this.pack = pack - this.ids = 0 - } - - /** - * The newest library in the pack with this machine name and, when given, this major — the - * one the player serves for any minor of it. - * @param {string} machineName - * @param {number} [major] - */ - find(machineName, major) { - let best = null - for (const entry of this.pack.values()) { - const { library } = entry - if (library.machineName !== machineName) continue - if (major !== undefined && library.majorVersion !== major) continue - if (!best || library.majorVersion > best.library.majorVersion || (library.majorVersion === best.library.majorVersion && library.minorVersion > best.library.minorVersion)) best = entry - } - return best - } - - /** - * The parameters for a library's content, with `written` — the hand-written parameters, if - * any — laid in. - * @param {PackLibrary} entry - * @param {any} [written] - */ - generate(entry, written) { - return this.fields(entry.semantics ?? [], written, [entry.library.machineName], false) - } - - /** A deterministic sub-content id: generated packages are the same bytes every run. */ - nextId() { - this.ids += 1 - return `00000000-0000-4000-8000-${this.ids.toString(16).padStart(12, '0')}` - } - - /** - * @param {any[]} fields - * @param {any} written the hand-written object for these fields, or undefined - * @param {string[]} stack the content types this value sits inside, to keep a type out of itself - * @param {boolean} lenient inside an optional group nobody wrote: defaults only, as the editor - * saves a group left closed — and so no sample image for a field required only within it - */ - fields(fields, written, stack, lenient) { - const out = {} - const given = isObject(written) ? written : {} - for (const field of fields) { - const value = this.field(field, given[field.name], stack, lenient) - if (value !== undefined) out[field.name] = value - } - // What the semantics do not name is kept as written: the content check removes it, which a - // file may mean to test. - for (const [key, value] of Object.entries(given)) if (!(key in out) && value !== null && !fields.some((field) => field.name === key)) out[key] = value - return out - } - - /** - * @param {any} field - * @param {any} written the hand-written value, `null` to leave the field out, or undefined - * @param {string[]} stack - * @param {boolean} lenient - */ - field(field, written, stack, lenient) { - if (written === null) return undefined - const optional = field.optional || lenient +/** @type {import('@missing-elements/h5p-author').GeneratorOptions} */ +export const sweepOptions = { + lenient: true, + id: (count) => `00000000-0000-4000-8000-${count.toString(16).padStart(12, '0')}`, + fill(field, { generator, stack }) { switch (field.type) { - case 'group': { - const children = field.fields ?? [] - // A group of one field is saved as that field's value, as the editor and the content - // check have it, unless the group is sub-content. - const flattened = children.length === 1 && !field.isSubContent - if (written === undefined && field.default !== undefined) return field.default - if (written !== undefined && !flattened && !isObject(written)) return written - const value = this.fields(children, flattened ? { [children[0].name]: written } : written, stack, optional && written === undefined) - // Saved even when optional and untouched, as the editor saves every group in its form: - // content types read into one without looking (Personality Quiz's `image.file`). - return flattened ? value[children[0].name] : value - } - case 'list': { - const item = { ...field.field, optional: false } - if (Array.isArray(written)) return written.map((each) => this.field(item, each, stack, false)).filter((each) => each !== undefined) - const count = Math.min(Math.max(optional ? 0 : (field.min ?? 0), field.defaultNum ?? (optional ? 0 : 1)), field.max ?? Infinity) - const items = [] - for (let index = 0; index < count; index++) { - const value = this.field(item, undefined, stack, lenient) - if (value !== undefined) items.push(value) - } - return items.length > 0 || !optional ? items : undefined - } case 'library': - if (isObject(written) && typeof written.library === 'string') return this.writtenLibrary(written, stack) - // A default names the content the editor starts with: Interactive Video's summary task. - if (written === undefined && isObject(field.default) && typeof field.default.library === 'string') return this.writtenLibrary(field.default, stack) - return optional ? undefined : this.library(field, stack) + return generator.library(field, stack) case 'text': - if (written !== undefined) return written - if (field.default !== undefined) return field.default - return optional ? undefined : sampleText(field) + return sampleText(field) case 'number': - if (written !== undefined) return written - if (field.default !== undefined) return field.default - return optional ? undefined : Math.max(field.min ?? 0, Math.min(field.max ?? Infinity, 1)) - case 'boolean': - // The editor's checkbox saves false when nobody ticked it. - return written ?? field.default ?? false + return Math.max(field.min ?? 0, Math.min(field.max ?? Infinity, 1)) case 'select': - if (written !== undefined) return written - if (field.default !== undefined) return field.default - return optional || !field.options?.length ? undefined : field.options[0].value + return field.options?.length ? field.options[0].value : undefined case 'image': case 'file': - if (written !== undefined) return written - return optional ? undefined : { ...MEDIA[field.type], copyright: { license: 'U' } } + return { ...MEDIA[field.type], copyright: { license: 'U' } } case 'video': case 'audio': - if (written !== undefined) return written - return optional ? undefined : [{ path: MEDIA[field.type].path, mime: MEDIA[field.type].mime, copyright: { license: 'U' } }] + return [{ path: MEDIA[field.type].path, mime: MEDIA[field.type].mime, copyright: { license: 'U' } }] default: - return written - } - } - - /** - * Sub-content: the first option the pack has and that is not already a parent here, made from - * its own semantics. None at all is left out, which the content check would do anyway. - * @param {any} field - * @param {string[]} stack - */ - library(field, stack) { - if (stack.length > MAX_DEPTH) return undefined - for (const option of field.options ?? []) { - const name = typeof option === 'string' ? option : option?.name - const match = /^(\S+) (\d+)\.(\d+)$/.exec(name ?? '') - if (!match || stack.includes(match[1])) continue - const entry = this.find(match[1], Number(match[2])) - if (!entry) continue - return this.subContent(entry, undefined, stack) - } - return undefined - } - - /** - * Sub-content written by hand: the library it names, its parameters filled in from that - * library's semantics. A library the pack does not have is kept as written, for the check to - * remove or the runtime to refuse. - * @param {any} written - * @param {string[]} stack - */ - writtenLibrary(written, stack) { - const match = /^(\S+) (\d+)\.(\d+)$/.exec(written.library) - const entry = match ? this.find(match[1], Number(match[2])) : null - if (!entry) return written - return { ...this.subContent(entry, written.params, stack), ...omit(written, ['params']), library: libraryString(entry.library) } - } - - /** - * @param {PackLibrary} entry - * @param {any} written - * @param {string[]} stack - */ - subContent(entry, written, stack) { - return { - library: libraryString(entry.library), - params: this.fields(entry.semantics ?? [], written, [...stack, entry.library.machineName], false), - subContentId: this.nextId(), - metadata: { contentType: entry.library.title, license: 'U', title: entry.library.title } + return undefined } } } @@ -212,21 +61,6 @@ export function mediaIn(params) { return /** @type {(keyof typeof MEDIA)[]} */ (Object.keys(MEDIA)).filter((kind) => text.includes(`"${MEDIA[kind].path}"`)) } -/** Every `library` string in the parameters: the sub-content a package plays. */ -export function librariesIn(params, found = new Set()) { - if (Array.isArray(params)) for (const item of params) librariesIn(item, found) - else if (isObject(params)) { - if (typeof params.library === 'string' && /^\S+ \d+\.\d+$/.test(params.library)) found.add(params.library) - for (const value of Object.values(params)) librariesIn(value, found) - } - return found -} - -/** `H5P.MultiChoice 1.16`, the form `library` fields and `h5p.json` use. */ -export function libraryString(library) { - return `${library.machineName} ${library.majorVersion}.${library.minorVersion}` -} - /** * Text for a required field: its label, as an editor would show it, as markup for an HTML * field, or the first sample its pattern accepts. @@ -245,11 +79,3 @@ function sampleText(field) { function escapeHtml(text) { return text.replace(/[&<>"]/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[character]) } - -function omit(object, keys) { - return Object.fromEntries(Object.entries(object).filter(([key]) => !keys.includes(key))) -} - -function isObject(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value) -} diff --git a/apps/demo/scripts/sweep-content-types.mjs b/apps/demo/scripts/sweep-content-types.mjs index 7ce309bb..78e84313 100644 --- a/apps/demo/scripts/sweep-content-types.mjs +++ b/apps/demo/scripts/sweep-content-types.mjs @@ -6,18 +6,19 @@ import { extname, join, normalize, resolve } from 'node:path' import { crc32, deflateSync } from 'node:zlib' import { BlobReader, BlobWriter, TextReader, Uint8ArrayReader, Uint8ArrayWriter, ZipReader, ZipWriter, configure } from '@zip.js/zip.js' import { chromium } from 'playwright' -import { ContentGenerator, MEDIA, libraryString, librariesIn, mediaIn } from './lib/sweep-content.mjs' +import { ContentGenerator, MEDIA, libraryString, librariesIn, mediaIn, sweepOptions } from './lib/sweep-content.mjs' /** * Plays every content type in the library pack and reports what each one does: whether it boots, * played `untrusted` and trusted, and what it sends when worked through. Built on 2026-10-14; the * hub serves no example content, so each package is made here. * - * Each content type's content is generated from its own `semantics.json` (`lib/sweep-content.mjs`), - * and `sweep/.json`, where one exists, adds what generation cannot give — a drop - * zone, words that cross — and the element's attributes for it (`attributes`). The packages are - * content-only, as h5p.com and h5p.org export, so the pack supplies every library: this is the - * pack's own test as much as the player's. Run it with the player built (`pnpm build`): + * Each content type's content is generated from its own `semantics.json` by the generator of + * @missing-elements/h5p-author, run as `lib/sweep-content.mjs` says, and `sweep/.json`, + * where one exists, adds what generation cannot give — a drop zone, words that cross — and the + * element's attributes for it (`attributes`). The packages are content-only, as h5p.com and + * h5p.org export, so the pack supplies every library: this is the pack's own test as much as the + * player's. Run it with the player built (`pnpm build`): * * pnpm sweep every content type, both modes * pnpm sweep --only H5P.Blanks one or more, comma-separated @@ -52,7 +53,7 @@ const SETTLE = 1_500 for (const mode of modes) if (mode !== 'untrusted' && mode !== 'trusted') fail(`--modes: unknown mode "${mode}"`) const pack = await readPack(packPath) -const generator = new ContentGenerator(pack) +const generator = new ContentGenerator(pack, sweepOptions) if (args.semantics) { const entry = generator.find(args.semantics) if (!entry) fail(`--semantics: no ${args.semantics} in the pack`) diff --git a/apps/demo/tests/sweep-content.test.ts b/apps/demo/tests/sweep-content.test.ts index c2d0a37b..764494ef 100644 --- a/apps/demo/tests/sweep-content.test.ts +++ b/apps/demo/tests/sweep-content.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest' -import { ContentGenerator, MEDIA, librariesIn, mediaIn } from '../scripts/lib/sweep-content.mjs' +import { ContentGenerator, MEDIA, librariesIn, mediaIn, sweepOptions } from '../scripts/lib/sweep-content.mjs' + +/** + * The sweep's way of running @missing-elements/h5p-author's generator: what it fills a required + * field with so that every content type plays. The generator's own rules are tested in the package. + */ /** A pack of the libraries a test names: folder -> library.json and semantics.json. */ function pack(libraries: { machineName: string; major?: number; minor?: number; title?: string; semantics: unknown[] }[]) { @@ -14,12 +19,11 @@ function pack(libraries: { machineName: string; major?: number; minor?: number; const TEXT = { machineName: 'H5P.AdvancedText', minor: 1, title: 'Text', semantics: [{ name: 'text', type: 'text', widget: 'html', label: 'Text' }] } function generate(semantics: unknown[], written?: unknown, others: Parameters[0] = []): Record { - const libraries = pack([{ machineName: 'H5P.Test', semantics }, ...others]) - const generator = new ContentGenerator(libraries) + const generator = new ContentGenerator(pack([{ machineName: 'H5P.Test', semantics }, ...others]), sweepOptions) return generator.generate(generator.find('H5P.Test')!, written) } -describe('content generated from semantics', () => { +describe('content the sweep generates', () => { it('takes every default, and the smallest valid value for a required field without one', () => { const params = generate([ { name: 'title', type: 'text', default: 'Hello' }, @@ -53,42 +57,6 @@ describe('content generated from semantics', () => { expect(params).toEqual({ color: '#808080', date: '2026/1/1' }) }) - it('saves a group of one field as that field, and a group default as the whole value', () => { - const params = generate([ - { name: 'single', type: 'group', fields: [{ name: 'only', type: 'text', default: 'x' }] }, - { name: 'sub', type: 'group', isSubContent: true, fields: [{ name: 'only', type: 'text', default: 'y' }] }, - { name: 'size', type: 'group', default: { width: 620, height: 310 }, fields: [{ name: 'width', type: 'number' }, { name: 'height', type: 'number' }] } - ]) - expect(params).toEqual({ single: 'x', sub: { only: 'y' }, size: { width: 620, height: 310 } }) - }) - - it('fills an optional group nobody wrote with defaults only, as the editor saves one left closed', () => { - const params = generate([ - { - name: 'image', - type: 'group', - optional: true, - fields: [ - { name: 'file', type: 'image' }, - { name: 'alt', type: 'text' }, - { name: 'decorative', type: 'boolean' }, - { name: 'position', type: 'select', default: 'left', options: [{ value: 'left' }] } - ] - } - ]) - expect(params).toEqual({ image: { decorative: false, position: 'left' } }) - }) - - it('makes a list as long as its minimum or default number, and leaves an optional one out', () => { - const params = generate([ - { name: 'answers', type: 'list', min: 2, field: { name: 'answer', type: 'text', default: 'a' } }, - { name: 'cards', type: 'list', defaultNum: 3, field: { name: 'card', type: 'text', default: 'c' } }, - { name: 'one', type: 'list', field: { name: 'item', type: 'text', default: 'i' } }, - { name: 'keywords', type: 'list', optional: true, field: { name: 'keyword', type: 'text' } } - ]) - expect(params).toEqual({ answers: ['a', 'a'], cards: ['c', 'c', 'c'], one: ['i'] }) - }) - it('fills a library field with the first option the pack has, never the content type itself', () => { const params = generate( [{ name: 'content', type: 'library', options: ['H5P.Test 1.0', 'H5P.Missing 1.0', 'H5P.AdvancedText 1.1'] }], @@ -105,54 +73,8 @@ describe('content generated from semantics', () => { }) }) - it('uses a library field default as written content', () => { - const params = generate([{ name: 'task', type: 'library', default: { library: 'H5P.AdvancedText 1.0', params: { text: '

Given

' } }, options: ['H5P.AdvancedText 1.1'] }], undefined, [TEXT]) - expect(params.task).toMatchObject({ library: 'H5P.AdvancedText 1.1', params: { text: '

Given

' } }) - }) -}) - -describe('hand-written content laid in', () => { - const QUESTION = [ - { name: 'question', type: 'text', widget: 'html', label: 'Question' }, - { - name: 'answers', - type: 'list', - min: 1, - field: { name: 'answer', type: 'group', fields: [{ name: 'text', type: 'text', widget: 'html', label: 'Text' }, { name: 'correct', type: 'boolean' }, { name: 'tip', type: 'text', default: '' }] } - }, - { name: 'behaviour', type: 'group', fields: [{ name: 'random', type: 'boolean', default: true }, { name: 'retry', type: 'boolean', default: true }] } - ] - - it('keeps what is written, fills in the rest, and keeps a written list as long as it is', () => { - const params = generate(QUESTION, { - answers: [{ text: '
Right
', correct: true }, { text: '
Wrong
' }], - behaviour: { random: false } - }) - expect(params).toEqual({ - question: '

Question

', - answers: [ - { text: '
Right
', correct: true, tip: '' }, - { text: '
Wrong
', correct: false, tip: '' } - ], - behaviour: { random: false, retry: true } - }) - }) - - it('removes a field written as null, and keeps a key the semantics do not name', () => { - const params = generate(QUESTION, { question: null, unknown: 1 }) - expect(params).not.toHaveProperty('question') - expect(params.unknown).toBe(1) - }) - - it('fills written sub-content from its own semantics, at the version the pack has', () => { - const params = generate([{ name: 'content', type: 'library', options: ['H5P.AdvancedText 1.1'] }], { content: { library: 'H5P.AdvancedText 1.0', params: {} } }, [TEXT]) - expect(params.content).toMatchObject({ library: 'H5P.AdvancedText 1.1', params: { text: '

Text

' } }) - expect(params.content.subContentId).toMatch(/^00000000-0000-4000-8000-/) - }) - - it('keeps sub-content of a library the pack does not have as written', () => { - const written = { library: 'H5P.Elsewhere 1.0', params: { a: 1 } } - expect(generate([{ name: 'content', type: 'library', options: [] }], { content: written }).content).toEqual(written) + it('keeps a key the semantics do not name, which the content check is then to remove', () => { + expect(generate([{ name: 'title', type: 'text', default: 'x' }], { unknown: 1 }).unknown).toBe(1) }) }) diff --git a/apps/skills/package.json b/apps/skills/package.json index 29e0fbc5..5799ac95 100644 --- a/apps/skills/package.json +++ b/apps/skills/package.json @@ -7,6 +7,7 @@ "typecheck": "tsc -p tsconfig.json" }, "devDependencies": { + "@missing-elements/h5p-author": "workspace:*", "@missing-elements/h5p-libraries": "workspace:*", "@missing-elements/h5p-verify": "workspace:*", "@types/node": "^26.6.5", diff --git a/apps/skills/tests/author-playback.test.ts b/apps/skills/tests/author-playback.test.ts index 9a162e61..b0cd23bf 100644 --- a/apps/skills/tests/author-playback.test.ts +++ b/apps/skills/tests/author-playback.test.ts @@ -4,11 +4,16 @@ import { join, resolve } from 'node:path' import { chromium, type Browser, type Page } from 'playwright' import { afterAll, beforeAll, expect, it } from 'vitest' import { previewPackage } from '../../../packages/verify/lib/preview.mjs' -import { buildQuiz, type Quiz } from '../../../skills/h5p-author/scripts/build-quiz.mjs' +import { buildPackage } from '@missing-elements/h5p-author' const project = resolve(import.meta.dirname, '..') // The pack this project installed, named to the preview as `--libraries` names a copy of its parts. const parts = resolve(project, 'node_modules/@missing-elements/h5p-libraries/parts') +/** The skill's quiz format, as the scenario example writes it. */ +type Quiz = { + kind: string, passPercentage?: number, passedFeedback?: string, failedFeedback?: string, + questions: { title?: string, prompt: string, multipleAnswers?: boolean, answers: { text: string, correct: boolean, feedback?: string }[] }[] +} const source: Quiz = JSON.parse(await readFile(resolve(project, '../../skills/h5p-author/assets/phishing-scenarios.json'), 'utf8')) const example: Quiz = JSON.parse(await readFile(resolve(project, '../../skills/h5p-author/assets/quiz.json'), 'utf8')) const single: Quiz = { ...example, kind: 'multiple-choice', questions: [example.questions[0]] } @@ -20,9 +25,9 @@ let browser: Browser beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), 'h5p-author-interaction-')) file = join(dir, 'scenarios.h5p') - await buildQuiz(source, file, project) + await buildPackage(source, file) singleFile = join(dir, 'single.h5p') - await buildQuiz(single, singleFile, project) + await buildPackage(single, singleFile) browser = await chromium.launch() }) afterAll(async () => { diff --git a/apps/skills/tests/author-verify.test.ts b/apps/skills/tests/author-verify.test.ts index b3ebdcbb..034b9db1 100644 --- a/apps/skills/tests/author-verify.test.ts +++ b/apps/skills/tests/author-verify.test.ts @@ -1,69 +1,142 @@ -import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' +import { crc32, deflateSync } from 'node:zlib' +import { BlobReader, Uint8ArrayWriter, ZipReader } from '@zip.js/zip.js' +import { buildPackage, schemaOf } from '@missing-elements/h5p-author' import { verifyPackage } from '@missing-elements/h5p-verify' -import { afterAll, beforeAll, expect, it } from 'vitest' -import { buildQuiz, type Quiz } from '../../../skills/h5p-author/scripts/build-quiz.mjs' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' const project = resolve(import.meta.dirname, '..') // The pack this project installed, named to the check as `--libraries` names a copy of its parts. const parts = resolve(project, 'node_modules/@missing-elements/h5p-libraries/parts') const skill = resolve(project, '../../skills/h5p-author') -const example: Quiz = JSON.parse(await readFile(join(skill, 'assets/quiz.json'), 'utf8')) -const scenarios: Quiz = JSON.parse(await readFile(join(skill, 'assets/phishing-scenarios.json'), 'utf8')) +const types = join(skill, 'references/types') +const example = JSON.parse(await readFile(join(skill, 'assets/quiz.json'), 'utf8')) +const scenarios = JSON.parse(await readFile(join(skill, 'assets/phishing-scenarios.json'), 'utf8')) +const META = { title: 'Example', language: 'en', license: 'CC BY', authors: [{ name: 'Ann Author', role: 'Author' }] } +const files = (await readdir(types)).filter((name) => name.endsWith('.md')).sort() let dir: string -const files = new Map() +let clip: Uint8Array + +/** The source a type file gives as its example, the metadata every source carries added. */ +async function exampleOf(file: string) { + const text = await readFile(join(types, file), 'utf8') + const block = /## Example\s+```json\n([\s\S]*?)\n```/.exec(text) + if (!block) throw new Error(`${file} has no example`) + return { ...META, ...JSON.parse(block[1]) } +} + +/** Every file an example names, by its `path`. */ +function paths(value: unknown, found: string[] = []): string[] { + if (Array.isArray(value)) value.forEach((item) => paths(item, found)) + else if (value && typeof value === 'object') { + const object = value as Record + if (typeof object.path === 'string') found.push(object.path) + Object.values(object).forEach((item) => paths(item, found)) + } + return found +} + +/** A PNG of one colour. */ +function png(width: number, height: number) { + const chunk = (type: string, data: Buffer) => { + const head = Buffer.alloc(8) + head.writeUInt32BE(data.length) + head.write(type, 4) + const crc = Buffer.alloc(4) + crc.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type), data]))) + return Buffer.concat([head, data, crc]) + } + const header = Buffer.alloc(13) + header.writeUInt32BE(width, 0) + header.writeUInt32BE(height, 4) + header[8] = 8 + header[9] = 2 + const row = Buffer.alloc(1 + width * 3, 0x90) + row[0] = 0 + return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', header), chunk('IDAT', deflateSync(Buffer.concat(Array.from({ length: height }, () => row)))), chunk('IEND', Buffer.alloc(0))]) +} + +/** A second of silence as MPEG-1 Layer III, 128 kbit/s at 44.1 kHz. */ +function mp3() { + const frame = Buffer.alloc(417) + frame.set([0xff, 0xfb, 0x90, 0x64]) + return Buffer.concat(Array.from({ length: 38 }, () => frame)) +} + +/** A sample file for each name an example gives, by its type: what the user would supply. */ +function sample(name: string) { + const extension = name.split('.').pop() + if (extension === 'png') return png(480, 270) + if (extension === 'mp4') return clip + if (extension === 'mp3') return mp3() + if (extension === 'vtt') return Buffer.from('WEBVTT\n\n00:00.000 --> 00:02.000\nA river.\n') + throw new Error(`No sample for ${name}`) +} beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), 'h5p-author-verify-')) - for (const kind of ['multiple-choice', 'question-set'] as const) { - const source: Quiz = { ...example, kind, questions: kind === 'multiple-choice' ? [example.questions[0]] : example.questions } - const file = join(dir, `${kind}.h5p`) - await buildQuiz(source, file, project) - files.set(kind, file) + // The demo's clip, which the player's own tests play: an H.264 mp4 of ten seconds. + const reader = new ZipReader(new BlobReader(new Blob([await readFile(resolve(project, '../demo/demo/content/video.h5p'))]))) + try { + const entry = (await reader.getEntries()).find((each) => each.filename.endsWith('.mp4'))! + clip = await (entry as import('@zip.js/zip.js').FileEntry).getData(new Uint8ArrayWriter()) + } finally { + await reader.close() } - const file = join(dir, 'scenarios.h5p') - await buildQuiz(scenarios, file, project) - files.set('scenarios', file) - // Interface texts from the libraries' Ukrainian, one of them with an apostrophe the content check escapes. - const translated = join(dir, 'ukrainian.h5p') - await buildQuiz({ ...example, language: 'uk' }, translated, project) - files.set('ukrainian', translated) - // Titles and an author's name with quotes and markup, which the content check escapes. - const punctuation = join(dir, 'punctuation.h5p') - await buildQuiz({ - ...example, - authors: [{ name: "Anne O'Brien ", role: 'Author' }], - questions: example.questions.map(question => ({ ...question, title: `${question.title}'s "draft" & co` })) - }, punctuation, project) - files.set('punctuation', punctuation) }) afterAll(async () => { if (dir) await rm(dir, { recursive: true, force: true }) }) -// Step 4 of the skill: the check, through the verifier's published API. -it.each([ - ['multiple-choice', false], - ['multiple-choice', true], - ['question-set', false], - ['question-set', true], - ['scenarios', false], - ['scenarios', true], - ['ukrainian', false], - ['ukrainian', true], - ['punctuation', false], - ['punctuation', true] -])('plays authored %s (untrusted: %s) without warnings', async (kind, untrusted) => { - const report = await verifyPackage({ - file: files.get(kind)!, - untrusted, - libraries: untrusted ? parts : undefined, - settle: 500 +/** Step 4 of the skill: the check, through the verifier's published API, trusted and untrusted. */ +async function playsBothWays(file: string) { + for (const untrusted of [false, true]) { + const report = await verifyPackage({ file, untrusted, libraries: untrusted ? parts : undefined, settle: 500 }) + expect(report.verdict, JSON.stringify(report)).toBe('pass') + expect(report.warnings, `${file}, untrusted: ${untrusted}`).toEqual([]) + expect(report.errors).toEqual([]) + expect(report.state).toBe('ready') + expect(report.untrusted).toBe(untrusted) + expect(report.revision).toMatch(/^sha256:[0-9a-f]{64}(; libraries sha256:[0-9a-f]{64})?$/) + } +} + +describe.concurrent('every type file', () => { + it.each(files)('%s: its example builds, and plays trusted and untrusted without warnings', async (file) => { + const source = await exampleOf(file) + const folder = join(dir, file.slice(0, -'.md'.length)) + await mkdir(folder, { recursive: true }) + for (const path of paths(source.params)) if (!/^https?:/.test(path)) await writeFile(join(folder, path), sample(path)) + const output = join(folder, 'example.h5p') + const result = await buildPackage(source, output, { base: folder }) + expect(result.notes).toEqual([]) + await playsBothWays(output) + }, 180_000) + + it.each(files)('%s: its fields are the pack\'s, as `h5p-author schema --markdown` writes them', async (file) => { + const text = await readFile(join(types, file), 'utf8') + // Out of date after the pack changed: run `pnpm --filter @missing-elements/h5p-author sync:skill`. + expect(text).toContain(await schemaOf(file.slice(0, -'.md'.length), { markdown: true })) }) - expect(report.verdict, JSON.stringify(report)).toBe('pass') - expect(report.warnings).toEqual([]) - expect(report.errors).toEqual([]) - expect(report.state).toBe('ready') - expect(report.untrusted).toBe(untrusted) - expect(report.revision).toMatch(/^sha256:[0-9a-f]{64}(; libraries sha256:[0-9a-f]{64})?$/) - expect(report.rendered?.text).toBeGreaterThan(100) -}, 60_000) +}) + +describe.concurrent('the quiz format', () => { + const quizzes: [string, unknown][] = [ + ['multiple choice', { ...example, kind: 'multiple-choice', questions: [example.questions[0]] }], + ['question set', example], + ['eight scenarios', scenarios], + // Interface texts from the libraries' Ukrainian, one of them with an apostrophe the content check escapes. + ['Ukrainian', { ...example, language: 'uk' }], + // Titles and an author's name with quotes and markup, which the content check escapes. + ['punctuation', { + ...example, + authors: [{ name: "Anne O'Brien ", role: 'Author' }], + questions: example.questions.map((question: { title: string }) => ({ ...question, title: `${question.title}'s "draft" & co` })) + }] + ] + it.each(quizzes)('%s plays trusted and untrusted without warnings', async (name, source) => { + const output = join(dir, `${name.replaceAll(' ', '-')}.h5p`) + await buildPackage(source, output) + await playsBothWays(output) + }, 180_000) +}) diff --git a/apps/skills/tests/author.test.ts b/apps/skills/tests/author.test.ts deleted file mode 100644 index 6d0bd57a..00000000 --- a/apps/skills/tests/author.test.ts +++ /dev/null @@ -1,374 +0,0 @@ -import { execFile } from 'node:child_process' -import { cp, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { basename, dirname, join, resolve } from 'node:path' -import { promisify } from 'node:util' -import { BlobReader, TextWriter, ZipReader } from '@zip.js/zip.js' -import { pack } from '@missing-elements/h5p-libraries' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { buildQuiz, translateDefaults, translationFiles, validateQuiz } from '../../../skills/h5p-author/scripts/build-quiz.mjs' - -const skill = resolve(import.meta.dirname, '../../../skills/h5p-author') -const project = resolve(import.meta.dirname, '..') -const example = JSON.parse(await readFile(join(skill, 'assets/quiz.json'), 'utf8')) -const scenarios = JSON.parse(await readFile(join(skill, 'assets/phishing-scenarios.json'), 'utf8')) -const exec = promisify(execFile) -const require = createRequire(import.meta.url) -let dir: string - -beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), 'h5p-author-test-')) }) -afterAll(async () => { await rm(dir, { recursive: true, force: true }) }) - -async function archive(path: string | URL) { - const reader = new ZipReader(new BlobReader(new Blob([await readFile(path)])), { checkSignature: true }) - try { - const entries = (await reader.getEntries()).filter(entry => !entry.directory) - const files = new Map() - // Decode every file independently; a copied entry must retain its CRC and compression method. - for (const entry of entries) files.set(entry.filename, await entry.getData(new TextWriter())) - return files - } finally { await reader.close() } -} - -type Field = { name: string, type: string, default?: unknown, fields?: Field[] } -type Translated = { default?: string, fields?: Translated[] } - -/** A library's English and translated default for a field, named in its semantics, read from the installed part. */ -async function defaults(machineName: string, code: string, path: string[]) { - const library = pack.libraries.find(library => library.machineName === machineName && library.majorVersion === 1)! - const files = await archive(new URL(library.url)) - let fields: Field[] = JSON.parse(files.get(`${library.folder}/semantics.json`)!) - let translation: Translated[] = JSON.parse(files.get(`${library.folder}/language/${code}.json`)!).semantics - let field: Field | undefined - let translated: Translated | undefined - for (const name of path) { - const i = fields.findIndex(candidate => candidate.name === name) - field = fields[i] - translated = translation[i] - fields = field.fields ?? [] - translation = translated.fields ?? [] - } - return { english: field!.default, translated: translated!.default } -} - -/** Builds a quiz, and reads its content back from the archive written. */ -async function build(source: unknown, name: string) { - const path = join(dir, name) - const { translations } = await buildQuiz(source, path, project) - return { translations, content: JSON.parse((await archive(path)).get('content/content.json')!) } -} - -async function copyDependencies(projectDir: string) { - for (const name of ['@missing-elements/h5p-libraries', '@zip.js/zip.js']) { - await cp(dirname(require.resolve(name)), join(projectDir, 'node_modules', name), { - recursive: true, filter: path => basename(path) !== 'node_modules' - }) - } -} - -describe('quiz authoring', () => { - it('accepts both kinds, multiple correct answers, and a zero pass threshold', () => { - expect(() => validateQuiz(example)).not.toThrow() - expect(() => validateQuiz({ ...example, kind: 'multiple-choice', passPercentage: 0, questions: [example.questions[0]] })).not.toThrow() - // A quiz without a pass mark, and so without its messages, as before they existed. - expect(() => validateQuiz({ ...example, passPercentage: undefined, passedFeedback: undefined, failedFeedback: undefined })).not.toThrow() - }) - - it.each([ - [null, 'quiz: expected an object'], - [{ ...example, kind: 'slides' }, 'quiz.kind'], - [{ ...example, title: '' }, 'quiz.title'], - [{ ...example, title: 'a'.repeat(256) }, 'quiz.title'], - [{ ...example, language: 'not_a_tag' }, 'quiz.language'], - [{ ...example, license: 'made-up' }, 'quiz.license'], - [{ ...example, authors: [] }, 'quiz.authors'], - [{ ...example, authors: [{ name: 'A', role: 'Editor' }] }, 'quiz.authors[0].role'], - [{ ...example, passPercentage: 101 }, 'quiz.passPercentage'], - [{ ...example, passPercentage: '50' }, 'quiz.passPercentage'], - [{ ...example, failedFeedback: undefined }, 'quiz.failedFeedback: set passedFeedback and failedFeedback together'], - [{ ...example, passedFeedback: undefined }, 'quiz.passedFeedback: set passedFeedback and failedFeedback together'], - [{ ...example, passedFeedback: ' ' }, 'quiz.passedFeedback: expected non-empty text'], - [{ ...example, passPercentage: undefined }, 'quiz.passPercentage: set it with passedFeedback and failedFeedback'], - [{ ...example, questions: [] }, 'quiz.questions'], - [{ ...example, kind: 'multiple-choice' }, 'exactly one question'], - [{ ...example, customJs: 'evil.js' }, 'quiz.customJs: unsupported field'], - [{ ...example, questions: [null] }, 'quiz.questions[0]'], - [{ ...example, questions: [{ ...example.questions[0], prompt: '' }] }, 'quiz.questions[0].prompt'], - [{ ...example, questions: [{ ...example.questions[0], multipleAnswers: 'yes' }] }, 'quiz.questions[0].multipleAnswers'], - [{ ...example, questions: [{ ...example.questions[0], answers: [] }] }, 'at least two answers'], - [{ ...example, questions: [{ ...example.questions[0], answers: [{ text: 'a', correct: 'true' }, { text: 'b', correct: false }] }] }, '.correct'], - [{ ...example, questions: [{ ...example.questions[0], answers: [{ text: 'a', correct: true }, { text: 'b', correct: true }] }] }, 'exactly one answer'], - [{ ...example, questions: [{ ...example.questions[0], multipleAnswers: true, answers: [{ text: 'a', correct: false }, { text: 'b', correct: false }] }] }, 'at least one answer'], - [{ ...example, questions: [{ ...example.questions[0], answers: [{ text: 'a', correct: true, typo: 'lost' }, { text: 'b', correct: false }] }] }, '.typo: unsupported field'] - ])('rejects malformed input with its field path (%#)', (input, message) => { - expect(() => validateQuiz(input)).toThrow(message) - }) - - it('builds a self-contained Question Set using pack versions, semantics defaults, and the full dependency closure', async () => { - const path = join(dir, 'set.h5p') - const result = await buildQuiz(example, path, project) - const files = await archive(path) - const manifest = JSON.parse(files.get('h5p.json')!) - const content = JSON.parse(files.get('content/content.json')!) - expect([...files.keys()][0]).toBe('h5p.json') - expect([...files.keys()].at(-1)).toBe('content/content.json') - expect(manifest.mainLibrary).toBe('H5P.QuestionSet') - expect(manifest.defaultLanguage).toBe(example.language) - expect(manifest.authors).toEqual(example.authors) - expect(content.passPercentage).toBe(100) - expect(content.texts.finishButton).toBeTruthy() - expect(content.endGame.showResultPage).toBe(true) - // The pass mark as the set's own score ranges, escaped as H5P stores a text field; the rest - // of the result page keeps its defaults, and no question inside gets the quiz's message. - expect(content.endGame.overallFeedback).toEqual([ - { from: 0, to: 99, feedback: 'Not passed yet. Read each answer's feedback, then select Retry.' }, - { from: 100, to: 100, feedback: 'Passed. You chose the safe response every time.' } - ]) - expect(content.endGame.retryButtonText).toBe('Retry') - // English is the libraries' own; no file stands in for it. - expect(result.translations.map(({ translation }) => translation)).toEqual([null, null]) - for (const question of content.questions) expect(question.params.overallFeedback).toBeUndefined() - expect(content.questions).toHaveLength(2) - expect(content.questions[0].params.question).toContain(example.questions[0].prompt) - expect(content.questions[0].params.UI.checkAnswerButton).toBe('Check') - expect(content.questions[0].params.behaviour.type).toBe('single') - expect(content.questions[1].params.behaviour.type).toBe('multi') - const ids = content.questions.map((question: { subContentId: string }) => question.subContentId) - expect(new Set(ids).size).toBe(2) - expect(ids.every((id: string) => /^[0-9a-f-]{36}$/.test(id))).toBe(true) - expect(result.libraries.length).toBeGreaterThan(2) - expect(result.libraries.length).toBeLessThan(30) - for (const dependency of manifest.preloadedDependencies) { - expect(files.has(`${dependency.machineName}-${dependency.majorVersion}.${dependency.minorVersion}/library.json`)).toBe(true) - } - for (const [name, json] of files) { - if (!name.endsWith('/library.json')) continue - const library = JSON.parse(json) - expect(library.machineName).not.toMatch(/H5PEditor/) - for (const dependency of [...(library.preloadedDependencies ?? []), ...(library.dynamicDependencies ?? [])]) { - const available = manifest.preloadedDependencies.find((candidate: { machineName: string, majorVersion: string, minorVersion: string }) => - candidate.machineName === dependency.machineName && Number(candidate.majorVersion) === Number(dependency.majorVersion) && Number(candidate.minorVersion) >= Number(dependency.minorVersion)) - expect(available, `${name}: ${dependency.machineName}`).toBeDefined() - } - } - }) - - it('builds standalone Multiple Choice, escapes markup, and preserves false and zero values', async () => { - const path = join(dir, 'single.h5p') - const source = { - ...example, kind: 'multiple-choice', passPercentage: 0, passedFeedback: 'Done & dusted', - questions: [{ ...example.questions[0], prompt: ' & "quoted"\nNext line' }] - } - const { manifest, content, libraries } = await buildQuiz(source, path, project) - expect(manifest.mainLibrary).toBe('H5P.MultiChoice') - expect(content.question).toBe('

<script>run()</script> & "quoted"
Next line

') - expect(content.behaviour).toMatchObject({ type: 'single', passPercentage: 0 }) - // With nothing to fail, one range: every score passes. - expect(content.overallFeedback).toEqual([{ from: 0, to: 100, feedback: 'Done <b>& dusted</b>' }]) - expect(content.answers).toEqual(expect.arrayContaining([expect.objectContaining({ correct: false })])) - expect(libraries.some(name => name.startsWith('H5P.QuestionSet-'))).toBe(false) - await archive(path) - }) - - it('stores question titles and author names as H5P stores text, and h5p.json as its exports write it', async () => { - const source = { - ...example, - authors: [{ name: "Anne O'Brien ", role: 'Author' }], - questions: [{ ...example.questions[0], title: 'Kyivan Rus\' & "Cossacks" ' }, { ...example.questions[1], title: undefined }] - } - const path = join(dir, 'punctuation.h5p') - await buildQuiz(source, path, project) - const files = await archive(path) - const content = JSON.parse(files.get('content/content.json')!) - expect(content.questions.map((question: { metadata: { title: string } }) => question.metadata.title)).toEqual(['Kyivan Rus' & "Cossacks" <b>', 'Question 2']) - for (const question of content.questions) expect(question.metadata.authors).toEqual([{ name: 'Anne O'Brien <ed>', role: 'Author' }]) - expect(JSON.parse(files.get('h5p.json')!).authors).toEqual(source.authors) - }) - - it('builds the eight-scenario example without losing questions, feedback, or its pass threshold', async () => { - const path = join(dir, 'scenarios.h5p') - await buildQuiz(scenarios, path, project) - const files = await archive(path) - const content = JSON.parse(files.get('content/content.json')!) - expect(content.passPercentage).toBe(80) - expect(content.endGame.overallFeedback.map(({ from, to }: { from: number, to: number }) => [from, to])).toEqual([[0, 79], [80, 100]]) - expect(content.questions).toHaveLength(8) - expect(content.questions.filter((question: { params: { behaviour: { type: string } } }) => question.params.behaviour.type === 'multi')).toHaveLength(4) - expect(content.questions[0].params.question).toContain('"Benefits & Payroll:') - expect(content.questions[0].params.question).toContain('
') - for (let i = 0; i < scenarios.questions.length; i++) { - const written = scenarios.questions[i] - const generated = content.questions[i] - expect(generated.metadata.title).toBe(written.title) - expect(generated.params.answers).toHaveLength(4) - for (let j = 0; j < written.answers.length; j++) { - expect(written.answers[j].feedback).toBeTruthy() - expect(generated.params.answers[j].correct).toBe(written.answers[j].correct) - expect(generated.params.answers[j].tipsAndFeedback.chosenFeedback).toBeTruthy() - } - } - }) - - // Names as the pack's quiz libraries have them, `sme` and Question Set's Traditional `zh` among them. - const files = ['de', 'es', 'es-mx', 'he', 'nb', 'nn', 'pt', 'pt-br', 'sme', 'sr', 'zh', 'zh-cn', 'zh-hans', 'zh-hant', 'zh-tw'] - it.each([ - ['de', ['de']], - ['de-AT', ['de']], - ['es-MX', ['es-mx', 'es']], - ['pt-BR', ['pt-br', 'pt']], - ['iw', ['he']], - ['no', ['nb']], - ['se', ['sme']], - ['sr-Cyrl-BA', ['sr']], - ['sr-Latn', []], - ['sh', []], - ['zh', ['zh-hans', 'zh-cn']], - ['zh-TW', ['zh-hant', 'zh-tw']], - ['zh-Hant', ['zh-hant', 'zh-tw']], - ['en', []] - ])('looks the translation for %s up by H5P\'s file names, never in another script', (tag, names) => { - expect(translationFiles(files, tag)).toEqual(names) - }) - - it('takes a translation\'s text defaults only, and keeps the English where it has none, the same, or loses a placeholder', () => { - const fields = [ - { name: 'check', type: 'text', default: 'Check' }, - { name: 'mode', type: 'select', default: 'auto' }, - { name: 'score', type: 'text', default: 'You got :num of :total' }, - { - name: 'texts', type: 'group', fields: [ - { name: 'question', type: 'text', default: 'Question' }, - { name: 'next', type: 'text', default: 'Next' }, - { name: 'progress', type: 'text', default: '@current of @total' }, - { name: 'results', type: 'text', default: 'Results' } - ] - }, - { name: 'items', type: 'list', field: { name: 'item', type: 'text', default: 'Item' } } - ] - const { strings, translated, english } = translateDefaults(fields, [ - { default: 'Prüfen' }, - { default: 'manuell' }, - { default: 'Du hast :num von :max' }, - { fields: [{ default: 'Question' }, { default: ' ' }, { default: '@current von @total' }] }, - { field: { default: 'Eintrag' } } - ]) - expect(strings).toBe(7) - expect(translated.map(({ field, text }) => [field.name, text])).toEqual([['check', 'Prüfen'], ['progress', '@current von @total'], ['item', 'Eintrag']]) - expect(english).toEqual([ - { field: 'score', text: 'You got :num of :total', dropped: [':total'] }, - { field: 'texts.question', text: 'Question' }, - { field: 'texts.next', text: 'Next' }, - { field: 'texts.results', text: 'Results' } - ]) - expect(translateDefaults(fields, { semantics: [] }).translated).toEqual([]) - }) - - it('takes the interface texts from the libraries\' own translation for the quiz\'s language', async () => { - const untitled = { ...example, language: 'de-AT', questions: example.questions.map(({ title: _, ...question }: { title?: string }) => question) } - const { content, translations } = await build(untitled, 'german.h5p') - expect(translations.map(({ library, translation }) => [library.split(' ')[0], translation])).toEqual([['H5P.QuestionSet', 'de'], ['H5P.MultiChoice', 'de']]) - const question = content.questions[0].params - for (const [machineName, path, value] of [ - ['H5P.QuestionSet', ['introPage', 'startButtonText'], content.introPage.startButtonText], - ['H5P.QuestionSet', ['texts', 'finishButton'], content.texts.finishButton], - ['H5P.QuestionSet', ['endGame', 'retryButtonText'], content.endGame.retryButtonText], - ['H5P.MultiChoice', ['UI', 'checkAnswerButton'], question.UI.checkAnswerButton] - ] as const) { - const { english, translated } = await defaults(machineName, 'de', [...path]) - expect(translated).not.toBe(english) - expect(value, path.join('.')).toBe(translated) - } - // What the report names as English is what the content holds. - for (const [report, params] of [[translations[0], content], [translations[1], question]] as const) { - for (const { field, text } of report.english) expect(field.split('.').reduce((object, key) => object[key], params), field).toBe(text) - } - // An untitled question is named as the set labels it, in the result screen's list too. - const { translated: label } = await defaults('H5P.QuestionSet', 'de', ['texts', 'questionLabel']) - expect(content.questions.map((question: { metadata: { title: string } }) => question.metadata.title)).toEqual([`${label} 1`, `${label} 2`]) - }) - - it('stores a translated text as H5P stores plain text, escaped', async () => { - const { content } = await build({ ...example, kind: 'multiple-choice', language: 'uk', questions: [example.questions[0]] }, 'ukrainian.h5p') - const { translated } = await defaults('H5P.MultiChoice', 'uk', ['UI', 'feedbackAvailable']) - expect(translated).toContain("'") - expect(content.UI.feedbackAvailable).toBe(translated!.replaceAll("'", ''')) - }) - - it('never gives Simplified Chinese a Traditional file, and says when a library has no translation', async () => { - const chinese = await build({ ...example, language: 'zh-CN' }, 'chinese.h5p') - // Question Set's `zh.json` is Traditional, and it has no Simplified file. - expect(chinese.translations.map(({ translation }) => translation)).toEqual([null, 'zh-hans']) - expect(chinese.content.texts.finishButton).toBe('Finish') - const esperanto = await build({ ...example, language: 'eo' }, 'esperanto.h5p') - expect(esperanto.translations).toEqual([ - expect.objectContaining({ translation: null, strings: esperanto.translations[0].english.length }), - expect.objectContaining({ translation: null, strings: esperanto.translations[1].english.length }) - ]) - expect(esperanto.content.questions[0].params.UI.checkAnswerButton).toBe('Check') - }) - - it('does not overwrite an output, publish partial failures, or leave staging directories', async () => { - const path = join(dir, 'existing.h5p') - await writeFile(path, 'keep me') - await expect(buildQuiz(example, path, project)).rejects.toMatchObject({ code: 'EEXIST' }) - expect(await readFile(path, 'utf8')).toBe('keep me') - expect((await readdir(dir)).filter(name => name.startsWith('.h5p-author-'))).toEqual([]) - await expect(buildQuiz({ ...example, questions: [] }, join(dir, 'invalid.h5p'), project)).rejects.toThrow('quiz.questions') - expect(await readdir(dir)).not.toContain('invalid.h5p') - }) - - it('refuses a damaged library part before publishing an archive', async () => { - const damaged = join(dir, 'damaged-pack') - await copyDependencies(damaged) - const library = pack.libraries.find(library => library.machineName === 'H5P.MultiChoice' && library.majorVersion === 1)! - const part = join(damaged, `node_modules/@missing-elements/h5p-libraries/parts/${library.folder}.h5p`) - const bytes = await readFile(part) - const reader = new ZipReader(new BlobReader(new Blob([bytes]))) - try { - const entry = (await reader.getEntries()).find(entry => !entry.directory && entry.filename.endsWith('.js'))! - const offset = entry.offset + 30 + bytes.readUInt16LE(entry.offset + 26) + bytes.readUInt16LE(entry.offset + 28) - // Damage script data without changing library.json, semantics, or the central directory. - bytes[offset + Math.floor(entry.compressedSize / 2)] ^= 1 - } finally { await reader.close() } - await writeFile(part, bytes) - const output = join(damaged, 'quiz.h5p') - await expect(buildQuiz(example, output, damaged)).rejects.toThrow(`Library part failed SHA-256: ${library.folder}`) - expect(await readdir(damaged)).not.toContain('quiz.h5p') - expect((await readdir(damaged)).filter(name => name.startsWith('.h5p-author-'))).toEqual([]) - }) - - it('stops with the install command when the project has an older zip.js', async () => { - const old = join(dir, 'old-zip') - const installed = join(old, 'node_modules/@zip.js/zip.js') - await mkdir(installed, { recursive: true }) - // 2.15 has appendZip without its filter option; only the version is read before the refusal. - await writeFile(join(installed, 'package.json'), JSON.stringify({ name: '@zip.js/zip.js', version: '2.15.0', exports: { './package.json': './package.json' } })) - const error = await buildQuiz(example, join(old, 'quiz.h5p'), old).catch(error => error) - expect(error.message).toContain('Run: npm install --save-dev @missing-elements/h5p-libraries@^1 @zip.js/zip.js@^2.24') - expect(error.cause.message).toBe('@zip.js/zip.js 2.15.0 is older than 2.24') - expect(await readdir(old)).toEqual(['node_modules']) - }) - - it('runs a copied skill outside the checkout and resolves dependencies from the calling project', async () => { - const portable = join(dir, 'portable') - await cp(skill, join(portable, 'installed-skill'), { recursive: true }) - expect(await readFile(join(portable, 'installed-skill/LICENSE'), 'utf8')).toBe(await readFile(resolve(project, '../../LICENSE'), 'utf8')) - await writeFile(join(portable, 'package.json'), '{"private":true}') - await copyDependencies(portable) - const script = join(portable, 'installed-skill/scripts/build-quiz.mjs') - const { stdout } = await exec(process.execPath, [script, join(portable, 'installed-skill/assets/quiz.json'), 'portable.h5p'], { cwd: portable }) - expect(stdout).toContain('Not verified') - const files = await archive(join(portable, 'portable.h5p')) - expect(JSON.parse(files.get('h5p.json')!).mainLibrary).toBe('H5P.QuestionSet') - // In another language, the command says where the interface texts came from. - await writeFile(join(portable, 'german.json'), JSON.stringify({ ...example, language: 'de' })) - const german = await exec(process.execPath, [script, 'german.json', 'german.h5p'], { cwd: portable }) - expect(german.stdout).toMatch(/H5P\.MultiChoice 1\.\d+: interface texts from its translation language\/de\.json\./) - expect(german.stdout + german.stderr).toMatch(/H5P\.QuestionSet 1\.\d+: interface texts from its translation language\/de\.json/) - const failed = exec(process.execPath, [script, join(portable, 'installed-skill/assets/quiz.json'), 'missing.h5p'], { - cwd: dir, env: { ...process.env, NODE_PATH: '' } - }) - await expect(failed).rejects.toMatchObject({ code: 1, stderr: expect.stringContaining('npm install --save-dev') }) - }) -}) diff --git a/docs/development.md b/docs/development.md index af4f38f2..acbbf094 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,9 +1,10 @@ # Development A pnpm workspace: `packages/player`, `packages/runtime`, `packages/libraries`, -`packages/normalize`, `packages/verify`, `packages/cmi5`, `packages/embed`, the demo site in -`apps/demo`, and in `apps/skills` the tests of the agent skills' scripts, run from a project the -way a skill's user runs them. +`packages/normalize`, `packages/verify`, `packages/author`, `packages/cmi5`, `packages/embed`, +`packages/vscode`, the demo site in `apps/demo`, and in `apps/skills` the tests of the agent +skills, run from a project the way a skill's user runs them: every h5p-author type file's example +built and played. ```bash pnpm install diff --git a/docs/verify.md b/docs/verify.md index 68199e92..15eeebb7 100644 --- a/docs/verify.md +++ b/docs/verify.md @@ -36,10 +36,11 @@ library pack, so an export without its libraries plays offline. For authoring, the [`h5p-author` skill](https://github.com/missing-elements/h5p-offline-player/tree/main/skills/h5p-author) -adds a prompt-to-quiz workflow and a portable packaging helper for text-only Multiple Choice -and Question Set. It takes a small quiz JSON file, fills the installed libraries' defaults, -includes their runtime dependencies, then requires this playback check and screenshot review, -and opens the quiz in the preview for a person to answer every question. The source JSON remains -editable; the `.h5p` and full revision from the verification report identify what was checked. -Answer accuracy and a complete question-by-question interaction check remain separate from the +adds a prompt-to-package workflow for 28 content types, on +[`@missing-elements/h5p-author`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/author#readme). +It takes a short JSON source of only what differs from a type's defaults, fills the rest from the +libraries' semantics and translations, includes their runtime dependencies, then requires this +playback check and screenshot review, and opens the package in the preview for a person to work +through. The source JSON remains editable; the `.h5p` and full revision from the verification +report identify what was checked. Whether the content is right remains separate from the verifier's startup verdict. diff --git a/package.json b/package.json index fb6fa9ea..094b1987 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "typecheck": "pnpm -r typecheck", "normalize": "node packages/normalize/bin/h5p-normalize.mjs", "verify": "node packages/verify/bin/h5p-verify.mjs", + "author": "node packages/author/bin/h5p-author.mjs", "demo:content": "pnpm --filter @missing-elements/h5p-demo demo:content", "demo:og": "pnpm --filter @missing-elements/h5p-demo demo:og", "demo:icons": "pnpm --filter @missing-elements/h5p-demo demo:icons", diff --git a/packages/author/README.md b/packages/author/README.md new file mode 100644 index 00000000..7312cd2b --- /dev/null +++ b/packages/author/README.md @@ -0,0 +1,129 @@ +# @missing-elements/h5p-author + +Builds a playable `.h5p` of any content type in the H5P hub from a short JSON source: the content +type, and only the fields that differ from its defaults. The rest comes from the libraries' own +`semantics.json` and their translations for the content's language; the libraries come from +[@missing-elements/h5p-libraries](https://www.npmjs.com/package/@missing-elements/h5p-libraries), +the pack this release pins, each checked against the pack's SHA-256 index. No H5P server, no +editor, no network but for media named by web address. Needs Node 22 or later; write `@latest`, +since without it npm on an older Node quietly installs an older release. + +```bash +npx @missing-elements/h5p-author@latest build rivers.json rivers.h5p +``` + +```json +{ + "type": "H5P.Blanks", + "title": "Rivers of Europe", + "language": "de", + "license": "CC BY", + "authors": [{ "name": "Ann Author", "role": "Author" }], + "params": { + "questions": ["Die *Donau* fließt ins Schwarze Meer.", "Paris liegt an der *Seine*."] + } +} +``` + +``` +Built /work/rivers.h5p: H5P.Blanks, 9 libraries from the library pack 1.0.0. +H5P.Blanks 1.14: interface texts from its translation language/de.json. +Not verified: run npx @missing-elements/h5p-verify@latest on it and look at its screenshot before handing it over. +``` + +It is written for an AI agent and its tokens: the agent writes what only an author can know, and +code writes everything that can be derived. The +[h5p-author skill](https://github.com/missing-elements/h5p-offline-player/tree/main/skills/h5p-author) +is the workflow around it: choosing the content type with the user, a file per type with notes, +an example and the fields, then the check and the preview. + +## The source + +| Field | Meaning | +|---|---| +| `type` | The content type's machine name, such as `H5P.Blanks`; the pack's newest version is used | +| `title` | The title, at most 255 characters | +| `language` | A BCP 47 tag, `en`, `de-AT`; it picks the libraries' translation of their interface texts | +| `license` | An H5P licence code: `U` (undisclosed), `CC BY`, `CC BY-SA`, `CC BY-ND`, `CC BY-NC`, `CC BY-NC-SA`, `CC BY-NC-ND`, `CC0 1.0`, `CC PDM`, `GNU GPL`, `PD`, `ODC PDDL`, `C`; `licenseVersion` for a CC BY one | +| `authors` | `[{ "name": "…", "role": "Author" }]`, the role one of Author, Editor, Licensee, Originator | +| `params` | The content type's fields that differ from their defaults | + +What `params` takes is what H5P's editor would let an author save in the same form: + +- **Text**: plain text in a plain field, stored escaped as the platforms store it; in a field with + tags, markup with those tags only, or plain text, which is wrapped in paragraphs as the editor + wraps typing. A tag the field does not take, an event handler or a script address is refused. +- **Choices, numbers, lists**: a select's options, a number's range, a list's size, all checked. + A field the semantics do not name is refused, so a misspelt one is never dropped in silence. +- **Sub-content**: `{ "library": "H5P.MultiChoice", "params": { … }, "metadata": { "title": "…" } }`, + filled in the same way, at the pack's version. +- **Files**: `{ "path": "photo.jpg" }`, a file beside the source or an `http(s)` address, with an + optional `copyright`. Each is copied into the package with its type and, for a picture, its size; + the package is then laid out to stream, media stored and an mp4's index first. A YouTube, Vimeo, + Panopto or Echo360 address stays where it is, if it is one H5P.Video plays: a Short's is taken + as its video's, and another address on those sites is refused. A download is given up once + nothing has arrived for a minute, however long it runs. +- **Interface texts** (Check, Retry…): leave them out; they come from the libraries' translations, + and the command lists what stayed English. A source may still set one by name. + +Some content types have a widget of their own in the editor, which sets fields the form hides. +The build does what those widgets do: it lays out a Course Presentation slide's elements, places +Interactive Video interactions, joins Game Map stages and sets their ids, numbers Branching +Scenario end screens, and names untitled Question Set questions. It refuses what they would not +let pass: a scenario path with no end, a map with no start, a hotspot question with no right area. + +A source with problems writes nothing and lists every problem by its path at once: + +``` +h5p-author: The source has 2 problems: + params.correct: "yes" is not an option; the options are "true", "false" + params.behaviour.sideways: is not a field here; the fields are enableRetry, enableSolutionsButton, … +``` + +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. + +## A content type's fields + +```bash +npx @missing-elements/h5p-author@latest schema H5P.TrueFalse +``` + +``` +H5P.TrueFalse 1.8: True/False Question +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. +- `question` html: strong em sub sup h2 h3 pre code, required — Question +- `correct` one of "true" | "false" = "true" — Correct answer +… +``` + +`--all` adds the interface texts; `--markdown` prints the section the skill's type files carry. +An unknown name lists the pack's content types. + +## Options + +- `--libraries `: another copy of the pack's `parts/` folder, in place of the pinned one. + +## API + +```js +import { buildPackage, schemaOf, SourceError } from '@missing-elements/h5p-author' + +const { output, manifest, content, libraries, translations, notes, media } = + await buildPackage(source, 'rivers.h5p', { base: process.cwd() }) +``` + +`buildPackage(source, output, { libraries, base, fetch })` refuses an existing output, and throws a +`SourceError` whose `problems` are `{ path, message }`. `schemaOf(machineName, { markdown, all, +libraries })` returns the field list. `ContentGenerator` is the engine underneath, also run by the +repository's sweep of every content type. + +## What it does not do + +It checks structure, not pedagogy: whether the answers are right, the questions fair, or the +pictures placed well is for a person to judge, in +[h5p-verify](https://www.npmjs.com/package/@missing-elements/h5p-verify)'s `--preview`. It does not +edit an existing package. The licence of each library is in the pack's `libraries.txt`. + +MIT. diff --git a/packages/author/bin/h5p-author.mjs b/packages/author/bin/h5p-author.mjs new file mode 100755 index 00000000..3083129f --- /dev/null +++ b/packages/author/bin/h5p-author.mjs @@ -0,0 +1,89 @@ +#!/usr/bin/env node +import { readFile } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { buildPackage, schemaOf, SourceError } from '../lib/author.mjs' +import { packVersion } from '../lib/pack.mjs' + +const USAGE = `Usage: + h5p-author build [--libraries ] + h5p-author schema [--markdown] [--all] [--libraries ] + +build Makes a playable .h5p from a source: { "type", "title", "language", "license", + "authors", "params" }, or a quiz in the h5p-author skill's quiz format. Writes only + when the whole source is right, and never over an existing file. +schema Prints a content type's fields as a source writes them: --markdown as a skill's + type file carries them, --all with the interface texts. + +The libraries come from the pack this release pins (@missing-elements/h5p-libraries); +--libraries names another copy's parts/ folder. Check every package with +npx @missing-elements/h5p-verify@latest before handing it over.` + +/** @param {string[]} argv */ +function parse(argv) { + /** @type {string[]} */ + const positional = [] + /** @type {Record} */ + const flags = {} + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] + if (arg === '--libraries') { + const value = argv[++i] + if (!value || value.startsWith('--')) throw new Error('--libraries needs a folder') + flags.libraries = value + } else if (arg.startsWith('--')) flags[arg.slice(2)] = true + else positional.push(arg) + } + return { positional, flags } +} + +try { + const { positional, flags } = parse(process.argv.slice(2)) + const [command, ...rest] = positional + if (flags.version) { + const own = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version + console.log(`@missing-elements/h5p-author ${own}, library pack ${await packVersion()}`) + } else if (flags.help || !command) { + console.log(USAGE) + if (!command && !flags.help) process.exitCode = 1 + } else if (command === 'schema') { + if (rest.length !== 1) throw new Error('schema takes one content type, such as H5P.Blanks') + for (const flag of Object.keys(flags)) if (!['markdown', 'all', 'libraries'].includes(flag)) throw new Error(`schema does not take --${flag}`) + console.log(await schemaOf(rest[0], { markdown: Boolean(flags.markdown), all: Boolean(flags.all), libraries: /** @type {string | undefined} */ (flags.libraries) })) + } else if (command === 'build') { + if (rest.length !== 2) throw new Error('build takes a source and an output: h5p-author build quiz.json quiz.h5p') + for (const flag of Object.keys(flags)) if (flag !== 'libraries') throw new Error(`build does not take --${flag}`) + const sourcePath = resolve(rest[0]) + let source + try { + source = JSON.parse(await readFile(sourcePath, 'utf8')) + } catch (error) { + throw new Error(`${rest[0]} is not a readable JSON file: ${error instanceof Error ? error.message : error}`) + } + const result = await buildPackage(source, rest[1], { base: dirname(sourcePath), libraries: /** @type {string | undefined} */ (flags.libraries) }) + const from = flags.libraries ? `the pack in ${flags.libraries}` : `the library pack ${await packVersion()}` + console.log(`Built ${result.output}: ${result.manifest.mainLibrary}, ${result.libraries.length} libraries from ${from}${result.media.length ? `, ${result.media.length} media file${result.media.length === 1 ? '' : 's'}` : ''}.`) + const language = String(result.manifest.language) + if (!/^en(?:-|$)/i.test(language)) { + for (const { library, translation, strings, english } of result.translations) { + if (!translation) console.warn(`${library} has no translation for ${language}: its ${strings} interface texts are English.`) + else if (!english.length) console.log(`${library}: interface texts from its translation language/${translation}.json.`) + else { + const list = english.map(({ field, text, dropped }) => ` ${field}: ${JSON.stringify(text)}${dropped ? ` (its translation drops ${dropped.join(' and ')})` : ''}`) + console.warn(`${library}: interface texts from its translation language/${translation}.json; ${english.length} of ${strings} as in English, untranslated or the same word:\n${list.join('\n')}`) + } + } + } + for (const { path, message } of result.notes) console.warn(`Note: ${path} ${message}`) + console.log('Not verified: run npx @missing-elements/h5p-verify@latest on it and look at its screenshot before handing it over.') + } else { + throw new Error(`unknown command "${command}"\n\n${USAGE}`) + } +} catch (error) { + if (error instanceof SourceError) { + console.error(`h5p-author: ${error.message}`) + } else { + console.error(`h5p-author: ${error instanceof Error ? error.message : error}`) + if (error instanceof Error && error.cause instanceof Error) console.error(error.cause.message) + } + process.exitCode = 1 +} diff --git a/packages/author/lib/author.mjs b/packages/author/lib/author.mjs new file mode 100644 index 00000000..c15aabf6 --- /dev/null +++ b/packages/author/lib/author.mjs @@ -0,0 +1,56 @@ +/** + * @missing-elements/h5p-author: a playable .h5p of any content type in the H5P hub's library pack, + * from a short JSON source. The source writes only what the defaults cannot know; everything else + * comes from the libraries' own semantics and translations, and the libraries from the pack this + * package pins, checked against its index. + */ + +import { openPack } from './pack.mjs' +import { schemaLines, schemaMarkdown } from './schema.mjs' +import { LAYOUTS } from './types.mjs' + +export { buildPackage, SourceError } from './build.mjs' +export { ContentGenerator, librariesIn, libraryString } from './generator.mjs' +export { GENERATED_END, GENERATED_START } from './schema.mjs' + +/** + * @typedef {import('./build.mjs').Source} Source + * @typedef {import('./build.mjs').BuildResult} BuildResult + * @typedef {import('./build.mjs').BuildOptions} BuildOptions + * @typedef {import('./generator.mjs').GeneratorOptions} GeneratorOptions + */ + +/** + * A content type's fields as a source writes them, from the pack: one line each. + * @param {string} machineName such as `H5P.Blanks` + * @param {{ libraries?: string, markdown?: boolean, all?: boolean }} [options] + * `libraries`, a parts folder in place of the pinned pack; `markdown`, the section a type file + * carries, between its markers; `all`, the interface texts too + * @returns {Promise} + */ +export async function schemaOf(machineName, options = {}) { + const pack = await openPack(options.libraries) + try { + const entry = pack.newest(machineName) + if (!entry) { + const runnable = [] + for (const each of pack.libraries) { + const part = await pack.open(each) + if (part.library.runnable) runnable.push(`${each.machineName} (${part.library.title})`) + } + throw new Error(`The library pack has no ${machineName}. Its content types: ${[...new Set(runnable)].sort().join(', ')}`) + } + const part = await pack.open(entry) + if (!part.semantics) throw new Error(`${machineName} has no semantics: it is not a content type an author fills in`) + /** @type {(name: string) => boolean} */ + const has = (name) => Boolean(pack.newest(name)) + const sets = LAYOUTS[machineName]?.sets ?? [] + if (options.markdown) return schemaMarkdown(part.library, part.semantics, { has, sets }) + const { lines, interfaceTexts } = schemaLines(part.semantics, { all: options.all, has, sets }) + const header = `${part.library.machineName} ${part.library.majorVersion}.${part.library.minorVersion}: ${part.library.title}` + const footer = !options.all && interfaceTexts ? [`(${interfaceTexts} interface texts left out; --all lists them)`] : [] + return [header, ...lines, ...footer].join('\n') + } finally { + await pack.close() + } +} diff --git a/packages/author/lib/build.mjs b/packages/author/lib/build.mjs new file mode 100644 index 00000000..d5a09a6a --- /dev/null +++ b/packages/author/lib/build.mjs @@ -0,0 +1,398 @@ +import { constants, createReadStream } from 'node:fs' +import { copyFile, lstat, mkdtemp, open, rm, stat } from 'node:fs/promises' +import { dirname, join, resolve } from 'node:path' +import { Readable, Writable } from 'node:stream' +import { TextReader, ZipWriter } from '@zip.js/zip.js' +import { normalizeArchive } from '@missing-elements/h5p-normalize' +import { ContentGenerator, librariesIn, libraryString } from './generator.mjs' +import { MediaStore } from './media.mjs' +import { openPack } from './pack.mjs' +import { quizProblems, quizSource } from './quiz.mjs' +import { escapeText } from './text.mjs' +import { localize, translationFiles } from './translate.mjs' +import { LAYOUTS, patchSemantics, placesOf } from './types.mjs' + +/** + * A source made a package: validated, filled in from the pack's semantics and translations, + * laid out, its media copied and described, and written with the libraries it needs, each part + * checked against the pack's index. Nothing is written unless all of it is right: every problem + * the source has is listed at once, each by its path, so a fix takes one round. + */ + +/** The licences H5P's metadata takes. */ +const LICENSES = ['U', 'CC BY', 'CC BY-SA', 'CC BY-ND', 'CC BY-NC', 'CC BY-NC-SA', 'CC BY-NC-ND', 'CC0 1.0', 'CC PDM', 'GNU GPL', 'PD', 'ODC PDDL', 'C'] +const CC_VERSIONS = ['4.0', '3.0', '2.5', '2.0', '1.0'] +const ROLES = ['Author', 'Editor', 'Licensee', 'Originator'] + +/** + * @typedef {{ name: string, role: string }} Author + * @typedef {{ + * type: string, title: string, language: string, license: string, licenseVersion?: string, + * authors: Author[], source?: string, yearFrom?: number, yearTo?: number, params: Record + * }} Source a package's source: the content type, its metadata, and the parameters that differ from the defaults + * @typedef {{ path: string, message: string }} Problem + * @typedef {import('./translate.mjs').TranslationReport} TranslationReport + * @typedef {{ + * output: string, manifest: Record, content: Record, + * libraries: string[], translations: TranslationReport[], notes: Problem[], media: string[] + * }} BuildResult what was written, and what is worth telling about it + * @typedef {{ libraries?: string, base?: string, fetch?: typeof fetch }} BuildOptions + * `libraries`, a library pack's parts folder in place of the pinned pack; `base`, the folder a + * source's file paths are read from; `fetch`, for media named by web address + */ + +/** A source's problems, all of them, each named by its path. */ +export class SourceError extends Error { + /** @param {Problem[]} problems */ + constructor(problems) { + super(`The source has ${problems.length} problem${problems.length === 1 ? '' : 's'}:\n${problems.map(({ path, message }) => ` ${path}: ${message}`).join('\n')}`) + this.name = 'SourceError' + this.problems = problems + } +} + +/** @param {unknown} value @returns {value is Record} */ +const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) + +/** + * The general source checked for its own fields; a quiz in the published format mapped onto it. + * @param {unknown} input + * @returns {Source} + * @internal + */ +export function readSource(input) { + if (isObject(input) && 'kind' in input) { + const problems = quizProblems(input) + if (problems.length) throw new SourceError(problems) + return /** @type {Source} */ (quizSource(/** @type {import('./quiz.mjs').Quiz} */ (input))) + } + /** @type {Problem[]} */ + const problems = [] + const report = (/** @type {string} */ path, /** @type {string} */ message) => problems.push({ path, message }) + if (!isObject(input)) throw new SourceError([{ path: 'source', message: 'expected an object: { "type", "title", "language", "license", "authors", "params" }' }]) + const known = ['type', 'title', 'language', 'license', 'licenseVersion', 'authors', 'source', 'yearFrom', 'yearTo', 'params'] + for (const key of Object.keys(input)) if (!known.includes(key)) report(key, `is not a field of a source; the fields are ${known.join(', ')}`) + if (typeof input.type !== 'string' || !/^\S+$/.test(input.type.trim())) report('type', 'expected a content type\'s machine name, such as "H5P.Blanks"') + if (typeof input.title !== 'string' || !input.title.trim()) report('title', 'expected the activity\'s title') + else if (input.title.length > 255) report('title', 'takes at most 255 characters') + if (typeof input.language !== 'string') report('language', 'expected a BCP 47 language tag, such as "en" or "de-AT"') + else { + try { + Intl.getCanonicalLocales(input.language) + } catch { + report('language', 'expected a BCP 47 language tag, such as "en" or "de-AT"') + } + } + if (!LICENSES.includes(/** @type {string} */ (input.license))) report('license', `use one of ${LICENSES.map((each) => JSON.stringify(each)).join(', ')}; "U" when it is not known`) + if (input.licenseVersion !== undefined) { + if (!String(input.license).startsWith('CC ') || input.license === 'CC0 1.0' || input.license === 'CC PDM') report('licenseVersion', 'is for a Creative Commons BY licence only') + else if (!CC_VERSIONS.includes(input.licenseVersion)) report('licenseVersion', `use one of ${CC_VERSIONS.join(', ')}`) + } + if (!Array.isArray(input.authors) || !input.authors.length) report('authors', 'name at least one author: [{ "name": "…", "role": "Author" }]') + else input.authors.forEach((/** @type {unknown} */ author, /** @type {number} */ i) => { + if (!isObject(author) || typeof author.name !== 'string' || !author.name.trim()) report(`authors[${i}].name`, 'expected the author\'s name') + else if (!ROLES.includes(author.role)) report(`authors[${i}].role`, `use one of ${ROLES.join(', ')}`) + else for (const key of Object.keys(author)) if (key !== 'name' && key !== 'role') report(`authors[${i}].${key}`, 'is not part of an author; write name and role') + }) + if (input.source !== undefined && (typeof input.source !== 'string' || !/^https?:\/\/\S+$/i.test(input.source))) report('source', 'expected the address the content comes from') + for (const key of ['yearFrom', 'yearTo']) if (input[key] !== undefined && !Number.isInteger(input[key])) report(key, 'expected a year') + if (input.params !== undefined && !isObject(input.params)) report('params', 'expected an object of the content type\'s fields') + if (problems.length) throw new SourceError(problems) + return /** @type {Source} */ ({ ...input, type: String(input.type).trim(), params: input.params ?? {} }) +} + +/** + * The libraries a source can bring in, opened and localized before generation: the content type, + * every library the written parameters name, and every one a library field names as its default. + * @param {import('./pack.mjs').Pack} pack + * @param {Source} source + * @param {(path: string, message: string) => void} report + */ +async function loadLibraries(pack, source, report) { + /** @type {Map} */ + const entries = new Map() + /** @type {TranslationReport[]} */ + const translations = [] + /** @type {Map} */ + const parts = new Map() + const main = /^(\S+?)(?:\s+(\d+)\.\d+)?$/.exec(source.type) + const mainEntry = main ? pack.newest(main[1], main[2] === undefined ? undefined : Number(main[2])) : null + if (!mainEntry) { + report('type', `the library pack has no content type ${source.type}`) + return null + } + /** @type {{ machineName: string, major?: number }[]} */ + const queue = [{ machineName: mainEntry.machineName, major: mainEntry.majorVersion }] + /** @param {unknown} value */ + const named = (value) => { + if (Array.isArray(value)) value.forEach(named) + else if (isObject(value)) { + const match = typeof value.library === 'string' ? /^\s*(\S+?)(?:\s+(\d+)\.\d+)?\s*$/.exec(value.library) : null + // A name without a version is resolved by the field's options, which may name any major the + // pack has: each is loaded. + if (match && match[2] !== undefined) queue.push({ machineName: match[1], major: Number(match[2]) }) + else if (match) for (const entry of pack.libraries) if (entry.machineName === match[1]) queue.push({ machineName: match[1], major: entry.majorVersion }) + Object.values(value).forEach(named) + } + } + named(source.params) + /** @param {any[]} fields */ + const defaults = (fields) => { + for (const field of fields) { + if (field.type === 'library' && isObject(field.default)) named(field.default) + 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 entry = pack.newest(machineName, major) + if (!entry || parts.has(entry.folder)) continue + const part = await pack.open(entry) + parts.set(entry.folder, part) + let semantics = part.semantics + if (semantics) { + const files = translationFiles([...part.translations.keys()], source.language).map((name) => ({ name, read: () => pack.translation(part, name) })) + const localized = await localize(semantics, files, libraryString(part.library)) + semantics = patchSemantics(part.library.machineName, localized.semantics) + if (part.library.runnable || entry === mainEntry) translations.push(localized.report) + defaults(semantics) + } + entries.set(entry.folder, { folder: entry.folder, library: part.library, semantics }) + } + // 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) { + if (!entries.has(entry.folder)) entries.set(entry.folder, { folder: entry.folder, library: { machineName: entry.machineName, majorVersion: entry.majorVersion, minorVersion: entry.minorVersion, title: entry.machineName }, semantics: null }) + } + return { entries, mainEntry, translations, parts } +} + +/** + * The libraries a package carries: what the content names, its dependencies, and the addons the + * pack has whose pattern its text matches, as a site with the addon installed exports it. + * @param {import('./pack.mjs').Pack} pack + * @param {string[]} named library strings, the main library first + * @param {Record} content + */ +async function closure(pack, named, content) { + /** @type {Map} */ + const selected = new Map() + /** @param {string} machineName @param {number} [major] @param {number} [minor] */ + const use = async (machineName, major, minor = 0) => { + const entry = pack.newest(machineName, major) + if (!entry || entry.minorVersion < minor) throw new Error(`The library pack cannot supply ${machineName} ${major ?? ''}.${minor}`) + if (selected.has(entry.folder)) return + const part = await pack.open(entry) + selected.set(entry.folder, part) + for (const dependency of [...(part.library.preloadedDependencies ?? []), ...(part.library.dynamicDependencies ?? [])]) { + await use(dependency.machineName, Number(dependency.majorVersion), Number(dependency.minorVersion)) + } + } + for (const name of named) { + const [machineName, version] = name.split(' ') + const [major, minor] = version.split('.').map(Number) + await use(machineName, major, minor) + } + const addons = [] + for (const entry of pack.libraries) { + const patterns = entry.addTo?.content?.types ?? [] + for (const type of patterns) { + const regex = type?.text?.regex + if (typeof regex !== 'string') continue + const match = /^\/(.*)\/([a-z]*)$/s.exec(regex) + if (!match) continue + let pattern + try { + pattern = new RegExp(match[1], match[2].replace(/[^imsuy]/g, '')) + } catch { + continue + } + if (strings(content).some((each) => pattern.test(each))) { + addons.push(entry) + break + } + } + } + for (const addon of addons) await use(addon.machineName, addon.majorVersion, addon.minorVersion) + return { selected, addons: addons.map((addon) => `${addon.machineName} ${addon.majorVersion}.${addon.minorVersion}`) } +} + +/** Every string in a value. @param {unknown} value @param {string[]} [found] */ +function strings(value, found = []) { + if (typeof value === 'string') found.push(value) + else if (Array.isArray(value)) value.forEach((item) => strings(item, found)) + else if (isObject(value)) Object.values(value).forEach((item) => strings(item, found)) + return found +} + +/** + * The refusal of an output that exists, with the file system's code, so a caller tells it from + * a source's problems. + * @param {string} output + */ +function exists(output) { + return Object.assign(new Error(`${output} exists, and a build never writes over a file: name a new one`), { code: 'EEXIST' }) +} + +/** + * Builds a package from a source and writes it to `output`, which must not exist yet. + * @param {unknown} input the source: `{ type, title, language, license, authors, params }`, or a quiz in the published quiz format + * @param {string} output + * @param {BuildOptions} [options] + * @returns {Promise} + */ +export async function buildPackage(input, output, options = {}) { + output = resolve(output) + // Before any work, and again as the package lands, for a file that appears in between. + if (await lstat(output).then(() => true, () => false)) throw exists(output) + if (!(await stat(dirname(output)).catch(() => null))?.isDirectory()) throw new Error(`${dirname(output)} is not a folder to write the package in`) + const source = readSource(input) + const pack = await openPack(options.libraries) + let temporary + try { + /** @type {Problem[]} */ + const problems = [] + /** @type {Problem[]} */ + const notes = [] + const report = (/** @type {string} */ path, /** @type {string} */ message) => problems.push({ path, message }) + const note = (/** @type {string} */ path, /** @type {string} */ message) => notes.push({ path, message }) + const loaded = await loadLibraries(pack, source, report) + if (!loaded) throw new SourceError(problems) + const { entries, mainEntry, translations } = loaded + const authors = source.authors.map((author) => ({ name: escapeText(author.name), role: author.role })) + const generator = new ContentGenerator(entries, { + metadata(entry, written, path) { + const title = written?.title + if (title !== undefined && (typeof title !== 'string' || !title.trim())) report(`${path}.metadata.title`, 'expected a title') + else if (typeof title === 'string' && title.length > 255) report(`${path}.metadata.title`, 'takes at most 255 characters') + return { + contentType: escapeText(String(entry.library.title ?? entry.library.machineName)), + license: source.license, + ...(source.licenseVersion ? { licenseVersion: source.licenseVersion } : {}), + authors: authors.map((author) => ({ ...author })), + ...(typeof title === 'string' && title.trim() ? { title: escapeText(title) } : {}) + } + } + }) + const main = /** @type {NonNullable} */ (mainEntry) + const mainLibrary = /** @type {{ folder: string, library: any, semantics: any[] | null }} */ (entries.get(main.folder)) + if (!mainLibrary.semantics) report('type', `${source.type} has no semantics: it is not a content type an author fills in`) + else if (!mainLibrary.library.runnable) report('type', `${mainLibrary.library.machineName} is a part other content holds, not a content type on its own: put it in one, such as H5P.Column`) + + // Layouts that adjust what is written, before it is generated. + const context = (/** @type {string} */ machineName) => { + const entry = [...entries.values()].find((each) => each.library.machineName === machineName && each.semantics) + return { + report, note, + semantics: entry?.semantics ?? [], + library: entry?.library, + title: (/** @type {string} */ library) => { + const name = String(library).split(' ')[0] + const found = [...entries.values()].find((each) => each.library.machineName === name && each.semantics) + return String(found?.library.title ?? name) + } + } + } + const written = structuredClone(source.params) + for (const place of placesOf(main.machineName, written)) LAYOUTS[place.library]?.before?.(place.params, place.path, context(place.library)) + + const content = generator.generate(mainLibrary, written) + problems.push(...generator.problems) + notes.push(...generator.notes) + + // Media: copied, described, put in place of what was written. + temporary = await mkdtemp(join(dirname(output), '.h5p-author-')) + const media = new MediaStore({ base: options.base ?? process.cwd(), temporary, fetch: options.fetch }) + for (const { field, value, path } of generator.media) { + const resolved = await media.resolve(field, value, path, report) + for (const key of Object.keys(value)) delete value[key] + Object.assign(value, resolved) + } + + // Layouts that set what the editor's widgets set, and check what they would not let pass. + for (const place of placesOf(main.machineName, content)) LAYOUTS[place.library]?.after?.(place.params, place.path, context(place.library)) + for (const place of placesOf(main.machineName, content)) { + if (place.holder && isObject(place.holder.metadata) && place.holder.metadata.title === undefined) place.holder.metadata.title = place.holder.metadata.contentType + } + for (const { field, path } of generator.unset) { + if (valueAt(content, path) === undefined && !problems.some((problem) => problem.path === path)) report(path, `is required (${field.type}), and nothing set it`) + } + if (problems.length) throw new SourceError(problems) + + const named = [libraryString(mainLibrary.library), ...[...librariesIn(content)].filter((name) => name !== libraryString(mainLibrary.library))] + const { selected, addons } = await closure(pack, named, content) + if (addons.length) notes.push({ path: 'params', message: `its text matches ${addons.join(', ')}, which the package carries, as a site with it installed would add it` }) + + // As H5P's exports write it, unescaped: the platforms check it when they load content. + const manifest = { + title: source.title, + language: source.language, + defaultLanguage: source.language, + license: source.license, + ...(source.licenseVersion ? { licenseVersion: source.licenseVersion } : {}), + authors: source.authors.map(({ name, role }) => ({ name, role })), + ...(source.source ? { source: source.source } : {}), + ...(source.yearFrom !== undefined ? { yearFrom: source.yearFrom } : {}), + ...(source.yearTo !== undefined ? { yearTo: source.yearTo } : {}), + mainLibrary: mainLibrary.library.machineName, + embedTypes: ['div'], + preloadedDependencies: [...selected.values()].map((part) => ({ + machineName: part.library.machineName, majorVersion: String(part.library.majorVersion), minorVersion: String(part.library.minorVersion) + })) + } + + const staged = join(temporary, 'package.h5p') + const file = await open(staged, 'wx') + try { + const writer = new ZipWriter(Writable.toWeb(file.createWriteStream()), { useWebWorkers: false }) + await writer.add('h5p.json', new TextReader(JSON.stringify(manifest))) + for (const part of selected.values()) { + await writer.appendZip(part.file, { filter: (entry) => !entry.directory && entry.filename.startsWith(`${part.folder}/`) }) + } + await writer.add('content/content.json', new TextReader(JSON.stringify(content))) + for (const item of media.files) { + await writer.add(`content/${item.name}`, /** @type {ReadableStream} */ (Readable.toWeb(createReadStream(item.from))), { level: 0 }) + } + await writer.close() + } finally { + await file.close() + } + let final = staged + if (media.files.length) { + // Media stored and last, an mp4's index first: the layout a package streams in. + final = join(temporary, 'normalized.h5p') + await normalizeArchive({ input: staged, output: final }) + } + // Unlike a hard link, an exclusive copy also works on FAT/exFAT destinations. + await copyFile(final, output, constants.COPYFILE_EXCL).catch((error) => { + throw error?.code === 'EEXIST' ? exists(output) : error + }) + return { + output, + manifest, + content, + libraries: [...selected.keys()], + translations, + notes, + media: media.files.map((item) => item.name) + } + } finally { + await pack.close() + if (temporary) await rm(temporary, { recursive: true, force: true }) + } +} + +/** + * The value at a generator path, `params.a[0].b`, in the content. + * @param {any} content + * @param {string} path + */ +function valueAt(content, path) { + let value = { params: content } + for (const part of path.replace(/\[(\d+)\]/g, '.$1').split('.')) { + if (value === undefined || value === null) return undefined + value = /** @type {any} */ (value)[part] + } + return value +} diff --git a/packages/author/lib/generator.mjs b/packages/author/lib/generator.mjs new file mode 100644 index 00000000..ebb210b3 --- /dev/null +++ b/packages/author/lib/generator.mjs @@ -0,0 +1,668 @@ +import { randomUUID } from 'node:crypto' +import { markupText, plainText } from './text.mjs' + +/** + * Content for a content type, made from its own `semantics.json` as H5P's editor saves a form: + * what is written where it says something, and everywhere else every default the semantics give. + * A field that holds another content type takes the library the written value names, filled in + * the same way. So a source states only what the defaults cannot know, and a list in it is as long + * as it is written. + * + * Two ways to run it. Authoring, the default, checks every written value against its field, as the + * editor's form would: a field the semantics do not name, a select's unknown option, a list too + * short or too long, a tag a markup field does not take, a required field with neither a written + * value nor a default — each a problem named by its path. The content-type sweep runs it + * `lenient`, taking what is written as it is and filling a required field from `fill`, so that + * every content type in the pack plays (apps/demo/scripts/sweep-content-types.mjs). + * + * 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, + * translate.mjs, schema.mjs and media.mjs; AGENTS.md says how to move them to a newer editor. Where + * this departs from that editor: + * + * - An optional list nobody wrote stays empty. The editor starts every new list with `defaultNum`, + * `min` or one item, optional or not, for an author to fill or remove. + * - A `showWhen` rule on a field that is not a select, a library or a boolean is compared as text, + * where ShowWhen leaves the rule out; the pack has none. A value a source writes for a field + * that `nullWhenHidden` hides is kept, where the editor clears it. + * + * Pure but for the ids: the pack is handed in as a map of folders, each with its `library.json` + * and `semantics.json`. Media are not read here: a written file is checked for its shape and + * collected in `media`, for the caller to copy and describe. + */ + +/** The nesting depth at which a library field stops choosing content of its own. */ +const MAX_DEPTH = 4 + +/** + * @typedef {{ folder: string, library: any, semantics: any[] | null }} PackEntry + * @typedef {{ path: string, message: string }} Problem + * @typedef {{ field: any, value: any, path: string }} MediaReference + * @typedef {{ + * lenient?: boolean, + * fill?: (field: any, context: { generator: ContentGenerator, stack: string[], path: string }) => unknown, + * id?: (count: number) => string, + * metadata?: (entry: PackEntry, written: any, path: string) => any + * }} GeneratorOptions + */ + +export class ContentGenerator { + /** + * @param {Map} pack every library folder the content may use, by folder name + * @param {GeneratorOptions} [options] + */ + constructor(pack, options = {}) { + this.pack = pack + this.options = options + this.lenient = options.lenient ?? false + this.ids = 0 + /** @type {Problem[]} what is wrong with the written content, authoring only */ + this.problems = [] + /** @type {Problem[]} what is worth saying about it and does not stop a build */ + this.notes = [] + /** @type {MediaReference[]} the files the written content names, for the caller to copy */ + this.media = [] + /** @type {WeakSet} fields a content type's own widget draws: numbers take decimals, lists start empty */ + this.drawn = new WeakSet() + /** @type {{ field: any, path: string }[]} hidden fields left for a content type's layout to set */ + this.unset = [] + /** @type {{ fields: any[], given: Record }[]} the levels a `showWhen` path climbs, innermost last */ + this.scopes = [] + } + + /** + * Whether the editor shows a field, by its `showWhen` rules as H5PEditor.ShowWhen reads them: + * one of them holds, or every one where the rules say `and`, on the value written for the field + * a rule names, or its default. Each `../` in that name climbs a level, as h5peditor.js's + * `findField` climbs from a widget to its parent (see `#level`). A field the editor hides is not + * asked for. + * @param {any} field + */ + #visible(field) { + const rules = field.showWhen?.rules + if (!Array.isArray(rules) || !rules.length) return true + const results = rules.map((/** @type {any} */ rule) => { + let name = String(rule.field ?? '') + let level = this.scopes.length - 1 + while (name.startsWith('../')) { + name = name.slice(3) + level -= 1 + } + const scope = this.scopes[level] + if (!scope) return true + const sibling = scope.fields.find((each) => each.name === name) + let value = scope.given[name] ?? sibling?.default + if (value === undefined && sibling?.type === 'boolean') value = false + if (isObject(value) && typeof value.library === 'string') value = value.library.trim().split(/\s+/)[0] + return [rule.equals].flat().some((/** @type {unknown} */ wanted) => { + if (typeof value === 'string' && typeof wanted === 'string' && /^\S+ \d+\.\d+$/.test(wanted)) return wanted.split(' ')[0] === value + return String(wanted) === String(value) + }) + }) + return field.showWhen.type === 'and' ? results.every(Boolean) : results.some(Boolean) + } + + /** + * A copy of a field with something changed, drawn by a widget if the field is. + * @param {any} field + * @param {Record} changes + */ + #copy(field, changes) { + const copy = { ...field, ...changes } + if (this.drawn.has(field)) this.drawn.add(copy) + return copy + } + + /** A field as optional, for one the editor hides. @param {any} field */ + #optional(field) { + return this.#copy(field, { optional: true }) + } + + /** A field as it is filled here: optional where the editor hides it. @param {any} field */ + #shown(field) { + return this.lenient || this.#visible(field) ? field : this.#optional(field) + } + + /** + * What a callback generates a level down, for `showWhen`: the fields a rule can name there, and + * what was written for them. The editor makes a level of every widget that holds others: the + * form, each group, a group of one field among them, each list and each sub-content. A list's + * level names no field, so a rule in a list's item reaches what holds the list with `../../`. + * @template T + * @param {any[]} fields + * @param {Record} given + * @param {() => T} generate + * @returns {T} + */ + #level(fields, given, generate) { + this.scopes.push({ fields, given }) + try { + return generate() + } finally { + this.scopes.pop() + } + } + + /** + * The newest library in the pack with this machine name and, when given, this major — the + * one the player serves for any minor of it. + * @param {string} machineName + * @param {number} [major] + */ + find(machineName, major) { + /** @type {PackEntry | null} */ + let best = null + for (const entry of this.pack.values()) { + const { library } = entry + if (library.machineName !== machineName) continue + if (major !== undefined && library.majorVersion !== major) continue + if (!best || library.majorVersion > best.library.majorVersion || (library.majorVersion === best.library.majorVersion && library.minorVersion > best.library.minorVersion)) best = entry + } + return best + } + + /** + * The parameters for a library's content, with `written` — the authored parameters, if any — + * laid in. + * @param {PackEntry} entry + * @param {any} [written] + * @param {string} [path] where the parameters sit, for problems: `params` by default + */ + generate(entry, written, path = 'params') { + return this.fields(entry.semantics ?? [], written, [entry.library.machineName], false, path) + } + + /** A sub-content id: random, or the caller's, numbered, where it wants the same bytes every run. */ + nextId() { + this.ids += 1 + return this.options.id ? this.options.id(this.ids) : randomUUID() + } + + /** @param {string} path @param {string} message */ + report(path, message) { + this.problems.push({ path, message }) + } + + /** @param {string} path @param {string} message */ + note(path, message) { + this.notes.push({ path, message }) + } + + /** + * @param {any[]} fields + * @param {any} written the written object for these fields, or undefined + * @param {string[]} stack the content types this value sits inside, to keep a type out of itself + * @param {boolean} lenient inside an optional group nobody wrote: defaults only, as the editor + * saves a group left closed — and so nothing asked for a field required only within it + * @param {string} path + */ + fields(fields, written, stack, lenient, path) { + /** @type {Record} */ + const out = {} + if (!this.lenient && written !== undefined && !isObject(written)) { + this.report(path, `expected an object with the fields ${names(fields)}`) + return out + } + const given = isObject(written) ? written : {} + this.#level(fields, given, () => { + for (const field of fields) { + const value = this.field(this.#shown(field), given[field.name], stack, lenient, `${path}.${field.name}`) + if (value !== undefined) out[field.name] = value + } + }) + for (const [key, value] of Object.entries(given)) { + if (key in out || fields.some((field) => field.name === key)) continue + // Lenient, what the semantics do not name is kept as written: the content check removes + // it, which a sweep file may mean to test. + if (this.lenient) { + if (value !== null) out[key] = value + } else this.report(`${path}.${key}`, `is not a field here; the fields are ${names(fields)}`) + } + return out + } + + /** + * @param {any} field + * @param {any} written the written value, `null` to leave the field out, or undefined + * @param {string[]} stack + * @param {boolean} lenient + * @param {string} path + * @returns {any} + */ + field(field, written, stack, lenient, path) { + const optional = field.optional || lenient + 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 + } + switch (field.type) { + case 'group': { + const children = field.fields ?? [] + // A group of one field is saved as that field's value, as the editor (h5peditor-group.js) + // and the content check have it, unless the group is sub-content. It is still a level for + // `showWhen`, the parent of its one field. + const flattened = children.length === 1 && !field.isSubContent + if (written === undefined && field.default !== undefined) return structuredClone(field.default) + if (flattened) { + const [only] = children + return this.#level(children, written === undefined ? {} : { [only.name]: written }, () => + this.field(this.#shown(only), written, stack, optional && written === undefined, path)) + } + if (written !== undefined && !isObject(written)) { + if (this.lenient) return written + this.report(path, `expected an object with the fields ${names(children)}`) + return undefined + } + // A group the editor draws with a widget of its own — a duration, a position on an image, + // a slide — takes numbers as that widget sets them, decimals included, and starts its + // lists empty. + if (field.widget && field.widget !== 'showWhen' && field.widget !== 'none') this.#draw(children) + // Saved even when optional and untouched, as the editor saves every group in its form + // (h5peditor-group.js): content types read into one without looking (Personality Quiz's + // `image.file`). + return this.fields(children, written, stack, optional && written === undefined, path) + } + case 'list': { + const item = this.#copy(field.field, { optional: false }) + if (Array.isArray(written)) { + if (!this.lenient) { + if (field.min !== undefined && written.length < field.min) 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}`) + } + return this.#level([], {}, () => written.map((each, index) => this.field(item, each, stack, false, `${path}[${index}]`)).filter((each) => each !== undefined)) + } + if (written !== undefined && !this.lenient) { + this.report(path, 'expected a list') + return undefined + } + const count = !this.lenient && this.drawn.has(field) + ? optional ? 0 : field.min ?? 0 + : Math.min(Math.max(optional ? 0 : (field.min ?? 0), field.defaultNum ?? (optional ? 0 : 1)), field.max ?? Infinity) + if (!this.lenient && count > 0) { + // A required list nobody wrote is what the editor offers a new author + // (h5peditor-list.js): as many items as it asks for, each with its defaults. Where an + // item needs something only an author can give, the list itself is what is missing. + const before = this.problems.length + const items = this.#items(item, count, stack, lenient, path) + if (this.problems.length > before) { + this.problems.length = before + this.report(path, `is required: write at least ${Math.max(field.min ?? 1, 1)} item${Math.max(field.min ?? 1, 1) === 1 ? '' : 's'}`) + return undefined + } + return items + } + const items = this.#items(item, count, stack, lenient, path) + return items.length > 0 || !optional ? items : undefined + } + 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": { … } }`) + return undefined + } + // A default names the content the editor starts with (h5peditor.js puts it in the + // parameters, h5peditor-library.js loads it): Interactive Video's summary task. Left as the + // editor leaves it for an author who never opens it: what it would ask for is not asked + // here either, and stays unwritten. + if (written === undefined && isObject(field.default) && typeof field.default.library === 'string') { + if (this.lenient) return this.writtenLibrary(field.default, stack, path, null) + return this.#quietly(() => this.writtenLibrary(structuredClone(field.default), stack, path, null)) + } + return optional ? undefined : this.missing(field, stack, path) + case 'text': + if (written !== undefined) return this.lenient ? written : this.text(field, written, path) + // A default of null, which Course Presentation gives its colours, is stored as nothing: the + // platforms' check would turn it into an empty text. + if (field.default === null && !this.lenient) return undefined + if (field.default !== undefined) return field.default + return optional ? undefined : this.missing(field, stack, path) + case 'number': + if (written !== undefined) return this.lenient ? written : this.number(field, written, path) + if (field.default !== undefined) return field.default + return optional ? undefined : this.missing(field, stack, path) + case 'boolean': + if (written !== undefined && !this.lenient && typeof written !== 'boolean') this.report(path, 'expected true or false') + // The editor's checkbox saves false when nobody ticked it (h5peditor-boolean.js). + return written ?? field.default ?? false + case 'select': + if (written !== undefined) return this.lenient ? written : this.select(field, written, path) + if (field.default !== undefined) return structuredClone(field.default) + return optional ? undefined : this.missing(field, stack, path) + case 'image': + case 'file': + case 'video': + case 'audio': + if (written !== undefined) return this.lenient ? written : this.file(field, written, path) + return optional ? undefined : this.missing(field, stack, path) + default: + return written + } + } + + /** + * What a callback generates, with nothing it would report: problems, notes and hidden fields. + * @template T + * @param {() => T} generate + * @returns {T} + */ + #quietly(generate) { + const counts = [this.problems.length, this.notes.length, this.unset.length] + try { + return generate() + } finally { + this.problems.length = counts[0] + this.notes.length = counts[1] + this.unset.length = counts[2] + } + } + + /** Fields, and all within them, as a widget of the editor's draws them. @param {any[]} fields */ + #draw(fields) { + for (const field of fields) { + if (!field || this.drawn.has(field)) continue + this.drawn.add(field) + if (field.fields) this.#draw(field.fields) + if (field.field) this.#draw([field.field]) + } + } + + /** + * A new list's items, each with its defaults, a level below the list's. + * @param {any} item + * @param {number} count + * @param {string[]} stack + * @param {boolean} lenient + * @param {string} path + */ + #items(item, count, stack, lenient, path) { + return this.#level([], {}, () => { + const items = [] + for (let index = 0; index < count; index++) { + const value = this.field(item, undefined, stack, lenient, `${path}[${index}]`) + if (value !== undefined) items.push(value) + } + return items + }) + } + + /** + * A required field with neither a written value nor a default: the caller's to fill, or a + * problem. + * @param {any} field + * @param {string[]} stack + * @param {string} path + */ + missing(field, stack, path) { + if (this.options.fill) return this.options.fill(field, { generator: this, stack, path }) + // A field the editor hides is its own bookkeeping, a position it sets when an author drags + // something: a content type's layout sets it here, and what none sets is a problem then. + if (field.widget === 'none') { + this.unset.push({ field, path }) + return undefined + } + this.report(path, `is required (${describe(field)})`) + return undefined + } + + /** + * Sub-content: the first option the pack has and that is not already a parent here, made from + * its own semantics. None at all is left out, which the content check would do anyway. The + * sweep's fill, for a field it has to fill to make a content type play. + * @param {any} field + * @param {string[]} stack + * @param {string} [path] + */ + library(field, stack, path = '') { + if (stack.length > MAX_DEPTH) return undefined + for (const option of field.options ?? []) { + const name = typeof option === 'string' ? option : option?.name + const match = /^(\S+) (\d+)\.(\d+)$/.exec(name ?? '') + if (!match || stack.includes(match[1])) continue + const entry = this.find(match[1], Number(match[2])) + if (!entry) continue + return this.subContent(entry, undefined, undefined, stack, path) + } + return undefined + } + + /** + * 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 + * remove or the runtime to refuse; authoring, it is a problem, as is one the field does not take. + * @param {any} written + * @param {string[]} stack + * @param {string} path + * @param {any} field the library field, or null for a default the semantics give + */ + writtenLibrary(written, stack, path, field) { + if (this.lenient) { + const match = /^(\S+) (\d+)\.(\d+)$/.exec(written.library) + const entry = match ? this.find(match[1], Number(match[2])) : null + if (!entry) return written + return { ...this.subContent(entry, written.params, undefined, stack, path), ...omit(written, ['params']), library: libraryString(entry.library) } + } + const match = /^\s*(\S+?)(?:\s+(\d+)\.(\d+))?\s*$/.exec(written.library) + if (!match) { + this.report(`${path}.library`, `expected a library's machine name, such as ${optionNames(field)[0] ?? '"H5P.MultiChoice"'}`) + return undefined + } + const machineName = match[1] + let major = match[2] === undefined ? undefined : Number(match[2]) + if (field) { + const options = libraryOptions(field) + const option = options.find((each) => each.machineName === machineName && (major === undefined || each.major === major)) + if (!option) { + this.report(`${path}.library`, `${machineName} is not one this field takes; it takes ${[...new Set(options.map((each) => each.machineName))].join(', ')}`) + return undefined + } + major = option.major + } + const entry = this.find(machineName, major) + if (!entry) { + this.report(`${path}.library`, `the library pack has no ${machineName}${major === undefined ? '' : ` ${major}.x`}`) + return undefined + } + for (const key of Object.keys(written)) { + if (!['library', 'params', 'metadata'].includes(key)) this.report(`${path}.${key}`, 'is not part of sub-content; write library, params and metadata') + } + if (written.metadata !== undefined && !isObject(written.metadata)) this.report(`${path}.metadata`, 'expected an object, such as { "title": "…" }') + 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) + } + + /** + * @param {PackEntry} entry + * @param {any} written its parameters + * @param {any} metadata its written metadata + * @param {string[]} stack + * @param {string} path + */ + subContent(entry, written, metadata, stack, path) { + return { + library: libraryString(entry.library), + params: this.fields(entry.semantics ?? [], written, [...stack, entry.library.machineName], false, `${path}.params`), + subContentId: this.nextId(), + metadata: this.options.metadata + ? this.options.metadata(entry, metadata, path) + : { contentType: entry.library.title, license: 'U', title: entry.library.title } + } + } + + /** + * @param {any} field + * @param {unknown} written + * @param {string} path + */ + text(field, written, path) { + if (typeof written !== 'string') { + this.report(path, `expected text${typeof written === 'number' ? `, such as "${written}"` : ''}`) + return undefined + } + const stored = field.tags === undefined || field.tags === null + ? plainText(written, (message) => this.note(path, message)) + : markupText(written, field, (message) => this.report(path, message)) + const length = Array.from(stored).length + if (typeof field.maxLength === 'number' && length > field.maxLength) this.report(path, `is ${length} characters as stored; it takes at most ${field.maxLength}`) + if (field.regexp?.pattern && !(stored === '' && field.optional)) { + let pattern = null + try { + pattern = new RegExp(field.regexp.pattern, (field.regexp.modifiers ?? '').replace(/[^gimsuy]/g, '')) + } catch { + // A pattern JavaScript cannot read is the content check's to apply, not ours. + } + if (pattern && !pattern.test(stored)) this.report(path, `"${written.slice(0, 40)}" is not in the form this field takes${field.description ? ` (${stripTags(field.description).slice(0, 120)})` : ''}`) + } + if (!field.optional && stripTags(stored) === '' && !/<(img|iframe|video|audio|hr|table)/i.test(stored)) this.report(path, 'is required and is empty') + return stored + } + + /** + * A number as h5peditor-number.js checks it: within its range; with at most `decimals` + * decimals, or none where the field has no `decimals` and no widget of its own draws it; and a + * multiple of `step`, counted from 0 as its `value % step` counts. + * @param {any} field + * @param {unknown} written + * @param {string} path + */ + number(field, written, path) { + if (typeof written !== 'number' || !Number.isFinite(written)) { + this.report(path, 'expected a number') + return undefined + } + if (field.min !== undefined && written < Number(field.min)) this.report(path, `is ${written}; the least it takes is ${field.min}`) + if (field.max !== undefined && written > Number(field.max)) this.report(path, `is ${written}; the most it takes is ${field.max}`) + if (field.decimals !== undefined && Number(field.decimals) >= 0) { + const factor = 10 ** Number(field.decimals) + if (Math.round(written * factor) / factor !== written) this.report(path, `takes ${field.decimals ? `at most ${field.decimals} decimals` : 'a whole number'}`) + } else if (!field.widget && !this.drawn.has(field) && !Number.isInteger(written)) this.report(path, 'takes a whole number') + if (field.step !== undefined && Number(field.step) > 0 && written % Number(field.step) !== 0) this.report(path, `takes steps of ${field.step}`) + return written + } + + /** + * @param {any} field + * @param {unknown} written + * @param {string} path + */ + select(field, written, path) { + const values = selectValues(field) + const check = (/** @type {unknown} */ value) => { + if (values.length && !values.includes(String(value))) this.report(path, `${JSON.stringify(value)} is not an option; the options are ${values.map((each) => JSON.stringify(each)).join(', ')}`) + } + if (field.multiple) { + if (!Array.isArray(written)) this.report(path, 'expected a list of options') + else written.forEach(check) + } else if (typeof written !== 'string' && typeof written !== 'number' && typeof written !== 'boolean') this.report(path, 'expected one of its options') + else check(written) + return written + } + + /** + * A written file: `{ "path": … }`, a file beside the source or a web address, with `copyright` + * when known. A video or an audio field takes a list of them, one per format, or one alone. + * Checked for its shape here; the caller copies it and fills in its type and size. + * @param {any} field + * @param {unknown} written + * @param {string} path + */ + file(field, written, path) { + const many = field.type === 'video' || field.type === 'audio' + const list = many && Array.isArray(written) ? written : [written] + if (many && Array.isArray(written) && !written.length) { + this.report(path, 'expected at least one file') + return undefined + } + if (!many && Array.isArray(written)) { + this.report(path, 'expected one file, { "path": "…" }') + return undefined + } + const files = [] + for (const [index, each] of list.entries()) { + const at = many && Array.isArray(written) ? `${path}[${index}]` : path + if (!isObject(each) || typeof each.path !== 'string' || !each.path.trim()) { + this.report(at, `expected a file, { "path": "picture.jpg" }, a file beside the source or a web address`) + continue + } + for (const key of Object.keys(each)) if (!['path', 'copyright'].includes(key)) this.report(`${at}.${key}`, 'is not part of a file here; write path and, when known, copyright') + if (each.copyright !== undefined && !isObject(each.copyright)) this.report(`${at}.copyright`, 'expected an object, such as { "license": "CC BY", "author": "…" }') + const value = { ...each } + this.media.push({ field, value, path: at }) + files.push(value) + } + return many ? files : files[0] + } +} + +/** Every `library` string in the parameters: the sub-content a package plays. */ +export function librariesIn(/** @type {any} */ params, found = new Set()) { + if (Array.isArray(params)) for (const item of params) librariesIn(item, found) + else if (isObject(params)) { + if (typeof params.library === 'string' && /^\S+ \d+\.\d+$/.test(params.library)) found.add(params.library) + for (const value of Object.values(params)) librariesIn(value, found) + } + return found +} + +/** `H5P.MultiChoice 1.16`, the form `library` fields and `h5p.json` use. */ +export function libraryString(/** @type {any} */ library) { + return `${library.machineName} ${library.majorVersion}.${library.minorVersion}` +} + +/** @param {any} field @returns {{ machineName: string, major: number, minor: number }[]} */ +function libraryOptions(field) { + return (field?.options ?? []) + .map((/** @type {any} */ option) => /^(\S+) (\d+)\.(\d+)$/.exec(typeof option === 'string' ? option : option?.name ?? '')) + .filter(Boolean) + .map((/** @type {RegExpExecArray} */ match) => ({ machineName: match[1], major: Number(match[2]), minor: Number(match[3]) })) +} + +/** @param {any} field */ +function optionNames(field) { + return libraryOptions(field).map((option) => option.machineName) +} + +/** @param {any} field @returns {string[]} */ +function selectValues(field) { + /** @type {string[]} */ + const values = [] + for (const option of field.options ?? []) { + if (option?.type === 'optgroup') for (const sub of option.options ?? []) values.push(String(sub.value)) + else if (option?.value !== undefined && option?.value !== null) values.push(String(option.value)) + } + return values +} + +/** A field's kind, as a problem names it. @param {any} field */ +function describe(field) { + switch (field.type) { + case 'text': return field.tags ? 'markup text' : 'text' + case 'select': return `one of ${selectValues(field).map((value) => JSON.stringify(value)).join(', ')}` + case 'library': return `sub-content: ${optionNames(field).join(', ')}` + case 'image': case 'file': return `a file, { "path": "…" }` + case 'video': case 'audio': return `a list of files, [{ "path": "…" }]` + default: return field.type + } +} + +/** @param {any[]} fields */ +function names(fields) { + return fields.map((field) => field.name).join(', ') +} + +/** @param {string} html */ +function stripTags(html) { + return html.replace(/<[^<>]*>/g, ' ').replace(/\s+/g, ' ').trim() +} + +/** @param {any} object @param {string[]} keys */ +function omit(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/media.mjs b/packages/author/lib/media.mjs new file mode 100644 index 00000000..d420a8b1 --- /dev/null +++ b/packages/author/lib/media.mjs @@ -0,0 +1,348 @@ +import { createWriteStream } from 'node:fs' +import { open, stat } from 'node:fs/promises' +import { basename, extname, join, resolve } from 'node:path' +import { Readable, Transform } from 'node:stream' +import { pipeline } from 'node:stream/promises' +import { escapeText } from './text.mjs' + +/** + * The files content shows: images, video, audio and other files, named in a source by a path + * beside it or a web address, copied into the package's `content/` folder with what H5P records + * of each — its type, an image's size, its copyright. A video on YouTube, Vimeo, Panopto or + * Echo360 stays there and is played from there, as H5P's editor embeds it (h5peditor-av.js, its + * `providers`), at an address H5P.Video plays. + */ + +/** The types H5P accepts for content (`H5PCore::$defaultContentWhitelist`), by what a field takes. */ +const TYPES = { + image: { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', bmp: 'image/bmp' }, + video: { mp4: 'video/mp4', webm: 'video/webm', ogg: 'video/ogg' }, + audio: { mp3: 'audio/mpeg', m4a: 'audio/mp4', wav: 'audio/wav', ogg: 'audio/ogg', webm: 'audio/webm' }, + file: { + pdf: 'application/pdf', txt: 'text/plain', csv: 'text/csv', md: 'text/markdown', vtt: 'text/vtt', webvtt: 'text/vtt', rtf: 'application/rtf', + doc: 'application/msword', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + xls: 'application/vnd.ms-excel', xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ppt: 'application/vnd.ms-powerpoint', pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + odt: 'application/vnd.oasis.opendocument.text', ods: 'application/vnd.oasis.opendocument.spreadsheet', odp: 'application/vnd.oasis.opendocument.presentation', + png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', mp3: 'audio/mpeg', mp4: 'video/mp4', json: 'application/json' + } +} + +/** The folder under `content/` H5P's editor keeps each kind in (h5peditor-file.class.php). */ +const FOLDERS = { image: 'images', video: 'videos', audio: 'audios', file: 'files' } + +/** Whether a host name is one of these domains or under one. @param {string} host @param {string[]} domains */ +const under = (host, domains) => domains.some((domain) => host === domain || host.endsWith(`.${domain}`)) + +/** + * Video a host plays itself, which H5P.Video embeds by address. H5P.Video chooses the player for + * an address by its own pattern for each host, and gives one no pattern matches to its HTML5 + * player, which cannot play a page. So `plays` takes only addresses H5P.Video 1.6's pattern for + * the host takes as well, and any other address on the host (`on`, told by its name, with no + * pattern to backtrack through its labels) is refused, naming the form. + * @type {{ host: string, mime: string, plays: RegExp, on: (url: URL) => boolean, form: string }[]} + */ +const HOSTED = [ + { + host: 'Vimeo', + mime: 'video/Vimeo', + plays: /^https?:\/\/(?:[\w-]+\.)*vimeo\.com\/(?:channels\/[A-Za-z_]+\/|groups\/[A-Za-z_]+\/videos\/)?\d/, + on: (url) => under(url.hostname, ['vimeo.com']), + form: 'https://vimeo.com/ and the video\'s number' + }, + { + host: 'YouTube', + mime: 'video/YouTube', + plays: /^https?:\/\/(?:[\w-]+\.)*(?:youtube\.com\/(?:watch\?(?:[^#\s]*&)?v=|embed\/|v\/)|youtu\.be\/)[\w-]{11}/i, + on: (url) => under(url.hostname, ['youtube.com', 'youtube-nocookie.com', 'youtu.be']), + form: 'https://www.youtube.com/watch?v= and the video\'s id' + }, + { + host: 'Panopto', + mime: 'video/Panopto', + plays: /^https?:\/\/[^/\s]+\/Panopto\/[^?\s]+\?id=\S+$/, + on: (url) => under(url.hostname, ['panopto.com', 'panopto.eu']) || url.pathname.toLowerCase().startsWith('/panopto/'), + form: 'the viewer\'s, …/Panopto/Pages/Viewer.aspx?id= and the session\'s id' + }, + { + host: 'Echo360', + mime: 'video/Echo360', + plays: /^https?:\/\/echo360[^/\s]+\/media\/[^/\s]+\/h5p(?:[/?#]\S*)?$/i, + on: (url) => url.hostname.split('.').some((label) => label.startsWith('echo360')), + form: 'its H5P address, https://echo360.org/media/, the media\'s id and /h5p' + } +] + +/** A YouTube Short or live stream, by its video's id, which H5P.Video plays at the watch address. */ +const YOUTUBE_SHORT = /^https?:\/\/(?:[\w-]+\.)*youtube\.com\/(?:shorts|live)\/([\w-]{11})(?![\w-])/i + +/** The licences a file's copyright may name, as H5P lists them. */ +const COPYRIGHT_LICENSES = ['U', 'CC BY', 'CC BY-SA', 'CC BY-ND', 'CC BY-NC', 'CC BY-NC-SA', 'CC BY-NC-ND', 'GNU GPL', 'PD', 'C'] + +/** The most a download may bring: a package of this size is already past what a learner waits for. */ +const MAX_DOWNLOAD = 1024 ** 3 + +/** + * How long a download may go without a byte before it is given up. Not a bound on the whole: a + * large video over a slow link takes as long as it takes, and only a silent one is dead. + */ +const IDLE_MS = 60_000 + +/** + * @typedef {{ name: string, from: string }} StagedFile a file to add to the package: its name under `content/`, and where it is on disk + * @typedef {{ path: string, message: string }} Problem + */ + +/** + * An image's width and height, read from its header: PNG, JPEG, GIF and BMP. A JPEG's are in its + * frame header, which any number of other segments may come before, a colour profile or XMP among + * them, so its segments are walked by their lengths, as far into the file as they go. + * @param {(offset: number, length: number) => Promise} read the file's bytes from an offset, fewer at its end + * @returns {Promise<{ width: number, height: number } | null>} + * @internal + */ +export async function imageSize(read) { + const head = await read(0, 26) + const view = new DataView(head.buffer, head.byteOffset, head.byteLength) + const ascii = (/** @type {number} */ offset, /** @type {number} */ length) => String.fromCharCode(...head.subarray(offset, offset + length)) + if (head.length >= 24 && ascii(1, 3) === 'PNG' && ascii(12, 4) === 'IHDR') return { width: view.getUint32(16), height: view.getUint32(20) } + if (head.length >= 10 && (ascii(0, 6) === 'GIF87a' || ascii(0, 6) === 'GIF89a')) return { width: view.getUint16(6, true), height: view.getUint16(8, true) } + if (head.length >= 26 && ascii(0, 2) === 'BM') return { width: Math.abs(view.getInt32(18, true)), height: Math.abs(view.getInt32(22, true)) } + if (head.length < 4 || head[0] !== 0xff || head[1] !== 0xd8) return null + let offset = 2 + // A bound on the walk, far past the few dozen segments a camera or an editor writes. + for (let steps = 0; steps < 10_000; steps++) { + const segment = await read(offset, 9) + if (segment.length < 4 || segment[0] !== 0xff) return null + const marker = segment[1] + // Fill before a marker. + if (marker === 0xff) { + offset += 1 + continue + } + const header = new DataView(segment.buffer, segment.byteOffset, segment.byteLength) + // A start-of-frame marker, baseline to lossless, holds the size; DHT, JPG and DAC do not. + if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) { + return segment.length < 9 ? null : { width: header.getUint16(7), height: header.getUint16(5) } + } + offset += 2 + header.getUint16(2) + } + return null +} + +export class MediaStore { + /** + * @param {{ base: string, temporary: string, fetch?: typeof fetch, idle?: number }} options + * `base`, the folder a source's relative paths are read from; `temporary`, where downloads land; + * `idle`, the milliseconds a download may go without a byte + */ + constructor({ base, temporary, fetch: fetchImpl = globalThis.fetch, idle = IDLE_MS }) { + this.base = base + this.temporary = temporary + this.fetch = fetchImpl + this.idle = idle + /** @type {StagedFile[]} */ + this.files = [] + /** @type {Map} by source, so one file named twice is copied once */ + this.known = new Map() + /** @type {Set} */ + this.names = new Set() + this.downloads = 0 + } + + /** + * A written file made what H5P stores: `{ path, mime, width?, height?, copyright }`, its bytes + * staged for the package. + * @param {any} field the image, video, audio or file field + * @param {{ path: string, copyright?: any }} value as written + * @param {string} at where it is written, for problems + * @param {(path: string, message: string) => void} report + * @returns {Promise>} + */ + async resolve(field, value, at, report) { + const kind = /** @type {'image' | 'video' | 'audio' | 'file'} */ (field.type) + const source = value.path.trim() + const copyright = this.copyright(value.copyright, `${at}.copyright`, report) + const web = /^https?:\/\//i.test(source) + if (web && kind === 'video') { + const short = YOUTUBE_SHORT.exec(source) + const address = short ? `https://www.youtube.com/watch?v=${short[1]}` : source + const hosted = HOSTED.find(({ plays }) => plays.test(address)) + if (hosted) return { path: address, mime: hosted.mime, copyright } + const url = URL.canParse(address) ? new URL(address) : null + const other = url ? HOSTED.find(({ on }) => on(url)) : undefined + if (other) { + report(`${at}.path`, `${source} is an address on ${other.host} that H5P.Video cannot play: give ${other.form}`) + return { path: source, copyright } + } + } + if (/^[a-z][a-z0-9+.-]*:/i.test(source) && !web) { + report(`${at}.path`, 'expected a file beside the source or an http(s) address') + return { path: source, copyright } + } + const types = /** @type {Record} */ (TYPES[kind]) + let known = this.known.get(source) + if (!known) { + const staged = web ? await this.#download(source, kind, types, at, report) : await this.#local(source, types, at, report) + if (!staged) return { path: source, copyright } + const extension = staged.extension + const mime = types[extension] + const name = this.#name(FOLDERS[kind], staged.stem, extension) + /** @type {{ name: string, mime: string, width?: number, height?: number }} */ + const described = { name, mime } + if (kind === 'image') { + const handle = await open(staged.from, 'r') + try { + const size = await imageSize(async (offset, length) => { + const bytes = new Uint8Array(length) + const { bytesRead } = await handle.read(bytes, 0, length, offset) + return bytes.subarray(0, bytesRead) + }) + if (!size) report(`${at}.path`, `${source} is not a ${extension.toUpperCase()} image whose size can be read`) + else Object.assign(described, size) + } finally { + await handle.close() + } + } + this.files.push({ name, from: staged.from }) + this.known.set(source, described) + known = described + } + const { name, ...rest } = known + return { path: name, ...rest, copyright } + } + + /** + * A file's copyright as H5P records it: a licence, and its author, title, year, source and + * version when given, as plain text. + * @param {unknown} written + * @param {string} at + * @param {(path: string, message: string) => void} report + */ + copyright(written, at, report) { + if (written === undefined) return { license: 'U' } + if (!written || typeof written !== 'object' || Array.isArray(written)) return { license: 'U' } + const value = /** @type {Record} */ (written) + /** @type {Record} */ + const out = { license: 'U' } + for (const [key, entry] of Object.entries(value)) { + if (!['license', 'author', 'title', 'year', 'source', 'version'].includes(key)) { + report(`${at}.${key}`, 'is not part of a copyright; write license, author, title, year, source or version') + continue + } + if (typeof entry !== 'string' || !entry.trim()) { + report(`${at}.${key}`, 'expected text') + continue + } + if (key === 'license' && !COPYRIGHT_LICENSES.includes(entry)) report(`${at}.license`, `use one of ${COPYRIGHT_LICENSES.join(', ')}`) + if (key === 'source' && !/^https?:\/\/.+/i.test(entry)) report(`${at}.source`, 'expected an http(s) address') + out[key] = key === 'license' || key === 'version' ? entry : escapeText(entry) + } + return out + } + + /** + * @param {string} source + * @param {Record} types + * @param {string} at + * @param {(path: string, message: string) => void} report + */ + async #local(source, types, at, report) { + const from = resolve(this.base, source) + const extension = extname(from).slice(1).toLowerCase() + if (!(extension in types)) { + report(`${at}.path`, `${source}: this field takes ${Object.keys(types).map((each) => `.${each}`).join(', ')}`) + return null + } + try { + const info = await stat(from) + if (!info.isFile()) throw new Error('not a file') + } catch { + report(`${at}.path`, `${source}: no such file beside the source (${from})`) + return null + } + return { from, extension, stem: basename(from, extname(from)) } + } + + /** + * A web address downloaded to the temporary folder, its type taken from its name or, failing + * that, from what the server says it is. + * @param {string} source + * @param {string} kind + * @param {Record} types + * @param {string} at + * @param {(path: string, message: string) => void} report + */ + async #download(source, kind, types, at, report) { + let url + try { + url = new URL(source) + } catch { + report(`${at}.path`, `${source} is not a web address`) + return null + } + // Started again by every byte that arrives. + const controller = new AbortController() + const failed = (/** @type {unknown} */ error) => { + const cause = controller.signal.aborted ? controller.signal.reason : error + report(`${at}.path`, `${source} could not be downloaded: ${cause instanceof Error ? cause.message : cause}`) + return null + } + const timer = setTimeout(() => controller.abort(new Error(`nothing arrived for ${this.idle / 1000} s`)), this.idle) + try { + let response + try { + response = await this.fetch(url.href, { redirect: 'follow', signal: controller.signal }) + } catch (error) { + return failed(error) + } + timer.refresh() + if (!response.ok || !response.body) { + await response.body?.cancel() + report(`${at}.path`, `${source} answered ${response.status}${kind === 'video' ? '; for a video on YouTube, Vimeo, Panopto or Echo360 give its address there' : ''}`) + return null + } + const named = extname(new URL(response.url || url.href).pathname).slice(1).toLowerCase() + const served = (response.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase() + const extension = named in types ? named : Object.keys(types).find((each) => types[each] === served) + if (!extension) { + await response.body.cancel() + report(`${at}.path`, `${source} is ${served || 'of an unknown type'}: this field takes ${Object.keys(types).map((each) => `.${each}`).join(', ')}`) + return null + } + this.downloads += 1 + const from = join(this.temporary, `download-${this.downloads}.${extension}`) + let received = 0 + const limit = new Transform({ + transform(chunk, _encoding, callback) { + timer.refresh() + received += chunk.length + callback(received > MAX_DOWNLOAD ? new Error(`larger than ${MAX_DOWNLOAD / 1024 ** 3} GB`) : null, chunk) + } + }) + try { + await pipeline(Readable.fromWeb(/** @type {import('node:stream/web').ReadableStream} */ (response.body)), limit, createWriteStream(from)) + } catch (error) { + return failed(error) + } + const stem = basename(decodeURIComponent(new URL(response.url || url.href).pathname), `.${named}`) || kind + return { from, extension, stem } + } finally { + clearTimeout(timer) + } + } + + /** + * A name under `content/` for a file: its own, made safe, and numbered where another has it. + * @param {string} folder + * @param {string} stem + * @param {string} extension + */ + #name(folder, stem, extension) { + const safe = stem.normalize('NFKD').replace(/[^\w.-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 60) || folder.slice(0, -1) + let name = `${folder}/${safe}.${extension}` + for (let count = 2; this.names.has(name.toLowerCase()); count++) name = `${folder}/${safe}-${count}.${extension}` + this.names.add(name.toLowerCase()) + return name + } +} diff --git a/packages/author/lib/pack.mjs b/packages/author/lib/pack.mjs new file mode 100644 index 00000000..ef05a655 --- /dev/null +++ b/packages/author/lib/pack.mjs @@ -0,0 +1,214 @@ +import { createHash } from 'node:crypto' +import { createReadStream } from 'node:fs' +import { open, readFile } from 'node:fs/promises' +import { join, resolve } from 'node:path' +import { Readable } from 'node:stream' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { Reader, TextWriter, ZipReader } from '@zip.js/zip.js' + +/** + * The library pack a build takes its libraries from: by default the one this package was released + * with, `@missing-elements/h5p-libraries` at the version it pins; or a copy of its `parts/` folder. + * Its index says each library's version, dependencies and part; a part is opened only when a + * build needs that library, and checked against the index's SHA-256 first, so a damaged or + * altered part is never read, let alone copied into a package. + */ + +/** + * @typedef {{ + * folder: string, machineName: string, majorVersion: number, minorVersion: number, patchVersion: number, + * preloadedDependencies?: { machineName: string, majorVersion: number, minorVersion: number }[], + * addTo?: any, size: number, sha256: string, url: string + * }} IndexEntry + */ + +/** + * A library whose part has been opened: what the generator reads (`folder`, `library`, + * `semantics`) and what a build copies. + * @typedef {{ + * folder: string, library: any, semantics: any[] | null, index: IndexEntry, + * translations: Map, file: PartFile, reader: ZipReader + * }} PartLibrary + */ + +/** + * A part read from disk by range: the largest, MathDisplay's, need not be held whole. + * @extends {Reader} + */ +class PartFile extends Reader { + /** @param {string} path */ + constructor(path) { + super(path) + this.path = path + /** @type {import('node:fs/promises').FileHandle | null} */ + this.handle = null + } + + async init() { + await super.init?.() + this.handle = await open(this.path, 'r') + this.size = (await this.handle.stat()).size + } + + /** + * A span streamed from disk, which zip.js copies an entry through. + * @param {{ offset?: number, size?: number }} [span] + * @returns {ReadableStream} + */ + createReadable({ offset = 0, size = this.size - offset } = {}) { + if (!size) return new ReadableStream({ start(controller) { controller.close() } }) + return /** @type {ReadableStream} */ (Readable.toWeb(createReadStream(this.path, { start: offset, end: offset + size - 1 }))) + } + + /** @param {number} offset @param {number} length */ + async readUint8Array(offset, length) { + if (!this.handle) throw new Error(`Library part not open: ${this.path}`) + const bytes = new Uint8Array(length) + let read = 0 + while (read < length) { + const { bytesRead } = await this.handle.read(bytes, read, length - read, offset + read) + if (!bytesRead) throw new Error(`Short read from library part: ${this.path}`) + read += bytesRead + } + return bytes + } + + async close() { + await this.handle?.close() + this.handle = null + } +} + +export class Pack { + /** + * @param {IndexEntry[]} libraries + * @param {string} origin where the pack came from, for messages + */ + constructor(libraries, origin) { + this.libraries = libraries + this.origin = origin + /** @type {Map>} */ + this.opened = new Map() + } + + /** + * The library the pack serves for a machine name, and a major when given: the newest, as the + * player serves it for any minor of that major. + * @param {string} machineName + * @param {number} [major] + */ + newest(machineName, major) { + let best = null + for (const entry of this.libraries) { + if (entry.machineName !== machineName || (major !== undefined && entry.majorVersion !== major)) continue + if (!best || entry.majorVersion > best.majorVersion || (entry.majorVersion === best.majorVersion && (entry.minorVersion > best.minorVersion || (entry.minorVersion === best.minorVersion && entry.patchVersion > best.patchVersion)))) best = entry + } + return best + } + + /** + * A library's part, opened once: checked against the index, then its `library.json`, + * `semantics.json` and the names of its translations read. + * @param {IndexEntry} entry + * @returns {Promise} + */ + open(entry) { + let opened = this.opened.get(entry.folder) + if (!opened) { + opened = this.#open(entry) + this.opened.set(entry.folder, opened) + } + return opened + } + + /** @param {IndexEntry} entry */ + async #open(entry) { + const path = fileURLToPath(entry.url) + const hash = createHash('sha256') + try { + for await (const chunk of createReadStream(path)) hash.update(chunk) + } catch (error) { + throw new Error(`Cannot read the library part ${entry.folder} from ${this.origin}`, { cause: error }) + } + if (hash.digest('hex') !== entry.sha256) throw new Error(`The library part ${entry.folder} does not match the pack's index (SHA-256): reinstall the pack.`) + const file = new PartFile(path) + const reader = new ZipReader(file, { checkSignature: true }) + const entries = (await reader.getEntries()).filter((item) => !item.directory && item.filename.startsWith(`${entry.folder}/`)) + /** @param {string} name */ + const json = async (name) => { + const found = entries.find((item) => item.filename === `${entry.folder}/${name}`) + return found ? JSON.parse(await /** @type {import('@zip.js/zip.js').FileEntry} */ (found).getData(new TextWriter())) : null + } + const library = await json('library.json') + if (!library) throw new Error(`The library part ${entry.folder} has no library.json`) + if (library.machineName !== entry.machineName || Number(library.majorVersion) !== entry.majorVersion || Number(library.minorVersion) !== entry.minorVersion || Number(library.patchVersion) !== entry.patchVersion) { + throw new Error(`The library part ${entry.folder} disagrees with the pack's index`) + } + const languages = `${entry.folder}/language/` + const translations = new Map( + entries + .filter((item) => item.filename.startsWith(languages) && item.filename.endsWith('.json')) + .map((item) => [item.filename.slice(languages.length, -'.json'.length), /** @type {import('@zip.js/zip.js').FileEntry} */ (item)]) + ) + return { folder: entry.folder, library, semantics: await json('semantics.json'), index: entry, translations, file, reader } + } + + /** + * A translation file of an opened library, parsed: its `semantics`. + * @param {PartLibrary} part + * @param {string} name + */ + async translation(part, name) { + const file = part.translations.get(name) + if (!file) return undefined + try { + return JSON.parse(await file.getData(new TextWriter())).semantics + } catch (error) { + throw new Error(`The translation ${file.filename} is not JSON`, { cause: error }) + } + } + + /** Every opened part closed. */ + async close() { + for (const opened of this.opened.values()) { + try { + const part = await opened + try { + await part.reader.close() + } finally { + await part.file.close() + } + } catch { + // A part that failed to open has nothing to close. + } + } + this.opened.clear() + } +} + +/** + * The pack a build reads: the one this package pins, or the `parts/` folder of another copy. + * @param {string} [folder] a folder holding `index.json` and the parts it names + */ +export async function openPack(folder) { + if (folder) { + const directory = resolve(folder) + let index + try { + index = JSON.parse(await readFile(join(directory, 'index.json'), 'utf8')) + } catch (error) { + throw new Error(`${directory} is not a library pack's parts folder: it has no readable index.json`, { cause: error }) + } + if (!Array.isArray(index?.libraries)) throw new Error(`${join(directory, 'index.json')} lists no libraries`) + const libraries = index.libraries.map((/** @type {IndexEntry} */ entry) => ({ ...entry, url: pathToFileURL(join(directory, `${entry.folder}.h5p`)).href })) + return new Pack(libraries, directory) + } + const { pack } = await import('@missing-elements/h5p-libraries') + return new Pack(/** @type {IndexEntry[]} */ (pack.libraries), '@missing-elements/h5p-libraries') +} + +/** The pinned pack's version, for messages and reports. */ +export async function packVersion() { + const url = import.meta.resolve('@missing-elements/h5p-libraries/package.json') + return JSON.parse(await readFile(fileURLToPath(url), 'utf8')).version +} diff --git a/packages/author/lib/quiz.mjs b/packages/author/lib/quiz.mjs new file mode 100644 index 00000000..0b0d003b --- /dev/null +++ b/packages/author/lib/quiz.mjs @@ -0,0 +1,183 @@ +import { escapeText } from './text.mjs' + +/** + * The quiz format the h5p-author skill published on 2026-10-23: a Multiple Choice question or a + * Question Set of them, in plain text. It stays a source the build takes, mapped here onto the + * general one, so nothing written in it breaks. + */ + +/** + * @typedef {{ text: string, correct: boolean, feedback?: string }} Answer + * @typedef {{ title?: string, prompt: string, multipleAnswers?: boolean, answers: Answer[] }} Question + * @typedef {{ + * kind: 'multiple-choice' | 'question-set', title: string, language: string, license: string, + * authors: { name: string, role: 'Author' }[], passPercentage?: number, + * passedFeedback?: string, failedFeedback?: string, questions: Question[] + * }} Quiz + */ + +/** @param {unknown} value @returns {value is Record} */ +const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) + +/** + * What is wrong with a quiz, all of it, each by its path, as a general source's problems are + * listed: a fix takes one round. + * @param {unknown} source + * @returns {{ path: string, message: string }[]} + * @internal + */ +export function quizProblems(source) { + /** @type {{ path: string, message: string }[]} */ + const problems = [] + const report = (/** @type {string} */ path, /** @type {string} */ message) => problems.push({ path, message }) + /** Whether a value is an object; a field it should not have is reported. @param {unknown} value @param {string} path @param {string[]} keys */ + const record = (value, path, keys) => { + if (!isObject(value)) { + report(path, 'expected an object') + return false + } + for (const key of Object.keys(value)) if (!keys.includes(key)) report(`${path}.${key}`, 'unsupported field') + return true + } + /** Whether a value is text with something in it. @param {unknown} value @param {string} path */ + const text = (value, path) => { + if (typeof value === 'string' && value.trim()) return true + report(path, 'expected non-empty text') + return false + } + + if (!record(source, 'quiz', ['kind', 'title', 'language', 'license', 'authors', 'passPercentage', 'passedFeedback', 'failedFeedback', 'questions'])) return problems + const quiz = /** @type {Record} */ (source) + if (!['multiple-choice', 'question-set'].includes(quiz.kind)) report('quiz.kind', 'use "multiple-choice" or "question-set"') + if (text(quiz.title, 'quiz.title') && quiz.title.length > 255) report('quiz.title', 'at most 255 characters') + if (text(quiz.language, 'quiz.language')) { + try { + Intl.getCanonicalLocales(quiz.language) + } catch { + report('quiz.language', 'expected a BCP 47 language tag, such as "en"') + } + } + if (text(quiz.license, 'quiz.license') && !['U', 'CC BY', 'CC BY-SA', 'CC BY-ND', 'CC BY-NC', 'CC BY-NC-SA', 'CC BY-NC-ND', 'CC0 1.0', 'PD', 'C'].includes(quiz.license)) { + report('quiz.license', 'use an H5P license code (for example "U", "CC BY", or "CC0 1.0")') + } + if (!Array.isArray(quiz.authors) || !quiz.authors.length) report('quiz.authors', 'name at least one author') + else quiz.authors.forEach((/** @type {unknown} */ author, /** @type {number} */ i) => { + if (!record(author, `quiz.authors[${i}]`, ['name', 'role'])) return + const { name, role } = /** @type {Record} */ (author) + text(name, `quiz.authors[${i}].name`) + if (role !== 'Author') report(`quiz.authors[${i}].role`, 'use "Author"') + }) + if (quiz.passPercentage !== undefined && (!Number.isInteger(quiz.passPercentage) || quiz.passPercentage < 0 || quiz.passPercentage > 100)) { + report('quiz.passPercentage', 'expected an integer from 0 to 100') + } + if (quiz.passedFeedback !== undefined || quiz.failedFeedback !== undefined) { + // One without the other leaves some learners with no word on the result. + for (const key of ['passedFeedback', 'failedFeedback']) { + if (quiz[key] === undefined) report(`quiz.${key}`, 'set passedFeedback and failedFeedback together') + else text(quiz[key], `quiz.${key}`) + } + if (quiz.passPercentage === undefined) report('quiz.passPercentage', 'set it with passedFeedback and failedFeedback; the library defaults differ by kind') + } + if (!Array.isArray(quiz.questions) || !quiz.questions.length) { + report('quiz.questions', 'at least one question is required') + return problems + } + if (quiz.kind === 'multiple-choice' && quiz.questions.length !== 1) report('quiz.questions', 'multiple-choice requires exactly one question') + quiz.questions.forEach((/** @type {unknown} */ written, /** @type {number} */ i) => { + const path = `quiz.questions[${i}]` + if (!record(written, path, ['title', 'prompt', 'multipleAnswers', 'answers'])) return + const question = /** @type {Record} */ (written) + text(question.prompt, `${path}.prompt`) + if (question.title !== undefined) text(question.title, `${path}.title`) + const multiple = question.multipleAnswers + if (multiple !== undefined && typeof multiple !== 'boolean') report(`${path}.multipleAnswers`, 'expected a boolean') + if (!Array.isArray(question.answers) || question.answers.length < 2) { + report(`${path}.answers`, 'at least two answers are required') + return + } + let marked = true + question.answers.forEach((/** @type {unknown} */ answer, /** @type {number} */ j) => { + const answerPath = `${path}.answers[${j}]` + if (!record(answer, answerPath, ['text', 'correct', 'feedback'])) { + marked = false + return + } + const { text: words, correct, feedback } = /** @type {Record} */ (answer) + text(words, `${answerPath}.text`) + if (typeof correct !== 'boolean') { + report(`${answerPath}.correct`, 'expected a boolean') + marked = false + } + if (feedback !== undefined) text(feedback, `${answerPath}.feedback`) + }) + // Counted once every answer says whether it is correct, and the question how many may be. + if (!marked || (multiple !== undefined && typeof multiple !== 'boolean')) return + const correct = question.answers.filter((/** @type {{ correct: boolean }} */ answer) => answer.correct).length + if (multiple ? correct === 0 : correct !== 1) report(`${path}.answers`, `${multiple ? 'at least one' : 'exactly one'} answer must be correct`) + }) + return problems +} + +/** A plain text written as the paragraph the quiz format has always made of it. @param {string} value */ +function paragraph(value) { + return `

${escapeText(value).replaceAll('\n', '
')}

` +} + +/** + * The pass mark as two score ranges for the content's overall feedback. The libraries pick a + * range by the floored percentage and judge `success` by the exact one, which agree for a whole + * number, so the message a learner gets matches the result an LMS records. + * @param {Quiz} quiz + */ +function passFeedback(quiz) { + if (quiz.passedFeedback === undefined || quiz.failedFeedback === undefined || quiz.passPercentage === undefined) return undefined + const pass = quiz.passPercentage + return [ + ...(pass > 0 ? [{ from: 0, to: pass - 1, feedback: quiz.failedFeedback }] : []), + { from: pass, to: 100, feedback: quiz.passedFeedback } + ] +} + +/** + * A quiz as a general source: Multiple Choice's parameters for each question, inside a Question + * Set's for a set. A question with no title takes the set's own label and number, as the set's + * layout does (`H5P.QuestionSet` in types.mjs). + * @param {Quiz} quiz + * @internal + */ +export function quizSource(quiz) { + const overallFeedback = passFeedback(quiz) + const set = quiz.kind === 'question-set' + const questions = quiz.questions.map((question) => ({ + question: paragraph(question.prompt), + answers: question.answers.map((answer) => ({ + text: paragraph(answer.text), + correct: answer.correct, + tipsAndFeedback: answer.feedback ? { chosenFeedback: paragraph(answer.feedback) } : {} + })), + behaviour: { + type: question.multipleAnswers ? 'multi' : 'single', + ...(!set && quiz.passPercentage !== undefined ? { passPercentage: quiz.passPercentage } : {}) + }, + ...(!set && overallFeedback ? { overallFeedback } : {}) + })) + const params = set + ? { + questions: questions.map((params, i) => ({ + library: 'H5P.MultiChoice', + params, + ...(quiz.questions[i].title === undefined ? {} : { metadata: { title: quiz.questions[i].title } }) + })), + ...(quiz.passPercentage === undefined ? {} : { passPercentage: quiz.passPercentage }), + ...(overallFeedback ? { endGame: { overallFeedback } } : {}) + } + : questions[0] + return { + type: set ? 'H5P.QuestionSet' : 'H5P.MultiChoice', + title: quiz.title, + language: quiz.language, + license: quiz.license, + authors: quiz.authors, + params + } +} diff --git a/packages/author/lib/schema.mjs b/packages/author/lib/schema.mjs new file mode 100644 index 00000000..2579c6a4 --- /dev/null +++ b/packages/author/lib/schema.mjs @@ -0,0 +1,225 @@ +import { allowedTags } from './text.mjs' + +/** + * A content type's fields as an author writes them, from its `semantics.json`: names, kinds, + * which are required, defaults, options, list sizes, the tags a markup field takes, the sub-content + * a library field takes, and the syntax the editor explains for a field. What an author never + * writes is left out: the interface texts, which come from the libraries' translations, and the + * hidden fields a content type's layout sets. A group of one field is shown as that field, since + * it is written as that field's value. + */ + +/** Groups that hold interface texts, under the names the pack's libraries give them. */ +const INTERFACE_GROUPS = new Set(['l10n', 'i10n', 'a11y', 'texts', 'UI', 'localize', 'labels', 'translations']) + +/** + * Whether a field is an interface text, or a group of nothing else: what a translation supplies. + * @param {any} field + * @returns {boolean} + */ +export function isInterfaceText(field) { + if (field.type === 'text') return Boolean(field.common) + if (field.type === 'group') { + const children = field.fields ?? [] + const texts = children.length > 0 && children.every((/** @type {any} */ child) => child.type === 'text' || (child.type === 'group' && isInterfaceText(child))) + return texts && (Boolean(field.common) || INTERFACE_GROUPS.has(field.name)) + } + return false +} + +/** @param {string} html */ +function plain(html) { + return html.replace(/<\/li>/g, '. ').replace(/<[^<>]*>/g, ' ').replace(/ /g, ' ').replace(/"/g, '"').replace(/'|'/g, "'").replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&').replace(/\s+/g, ' ').replace(/\.\s*\./g, '.').trim() +} + +/** @param {unknown} value */ +function short(value) { + const text = JSON.stringify(value) + return text.length > 48 ? `${text.slice(0, 45)}…` : text +} + +/** @param {any} field @returns {string[]} */ +function selectValues(field) { + /** @type {string[]} */ + const values = [] + for (const option of field.options ?? []) { + if (option?.type === 'optgroup') for (const sub of option.options ?? []) values.push(String(sub.value)) + else if (option?.value !== undefined && option?.value !== null) values.push(String(option.value)) + } + return values +} + +/** + * @typedef {{ has?: (machineName: string) => boolean, sets?: string[], descriptions?: boolean, all?: boolean }} SchemaOptions + * `has`, whether the pack has a library, to list only the sub-content it can build; `sets`, the + * hidden fields a layout sets, as `a.b[].c`; `descriptions`, each field's description; `all`, + * the interface texts too + */ + +/** + * What a field takes, in a few words. + * @param {any} field + * @param {SchemaOptions} options + * @param {boolean} [drawn] drawn by a widget, whose numbers take decimals + */ +function kind(field, options, drawn = false) { + switch (field.type) { + case 'text': { + const tags = allowedTags(field) + if (!tags) return field.widget === 'textarea' ? 'text, multi-line' : 'text' + const own = (Array.isArray(field.tags) ? field.tags : []).filter((/** @type {string} */ tag) => !['div', 'span', 'p', 'br'].includes(tag)) + return own.length ? `html: ${own.join(' ')}` : 'html' + } + case 'number': { + const range = field.min !== undefined || field.max !== undefined ? ` ${field.min ?? ''}–${field.max ?? ''}` : '' + return `${field.decimals || field.widget || drawn ? 'number' : 'whole number'}${range}` + } + case 'boolean': + return 'boolean' + case 'select': { + const values = selectValues(field) + return values.length ? `${field.multiple ? 'some of' : 'one of'} ${values.map((value) => JSON.stringify(value)).join(' | ')}` : field.multiple ? 'list of values' : 'value' + } + case 'library': { + const names = [...new Set((field.options ?? []).map((/** @type {any} */ option) => String(typeof option === 'string' ? option : option?.name).split(' ')[0]))] + return `sub-content: ${names.filter((name) => !options.has || options.has(name)).join(' | ')}` + } + case 'image': + return 'image file' + case 'file': + return 'file' + case 'video': + return 'video files' + case 'audio': + return 'audio files' + default: + return field.type + } +} + +/** A group of one field is written as that field; this is the field it is written as. @param {any} field */ +function written(field) { + let shown = field + while (shown.type === 'group' && (shown.fields ?? []).length === 1 && !shown.isSubContent) { + const child = shown.fields[0] + shown = { ...child, optional: shown.optional || child.optional, label: shown.label ?? child.label, default: shown.default ?? child.default, showWhen: shown.showWhen ?? child.showWhen } + } + return shown +} + +/** + * One field's lines and, for a group or a list of groups, its children's. + * @param {any} field + * @param {string} indent + * @param {string} path the field's path, `a.b[].c` + * @param {{ left: number }} counts + * @param {SchemaOptions} options + * @param {boolean} [drawn] whether a widget of the content type's draws it, not the editor's form + * @returns {string[]} + */ +function lines(field, indent, path, counts, options, drawn = false) { + if ((options.sets ?? []).includes(path)) return [] + const hidden = field.widget === 'none' || field.widget === 'hidden' + if (hidden && field.type === 'boolean') return [] + if (!options.all && isInterfaceText(field)) { + counts.left += countTexts(field) + return [] + } + const shown = written(field) + const media = ['image', 'file', 'video', 'audio'].includes(shown.type) + const required = !shown.optional && (media || (shown.default === undefined && !['boolean', 'group', 'list'].includes(shown.type))) + let head + /** @type {any} */ + let item = null + if (shown.type === 'list') { + const range = shown.max ? ` ${shown.min ?? 0}–${shown.max}` : shown.min ? ` ${shown.min}+` : '' + item = written(shown.field ?? {}) + head = item.type === 'group' ? `list${range} of` : `list${range} of ${kind(item, options, drawn)}` + } else if (shown.type === 'group') head = 'group' + else head = kind(shown, options, drawn) + // A list the editor's own form starts with an item is required when its item needs writing; one + // a widget of a content type's draws starts empty, and needs only its minimum. + const list = shown.type === 'list' && !shown.optional && (shown.min > 0 || (!drawn && needsWriting(item))) + if (required || list) head += ', required' + if (shown.default !== undefined && shown.default !== null && shown.type !== 'group') head += ` = ${short(shown.default)}` + if (hidden) head += ', hidden in the editor' + const rules = shown.showWhen?.rules ?? [] + if (rules.length) head += `; only when ${rules.map((/** @type {any} */ rule) => `${String(rule.field).replace(/^\.\.\//, '')} is ${[rule.equals].flat().map((value) => JSON.stringify(value)).join(' or ')}`).join(' or ')}` + const label = typeof shown.label === 'string' ? plain(shown.label) : '' + const own = typeof shown.description === 'string' ? shown.description : '' + const itemDescription = item && item.type !== 'group' && typeof item.description === 'string' ? item.description : '' + const description = options.descriptions !== false && ['text', 'list', 'library', 'number', 'select'].includes(shown.type) ? plain(own || itemDescription) : '' + const about = [label, description && description !== label ? description : ''].filter(Boolean).join(': ') + const out = [`${indent}- \`${field.name}\` ${head}${about ? ` — ${about.length > 200 ? `${about.slice(0, 197)}…` : about}` : ''}`] + // What the editor shows in its "important" box (h5peditor.js, `createImportantDescription`): the + // syntax a field's text is written in. + const important = shown.important ?? (item && item.type !== 'group' ? item.important : null) + if (options.descriptions !== false && important?.description) { + const example = important.example ? ` Example: ${plain(String(important.example))}` : '' + out.push(`${indent} ${plain(String(important.description))}${example}`) + } + const inner = drawn || Boolean(shown.type === 'group' && shown.widget && shown.widget !== 'showWhen' && shown.widget !== 'none') + if (shown.type === 'group') for (const child of shown.fields ?? []) out.push(...lines(child, `${indent} `, `${path}.${child.name}`, counts, options, inner)) + if (item?.type === 'group') for (const child of item.fields ?? []) out.push(...lines(child, `${indent} `, `${path}[].${child.name}`, counts, options, inner)) + return out +} + +/** + * Whether a list's item needs something written: a required field with no default in it. + * @param {any} item + * @returns {boolean} + */ +function needsWriting(item) { + if (!item) return false + const shown = written(item) + if (shown.type === 'group') return (shown.fields ?? []).some((/** @type {any} */ child) => !child.optional && needsWriting(child)) + if (shown.optional || shown.default !== undefined || shown.type === 'boolean') return false + return shown.type !== 'list' || shown.min > 0 +} + +/** @param {any} field @returns {number} */ +function countTexts(field) { + if (field.type === 'text') return 1 + return (field.fields ?? []).reduce((/** @type {number} */ sum, /** @type {any} */ child) => sum + countTexts(child), 0) +} + +/** + * A content type's fields, one line each, nested as they are written. + * @param {any[]} semantics + * @param {SchemaOptions} [options] + * @returns {{ lines: string[], interfaceTexts: number }} + */ +export function schemaLines(semantics, options = {}) { + const counts = { left: 0 } + const out = [] + for (const field of semantics) out.push(...lines(field, '', field.name, counts, options)) + return { lines: out, interfaceTexts: counts.left } +} + +/** The line that opens a type file's generated section, and the one that closes it. */ +export const GENERATED_START = '' +export const GENERATED_END = '' + +/** + * The generated section of a type file: the fields, under a heading, between markers that a + * refresh rewrites. + * @param {any} library its `library.json` + * @param {any[]} semantics + * @param {SchemaOptions} [options] + */ +export function schemaMarkdown(library, semantics, options = {}) { + const { lines: fields, interfaceTexts } = schemaLines(semantics, options) + return [ + GENERATED_START, + '', + `## Fields of ${library.machineName} ${library.majorVersion}.${library.minorVersion}`, + '', + ...fields, + '', + interfaceTexts + ? `${interfaceTexts} interface texts are left out: they come from the libraries' translations. \`h5p-author schema ${library.machineName} --all\` lists them, for a source to set one.` + : 'It has no interface texts of its own.', + '', + GENERATED_END + ].join('\n') +} diff --git a/packages/author/lib/text.mjs b/packages/author/lib/text.mjs new file mode 100644 index 00000000..7ac49261 --- /dev/null +++ b/packages/author/lib/text.mjs @@ -0,0 +1,166 @@ +/** + * Authored text as H5P stores it. A field without `tags` is plain text, which the platforms keep + * escaped (PHP's `htmlspecialchars`, existing entities left alone). A field with `tags` holds + * markup, as H5P's editor writes it into that field: the tags the field names, and the four the + * content check always keeps, `div`, `span`, `p` and `br`. Anything else is refused by name, so a + * source never reaches a learner in a form the platforms would have changed. + */ + +/** An `&` that does not begin an entity. */ +const BARE_AMPERSAND = /&(?!(?:[a-zA-Z][a-zA-Z0-9]*|#[0-9]+|#[xX][0-9a-fA-F]+);)/g + +/** + * Plain text as the platforms store a text field: `&`, `<`, `>`, `"` and `'` escaped, an entity + * already there kept, as `htmlspecialchars` with `ENT_QUOTES` and no double encoding keeps it. + * @param {string} value + */ +export function escapeText(value) { + return value.replace(BARE_AMPERSAND, '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''') +} + +/** + * The tags a markup field keeps, as the content check derives them from its semantics: the four + * it always keeps, the field's own, and those one of them implies. `null` for a plain text field. + * @param {any} field + * @returns {Set | null} + */ +export function allowedTags(field) { + if (field.tags === undefined || field.tags === null) return null + const tags = new Set(['div', 'span', 'p', 'br', ...(Array.isArray(field.tags) ? field.tags.filter((/** @type {unknown} */ tag) => typeof tag === 'string') : [])]) + if (tags.has('table')) for (const tag of ['tr', 'td', 'th', 'colgroup', 'col', 'thead', 'tbody', 'tfoot', 'figure', 'figcaption']) tags.add(tag) + if (tags.has('b')) tags.add('strong') + if (tags.has('i')) tags.add('em') + if (tags.has('ul') || tags.has('ol')) tags.add('li') + if (tags.has('del') || tags.has('strike')) tags.add('s') + return tags +} + +/** + * The block a line of text becomes in a markup field, as H5P's editor writes it + * (h5peditor-html.js): `

` where the field asks for paragraphs or offers headings, `pre`, `p` or + * `div`, `

` otherwise. + * @param {any} field + */ +export function blockTag(field) { + const own = Array.isArray(field.tags) ? field.tags : [] + return field.enterMode === 'p' || own.some((/** @type {string} */ tag) => /^(h[1-6]|pre|p|div)$/.test(tag)) ? 'p' : 'div' +} + +/** The tags a style attribute may sit on, and what it may say there, as the content check keeps them. */ +const STYLEABLE = new Set(['span', 'p', 'div', 'h1', 'h2', 'h3', 'table', 'col', 'figure', 'td', 'th', 'li']) +const COLOR = '(#[a-f0-9]{3}[a-f0-9]{3}?|rgba?\\([0-9, ]+\\)|hsla?\\([0-9,.% ]+\\))' +const BORDER_STYLE = '(none|solid|dotted|dashed|double|groove|ridge|inset|outset)' + +/** @param {any} field */ +function stylePatterns(field) { + const patterns = ['^text-align: *(center|left|right);?$'] + const font = field.font && typeof field.font === 'object' ? field.font : {} + if (font.size) patterns.push('^font-size: *[0-9.]+(em|px|%) *;?$') + if (font.family) patterns.push("^font-family: *[-a-z0-9,'&; ]+;?$") + if (font.color) patterns.push(`^color: *${COLOR} *;?$`) + if (font.background) patterns.push(`^background-color: *${COLOR} *;?$`) + if (font.spacing) patterns.push('^letter-spacing: *[0-9.]+(em|px|%) *;?$') + if (font.height) patterns.push('^line-height: *[0-9.]+(em|px|%|) *;?$') + if (Array.isArray(field.tags) && field.tags.includes('table')) { + patterns.push( + `^border: *[0-9.]+(em|px|%|) *${BORDER_STYLE} *${COLOR} *;?$`, `^border-style: *${BORDER_STYLE} *;?$`, + '^border-width: *[0-9.]+(em|px|%|) *;?$', `^border-color: *${COLOR} *;?$`, '^vertical-align: *(middle|top|bottom);?$', + '^padding: *[0-9.]+(em|px|%|) *;?$', '^width: *[0-9.]+(em|px|%|) *;?$', '^height: *[0-9.]+(em|px|%|) *;?$', + '^float: *(right|left|none) *;?$', '^border-collapse: *collapse *;?$', `^background-color: *${COLOR} *;?$` + ) + } + return patterns.map((pattern) => new RegExp(pattern, 'i')) +} + +/** + * A tag, a comment, or a lone `<` or `>`: the pieces the content check reads markup in. A comment + * left open runs to the end, as a browser reads it, so its end is looked for once and not again + * from every `|$)|<[^>]*(>|$)|>)/g +const ATTRIBUTE = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g +const SAFE_URL = /^(?:https?:|mailto:|ftp:|[^:]*$)/i + +/** + * Whether a value is written as markup: it has a tag. Text without one is plain, and is wrapped + * as the editor wraps what an author types. + * @param {string} value + */ +export function hasMarkup(value) { + return /<[a-zA-Z!/]/.test(value) +} + +/** + * A markup field's value as it is stored. Plain text is escaped and wrapped in the field's block, + * a paragraph per blank line and a `
` per other line break. Markup is checked: a tag the field + * does not take, an event handler, a style the field does not allow, a script URL or a comment is + * reported; a lone `<` or `>` is escaped, as the content check would escape it. + * @param {string} value + * @param {any} field + * @param {(message: string) => void} report + */ +export function markupText(value, field, report) { + const tags = allowedTags(field) ?? new Set() + if (!hasMarkup(value)) { + const block = blockTag(field) + const paragraphs = value.trim().split(/\n[ \t]*\n+/).filter((paragraph) => paragraph.trim()) + if (!paragraphs.length) return '' + return paragraphs.map((paragraph) => `<${block}>${escapeText(paragraph.trim()).replace(/\r?\n/g, '
')}`).join('') + } + const styles = stylePatterns(field) + // Each thing said once, however often the value repeats it: an opening tag and its closing one. + const said = new Set() + const once = (/** @type {string} */ message) => { + if (said.has(message)) return + said.add(message) + report(message) + } + return value.replace(PIECE, (piece) => { + if (piece === '<') return '<' + if (piece === '>') return '>' + if (piece.startsWith('', field, (message) => problems.push(message)) + expect(problems).toEqual([ + 'has an event handler, onclick, on

, which H5P removes', + expect.stringContaining('has , which this field does not take'), + expect.stringContaining('has '), + expect.stringContaining('has
'), + 'has the style "position: fixed" on , which this field does not allow', + 'has href="javascript:alert(1)": only http, https, mailto and ftp addresses are kept', + 'has a comment, which H5P removes: take it out' + ]) + }) + + it('reads a self-closing tag without its slash, and a comment left open to the end, as a browser does', () => { + const problems: string[] = [] + const field = { tags: ['strong'], font: { color: true } } + expect(markupText('a
b', field, (message) => problems.push(message))).toBe('a
b') + expect(problems).toEqual([]) + markupText('

a

+ +## Fields of H5P.Accordion 1.0 + +- `panels` list 1–100 of, required — Panels + - `title` text, required — Title + - `content` sub-content: H5P.AdvancedText, required — Content type +- `hTag` one of "h2" | "h3" | "h4" = "h2" — H tags for labels (does not affect the size of the label): The h tag used on the labels. Normally H2 but if this belongs under an H2 heading use H3. Does not affect the size of the labels, only use… + +It has no interface texts of its own. + + diff --git a/skills/h5p-author/references/types/H5P.AdvancedText.md b/skills/h5p-author/references/types/H5P.AdvancedText.md new file mode 100644 index 00000000..2bfc1dd6 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.AdvancedText.md @@ -0,0 +1,28 @@ +# Text (H5P.AdvancedText) + +Formatted text, a part other content holds: in a page, a book, a slide, a scenario or an accordion. Not a content type on its own. + +- `text` takes the tags the Fields section lists: headings, lists, links, emphasis. Plain text is wrapped in paragraphs, a blank line between two. + +## Example + +```json +{ + "type": "H5P.Column", + "params": { + "content": [ + { "content": { "library": "H5P.AdvancedText", "params": { "text": "

Rivers

A river has:

  • a source
  • a course
  • a mouth
" } } } + ] + } +} +``` + + + +## Fields of H5P.AdvancedText 1.1 + +- `text` html: strong em del a ul ol h2 h3 hr pre code, required — Text + +It has no interface texts of its own. + + diff --git a/skills/h5p-author/references/types/H5P.Audio.md b/skills/h5p-author/references/types/H5P.Audio.md new file mode 100644 index 00000000..78be5865 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Audio.md @@ -0,0 +1,29 @@ +# Audio (H5P.Audio) + +An audio player. On its own it suits a listening task beside other content; in a page, a book or on a card it is a part. + +- `files` is the recording: a file beside the source (`.mp3`, `.m4a`, `.wav`, `.ogg`) or a web address of one. +- `playerMode` `"full"` shows the full controls, `"minimalistic"` a play button. + +## Example + +```json +{ + "type": "H5P.Audio", + "params": { "files": [{ "path": "river.mp3" }], "playerMode": "full" } +} +``` + + + +## Fields of H5P.Audio 1.5 + +- `files` audio files, required — Source files +- `playerMode` one of "minimalistic" | "full" | "transparent" = "minimalistic" — Player mode: Select the layout of the player. +- `fitToWrapper` boolean = false; only when playerMode is "minimalistic" or playerMode is "full" — Fit to wrapper +- `controls` boolean = true; only when playerMode is "full" — Enable controls +- `autoplay` boolean — Enable autoplay + +4 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.Audio --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Blanks.md b/skills/h5p-author/references/types/H5P.Blanks.md new file mode 100644 index 00000000..26896951 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Blanks.md @@ -0,0 +1,53 @@ +# Fill in the Blanks (H5P.Blanks) + +Text with gaps the learner types the missing words into. For recall of exact words: terms, names, spellings. + +- Each item of `questions` is one block of text with its gaps, marked as the Fields section below says: `*answer*`, alternatives with `/`, a tip after `:`. +- Answers are compared as typed. `behaviour.caseSensitive: false` for names that may be capitalised either way; `behaviour.acceptSpellingErrors: true` forgives a wrong letter. +- `text` is the instruction above the blocks. + +## Example + +```json +{ + "type": "H5P.Blanks", + "params": { + "text": "Fill in the names of the rivers.", + "questions": [ + "The *Danube/Donau:It flows through Vienna* reaches the Black Sea.", + "Paris lies on the *Seine*, London on the *Thames*." + ], + "behaviour": { "caseSensitive": false } + } +} +``` + + + +## Fields of H5P.Blanks 1.14 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `text` html: strong em u a ul ol h2 h3 hr pre code = "Fill in the missing words" — Task description: A guide telling the user how to answer this task. +- `questions` list 1–31 of html: strong em del u code, required — Text blocks + Blanks are added with an asterisk (*) in front and behind the correct word/phrase. Alternative answers are separated with a forward slash (/). You may add a textual tip, using a colon (:) in front of the tip. Example: H5P content may be edited using a *browser/web-browser:Something you use every day*. +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings. + - `enableRetry` boolean = true — Enable "Retry" + - `allowRetryIfCorrect` boolean = false; only when enableRetry is true — Allow "Retry" even if all answers were correct + - `enableSolutionsButton` boolean = true — Enable "Show solution" button + - `autoCheck` boolean = false — Automatically check answers after input + - `caseSensitive` boolean = true — Case sensitive + - `showSolutionsRequiresInput` boolean = true — Require all fields to be answered before the solution can be viewed + - `separateLines` boolean = false — Put input fields on separate lines + - `confirmCheckDialog` boolean = false — Show confirmation dialog on "Check" + - `confirmRetryDialog` boolean = false — Show confirmation dialog on "Retry" + - `acceptSpellingErrors` boolean = false — Accept minor spelling errors + +26 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.Blanks --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.BranchingScenario.md b/skills/h5p-author/references/types/H5P.BranchingScenario.md new file mode 100644 index 00000000..c6ab023c --- /dev/null +++ b/skills/h5p-author/references/types/H5P.BranchingScenario.md @@ -0,0 +1,75 @@ +# Branching Scenario (H5P.BranchingScenario) + +A story in which the learner's choices lead to different paths and endings: decisions, conversations, procedures. + +- `branchingScenario.content` is the list of nodes, numbered from 0 in order; the scenario starts at node 0. +- A node's `type` is sub-content: text, an image, a video, a presentation, or a choice (H5P.BranchingQuestion). Every node that is not a choice says where it goes in `nextContentId`: the number of the next node, or `-1` to end the scenario there. +- A choice: `{ "library": "H5P.BranchingQuestion", "params": { "branchingQuestion": { "question": "…", "alternatives": [{ "text": "…", "nextContentId": 3 }] } } }`, each alternative leading to a node or an end. +- An end shows `endScreens[0]`; give a node `feedback` (`title`, `subtitle`, `endScreenScore`) for an ending of its own. More end screens are numbered `-2`, `-3`… in order, and a `nextContentId` can name one. +- The build refuses a link to a node that does not exist and a loop with no way out, and notes a node nothing leads to. + +## Example + +```json +{ + "type": "H5P.BranchingScenario", + "params": { + "branchingScenario": { + "title": "Crossing the river", + "startScreen": { "startScreenTitle": "Crossing the river", "startScreenSubtitle": "Choose a way across." }, + "content": [ + { "type": { "library": "H5P.AdvancedText", "params": { "text": "You reach a river after heavy rain. The water is high and fast." } }, "nextContentId": 1 }, + { + "type": { + "library": "H5P.BranchingQuestion", + "params": { "branchingQuestion": { "question": "How do you cross?", "alternatives": [{ "text": "Wade across here", "nextContentId": 2 }, { "text": "Walk to the bridge", "nextContentId": 3 }] } } + } + }, + { "type": { "library": "H5P.AdvancedText", "params": { "text": "The current knocks you over. Never wade into fast water." } }, "nextContentId": -1, "feedback": { "title": "Swept away", "endScreenScore": 0 } }, + { "type": { "library": "H5P.AdvancedText", "params": { "text": "The bridge takes longer, and you cross safely." } }, "nextContentId": -1, "feedback": { "title": "Safely across", "endScreenScore": 1 } } + ], + "endScreens": [{ "endScreenTitle": "The end" }] + } + } +} +``` + + + +## Fields of H5P.BranchingScenario 1.11 + +- `branchingScenario` group — Branching Scenario Editor + - `title` text, required — Title + - `startScreen` group — Start screen + - `startScreenTitle` html: strong em del code a — Course Title + - `startScreenSubtitle` html: strong em del code a — Course Details + - `startScreenImage` image file — Course image + - `startScreenAltText` text — Image alternative text + - `endScreens` list of — List of end screens + - `endScreenTitle` html: strong em del code a — Title + - `endScreenSubtitle` html: strong em del code a — Text + - `endScreenImage` image file — Image + - `endScreenScore` number = 0 — Score: The score will be sent to any LMS, LRS or any other connected service that receives scores from H5P for users who reach the default end scenario. + - `content` list 1+ of, required — List of branching scenario content + - `type` sub-content: H5P.BranchingQuestion | H5P.CoursePresentation | H5P.AdvancedText | H5P.Image | H5P.ImageHotspots | H5P.InteractiveVideo | H5P.Video, required + - `showContentTitle` boolean — Show content title in view + - `proceedButtonText` text = "Proceed" — Text for the proceed button (max length: 50 characters) + - `forceContentFinished` one of "useBehavioural" | "enabled" | "disabled" = "useBehavioural" — Override require content finished: Override the individual settings for requiring the content to be finished before activating the "Proceed" button. Will not have any effect if the content doesn't … + - `nextContentId` number, required, hidden in the editor + - `feedback` group — Feedback + - `title` html: strong em del code a — Feedback title + - `subtitle` html: strong em del code a — Feedback text + - `image` image file — Feedback image + - `endScreenScore` number — Score for this scenario: The score will be sent to any LMS, LRS or any other connected service that receives scores from H5P for users who reach this scenario + - `contentBehaviour` one of "useBehavioural" | "enabled" | "disabled" = "useBehavioural" — Navigate back: This will allow user to go back and see the previous content/question in the scenario. + - `scoringOptionGroup` group — Scoring options + - `scoringOption` one of "static-end-score" | "dynamic-score" | "no-score" = "no-score" — Scoring options: Select type of scoring. + - `includeInteractionsScores` boolean = true; only when scoringOption is "dynamic-score" — Include scores from interactions within the Branching Scenario + - `behaviour` group — Behavioural settings + - `enableBackwardsNavigation` boolean = false — Navigate back + - `forceContentFinished` boolean = false — Required to watch + - `randomizeBranchingQuestions` boolean = false — Randomize Branching Questions + +7 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.BranchingScenario --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Column.md b/skills/h5p-author/references/types/H5P.Column.md new file mode 100644 index 00000000..6097d578 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Column.md @@ -0,0 +1,33 @@ +# Column (H5P.Column) + +A page of content one below another: text, pictures, video and questions, in the order written. Called "Page" in the editor. + +- Each item of `content` is `{ "content": { "library": "…", "params": { … } } }`, sub-content of any library the Fields section lists. Write each from its type file: H5P.AdvancedText, H5P.Image and H5P.Video have files of their own. +- `useSeparator` draws a line between items: `"auto"`, `"enabled"` or `"disabled"`. + +## Example + +```json +{ + "type": "H5P.Column", + "params": { + "content": [ + { "content": { "library": "H5P.AdvancedText", "params": { "text": "

The water cycle

Rain falls, rivers carry it to the sea, and the sun lifts it again.

" } } }, + { "content": { "library": "H5P.Image", "params": { "file": { "path": "cycle.png" }, "alt": "Rain, a river and the sea" } } }, + { "content": { "library": "H5P.TrueFalse", "metadata": { "title": "Rivers and the sea" }, "params": { "question": "Rivers carry water to the sea.", "correct": "true" } } } + ] + } +} +``` + + + +## Fields of H5P.Column 1.22 + +- `content` list 1+ of, required — List of Column Content + - `content` sub-content: H5P.Accordion | H5P.Agamotto | H5P.Audio | H5P.AudioRecorder | H5P.Blanks | H5P.Chart | H5P.Collage | H5P.CoursePresentation | H5P.Dialogcards | H5P.DocumentationTool | H5P.DragQuestion | H5P.DragText | H5P.Essay | H5P.GuessTheAnswer | H5P.Table | H5P.AdvancedText | H5P.IFrameEmbed | H5P.Image | H5P.ImageHotspots | H5P.ImageHotspotQuestion | H5P.ImageSlider | H5P.InteractiveVideo | H5P.Link | H5P.MarkTheWords | H5P.MemoryGame | H5P.MultiChoice | H5P.Questionnaire | H5P.QuestionSet | H5P.Row | H5P.SingleChoiceSet | H5P.Summary | H5P.Timeline | H5P.TrueFalse | H5P.Video | H5P.MultiMediaChoice, required — Content + - `useSeparator` one of "auto" | "disabled" | "enabled" = "auto" — Separate content with a horizontal ruler + +It has no interface texts of its own. + + diff --git a/skills/h5p-author/references/types/H5P.CoursePresentation.md b/skills/h5p-author/references/types/H5P.CoursePresentation.md new file mode 100644 index 00000000..5a9b158e --- /dev/null +++ b/skills/h5p-author/references/types/H5P.CoursePresentation.md @@ -0,0 +1,91 @@ +# Course Presentation (H5P.CoursePresentation) + +Slides with text, pictures, video and questions; a summary slide with the score follows when there are questions. + +- `presentation.slides` is the list of slides; each slide's `elements` are sub-content under `action`: `{ "action": { "library": "H5P.AdvancedText", "params": { … } } }`. +- Leave out `x`, `y`, `width` and `height` and the build stacks a slide's elements top to bottom: text as tall as its lines, pictures in shape, a question in what is left. It notes a slide that holds too much; split it, or show its question as a button (`"displayAsButton": true`). To place an element by hand, give all four, in percent of the slide's width and height from the top left. +- A slide's `keywords` (`[{ "main": "…" }]`) name it in the outline. +- The slide is 16:9; at most a short heading, a paragraph and a picture, or a question, fit one slide. + +## Example + +```json +{ + "type": "H5P.CoursePresentation", + "params": { + "presentation": { + "slides": [ + { + "elements": [ + { "action": { "library": "H5P.AdvancedText", "params": { "text": "

Rivers of Europe

The Volga is the longest, at about 3,530 km.

" } } }, + { "action": { "library": "H5P.Image", "params": { "file": { "path": "map.png" }, "alt": "A map of Europe's rivers" } } } + ], + "keywords": [{ "main": "Rivers of Europe" }] + }, + { + "elements": [ + { "action": { "library": "H5P.MultiChoice", "params": { "question": "Which river is the longest in Europe?", "answers": [{ "text": "Volga", "correct": true }, { "text": "Danube", "correct": false }] } } } + ], + "keywords": [{ "main": "Question" }] + } + ] + } + } +} +``` + + + +## Fields of H5P.CoursePresentation 1.27 + +- `presentation` group + - `slides` list of + - `elements` list of + - `action` sub-content: H5P.AdvancedText | H5P.Link | H5P.Image | H5P.Shape | H5P.Video | H5P.Audio | H5P.Blanks | H5P.SingleChoiceSet | H5P.MultiChoice | H5P.TrueFalse | H5P.DragQuestion | H5P.Summary | H5P.DragText | H5P.MarkTheWords | H5P.Dialogcards | H5P.ContinuousText | H5P.ExportableTextArea | H5P.Table | H5P.InteractiveVideo | H5P.TwitterUserFeed | H5P.AudioRecorder | H5P.MultiMediaChoice + - `solution` html: strong em del a ul ol h2 h3 hr pre code — Comments: The comments are shown when the user displays the suggested answers for all slides. + - `alwaysDisplayComments` boolean — Always display comments + - `backgroundOpacity` number 0–100 = 0 — Background Opacity + - `displayAsButton` boolean = false — Display as button + - `buttonLabel` text — Optional button label + - `buttonSize` one of "small" | "big" = "big" — Button size + - `title` text — Title + - `goToSlideType` one of "specified" | "next" | "previous" = "specified" — Go to + - `goToSlide` number 1– — Specific slide number: Only applicable when 'Specific slide number' is selected + - `invisible` boolean = false — Invisible + - `keywords` list of + - `main` text + - `subs` list of text + - `slideBackgroundSelector` group + - `imageSlideBackground` image file — Image + - `fillSlideBackground` text — Pick a color + - `keywordListEnabled` boolean = true — Keyword list + - `keywordListAlwaysShow` boolean = false — Always show + - `keywordListAutoHide` boolean = false — Auto hide + - `keywordListOpacity` number 0–100 = 100 — Opacity + - `globalBackgroundSelector` group + - `imageGlobalBackground` image file — Image + - `fillGlobalBackground` text — Pick a color +- `override` group — Behaviour settings. + - `activeSurface` boolean = false — Activate Active Surface Mode + - `hideSummarySlide` boolean = false — Hide Summary Slide + - `showSolutionButton` one of "on" | "off" — Override "Show Solution" button: This option determines if the "Show Solution" button will be configured for each question individually (default) shown for all questions (Enabled) or disabled for a… + - `retryButton` one of "on" | "off" — Override "Retry" button: This option determines if the "Retry" button will be configured for each question individually (default) shown for all questions (Enabled) or disabled for all questions (Di… + - `summarySlideSolutionButton` boolean = true; only when hideSummarySlide is false — Show "Show solution" button in the summary slide + - `summarySlideRetryButton` boolean = true; only when hideSummarySlide is false — Show "Retry" button in the summary slide + - `enablePrintButton` boolean = false — Enable print button + - `social` group; only when hideSummarySlide is false — Social Settings + - `showFacebookShare` boolean = false — Display Facebook share icon + - `facebookShare` group; only when showFacebookShare is true — Facebook share settings + - `url` text = "@currentpageurl" — Share to Facebook link + - `quote` text = "I scored @score out of @maxScore on a task a… — Share to Facebook quote + - `showTwitterShare` boolean = false — Display Twitter share icon + - `twitterShare` group; only when showTwitterShare is true — Twitter share settings + - `statement` text = "I scored @score out of @maxScore on a task a… — Share to Twitter statement + - `url` text = "@currentpageurl" — Share to Twitter link + - `hashtags` text = "h5p, course" — Share to Twitter hashtags + - `showGoogleShare` boolean = false — Display Google+ share icon + - `googleShareUrl` text = "@currentpageurl"; only when showGoogleShare is true — Share to Google link + +53 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.CoursePresentation --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Dialogcards.md b/skills/h5p-author/references/types/H5P.Dialogcards.md new file mode 100644 index 00000000..5792cf29 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Dialogcards.md @@ -0,0 +1,49 @@ +# Dialog Cards (H5P.Dialogcards) + +Flash cards: a prompt on the front, the answer on the back, turned by the learner. Not scored. + +- Each item of `dialogs` is a card: `text` on the front, `answer` on the back, optionally an `image` with its `imageAltText`, an `audio` track and `tips`. +- `mode: "repetition"` brings back the cards a learner got wrong, until they know them all. + +## Example + +```json +{ + "type": "H5P.Dialogcards", + "params": { + "title": "Rivers in German", + "dialogs": [ + { "text": "the river", "answer": "der Fluss", "image": { "path": "river.png" }, "imageAltText": "A river between hills" }, + { "text": "the bridge", "answer": "die Brücke", "tips": { "front": "It crosses the river." } } + ] + } +} +``` + + + +## Fields of H5P.Dialogcards 1.9 + +- `title` html: strong em code — Heading +- `mode` one of "normal" | "repetition" = "normal" — Mode: Mode of presenting the dialog cards +- `description` html: strong em code — Task description +- `dialogs` list 1+ of, required — Dialogs + - `text` html: strong em code = "

" — Text: Hint for the first part of the dialogue + - `answer` html: strong em code = "

" — Answer: Hint for the second part of the dialogue + - `image` image file — Image + - `imageAltText` text — Alternative text for the image + - `audio` audio files — Audio files + - `tips` group — Tips + - `front` text — Tip for text: Tip for the first part of the dialogue + - `back` text — Tip for answer: Tip for the second part of the dialogue +- `behaviour` group — Behavioural settings + - `enableRetry` boolean = true — Enable "Retry" button + - `disableBackwardsNavigation` boolean = false; only when mode is "normal" — Disable backwards navigation + - `scaleTextNotCard` boolean = false — Scale the text to fit inside the card + - `randomCards` boolean = false; only when mode is "normal" — Randomize cards + - `maxProficiency` number 3–7 = 5; only when mode is "repetition" — Maximum proficiency level + - `quickProgression` boolean = false; only when mode is "repetition" — Allow quick progression + +28 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.Dialogcards --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Dictation.md b/skills/h5p-author/references/types/H5P.Dictation.md new file mode 100644 index 00000000..36ed0a66 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Dictation.md @@ -0,0 +1,64 @@ +# Dictation (H5P.Dictation) + +The learner hears sentences and types them; the content compares what was typed word by word. + +- Each item of `sentences` is a recording, `sample`, and the `text` it says. A slower recording can go in `sampleAlternative`. +- Alternative spellings of a word: `colour|color`. +- `behaviour.tries` limits how often a recording plays. + +## Example + +```json +{ + "type": "H5P.Dictation", + "params": { + "taskDescription": "Listen, then write what you hear.", + "sentences": [ + { "sample": [{ "path": "sentence1.mp3" }], "text": "The river flows to the sea." }, + { "sample": [{ "path": "sentence2.mp3" }], "text": "The bridge is old." } + ] + } +} +``` + + + +## Fields of H5P.Dictation 1.3 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `taskDescription` html: strong em u a ul ol h2 h3 hr pre code, required — Task description: Describe your task here. +- `sentences` list 1+ of, required — Sentences + - `description` text — Description: You can optionally put a simple description above the text input field, useful e.g. for dialogues. + - `sample` audio files, required — Sound sample + - `sampleAlternative` audio files — Sound sample slow + - `text` text, required — Text: Text that should be written. You can add alternate spellings to a word by adding a vertical line (|) behind followed by an alternative. +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings + - `tries` whole number 1– — Maximum tries: Will limit the number of times the samples for each sentence can be listened to. + - `triesAlternative` whole number 1– — Maximum tries for slow speed: Will limit the number of times the slow samples for each sentence can be listened to. + - `disablePause` boolean = false — Disable pause option + - `playButtonDelay` whole number 0–3 — Play button delay: Optionally set a time period of up to three seconds that playing a button should be delayed. This is useful if you want to allow students to enter the text field before they star… + - `shuffleSentences` one of "never" | "once" | "onRetry" = "never" — Shuffle sentences: Define when the sentences should be shuffled. + - `scoring` group — Scoring + - `ignorePunctuation` boolean = true — Ignore Punctuation marks + - `zeroMistakeMode` boolean = false — Zero mistakes mode + - `typoFactor` one of "100" | "50" | "0" = "100" — Value of typos: Determine to which extent typing errors (word with 3-9 characters: up to 1 mistake, word with more than 9 characters: up to 2 mistakes) count as a real mistake. + - `textual` group — Text + - `wordSeparator` text = " " — Word separator: Define the separator of words different than space character to support alternate solutions with different number of words. + - `overrideRTL` one of "auto" | "on" | "off" = "auto" — Writing direction: Set whether the sentences' language is right-to-left or left-to-right. + - `autosplit` boolean = true — Splitting of characters + - `feedbackPresentation` group — Presentation of feedback + - `customTypoDisplay` boolean = false — Custom typo display + - `alternateSolution` one of "first" | "all" = "first" — Presentation of alternate solutions: Define which alternatives should be presented for wrong or missing words in the solution. + - `enableRetry` boolean = true — Enable "Retry" + - `enableSolutionsButton` boolean = true — Enable "Show solution" button + - `enableSolutionOnCheck` boolean = false; only when enableSolutionsButton is true — Show solution on check + +40 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.Dictation --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.DragText.md b/skills/h5p-author/references/types/H5P.DragText.md new file mode 100644 index 00000000..4116fc33 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.DragText.md @@ -0,0 +1,44 @@ +# Drag the Words (H5P.DragText) + +Text with gaps the learner fills by dragging words from a list. Easier than typing them: recognition, not recall. + +- `textField` is plain text with the words to drag marked `*word*`; a tip after `:`, feedback after `\+` (right) and `\-` (wrong), as the Fields section shows. +- Each gap has one right word. Line breaks in `textField` are kept. +- `distractors` adds wrong words to the list, in the same `*word*` form. + +## Example + +```json +{ + "type": "H5P.DragText", + "params": { + "taskDescription": "Drag each river to the city it flows through.", + "textField": "Vienna lies on the *Danube*.\nLondon lies on the *Thames*.\nParis lies on the *Seine*.", + "distractors": "*Rhine* *Volga*" + } +} +``` + + + +## Fields of H5P.DragText 1.10 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `taskDescription` html: strong em u a ul ol h2 h3 hr pre code = "Drag the words into the correct boxes" — Task description: Describe how the user should solve the task. +- `textField` text, multi-line, required — Text + Droppable words are added with an asterisk (*) in front and behind the correct word/phrase. You may add a textual tip, using a colon (:) in front of the tip. For every empty spot there is only one correct word. You may add feedback to be displayed when a task is completed. Use '\+' for correct and '\-' for incorrect feedback. Example: H5P content may be edited using a *browser:What type of program is Chrome?*. H5P content is *interactive\+Correct! \-Incorrect, try again!* +- `distractors` text — Distractors: Enter extra solutions that are wrong as distractors. Use the same asterisk (*) scheme as for the text. +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings. + - `enableRetry` boolean = true — Enable "Retry" + - `enableSolutionsButton` boolean = true — Enable "Show Solution" button + - `instantFeedback` boolean = false — Instant feedback + +21 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.DragText --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Essay.md b/skills/h5p-author/references/types/H5P.Essay.md new file mode 100644 index 00000000..f2b5747d --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Essay.md @@ -0,0 +1,69 @@ +# Essay (H5P.Essay) + +The learner writes a text, scored by the keywords it contains, with feedback per keyword and a sample answer to compare. + +- Each item of `keywords` is a word or phrase to look for, with its `alternatives`, and `options` for its points and feedback. `*` matches any characters; `/…/` is a regular expression. +- A sample solution: `solution.sample`, shown after the learner submits. +- `behaviour.minimumLength` and `behaviour.maximumLength` bound the answer in characters. +- Keyword scoring cannot judge an argument: say so to the user, and keep the essay's weight low where it counts. + +## Example + +```json +{ + "type": "H5P.Essay", + "params": { + "taskDescription": "In two or three sentences, explain how a river reaches the sea.", + "keywords": [ + { "keyword": "downhill", "alternatives": ["down hill", "gravity"], "options": { "points": 1, "feedbackMissed": "Say what makes the water move." } }, + { "keyword": "sea", "options": { "points": 1, "feedbackMissed": "Say where the river ends." } } + ], + "solution": { "sample": "Water flows downhill under gravity, gathering into streams and then a river, which ends in the sea." } + } +} +``` + + + +## Fields of H5P.Essay 1.5 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `taskDescription` html: strong em u a ul ol h2 h3 hr pre code, required — Task description: Describe your task here. The task description will appear above text input area. +- `placeholderText` text — Help text: This text should help the user to get started. +- `solution` group — Sample solution + - `introduction` html: strong em u a ul ol hr code — Introduction: You can optionally leave the students some explanations about your example. The explanation will only show up if you add an example, too. + - `sample` html: strong a — Sample solution text: The student will see a "Show solution" button after submitting if you provide some text here. +- `keywords` list 1+ of, required — Keywords + - `keyword` text, required — Keyword: Keyword or phrase to look for. Use an asterisk '*' as a wildcard for one or more characters. Use a slash '/' at the beginning and the end to use a regular expression. + - `alternatives` list of text — Variations: Add optional variations for this keyword. Example: For a 'city' add alternatives 'town', 'municipality' etc. Points will be awarded if the user includes any of the specified alternatives. + - `options` group — Points, Options and Feedback + - `points` whole number 0– = 1 — Points: Points that the user will get if he/she includes this keyword or its alternatives in the answer. + - `occurrences` whole number 1– = 1 — Occurrences: Define how many occurrences of the keyword or its variations should be awarded with points. + - `caseSensitive` boolean = true — Case sensitive + - `forgiveMistakes` boolean — Forgive minor mistakes + - `feedbackIncluded` text — Feedback if keyword included: This feedback will be displayed if the user includes this keyword or its alternatives in the answer. + - `feedbackMissed` text — Feedback if keyword missing: This feedback will be displayed if the user doesn’t include this keyword or its alternatives in the answer. + - `feedbackIncludedWord` one of "keyword" | "alternative" | "answer" | "none" = "keyword" — Feedback word shown if keyword included: This option allows you to specify which word should be shown in front of your feedback if a keyword was found in the text. + - `feedbackMissedWord` one of "keyword" | "none" = "none" — Feedback word shown if keyword missing: This option allows you to specify which word should be shown in front of your feedback if a keyword was not found in the text. +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings + - `minimumLength` whole number 0– — Minimum number of characters: Specify the minimum number of characters that the user must enter. + - `maximumLength` whole number 0– — Maximum number of characters: Specify the maximum number of characters that the user can enter. + - `inputFieldSize` one of "1" | "3" | "10" = "10" — Input field size: The size of the input field in amount of lines it will cover + - `enableRetry` boolean = true — Enable "Retry" + - `ignoreScoring` boolean = false — Ignore scoring + - `pointsHost` number 0– = 1; only when ignoreScoring is true — Points in host environment: Used to award points in host environment merely for answering (not shown to learner). + - `percentagePassing` number 0–100; only when ignoreScoring is false — Passing percentage: Percentage that's necessary for passing + - `percentageMastering` number 0–100; only when ignoreScoring is false — Mastering percentage: Percentage that's necessary for mastering. Setting the mastering percentage below 100 % will lower the maximum possible score accordingly. It's intended to give some leeway to… + - `overrideCaseSensitive` one of "on" | "off" — Override case sensitive: This option determines if the "Case sensitive" option will be activated for all keywords. + - `overrideForgiveMistakes` one of "on" | "off" — Override forgive mistakes: This option determines if the "Forgive mistakes" option will be activated for all keywords. + - `linebreakReplacement` one of " " | "\n" = " " — Replacement for line breaks: By default, line breaks will be replaced with a space character. If you want to check for line breaks, e.g. in regular expressions, you can set a different replacement … + +14 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.Essay --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.GameMap.md b/skills/h5p-author/references/types/H5P.GameMap.md new file mode 100644 index 00000000..20f7e3fe --- /dev/null +++ b/skills/h5p-author/references/types/H5P.GameMap.md @@ -0,0 +1,160 @@ +# Game Map (H5P.GameMap) + +A map with stages, each holding exercises; finishing a stage opens the stages joined to it. + +- `gamemapSteps.backgroundImageSettings.backgroundImage` is the map. +- Each item of `gamemapSteps.gamemap.elements` is a stage: a `label`, its exercises under `contentsList` (`[{ "contentType": { "library": "…", "params": { … } } }]`), its `neighbors` named by label, and `telemetry.x` and `telemetry.y`, its place in percent of the map from the top left. The build joins neighbours both ways, sets the ids the map keeps, and spreads out stages written without a place. +- At least one stage has `canBeStartStage: true`. +- `behaviour.lives` and `behaviour.timeLimitGlobal` make it a game; leave them out for a plain path. + +## Example + +```json +{ + "type": "H5P.GameMap", + "params": { + "gamemapSteps": { + "backgroundImageSettings": { "backgroundImage": { "path": "valley.png" } }, + "gamemap": { + "elements": [ + { + "label": "Source", + "canBeStartStage": true, + "telemetry": { "x": 15, "y": 20 }, + "neighbors": ["Mouth"], + "contentsList": [{ "contentType": { "library": "H5P.TrueFalse", "params": { "question": "A river can begin at a glacier.", "correct": "true" } } }] + }, + { + "label": "Mouth", + "telemetry": { "x": 75, "y": 70 }, + "contentsList": [{ "contentType": { "library": "H5P.MultiChoice", "params": { "question": "Where does a river end?", "answers": [{ "text": "In a sea or a lake", "correct": true }, { "text": "In the mountains", "correct": false }] } } }] + } + ] + } + } + } +} +``` + + + +## Fields of H5P.GameMap 1.5 + +- `showTitleScreen` boolean = false — Show title screen +- `titleScreen` group — Title screen + - `titleScreenIntroduction` html: sub sup strong em code u del a ul ol hr pre code = "

" — Introduction + - `titleScreenMedium` sub-content: H5P.Image | H5P.Video — Title screen media +- `headline` text — Headline: Optional headline for the titlebar. +- `gamemapSteps` group — Game map editor + - `backgroundImageSettings` group — Background + - `backgroundImage` image file — Background image + - `backgroundColor` text = "rgb(255, 255, 255)" — Background color: Choose a color to use as the background of the game map. + - `gamemap` group — Game map + - `elements` list of — Elements + - `label` text, required — Stage label: This label will be displayed on top of your exercise and will help you to connect different stages with one another. + - `canBeStartStage` boolean = false — User can start here + - `time` group — Time limit + - `timeLimit` number 1– — Time limit: Optional time limit in seconds. If a user exceeds this time, the exercise will close, be reset, and the user will loose a life if lives are limited. + - `timeoutWarning` number 1– — Timeout warning time: Optionally set when a timeout warning audio should be played (number of remaining seconds). An audio needs to be set in the audio settings. + - `accessRestrictions` group — Access restrictions + - `allOrAnyRestrictionSet` one of "all" | "any" = "all" — All or any restriction set: Choose if all or any of the following restrictions need to be met. + - `restrictionSetList` list of — Restriction sets + - `allOrAnyRestriction` one of "all" | "any" = "any" — All or any restriction: Choose if all or any of the following restrictions need to be met. + - `restrictionList` list of — Restrictions + - `restrictionType` one of "totalScore" | "stageScore" | "stageProgress" | "time" = "totalScore" — Restriction type + - `totalScoreGroup` group — Total score + - `totalScoreOperator` one of "lessThan" | "equalTo" | "notEqualTo" | "greaterThan" = "greaterThan" — Operator for total score + - `totalScoreValue` number — Value of total score to compare to + - `stageScoreGroup` group — Stage score + - `stageScoreId` value — Stage to get score from + - `stageScoreOperator` one of "lessThan" | "equalTo" | "notEqualTo" | "greaterThan" = "before" — Operator for stage score + - `stageScoreValue` number — Score score to compare to + - `stageProgressGroup` group — Stage progress + - `stageProgressId` value — Stage to get progress from + - `stageProgressOperator` one of "is" | "isNot" = "is" — Operator for stage progress + - `stageProgressValue` one of "unstarted" | "opened" | "completed" | "cleared" = "open" — Progress to compare to + - `timeGroup` group — Time + - `timeOperator` one of "before" | "is" | "is not" | "after" = "before" — Operator for time + - `timeValue` text — Time to compare to + - `contentsList` list 1+ of, required — Contents + - `contentType` sub-content: H5P.Accordion | H5P.Agamotto | H5P.Audio | H5P.AudioRecorder | H5P.CoursePresentation | H5P.Crossword | H5P.Dialogcards | H5P.DragQuestion | H5P.DragText | H5P.Essay | H5P.Blanks | H5P.ImageHotspotQuestion | H5P.Image | H5P.MultiMediaChoice | H5P.ImageHotspots | H5P.ImageSlider | H5P.InteractiveVideo | H5P.MarkTheWords | H5P.MemoryGame | H5P.MultiChoice | H5P.QuestionSet | H5P.SingleChoiceSet | H5P.AdvancedText | H5P.TrueFalse | H5P.Video, required — Stage content: Choose the type of content you would like to add. + - `specialStageType` one of "finish" | "extra-life" | "extra-time" | "link", required — Special stage type + - `specialStageExtraLives` number 1– = 1 — Number of extra lives: Set how many lives the user will get when entering this stage. + - `specialStageExtraTime` number 1– = 1 — Number of seconds of extra time: Set how many seconds the user will gain for the global time limit when entering this stage. + - `specialStageLinkURL` text, required — URL to link to: Set where the user should be sent to when opening this stage. + - `specialStageLinkTarget` one of "_blank" | "_parent" = "_blank" — Place to open link in + - `alwaysVisible` boolean = false — Always visible + - `overrideSymbol` boolean = false — Override lock symbol + - `neighbors` list of values, required — Connected stages + - `telemetry` group, hidden in the editor — Telemetry + - `x` text, required + - `y` text, required + - `height` text, required + - `width` text, required + - `paths` list of — Paths + - `visualsType` one of "global" | "custom" = "global" — Visual settings + - `customVisuals` group — Custom visual settings + - `colorPath` text = "rgba(0, 0, 0, 0.7)" — Color path + - `pathWidth` one of "0.1" | "0.2" | "0.3" = "0.2" — Path width + - `pathStyle` one of "solid" | "dotted" | "dashed" | "double" = "dotted" — Path style +- `endScreen` group — End screen + - `noSuccess` group — User not successful + - `endScreenTextNoSuccess` html: sub sup strong em code u del a ul ol hr pre code = "

" — Message (user not successful) + - `endScreenMediumNoSuccess` sub-content: H5P.Image | H5P.Video — End screen media (user not successful) + - `success` group — User successful + - `endScreenTextSuccess` html: sub sup strong em code u del a ul ol hr pre code = "

" — Message (user successful) + - `endScreenMediumSuccess` sub-content: H5P.Image | H5P.Video — End screen media (user successful) + - `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `visual` group — Visual settings + - `stages` group — Stages + - `colorStage` text = "rgba(250, 223, 10, 0.7)" — Color not visited stage + - `colorStageLocked` text = "rgba(153, 0, 0, 0.7)" — Color locked stage + - `colorStageCleared` text = "rgba(0, 130, 0, 0.7)" — Color cleared stage + - `showScoreStars` one of "never" | "onHover" | "always" = "never" — Show stars for scores: Choose if and when stars will be displayed on the map for the scores of the stages. Please note that stages without scored exercises will not get the stars. + - `paths` group — Paths + - `displayPaths` boolean = true — Display paths + - `style` group — Style + - `colorPath` text = "rgba(0, 0, 0, 0.7)" — Color path + - `colorPathCleared` text = "rgba(0, 130, 0, 0.7)" — Color path cleared + - `pathWidth` one of "0.1" | "0.2" | "0.3" = "0.2" — Path width + - `pathStyle` one of "solid" | "dotted" | "dashed" | "double" = "dotted" — Path style + - `misc` group — Miscellaneous + - `useAnimation` boolean = true — Animate map +- `audio` group — Audio settings + - `backgroundMusic` group — Background music + - `music` audio files — Background music + - `muteDuringExercise` boolean = true — Mute when taking exercises + - `ambient` group — Events + - `clickStageLocked` audio files — Click on locked stage + - `checkExerciseNotFullScore` audio files — Check exercise (not full score) + - `checkExerciseFullScore` audio files — Check exercise (full score) + - `unlockStage` audio files — Unlocking a stage + - `openExercise` audio files — Open exercise + - `closeExercise` audio files — Close exercise + - `showDialog` audio files — Show dialog + - `fullScore` audio files — Full score + - `lostLife` audio files — Lost a life + - `gainedLife` audio files — Gained life + - `gameOver` audio files — Game over + - `extraTime` audio files — Gained extra time + - `timeoutWarning` audio files — Timeout warning + - `endscreenNoSuccess` audio files — End screen (not full score) + - `endscreenSuccess` audio files — End screen (full score) +- `behaviour` group — Behavioural settings + - `lives` whole number 1– — Lives: Set the number of lives for a user or leave empty for unlimited lives. Users will lose a life when they do not get full score and they cannot continue once all lives are lost. + - `timeLimitGlobal` whole number 1– — Global time limit: Optional time limit in seconds for the whole game. If a user exceeds this time, the game will be over immediately. + - `timeoutWarningGlobal` whole number 1– — Timeout warning time: Optionally set when a timeout warning audio should be played (number of remaining seconds). An audio needs to be set in the audio settings. + - `finishScore` whole number 0– — Finish score: Optional score that can be lower than the summed maximum score of all exercises, so users can receive full score without completing all exercises. + - `enableRetry` boolean = true — Enable "Retry" button + - `enableSolutionsButton` boolean = true — Enable "Show solutions" button + - `map` group — Map + - `showLabels` boolean = true — Show stage labels + - `roaming` one of "free" | "complete" | "success" = "free" — Roaming: Choose whether users can roam all stages freely, need to finish a stage to get access to that stage's neighbors, or need to pass a stage to get access to that stage's neigbors. + - `fog` one of "all" | "1" | "0" = "all" — Visibility range: Select how far the user can see ahead + +75 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.GameMap --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Image.md b/skills/h5p-author/references/types/H5P.Image.md new file mode 100644 index 00000000..f9ef9120 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Image.md @@ -0,0 +1,32 @@ +# Image (H5P.Image) + +A picture, a part other content holds: in a page, a book, a slide, a hotspot or an answer. Not a content type on its own. + +- `file` is the picture, a file beside the source (`.png`, `.jpg`, `.gif`) or a web address of one; the build reads its size. +- `alt` is required: what the picture shows, for a learner who cannot see it. A picture that only decorates is `"decorative": true` instead. + +## Example + +```json +{ + "type": "H5P.Column", + "params": { + "content": [ + { "content": { "library": "H5P.Image", "params": { "file": { "path": "delta.png", "copyright": { "license": "CC BY", "author": "Ann Author" } }, "alt": "A river delta seen from above" } } } + ] + } +} +``` + + + +## Fields of H5P.Image 1.1 + +- `file` image file, required — Image +- `decorative` boolean = false — Decorative only +- `alt` text, required; only when decorative is false — Alternative text: Required. If the browser can't load the image this text will be displayed instead. Also used by "text-to-speech" readers. +- `title` text — Hover text: Optional. This text is displayed when the users hover their pointing device over the image. + +3 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.Image --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.ImageHotspotQuestion.md b/skills/h5p-author/references/types/H5P.ImageHotspotQuestion.md new file mode 100644 index 00000000..ba24422b --- /dev/null +++ b/skills/h5p-author/references/types/H5P.ImageHotspotQuestion.md @@ -0,0 +1,53 @@ +# Find the Hotspot (H5P.ImageHotspotQuestion) + +A picture in which the learner clicks the right area: a part of a diagram, a place on a map. + +- `imageHotspotQuestion.backgroundImageSettings` is the picture. +- Each item of `imageHotspotQuestion.hotspotSettings.hotspot` is an area: `computedSettings` holds `x`, `y`, `width` and `height` in percent of the picture from its top left, and `figure`, `"rectangle"` or `"circle"`; `userSettings.correct` says whether it is the right one, and `userSettings.feedbackText` what a click on it says. At least one is correct. +- `hotspotSettings.noneSelectedFeedback` is said for a click outside every area. + +## Example + +```json +{ + "type": "H5P.ImageHotspotQuestion", + "params": { + "imageHotspotQuestion": { + "backgroundImageSettings": { "path": "delta.png" }, + "hotspotSettings": { + "taskDescription": "Click the river's mouth.", + "hotspot": [ + { "computedSettings": { "x": 60, "y": 55, "width": 20, "height": 20, "figure": "circle" }, "userSettings": { "correct": true, "feedbackText": "Yes: here it meets the sea." } }, + { "computedSettings": { "x": 10, "y": 10, "width": 25, "height": 25, "figure": "rectangle" }, "userSettings": { "correct": false, "feedbackText": "That is upstream." } } + ], + "noneSelectedFeedback": "Look where the river widens into the sea." + } + } + } +} +``` + + + +## Fields of H5P.ImageHotspotQuestion 1.8 + +- `imageHotspotQuestion` group — Image Hotspot Question Editor + - `backgroundImageSettings` image file, required — Background image + - `hotspotSettings` group — Hotspots + - `taskDescription` text — Task description: Instructions to the user. + - `hotspot` list of — Hotspot + - `userSettings` group — userSettings + - `correct` boolean — Correct + - `feedbackText` text — Feedback + - `computedSettings` group — computedSettings + - `x` number + - `y` number + - `width` number + - `height` number + - `figure` text + - `noneSelectedFeedback` text — Feedback if the user selects an empty spot: + - `showFeedbackAsPopup` boolean = true — Show feedback as a popup + +4 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.ImageHotspotQuestion --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.ImageHotspots.md b/skills/h5p-author/references/types/H5P.ImageHotspots.md new file mode 100644 index 00000000..9ea76442 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.ImageHotspots.md @@ -0,0 +1,50 @@ +# Image Hotspots (H5P.ImageHotspots) + +A picture with spots that open text, a picture, audio or video when clicked: a labelled diagram, a map to explore. Not scored. + +- `image` is the picture; `backgroundImageAltText` describes it. +- Each item of `hotspots` sits at `position.x` and `position.y`, in percent of the picture's width and height from its top left. Look at the picture to place them; the preview shows where they landed. +- A hotspot's `content` is a list of sub-content: H5P.Text, H5P.Image, H5P.Audio or H5P.Video. `header` titles its popup. + +## Example + +```json +{ + "type": "H5P.ImageHotspots", + "params": { + "image": { "path": "delta.png" }, + "backgroundImageAltText": "A river delta seen from above", + "hotspots": [ + { "position": { "x": 30, "y": 40 }, "header": "Main channel", "content": [{ "library": "H5P.Text", "params": { "text": "Most of the water flows here." } }] }, + { "position": { "x": 70, "y": 65 }, "header": "Mouth", "content": [{ "library": "H5P.Text", "params": { "text": "Here the river meets the sea." } }] } + ] + } +} +``` + + + +## Fields of H5P.ImageHotspots 1.11 + +- `image` image file, required — Background image +- `backgroundImageAltText` text — Alternative text for background image: If the browser can't load the image this text will be displayed instead. Also used by assistive technologies. +- `globalIconType` one of "icon" | "image" | "numbers" = "icon" — Global hotspot Icon +- `globalIcon` one of "plus" | "minus" | "times" | "check" | "question" | "info" | "exclamation" = "plus"; only when globalIconType is "icon" — Predefined icon: Using a predefined icon for the hotspots. +- `globalIconImage` image file; only when globalIconType is "image" — Uploaded image +- `globalColor` text = "#981d99"; only when globalIconType is "icon" or "numbers" — Hotspot color: The color of the hotspots +- `hotspots` list 1+ of, required — Hotspots + - `position` group — Hotspot position + - `x` number, required + - `y` number, required + - `legacyPositioning` boolean + - `hotspotIconType` one of "default" | "icon" | "image" = "default" — Custom hotspot icon + - `hotspotIcon` one of "plus" | "minus" | "times" | "check" | "question" | "info" | "exclamation" = "plus"; only when hotspotIconType is "icon" — Predefined icon: Using a predefined icon for the hotspot. + - `hotspotIconImage` image file; only when hotspotIconType is "image" — Uploaded image + - `hotspotColor` text = "#981d99"; only when hotspotIconType is "icon" — Hotspot color: The color of the hotspot + - `alwaysFullscreen` boolean — Cover entire background image + - `header` text — Header: Optional header for the popup. This is used by assistive technologies. + - `content` list of sub-content: H5P.Text | H5P.Video | H5P.Image | H5P.Audio, required — Popup content + +3 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.ImageHotspots --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.ImagePair.md b/skills/h5p-author/references/types/H5P.ImagePair.md new file mode 100644 index 00000000..8397479c --- /dev/null +++ b/skills/h5p-author/references/types/H5P.ImagePair.md @@ -0,0 +1,37 @@ +# Image Pairing (H5P.ImagePair) + +Two columns of pictures; the learner drags each one on the left onto its match on the right. + +- Each item of `cards` is a pair: `image` with `imageAlt`, and `match` with `matchAlt`. +- `behaviour` is one setting, whether to offer Retry: `true` or `false`. + +## Example + +```json +{ + "type": "H5P.ImagePair", + "params": { + "taskDescription": "Match each river to its city.", + "cards": [ + { "image": { "path": "danube.png" }, "imageAlt": "The Danube", "match": { "path": "budapest.png" }, "matchAlt": "Budapest" }, + { "image": { "path": "thames.png" }, "imageAlt": "The Thames", "match": { "path": "london.png" }, "matchAlt": "London" } + ] + } +} +``` + + + +## Fields of H5P.ImagePair 1.4 + +- `taskDescription` text = "Drag images from the left to match them with… — Task Description: A guide telling the user how to solve this task. +- `cards` list 2–100 of, required — Cards + - `image` image file, required — Image + - `imageAlt` text, required — Alternative text for Image: Describe what can be seen in the photo. The text is read by text-to-speech tools needed by visually impaired users. + - `match` image file — Matching Image + - `matchAlt` text — Alternative text for Matching Image: Describe what can be seen in the photo. The text is read by text-to-speech tools needed by visually impaired users. +- `behaviour` boolean = true — Behavioural settings + +4 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.ImagePair --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.ImageSequencing.md b/skills/h5p-author/references/types/H5P.ImageSequencing.md new file mode 100644 index 00000000..3ae58cec --- /dev/null +++ b/skills/h5p-author/references/types/H5P.ImageSequencing.md @@ -0,0 +1,40 @@ +# Image Sequencing (H5P.ImageSequencing) + +Pictures shown shuffled, which the learner puts in order: stages of a process, ages of a thing. + +- Write `sequenceImages` in the right order, at least three, each with `image` and `imageDescription`; the content shuffles them. + +## Example + +```json +{ + "type": "H5P.ImageSequencing", + "params": { + "taskDescription": "Put the river's course in order, from source to sea.", + "sequenceImages": [ + { "image": { "path": "source.png" }, "imageDescription": "A spring in the mountains" }, + { "image": { "path": "valley.png" }, "imageDescription": "A river in a valley" }, + { "image": { "path": "delta.png" }, "imageDescription": "A delta at the sea" } + ] + } +} +``` + + + +## Fields of H5P.ImageSequencing 1.1 + +- `taskDescription` text = "Drag to arrange the images in the correct se… — Task Description: A guide telling the user how to solve this task. +- `altTaskDescription` text = "Make the following list be ordered correctly… — Alternate Task Description: A guide intended for visually impaired users on how to solve this task. +- `sequenceImages` list 3+ of, required — Images + - `image` image file, required — Image + - `imageDescription` text, required — Image Description: An image description for users who cannot recognize the image + - `audio` audio files — Audio files +- `behaviour` group — Behavioural settings + - `enableSolution` boolean = true — Add a show solution button for the game + - `enableRetry` boolean = true — Add button for retrying when the game is over + - `enableResume` boolean = true — Add button for resuming from the current state + +11 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.ImageSequencing --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.InteractiveBook.md b/skills/h5p-author/references/types/H5P.InteractiveBook.md new file mode 100644 index 00000000..795c68b4 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.InteractiveBook.md @@ -0,0 +1,50 @@ +# Interactive Book (H5P.InteractiveBook) + +A book of chapters with a table of contents, each chapter a page of text, media and questions, and a summary of the learner's progress at the end. + +- Each item of `chapters` is a page, sub-content of H5P.Column: `{ "library": "H5P.Column", "metadata": { "title": "…" }, "params": { "content": [ … ] } }`. Its `metadata.title` is the chapter's name in the table of contents, and is required. Write the page's `content` as H5P.Column's file says. +- A cover: `showCoverPage: true`, with `bookCover.coverDescription` and, optionally, `bookCover.coverMedium` (H5P.Image or H5P.Video). +- The summary page lists every question and its score. Played on a site that records results, the book reports its own result only with the site's reporting turned on. + +## Example + +```json +{ + "type": "H5P.InteractiveBook", + "params": { + "chapters": [ + { + "library": "H5P.Column", + "metadata": { "title": "Where rivers begin" }, + "params": { "content": [{ "content": { "library": "H5P.AdvancedText", "params": { "text": "A river begins at its source: a spring, a lake or a glacier." } } }] } + }, + { + "library": "H5P.Column", + "metadata": { "title": "Check yourself" }, + "params": { "content": [{ "content": { "library": "H5P.TrueFalse", "metadata": { "title": "Sources" }, "params": { "question": "Every river begins at a spring.", "correct": "false" } } }] } + } + ] + } +} +``` + + + +## Fields of H5P.InteractiveBook 1.15 + +- `showCoverPage` boolean = false — Enable book cover +- `bookCover` group; only when showCoverPage is true — Cover Page + - `coverDescription` html: sub sup strong em code u del a ul ol h1 h2 h3 h4 h5 h6 pre hr table = "

" — Cover description: This text will be the description of your book. + - `coverMedium` sub-content: H5P.Image | H5P.Video — Cover media: Optional media to display on the cover. +- `chapters` list 1–50 of sub-content: H5P.Column, required — Pages +- `behaviour` group — Behavioural settings + - `baseColor` text = "#1768c4" — Base color: Set the base color that will define the overall color scheme of the book. Please ensure a high enough contrast. + - `defaultTableOfContents` boolean = true — Display table of contents as default + - `progressIndicators` boolean = true — Display Progress Indicators + - `progressAuto` boolean = true; only when progressIndicators is true — Enable automatic progress + - `displaySummary` boolean = true — Display summary + - `enableRetry` boolean = true — Enable "Restart" button + +35 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.InteractiveBook --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.InteractiveVideo.md b/skills/h5p-author/references/types/H5P.InteractiveVideo.md new file mode 100644 index 00000000..a821a1c6 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.InteractiveVideo.md @@ -0,0 +1,111 @@ +# Interactive Video (H5P.InteractiveVideo) + +A video with questions, text and links appearing over it at set times, a bookmark menu, and a summary task at the end. + +- `interactiveVideo.video.files` is the video: a file beside the source (`.mp4` or `.webm`), a web address of one, or the address of a video on YouTube, Vimeo, Panopto or Echo360, which plays from there. +- Each item of `interactiveVideo.assets.interactions` shows its `action` (sub-content) from `duration.from` to `duration.to`, in seconds. `pause: true` stops the video for it; `displayType` `"button"` shows an icon to open it, `"poster"` shows it open over the video. The build places each interaction; give `x` and `y` (percent of the picture) to place one yourself. +- The build sizes a poster by what it holds: a question 17 by 16, room for four short answers and its buttons; a text as wide as keeps it short; a picture in its own shape. `width` and `height` size one yourself, in em: the video is 40 wide and 22.5 tall at 16:9. Check posters in the preview; on a phone they show as buttons. +- Bookmarks: `interactiveVideo.assets.bookmarks`, `[{ "time": 30, "label": "…" }]`. +- The summary task at the end is H5P.Summary at `interactiveVideo.summary.task`, shown at `interactiveVideo.summary.displayAt` seconds before the end; leave it out and there is none. +- Know the video's length, and keep every time within it. + +## Example + +```json +{ + "type": "H5P.InteractiveVideo", + "params": { + "interactiveVideo": { + "video": { "files": [{ "path": "clip.mp4" }], "startScreenOptions": { "title": "A river in spring" } }, + "assets": { + "interactions": [ + { "duration": { "from": 2, "to": 6 }, "label": "Where does it go?", "action": { "library": "H5P.Text", "params": { "text": "All of this water ends in the sea." } } }, + { + "duration": { "from": 7, "to": 9 }, + "pause": true, + "displayType": "poster", + "action": { "library": "H5P.TrueFalse", "params": { "question": "This river flows uphill.", "correct": "false" } } + } + ], + "bookmarks": [{ "time": 7, "label": "Question" }] + } + } + } +} +``` + + + +## Fields of H5P.InteractiveVideo 1.28 + +- `interactiveVideo` group — Interactive Video Editor + - `video` group — Upload/embed video + - `files` video files, required — Add a video + - `startScreenOptions` group — Start screen options (unsupported for YouTube videos) + - `title` text = "Interactive Video" — The title of this interactive video: Used in summaries, statistics etc. + - `hideStartTitle` boolean = false — Hide title on video start screen + - `shortStartDescription` text — Short description (Optional): Optional. Display a short description text on the video start screen. Does not work for YouTube videos. + - `poster` image file — Poster image + - `textTracks` group — Text tracks (unsupported for YouTube videos) + - `videoTrack` list of — Available text tracks + - `label` text = "Subtitles" — Track label: Used if you offer multiple tracks and the user has to choose a track. For instance 'Spanish subtitles' could be the label of a Spanish subtitle track. + - `kind` one of "subtitles" | "captions" | "descriptions" = "subtitles" — Type of text track + - `srcLang` text = "en" — Source language, must be defined for subtitles: Must be a valid BCP 47 language tag. If 'Subtitles' is the type of text track selected, the source language of the track must be defined. + - `track` file, required — Track source (WebVTT file) + - `defaultTrackLabel` text — Default text track: If left empty or not matching any of the text tracks the first text track will be used as the default. + - `assets` group — Add interactions + - `interactions` list of + - `duration` group — Display time + - `from` number, required + - `to` number, required + - `pause` boolean — Pause video + - `displayType` one of "button" | "poster" = "button" — Display as: Button is a collapsed interaction the user must press to open. Poster is an expanded interaction displayed directly on top of the video + - `buttonOnMobile` boolean = false — Turn into button on small screens + - `label` html — Label: Label displayed next to interaction icon. + - `action` sub-content: H5P.Nil | H5P.Text | H5P.Table | H5P.Link | H5P.Image | H5P.Summary | H5P.SingleChoiceSet | H5P.MultiChoice | H5P.TrueFalse | H5P.Blanks | H5P.DragQuestion | H5P.MarkTheWords | H5P.DragText | H5P.GoToQuestion | H5P.IVHotspot | H5P.Questionnaire | H5P.FreeTextQuestion | H5P.MultiMediaChoice, required + - `adaptivity` group — Adaptivity + - `correct` group — Action on all correct + - `seekTo` number, required — Seek to: Enter timecode in the format M:SS + - `allowOptOut` boolean — Allow the user to opt out and continue + - `message` html: strong em del a code, required — Message + - `seekLabel` text, required — Label for seek button + - `wrong` group — Action on wrong + - `seekTo` number, required — Seek to: Enter timecode in the format M:SS + - `allowOptOut` boolean — Allow the user to opt out and continue + - `message` html: strong em del a code, required — Message + - `seekLabel` text, required — Label for seek button + - `requireCompletion` boolean — Require full score for task before proceeding + - `visuals` group — Visuals + - `backgroundColor` text = "rgb(255, 255, 255)" — Background color + - `boxShadow` boolean = true — Box shadow + - `goto` group — Go to on click + - `type` one of "timecode" | "url" — Type + - `time` number — Go To: The target time the user will be taken to upon pressing the hotspot. Enter timecode in the format M:SS. + - `url` group — URL + - `protocol` one of "http://" | "https://" | "/" | "other" = "http://" — Protocol + - `url` text — URL + - `visualize` boolean — Visualize + - `bookmarks` list of + - `time` number, required + - `label` text, required + - `endscreens` list of + - `time` number, required + - `label` text, required + - `summary` group — Summary task + - `task` sub-content: H5P.Summary = {"library":"H5P.Summary 1.10","params":{}} + - `displayAt` number = 3 — Display at: Number of seconds before the video ends. +- `override` group — Behavioural settings + - `startVideoAt` number — Start video at: Enter timecode in the format M:SS + - `autoplay` boolean = false — Auto-play video + - `loop` boolean = false — Loop the video + - `hasNoAutoPause` boolean = false — Deactivate auto-pause + - `showSolutionButton` one of "on" | "off" — Override "Show Solution" button: This option determines if the "Show Solution" button will be shown for all questions, disabled for all or configured for each question individually. + - `retryButton` one of "on" | "off", required — Override "Retry" button: This option determines if the "Retry" button will be shown for all questions, disabled for all or configured for each question individually. + - `showBookmarksmenuOnLoad` boolean = false — Start with bookmarks menu open + - `showRewind10` boolean = false — Show button for rewinding 10 seconds + - `preventSkippingMode` one of "none" | "forward" | "both" = "none" — Disable navigation: These options will disable user video navigation as specified. + - `deactivateSound` boolean = false — Deactivate sound + +47 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.InteractiveVideo --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.MarkTheWords.md b/skills/h5p-author/references/types/H5P.MarkTheWords.md new file mode 100644 index 00000000..475c0a33 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.MarkTheWords.md @@ -0,0 +1,41 @@ +# Mark the Words (H5P.MarkTheWords) + +A text in which the learner clicks the words that fit a rule: every verb, every misspelt word. + +- Mark the right words in `textField` with asterisks: `*word*`. Single words only, not phrases. +- `taskDescription` says what to mark; it is required. + +## Example + +```json +{ + "type": "H5P.MarkTheWords", + "params": { + "taskDescription": "Click every name of a river.", + "textField": "The *Danube* rises in the Black Forest and the *Rhine* in the Alps; both cross Germany." + } +} +``` + + + +## Fields of H5P.MarkTheWords 1.11 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `taskDescription` html: strong em u a ul ol h2 h3 hr pre code, required — Task description: Describe how the user should solve the task. +- `textField` html: strong em code, required — Textfield + Correct words are marked with asterisks (*) before and after the word. Asterisks can be added within marked words by adding another asterisk, *correctword*** => correctword*. Only words may be marked as correct. Not phrases. Example: The correct words are marked like this: *correctword*, an asterisk is written like this: *correctword***. +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings. + - `enableRetry` boolean = true — Enable "Retry" + - `enableSolutionsButton` boolean = true — Enable "Show solution" button + - `showScorePoints` boolean = true — Show score points + +16 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.MarkTheWords --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.MemoryGame.md b/skills/h5p-author/references/types/H5P.MemoryGame.md new file mode 100644 index 00000000..df0c58eb --- /dev/null +++ b/skills/h5p-author/references/types/H5P.MemoryGame.md @@ -0,0 +1,45 @@ +# Memory Game (H5P.MemoryGame) + +Cards face down, turned two at a time, until every pair is found. + +- Each item of `cards` is a pair: `image` and `imageAlt`, and, for a pair of two different pictures, `match` and `matchAlt`. Without `match` the pair is two copies of `image`. +- `description` is shown when the pair is found: say what it shows. +- Square-ish pictures work best; at least two cards. + +## Example + +```json +{ + "type": "H5P.MemoryGame", + "params": { + "cards": [ + { "image": { "path": "danube.png" }, "imageAlt": "The Danube in Budapest", "description": "The Danube flows through four capitals." }, + { "image": { "path": "thames.png" }, "imageAlt": "The Thames in London", "description": "The Thames flows through London." } + ] + } +} +``` + + + +## Fields of H5P.MemoryGame 1.3 + +- `cards` list 2–100 of, required — Cards + - `image` image file, required — Image + - `imageAlt` text, required — Alternative text for Image: Describe what can be seen in the photo. The text is read by text-to-speech tools needed by visually impaired users. + - `audio` audio files — Audio Track + - `match` image file — Matching Image + - `matchAlt` text — Alternative text for Matching Image: Describe what can be seen in the photo. The text is read by text-to-speech tools needed by visually impaired users. + - `matchAudio` audio files — Matching Audio Track + - `description` text — Description: An optional short text that will pop up once the two matching cards are found. +- `behaviour` group — Behavioural settings + - `useGrid` boolean = true — Position the cards in a square + - `numCardsToUse` whole number 2– — Number of cards to use: Setting this to a number greater than 2 will make the game pick random cards from the list of cards. + - `allowRetry` boolean = true — Add button for retrying when the game is over +- `lookNFeel` group — Look and feel + - `themeColor` text = "#707070" — Theme Color: Choose a color to create a theme for your card game. + - `cardBack` image file — Card Back + +14 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.MemoryGame --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.MultiChoice.md b/skills/h5p-author/references/types/H5P.MultiChoice.md new file mode 100644 index 00000000..38cdf9a9 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.MultiChoice.md @@ -0,0 +1,61 @@ +# Multiple Choice (H5P.MultiChoice) + +One question, two or more answers, one or several of them correct, with feedback per answer. + +- Mark the right answers with `"correct": true`. `behaviour.type` is `"single"` (radio buttons, exactly one correct), `"multi"` (checkboxes) or `"auto"`, which picks by how many are correct. +- Feedback for an answer goes in its `tipsAndFeedback.chosenFeedback`, shown after Check when it was chosen. Write it for every answer, wrong ones especially: say why. +- A pass mark: `behaviour.passPercentage`, with `overallFeedback` ranges for each score band, `{ "from": 0, "to": 99, "feedback": "…" }`. +- Answers are shuffled unless `behaviour.randomAnswers` is false. + +## Example + +```json +{ + "type": "H5P.MultiChoice", + "params": { + "question": "Which river is the longest in Europe?", + "answers": [ + { "text": "Volga", "correct": true, "tipsAndFeedback": { "chosenFeedback": "Right: about 3,530 km." } }, + { "text": "Danube", "correct": false, "tipsAndFeedback": { "chosenFeedback": "The Danube is second, about 2,850 km." } }, + { "text": "Rhine", "correct": false, "tipsAndFeedback": { "chosenFeedback": "The Rhine is about 1,230 km." } } + ], + "behaviour": { "type": "single" } + } +} +``` + + + +## Fields of H5P.MultiChoice 1.16 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `question` html: strong em sub sup h2 h3 pre code, required — Question +- `answers` list 1+ of, required — Available options + - `text` html: strong em sub sup code, required — Text + - `correct` boolean — Correct + - `tipsAndFeedback` group — Tips and feedback + - `tip` html: strong em a code — Tip text: Hint for the user. This will appear before user checks his answer/answers. + - `chosenFeedback` html: strong em sub sup a code — Message displayed if answer is selected: Message will appear below the answer on "check" if this answer is selected. + - `notChosenFeedback` html: strong em sub sup a code — Message displayed if answer is not selected: Message will appear below the answer on "check" if this answer is not selected. +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings + - `enableRetry` boolean = true — Enable "Retry" button + - `enableSolutionsButton` boolean = true — Enable "Show Solution" button + - `type` one of "auto" | "multi" | "single" = "auto" — Question Type: Select the look and behaviour of the question. + - `singlePoint` boolean = false — Give one point for the whole task + - `randomAnswers` boolean = true — Randomize answers + - `showSolutionsRequiresInput` boolean = true — Require answer before the solution can be viewed + - `confirmCheckDialog` boolean = false — Show confirmation dialog on "Check" + - `confirmRetryDialog` boolean = false — Show confirmation dialog on "Retry" + - `autoCheck` boolean = false — Automatically check answers + - `passPercentage` whole number 0–100 = 100 — Pass percentage: This setting often won't have any effect. It is the percentage of the total score required for getting 1 point when one point for the entire task is enabled, and for getting result… + - `showScorePoints` boolean = true — Show score points + +25 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.MultiChoice --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.MultiMediaChoice.md b/skills/h5p-author/references/types/H5P.MultiMediaChoice.md new file mode 100644 index 00000000..dc5617d4 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.MultiMediaChoice.md @@ -0,0 +1,53 @@ +# Image Choice (H5P.MultiMediaChoice) + +A multiple-choice question whose answers are pictures. + +- Each item of `options` holds its picture as sub-content under `media`, `{ "library": "H5P.Image", "params": { "file": { "path": "…" }, "alt": "…" } }`, and `correct`. The alternative text is what a screen reader reads as the answer: write it as the answer. +- `behaviour.questionType` `"single"` or `"multi"`, as for Multiple Choice; `behaviour.aspectRatio` fits pictures of different shapes. + +## Example + +```json +{ + "type": "H5P.MultiMediaChoice", + "params": { + "question": "Which picture shows a river delta?", + "options": [ + { "media": { "library": "H5P.Image", "params": { "file": { "path": "delta.png" }, "alt": "A delta" } }, "correct": true }, + { "media": { "library": "H5P.Image", "params": { "file": { "path": "source.png" }, "alt": "A spring" } }, "correct": false } + ] + } +} +``` + + + +## Fields of H5P.MultiMediaChoice 0.3 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `question` html: strong em sub sup h2 h3 pre code, required — Question +- `options` list 2–20 of, required — Available options + - `media` sub-content: H5P.Image | H5P.Video | H5P.Audio, required — Media: Media to display as a choice. + - `poster` image file, required; only when media is "H5P.Audio 1.5" — Poster image + - `correct` boolean — Correct +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings + - `enableRetry` boolean = true — Enable "Retry" button + - `enableSolutionsButton` boolean = true — Enable "Show Solution" button + - `confirmCheckDialog` boolean = false — Show confirmation dialog on "Check" + - `confirmRetryDialog` boolean = false — Show confirmation dialog on "Retry" + - `singlePoint` boolean = false — Give one point for the whole question + - `showSolutionsRequiresInput` boolean = true — Require answer before the solution can be viewed + - `questionType` one of "auto" | "multi" | "single" = "auto" — Question Type: Select the look and behaviour of the question. + - `aspectRatio` one of "auto" | "16to9" | "4to3" | "3to2" | "1to1" = "auto" — Aspect ratio: Select the aspect ratio of the alternatives + - `maxAlternativesPerRow` one of "1" | "2" | "3" | "4" = "4" — Maximum alternatives per row: Set the maximum number of alternatives per row to ensure the questions look alright. + - `passPercentage` whole number 0–100 = 100 — Pass percentage: This setting often won't have any effect. It is the percentage of the total score required for getting 1 point when one point for the entire task is enabled, and for getting result… + +23 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.MultiMediaChoice --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.QuestionSet.md b/skills/h5p-author/references/types/H5P.QuestionSet.md new file mode 100644 index 00000000..e231b816 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.QuestionSet.md @@ -0,0 +1,98 @@ +# Question Set (H5P.QuestionSet) + +A quiz: questions one after another, then a result page with the score. + +- Each item of `questions` is sub-content: `{ "library": "H5P.MultiChoice", "params": { … }, "metadata": { "title": "…" } }`. Write each question's `params` from its own type file. The result page lists questions by `metadata.title`; without one a question is "Question 2" in the content's language. +- `passPercentage` is the pass mark; `endGame.overallFeedback` holds the score ranges' messages. Question Set 1.21 draws neither on its result page, an H5P bug (h5p/h5p-question-set#183): screen readers announce the message, and a learner sees only the score. Tell the user. +- An intro screen: `introPage.showIntroPage: true`, with `title` and `introduction`. +- `randomQuestions` shuffles them; `poolSize` draws that many from the list each time. +- Its navigation and result screen ("Previous", "Next", "Results", "Score") are English in all but one or two of its 48 translations; the build lists what stayed English. + +## Example + +```json +{ + "type": "H5P.QuestionSet", + "params": { + "passPercentage": 50, + "questions": [ + { + "library": "H5P.MultiChoice", + "metadata": { "title": "The longest river" }, + "params": { + "question": "Which river is the longest in Europe?", + "answers": [ + { "text": "Volga", "correct": true }, + { "text": "Danube", "correct": false } + ] + } + }, + { + "library": "H5P.TrueFalse", + "metadata": { "title": "The Rhine" }, + "params": { "question": "The Rhine flows into the North Sea.", "correct": "true" } + } + ], + "endGame": { + "overallFeedback": [ + { "from": 0, "to": 49, "feedback": "Not yet: read about the rivers again, then retry." }, + { "from": 50, "to": 100, "feedback": "Passed." } + ] + } + } +} +``` + + + +## Fields of H5P.QuestionSet 1.21 + +- `introPage` group — Quiz introduction + - `showIntroPage` boolean — Display introduction + - `title` html: sub sup strong em code — Title: This title will be displayed above the introduction text. + - `introduction` html: sub sup strong em code — Introduction text: This text will be displayed before the quiz starts. + - `startButtonText` text = "Start Quiz" — Start button text + - `backgroundImage` image file — Cover image + - `backgroundImageAltText` text — Alternative text: If the browser can't load the image this text will be displayed instead. Also used by "text-to-speech" readers. +- `progressType` one of "textual" | "dots" = "dots" — Progress indicator: Question set progress indicator style. Will be Textual if backwards navigation is disabled. +- `passPercentage` whole number 0–100 = 50 — Pass percentage: Percentage of Total score required for passing the quiz. +- `questions` list 1+ of sub-content: H5P.MultiChoice | H5P.DragQuestion | H5P.Blanks | H5P.MarkTheWords | H5P.DragText | H5P.TrueFalse | H5P.Essay | H5P.MultiMediaChoice, required — Questions: Library for this question. +- `disableBackwardsNavigation` boolean = false — Disable backwards navigation +- `randomQuestions` boolean = false — Randomize questions +- `poolSize` whole number 1– — Number of questions to be shown:: Create a randomized batch of questions from the total. +- `endGame` group — Quiz finished + - `showResultPage` boolean = true — Display results + - `showSolutionButton` boolean = true — Display solution button + - `showRetryButton` boolean = true — Display retry button + - `noResultMessage` text = "Finished" — No results message: Text displayed on end page when "Display results" is disabled + - `message` html: strong em code = "Results" — Results heading: This heading will be displayed at the end of the quiz when the user has answered all questions. + - `amountCorrect` text = "@finals of @totals correct" — Amount correct heading: Header to show the final score to the user on the end screen + - `scoreBarLabel` text = "You got @finals out of @totals points" — Score announcer: This label will be used for announcing the final score to the user on the end screen + - `scoreHeader` text = "Score" — Score heading: Header for the score part of the results table + - `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range + - `oldFeedback` group — Old Feedback + - `successGreeting` html: strong em code — Quiz passed greeting: This text will be displayed above the score if the user has successfully passed the quiz. + - `successComment` html: sub sup strong em a code — Passed comment: This comment will be displayed after the score if the user has successfully passed the quiz. + - `failGreeting` html: strong em code — Quiz failed title: This text will be displayed above the score if the user has failed the quiz. + - `failComment` html: sub sup strong em a code — Failed comment: This comment will be displayed after the score if the user has failed the quiz. + - `solutionButtonText` text = "Show solution" — Solution button label: Text for the solution button. + - `retryButtonText` text = "Retry" — Retry button label: Text for the retry button. + - `finishButtonText` text = "Finish" — Finish button text + - `submitButtonText` text = "Submit" — Submit button text + - `showAnimations` boolean — Display video before quiz results + - `skippable` boolean — Enable skip video button + - `skipButtonText` text = "Skip video" — Skip video button label + - `successVideo` video files — Passed video + - `failVideo` video files — Fail video +- `override` group — Behavioural settings + - `checkButton` boolean = true — Show "Check" buttons + - `showSolutionButton` one of "on" | "off"; only when checkButton is true — Override "Show Solution" button: This option determines if the "Show Solution" button will be shown for all questions, disabled for all or configured for each question individually. + - `retryButton` one of "on" | "off"; only when checkButton is true — Override "Retry" button: This option determines if the "Retry" button will be shown for all questions, disabled for all or configured for each question individually. + - `backgroundImage` image file — Background image + +15 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.QuestionSet --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Questionnaire.md b/skills/h5p-author/references/types/H5P.Questionnaire.md new file mode 100644 index 00000000..0b737787 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Questionnaire.md @@ -0,0 +1,57 @@ +# Questionnaire (H5P.Questionnaire) + +A survey: open questions and multiple-choice questions with no right answer, then a thank-you screen. Not scored. + +- Each item of `questionnaireElements` holds its question under `library`, which is itself sub-content: `{ "library": { "library": "H5P.SimpleMultiChoice", "params": { … } }, "requiredField": true }`. +- H5P.SimpleMultiChoice: `question` (plain text), `inputType` `"radio"` (one answer) or `"checkbox"` (several), `alternatives` of `{ "text": "…" }`. +- H5P.OpenEndedQuestion: `question`, `placeholderText`, `inputRows` `"1"`, `"2"`, `"3"` or `"10"`. +- The answers go out as xAPI statements; nothing stores them unless the site does. + +## Example + +```json +{ + "type": "H5P.Questionnaire", + "params": { + "questionnaireElements": [ + { + "library": { + "library": "H5P.SimpleMultiChoice", + "params": { "question": "How often do you walk by a river?", "inputType": "radio", "alternatives": [{ "text": "Every week" }, { "text": "Sometimes" }, { "text": "Never" }] } + }, + "requiredField": true + }, + { "library": { "library": "H5P.OpenEndedQuestion", "params": { "question": "Which river do you know best, and why?", "inputRows": "3" } } } + ] + } +} +``` + + + +## Fields of H5P.Questionnaire 1.3 + +- `questionnaireElements` list 1+ of, required — Questionnaire elements + - `library` sub-content: H5P.OpenEndedQuestion | H5P.SimpleMultiChoice, required — Library: Choose a library + - `requiredField` boolean = false — Required field +- `successScreenOptions` group — Success screen options + - `enableSuccessScreen` boolean = true — Enable success screen + - `successScreenImage` sub-content: H5P.Image — Add success screen image + - `successMessage` text = "You have completed the questionnaire." — Text to display on submit +- `uiElements` group — UI Elements + - `buttonLabels` group — Button labels + - `prevLabel` text = "Back" — Previous button label + - `continueLabel` text = "Continue" — Continue button label + - `nextLabel` text = "Next" — Next button label + - `submitLabel` text = "Submit" — Submit button label + - `accessibility` group — Accessibility + - `requiredTextExitLabel` text = "Close error message" — Required message exit button label + - `progressBarText` text = "Question %current of %max" — Progress bar text: Used to tell assistive technologies what question it is. Variables: [ %current, %max ] + - `requiredMessage` text = "This question requires an answer" — Required message: Will display if this field is unanswered and required by a wrapper content type + - `requiredText` text = "required" — Required symbol text: Text that will accompany an asterisk to signal that a question is required + - `submitScreenTitle` text = "You successfully answered all of the questions" — Title for the submit screen + - `submitScreenSubtitle` text = "Click below to submit your answers" — Subtitle for the submit screen + +It has no interface texts of its own. + + diff --git a/skills/h5p-author/references/types/H5P.SingleChoiceSet.md b/skills/h5p-author/references/types/H5P.SingleChoiceSet.md new file mode 100644 index 00000000..f5e10000 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.SingleChoiceSet.md @@ -0,0 +1,44 @@ +# Single Choice Set (H5P.SingleChoiceSet) + +Quick questions, one after another, each with one right answer of two to four; the learner moves on at the first click. + +- In each item of `choices`, the first of `answers` is the right one; the set shuffles them when shown. +- Keep answers short: they are buttons. + +## Example + +```json +{ + "type": "H5P.SingleChoiceSet", + "params": { + "choices": [ + { "question": "Which sea does the Danube reach?", "answers": ["Black Sea", "North Sea", "Baltic Sea"] }, + { "question": "Which river flows through Paris?", "answers": ["Seine", "Loire", "Rhône"] } + ] + } +} +``` + + + +## Fields of H5P.SingleChoiceSet 1.11 + +- `choices` list 1+ of, required — List of questions + - `question` html: strong em code, required — Question + - `answers` list 2–4 of html: strong em code, required — Alternatives - first alternative is the correct one. +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings + - `autoContinue` boolean = true — Auto continue + - `timeoutCorrect` number = 2000; only when autoContinue is true — Timeout on correct answers: Value in milliseconds + - `timeoutWrong` number = 3000; only when autoContinue is true — Timeout on wrong answers: Value in milliseconds + - `soundEffectsEnabled` boolean = true — Enable sound effects + - `enableRetry` boolean = true — Enable retry button + - `enableSolutionsButton` boolean = true — Enable show solution button + - `passPercentage` whole number 0–100 = 100 — Pass percentage: Percentage of Total score required for passing the quiz. + +21 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.SingleChoiceSet --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.SortParagraphs.md b/skills/h5p-author/references/types/H5P.SortParagraphs.md new file mode 100644 index 00000000..82961119 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.SortParagraphs.md @@ -0,0 +1,48 @@ +# Sort the Paragraphs (H5P.SortParagraphs) + +Paragraphs shown shuffled, which the learner puts in order: steps of a process, events of a story. + +- Write `paragraphs` in the right order, at least three; the content shuffles them. +- Scoring: `behaviour.scoringMode` `"positions"` counts paragraphs in the right place, `"transitions"` each one that follows the right one. + +## Example + +```json +{ + "type": "H5P.SortParagraphs", + "params": { + "taskDescription": "Put the journey of a raindrop in order.", + "paragraphs": [ + "Rain falls on the mountains.", + "Streams gather the water.", + "A river carries it through the valley.", + "The river reaches the sea." + ] + } +} +``` + + + +## Fields of H5P.SortParagraphs 0.11 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `taskDescription` html: strong em u a ul ol h2 h3 hr pre code, required — Task description: What your students should know. +- `paragraphs` list 3+ of html: strong em u ul ol h2 h3 hr pre code, required — Paragraphs +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range +- `behaviour` group — Behavioural settings + - `scoringMode` one of "positions" | "transitions" = "positions" — Scoring mode: Decide whether to give points for each correctly placed paragraph or for each paragraph that is placed after the paragraph it is supposed to be placed after ("correct sequence") + - `applyPenalties` boolean = true; only when scoringMode is "positions" — Apply penalties + - `duplicatesInterchangeable` boolean = true — Duplicate parapraphs interchangeable + - `addButtonsForMovement` boolean = true — Add buttons for movement + - `enableRetry` boolean = true — Enable "Retry" button + - `enableSolutionsButton` boolean = true — Enable "Show Solution" button + +29 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.SortParagraphs --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Summary.md b/skills/h5p-author/references/types/H5P.Summary.md new file mode 100644 index 00000000..ac8bf706 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Summary.md @@ -0,0 +1,38 @@ +# Summary (H5P.Summary) + +The learner builds a summary statement by statement, picking the true one from each group. + +- In each item of `summaries`, the first of `summary` is the true statement; the others are false. The content shuffles them. +- Each group should test one point; the true statements, in order, read as the summary. + +## Example + +```json +{ + "type": "H5P.Summary", + "params": { + "intro": "Choose the correct statement.", + "summaries": [ + { "summary": ["Rivers flow from higher to lower ground.", "Rivers flow from lower to higher ground."] }, + { "summary": ["Most rivers end in a sea or a lake.", "Most rivers end in a mountain spring."] } + ] + } +} +``` + + + +## Fields of H5P.Summary 1.10 + +- `intro` html: strong em u a ul ol h2 h3 hr pre code = "Choose the correct statement." — Introduction text: Will be displayed above the summary task. +- `summaries` list 1–100 of, required — Summary + - `summary` list 2+ of html, required — List of statements for the summary - the first statement is correct. + - `tip` html: strong em code — Tip +- `overallFeedback` list 1+ of — Overall Feedback: Click the "Add range" button to add as many ranges as you need. Example: 0-20% Bad score, 21-91% Average Score, 91-100% Great Score! + - `from` whole number 0–100 = 0 — Score Range + - `to` whole number 0–100 = 100 + - `feedback` text — Feedback for defined score range + +10 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.Summary --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Text.md b/skills/h5p-author/references/types/H5P.Text.md new file mode 100644 index 00000000..4d95a80d --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Text.md @@ -0,0 +1,28 @@ +# Text in a video or a hotspot (H5P.Text) + +Formatted text, the part Interactive Video and Image Hotspots hold. Elsewhere, use H5P.AdvancedText. + +- `text` takes the tags the Fields section lists. + +## Example + +```json +{ + "type": "H5P.ImageHotspots", + "params": { + "image": { "path": "delta.png" }, + "backgroundImageAltText": "A river delta", + "hotspots": [{ "position": { "x": 50, "y": 50 }, "header": "Delta", "content": [{ "library": "H5P.Text", "params": { "text": "

The river splits into channels.

" } }] }] + } +} +``` + + + +## Fields of H5P.Text 1.1 + +- `text` html: strong em del a ul ol h2 h3 hr pre code, required — Text + +It has no interface texts of its own. + + diff --git a/skills/h5p-author/references/types/H5P.Timeline.md b/skills/h5p-author/references/types/H5P.Timeline.md new file mode 100644 index 00000000..67d25da1 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Timeline.md @@ -0,0 +1,63 @@ +# Timeline (H5P.Timeline) + +Events along a time line, each with a date, a headline and a text, browsed in order. + +- `timeline.headline` and `timeline.text` make the title slide; each item of `timeline.date` is an event. +- Dates are written `YYYY,MM,DD`, the month and day optional: `"1888"`, `"1888,7,22"`. An event with an `endDate` spans a period; `timeline.era` shades longer periods. +- An event's `asset.media` is a web address (a YouTube video, a Wikipedia article, a picture's URL) that the timeline loads from that site when shown. That site then learns who views it; tell the user, or leave media out. + +## Example + +```json +{ + "type": "H5P.Timeline", + "params": { + "timeline": { + "headline": "Bridges over the Danube in Budapest", + "text": "From the first permanent bridge to the newest.", + "date": [ + { "startDate": "1849,11,20", "headline": "Chain Bridge", "text": "The first permanent bridge between Buda and Pest." }, + { "startDate": "1876,4,30", "headline": "Margaret Bridge", "text": "The second permanent bridge." }, + { "startDate": "1896", "headline": "Liberty Bridge", "text": "Opened for the millennium celebrations." } + ] + } + } +} +``` + + + +## Fields of H5P.Timeline 1.1 + +- `timeline` group — Timeline + - `headline` text, required — Headline: Main timeline heading goes here (first page) + - `text` html: strong em del a ul ol hr code — Body Text: The main timeline body goes here (first page). + - `defaultZoomLevel` text = "0" — Default zoom level: This will tweak the default zoom level. Equivilent to pressing the zoom in or zoom out button the specified number of times. Negative numbers zoom out. default is 0 + - `backgroundImage` image file — Background image + - `height` whole number = 600 — Height: The height in pixels + - `asset` group — Asset + - `media` text — Media: Link to media URL (Twitter, YouTube, Flickr, Vimeo, Google Maps and SoundCloud are currently supported) + - `credit` text — Credits: Credits to the media + - `caption` text — Caption: Caption description goes here + - `date` list 1+ of, required — Dates: Add some dates to your timeline! + - `startDate` text, required — Start date: YYYY,MM,DD (Minimum YYYY required) + - `endDate` text — End date: YYYY,MM,DD (Minimum YYYY required) + - `headline` text, required — Headline: Headline for the date entry + - `text` html: strong em del a ul ol h2 h3 hr pre code — Body text: Body for the date entry + - `tag` text — Tags: Enter Tags (categories) + - `asset` group — Asset + - `media` text — Media: URL to the media (Twitter, YouTube, Flickr, Vimeo, Wikipedia, Google Maps and SoundCloud are currently supported). + - `thumbnail` image file — Thumbnail + - `credit` text — Credit: Credits to the media + - `caption` text — Caption: Caption text + - `era` list of — Eras: Add an era to your timeline + - `startDate` text, required — Start date: YYYY,MM,DD (Minimum YYYY required) + - `endDate` text — End date: YYYY,MM,DD (Minimum YYYY required) + - `headline` text, required — Headline: Era headline + - `text` html: strong em del a ul ol hr code — Text: Era body + - `tag` text — Tag: Era tags (categories) + - `language` one of "af" | "ar" | "hy" | "eu" | "bg" | "ca" | "zh-cn" | "hr" | "cz" | "da" | "nl" | "en" | "en-24hr" | "eo" | "et" | "fo" | "fa" | "fi" | "fr" | "gl" | "ka" | "de" | "el" | "he" | "hu" | "is" | "id" | "it" | "ja" | "ko" | "lv" | "lt" | "lb" | "ms" | "ne" | "no" | "pl" | "pt" | "pt-br" | "rm" | "ru" | "sr-cy" | "sr" | "si" | "sk" | "sl" | "es" | "sv" | "tl" | "ta" | "zh-tw" | "te" | "tr" | "uk" = "en" — Language: The language of the user interface + +It has no interface texts of its own. + + diff --git a/skills/h5p-author/references/types/H5P.TrueFalse.md b/skills/h5p-author/references/types/H5P.TrueFalse.md new file mode 100644 index 00000000..cc4627eb --- /dev/null +++ b/skills/h5p-author/references/types/H5P.TrueFalse.md @@ -0,0 +1,45 @@ +# True/False Question (H5P.TrueFalse) + +One statement the learner marks true or false. + +- `correct` is the text `"true"` or `"false"`, not a boolean. +- Write the statement as a claim, not a question, so either answer is a judgement of it. +- `behaviour.feedbackOnCorrect` and `behaviour.feedbackOnWrong` replace the default messages; say why. + +## Example + +```json +{ + "type": "H5P.TrueFalse", + "params": { + "question": "The Danube flows through four capital cities.", + "correct": "true", + "behaviour": { + "feedbackOnCorrect": "Yes: Vienna, Bratislava, Budapest and Belgrade.", + "feedbackOnWrong": "It does: Vienna, Bratislava, Budapest and Belgrade." + } + } +} +``` + + + +## Fields of H5P.TrueFalse 1.8 + +- `media` group — Media + - `type` sub-content: H5P.Image | H5P.Video | H5P.Audio — Type: Optional media to display above the question. + - `disableImageZooming` boolean = false; only when type is "H5P.Image 1.1" — Disable image zooming +- `question` html: strong em sub sup h2 h3 pre code, required — Question +- `correct` one of "true" | "false" = "true" — Correct answer +- `behaviour` group — Behavioural settings + - `enableRetry` boolean = true — Enable "Retry" button + - `enableSolutionsButton` boolean = true — Enable "Show Solution" button + - `confirmCheckDialog` boolean = false — Show confirmation dialog on "Check" + - `confirmRetryDialog` boolean = false — Show confirmation dialog on "Retry" + - `autoCheck` boolean = false — Automatically check answer + - `feedbackOnCorrect` text — Feedback on correct answer: This will override the default feedback text. Variables available: @score and @total + - `feedbackOnWrong` text — Feedback on wrong answer: This will override the default feedback text. Variables available: @score and @total + +21 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.TrueFalse --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/references/types/H5P.Video.md b/skills/h5p-author/references/types/H5P.Video.md new file mode 100644 index 00000000..8ac0ada2 --- /dev/null +++ b/skills/h5p-author/references/types/H5P.Video.md @@ -0,0 +1,42 @@ +# Video (H5P.Video) + +A video player, a part other content holds: in a page, a book, a slide or a scenario. Not a content type on its own; Interactive Video is the one with questions over a video. + +- `sources` is the video: a file beside the source (`.mp4`, `.webm`), a web address of one, or the address of a video on YouTube, Vimeo, Panopto or Echo360, which plays from there and shares the viewing with that site. +- Captions: `a11y`, `[{ "label": "English", "kind": "captions", "srcLang": "en", "track": { "path": "captions.vtt" } }]`. + +## Example + +```json +{ + "type": "H5P.Column", + "params": { + "content": [ + { "content": { "library": "H5P.Video", "params": { "sources": [{ "path": "clip.mp4" }], "a11y": [{ "label": "English", "kind": "captions", "srcLang": "en", "track": { "path": "captions.vtt" } }] } } } + ] + } +} +``` + + + +## Fields of H5P.Video 1.6 + +- `sources` video files, required — Video sources +- `visuals` group — Visuals + - `poster` image file, required — Poster image + - `fit` boolean = true — Fit video player to use all available space + - `controls` boolean = true — Show video player controls +- `playback` group — Playback + - `autoplay` boolean = false — Auto-play video + - `loop` boolean = false — Loop video + - `hasNoAutoPause` boolean = false — Deactivate auto-pause +- `a11y` list of — Accessibility + - `label` text — Track label + - `kind` one of "subtitles" | "captions" | "descriptions" | "chapters" = "descriptions" — Type kind, refer to HTML living standard + - `srcLang` text = "en" — Source language, must be defined for subtitles: Must be a valid BCP 47 language tag. If the kind attribute is set to subtitles, then srclang must be defined. + - `track` file, required — Track file (WebVTT) + +13 interface texts are left out: they come from the libraries' translations. `h5p-author schema H5P.Video --all` lists them, for a source to set one. + + diff --git a/skills/h5p-author/scripts/build-quiz.mjs b/skills/h5p-author/scripts/build-quiz.mjs deleted file mode 100644 index c45ea3eb..00000000 --- a/skills/h5p-author/scripts/build-quiz.mjs +++ /dev/null @@ -1,446 +0,0 @@ -import { constants, createReadStream } from 'node:fs' -import { copyFile, mkdtemp, open, readFile, realpath, rm } from 'node:fs/promises' -import { createRequire } from 'node:module' -import { dirname, join, resolve } from 'node:path' -import { Readable, Writable } from 'node:stream' -import { fileURLToPath, pathToFileURL } from 'node:url' -import { createHash, randomUUID } from 'node:crypto' - -/** - * @typedef {{ text: string, correct: boolean, feedback?: string }} Answer - * @typedef {{ title?: string, prompt: string, multipleAnswers?: boolean, answers: Answer[] }} Question - * @typedef {{ - * kind: 'multiple-choice' | 'question-set', title: string, language: string, license: string, - * authors: { name: string, role: 'Author' }[], passPercentage?: number, - * passedFeedback?: string, failedFeedback?: string, questions: Question[] - * }} Quiz - * @typedef {{ - * name: string, type: string, optional?: boolean, default?: unknown, - * fields?: Field[], field?: Field, min?: number, defaultNum?: number, tags?: string[] - * }} Field - */ - -function record(value, path, keys) { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${path}: expected an object`) - for (const key of Object.keys(value)) { - if (!keys.includes(key)) throw new Error(`${path}.${key}: unsupported field`) - } -} - -function text(value, path) { - if (typeof value !== 'string' || !value.trim()) throw new Error(`${path}: expected non-empty text`) -} - -/** @param {unknown} source @returns {asserts source is Quiz} */ -export function validateQuiz(source) { - record(source, 'quiz', ['kind', 'title', 'language', 'license', 'authors', 'passPercentage', 'passedFeedback', 'failedFeedback', 'questions']) - const quiz = /** @type {Quiz} */ (source) - if (!['multiple-choice', 'question-set'].includes(quiz.kind)) throw new Error('quiz.kind: use "multiple-choice" or "question-set"') - for (const key of ['title', 'language', 'license']) text(quiz[key], `quiz.${key}`) - if (quiz.title.length > 255) throw new Error('quiz.title: at most 255 characters') - try { - Intl.getCanonicalLocales(quiz.language) - } catch { - throw new Error('quiz.language: expected a BCP 47 language tag, such as "en"') - } - if (!['U', 'CC BY', 'CC BY-SA', 'CC BY-ND', 'CC BY-NC', 'CC BY-NC-SA', 'CC BY-NC-ND', 'CC0 1.0', 'PD', 'C'].includes(quiz.license)) { - throw new Error('quiz.license: use an H5P license code (for example "U", "CC BY", or "CC0 1.0")') - } - if (!Array.isArray(quiz.authors) || !quiz.authors.length) throw new Error('quiz.authors: name at least one author') - quiz.authors.forEach((author, i) => { - record(author, `quiz.authors[${i}]`, ['name', 'role']) - text(author.name, `quiz.authors[${i}].name`) - if (author.role !== 'Author') throw new Error(`quiz.authors[${i}].role: use "Author"`) - }) - if (quiz.passPercentage !== undefined && (!Number.isInteger(quiz.passPercentage) || quiz.passPercentage < 0 || quiz.passPercentage > 100)) { - throw new Error('quiz.passPercentage: expected an integer from 0 to 100') - } - if (quiz.passedFeedback !== undefined || quiz.failedFeedback !== undefined) { - // One without the other leaves some learners with no word on the result. - for (const key of ['passedFeedback', 'failedFeedback']) { - if (quiz[key] === undefined) throw new Error(`quiz.${key}: set passedFeedback and failedFeedback together`) - text(quiz[key], `quiz.${key}`) - } - if (quiz.passPercentage === undefined) throw new Error('quiz.passPercentage: set it with passedFeedback and failedFeedback; the library defaults differ by kind') - } - if (!Array.isArray(quiz.questions) || !quiz.questions.length) throw new Error('quiz.questions: at least one question is required') - if (quiz.kind === 'multiple-choice' && quiz.questions.length !== 1) throw new Error('quiz.questions: multiple-choice requires exactly one question') - quiz.questions.forEach((question, i) => { - const path = `quiz.questions[${i}]` - record(question, path, ['title', 'prompt', 'multipleAnswers', 'answers']) - text(question.prompt, `${path}.prompt`) - if (question.title !== undefined) text(question.title, `${path}.title`) - if (question.multipleAnswers !== undefined && typeof question.multipleAnswers !== 'boolean') throw new Error(`${path}.multipleAnswers: expected a boolean`) - if (!Array.isArray(question.answers) || question.answers.length < 2) throw new Error(`${path}.answers: at least two answers are required`) - question.answers.forEach((answer, j) => { - const answerPath = `${path}.answers[${j}]` - record(answer, answerPath, ['text', 'correct', 'feedback']) - text(answer.text, `${answerPath}.text`) - if (typeof answer.correct !== 'boolean') throw new Error(`${answerPath}.correct: expected a boolean`) - if (answer.feedback !== undefined) text(answer.feedback, `${answerPath}.feedback`) - }) - const correct = question.answers.filter(answer => answer.correct).length - if (question.multipleAnswers ? correct === 0 : correct !== 1) { - throw new Error(`${path}.answers: ${question.multipleAnswers ? 'at least one' : 'exactly one'} answer must be correct`) - } - }) -} - -/** Fill only the field kinds these two content types use; a changed schema must fail loudly. - * @param {Field[]} fields @param {Record} written - * @returns {Record} - */ -function parameters(fields, written) { - for (const key of Object.keys(written)) { - if (!fields.some(field => field.name === key)) throw new Error(`Installed semantics do not name "${key}"`) - } - return Object.fromEntries(fields.map(field => [field.name, valueFor(field, written[field.name])]).filter(([, value]) => value !== undefined)) -} - -/** @param {Field} field @param {unknown} written @returns {unknown} */ -function valueFor(field, written) { - if (field.type === 'group') { - const fields = field.fields - if (!fields?.length) throw new Error(`Invalid group semantics: ${field.name}`) - // H5P saves a group with one field as that field, without the group's wrapper. - if (fields.length === 1) return valueFor(fields[0], written) - return parameters(fields, /** @type {Record} */ (written ?? field.default ?? {})) - } - if (field.type === 'list') { - const list = written ?? field.default - if (list !== undefined) { - if (!Array.isArray(list)) throw new Error(`Expected a list: ${field.name}`) - return list.map(item => valueFor(field.field, item)) - } - if (field.optional) return undefined - throw new Error(`Missing required list: ${field.name}`) - } - if (field.type === 'library' && written !== undefined) return written - if (written !== undefined) return written - if (field.default !== undefined) return structuredClone(field.default) - if (field.type === 'boolean') return false - if (field.optional) return undefined - throw new Error(`No authoring value or default for required field: ${field.name} (${field.type})`) -} - -/** Plain text as H5P stores a text field: escaped, since the libraries insert it as HTML. */ -function escape(value) { - return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''') -} - -function html(value) { - return `

${escape(value).replaceAll('\n', '
')}

` -} - -/** - * The pass mark as two score ranges for the content's overall feedback. The libraries pick a - * range by the floored percentage and judge `success` by the exact one, which agree for a whole - * number, so the message a learner gets matches the result an LMS records. - * @param {Quiz} quiz - */ -function passFeedback(quiz) { - if (quiz.passedFeedback === undefined || quiz.failedFeedback === undefined || quiz.passPercentage === undefined) return undefined - const pass = quiz.passPercentage - return [ - ...(pass > 0 ? [{ from: 0, to: pass - 1, feedback: escape(quiz.failedFeedback) }] : []), - { from: pass, to: 100, feedback: escape(quiz.passedFeedback) } - ] -} - -/** A tag's canonical form in lower case, as H5P names its files; a name that is no tag as it is. */ -function canonical(tag) { - try { - return Intl.getCanonicalLocales(tag)[0].toLowerCase() - } catch { - return tag.toLowerCase() - } -} - -/** The script a tag is written in, its own or the likely one: `Cyrl` for `sr`. */ -function scriptOf(tag) { - try { - return new Intl.Locale(tag).maximize().script - } catch { - return undefined - } -} - -/** - * Which of a library's translation files serve a language tag, best first: RFC 4647 lookup over - * the files' names, so `de-AT` takes `de.json` and `pt-BR` `pt-br.json`. A shorter tag written in - * another script is passed over: `sr.json` is Cyrillic, so `sr-Latn` takes none. Names are compared - * in canonical form, since H5P names Northern Sami `sme`, which is `se` as a tag. Two exceptions - * follow H5P's own naming. Norwegian Bokmål is `nb`. Chinese goes by script and never to a bare - * `zh.json`, which is Traditional in Question Set 1.21 where the tag means Simplified. - * @param {string[]} files the files' names, without `.json` - * @param {string} language - */ -export function translationFiles(files, language) { - const tag = Intl.getCanonicalLocales(language)[0] - const { language: base, script } = new Intl.Locale(tag).maximize() - let names - if (base === 'zh') names = script === 'Hant' ? ['zh-hant', 'zh-tw'] : ['zh-hans', 'zh-cn'] - else { - const subtags = tag.toLowerCase().split('-') - names = subtags.map((_, i) => subtags.slice(0, subtags.length - i).join('-')).filter(name => scriptOf(name) === script) - if (base === 'no') names.push('nb') - } - return names.flatMap(name => files.filter(file => canonical(file) === name)) -} - -/** What the libraries fill into their own texts: `:num`, `@total`, `%d`. */ -const PLACEHOLDER = /[:@%][A-Za-z]+/g - -/** - * A translation file's `semantics` laid over a library's, position by position, as an H5P editor - * lays it: the text defaults it replaces, and those that stay English. Only a text field's default - * is replaced, never a select's value. The English stays where the translation has no text, the - * same text, or text without a placeholder the library fills in, which a learner would otherwise - * meet as `@finals`. - * @param {Field[]} fields @param {unknown} translation - */ -export function translateDefaults(fields, translation) { - /** @type {{ field: Field, text: string }[]} */ - const translated = [] - /** @type {{ field: string, text: string, dropped?: string[] }[]} */ - const english = [] - /** @param {Field[]} fields @param {unknown} translation @param {string} path @param {string} [item] */ - const walk = (fields, translation, path, item) => fields.forEach((field, i) => { - const entry = Array.isArray(translation) && translation[i] && typeof translation[i] === 'object' ? translation[i] : undefined - const name = item ?? (path ? `${path}.${field.name}` : field.name) - if (field.type === 'text' && typeof field.default === 'string') { - const text = entry?.default - const kept = typeof text === 'string' ? text.match(PLACEHOLDER) ?? [] : [] - const dropped = typeof text === 'string' ? (field.default.match(PLACEHOLDER) ?? []).filter(placeholder => !kept.includes(placeholder)) : [] - if (typeof text === 'string' && text.trim() && text !== field.default && !dropped.length) translated.push({ field, text }) - else english.push({ field: name, text: field.default, ...(dropped.length ? { dropped } : {}) }) - } - if (field.fields) walk(field.fields, entry?.fields, name) - if (field.field) walk([field.field], entry ? [entry.field] : undefined, name, `${name}[]`) - }) - walk(fields, translation, '') - return { strings: translated.length + english.length, translated, english } -} - -/** The versions the helper is tested with; a missing or older install is refused with this command. */ -const INSTALL = 'npm install --save-dev @missing-elements/h5p-libraries@^1 @zip.js/zip.js@^2.24' - -/** - * Dependencies are resolved from the caller's project, not from the installed skill directory. - * @param {string} project - */ -async function dependencies(project) { - const require = createRequire(join(resolve(project), 'package.json')) - try { - // appendZip has no filter before zip.js 2.20, so each part's own h5p.json would be copied too. - const { version } = require('@zip.js/zip.js/package.json') - const [major, minor] = version.split('.').map(Number) - if (major < 2 || (major === 2 && minor < 24)) throw new Error(`@zip.js/zip.js ${version} is older than 2.24`) - const [zip, { pack }] = await Promise.all([ - import(pathToFileURL(require.resolve('@zip.js/zip.js')).href), - import(pathToFileURL(require.resolve('@missing-elements/h5p-libraries')).href) - ]) - return { zip, pack } - } catch (error) { - throw new Error(`Cannot load authoring dependencies from the current project. Run: ${INSTALL}`, { cause: error }) - } -} - -/** @param {unknown} source @param {string} output @param {string} [project] */ -export async function buildQuiz(source, output, project = process.cwd()) { - validateQuiz(source) - const { zip, pack } = await dependencies(project) - const { ZipReader, ZipWriter, Reader, TextReader, TextWriter } = zip - const selected = new Map() - const readers = new Map() - - // The pack's largest library need not fit in memory. - class FileReader extends Reader { - constructor(path) { super(); this.path = path } - async init() { - await super.init() - this.file = await open(this.path, 'r') - this.size = (await this.file.stat()).size - } - async readUint8Array(offset, length) { - const bytes = new Uint8Array(length) - let read = 0 - while (read < length) { - const { bytesRead } = await this.file.read(bytes, read, length - read, offset + read) - if (!bytesRead) throw new Error(`Short read from library part: ${this.path}`) - read += bytesRead - } - return bytes - } - createReadable({ offset = 0, size = this.size - offset } = {}) { - if (!size) return new ReadableStream({ start(controller) { controller.close() } }) - return Readable.toWeb(createReadStream(this.path, { start: offset, end: offset + size - 1 })) - } - } - - async function use(machineName, major, minor = 0) { - const candidates = pack.libraries.filter(lib => lib.machineName === machineName && (major === undefined || lib.majorVersion === major) && lib.minorVersion >= minor) - candidates.sort((a, b) => b.majorVersion - a.majorVersion || b.minorVersion - a.minorVersion || b.patchVersion - a.patchVersion) - const candidate = candidates[0] - if (!candidate) throw new Error(`Installed pack cannot supply ${machineName} ${major ?? ''}.${minor}`) - if (selected.has(candidate.folder)) return selected.get(candidate.folder) - const library = { ...candidate } - selected.set(library.folder, library) - const path = new URL(library.url) - const hash = createHash('sha256') - for await (const chunk of createReadStream(path)) hash.update(chunk) - if (hash.digest('hex') !== library.sha256) throw new Error(`Library part failed SHA-256: ${library.folder}. Reinstall the library pack.`) - const file = new FileReader(path) - const reader = new ZipReader(file, { checkSignature: true }) - readers.set(library.folder, { reader, file }) - const entries = (await reader.getEntries()).filter(entry => !entry.directory && entry.filename.startsWith(`${library.folder}/`)) - const metadata = entries.find(entry => entry.filename === `${library.folder}/library.json`) - if (!metadata) throw new Error(`Library part has no library.json: ${library.folder}`) - const info = JSON.parse(await metadata.getData(new TextWriter())) - if (info.machineName !== library.machineName || Number(info.majorVersion) !== library.majorVersion || Number(info.minorVersion) !== library.minorVersion || Number(info.patchVersion) !== library.patchVersion) { - throw new Error(`Library part disagrees with pack index: ${library.folder}`) - } - const semantics = entries.find(entry => entry.filename === `${library.folder}/semantics.json`) - if (semantics) library.semantics = JSON.parse(await semantics.getData(new TextWriter())) - const languages = `${library.folder}/language/` - library.translations = new Map(entries.filter(entry => entry.filename.startsWith(languages) && entry.filename.endsWith('.json')) - .map(entry => [entry.filename.slice(languages.length, -'.json'.length), entry])) - for (const dependency of [...(info.preloadedDependencies ?? []), ...(info.dynamicDependencies ?? [])]) { - await use(dependency.machineName, Number(dependency.majorVersion), Number(dependency.minorVersion)) - } - return library - } - - /** - * The library's interface texts in the quiz's language, from the first of its own translations - * that translates any. An H5P editor fills new content's defaults from these files: every field - * from the translation for the editor's own language, then the fields a library marks `common` - * from the one for the content's. With no editor here, the quiz's language fills all of them. - */ - async function localize(library) { - const label = `${library.machineName} ${library.majorVersion}.${library.minorVersion}` - for (const name of translationFiles([...library.translations.keys()], source.language)) { - const entry = library.translations.get(name) - let translation - try { - translation = JSON.parse(await entry.getData(new TextWriter())).semantics - } catch (error) { - throw new Error(`Library translation is not JSON: ${entry.filename}`, { cause: error }) - } - const { strings, translated, english } = translateDefaults(library.semantics, translation) - if (!translated.length) continue - // Plain text as H5P stores it; a field with `tags` holds markup, which the content check filters. - for (const { field, text } of translated) field.default = field.tags ? text : escape(text) - return { library: label, translation: name, strings, english } - } - const { strings, english } = translateDefaults(library.semantics, undefined) - return { library: label, translation: null, strings, english } - } - - let temporary - try { - const choice = await use('H5P.MultiChoice', 1) - const set = source.kind === 'question-set' ? await use('H5P.QuestionSet', 1) : null - if (!choice.semantics || (set && !set.semantics)) throw new Error('The installed quiz libraries must carry semantics.json') - const translations = [] - for (const library of set ? [set, choice] : [choice]) translations.push(await localize(library)) - // The whole quiz's result, never a question's inside a set, which shows its own after Check. - const overallFeedback = passFeedback(source) - // An untitled question is named as the set labels it itself, in the quiz's language; its - // result screen lists each question by this title. A default is stored as it stands. - const label = set?.semantics.find(field => field.name === 'texts')?.fields?.find(field => field.name === 'questionLabel')?.default ?? 'Question' - // A question's title and authors as H5P stores a text field: the platforms check sub-content - // metadata as they check its parameters, and Question Set draws the title as HTML. - const authors = source.authors.map(author => ({ ...author, name: escape(author.name) })) - const questions = source.questions.map((question, i) => { - const written = { - question: html(question.prompt), - answers: question.answers.map(answer => ({ - text: html(answer.text), correct: answer.correct, - tipsAndFeedback: answer.feedback ? { chosenFeedback: html(answer.feedback) } : {} - })), - behaviour: { - type: question.multipleAnswers ? 'multi' : 'single', - ...(!set && source.passPercentage !== undefined ? { passPercentage: source.passPercentage } : {}) - }, - ...(!set && overallFeedback ? { overallFeedback } : {}) - } - return { - library: `${choice.machineName} ${choice.majorVersion}.${choice.minorVersion}`, - params: parameters(choice.semantics, written), - subContentId: randomUUID(), - metadata: { title: question.title === undefined ? `${label} ${i + 1}` : escape(question.title), license: source.license, authors } - } - }) - const content = set - ? parameters(set.semantics, { - questions, - ...(source.passPercentage === undefined ? {} : { passPercentage: source.passPercentage }), - ...(overallFeedback ? { endGame: { overallFeedback } } : {}) - }) - : questions[0].params - const root = set ?? choice - // As H5P's exports write it, unescaped: the platforms check it when they load content. - const manifest = { - title: source.title, language: source.language, defaultLanguage: source.language, - license: source.license, authors: source.authors, mainLibrary: root.machineName, embedTypes: ['div'], - preloadedDependencies: [...selected.values()].map(lib => ({ - machineName: lib.machineName, majorVersion: String(lib.majorVersion), minorVersion: String(lib.minorVersion) - })) - } - - output = resolve(output) - temporary = await mkdtemp(join(dirname(output), '.h5p-author-')) - const staged = join(temporary, 'quiz.h5p') - const file = await open(staged, 'wx') - try { - const writer = new ZipWriter(Writable.toWeb(file.createWriteStream()), { useWebWorkers: false }) - await writer.add('h5p.json', new TextReader(JSON.stringify(manifest))) - for (const library of selected.values()) { - await writer.appendZip(readers.get(library.folder).file, { - filter: entry => !entry.directory && entry.filename.startsWith(`${library.folder}/`) - }) - } - await writer.add('content/content.json', new TextReader(JSON.stringify(content))) - await writer.close() - } finally { - await file.close() - } - // Unlike a hard link, an exclusive copy also works on FAT/exFAT destinations. - await copyFile(staged, output, constants.COPYFILE_EXCL) - return { output, manifest, content, libraries: [...selected.keys()], translations } - } finally { - for (const { reader, file } of readers.values()) { - try { await reader.close() } finally { await file.file?.close() } - } - if (temporary) await rm(temporary, { recursive: true, force: true }) - } -} - -if (process.argv[1] && await realpath(process.argv[1]) === fileURLToPath(import.meta.url)) { - const args = process.argv.slice(2) - if (args.length === 1 && args[0] === '--help') { - console.log(`Usage: node /scripts/build-quiz.mjs \nRun from a project with the dependencies installed: ${INSTALL}\nBuilds a self-contained, text-only Multiple Choice or Question Set. Refuses to overwrite output.`) - } else { - try { - if (args.length !== 2 || args.some(arg => arg.startsWith('--'))) throw new Error('Usage: node /scripts/build-quiz.mjs ') - const source = JSON.parse(await readFile(resolve(args[0]), 'utf8')) - const result = await buildQuiz(source, args[1]) - console.log(`Built ${result.output}\n${result.manifest.mainLibrary}; ${result.libraries.length} libraries from the installed pack.\nNot verified: run h5p-verify and inspect its screenshot before handing this package over.`) - if (!/^en(?:-|$)/i.test(source.language)) { - for (const { library, translation, strings, english } of result.translations) { - if (!translation) console.warn(`${library} has no translation for ${source.language}: its ${strings} interface texts are English.`) - else if (!english.length) console.log(`${library}: interface texts from its translation language/${translation}.json.`) - else { - const list = english.map(({ field, text, dropped }) => ` ${field}: ${JSON.stringify(text)}${dropped ? ` (its translation drops ${dropped.join(' and ')})` : ''}`) - console.warn(`${library}: interface texts from its translation language/${translation}.json; ${english.length} of ${strings} as in English, untranslated or the same word:\n${list.join('\n')}`) - } - } - } - } catch (error) { - console.error(`h5p-author: ${error.message}`) - if (error.cause) console.error(error.cause.message) - process.exitCode = 1 - } - } -}