diff --git a/AGENTS.md b/AGENTS.md index dcec3dd4..a7d2eec3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,9 @@ player's unless a section says otherwise. packages/player/ @missing-elements/h5p-offline-player — the published package src/ h5p-offline-player.ts the custom element — the only public entry point + plan.ts `./plan` -> dist/h5p-plan.js: the player's library rules (`planPack`, `librariesNamedIn`, + `addonPatterns`, `textMatches`, `dependenciesIn`) for the packages that write what it + plays; not covered by docs/compatibility.md, so they pin the player exactly (#106) jobs-worker-handle.ts starts the Jobs worker from the first script the page's CSP allows, holding jobs until it runs user-data-store.ts the learner's saved state for `resume`, in a database of the page's own shadow.css the element's own box, imported `?inline` so Vite minifies it into the bundle @@ -57,6 +60,9 @@ packages/player/ @missing-elements/h5p-offline-player — the published revision.ts `withProvenance` and `indexFingerprint`: the build every statement names; `librariesFingerprint`, one for the parts of the pack a package used pack.ts `packLibrariesIn`: a pack index held to its shape; imports nothing, the element carries it + content-libraries.ts which libraries `h5p.json`, a `library.json` and content's parameters name, and an + addon's patterns: out of package-reader.ts on 2026-11-02, so that the plan and + `./plan` carry no zip.js (#106) pack-index.ts generated by sync-h5p-assets from packages/libraries/parts/index.json: the pinned pack's index, which the worker plans from and checks each part against metadata.ts `h5p.json`'s metadata in the shape the runtime reads, held to the core's licence table @@ -83,7 +89,8 @@ packages/player/ @missing-elements/h5p-offline-player — the published warm.ts walks the library spans off one ranged request each and caches their entries scripts/ sync-h5p-assets (builds the runtime package and copies its dist/ to public/frame-assets/, writes frame-fonts.ts and pack-index.ts, stamps the versions), build-workers, - build-fixtures, prepack; + build-plan (dist/h5p-plan.js alone, which `prepare:dev` and h5p-author's tests + run, since h5p-author imports it), build-fixtures, prepack; scripts/lib/worker-bundle.mjs builds both workers, and a host's own worker with the handlers mounted (the demo uses it for h5p-sw.js and the app's sw.js) vite.config.ts the library build and the test runner @@ -170,8 +177,12 @@ packages/verify/ @missing-elements/h5p-verify — plays a package headl 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/build.mjs the source read and checked, the libraries loaded, the content generated, + media copied, layouts run, the parts planned with the player's `planPack`, + the archive written + lib/libraries.mjs `loadLibraries`: the libraries content brings in, loaded and localized as + the build loads them, for the build and for a tool beside it; no Node + import of its own, nor has lib/source-error.mjs, `SourceError` (#106) lib/generator.mjs `ContentGenerator`: content from a type's `semantics.json`, authoring (every written value checked as the editor's form would) or lenient, as the sweep runs it; moved out of the demo on 2026-11-01 (#100) @@ -184,10 +195,10 @@ packages/author/ @missing-elements/h5p-author — a playable .h5p of an quiz format, still built 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, the quiz - format; fixtures/ the quiz format's two examples, which apps/skills + check-pack-published.mjs, the publish guard for the pinned pack and player + tests/ node tests: the generator, text and translations, layouts and schema, the + loader, builds with media from disk and a local server, the command, the + quiz format; fixtures/ the quiz format's two examples, which apps/skills plays too; package-types.ts as for the normalizer types/ generated, not in git: the declarations @@ -390,7 +401,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 author build source.json course.h5p # a package of any content type in the pack from a short source; + # after pnpm build, or the player's build:plan, whose dist/h5p-plan.js it imports 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 @@ -1969,7 +1981,7 @@ already holds text to the content check's rules, from the pack an untrusted chec `apps/skills` plays every example untrusted too. Measured on a five-question quiz, at four characters a token: `content.json` was about 3,470 tokens to write by hand, after reading 3,900 to 9,500 of a type's semantics; the source is 1,000 to 1,800 tokens, written from a type file of 200 -to 3,000. Seven things the code does not say by itself: +to 3,000. Eight 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 @@ -2035,7 +2047,28 @@ to 3,000. Seven things the code does not say by itself: 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. + on npm with this checkout's index (`scripts/check-pack-published.mjs`, which checks the player it + pins too, next bullet), as the player's does. +- **The player's library rules, not copies of them** (2026-11-02, #106, the owner's rule: reuse what + another package has, and extend it where needed). Which libraries content names, an addon's + patterns and what they match, and which parts of the pack a package needs are the player's: the + build plans what a package carries with `planPack` from the player's `./plan`, for a package that + carries nothing yet, so a package carries the parts the player would take from the pack for it. + Two things stay here. A check that every library the content and the parts name was planned, + since the plan leaves a gap without a word. And the order: depth first from the content type, as + the closure the plan replaced listed them, which `h5p.json` and the zip's folders follow, because + the runtime keeps that order between libraries that do not depend on each other and so decides + whose stylesheet comes later; `build.test.ts` holds a build's `h5p.json` to it, derived from the + parts' own `library.json` files. All 32 type files' examples came out with the libraries, order, + folders and notes of the build before. The old closure also followed `dynamicDependencies`, which + no library in the pack has (checked the same day). `./plan` is not covered by + docs/compatibility.md, so the dependency is `workspace:*`, the player's exact version, published + first: `scripts/check-pack-published.mjs` refuses to publish until the pinned version is on npm + and exports `./plan`, since a player published before it existed would install and fail on the + first import. A tool beside the build takes what the build loads (`openPack`, and `loadLibraries` over + any source with the pack's members) and its rules for text; not the build's check, which reads a + source where a tool edits saved content (#107). The runtime's library-name parser, content check + and content upgrade stay out: they are GPL-3.0-only. - **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 @@ -2256,7 +2289,8 @@ one row each; an LMS added here gets a row there. (the owner's call, the same day: those exports are what many teachers have). The writer runs the player's planner as the launch page has the element run it, filling gaps only: `planParts` is `planPack` with `refresh` off and nothing attached before, and `librariesNamedIn`, - `addonPatterns`, `textMatches` and `ownLibraries` are copies of the player's. Keep them in step. + `addonPatterns`, `textMatches` and `ownLibraries` are copies of the player's. Keep them in step + until #109 has the writer import them from the player's `./plan`, as h5p-author does. It writes those parts into `libraries/`, with an `index.json` that lists only them, and the page names the folder with `libraries="pack"`, `pack-base` and `refresh-libraries="off"`. The element then plans the same parts and finds each in the zip, and plays a package's own libraries as @@ -2605,6 +2639,7 @@ Three artefacts, built three different ways, because they are consumed three dif | `dist/h5p-sw.js` | esbuild, IIFE | Registered by URL; has to run on a site with no build step | | `dist/h5p-sw-mount.js` | esbuild, ESM | For hosts that enforce one worker per origin | | `dist/h5p-jobs.js` | esbuild, IIFE | The Jobs worker as a file, for a page whose CSP refuses a `blob:` worker | +| `dist/h5p-plan.js` | esbuild, ESM, not minified | The player's library rules, `./plan`, for the packages that write what it plays; the build fails if zip.js gets in | | `packages/runtime/dist/` | `packages/runtime/scripts/build.mjs` | The H5P core from `vendor/h5p-core/`, its scripts joined and minified under a licence header, its stylesheets rebuilt to stand alone, and the boot script; a package of its own, GPL | | `apps/demo/dist-demo/` | `apps/demo/scripts/build-demo.mjs` | The hosted demo: the pages, and `dist/`'s layout at the site root | diff --git a/docs/compatibility.md b/docs/compatibility.md index 481fc4a3..47147eb4 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -133,7 +133,9 @@ warning can come in any release. with the pack. - Exports and files this page does not name: a package's other exports, the rest of the player's `dist/`, the files inside the runtime's. Nor anything reached by a path a package does - not export. + not export. Among them the player's `./plan`, its library rules for the packages of this + repository that write what it plays, which depend on an exact version of the player for that + reason. - The demo site, including `/app/` and `/embed` there, and this repository's scripts and workflows. diff --git a/packages/author/README.md b/packages/author/README.md index 7312cd2b..41830f6e 100644 --- a/packages/author/README.md +++ b/packages/author/README.md @@ -119,6 +119,31 @@ const { output, manifest, content, libraries, translations, notes, media } = libraries })` returns the field list. `ContentGenerator` is the engine underneath, also run by the repository's sweep of every content type. +A tool beside the build takes the libraries as the build loads them, the generator, and the +build's rules for text: + +```js +import { ContentGenerator, loadLibraries, markupText, openPack } from '@missing-elements/h5p-author' + +const params = { questions: ['Die *Donau* mündet ins Schwarze Meer.'] } +const pack = await openPack() +try { + const { entries, main, translations } = await loadLibraries(pack, { type: 'H5P.Blanks', language: 'de', params }) + const content = new ContentGenerator(entries).generate(main, params) +} finally { + await pack.close() +} +``` + +`openPack(libraries)` opens the pinned pack, or another copy's `parts/` folder. `loadLibraries` +loads what the content brings in: the content type, every library its parameters name and each +library field's default, with their semantics in the language and marked as the layouts need them. +`entries` is the map `ContentGenerator` takes, every other library of the pack in it without its +semantics. It takes any object with `libraries`, `newest`, `open` and `translation`, such as one +over a package's own library folders. `markupText(value, field, report)`, `plainText(value, note)` +and `allowedTags(field)` are the build's rules for one text value against its field. What a type's +editor widget sets, and the check of a source, are the build's own and not exported. + ## What it does not do It checks structure, not pedagogy: whether the answers are right, the questions fair, or the diff --git a/packages/author/lib/author.mjs b/packages/author/lib/author.mjs index c15aabf6..26a5bc28 100644 --- a/packages/author/lib/author.mjs +++ b/packages/author/lib/author.mjs @@ -2,7 +2,9 @@ * @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. + * package pins, checked against its index. A tool beside the build takes the libraries as the build + * loads them (`openPack`, `loadLibraries`) and its rules for text (`markupText`, `plainText`, + * `allowedTags`). */ import { openPack } from './pack.mjs' @@ -11,13 +13,23 @@ import { LAYOUTS } from './types.mjs' export { buildPackage, SourceError } from './build.mjs' export { ContentGenerator, librariesIn, libraryString } from './generator.mjs' +export { loadLibraries } from './libraries.mjs' +export { openPack } from './pack.mjs' export { GENERATED_END, GENERATED_START } from './schema.mjs' +export { allowedTags, markupText, plainText } from './text.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 + * @typedef {import('./generator.mjs').PackEntry} PackEntry + * @typedef {import('./libraries.mjs').LibraryRecord} LibraryRecord + * @typedef {import('./libraries.mjs').LibrarySource} LibrarySource + * @typedef {import('./libraries.mjs').LoadedLibraries} LoadedLibraries + * @typedef {import('./translate.mjs').TranslationReport} TranslationReport + * @typedef {import('./pack.mjs').IndexEntry} IndexEntry + * @typedef {import('./pack.mjs').PartLibrary} PartLibrary */ /** diff --git a/packages/author/lib/build.mjs b/packages/author/lib/build.mjs index d5a09a6a..21da1d73 100644 --- a/packages/author/lib/build.mjs +++ b/packages/author/lib/build.mjs @@ -4,13 +4,17 @@ 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 { librariesNamedIn, planPack } from '@missing-elements/h5p-offline-player/plan' +import { ContentGenerator } from './generator.mjs' +import { loadLibraries } from './libraries.mjs' import { MediaStore } from './media.mjs' import { openPack } from './pack.mjs' import { quizProblems, quizSource } from './quiz.mjs' +import { SourceError } from './source-error.mjs' import { escapeText } from './text.mjs' -import { localize, translationFiles } from './translate.mjs' -import { LAYOUTS, patchSemantics, placesOf } from './types.mjs' +import { LAYOUTS, placesOf } from './types.mjs' + +export { SourceError } /** * A source made a package: validated, filled in from the pack's semantics and translations, @@ -41,16 +45,6 @@ const ROLES = ['Author', 'Editor', 'Licensee', 'Originator'] * 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) @@ -102,128 +96,49 @@ export function readSource(input) { } /** - * 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. + * The libraries a package carries: what the content names, what those need in turn, and the addons + * the pack has whose pattern its text matches, as a site with the addon installed exports it. It is + * the player's own plan (`planPack`) for a package that carries nothing yet, so that a package + * carries the parts the player would take from the pack for it. The plan leaves out what the pack + * cannot supply, which a package would then miss as it played, so that is checked. * @param {import('./pack.mjs').Pack} pack - * @param {Source} source - * @param {(path: string, message: string) => void} report + * @param {any} main the content type's `library.json` + * @param {Record} content */ -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]) - } +async function closure(pack, main, content) { + const roots = [main, ...librariesNamedIn(content)].map(({ machineName, majorVersion, minorVersion }) => ({ machineName, majorVersion: Number(majorVersion), minorVersion: Number(minorVersion) })) + /** @param {unknown} params */ + const plan = (params) => (planPack({ own: [], provided: [], roots, params, pack: pack.libraries, refresh: false, fill: true })?.parts ?? []) + .map((part) => /** @type {import('./pack.mjs').IndexEntry} */ (pack.libraries.find((entry) => entry.folder === part.folder))) + const planned = plan(content) + /** @param {{ machineName: string, majorVersion: string | number, minorVersion: string | number }} dependency */ + const supplied = (dependency) => planned.some((entry) => entry.machineName === dependency.machineName && entry.majorVersion === Number(dependency.majorVersion) && entry.minorVersion >= Number(dependency.minorVersion)) + for (const dependency of [...roots, ...planned.flatMap((entry) => entry.preloadedDependencies ?? [])]) { + if (!supplied(dependency)) throw new Error(`The library pack cannot supply ${dependency.machineName} ${dependency.majorVersion}.${dependency.minorVersion}`) } - 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 }) + // Listed as the build has always listed them, depth first from the content type with each + // library's dependencies after it, the addons last: the runtime sorts libraries by their + // dependencies and keeps this order between two that do not depend on each other, which decides + // whose stylesheet comes later. + const byLibrary = new Map(planned.map((entry) => [`${entry.machineName} ${entry.majorVersion}`, entry])) + /** @type {Map} */ + const ordered = new Map() + /** @param {{ machineName: string, majorVersion: string | number }} dependency */ + const visit = (dependency) => { + const entry = byLibrary.get(`${dependency.machineName} ${Number(dependency.majorVersion)}`) + if (!entry || ordered.has(entry.folder)) return + ordered.set(entry.folder, entry) + for (const each of entry.preloadedDependencies ?? []) visit(each) } - // 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) { + for (const each of [...roots, ...planned]) visit(each) /** @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 + for (const entry of ordered.values()) selected.set(entry.folder, await pack.open(entry)) + // Planned without the parameters, nothing matches an addon's pattern: what they add are the + // addons, and of what they add, the addons alone, not what an addon would need in turn. + const plain = new Set(plan(undefined).map((entry) => entry.folder)) + const addons = planned.filter((entry) => entry.addTo !== undefined && !plain.has(entry.folder)).map((entry) => `${entry.machineName} ${entry.majorVersion}.${entry.minorVersion}`) + return { selected, addons } } /** @@ -257,9 +172,8 @@ export async function buildPackage(input, output, options = {}) { 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 { entries, main: mainLibrary, translations } = await loadLibraries(pack, source) + const main = mainLibrary.library.machineName const authors = source.authors.map((author) => ({ name: escapeText(author.name), role: author.role })) const generator = new ContentGenerator(entries, { metadata(entry, written, path) { @@ -275,8 +189,6 @@ export async function buildPackage(input, output, options = {}) { } } }) - 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`) @@ -295,7 +207,7 @@ export async function buildPackage(input, output, options = {}) { } } const written = structuredClone(source.params) - for (const place of placesOf(main.machineName, written)) LAYOUTS[place.library]?.before?.(place.params, place.path, context(place.library)) + for (const place of placesOf(main, written)) LAYOUTS[place.library]?.before?.(place.params, place.path, context(place.library)) const content = generator.generate(mainLibrary, written) problems.push(...generator.problems) @@ -311,8 +223,8 @@ export async function buildPackage(input, output, options = {}) { } // 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)) { + for (const place of placesOf(main, content)) LAYOUTS[place.library]?.after?.(place.params, place.path, context(place.library)) + for (const place of placesOf(main, 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) { @@ -320,8 +232,7 @@ export async function buildPackage(input, output, options = {}) { } 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) + const { selected, addons } = await closure(pack, mainLibrary.library, 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. @@ -348,7 +259,7 @@ export async function buildPackage(input, output, options = {}) { 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.appendZip(pack.archiveOf(part), { 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) { diff --git a/packages/author/lib/libraries.mjs b/packages/author/lib/libraries.mjs new file mode 100644 index 00000000..4e211f23 --- /dev/null +++ b/packages/author/lib/libraries.mjs @@ -0,0 +1,106 @@ +import { libraryString } from './generator.mjs' +import { SourceError } from './source-error.mjs' +import { localize, translationFiles } from './translate.mjs' +import { patchSemantics } from './types.mjs' + +/** + * The libraries content brings in, loaded as a build loads them, for the build and for a tool + * beside it that reads or changes content as the build would. No Node import of its own: the pack + * the libraries come from is handed in. + */ + +/** + * A library as a pack's index lists it. + * @typedef {{ folder: string, machineName: string, majorVersion: number, minorVersion: number }} LibraryRecord + */ + +/** + * What libraries are loaded from: the pack `openPack` opens, or any other with these members, such + * as one over a package's own library folders. `newest` is the library served for a machine name + * and a major; `open` reads a library's `library.json` and `semantics.json`, after whatever check + * its source makes, and the names of its translation files, which `translation` reads. + * @typedef {{ + * libraries: LibraryRecord[], + * newest(machineName: string, major?: number): LibraryRecord | null, + * open(entry: LibraryRecord): Promise<{ folder: string, library: any, semantics: any[] | null, translations: string[] }>, + * translation(part: { folder: string }, name: string): Promise + * }} LibrarySource + */ + +/** + * @typedef {import('./generator.mjs').PackEntry} PackEntry + * @typedef {import('./translate.mjs').TranslationReport} TranslationReport + * @typedef {{ entries: Map, main: PackEntry, translations: TranslationReport[] }} LoadedLibraries + * `entries` by folder, the map `ContentGenerator` takes; `main` the content type's; `translations` + * the translation each runnable library's interface texts came from + */ + +/** @param {unknown} value @returns {value is Record} */ +const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) + +/** + * The libraries content brings in, each the newest of its major that the pack has, loaded as the + * build loads them: the content type, every library its parameters name, and every one a library + * field names as its default. Each library's semantics come with the interface texts of its own + * translation for the language and with the fields a layout sets marked optional + * (`patchSemantics`). Every other library of the pack is in the map too, without its semantics. + * @param {LibrarySource} pack + * @param {{ type: string, language: string, params?: unknown }} content `type` a machine name, with + * a major and minor when known, `H5P.Blanks` or `H5P.Blanks 1.14` + * @returns {Promise} + * @throws {SourceError} when the pack has no such content type + */ +export async function loadLibraries(pack, { type, language, params }) { + /** @type {Map} */ + const entries = new Map() + /** @type {TranslationReport[]} */ + const translations = [] + const main = /^(\S+?)(?:\s+(\d+)\.\d+)?$/.exec(String(type).trim()) + const mainEntry = main ? pack.newest(main[1], main[2] === undefined ? undefined : Number(main[2])) : null + if (!mainEntry) throw new SourceError([{ path: 'type', message: `the library pack has no content type ${type}` }]) + /** @type {{ machineName: string, major?: number }[]} */ + 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(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 || entries.has(entry.folder)) continue + const part = await pack.open(entry) + let semantics = part.semantics + if (semantics) { + const files = translationFiles(part.translations, 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) + // By folder, not identity: a source may build its records anew on each call. + if (part.library.runnable || entry.folder === mainEntry.folder) translations.push(localized.report) + 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, main: /** @type {PackEntry} */ (entries.get(mainEntry.folder)), translations } +} diff --git a/packages/author/lib/pack.mjs b/packages/author/lib/pack.mjs index ef05a655..446e8f9c 100644 --- a/packages/author/lib/pack.mjs +++ b/packages/author/lib/pack.mjs @@ -24,11 +24,9 @@ import { Reader, TextWriter, ZipReader } from '@zip.js/zip.js' /** * 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 + * `semantics`), its record in the index, and the names of its translation files, which + * `translation` reads. The part's file stays inside the pack, which copies from it for a build. + * @typedef {{ folder: string, library: any, semantics: any[] | null, index: IndexEntry, translations: string[] }} PartLibrary */ /** @@ -80,15 +78,23 @@ class PartFile extends Reader { } export class Pack { + /** @type {Map>} */ + #opened = new Map() + /** + * Each opened part's file, its reader, and its translation files by name. + * @type {Map, translations: Map }>} + */ + #archives = new Map() + /** @type {string} where the pack came from, for messages */ + #origin + /** * @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() + this.#origin = origin } /** @@ -113,26 +119,33 @@ export class Pack { * @returns {Promise} */ open(entry) { - let opened = this.opened.get(entry.folder) + let opened = this.#opened.get(entry.folder) if (!opened) { opened = this.#open(entry) - this.opened.set(entry.folder, opened) + this.#opened.set(entry.folder, opened) } return opened } - /** @param {IndexEntry} entry */ + /** + * @param {IndexEntry} entry + * @returns {Promise} + */ 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 }) + 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 }) + // Kept before anything is read, so that `close` closes a part that then fails to open. + /** @type {Map} */ + const translations = new Map() + this.#archives.set(entry.folder, { file, reader, translations }) const entries = (await reader.getEntries()).filter((item) => !item.directory && item.filename.startsWith(`${entry.folder}/`)) /** @param {string} name */ const json = async (name) => { @@ -145,21 +158,21 @@ export class Pack { 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 } + for (const item of entries) { + if (item.filename.startsWith(languages) && item.filename.endsWith('.json')) { + translations.set(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: [...translations.keys()] } } /** * A translation file of an opened library, parsed: its `semantics`. - * @param {PartLibrary} part + * @param {{ folder: string }} part * @param {string} name */ async translation(part, name) { - const file = part.translations.get(name) + const file = this.#archives.get(part.folder)?.translations.get(name) if (!file) return undefined try { return JSON.parse(await file.getData(new TextWriter())).semantics @@ -168,21 +181,30 @@ export class Pack { } } - /** Every opened part closed. */ + /** + * The part an opened library came from, as zip.js reads it, for a build to copy its files. + * @param {{ folder: string }} part + * @internal + */ + archiveOf(part) { + const archive = this.#archives.get(part.folder) + if (!archive) throw new Error(`The library part ${part.folder} is not open`) + return archive.file + } + + /** Every opened part closed, each on its own, so that one that fails to close leaves no other open. */ async close() { - for (const opened of this.opened.values()) { + await Promise.allSettled(this.#opened.values()) + await Promise.allSettled([...this.#archives.values()].map(async ({ file, reader }) => { 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. + await reader.close() + } finally { + // A part that failed to open has its file to close, whatever its reader makes of closing. + await file.close() } - } - this.opened.clear() + })) + this.#archives.clear() + this.#opened.clear() } } diff --git a/packages/author/lib/source-error.mjs b/packages/author/lib/source-error.mjs new file mode 100644 index 00000000..2d4f5a35 --- /dev/null +++ b/packages/author/lib/source-error.mjs @@ -0,0 +1,18 @@ +/** + * The error every step of a build throws for what a source got wrong, in a module of its own with + * no Node import, so that the steps that need no Node import of their own can throw it. + */ + +/** + * @typedef {{ path: string, message: string }} Problem + */ + +/** 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 + } +} diff --git a/packages/author/package.json b/packages/author/package.json index d3ba7942..d50106e3 100644 --- a/packages/author/package.json +++ b/packages/author/package.json @@ -42,17 +42,18 @@ "agent-skill" ], "scripts": { - "test": "vitest run", - "test:unit": "vitest run", + "test": "pnpm --filter @missing-elements/h5p-offline-player build:plan && vitest run", + "test:unit": "pnpm --filter @missing-elements/h5p-offline-player build:plan && vitest run", "typecheck": "pnpm types && tsc -p tsconfig.json", "sync:skill": "node scripts/sync-skill.mjs", "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\" && pnpm types", "prepublishOnly": "node -e \"if (!/^pnpm\\//.test(process.env.npm_config_user_agent || '')) { console.error('Publish with pnpm publish: npm would ship the workspace: dependency ranges as they are, and the package would not install.'); process.exit(1) }\" && node scripts/check-pack-published.mjs && pnpm typecheck && pnpm test", - "types": "node -e \"require('node:fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json" + "types": "pnpm --filter @missing-elements/h5p-offline-player exec tsc -b && node -e \"require('node:fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json" }, "dependencies": { "@missing-elements/h5p-libraries": "workspace:*", "@missing-elements/h5p-normalize": "workspace:^", + "@missing-elements/h5p-offline-player": "workspace:*", "@zip.js/zip.js": "^2.24.0" }, "devDependencies": { diff --git a/packages/author/scripts/check-pack-published.mjs b/packages/author/scripts/check-pack-published.mjs index 113c82d9..cfe50372 100644 --- a/packages/author/scripts/check-pack-published.mjs +++ b/packages/author/scripts/check-pack-published.mjs @@ -1,26 +1,42 @@ /** - * Refuses to publish the author package while the library pack it pins is not on npm, or is there - * with another index than this checkout's. The dependency is `workspace:*`, which pnpm publishes - * as the exact version packages/libraries has: after the weekly refresh bumps it, a release made - * before the pack is published would not install, and one built against other parts would check - * them against an index npm does not serve. + * Refuses to publish the author package while what it pins is not on npm. Both pins are + * `workspace:*`, which pnpm publishes as the exact version the workspace has. The library pack: + * after the weekly refresh bumps it, a release made before the pack is published would not + * install, and one built against other parts would check them against an index npm does not + * serve. The player, whose `./plan` the build imports: a release made before the player's would + * not install either, and one pinned to a player published before `./plan` existed would install + * and fail on its first import, so the version on npm has to export it. */ import { readFile } from 'node:fs/promises' import { resolve } from 'node:path' -const libraries = resolve(import.meta.dirname, '..', '..', 'libraries') -const { version } = JSON.parse(await readFile(resolve(libraries, 'package.json'), 'utf8')) +const packages = resolve(import.meta.dirname, '..', '..') +/** @param {string} directory */ +const versionOf = async (directory) => JSON.parse(await readFile(resolve(packages, directory, 'package.json'), 'utf8')).version +const version = await versionOf('libraries') const response = await fetch(`https://registry.npmjs.org/@missing-elements%2fh5p-libraries/${version}`) if (!response.ok) { console.error(`[library-pack] @missing-elements/h5p-libraries@${version} is not on npm (${response.status}). Publish it from packages/libraries first: the author package pins it.`) process.exit(1) } const index = await fetch(`https://cdn.jsdelivr.net/npm/@missing-elements/h5p-libraries@${version}/parts/index.json`) -const local = await readFile(resolve(libraries, 'parts', 'index.json'), 'utf8') +const local = await readFile(resolve(packages, 'libraries', 'parts', 'index.json'), 'utf8') const same = index.ok && JSON.stringify((await index.json()).libraries) === JSON.stringify(JSON.parse(local).libraries) if (!same) { console.error(`[library-pack] @missing-elements/h5p-libraries@${version} on npm has another parts/index.json than this checkout: publish the pack from this checkout, under a new version.`) process.exit(1) } console.log(`[library-pack] @missing-elements/h5p-libraries@${version} is published, with this checkout's index`) + +const player = await versionOf('player') +const published = await fetch(`https://registry.npmjs.org/@missing-elements%2fh5p-offline-player/${player}`) +if (!published.ok) { + console.error(`[player] @missing-elements/h5p-offline-player@${player} is not on npm (${published.status}). Publish it from packages/player first: the author package pins it, for its ./plan.`) + process.exit(1) +} +if (!(await published.json()).exports?.['./plan']) { + console.error(`[player] @missing-elements/h5p-offline-player@${player} on npm does not export ./plan, which the build imports: bump the player's version, publish it, and publish the author package against that.`) + process.exit(1) +} +console.log(`[player] @missing-elements/h5p-offline-player@${player} is published, and exports ./plan`) diff --git a/packages/author/tests/build.test.ts b/packages/author/tests/build.test.ts index c2882b35..caf58652 100644 --- a/packages/author/tests/build.test.ts +++ b/packages/author/tests/build.test.ts @@ -8,7 +8,7 @@ import { promisify } from 'node:util' import { BlobReader, TextWriter, Uint8ArrayWriter, ZipReader } from '@zip.js/zip.js' import { pack } from '@missing-elements/h5p-libraries' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { buildPackage, SourceError } from '../lib/author.mjs' +import { buildPackage, librariesIn, SourceError } from '../lib/author.mjs' import { readSource } from '../lib/build.mjs' import { MediaStore } from '../lib/media.mjs' import { quizProblems } from '../lib/quiz.mjs' @@ -307,6 +307,34 @@ describe('any content type in the pack', () => { expect(manifest.preloadedDependencies.map(({ machineName }: { machineName: string }) => machineName)).toEqual(expect.arrayContaining(['H5P.Column', 'H5P.TrueFalse', 'H5P.AdvancedText'])) }) + it('lists the libraries depth first from the content type, the order the runtime keeps between libraries that do not depend on each other', async () => { + const { content, manifest, files } = await build({ + ...META, + type: 'H5P.Column', + params: { content: [{ content: { library: 'H5P.TrueFalse', params: { question: 'The Rhine reaches the sea.' } } }, { content: { library: 'H5P.AdvancedText', params: { text: 'Done.' } } }] } + }) + // The order the build has always written, from the libraries the zip carries: the content type, + // then each library the content names, each followed by its own dependencies before the next. + const libraries = new Map() + for (const [name, json] of files) { + if (!name.endsWith('/library.json')) continue + const library = JSON.parse(json) + libraries.set(library.machineName, library) + } + const expected: string[] = [] + const visit = (machineName: string) => { + if (expected.includes(machineName)) return + expected.push(machineName) + for (const dependency of libraries.get(machineName)?.preloadedDependencies ?? []) visit(dependency.machineName) + } + for (const name of ['H5P.Column', ...librariesIn(content)]) visit(name.split(' ')[0]) + const listed = manifest.preloadedDependencies.map(({ machineName }: { machineName: string }) => machineName) + expect(listed).toEqual(expected) + // Depth first, not breadth first: True/False's own dependencies come before the text beside it. + const [dependency] = libraries.get('H5P.TrueFalse')!.preloadedDependencies! + expect(listed.indexOf(dependency.machineName)).toBeLessThan(listed.indexOf('H5P.AdvancedText')) + }) + it('adds the formula addon the pack carries when the text holds LaTeX, as a site with it installed exports it', async () => { const { manifest, notes } = await build({ ...META, type: 'H5P.TrueFalse', params: { question: 'Is \\(e^{i\\pi} + 1 = 0\\)?' } }) expect(manifest.preloadedDependencies.map(({ machineName }: { machineName: string }) => machineName)).toContain('H5P.MathDisplay') diff --git a/packages/author/tests/libraries.test.ts b/packages/author/tests/libraries.test.ts new file mode 100644 index 00000000..d58dd9e9 --- /dev/null +++ b/packages/author/tests/libraries.test.ts @@ -0,0 +1,93 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { loadLibraries, openPack, SourceError, type LibrarySource } from '../lib/author.mjs' + +type Field = { name: string, type: string, optional?: boolean, default?: unknown, fields?: Field[], field?: Field } + +let pack: Awaited> +beforeAll(async () => { pack = await openPack() }) +afterAll(async () => { await pack?.close() }) + +/** A field of a library's semantics by its path of names, `visuals.poster`. */ +function fieldAt(semantics: Field[] | null, path: string): Field | undefined { + let fields: Field[] | undefined = semantics ?? undefined + let found: Field | undefined + for (const name of path.split('.')) { + found = fields?.find((field) => field.name === name) + fields = found?.fields ?? found?.field?.fields + } + return found +} + +/** The entry of the map for a machine name. */ +const entryOf = (entries: Map, machineName: string) => + [...entries.values()].find((entry) => entry.library.machineName === machineName) + +describe('loadLibraries', () => { + // Interactive Video with a question written by name alone, in a Column beside a video: what the + // parameters name, what a library field gives as its default, and a layout's patch, all at once. + const content = { + type: 'H5P.Column', + language: 'de', + params: { + content: [ + { content: { library: 'H5P.InteractiveVideo', params: { interactiveVideo: { assets: { interactions: [{ action: { library: 'H5P.MultiChoice', params: {} } }] } } } } }, + { content: { library: 'H5P.Video 1.6', params: {} } } + ] + } + } + + it('loads the content type, what its parameters name and what a library field gives as its default', async () => { + const { entries, main, translations } = await loadLibraries(pack, content) + expect(main.library.machineName).toBe('H5P.Column') + expect(main.semantics).not.toBeNull() + // Named in the parameters, with a version and without one. + for (const name of ['H5P.InteractiveVideo', 'H5P.MultiChoice', 'H5P.Video']) expect(entryOf(entries, name)?.semantics, name).not.toBeNull() + // Interactive Video's summary task, which nobody wrote: its default names H5P.Summary. + expect(entryOf(entries, 'H5P.Summary')?.semantics).not.toBeNull() + // Every other library of the pack is there too, without its semantics. + expect(entryOf(entries, 'H5P.GameMap')).toMatchObject({ semantics: null }) + expect(entries.size).toBe(pack.libraries.length) + // Each runnable library's interface texts, from its own German translation. + expect(translations.find((report) => report.library.startsWith('H5P.InteractiveVideo '))?.translation).toBe('de') + }) + + it('marks the fields a layout sets optional, and leaves the pack\'s own semantics as they are', async () => { + const { entries } = await loadLibraries(pack, content) + expect(fieldAt(entryOf(entries, 'H5P.Video')!.semantics as Field[], 'visuals.poster')?.optional).toBe(true) + const part = await pack.open(pack.newest('H5P.Video')!) + expect(fieldAt(part.semantics, 'visuals.poster')?.optional ?? false).toBe(false) + }) + + it('takes any source with the pack\'s members, such as one over a package\'s own folders', async () => { + const opened: string[] = [] + const source: LibrarySource = { + libraries: pack.libraries, + newest: (machineName, major) => pack.newest(machineName, major), + open: (entry) => { + opened.push(entry.folder) + return pack.open(pack.libraries.find(({ folder }) => folder === entry.folder)!) + }, + translation: (part, name) => pack.translation(part, name) + } + const fromSource = await loadLibraries(source, content) + const fromPack = await loadLibraries(pack, content) + expect(fromSource.entries).toEqual(fromPack.entries) + expect(opened).toContain(fromPack.main.folder) + }) + + it('refuses a content type the pack does not have, as a problem of the source', async () => { + const error = await loadLibraries(pack, { type: 'H5P.Nothing', language: 'en' }).then(() => null, (error: unknown) => error) + expect(error).toBeInstanceOf(SourceError) + expect((error as SourceError).problems).toEqual([{ path: 'type', message: 'the library pack has no content type H5P.Nothing' }]) + }) +}) + +describe('openPack', () => { + it('opens a part to what a reader needs, keeping its file and zip.js\'s reader to itself', async () => { + const part = await pack.open(pack.newest('H5P.Blanks')!) + expect(Object.keys(part).sort()).toEqual(['folder', 'index', 'library', 'semantics', 'translations']) + expect(part.translations).toContain('de') + expect(await pack.translation(part, 'de')).toBeInstanceOf(Array) + expect(await pack.translation(part, 'xx')).toBeUndefined() + }) +}) diff --git a/packages/author/tests/package-types.ts b/packages/author/tests/package-types.ts index 1eb81613..3ed9a9cf 100644 --- a/packages/author/tests/package-types.ts +++ b/packages/author/tests/package-types.ts @@ -1,6 +1,9 @@ // The package as a caller sees it, by its own name: through the `types` condition, so this checks the // published declarations, not the source. `pnpm typecheck` writes them first. -import { buildPackage, ContentGenerator, GENERATED_START, schemaOf, SourceError, type BuildResult, type Source } from '@missing-elements/h5p-author' +import { + allowedTags, buildPackage, ContentGenerator, GENERATED_START, loadLibraries, markupText, openPack, plainText, schemaOf, SourceError, + type BuildResult, type LibraryRecord, type LibrarySource, type Source, type TranslationReport +} from '@missing-elements/h5p-author' // @ts-expect-error The source reader is internal: a helper the tests import from its module. import { readSource } from '@missing-elements/h5p-author' @@ -17,3 +20,26 @@ export async function check(): Promise<[BuildResult, string, string]> { void readSource return [built, await schemaOf('H5P.Blanks', { markdown: true }), GENERATED_START] } + +/** A tool beside the build: the libraries as the build loads them, and its rules for text. */ +export async function beside(): Promise { + const pack = await openPack('parts') + try { + const libraries: LibrarySource = pack + const record: LibraryRecord = pack.libraries[0] + const { entries, main, translations } = await loadLibraries(libraries, { type: 'H5P.Blanks', language: 'de', params: {} }) + const reports: TranslationReport[] = translations + void [record, reports] + const content = new ContentGenerator(entries).generate(main, {}) + const part = await pack.open(pack.libraries[0]) + // @ts-expect-error A part's file stays inside the pack. + void part.file + // @ts-expect-error So does the pack's way to it, which only the build uses. + void pack.archiveOf + const field = (main.semantics ?? [])[0] + const notes: string[] = [] + return [markupText('

Rivers

', field, (message) => notes.push(message)), plainText('Rivers', (message) => notes.push(message)), [...(allowedTags(field) ?? [])].join(' '), JSON.stringify(content)].join('\n') + } finally { + await pack.close() + } +} diff --git a/packages/player/package.json b/packages/player/package.json index 7bc24379..1f90541c 100644 --- a/packages/player/package.json +++ b/packages/player/package.json @@ -28,6 +28,10 @@ "types": "./types/sw/mount.d.ts", "default": "./dist/h5p-sw-mount.js" }, + "./plan": { + "types": "./types/plan.d.ts", + "default": "./dist/h5p-plan.js" + }, "./dist/*": "./dist/*" }, "files": [ @@ -56,7 +60,8 @@ "scripts": { "sync:assets": "node scripts/sync-h5p-assets.mjs", "fixtures": "node scripts/build-fixtures.mjs", - "prepare:dev": "pnpm sync:assets && pnpm fixtures", + "build:plan": "node scripts/build-plan.mjs", + "prepare:dev": "pnpm sync:assets && pnpm fixtures && pnpm build:plan", "build": "pnpm sync:assets && node -e \"for (const p of ['types', 'tsconfig.tsbuildinfo', 'node_modules/.tsc-node']) require('node:fs').rmSync(p, { recursive: true, force: true })\" && tsc -b && vite build && node scripts/build-workers.mjs", "test": "pnpm prepare:dev && vitest run", "test:unit": "vitest run --project unit", diff --git a/packages/player/scripts/build-plan.mjs b/packages/player/scripts/build-plan.mjs new file mode 100644 index 00000000..4e5ec183 --- /dev/null +++ b/packages/player/scripts/build-plan.mjs @@ -0,0 +1,8 @@ +import { resolve } from 'node:path' +import { buildPlanModule } from './lib/worker-bundle.mjs' + +/** + * `dist/h5p-plan.js` on its own, without the rest of `pnpm build`: h5p-author imports it as it + * runs, so `prepare:dev` and h5p-author's tests build it first. + */ +await buildPlanModule(resolve(import.meta.dirname, '..', 'dist', 'h5p-plan.js')) diff --git a/packages/player/scripts/build-workers.mjs b/packages/player/scripts/build-workers.mjs index 72e620d5..9fe8fd80 100644 --- a/packages/player/scripts/build-workers.mjs +++ b/packages/player/scripts/build-workers.mjs @@ -1,7 +1,7 @@ import { readFile, writeFile } from 'node:fs/promises' import { resolve } from 'node:path' import { transform } from 'esbuild' -import { buildJobsWorker, buildMountModule, buildServiceWorker, playerNotice } from './lib/worker-bundle.mjs' +import { buildJobsWorker, buildMountModule, buildPlanModule, buildServiceWorker, playerNotice } from './lib/worker-bundle.mjs' /** * Builds the artefacts Vite's library build cannot produce. @@ -10,7 +10,8 @@ import { buildJobsWorker, buildMountModule, buildServiceWorker, playerNotice } f * URL and has to run on a site with no build step at all. `dist/h5p-sw-mount.js` is the same * handlers as an ES module, for hosts that enforce a single worker per origin and mount ours * into theirs. `dist/h5p-jobs.js` is the Jobs worker the element otherwise spawns from a `blob:` - * URL, for a page whose policy does not allow one. + * URL, for a page whose policy does not allow one. `dist/h5p-plan.js` is the player's library + * rules, `./plan`, for the packages that write what it plays. */ const rootDir = resolve(import.meta.dirname, '..') @@ -19,6 +20,7 @@ const distDir = resolve(rootDir, 'dist') await buildServiceWorker(resolve(distDir, 'h5p-sw.js')) await buildMountModule(resolve(distDir, 'h5p-sw-mount.js')) await buildJobsWorker(resolve(distDir, 'h5p-jobs.js')) +await buildPlanModule(resolve(distDir, 'h5p-plan.js')) // Vite leaves an ES library's whitespace and comments alone on purpose: esbuild drops the // `/* @__PURE__ */` annotations when it minifies whitespace, and a consumer's bundler tree-shakes @@ -43,4 +45,4 @@ await writeFile( 'utf8' ) -console.log(`[build-workers] ${await sizeOf('h5p-player.js')} (minified after Vite), ${await sizeOf('h5p-sw.js')}, ${await sizeOf('h5p-sw-mount.js')}, ${await sizeOf('h5p-jobs.js')}`) +console.log(`[build-workers] ${await sizeOf('h5p-player.js')} (minified after Vite), ${await sizeOf('h5p-sw.js')}, ${await sizeOf('h5p-sw-mount.js')}, ${await sizeOf('h5p-jobs.js')}, ${await sizeOf('h5p-plan.js')}`) diff --git a/packages/player/scripts/lib/worker-bundle.mjs b/packages/player/scripts/lib/worker-bundle.mjs index 9e4a0571..ec99b6cb 100644 --- a/packages/player/scripts/lib/worker-bundle.mjs +++ b/packages/player/scripts/lib/worker-bundle.mjs @@ -94,6 +94,20 @@ export async function buildJobsWorker(outfile) { return build({ ...options, banner: { js: await playerNotice() }, plugins: [], entryPoints: [resolve(rootDir, 'src/jobs/jobs-worker.ts')], outfile, format: 'iife' }) } +/** + * `h5p-plan.js`: the player's library rules (`src/plan.ts`) as an ES module, for the packages that + * write what it plays, in Node or a page. Not minified, so that a stack trace in a caller names the + * function; it is a few kilobytes. It must stay free of zip.js, which a careless import of + * `package-reader.ts` would bring along with its side effects, so the build fails on one. + */ +export async function buildPlanModule(outfile) { + const { banner, plugins, minify, ...options } = await shared() + const result = await build({ ...options, platform: 'neutral', banner: { js: await playerNotice() }, plugins: [], metafile: true, entryPoints: [resolve(rootDir, 'src/plan.ts')], outfile, format: 'esm' }) + const zipJs = Object.keys(result.metafile.inputs).find((input) => input.includes('@zip.js')) + if (zipJs) throw new Error(`[plan] dist/h5p-plan.js must not bundle zip.js, and imports ${zipJs}`) + return result +} + /** * Resolves `@missing-elements/h5p-offline-player/sw` to the mount's source, the way the demo's * Vite config resolves the element's name, so a worker in this repository imports the handlers diff --git a/packages/player/src/plan.ts b/packages/player/src/plan.ts new file mode 100644 index 00000000..3e8efae9 --- /dev/null +++ b/packages/player/src/plan.ts @@ -0,0 +1,12 @@ +/** + * `@missing-elements/h5p-offline-player/plan`: the player's rules for the libraries a package plays + * with, for the packages that write what it plays, so that they run the player's own rules rather + * than copies of them: which libraries content names, an addon's patterns and what they match, and + * which parts of the library pack a package needs. Pure and free of zip.js, for Node and a page + * alike. Not named in docs/compatibility.md, so it may change in any release: a package that + * imports it depends on an exact version of the player. + */ + +export { addonPatterns, dependenciesIn, librariesNamedIn, textMatches, type LibraryDependency } from './shared/content-libraries.js' +export { planPack, type OwnLibrary, type PlanInput, type ProvidedLibrary } from './sw/pack-plan.js' +export type { PackDependency, PackLibrary, PackPart, PackPlan, RefreshedLibrary } from './shared/protocol.js' diff --git a/packages/player/src/shared/content-libraries.ts b/packages/player/src/shared/content-libraries.ts new file mode 100644 index 00000000..ac3c4e11 --- /dev/null +++ b/packages/player/src/shared/content-libraries.ts @@ -0,0 +1,91 @@ +/** + * Which libraries a package's `h5p.json`, its `library.json` files and its content's parameters + * name, and which addons go with the content. Pure and free of zip.js, so that the pack plan + * (`sw/pack-plan.ts`) and the packages that write what the player plays, through `./plan`, take + * the player's own rules without its archive reader. + */ + +export interface LibraryDependency { + machineName: string + majorVersion: string | number + minorVersion: string | number +} + +/** + * Every library a content's parameters name, as sub-content does it: an object whose `library` + * is `" ."`, anywhere in the tree. In archive order of discovery, + * each once. Pure, and the parameters are untrusted, so anything else is ignored. + */ +export function librariesNamedIn(params: unknown): LibraryDependency[] { + const found = new Map() + const walk = (value: unknown, depth: number) => { + if (depth > 64 || !value || typeof value !== 'object') return + if (Array.isArray(value)) { + for (const item of value) walk(item, depth + 1) + return + } + const library = (value as { library?: unknown }).library + if (typeof library === 'string') { + const match = /^([A-Za-z0-9_.-]+) (\d+)\.(\d+)$/.exec(library) + if (match && !found.has(match[1])) { + found.set(match[1], { machineName: match[1], majorVersion: Number(match[2]), minorVersion: Number(match[3]) }) + } + } + for (const child of Object.values(value)) walk(child, depth + 1) + } + walk(params, 0) + return [...found.values()] +} + +/** + * The patterns an addon's `library.json` gives under `addTo.content.types[].text.regex`, PHP's + * `/…/flags` form made JavaScript's. A pattern JavaScript cannot read is left out, and so is one + * with a flag it has no counterpart for. + */ +export function addonPatterns(library: unknown): RegExp[] { + const types = (library as { addTo?: { content?: { types?: unknown } } } | null)?.addTo?.content?.types + if (!Array.isArray(types)) return [] + + const patterns: RegExp[] = [] + for (const type of types) { + const source = (type as { text?: { regex?: unknown } } | null)?.text?.regex + if (typeof source !== 'string' || source.length < 2) continue + // PCRE takes any delimiter that is not a letter, a digit, a backslash or a space; the + // bracket pairs are left out, as no addon uses them. + const delimiter = source[0] + if (/[\p{L}\p{N}\\\s([{<]/u.test(delimiter)) continue + const end = source.lastIndexOf(delimiter) + const flags = source.slice(end + 1) + if (end < 1 || /[^imsu]/.test(flags)) continue + try { + patterns.push(new RegExp(source.slice(1, end), flags)) + } catch { + // PCRE that JavaScript does not read. + } + } + return patterns +} + +/** + * Whether a string anywhere in the parameters matches one of the patterns: upstream's + * `textAddonMatches`. The parameters are untrusted, so the walk is bounded in depth. + */ +export function textMatches(params: unknown, patterns: RegExp[]): boolean { + const walk = (value: unknown, depth: number): boolean => { + if (typeof value === 'string') return patterns.some((pattern) => pattern.test(value)) + if (depth > 64 || !value || typeof value !== 'object') return false + return Object.values(value).some((child) => walk(child, depth + 1)) + } + return patterns.length > 0 && walk(params, 0) +} + +/** The well-formed entries of a manifest's or a `library.json`'s `preloadedDependencies`. */ +export function dependenciesIn(value: unknown): LibraryDependency[] { + const dependencies = (value as { preloadedDependencies?: unknown } | null)?.preloadedDependencies + if (!Array.isArray(dependencies)) return [] + const version = (part: unknown) => typeof part === 'number' || (typeof part === 'string' && /^\d+$/.test(part)) + return dependencies.filter( + (dependency): dependency is LibraryDependency => + typeof dependency?.machineName === 'string' && version(dependency.majorVersion) && version(dependency.minorVersion) + ) +} diff --git a/packages/player/src/sw/library-load.ts b/packages/player/src/sw/library-load.ts index 6741b8bd..9794da20 100644 --- a/packages/player/src/sw/library-load.ts +++ b/packages/player/src/sw/library-load.ts @@ -1,5 +1,6 @@ import type { LibraryLoad } from '../shared/protocol.js' -import { dependenciesIn, type LibraryDependency, type PackageManifest } from './package-reader.js' +import { dependenciesIn, type LibraryDependency } from '../shared/content-libraries.js' +import type { PackageManifest } from './package-reader.js' /** * What the frame loads, and in what order: every library the content needs, its scripts and its diff --git a/packages/player/src/sw/mount.ts b/packages/player/src/sw/mount.ts index 54ca4eea..3e485cb4 100644 --- a/packages/player/src/sw/mount.ts +++ b/packages/player/src/sw/mount.ts @@ -41,7 +41,8 @@ import { import { contentRange, parseRange, type ByteRange } from '../shared/range.js' import { openSource } from '../shared/source.js' import * as db from '../shared/idb.js' -import { type IndexedEntry, type LocatedEntry, PackageReader, dependenciesIn, explainMissingLibraries, libraryFolderNames, locationOf } from './package-reader.js' +import { dependenciesIn } from '../shared/content-libraries.js' +import { type IndexedEntry, type LocatedEntry, PackageReader, explainMissingLibraries, libraryFolderNames, locationOf } from './package-reader.js' import { libraryLoad, walkLibraries } from './library-load.js' import { STORED } from '../shared/local-header.js' import { CONTENT_CHECK_HEADER, buildFrameDocument, createNonce } from './frame-document.js' diff --git a/packages/player/src/sw/pack-plan.ts b/packages/player/src/sw/pack-plan.ts index af4eb146..cde09250 100644 --- a/packages/player/src/sw/pack-plan.ts +++ b/packages/player/src/sw/pack-plan.ts @@ -1,5 +1,5 @@ import type { PackDependency, PackLibrary, PackPart, PackPlan, RefreshedLibrary } from '../shared/protocol.js' -import { addonPatterns, textMatches } from './package-reader.js' +import { addonPatterns, textMatches } from '../shared/content-libraries.js' /** * Which parts of the library pack a package needs, and which of its own library folders the diff --git a/packages/player/src/sw/package-reader.ts b/packages/player/src/sw/package-reader.ts index eda7871b..7d4a1b0b 100644 --- a/packages/player/src/sw/package-reader.ts +++ b/packages/player/src/sw/package-reader.ts @@ -19,6 +19,7 @@ import { deferredStream, inflated } from '../shared/stream-utils.js' import type { ForwardEntry, ForwardIndexSnapshot } from '../shared/forward-index.js' import { indexFingerprint, librariesFingerprint, revisionOf } from '../shared/revision.js' import { contentMetadata, type ContentMetadata } from '../shared/metadata.js' +import { addonPatterns, dependenciesIn, librariesNamedIn, textMatches, type LibraryDependency } from '../shared/content-libraries.js' import type { OwnLibrary } from './pack-plan.js' /** @@ -42,12 +43,6 @@ export interface PackageManifest { preloadedDependencies?: LibraryDependency[] } -export interface LibraryDependency { - machineName: string - majorVersion: string | number - minorVersion: string | number -} - /** A library that names, in its `library.json`'s `addTo`, the content the platforms add it to. */ export interface Addon extends LibraryDependency { patterns: RegExp[] @@ -1039,85 +1034,6 @@ async function readManifest(reader: PackageReader): Promise { } } -/** - * Every library a content's parameters name, as sub-content does it: an object whose `library` - * is `" ."`, anywhere in the tree. In archive order of discovery, - * each once. Pure, and the parameters are untrusted, so anything else is ignored. - */ -export function librariesNamedIn(params: unknown): LibraryDependency[] { - const found = new Map() - const walk = (value: unknown, depth: number) => { - if (depth > 64 || !value || typeof value !== 'object') return - if (Array.isArray(value)) { - for (const item of value) walk(item, depth + 1) - return - } - const library = (value as { library?: unknown }).library - if (typeof library === 'string') { - const match = /^([A-Za-z0-9_.-]+) (\d+)\.(\d+)$/.exec(library) - if (match && !found.has(match[1])) { - found.set(match[1], { machineName: match[1], majorVersion: Number(match[2]), minorVersion: Number(match[3]) }) - } - } - for (const child of Object.values(value)) walk(child, depth + 1) - } - walk(params, 0) - return [...found.values()] -} - -/** - * The patterns an addon's `library.json` gives under `addTo.content.types[].text.regex`, PHP's - * `/…/flags` form made JavaScript's. A pattern JavaScript cannot read is left out, and so is one - * with a flag it has no counterpart for. - */ -export function addonPatterns(library: unknown): RegExp[] { - const types = (library as { addTo?: { content?: { types?: unknown } } } | null)?.addTo?.content?.types - if (!Array.isArray(types)) return [] - - const patterns: RegExp[] = [] - for (const type of types) { - const source = (type as { text?: { regex?: unknown } } | null)?.text?.regex - if (typeof source !== 'string' || source.length < 2) continue - // PCRE takes any delimiter that is not a letter, a digit, a backslash or a space; the - // bracket pairs are left out, as no addon uses them. - const delimiter = source[0] - if (/[\p{L}\p{N}\\\s([{<]/u.test(delimiter)) continue - const end = source.lastIndexOf(delimiter) - const flags = source.slice(end + 1) - if (end < 1 || /[^imsu]/.test(flags)) continue - try { - patterns.push(new RegExp(source.slice(1, end), flags)) - } catch { - // PCRE that JavaScript does not read. - } - } - return patterns -} - -/** - * Whether a string anywhere in the parameters matches one of the patterns: upstream's - * `textAddonMatches`. The parameters are untrusted, so the walk is bounded in depth. - */ -export function textMatches(params: unknown, patterns: RegExp[]): boolean { - const walk = (value: unknown, depth: number): boolean => { - if (typeof value === 'string') return patterns.some((pattern) => pattern.test(value)) - if (depth > 64 || !value || typeof value !== 'object') return false - return Object.values(value).some((child) => walk(child, depth + 1)) - } - return patterns.length > 0 && walk(params, 0) -} - -/** The well-formed entries of a manifest's or a `library.json`'s `preloadedDependencies`. */ -export function dependenciesIn(value: unknown): LibraryDependency[] { - const dependencies = (value as { preloadedDependencies?: unknown } | null)?.preloadedDependencies - if (!Array.isArray(dependencies)) return [] - const version = (part: unknown) => typeof part === 'number' || (typeof part === 'string' && /^\d+$/.test(part)) - return dependencies.filter( - (dependency): dependency is LibraryDependency => - typeof dependency?.machineName === 'string' && version(dependency.majorVersion) && version(dependency.minorVersion) - ) -} - /** * A dependency served at an older minor than it asks for, as `checkDependencies` reports it: only * from a versioned folder of the same major, the one a downgrade picks. A folder named without a diff --git a/packages/player/tests/package-types.ts b/packages/player/tests/package-types.ts index 8db6f9ec..91487af6 100644 --- a/packages/player/tests/package-types.ts +++ b/packages/player/tests/package-types.ts @@ -8,11 +8,18 @@ */ import { H5PPlayerElement, type PackageMetadata, type PlayerErrorDetail, type ReadyDetail } from '@missing-elements/h5p-offline-player' import { mountH5P } from '@missing-elements/h5p-offline-player/sw' +import { librariesNamedIn, planPack, type PackPlan } from '@missing-elements/h5p-offline-player/plan' export function asACallerWould(worker: ServiceWorkerGlobalScope): string[] { const player: H5PPlayerElement | null = document.querySelector('h5p-player') mountH5P(worker, { scope: '/h5p/' }) + // The library rules, as h5p-author runs them. + const roots = librariesNamedIn({ library: 'H5P.Blanks 1.14' }).map(({ machineName, majorVersion, minorVersion }) => ({ machineName, majorVersion: Number(majorVersion), minorVersion: Number(minorVersion) })) + const plan: PackPlan | null = planPack({ own: [], provided: [], roots, params: {}, pack: [], refresh: false, fill: true }) + // @ts-expect-error the parts are a list + const parts: PackPlan['parts'] = 'H5P.Blanks-1.14' + // @ts-expect-error not an error code const code: PlayerErrorDetail['code'] = 'offline' // @ts-expect-error the folders are a list @@ -22,6 +29,6 @@ export function asACallerWould(worker: ServiceWorkerGlobalScope): string[] { // @ts-expect-error the title is a string const title: PackageMetadata['title'] = 1 - void [player, code, folders, source, title] + void [player, code, folders, source, title, plan, parts] return player?.libraryBundle?.refreshed?.map(({ library, to }) => `${library} ${to}`) ?? [] } diff --git a/packages/player/tests/unit/library-load.test.ts b/packages/player/tests/unit/library-load.test.ts index a7c612cd..b670b08e 100644 --- a/packages/player/tests/unit/library-load.test.ts +++ b/packages/player/tests/unit/library-load.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { filesIn, libraryLoad, loadOrder, toposort, walkLibraries, type LibraryLookup } from '../../src/sw/library-load' -import type { LibraryDependency } from '../../src/sw/package-reader' +import type { LibraryDependency } from '../../src/shared/content-libraries' /** * The order the frame loads libraries in has to be h5p-standalone's, which every content type has diff --git a/packages/player/tests/unit/merged-manifest.test.ts b/packages/player/tests/unit/merged-manifest.test.ts index 58998432..fddfc3e8 100644 --- a/packages/player/tests/unit/merged-manifest.test.ts +++ b/packages/player/tests/unit/merged-manifest.test.ts @@ -1,6 +1,7 @@ import { memoryHandle, zipOf } from './helpers/archives' import { describe, expect, it } from 'vitest' -import { PackageReader, addonPatterns, librariesNamedIn, textMatches } from '../../src/sw/package-reader' +import { addonPatterns, librariesNamedIn, textMatches } from '../../src/shared/content-libraries' +import { PackageReader } from '../../src/sw/package-reader' import type { SourceHandle } from '../../src/shared/source' /** diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dc94b7be..b0312d1a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -93,6 +93,9 @@ importers: '@missing-elements/h5p-normalize': specifier: workspace:^ version: link:../normalize + '@missing-elements/h5p-offline-player': + specifier: workspace:* + version: link:../player '@zip.js/zip.js': specifier: ^2.24.0 version: 2.24.0