diff --git a/AGENTS.md b/AGENTS.md index 160b9bc2..47b0d8ce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,6 +93,8 @@ packages/player/ @missing-elements/h5p-offline-player — the published utils.ts its helpers — play and settle, waitForEvent with a filter, inject, the fixture's message and button — which a test uses rather than retyping tests/fixtures/src/ the source of the generated .h5p archives + tests/package-types.ts the published declarations as a caller on `nodenext` sees them, checked by + tsconfig.consumer.json (see *Types for the plain-JS packages*) public/ generated, not in git: the runtime's dist/ as frame-assets/, and the test fixtures NOTICE.md zip.js's notice, and where the runtime went; shipped with the package @@ -145,12 +147,17 @@ packages/normalize/ @missing-elements/h5p-normalize — the package rewrit bin/h5p-normalize.mjs the command lib/ normalize.mjs (the policy), mp4-faststart.mjs (the remux), zip-writer.mjs, crc32.mjs, format.mjs, fingerprint.mjs (the player's `indexFingerprint` for Node) - tests/ node tests; tests/helpers/mp4.ts builds structurally honest mp4s + tests/ node tests; tests/helpers/mp4.ts builds structurally honest mp4s; + package-types.ts the package by its name as a TypeScript caller sees it + types/ generated, not in git: the declarations, from the JSDoc (`pnpm types`; + see *Types for the plain-JS packages*) packages/verify/ @missing-elements/h5p-verify — plays a package headless and reports whether it works bin/h5p-verify.mjs the command lib/verify.mjs the static server, the browser run and the report; lib/page.html the page it drives - tests/ node tests that run the real thing against the demo's committed content + tests/ node tests that run the real thing against the demo's committed content; + package-types.ts as for the normalizer + types/ generated, not in git: the declarations, `VerifyReport` among them 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 @@ -174,7 +181,9 @@ packages/embed/ @missing-elements/h5p-embed — the embed page as a st page, the headers for five kinds of host and NOTICE.txt bin/h5p-embed.mjs the command tests/ build.test.ts, no browser; site.test.ts, a written site on 127.0.0.1 - framed by a page on localhost, as deployed + framed by a page on localhost, as deployed; package-types.ts as for the + normalizer + types/ generated, not in git: the declarations of both entries apps/demo/ the demo app: the dev server for the whole repository, and the hosted site index.html the hosted player page @@ -1702,6 +1711,41 @@ 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. +## Types for the plain-JS packages + +The normalizer, the verifier and the embed package 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` +writes them, deleting the folder first, since `tsc` never removes a declaration whose source +went; `typecheck` and `prepack` both run it. Three things learned writing them, with TypeScript 7: + +- **A top-level `@typedef` is always exported**, and `@internal` on one does not strip it. Worse, + its comment counts among the leading comments of the next declaration, which `stripInternal` + then drops: an `@internal` typedef above a public function took the function out of the + declarations and left the typedef in. A type only the code needs is written inline, derived + (`ReturnType`), or declared inside the function that uses it, where it is + local. `@internal` goes on functions and classes only: the helpers each entry exports for its + tests (`contentChanges`, `parseOrigin`, `orderEntries` and the rest). +- **`tests/package-types.ts` imports the package by its own name**, so it resolves through the + `types` condition. Without `types/`, TypeScript falls back to the JavaScript through `default` + and finds the internal helper, so the file's `@ts-expect-error` on that import fails: the check + cannot pass on anything but the published declarations. +- **The player's relative imports name their file, `./shared/protocol.js`**, as cmi5's do. + `tsc` copies a specifier into the declarations as written, and `node16`/`nodenext` resolution + follows only one that names its file, so up to 1.1.0 what came through `types/`'s own imports — + `PlayerErrorDetail['code']`, `missingLibraries`, `ReadyDetail['source']` — was `any` to such a + caller with `skipLibCheck`, and an error without it; under `bundler` everything was typed. + Found on 2026-10-21 installing the packed tarballs into a fresh project, and fixed in #65. + Vite and esbuild take `.js` to the `.ts` beside it, so the bundles are the same code (only the + minifier's names moved, since it picks them by the source's character frequency). + `tests/package-types.ts` is the player's check, compiled by `tsconfig.consumer.json` on + `nodenext` with `skipLibCheck` off — `skipDefaultLibCheck` on, since the DOM and WebWorker libs + clash when checked together — and kept out of `tsconfig.test.json`, where the source's + `H5PPlayerElement` would meet the declarations' one. `sync-h5p-assets` writes the `.js` into + the generated `pack-index.ts` too. The player's bundler resolution says nothing about a new + import without one: the check catches it only where the public types reach it. + ## The content-type sweep `pnpm sweep` (`apps/demo/scripts/sweep-content-types.mjs`) plays every runnable library in the diff --git a/docs/compatibility.md b/docs/compatibility.md index ebda9561..6ebfcba4 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -88,7 +88,7 @@ What is covered of the pack itself: the `pack` export, `parts/` with its `index. [README](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/embed#readme) lists them: what a snippet, or a page that reads `report`, is built on. - **`buildSite()`**, the command as a function, and **`startEmbed()`**, the page as one, with - their options; and `resizer.js`, which speaks H5P's own resizer protocol. + their options and their types; and `resizer.js`, which speaks H5P's own resizer protocol. A written site is a folder of copies and changes only when it is written again: upgrading is running the new version of the command and deploying the folder. @@ -102,14 +102,15 @@ with the specification is a conformance fix. ### The normalizer, `@missing-elements/h5p-normalize` -The command's options, and `normalizeArchive()`, `formatBytes()` and `archiveFingerprint()`. The -content of a package it rewrites never changes. How it lays out the zip may change in a minor, as +The command's options, and `normalizeArchive()`, `formatBytes()` and `archiveFingerprint()`, with +their types. The content of a package it rewrites never changes. How it lays out the zip may change in a minor, as long as the player streams the result at least as well. ### The verifier, `@missing-elements/h5p-verify` The command's options, its exit codes — 0 plays, 1 does not, 2 could not run — `report.json`, to -which fields may be added, and `verifyPackage()` and `summarize()`. The verifier is a step in other +which fields may be added, and `verifyPackage()` and `summarize()`, with their types: `VerifyReport` +is `report.json`'s shape, and gains fields the same way. The verifier is a step in other people's pipelines, so a check that turns a pass into a fail comes in a minor, never a patch; a new warning can come in any release. diff --git a/packages/embed/README.md b/packages/embed/README.md index 66b8deae..21d0f7be 100644 --- a/packages/embed/README.md +++ b/packages/embed/README.md @@ -138,6 +138,7 @@ export, which `libraries=pack` then plays from) or `packBase` (the folder of a c `@missing-elements/h5p-runtime` export, for a bundled element) and `askInOwnFrame` (default `true`; `false` plays a package from another origin as it is when a same-origin page frames it). `librariesPack`, the URL of a whole `libraries.h5p`, still works, as a bundle that only fills gaps. +Both entries ship with TypeScript declarations. ```js import '@missing-elements/h5p-offline-player' diff --git a/packages/embed/lib/build.mjs b/packages/embed/lib/build.mjs index 3734011b..90bf3db5 100644 --- a/packages/embed/lib/build.mjs +++ b/packages/embed/lib/build.mjs @@ -23,7 +23,11 @@ const PAGE_FILES = ['embed.js', 'embed.css', 'main.js', 'resizer.js'] /** The player's files, by the names the element looks for beside itself. */ const PLAYER_FILES = ['h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js'] -/** Where an installed package's file is, or a message that says which one is missing. */ +/** + * Where an installed package's file is, or a message that says which one is missing. + * @param {string} specifier + * @param {string} hint + */ function installed(specifier, hint) { try { return require.resolve(specifier) @@ -39,6 +43,9 @@ function installed(specifier, hint) { * CSP host is, letters, digits and hyphens between dots: the URL parser takes `*`, `;` and `"` in * a host, and a wildcard would allow what the page then refuses, by exact origin, on every load, * while a quote would end the policy in the files that quote it (#58). + * @internal + * @param {string} value + * @returns {string} */ export function parseOrigin(value) { let url @@ -65,6 +72,7 @@ const PACK_CDN_ORIGIN = 'https://cdn.jsdelivr.net' * A `libraries` value for addresses that name none, checked against the site it goes into: the * tokens the page understands (`pack`, `none`, https URLs), and with a host list, nothing * the page would then refuse on every load. Returns the value normalised to single spaces. + * @internal * * @param {string | null | undefined} value * @param {object} [site] @@ -103,7 +111,12 @@ export function parseDefaultLibraries(value, { packages = null, libraries = true return tokens.join(' ') } -/** Origins given as a list, or as one string separated by commas or whitespace. */ +/** + * Origins given as a list, or as one string separated by commas or whitespace. + * @internal + * @param {string[] | string | null | undefined} values + * @returns {string[] | null} + */ export function parseOrigins(values) { if (values == null) return null const list = (Array.isArray(values) ? values : [values]).flatMap((value) => String(value).split(/[\s,]+/)).filter(Boolean) @@ -117,6 +130,7 @@ export function parseOrigins(values) { * it — and names who may frame the page; without it any site may. */ /** + * @internal * @param {object} [options] * @param {string[] | null} [options.packages] * @param {string[] | null} [options.ancestors] @@ -140,7 +154,11 @@ export function contentSecurityPolicy({ packages = null, ancestors = null, meta return directives.join('; ') } -/** Header rules, one set for every host format: the policy everywhere, and the caching that matters. */ +/** + * Header rules, one set for every host format: the policy everywhere, and the caching that matters. + * @param {string} csp + * @returns {{ path: string, headers: Record }[]} + */ function headerRules(csp) { const revalidate = 'public, max-age=3600, stale-while-revalidate=86400' // Asked again on every load, a 304 when nothing changed. The runtime's files keep their names @@ -167,13 +185,20 @@ function headerRules(csp) { ] } -/** Netlify's and Cloudflare Pages' `_headers`. */ +/** + * Netlify's and Cloudflare Pages' `_headers`. + * @param {ReturnType} rules + */ function netlifyHeaders(rules) { return rules.map(({ path, headers }) => `${path}\n${Object.entries(headers).map(([key, value]) => ` ${key}: ${value}`).join('\n')}`).join('\n') + '\n' } -/** Vercel's `vercel.json`, for deploying the folder as a project of its own. */ +/** + * Vercel's `vercel.json`, for deploying the folder as a project of its own. + * @param {ReturnType} rules + */ function vercelConfig(rules) { + /** @param {string} path */ const source = (path) => (path === '/*' ? '/(.*)' : path.replace(/\*$/, '(.*)')) return JSON.stringify( { headers: rules.map(({ path, headers }) => ({ source: source(path), headers: Object.entries(headers).map(([key, value]) => ({ key, value })) })) }, @@ -190,13 +215,19 @@ function vercelConfig(rules) { * in every format, which is safe because the policy carries only single quotes. */ -/** The rule for every path, and the ones for a single path or prefix. */ +/** + * The rule for every path, and the ones for a single path or prefix. + * @param {ReturnType} rules + */ function splitRules(rules) { - const all = rules.find((rule) => rule.path === '/*') + const all = /** @type {ReturnType[number]} */ (rules.find((rule) => rule.path === '/*')) return { all, specific: rules.filter((rule) => rule !== all) } } -/** Caddy's `Caddyfile`: a site block to run as it is, or to paste into one. */ +/** + * Caddy's `Caddyfile`: a site block to run as it is, or to paste into one. + * @param {ReturnType} rules + */ function caddyfile(rules) { const { all, specific } = splitRules(rules) const lines = [ @@ -216,10 +247,13 @@ function caddyfile(rules) { * nginx: a file to `include` inside the `server` block that serves the folder. nginx's * `add_header` in a `location` replaces every `add_header` inherited from the server level * rather than adding to it, so each location repeats the headers that apply everywhere. + * @param {ReturnType} rules */ function nginxConf(rules) { const { all, specific } = splitRules(rules) + /** @param {[string, string]} entry */ const header = ([key, value]) => `add_header ${key} "${value}" always;` + /** @param {string} path */ const matcher = (path) => (path.endsWith('/*') ? `^~ ${path.slice(0, -1)}` : `= ${path}`) const lines = [ '# Written by h5p-embed. Include this file inside the server block that serves the folder:', @@ -235,10 +269,15 @@ function nginxConf(rules) { return lines.join('\n') + '\n' } -/** Apache's `.htaccess`, for a folder under a vhost that allows it. */ +/** + * Apache's `.htaccess`, for a folder under a vhost that allows it. + * @param {ReturnType} rules + */ function htaccess(rules) { const { all, specific } = splitRules(rules) + /** @param {[string, string]} entry */ const header = ([key, value]) => `Header always set ${key} "${value}"` + /** @param {ReturnType[number]} rule */ const block = ({ path, headers }) => { const body = Object.entries(headers).map((entry) => `\t${header(entry)}`).join('\n') // matches a name in any directory; a prefix needs the request URI, with no anchor at @@ -256,6 +295,7 @@ function htaccess(rules) { return lines.join('\n') + '\n' } +/** @param {{ version: string, libraries: boolean }} site */ function notice({ version, libraries }) { return `This folder is the H5P embed page, written by @missing-elements/h5p-embed. @@ -283,7 +323,10 @@ https://github.com/missing-elements/h5p-offline-player/tree/main/packages/embed ` } -/** Whether a directory exists and has anything in it. A path that is a file is an error. */ +/** + * Whether a directory exists and has anything in it. A path that is a file is an error. + * @param {string} dir + */ async function occupied(dir) { let info try { @@ -295,6 +338,19 @@ async function occupied(dir) { return (await readdir(dir)).length > 0 } +/** + * What `buildSite` wrote, for a summary. + * @typedef {object} BuiltSite + * @property {string} out the folder, as an absolute path + * @property {string} version the player's version, as its `dist/VERSION` says + * @property {string} csp the policy the headers carry + * @property {boolean} libraries whether the site carries the library pack's parts + * @property {string[] | null} packages the origins packages may come from; `null` for any + * @property {string[] | null} ancestors the origins that may frame the page; `null` for any + * @property {string | null} defaultLibraries the `libraries` value for addresses that name none + * @property {number} size the folder's size in bytes + */ + /** * Writes the site into `out`. Refuses a folder that already has files in it unless `force`, and * even then only replaces the files it writes, so pointing it at the wrong folder costs nothing @@ -307,6 +363,7 @@ async function occupied(dir) { * @param {string[] | string | null} [options.ancestors] the only origins that may frame the page * @param {string | null} [options.defaultLibraries] the `libraries` value for addresses that name none * @param {boolean} [options.force] + * @returns {Promise} */ export async function buildSite({ out, libraries = true, packages = null, ancestors = null, defaultLibraries = null, force = false }) { if (!out) throw new EmbedError('No output folder given.') @@ -372,6 +429,7 @@ export async function buildSite({ out, libraries = true, packages = null, ancest /** * The folder's size in bytes, for the summary. Paths from a recursive `readdir` rather than * `Dirent.parentPath`, which Node 20 has only from 20.12. + * @param {string} dir */ async function sizeOf(dir) { let total = 0 diff --git a/packages/embed/package.json b/packages/embed/package.json index c2b7714c..9a616abc 100644 --- a/packages/embed/package.json +++ b/packages/embed/package.json @@ -20,8 +20,14 @@ "h5p-embed": "./bin/h5p-embed.mjs" }, "exports": { - ".": "./lib/build.mjs", - "./embed.js": "./site/embed.js", + ".": { + "types": "./types/lib/build.d.mts", + "default": "./lib/build.mjs" + }, + "./embed.js": { + "types": "./types/site/embed.d.ts", + "default": "./site/embed.js" + }, "./embed.css": "./site/embed.css", "./resizer.js": "./site/resizer.js", "./package.json": "./package.json" @@ -29,7 +35,8 @@ "files": [ "bin", "lib", - "site" + "site", + "types" ], "keywords": [ "h5p", @@ -44,9 +51,10 @@ ], "scripts": { "test": "pnpm --filter @missing-elements/h5p-offline-player build && vitest run", - "typecheck": "tsc -p tsconfig.json", - "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\"", - "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) }\" && pnpm typecheck && pnpm test" + "typecheck": "pnpm types && tsc -p tsconfig.json", + "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) }\" && pnpm typecheck && pnpm test", + "types": "node -e \"require('node:fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json" }, "dependencies": { "@missing-elements/h5p-libraries": "workspace:^", diff --git a/packages/embed/site/embed.js b/packages/embed/site/embed.js index 20c9b3d2..a9dff130 100644 --- a/packages/embed/site/embed.js +++ b/packages/embed/site/embed.js @@ -18,6 +18,10 @@ * package shows under its preview. */ +/** + * @import { H5PPlayerElement, PlayerErrorDetail, PlayerStateChangeDetail, ReadyDetail } from '@missing-elements/h5p-offline-player' + */ + /** Where the element's `libraries="pack"` fetches the library pack from, for a site without its own copy. */ const PACK_CDN_ORIGIN = 'https://cdn.jsdelivr.net' @@ -25,7 +29,7 @@ const PACK_CDN_ORIGIN = 'https://cdn.jsdelivr.net' * @param {object} [options] * @param {string | null} [options.packBase] the folder of this site's copy of the library pack's * parts (`parts/` of `@missing-elements/h5p-libraries`), which `libraries=pack` plays from - * @param {{ libraries: object[] } | null} [options.pack] the same, as the `pack` export a bundler + * @param {H5PPlayerElement['pack']} [options.pack] the same, as the `pack` export a bundler * resolves; it wins over `packBase`. Without either, `pack` is the element's copy on jsDelivr * @param {string | null} [options.librariesPack] the URL of a whole `libraries.h5p` on this site, * for a page written before the pack was split: played as any bundle, with no refresh @@ -35,7 +39,7 @@ const PACK_CDN_ORIGIN = 'https://cdn.jsdelivr.net' * @param {string | null} [options.defaultLibraries] the `libraries` value for an address that has * none — `pack` or URLs, as the parameter — so a snippet without `&libraries=` still plays * an export that carries no libraries; `&libraries=none` turns it off for one address - * @param {object | null} [options.runtime] the `runtime` export of `@missing-elements/h5p-runtime`, + * @param {H5PPlayerElement['runtime']} [options.runtime] the `runtime` export of `@missing-elements/h5p-runtime`, * for a page that bundles the element; without it the element looks for `frame-assets/` beside itself * @param {boolean} [options.askInOwnFrame] whether a package from another origin plays `untrusted`, * with a click to play it with its own code when it needs that, when this page is framed by a @@ -44,19 +48,24 @@ const PACK_CDN_ORIGIN = 'https://cdn.jsdelivr.net' */ export function startEmbed({ packBase = null, pack = null, librariesPack = null, packages = null, defaultLibraries = null, runtime = null, askInOwnFrame = true } = {}) { const params = new URLSearchParams(location.search) - const player = document.querySelector('h5p-player') + const player = /** @type {H5PPlayerElement} */ (document.querySelector('h5p-player')) // Before `src`: the element resolves the runtime's files, and reads where the pack is, when a // package is set. if (runtime) player.runtime = runtime if (pack) player.pack = pack else if (packBase) player.setAttribute('pack-base', packBase) const ownPack = Boolean(pack || packBase) - const notice = document.querySelector('#notice') - const loader = document.querySelector('#loader') + const notice = /** @type {HTMLElement} */ (document.querySelector('#notice')) + const loader = /** @type {HTMLElement} */ (document.querySelector('#loader')) const framed = window.parent !== window /* ---------------------------------------------------------------- notices */ + /** + * @param {string} text + * @param {string} [kind] + * @param {{ href: string, text: string } | null} [link] + */ const say = (text, kind = '', link = null) => { notice.replaceChildren() if (text) { @@ -75,6 +84,10 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, requestAnimationFrame(announce) } + /** + * @param {string} text + * @param {string} [code] + */ const refuse = (text, code = 'refused') => { loader.hidden = true say(text, 'error') @@ -87,6 +100,8 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, * A message to the page that frames this one: the height in the shape h5p-resizer.js expects, * and `report`, `error` and `xapi` in this page's own. To any parent unless a target is named, * since nothing in the height is secret; the xAPI relay names the origin that opted in. + * @param {object} message + * @param {string} [target] */ const post = (message, target = '*') => { if (framed) window.parent.postMessage(message, target) @@ -139,7 +154,7 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, let startedAt = 0 player.addEventListener('ready', (event) => { - const { source, metadata, libraryBundle } = event.detail + const { source, metadata, libraryBundle } = /** @type {CustomEvent} */ (event).detail post({ context: 'h5p-offline-player', action: 'report', @@ -158,7 +173,10 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, /* ---------------------------------------------------------------- xAPI, relayed on request */ - /** An origin, or nothing: the parameter has to be exactly what `event.origin` will read. */ + /** + * An origin, or nothing: the parameter has to be exactly what `event.origin` will read. + * @param {string | null} value + */ const originOf = (value) => { if (!value) return null try { @@ -173,18 +191,22 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, if (relayTo && framed) { for (const type of ['xapi', 'finished']) { player.addEventListener(type, (event) => { - post({ context: 'h5p-offline-player', action: type, ...event.detail }, relayTo) + post({ context: 'h5p-offline-player', action: type, .../** @type {CustomEvent} */ (event).detail }, relayTo) }) } } /* ---------------------------------------------------------------- errors, and Safari */ - /** Asks whether to play an untrusted package with its own code; set when one is played so. */ + /** + * Asks whether to play an untrusted package with its own code; set when one is played so. + * @type {(() => void) | null} + */ let askToTrust = null player.addEventListener('error', (event) => { - const { code, message, missingLibraries } = event.detail + // The element's own `error`, which the DOM's types take for a script's `ErrorEvent`. + const { code, message, missingLibraries } = /** @type {CustomEvent} */ (/** @type {unknown} */ (event)).detail // Played untrusted, it cannot do without its own copy of a library: a click decides. if (missingLibraries?.carried && player.untrusted && askToTrust) { askToTrust() @@ -211,7 +233,7 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, }) player.addEventListener('statechange', (event) => { - const { state } = event.detail + const { state } = /** @type {CustomEvent} */ (event).detail if (state !== 'error') say('') // Shown from the HTML on, until the content is up or the load has failed. loader.hidden = state === 'ready' || state === 'error' || state === 'idle' @@ -220,7 +242,10 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, /* ---------------------------------------------------------------- which hosts */ - /** The origin of a URL as this page resolves it, or `null` for what is not one. */ + /** + * The origin of a URL as this page resolves it, or `null` for what is not one. + * @param {string} value + */ const urlOrigin = (value) => { try { const url = new URL(value, location.href) @@ -232,15 +257,21 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, } const allowed = packages ? new Set(packages) : null - /** Whether this player was told it may fetch from `origin`. Always true without a list. */ + /** + * Whether this player was told it may fetch from `origin`. Always true without a list. + * @param {string} origin + */ const permitted = (origin) => origin === location.origin || !allowed || allowed.has(origin) /** * The `libraries` value with `pack` resolved to this site's copy, or an error to show. With a * list of hosts, every bundle's origin has to be on it, jsDelivr's included when the pack comes * from there; the CSP that `h5p-embed` wrote says the same, this only says it in words. + * @param {string} value + * @returns {{ value?: string, error?: string }} */ const librarySources = (value) => { + /** @type {string[]} */ const sources = [] if (value === 'none') return { value: '' } for (const token of value.split(/\s+/).filter(Boolean)) { @@ -287,6 +318,10 @@ export function startEmbed({ packBase = null, pack = null, librariesPack = null, if (lang && /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(lang)) player.setAttribute('lang', lang) } + /** + * @param {string} value + * @param {string | undefined} libraries + */ const start = (value, libraries) => { if (libraries) player.setAttribute('libraries', libraries) if (params.get('preload') === 'auto') player.setAttribute('preload', 'auto') diff --git a/packages/embed/tests/package-types.ts b/packages/embed/tests/package-types.ts new file mode 100644 index 00000000..b0e76b32 --- /dev/null +++ b/packages/embed/tests/package-types.ts @@ -0,0 +1,25 @@ +/** + * The package as a TypeScript caller sees it: imported by its name, through the `types` condition + * of its `exports`, from the declarations `pnpm types` generates from the JSDoc. Type-checked by + * `pnpm typecheck`; nothing here runs. + */ +import { EmbedError, buildSite, type BuiltSite } from '@missing-elements/h5p-embed' +import { startEmbed } from '@missing-elements/h5p-embed/embed.js' +import { pack } from '@missing-elements/h5p-libraries' +import { runtime } from '@missing-elements/h5p-runtime' +// @ts-expect-error a helper the tests use, not part of the package's API (#60) +import { parseOrigin } from '@missing-elements/h5p-embed' + +export async function asACallerWould(): Promise { + const site: BuiltSite = await buildSite({ out: 'public/player', packages: ['https://cdn.example.org'], defaultLibraries: 'pack' }) + const hosts: string[] = site.packages ?? [] + + // The page, bundled, with the libraries and the runtime as their packages export them. + startEmbed({ runtime, pack, defaultLibraries: 'pack', askInOwnFrame: false }) + + // @ts-expect-error the folder is named `out` + await buildSite({ folder: 'public/player' }) + + void [hosts, parseOrigin, new EmbedError('refused') instanceof Error] + return site.csp +} diff --git a/packages/embed/tsconfig.json b/packages/embed/tsconfig.json index eba7c864..16a68a8e 100644 --- a/packages/embed/tsconfig.json +++ b/packages/embed/tsconfig.json @@ -10,7 +10,8 @@ "allowJs": true, "isolatedModules": true, "esModuleInterop": true, - "skipLibCheck": true + "skipLibCheck": true, + "checkJs": true }, - "include": ["tests/**/*.ts"] + "include": ["lib/**/*.mjs", "site/embed.js", "tests/**/*.ts"] } diff --git a/packages/embed/tsconfig.types.json b/packages/embed/tsconfig.types.json new file mode 100644 index 00000000..a22ec919 --- /dev/null +++ b/packages/embed/tsconfig.types.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "stripInternal": true, + "rootDir": ".", + "outDir": "types" + }, + "include": ["lib/build.mjs", "site/embed.js"] +} diff --git a/packages/normalize/README.md b/packages/normalize/README.md index e744b4f1..85924c53 100644 --- a/packages/normalize/README.md +++ b/packages/normalize/README.md @@ -46,6 +46,8 @@ const report = await normalizeArchive({ }) ``` +TypeScript declarations ship with the package: `Report` and `EntryResult` describe what it returns. + Node only, not a browser. Why deflated video cannot stream: the demo's [normalize page](https://github.com/missing-elements/h5p-offline-player/blob/main/apps/demo/demo/normalize.html). diff --git a/packages/normalize/lib/normalize.mjs b/packages/normalize/lib/normalize.mjs index 4fa66473..19e98132 100644 --- a/packages/normalize/lib/normalize.mjs +++ b/packages/normalize/lib/normalize.mjs @@ -88,6 +88,7 @@ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/ /** * The form an entry of this name should end up in. + * @internal * @param {string} name * @returns {TargetForm} */ @@ -109,6 +110,7 @@ function extensionOf(name) { * The same rule the player applies: the canonical form of a zip entry name, or `null` where * the name cannot be a plain relative path under the package root. Such an entry is dropped * rather than repaired, because the player would refuse it anyway. + * @internal * @param {string} raw */ export function plainRelativeName(raw) { @@ -130,6 +132,7 @@ export function plainRelativeName(raw) { * media last. Library folders are kept intact rather than having their images pulled to the * end: the player treats a folder as complete once a later folder has begun, and a straggler * would then be reported missing. + * @internal * * @template {{ name: string, target: TargetForm }} T * @param {T[]} entries in source order @@ -195,7 +198,7 @@ export async function normalizeArchive({ input, output, onEntry }) { /** @type {Report['dropped']} */ const dropped = { directories: 0, rejected: [] } - /** @type {Array<{ entry: import('@zip.js/zip.js').Entry, name: string, target: TargetForm }>} */ + /** @type {Array<{ entry: import('@zip.js/zip.js').FileEntry, name: string, target: TargetForm }>} */ const planned = [] const seen = new Set() for (const entry of all) { @@ -269,7 +272,7 @@ export async function normalizeArchive({ input, output, onEntry }) { } /** - * @param {{ entry: import('@zip.js/zip.js').Entry, name: string, target: TargetForm }} item + * @param {{ entry: import('@zip.js/zip.js').FileEntry, name: string, target: TargetForm }} item * @param {{ source: import('node:fs/promises').FileHandle, tempDir: string, writer: StreamingZipWriter | null, index: number }} context * @returns {Promise} */ @@ -281,10 +284,10 @@ async function processEntry({ entry, name, target }, { source, tempDir, writer, const dosDateTime = typeof entry.rawLastModDate === 'number' ? entry.rawLastModDate : undefined const base = { name, size, target, from } - /** @param {string} [warning] */ /** The header of this entry stored as it is, byte for byte: the source's own size and CRC. */ const storedMeta = { name, method: STORE, crc32: entry.signature ?? 0, compressedSize: size, uncompressedSize: size, dosDateTime } + /** @param {string} [warning] */ const copyRaw = async (warning) => { await writer?.add( { @@ -413,7 +416,10 @@ async function pump(chunks, sink) { } } -/** Opens the finished archive the way any reader would, and counts what it lists. */ +/** + * Opens the finished archive the way any reader would, and counts what it lists. + * @param {string} path + */ async function verifyArchive(path) { const blob = await openAsBlob(path) const reader = new ZipReader(new BlobReader(blob)) diff --git a/packages/normalize/package.json b/packages/normalize/package.json index 0106db0c..c2a3430d 100644 --- a/packages/normalize/package.json +++ b/packages/normalize/package.json @@ -20,12 +20,16 @@ "h5p-normalize": "./bin/h5p-normalize.mjs" }, "exports": { - ".": "./lib/normalize.mjs", + ".": { + "types": "./types/normalize.d.mts", + "default": "./lib/normalize.mjs" + }, "./package.json": "./package.json" }, "files": [ "bin", - "lib" + "lib", + "types" ], "keywords": [ "h5p", @@ -39,9 +43,10 @@ "scripts": { "test": "vitest run", "test:unit": "vitest run", - "typecheck": "tsc -p tsconfig.json", - "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\"", - "prepublishOnly": "pnpm typecheck && pnpm test" + "typecheck": "pnpm types && tsc -p tsconfig.json", + "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\" && pnpm types", + "prepublishOnly": "pnpm typecheck && pnpm test", + "types": "node -e \"require('node:fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json" }, "dependencies": { "@zip.js/zip.js": "^2.23.0" diff --git a/packages/normalize/tests/package-types.ts b/packages/normalize/tests/package-types.ts new file mode 100644 index 00000000..855007d4 --- /dev/null +++ b/packages/normalize/tests/package-types.ts @@ -0,0 +1,22 @@ +/** + * The package as a TypeScript caller sees it: imported by its name, through the `types` condition + * of its `exports`, from the declarations `pnpm types` generates from the JSDoc. Type-checked by + * `pnpm typecheck`; nothing here runs. + */ +import { archiveFingerprint, formatBytes, normalizeArchive, type EntryResult, type Report } from '@missing-elements/h5p-normalize' +// @ts-expect-error a helper the tests use, not part of the package's API (#60) +import { orderEntries } from '@missing-elements/h5p-normalize' + +export async function asACallerWould(): Promise { + const seen: EntryResult[] = [] + const report: Report = await normalizeArchive({ input: 'in.h5p', output: 'out.h5p', onEntry: (entry) => seen.push(entry) }) + const moved: string[] = report.entries.filter(({ action }) => action === 'faststart').map(({ name }) => name) + const saved: string = formatBytes(report.payloadIn - report.payloadOut) + const revision: string = await archiveFingerprint('out.h5p') + + // @ts-expect-error the source is named `input` + await normalizeArchive({ file: 'in.h5p' }) + + void [moved, saved, orderEntries] + return `${report.revision} ${revision}` +} diff --git a/packages/normalize/tsconfig.json b/packages/normalize/tsconfig.json index eba7c864..22a860ff 100644 --- a/packages/normalize/tsconfig.json +++ b/packages/normalize/tsconfig.json @@ -10,7 +10,8 @@ "allowJs": true, "isolatedModules": true, "esModuleInterop": true, - "skipLibCheck": true + "skipLibCheck": true, + "checkJs": true }, - "include": ["tests/**/*.ts"] + "include": ["lib/**/*.mjs", "tests/**/*.ts"] } diff --git a/packages/normalize/tsconfig.types.json b/packages/normalize/tsconfig.types.json new file mode 100644 index 00000000..88fee24d --- /dev/null +++ b/packages/normalize/tsconfig.types.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "stripInternal": true, + "rootDir": "lib", + "outDir": "types" + }, + "include": ["lib/normalize.mjs"] +} diff --git a/packages/player/package.json b/packages/player/package.json index 6d080366..0c50059d 100644 --- a/packages/player/package.json +++ b/packages/player/package.json @@ -63,7 +63,7 @@ "test:browser": "pnpm prepare:dev && vitest run --project browser --project browser-emulated", "test:engine": "pnpm prepare:dev && vitest run --project browser", "test:watch": "pnpm prepare:dev && vitest", - "typecheck": "tsc -b --force && tsc -p tsconfig.test.json", + "typecheck": "tsc -b --force && tsc -p tsconfig.test.json && tsc -p tsconfig.consumer.json", "prepack": "node scripts/prepack.mjs", "prepublishOnly": "node scripts/check-library-pack.mjs && pnpm typecheck && pnpm test:unit && pnpm build" }, diff --git a/packages/player/scripts/sync-h5p-assets.mjs b/packages/player/scripts/sync-h5p-assets.mjs index 24fa7cc6..7d6c4829 100644 --- a/packages/player/scripts/sync-h5p-assets.mjs +++ b/packages/player/scripts/sync-h5p-assets.mjs @@ -82,7 +82,7 @@ const packIndex = JSON.parse(await readFile(resolve(rootDir, '..', 'libraries', const packIndexPath = resolve(rootDir, 'src', 'shared', 'pack-index.ts') const packIndexModule = `// Written by scripts/sync-h5p-assets.mjs from @missing-elements/h5p-libraries ${librariesJson.version}'s // parts/index.json. Do not edit; run \`pnpm sync:assets\` in packages/player. -import type { PackLibrary } from './protocol' +import type { PackLibrary } from './protocol.js' /** * The index of the library pack this release pins, \`LIBRARY_PACK_VERSION\`: each library's diff --git a/packages/player/src/h5p-offline-player.ts b/packages/player/src/h5p-offline-player.ts index 784785a3..e2f4bbee 100644 --- a/packages/player/src/h5p-offline-player.ts +++ b/packages/player/src/h5p-offline-player.ts @@ -1,11 +1,11 @@ import jobsWorkerSource from 'virtual:h5p-jobs-worker' import SHADOW_CSS from './shadow.css?inline' -import { FRAME_FONTS } from './frame-fonts' -import { languageTag } from './shared/language' -import type { ContentMetadata } from './shared/metadata' -import { JobsWorkerHandle, type JobsScript } from './jobs-worker-handle' -import { parseLibrarySources } from './shared/library-sources' -import { packLibrariesIn } from './shared/pack' +import { FRAME_FONTS } from './frame-fonts.js' +import { languageTag } from './shared/language.js' +import type { ContentMetadata } from './shared/metadata.js' +import { JobsWorkerHandle, type JobsScript } from './jobs-worker-handle.js' +import { parseLibrarySources } from './shared/library-sources.js' +import { packLibrariesIn } from './shared/pack.js' import { CONTROL_TIMEOUT_MS, LIBRARY_PACK_BASE, @@ -17,7 +17,7 @@ import { WARM_ENTRY, WORKER_MAJOR_UPDATE_TIMEOUT_MS, WORKER_UPDATE_TIMEOUT_MS -} from './shared/constants' +} from './shared/constants.js' import { PlayerError, type ErrorCode, @@ -44,13 +44,13 @@ import { type UserDataEntry, type UserDataPreload, type WorkerReply -} from './shared/protocol' -import { packageLockName } from './shared/locks' -import { filePkgId, loadKey, partPkgId, randomHex, remotePkgId } from './shared/pkg-id' -import { platformOf, withProvenance } from './shared/revision' -import { probeSource } from './shared/source' -import { loadSegment, routesFor, type LoadRef, type Routes } from './sw/routes' -import { adoptRevision, clearUserData, readUserData, removeUserData, writeUserData } from './user-data-store' +} from './shared/protocol.js' +import { packageLockName } from './shared/locks.js' +import { filePkgId, loadKey, partPkgId, randomHex, remotePkgId } from './shared/pkg-id.js' +import { platformOf, withProvenance } from './shared/revision.js' +import { probeSource } from './shared/source.js' +import { loadSegment, routesFor, type LoadRef, type Routes } from './sw/routes.js' +import { adoptRevision, clearUserData, readUserData, removeUserData, writeUserData } from './user-data-store.js' /** * `` — the package's public surface. It plays a package and nothing else: no URL @@ -166,7 +166,7 @@ function declaredLanguage(element: Element): string | undefined { export type PlayerState = 'idle' | 'probing' | 'downloading' | 'indexing' | 'ready' | 'error' -export type { UserDataEntry } from './shared/protocol' +export type { UserDataEntry } from './shared/protocol.js' /** * The package's own account of itself: `h5p.json`'s metadata as the runtime's copyright dialog @@ -197,7 +197,7 @@ export interface LibraryBundle { refreshed?: RefreshedLibrary[] } -export type { RefreshedLibrary } from './shared/protocol' +export type { RefreshedLibrary } from './shared/protocol.js' /** Each library of a pack, with where its part is: the `pack` export of `@missing-elements/h5p-libraries`. */ export interface LibraryPack { diff --git a/packages/player/src/jobs-worker-handle.ts b/packages/player/src/jobs-worker-handle.ts index 43703664..bb0652b3 100644 --- a/packages/player/src/jobs-worker-handle.ts +++ b/packages/player/src/jobs-worker-handle.ts @@ -1,5 +1,5 @@ -import { WARM_ENTRY } from './shared/constants' -import { JOBS_READY, type FromJobsMessage, type ToJobsMessage } from './shared/protocol' +import { WARM_ENTRY } from './shared/constants.js' +import { JOBS_READY, type FromJobsMessage, type ToJobsMessage } from './shared/protocol.js' /** * Where the Jobs worker's script can come from, tried in order. `url` is called once per diff --git a/packages/player/src/jobs/chunk-writer.ts b/packages/player/src/jobs/chunk-writer.ts index 7211e3ca..814a16f3 100644 --- a/packages/player/src/jobs/chunk-writer.ts +++ b/packages/player/src/jobs/chunk-writer.ts @@ -1,5 +1,5 @@ -import { CHUNK_SIZE } from '../shared/constants' -import type { ChunkStore } from '../shared/chunk-store' +import { CHUNK_SIZE } from '../shared/constants.js' +import type { ChunkStore } from '../shared/chunk-store.js' /** * Smallest partial chunk that is worth publishing. Chunks are the unit of storage, but waiting diff --git a/packages/player/src/jobs/job-queue.ts b/packages/player/src/jobs/job-queue.ts index 53c52ae4..5179655c 100644 --- a/packages/player/src/jobs/job-queue.ts +++ b/packages/player/src/jobs/job-queue.ts @@ -1,4 +1,4 @@ -import type { EntryLocation, SourceDescriptor } from '../shared/protocol' +import type { EntryLocation, SourceDescriptor } from '../shared/protocol.js' /** * The order extractions run in. One at a time — two concurrent inflates halve the rate of diff --git a/packages/player/src/jobs/jobs-worker.ts b/packages/player/src/jobs/jobs-worker.ts index 09bc126c..b88c51a1 100644 --- a/packages/player/src/jobs/jobs-worker.ts +++ b/packages/player/src/jobs/jobs-worker.ts @@ -1,11 +1,11 @@ /// -import { ARCHIVE_ENTRY, CHUNK_SIZE, INPUT_LIVENESS_MS, WARM_ENTRY } from '../shared/constants' -import { ChunkStore, QuotaError, announceQueued, announceRunning, isQuotaError, type ChunkMeta } from '../shared/chunk-store' -import { installEvictionPolicy } from '../shared/eviction' -import { LocalHeaderScanner } from '../shared/forward-index' -import { DEFLATE, STORED, readDataStart } from '../shared/local-header' -import { packageLockName, packageLockPrefix } from '../shared/locks' -import { hex } from '../shared/pkg-id' +import { ARCHIVE_ENTRY, CHUNK_SIZE, INPUT_LIVENESS_MS, WARM_ENTRY } from '../shared/constants.js' +import { ChunkStore, QuotaError, announceQueued, announceRunning, isQuotaError, type ChunkMeta } from '../shared/chunk-store.js' +import { installEvictionPolicy } from '../shared/eviction.js' +import { LocalHeaderScanner } from '../shared/forward-index.js' +import { DEFLATE, STORED, readDataStart } from '../shared/local-header.js' +import { packageLockName, packageLockPrefix } from '../shared/locks.js' +import { hex } from '../shared/pkg-id.js' import { JOBS_READY, PlayerError, @@ -15,14 +15,14 @@ import { type SourceDescriptor, type ToJobsMessage, type WarmSpan -} from '../shared/protocol' -import { openSource, type SourceHandle } from '../shared/source' -import { streamSpan } from '../shared/span-stream' -import { inflated } from '../shared/stream-utils' -import { quotaMessage } from '../shared/storage' -import { createChunkWriter } from './chunk-writer' -import { JobQueue, type ExtractJob } from './job-queue' -import { warmPackage } from './warm' +} from '../shared/protocol.js' +import { openSource, type SourceHandle } from '../shared/source.js' +import { streamSpan } from '../shared/span-stream.js' +import { inflated } from '../shared/stream-utils.js' +import { quotaMessage } from '../shared/storage.js' +import { createChunkWriter } from './chunk-writer.js' +import { JobQueue, type ExtractJob } from './job-queue.js' +import { warmPackage } from './warm.js' /** * The Jobs worker. Everything that takes longer than a Service Worker event is allowed to lives diff --git a/packages/player/src/jobs/warm.ts b/packages/player/src/jobs/warm.ts index 6b6616c6..2d452f12 100644 --- a/packages/player/src/jobs/warm.ts +++ b/packages/player/src/jobs/warm.ts @@ -1,10 +1,10 @@ -import { inflated } from '../shared/stream-utils' -import { WARM_ENTRY, WARM_STALL_MS } from '../shared/constants' -import { QuotaError, type ChunkStore } from '../shared/chunk-store' -import { DEFLATE, LOCAL_HEADER_FIXED_SIZE, STORED, localHeaderDataStart } from '../shared/local-header' -import { contentTypeOf } from '../shared/mime' -import type { WarmSpan } from '../shared/protocol' -import type { SourceHandle } from '../shared/source' +import { inflated } from '../shared/stream-utils.js' +import { WARM_ENTRY, WARM_STALL_MS } from '../shared/constants.js' +import { QuotaError, type ChunkStore } from '../shared/chunk-store.js' +import { DEFLATE, LOCAL_HEADER_FIXED_SIZE, STORED, localHeaderDataStart } from '../shared/local-header.js' +import { contentTypeOf } from '../shared/mime.js' +import type { WarmSpan } from '../shared/protocol.js' +import type { SourceHandle } from '../shared/source.js' /** * Warming: pulls the spans the index named whole, one ranged request each, and lands every entry diff --git a/packages/player/src/shared/chunk-store.ts b/packages/player/src/shared/chunk-store.ts index 735eb530..b214c128 100644 --- a/packages/player/src/shared/chunk-store.ts +++ b/packages/player/src/shared/chunk-store.ts @@ -1,9 +1,9 @@ -import { ARCHIVE_ENTRY, CACHE_PREFIX, CHUNK_KEY_ORIGIN, CHUNK_SIZE } from './constants' -import type { ByteRange } from './range' -import { sliceStream } from './stream-utils' -import { busyPackages } from './locks' -import type { ForwardIndexSnapshot } from './forward-index' -import type { ErrorCode } from './protocol' +import { ARCHIVE_ENTRY, CACHE_PREFIX, CHUNK_KEY_ORIGIN, CHUNK_SIZE } from './constants.js' +import type { ByteRange } from './range.js' +import { sliceStream } from './stream-utils.js' +import { busyPackages } from './locks.js' +import type { ForwardIndexSnapshot } from './forward-index.js' +import type { ErrorCode } from './protocol.js' /** * The chunk store: one Cache API cache per package. Small entries are stored whole; archives and diff --git a/packages/player/src/shared/eviction.ts b/packages/player/src/shared/eviction.ts index ddb84746..8064fc67 100644 --- a/packages/player/src/shared/eviction.ts +++ b/packages/player/src/shared/eviction.ts @@ -1,6 +1,6 @@ -import { setEvictionListener, setEvictionPolicy } from './chunk-store' -import * as db from './idb' -import { busyPackages } from './locks' +import { setEvictionListener, setEvictionPolicy } from './chunk-store.js' +import * as db from './idb.js' +import { busyPackages } from './locks.js' /** * Which package a quota squeeze may drop: the coldest by `lastPlayed` that is neither the one diff --git a/packages/player/src/shared/forward-index.ts b/packages/player/src/shared/forward-index.ts index 6942a074..57a5e19d 100644 --- a/packages/player/src/shared/forward-index.ts +++ b/packages/player/src/shared/forward-index.ts @@ -23,7 +23,7 @@ * normalisation as everything else, and the snapshot is replaced by the real index once the whole * archive is present. */ -import { LOCAL_HEADER_FIXED_SIZE, LOCAL_HEADER_SIGNATURE } from './local-header' +import { LOCAL_HEADER_FIXED_SIZE, LOCAL_HEADER_SIGNATURE } from './local-header.js' export interface ForwardEntry { diff --git a/packages/player/src/shared/idb.ts b/packages/player/src/shared/idb.ts index 96c1509b..dad98419 100644 --- a/packages/player/src/shared/idb.ts +++ b/packages/player/src/shared/idb.ts @@ -1,5 +1,5 @@ -import { DB_NAME, DB_VERSION, PACKAGES_STORE } from './constants' -import type { PackageRecord } from './protocol' +import { DB_NAME, DB_VERSION, PACKAGES_STORE } from './constants.js' +import type { PackageRecord } from './protocol.js' /** * The `packages` table. Both the page and the Service Worker open it: the page writes the diff --git a/packages/player/src/shared/library-sources.ts b/packages/player/src/shared/library-sources.ts index e766e1bb..7311dd0a 100644 --- a/packages/player/src/shared/library-sources.ts +++ b/packages/player/src/shared/library-sources.ts @@ -1,4 +1,4 @@ -import type { LibrarySource } from './protocol' +import type { LibrarySource } from './protocol.js' /** * The `libraries` attribute: `pack` or a URL, or several separated by whitespace, in order. diff --git a/packages/player/src/shared/local-header.ts b/packages/player/src/shared/local-header.ts index 1d775b35..58834ba2 100644 --- a/packages/player/src/shared/local-header.ts +++ b/packages/player/src/shared/local-header.ts @@ -1,5 +1,5 @@ -import { PlayerError } from './protocol' -import type { SourceHandle } from './source' +import { PlayerError } from './protocol.js' +import type { SourceHandle } from './source.js' /** * The zip local header, the thirty bytes in front of every entry's data. Three places read it — * the virtual server before slicing a stored entry, the warm as it walks a span, the Jobs worker diff --git a/packages/player/src/shared/pack-index.ts b/packages/player/src/shared/pack-index.ts index ccc2b772..25ad5a7b 100644 --- a/packages/player/src/shared/pack-index.ts +++ b/packages/player/src/shared/pack-index.ts @@ -1,6 +1,6 @@ // Written by scripts/sync-h5p-assets.mjs from @missing-elements/h5p-libraries 1.0.0's // parts/index.json. Do not edit; run `pnpm sync:assets` in packages/player. -import type { PackLibrary } from './protocol' +import type { PackLibrary } from './protocol.js' /** * The index of the library pack this release pins, `LIBRARY_PACK_VERSION`: each library's diff --git a/packages/player/src/shared/pack.ts b/packages/player/src/shared/pack.ts index b5dff34e..f2af7310 100644 --- a/packages/player/src/shared/pack.ts +++ b/packages/player/src/shared/pack.ts @@ -1,4 +1,4 @@ -import type { PackDependency, PackLibrary } from './protocol' +import type { PackDependency, PackLibrary } from './protocol.js' /** * The entries of a library pack's index that are well formed. The index of a copy the host names diff --git a/packages/player/src/shared/protocol.ts b/packages/player/src/shared/protocol.ts index 5bee4f6d..b6771367 100644 --- a/packages/player/src/shared/protocol.ts +++ b/packages/player/src/shared/protocol.ts @@ -1,4 +1,4 @@ -import type { ContentMetadata } from './metadata' +import type { ContentMetadata } from './metadata.js' /** * The shapes crossing the three contexts: the page (element), the Service Worker and the Jobs diff --git a/packages/player/src/shared/resilient-stream.ts b/packages/player/src/shared/resilient-stream.ts index e55395e8..2ffe45bc 100644 --- a/packages/player/src/shared/resilient-stream.ts +++ b/packages/player/src/shared/resilient-stream.ts @@ -1,6 +1,6 @@ -import { READ_RETRIES, READ_RETRY_DELAY_MS, READ_STALL_MS } from './constants' -import { PlayerError } from './protocol' -import type { ByteRange } from './range' +import { READ_RETRIES, READ_RETRY_DELAY_MS, READ_STALL_MS } from './constants.js' +import { PlayerError } from './protocol.js' +import type { ByteRange } from './range.js' /** * A ranged read that survives the link: a request that stops delivering for `READ_STALL_MS`, or diff --git a/packages/player/src/shared/revision.ts b/packages/player/src/shared/revision.ts index 28d12f59..c25a738d 100644 --- a/packages/player/src/shared/revision.ts +++ b/packages/player/src/shared/revision.ts @@ -7,7 +7,7 @@ * Activity. *When* a build was the current one is not the statement's to say: that is the * publishing organisation's version record, which an audit compares these against. */ -import { hex } from './pkg-id' +import { hex } from './pkg-id.js' /** One central-directory record, as much of it as the fingerprint covers. */ diff --git a/packages/player/src/shared/source-reader.ts b/packages/player/src/shared/source-reader.ts index 9ddad140..1527bf66 100644 --- a/packages/player/src/shared/source-reader.ts +++ b/packages/player/src/shared/source-reader.ts @@ -1,6 +1,6 @@ import { Reader, type CreateReadableOptions } from '@zip.js/zip.js' -import type { SourceHandle } from './source' -import { streamSpan } from './span-stream' +import type { SourceHandle } from './source.js' +import { streamSpan } from './span-stream.js' /** * The zip.js side of a source: `SourceReader` presents a `SourceHandle` to zip.js. Kept apart diff --git a/packages/player/src/shared/source.ts b/packages/player/src/shared/source.ts index 22a96057..1b177935 100644 --- a/packages/player/src/shared/source.ts +++ b/packages/player/src/shared/source.ts @@ -1,9 +1,9 @@ -import { ARCHIVE_ENTRY } from './constants' -import { ChunkStore } from './chunk-store' -import { PlayerError, type RemoteSourceDescriptor, type SourceDescriptor } from './protocol' -import type { ByteRange } from './range' -import { resilientStream } from './resilient-stream' -import { sliceStream } from './stream-utils' +import { ARCHIVE_ENTRY } from './constants.js' +import { ChunkStore } from './chunk-store.js' +import { PlayerError, type RemoteSourceDescriptor, type SourceDescriptor } from './protocol.js' +import type { ByteRange } from './range.js' +import { resilientStream } from './resilient-stream.js' +import { sliceStream } from './stream-utils.js' /** * Source adapters. One interface — a size and a byte-range read — over the three ways an archive diff --git a/packages/player/src/shared/span-stream.ts b/packages/player/src/shared/span-stream.ts index 3e073611..6e5376e7 100644 --- a/packages/player/src/shared/span-stream.ts +++ b/packages/player/src/shared/span-stream.ts @@ -1,7 +1,7 @@ -import { SEGMENT_CONCURRENCY, SEGMENT_MIN_SPAN, SEGMENT_SIZE } from './constants' -import type { ByteRange } from './range' -import type { SourceHandle } from './source' -import { deferredStream } from './stream-utils' +import { SEGMENT_CONCURRENCY, SEGMENT_MIN_SPAN, SEGMENT_SIZE } from './constants.js' +import type { ByteRange } from './range.js' +import type { SourceHandle } from './source.js' +import { deferredStream } from './stream-utils.js' /** * How a span of the archive is pulled: one ranged request, or several at once when the span is diff --git a/packages/player/src/shared/stream-utils.ts b/packages/player/src/shared/stream-utils.ts index 63c7f877..bfd1419c 100644 --- a/packages/player/src/shared/stream-utils.ts +++ b/packages/player/src/shared/stream-utils.ts @@ -1,5 +1,5 @@ -import { STORED } from './local-header' -import type { ByteRange } from './range' +import { STORED } from './local-header.js' +import type { ByteRange } from './range.js' /** * Restricts a byte stream to an inclusive range without buffering it. Used to answer a `Range` diff --git a/packages/player/src/sw/frame-document.ts b/packages/player/src/sw/frame-document.ts index 1c7850ef..06ea7f13 100644 --- a/packages/player/src/sw/frame-document.ts +++ b/packages/player/src/sw/frame-document.ts @@ -1,7 +1,7 @@ -import { randomHex } from '../shared/pkg-id' -import type { FrameAssets, FrameFont, FrameOptions } from '../shared/protocol' -import { contentMetadata, type ContentMetadata } from '../shared/metadata' -import { isEnglish, LANGUAGE_TAG } from '../shared/language' +import { randomHex } from '../shared/pkg-id.js' +import type { FrameAssets, FrameFont, FrameOptions } from '../shared/protocol.js' +import { contentMetadata, type ContentMetadata } from '../shared/metadata.js' +import { isEnglish, LANGUAGE_TAG } from '../shared/language.js' /** * The frame document, generated per request. H5P core assumes it owns the page — it plants diff --git a/packages/player/src/sw/library-load.ts b/packages/player/src/sw/library-load.ts index 1943a2d4..6741b8bd 100644 --- a/packages/player/src/sw/library-load.ts +++ b/packages/player/src/sw/library-load.ts @@ -1,5 +1,5 @@ -import type { LibraryLoad } from '../shared/protocol' -import { dependenciesIn, type LibraryDependency, type PackageManifest } from './package-reader' +import type { LibraryLoad } from '../shared/protocol.js' +import { dependenciesIn, type LibraryDependency, 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 0c8f35c8..e33b8279 100644 --- a/packages/player/src/sw/mount.ts +++ b/packages/player/src/sw/mount.ts @@ -8,10 +8,10 @@ import { STREAM_KEEPALIVE_MS, VERSION, WATERMARK_POLL_MS -} from '../shared/constants' -import { PACK_INDEX } from '../shared/pack-index' -import { packLibrariesIn } from '../shared/pack' -import { planPack } from './pack-plan' +} from '../shared/constants.js' +import { PACK_INDEX } from '../shared/pack-index.js' +import { packLibrariesIn } from '../shared/pack.js' +import { planPack } from './pack-plan.js' import { ChunkStore, FORWARD_INDEX_ENTRY, @@ -21,10 +21,10 @@ import { onWatermark, type ChunkMeta, type EntryFailure -} from '../shared/chunk-store' -import { installEvictionPolicy } from '../shared/eviction' -import { normalizeRequestPath } from '../shared/entry-names' -import { contentTypeOf } from '../shared/mime' +} from '../shared/chunk-store.js' +import { installEvictionPolicy } from '../shared/eviction.js' +import { normalizeRequestPath } from '../shared/entry-names.js' +import { contentTypeOf } from '../shared/mime.js' import { PlayerError, type FromWorkerMessage, @@ -35,18 +35,18 @@ import { type PackageRecord, type ToWorkerMessage, type WorkerReply -} from '../shared/protocol' -import { contentRange, parseRange, type ByteRange } from '../shared/range' -import { openSource } from '../shared/source' -import * as db from '../shared/idb' -import { type IndexedEntry, type LocatedEntry, PackageReader, dependenciesIn, explainMissingLibraries, libraryFolderNames, locationOf } from './package-reader' -import { libraryLoad, walkLibraries } from './library-load' -import { STORED } from '../shared/local-header' -import { CONTENT_CHECK_HEADER, buildFrameDocument, createNonce } from './frame-document' -import { loadSegment, matchRoute, routesFor, type LoadRef, type RouteMatch, type Routes } from './routes' -import { sliceStream } from '../shared/stream-utils' -import { waitForWatermark } from './watermark-wait' -import { quotaMessage } from '../shared/storage' +} from '../shared/protocol.js' +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 { libraryLoad, walkLibraries } from './library-load.js' +import { STORED } from '../shared/local-header.js' +import { CONTENT_CHECK_HEADER, buildFrameDocument, createNonce } from './frame-document.js' +import { loadSegment, matchRoute, routesFor, type LoadRef, type RouteMatch, type Routes } from './routes.js' +import { sliceStream } from '../shared/stream-utils.js' +import { waitForWatermark } from './watermark-wait.js' +import { quotaMessage } from '../shared/storage.js' /** * The Service Worker half of the player: a virtual file server over a zip that is never diff --git a/packages/player/src/sw/pack-plan.ts b/packages/player/src/sw/pack-plan.ts index fb189fcb..06f78d06 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' -import { addonPatterns, textMatches } from './package-reader' +import type { PackDependency, PackLibrary, PackPart, PackPlan, RefreshedLibrary } from '../shared/protocol.js' +import { addonPatterns, textMatches } from './package-reader.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 2ed41247..233f9a95 100644 --- a/packages/player/src/sw/package-reader.ts +++ b/packages/player/src/sw/package-reader.ts @@ -1,8 +1,8 @@ import { ZipReader, type Entry, type FileEntry } from '@zip.js/zip.js' -import { INLINE_MAX_SIZE, MEDIA_INLINE_MAX_SIZE, WARM_ENTRY_MAX_SIZE, WARM_GAP, WARM_MAX_BYTES } from '../shared/constants' -import { indexEntryNames, normalizeEntryName } from '../shared/entry-names' -import { extensionOf, isMediaEntry, isTextEntry } from '../shared/mime' -import { DEFLATE, LOCAL_HEADER_FIXED_SIZE, STORED, readDataStart } from '../shared/local-header' +import { INLINE_MAX_SIZE, MEDIA_INLINE_MAX_SIZE, WARM_ENTRY_MAX_SIZE, WARM_GAP, WARM_MAX_BYTES } from '../shared/constants.js' +import { indexEntryNames, normalizeEntryName } from '../shared/entry-names.js' +import { extensionOf, isMediaEntry, isTextEntry } from '../shared/mime.js' +import { DEFLATE, LOCAL_HEADER_FIXED_SIZE, STORED, readDataStart } from '../shared/local-header.js' import { PlayerError, type EntryLocation, @@ -10,15 +10,15 @@ import { type PrefetchEntry, type WarmEntry, type WarmSpan -} from '../shared/protocol' -import type { SourceHandle } from '../shared/source' -import { SourceReader } from '../shared/source-reader' -import type { ByteRange } from '../shared/range' -import { deferredStream, inflated } from '../shared/stream-utils' -import type { ForwardEntry, ForwardIndexSnapshot } from '../shared/forward-index' -import { indexFingerprint, librariesFingerprint, revisionOf } from '../shared/revision' -import { contentMetadata, type ContentMetadata } from '../shared/metadata' -import type { OwnLibrary } from './pack-plan' +} from '../shared/protocol.js' +import type { SourceHandle } from '../shared/source.js' +import { SourceReader } from '../shared/source-reader.js' +import type { ByteRange } from '../shared/range.js' +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 type { OwnLibrary } from './pack-plan.js' /** * The package reader: a zip central directory turned into a name → entry index, plus the decision diff --git a/packages/player/src/sw/routes.ts b/packages/player/src/sw/routes.ts index 671bf19c..74d01e9c 100644 --- a/packages/player/src/sw/routes.ts +++ b/packages/player/src/sw/routes.ts @@ -5,7 +5,7 @@ * base. */ -import { LOAD_KEY_BYTES, PKG_ID_LENGTH } from '../shared/pkg-id' +import { LOAD_KEY_BYTES, PKG_ID_LENGTH } from '../shared/pkg-id.js' export interface Routes { /** Absolute URL prefix, always ending in `h5p/`. */ diff --git a/packages/player/src/sw/sw-entry.ts b/packages/player/src/sw/sw-entry.ts index 882a8724..f015c7bb 100644 --- a/packages/player/src/sw/sw-entry.ts +++ b/packages/player/src/sw/sw-entry.ts @@ -1,6 +1,6 @@ /// import { configure } from '@zip.js/zip.js' -import { mountH5P } from './mount' +import { mountH5P } from './mount.js' /** * The standalone Service Worker. Built to `dist/h5p-sw.js` as a self-contained IIFE so it can be diff --git a/packages/player/src/sw/watermark-wait.ts b/packages/player/src/sw/watermark-wait.ts index 9e7d9132..8333d719 100644 --- a/packages/player/src/sw/watermark-wait.ts +++ b/packages/player/src/sw/watermark-wait.ts @@ -1,5 +1,5 @@ -import { COLD_ENTRY_WAIT_MS, WATERMARK_POLL_MS } from '../shared/constants' -import { onWatermark, type ChunkMeta, type ChunkStore } from '../shared/chunk-store' +import { COLD_ENTRY_WAIT_MS, WATERMARK_POLL_MS } from '../shared/constants.js' +import { onWatermark, type ChunkMeta, type ChunkStore } from '../shared/chunk-store.js' /** * Waits until the entry has at least `needed` bytes, is complete, or carries a recorded failure. diff --git a/packages/player/src/user-data-store.ts b/packages/player/src/user-data-store.ts index 85f8ec43..62d7df7f 100644 --- a/packages/player/src/user-data-store.ts +++ b/packages/player/src/user-data-store.ts @@ -1,4 +1,4 @@ -import { USER_DATA_DB_NAME, USER_DATA_STORE } from './shared/constants' +import { USER_DATA_DB_NAME, USER_DATA_STORE } from './shared/constants.js' /** * The learner's saved state on this device, one row per value the runtime saved: what H5P core diff --git a/packages/player/tests/package-types.ts b/packages/player/tests/package-types.ts new file mode 100644 index 00000000..8db6f9ec --- /dev/null +++ b/packages/player/tests/package-types.ts @@ -0,0 +1,27 @@ +/** + * The package as a TypeScript caller sees it under `node16` and `nodenext` resolution: imported by + * its name, through the `types` condition of its `exports`, from the declarations `tsc -b` writes + * into `types/`. Type-checked by `pnpm typecheck` with `tsconfig.consumer.json`; nothing here runs. + * Those modes follow a relative import only when it names its file, so a source import written + * without `.js` leaves what comes through it `any` for such a caller (#60), and an expected error + * below then goes missing. + */ +import { H5PPlayerElement, type PackageMetadata, type PlayerErrorDetail, type ReadyDetail } from '@missing-elements/h5p-offline-player' +import { mountH5P } from '@missing-elements/h5p-offline-player/sw' + +export function asACallerWould(worker: ServiceWorkerGlobalScope): string[] { + const player: H5PPlayerElement | null = document.querySelector('h5p-player') + mountH5P(worker, { scope: '/h5p/' }) + + // @ts-expect-error not an error code + const code: PlayerErrorDetail['code'] = 'offline' + // @ts-expect-error the folders are a list + const folders: NonNullable['folders'] = 'H5P.Column-1.18' + // @ts-expect-error not a kind of source + const source: NonNullable['type'] = 'ftp' + // @ts-expect-error the title is a string + const title: PackageMetadata['title'] = 1 + + void [player, code, folders, source, title] + return player?.libraryBundle?.refreshed?.map(({ library, to }) => `${library} ${to}`) ?? [] +} diff --git a/packages/player/tsconfig.consumer.json b/packages/player/tsconfig.consumer.json new file mode 100644 index 00000000..5ccd079d --- /dev/null +++ b/packages/player/tsconfig.consumer.json @@ -0,0 +1,17 @@ +{ + // tests/package-types.ts as a caller on `nodenext` compiles it, against `types/` alone: run + // after `tsc -b` has written them. `skipLibCheck` off, so a declaration that names a module + // the caller cannot resolve is an error here rather than an `any` there. + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"], + "types": [], + "strict": true, + "noEmit": true, + "skipLibCheck": false, + "skipDefaultLibCheck": true + }, + "files": ["tests/package-types.ts"] +} diff --git a/packages/player/tsconfig.test.json b/packages/player/tsconfig.test.json index 5668d0f6..5dd2b4ca 100644 --- a/packages/player/tsconfig.test.json +++ b/packages/player/tsconfig.test.json @@ -12,5 +12,8 @@ "types": ["vite/client", "node"] }, "include": ["src/**/*.ts", "tests/**/*.ts"], + // The published declarations as a caller sees them, beside the source they were written from, + // would be two of every type: tsconfig.consumer.json checks it on its own. + "exclude": ["tests/package-types.ts"], "references": [] } diff --git a/packages/verify/README.md b/packages/verify/README.md index f8d967e7..3d92fed4 100644 --- a/packages/verify/README.md +++ b/packages/verify/README.md @@ -80,6 +80,8 @@ console.log(summarize(report)) if (report.verdict !== 'pass') process.exit(1) ``` +TypeScript declarations ship with the package: `VerifyReport` is `report.json`'s shape. + An [agent skill](https://agentskills.io) for it ships in the repository: `npx skills add missing-elements/h5p-offline-player --skill h5p-verify`. diff --git a/packages/verify/lib/verify.mjs b/packages/verify/lib/verify.mjs index 85b8f857..eeb37c9a 100644 --- a/packages/verify/lib/verify.mjs +++ b/packages/verify/lib/verify.mjs @@ -6,6 +6,8 @@ import { basename, dirname, extname, join, normalize, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium, errors as playwrightErrors } from 'playwright-core' +/** @import { H5PPlayerElement, PlayerErrorDetail, PlayerState, RefreshedLibrary } from '@missing-elements/h5p-offline-player' */ + /** * Plays a package the way a learner would — the real element, the real Service Worker, a real * browser — and reports what happened. The package is handed to the element as a picked file, @@ -31,6 +33,7 @@ const CHECK_NOTES = ": the content was checked against its libraries /** The header the Service Worker wants before it hands an untrusted package's `content.json` over as written. */ const CONTENT_CHECK_HEADER = 'X-H5P-Content-Check' +/** @type {Record} */ const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', @@ -62,10 +65,84 @@ const MIME = { * @property {number} [settle] ms watched after `ready` for late errors; default 3 000 */ +/** + * What `verifyPackage` found, as `report.json` holds it. Fields may be added in a minor release, + * none taken away or changed (docs/compatibility.md). + * @typedef {object} VerifyReport + * @property {string} tool `h5p-verify` and its version + * @property {string} file the package, as an absolute path + * @property {number} size its size in bytes + * @property {string | null} libraries the libraries asked for; `pack` when played untrusted and none were named + * @property {boolean} untrusted whether the element played it untrusted, read back from it + * @property {RefreshedLibrary[]} refreshed the libraries the package carries that played at the pack's newer version + * @property {'pass' | 'fail'} verdict + * @property {string[]} reasons why it failed; empty on a pass + * @property {string[]} warnings what is worth reading either way + * @property {PlayerState} state the element's state when the check ended + * @property {number | null} readyMs from handing the file over to `ready`, in ms + * @property {string | null} revision the build, as the element stamps it on every statement + * @property {ReportedError[]} errors every error the element reported + * @property {RenderedContent | null} rendered what the content drew; `null` when the frame could not be measured + * @property {(string | null)[]} xapi the verbs of the statements the content sent, each once + * @property {BlockedLoad[]} csp what the frame's policy blocked + * @property {FailedRequest[]} failedRequests requests to the player's own server that failed + * @property {string[]} console console errors not already among `errors`, the first twenty + * @property {ContentCheck | null} contentCheck played untrusted: what the content check changed + * @property {string | null} screenshot where `screenshot.png` was written, with `out` and a package that reached `ready` + */ + +/** + * An `error` event of the element. + * @typedef {object} ReportedError + * @property {PlayerErrorDetail['code']} code + * @property {string} message + * @property {PlayerErrorDetail['missingLibraries'] | null} missingLibraries + * @property {boolean} afterReady whether the content was up: an error then leaves it running + */ + +/** + * @typedef {object} RenderedContent + * @property {number} height of the content, in CSS pixels + * @property {number} elements in the content's root + * @property {number} text characters of text in it + * @property {number | null} instances the H5P instances the runtime made + */ + +/** + * @typedef {object} BlockedLoad + * @property {string} directive the frame's CSP directive that refused it + * @property {string} blocked what it refused + */ + +/** + * @typedef {object} FailedRequest + * @property {string} url the path asked for + * @property {number} [status] the HTTP status, for an answer of 400 or more + * @property {string} [error] the browser's reason, for a request that got no answer + */ + +/** + * @typedef {object} ContentCheck + * @property {string[]} notes what the runtime's content check wrote that it changed + * @property {ContentChange[] | null} changes the content as played against the package's own; `null` when they could not be compared + */ + +/** + * @typedef {object} ContentChange + * @property {string} path the field, as a JSON path; empty for the content as a whole + * @property {string} change what happened to it + */ + /** * @param {VerifyOptions} options + * @returns {Promise} */ export async function verifyPackage(options) { + /** + * What `page.html` keeps of the element's events, read back from the page. + * @typedef {{ started: number | null, states: { state: PlayerState, at: number }[], errors: (ReportedError & { at: number })[], xapi: (string | null)[] }} PageReport + * @typedef {Window & typeof globalThis & { __verify: PageReport, __csp?: BlockedLoad[], H5P?: { instances?: unknown[] }, H5PIntegration?: { contents?: Record } }} PageWindow + */ const file = resolve(options.file) let size try { @@ -87,6 +164,7 @@ export async function verifyPackage(options) { // Runs in every document, the frame included: a CSP violation fires an event in the document // it happens in, and nothing else reports it. await context.addInitScript(() => { + /** @type {BlockedLoad[]} */ const list = [] Object.defineProperty(window, '__csp', { value: list }) document.addEventListener('securitypolicyviolation', (event) => { @@ -95,8 +173,11 @@ export async function verifyPackage(options) { }) const page = await context.newPage() + /** @type {string[]} */ const consoleErrors = [] + /** @type {FailedRequest[]} */ const failedRequests = [] + /** @type {string[]} */ const checkNotes = [] page.on('console', (message) => { // The content check's own account of what it changed, one note to a line. @@ -131,7 +212,7 @@ export async function verifyPackage(options) { let timedOut = false await page - .waitForFunction(() => window.__verify.states.some((s) => s.state === 'ready' || s.state === 'error'), null, { timeout: readyTimeout }) + .waitForFunction(() => /** @type {PageWindow} */ (window).__verify.states.some((s) => s.state === 'ready' || s.state === 'error'), null, { timeout: readyTimeout }) .catch((error) => { // Only the time running out says something about the package. A browser that crashed // or a page that went away is the check failing to run, and is reported as that. @@ -143,27 +224,34 @@ export async function verifyPackage(options) { if (!timedOut) await page.waitForTimeout(settle) const collected = await page.evaluate(() => { - const player = document.querySelector('h5p-player') - return { ...window.__verify, state: player.state, revision: player.revision, untrusted: player.untrusted === true, libraryBundle: player.libraryBundle } + const player = /** @type {H5PPlayerElement} */ (document.querySelector('h5p-player')) + return { + .../** @type {PageWindow} */ (window).__verify, + state: player.state, + revision: player.revision, + untrusted: player.untrusted === true, + libraryBundle: player.libraryBundle + } }) const frame = page.frames().find((candidate) => candidate.url().includes('/h5p/frame/')) const rendered = frame ? await frame .evaluate(() => { - const root = document.querySelector('#h5p-root') + const root = /** @type {HTMLElement | null} */ (document.querySelector('#h5p-root')) const rect = root?.getBoundingClientRect() return { height: rect ? Math.round(rect.height) : 0, elements: root ? root.querySelectorAll('*').length : 0, text: (root?.innerText ?? '').trim().length, - instances: window.H5P?.instances?.length ?? null + instances: /** @type {PageWindow} */ (window).H5P?.instances?.length ?? null } }) // A frame that has navigated away, or was never reachable, has nothing to measure: // the verdict rules read that as nothing drawn. .catch(() => null) : null - const csp = frame ? await frame.evaluate(() => window.__csp ?? []).catch(() => []) : [] + /** @type {BlockedLoad[]} */ + const csp = frame ? await frame.evaluate(() => /** @type {PageWindow} */ (window).__csp ?? []).catch(() => []) : [] // Untrusted, the package's `content.json` beside what the runtime was handed: the Service // Worker gives the file as written to a request that names the check, and the boot script // leaves the checked parameters in `H5PIntegration`. @@ -172,7 +260,7 @@ export async function verifyPackage(options) { ? await frame .evaluate(async (header) => { const config = JSON.parse(document.getElementById('h5p-boot-config')?.textContent ?? 'null') - const content = Object.values(window.H5PIntegration?.contents ?? {})[0] + const content = Object.values(/** @type {PageWindow} */ (window).H5PIntegration?.contents ?? {})[0] if (!config?.h5pJsonPath || typeof content?.jsonContent !== 'string') return null const response = await fetch(`${config.h5pJsonPath}/content/content.json`, { headers: { [header]: 'semantics' } }) return response.ok ? { written: await response.text(), checked: content.jsonContent } : null @@ -188,6 +276,7 @@ export async function verifyPackage(options) { } const ready = collected.states.find((s) => s.state === 'ready') + /** @type {VerifyReport} */ const report = { tool: `h5p-verify ${version}`, file, @@ -308,19 +397,31 @@ function librarySources(value) { * of the markup it strips. The content upgrade runs first and can move fields too, when the * libraries served are newer than the ones the content was written for; a change that is not * markup may be its. + * @internal * @param {unknown} written * @param {unknown} played - * @returns {{ path: string, change: string }[]} + * @returns {ContentChange[]} */ export function contentChanges(written, played) { - /** @type {{ path: string, change: string }[]} */ + /** @type {ContentChange[]} */ const changes = [] + /** + * @param {unknown} value + * @returns {value is Record} + */ const isContainer = (value) => value !== null && typeof value === 'object' + /** @param {unknown} value */ const isEmpty = (value) => value === '' || (isContainer(value) && Object.keys(value).length === 0) + /** @param {unknown} value */ const show = (value) => { const text = JSON.stringify(value) ?? String(value) return text.length > 40 ? `${text.slice(0, 40)}…` : text } + /** + * @param {unknown} a + * @param {unknown} b + * @param {string} path + */ const walk = (a, b, path) => { if (a === b) return if (typeof a === 'string' && typeof b === 'string') { @@ -330,7 +431,7 @@ export function contentChanges(written, played) { return } if (isContainer(a) && isContainer(b) && Array.isArray(a) === Array.isArray(b)) { - if (Array.isArray(a) && a.length !== b.length) { + if (Array.isArray(a) && Array.isArray(b) && a.length !== b.length) { // Items cannot be paired once one is gone, so the list is reported whole. const gone = a.length - b.length changes.push({ path, change: gone > 0 ? `${gone} of ${a.length} items removed` : `${-gone} items added` }) @@ -361,15 +462,24 @@ export function contentChanges(written, played) { * @param {string} after */ function lostMarkup(before, after) { + /** + * @param {string[]} names + * @returns {Map} + */ const counted = (names) => names.reduce((map, name) => map.set(name, (map.get(name) ?? 0) + 1), new Map()) + /** @param {string} tag */ const tagName = (tag) => /^<([a-z][a-z0-9]*)/i.exec(tag)?.[1].toLowerCase() ?? '' + /** @param {string} html */ const tags = (html) => counted([...html.matchAll(/<([a-z][a-z0-9]*)\b/gi)].map((match) => match[1].toLowerCase())) // Attributes and styles are counted on the kinds of tag that are still there, so a tag removed // whole is reported once, as a tag, and not again through everything it carried. const kept = tags(after) + /** @param {string} html */ const openings = (html) => openingTags(html).filter((tag) => kept.has(tagName(tag))) + /** @param {string} html */ const attributes = (html) => counted(openings(html).flatMap((tag) => [...tag.slice(1).matchAll(/\s([a-z][a-z0-9:-]*)\s*=/gi)].map((match) => match[1].toLowerCase()))) + /** @param {string} html */ const styles = (html) => counted( openings(html).flatMap((tag) => @@ -378,10 +488,20 @@ function lostMarkup(before, after) { ) ) ) - /** Each name `before` has more of than `after`, with how many more. */ + /** + * Each name `before` has more of than `after`, with how many more. + * @param {Map} before + * @param {Map} after + * @returns {[string, number][]} + */ const lost = (before, after) => [...before].flatMap(([name, count]) => (count > (after.get(name) ?? 0) ? [[name, count - (after.get(name) ?? 0)]] : [])) + /** + * @param {[string, number][]} pairs + * @param {(name: string) => string} [shown] + */ const listed = (pairs, shown = (name) => name) => pairs.map(([name, gone]) => (gone > 1 ? `${shown(name)} ×${gone}` : shown(name))).join(', ') + /** @type {string[]} */ const parts = [] const tagsLost = lost(tags(before), tags(after)) if (tagsLost.length) parts.push(`markup removed: ${listed(tagsLost, (name) => `<${name}>`)}`) @@ -400,6 +520,7 @@ function lostMarkup(before, after) { * @param {string} html */ function openingTags(html) { + /** @type {string[]} */ const found = [] for (let start = html.indexOf('<'); start !== -1; start = html.indexOf('<', start + 1)) { if (!/[a-z]/i.test(html[start + 1] ?? '')) continue @@ -411,8 +532,12 @@ function openingTags(html) { return found } -/** The distinct messages, each with how often it occurred: `… (×4)`. */ +/** + * The distinct messages, each with how often it occurred: `… (×4)`. + * @param {string[]} messages + */ function dedupe(messages) { + /** @type {Map} */ const counts = new Map() for (const message of messages) counts.set(message, (counts.get(message) ?? 0) + 1) return [...counts].map(([message, count]) => (count > 1 ? `${message} (×${count})` : message)) @@ -442,12 +567,17 @@ async function playerDist() { * @param {{ dist: string, runtime: string }} roots * @param {Map} bundles routes to bundle files * @param {string | null} packDir a copy of the pack's `parts/`, served under `PACK_ROUTE` + * @returns {Promise<{ url: string, close: () => void }>} */ function serve({ dist, runtime }, bundles = new Map(), packDir = null) { const page = join(here, 'page.html') const ASSETS = '/frame-assets/' const server = createServer(async (request, response) => { const path = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname) + /** + * @param {string} root + * @param {string} rest + */ const safe = (root, rest) => join(root, normalize(rest).replace(/^(\.\.[/\\])+/, '')) const bundle = bundles.get(path) const inPack = packDir !== null && path.startsWith(PACK_ROUTE) @@ -481,11 +611,14 @@ function serve({ dist, runtime }, bundles = new Map(), packDir = null) { /** * A Chromium: the one named, else Chrome or Edge installed on the machine, else Playwright's * own. Chrome and Edge first because they are usually there and cost no download. + * @param {string | undefined} executablePath */ async function launch(executablePath) { + /** @type {import('playwright-core').LaunchOptions[]} */ const attempts = executablePath ? [{ executablePath }] : [{ channel: 'chrome' }, { channel: 'msedge' }, {}] + /** @type {string[]} */ const failures = [] for (const attempt of attempts) { try { @@ -500,7 +633,11 @@ async function launch(executablePath) { ) } -/** A one-line, human-readable account of a report, for the command and for logs. */ +/** + * A one-line, human-readable account of a report, for the command and for logs. + * @param {VerifyReport} report + * @returns {string} + */ export function summarize(report) { const name = basename(report.file) const took = report.readyMs !== null ? `ready in ${(report.readyMs / 1000).toFixed(2)} s` : `state ${report.state}` diff --git a/packages/verify/package.json b/packages/verify/package.json index a1018251..40a8c239 100644 --- a/packages/verify/package.json +++ b/packages/verify/package.json @@ -20,12 +20,16 @@ "h5p-verify": "./bin/h5p-verify.mjs" }, "exports": { - ".": "./lib/verify.mjs", + ".": { + "types": "./types/verify.d.mts", + "default": "./lib/verify.mjs" + }, "./package.json": "./package.json" }, "files": [ "bin", - "lib" + "lib", + "types" ], "keywords": [ "h5p", @@ -39,9 +43,10 @@ ], "scripts": { "test": "pnpm --filter @missing-elements/h5p-offline-player build && vitest run", - "typecheck": "tsc -p tsconfig.json", - "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\"", - "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) }\" && pnpm typecheck && pnpm test" + "typecheck": "pnpm types && tsc -p tsconfig.json", + "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) }\" && pnpm typecheck && pnpm test", + "types": "node -e \"require('node:fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json" }, "dependencies": { "@missing-elements/h5p-offline-player": "workspace:^", diff --git a/packages/verify/tests/package-types.ts b/packages/verify/tests/package-types.ts new file mode 100644 index 00000000..bd6d4658 --- /dev/null +++ b/packages/verify/tests/package-types.ts @@ -0,0 +1,22 @@ +/** + * The package as a TypeScript caller sees it: imported by its name, through the `types` condition + * of its `exports`, from the declarations `pnpm types` generates from the JSDoc. Type-checked by + * `pnpm typecheck`; nothing here runs. + */ +import { VerifyError, summarize, verifyPackage, type VerifyReport } from '@missing-elements/h5p-verify' +// @ts-expect-error a helper the tests use, not part of the package's API (#60) +import { contentChanges } from '@missing-elements/h5p-verify' + +export async function asACallerWould(): Promise { + const report: VerifyReport = await verifyPackage({ file: 'course.h5p', untrusted: true, out: 'report/' }) + const passed: boolean = report.verdict === 'pass' + const missing: string[] | undefined = report.errors.find((error) => error.missingLibraries)?.missingLibraries?.folders + const changed: string[] = (report.contentCheck?.changes ?? []).map(({ path, change }) => `${path}: ${change}`) + const refreshed: string[] = report.refreshed.map(({ library, from, to }) => `${library} ${from} → ${to}`) + + // @ts-expect-error an option the verifier does not take + await verifyPackage({ file: 'course.h5p', timeout: 1_000 }) + + void [passed, missing, changed, refreshed, contentChanges, new VerifyError('could not run') instanceof Error] + return summarize(report) +} diff --git a/packages/verify/tsconfig.json b/packages/verify/tsconfig.json index eba7c864..22a860ff 100644 --- a/packages/verify/tsconfig.json +++ b/packages/verify/tsconfig.json @@ -10,7 +10,8 @@ "allowJs": true, "isolatedModules": true, "esModuleInterop": true, - "skipLibCheck": true + "skipLibCheck": true, + "checkJs": true }, - "include": ["tests/**/*.ts"] + "include": ["lib/**/*.mjs", "tests/**/*.ts"] } diff --git a/packages/verify/tsconfig.types.json b/packages/verify/tsconfig.types.json new file mode 100644 index 00000000..01e1f769 --- /dev/null +++ b/packages/verify/tsconfig.types.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "stripInternal": true, + "rootDir": "lib", + "outDir": "types" + }, + "include": ["lib/verify.mjs"] +}